lang
stringclasses
2 values
license
stringclasses
13 values
stderr
stringlengths
0
343
commit
stringlengths
40
40
returncode
int64
0
128
repos
stringlengths
6
87.7k
new_contents
stringlengths
0
6.23M
new_file
stringlengths
3
311
old_contents
stringlengths
0
6.23M
message
stringlengths
6
9.1k
old_file
stringlengths
3
311
subject
stringlengths
0
4k
git_diff
stringlengths
0
6.31M
Java
epl-1.0
690f39ed068538adbe93f579a28998ae34b3a546
0
codeurjc/optsicom-framework,codeurjc/optsicom-framework,samuelmartingc/optsicom-framework,samuelmartingc/optsicom-framework,codeurjc/optsicom-framework,codeurjc/optsicom-framework,samuelmartingc/optsicom-framework,codeurjc/optsicom-framework
/******************************************************************************* * Copyright (c) Gavab Research Group. Universidad Rey Juan Carlos. * http://www.gavab.es * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package es.optsicom.lib.util; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; /** * @author Patxi Gortázar * */ public class TabuList<T extends Comparable<T>> { private int tabuTenure; List<T> tabuElements = new ArrayList<T>(); Map<T, Integer> generationsInTabuList = new HashMap<T, Integer>(); public TabuList(int tabuTenure) { this.tabuTenure = tabuTenure; } public void setTabuTenure(int tabuTenure) { this.tabuTenure = tabuTenure; } /* * (non-Javadoc) * * @see java.util.List#add(java.lang.Object) */ public void add(T e) { int index = Collections.binarySearch(tabuElements, e); if (index >= 0) { // No se admiten duplicados return; } tabuElements.add(-(index + 1), e); // 0 to (tabuTenure - 1) iterations generationsInTabuList.put(e, tabuTenure - 1); } public boolean contains(T e) { return Collections.binarySearch(tabuElements, e) >= 0; } /* * (non-Javadoc) * * @see java.util.List#size() */ public int size() { return tabuElements.size(); } public void finishIteration() { List<T> toDelete = new ArrayList<T>(); for (Entry<T, Integer> entry : generationsInTabuList.entrySet()) { if (entry.getValue() <= 0) { toDelete.add(entry.getKey()); } else { entry.setValue(entry.getValue() - 1); } } for (T t : toDelete) { tabuElements.remove(Collections.binarySearch(tabuElements, t)); generationsInTabuList.remove(t); } } /** * @return */ public Collection<T> getAllElements() { return tabuElements; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((tabuElements == null) ? 0 : tabuElements.hashCode()); result = prime * result + tabuTenure; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; TabuList other = (TabuList) obj; if (tabuElements == null) { if (other.tabuElements != null) return false; } else if (!tabuElements.equals(other.tabuElements)) return false; if (tabuTenure != other.tabuTenure) return false; return true; } @Override public String toString() { return "TabuList [tabuElements=" + tabuElements + ", tabuTenure=" + tabuTenure + "]"; } }
es.optsicom.lib.util/src/main/java/es/optsicom/lib/util/TabuList.java
/******************************************************************************* * Copyright (c) Gavab Research Group. Universidad Rey Juan Carlos. * http://www.gavab.es * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package es.optsicom.lib.util; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; /** * @author Patxi Gortázar * */ public class TabuList<T extends Comparable<T>> { private int tabuTenure; List<T> tabuElements = new ArrayList<T>(); Map<T, Integer> generationsInTabuList = new HashMap<T, Integer>(); public TabuList(int tabuTenure) { this.tabuTenure = tabuTenure; } /* * (non-Javadoc) * * @see java.util.List#add(java.lang.Object) */ public void add(T e) { int index = Collections.binarySearch(tabuElements, e); if (index >= 0) { // No se admiten duplicados return; } tabuElements.add(-(index + 1), e); generationsInTabuList.put(e, 0); } public boolean contains(T e) { return Collections.binarySearch(tabuElements, e) >= 0; } /* * (non-Javadoc) * * @see java.util.List#size() */ public int size() { return tabuElements.size(); } public void finishIteration() { List<T> toDelete = new ArrayList<T>(); for (Entry<T, Integer> entry : generationsInTabuList.entrySet()) { if (entry.getValue() >= tabuTenure) { toDelete.add(entry.getKey()); } else { entry.setValue(entry.getValue() + 1); } } for (T t : toDelete) { tabuElements.remove(Collections.binarySearch(tabuElements, t)); generationsInTabuList.remove(t); } } /** * @return */ public Collection<T> getAllElements() { return tabuElements; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((tabuElements == null) ? 0 : tabuElements.hashCode()); result = prime * result + tabuTenure; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; TabuList other = (TabuList) obj; if (tabuElements == null) { if (other.tabuElements != null) return false; } else if (!tabuElements.equals(other.tabuElements)) return false; if (tabuTenure != other.tabuTenure) return false; return true; } @Override public String toString() { return "TabuList [tabuElements=" + tabuElements + ", tabuTenure=" + tabuTenure + "]"; } }
dynamic tabuTenure support
es.optsicom.lib.util/src/main/java/es/optsicom/lib/util/TabuList.java
dynamic tabuTenure support
<ide><path>s.optsicom.lib.util/src/main/java/es/optsicom/lib/util/TabuList.java <ide> this.tabuTenure = tabuTenure; <ide> } <ide> <add> public void setTabuTenure(int tabuTenure) { <add> this.tabuTenure = tabuTenure; <add> } <add> <ide> /* <ide> * (non-Javadoc) <ide> * <ide> return; <ide> } <ide> tabuElements.add(-(index + 1), e); <del> generationsInTabuList.put(e, 0); <add> // 0 to (tabuTenure - 1) iterations <add> generationsInTabuList.put(e, tabuTenure - 1); <ide> } <ide> <ide> public boolean contains(T e) { <ide> public void finishIteration() { <ide> List<T> toDelete = new ArrayList<T>(); <ide> for (Entry<T, Integer> entry : generationsInTabuList.entrySet()) { <del> if (entry.getValue() >= tabuTenure) { <add> if (entry.getValue() <= 0) { <ide> toDelete.add(entry.getKey()); <ide> } else { <del> entry.setValue(entry.getValue() + 1); <add> entry.setValue(entry.getValue() - 1); <ide> } <ide> } <ide>
Java
apache-2.0
54f21ba13234e398b1f0919f20a054af5767d994
0
madmax983/aura,badlogicmanpreet/aura,badlogicmanpreet/aura,madmax983/aura,forcedotcom/aura,badlogicmanpreet/aura,forcedotcom/aura,badlogicmanpreet/aura,badlogicmanpreet/aura,madmax983/aura,madmax983/aura,badlogicmanpreet/aura,forcedotcom/aura,forcedotcom/aura,madmax983/aura,madmax983/aura,forcedotcom/aura
/* * Copyright (C) 2013 salesforce.com, inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.auraframework; import javax.inject.Inject; import org.auraframework.adapter.ConfigAdapter; import org.auraframework.adapter.DefinitionParserAdapter; import org.auraframework.adapter.ExceptionAdapter; import org.auraframework.adapter.LocalizationAdapter; import org.auraframework.adapter.ServletUtilAdapter; import org.auraframework.adapter.StyleAdapter; import org.auraframework.annotations.Annotations.ServiceComponent; import org.auraframework.clientlibrary.ClientLibraryService; import org.auraframework.def.Definition; import org.auraframework.ds.serviceloader.AuraServiceProvider; import org.auraframework.instance.Application; import org.auraframework.instance.Component; import org.auraframework.instance.Instance; import org.auraframework.service.BuilderService; import org.auraframework.service.CachingService; import org.auraframework.service.ContextService; import org.auraframework.service.DefinitionService; import org.auraframework.service.InstanceService; import org.auraframework.service.IntegrationService; import org.auraframework.service.LocalizationService; import org.auraframework.service.LoggingService; import org.auraframework.service.MetricsService; import org.auraframework.service.RenderingService; import org.auraframework.service.SerializationService; import org.auraframework.service.ServerService; import org.auraframework.system.AuraContext; import org.auraframework.util.ServiceLocator; import org.auraframework.util.adapter.SourceControlAdapter; /** * Entry point for accessing Aura services */ @ServiceComponent public class Aura { private static ClientLibraryService clientLibraryService; @Inject public void setClientLibraryService(ClientLibraryService cls) { clientLibraryService = cls; } /** * Get the Builder Service: for constructing your own {@link Definition} */ public static BuilderService getBuilderService() { return Aura.get(BuilderService.class); } /** * Get the Context Service: for creating or interacting with a {@link AuraContext} A AuraContext must be started * before working using any other service. */ public static ContextService getContextService() { return Aura.get(ContextService.class); } /** * Get the Definition Service: for loading, finding or interacting with a {@link Definition} */ public static DefinitionService getDefinitionService() { return Aura.get(DefinitionService.class); } /** * Get the Logging Service: Provides Aura with a top-level Logging handler from the host environments */ public static LoggingService getLoggingService() { return Aura.get(LoggingService.class); } /** * Get the Logging Service: Provides Aura with a top-level Logging handler from the host environments */ public static MetricsService getMetricsService() { return Aura.get(MetricsService.class); } /** * Get the Instance Service: for constructing an {@link Instance} of a {@link Definition} */ public static InstanceService getInstanceService() { return Aura.get(InstanceService.class); } /** * Get the Rendering Service: for rendering a {@link Component} or {@link Application} */ public static RenderingService getRenderingService() { return Aura.get(RenderingService.class); } /** * Get the Serialization Service: for serializing things into format specified in the current {@link AuraContext} */ public static SerializationService getSerializationService() { return Aura.get(SerializationService.class); } /** * Get the Server Service: for responding to requests from a Aura Client */ public static ServerService getServerService() { return Aura.get(ServerService.class); } /** * Get the Config Adapter: Provides Aura with configuration from the host environment */ public static ConfigAdapter getConfigAdapter() { return Aura.get(ConfigAdapter.class); } /** * Get the Localization Adapter: Provides Aura with Localization configuration from the host environments */ public static LocalizationAdapter getLocalizationAdapter() { return Aura.get(LocalizationAdapter.class); } /** * Gets the Localization Service: Gets the localization configuration */ public static LocalizationService getLocalizationService() { return Aura.get(LocalizationService.class); } /** * Get the Exception Adapter: Provides Aura with a top-level Exception handler from the host environments */ public static ExceptionAdapter getExceptionAdapter() { return Aura.get(ExceptionAdapter.class); } /** * Get the Source Control Adapter : Allows interaction with the source control system. */ public static SourceControlAdapter getSourceControlAdapter() { return Aura.get(SourceControlAdapter.class); } /** * Get the Style Adapter: Used to provide CSS/Style specific functionality. */ public static StyleAdapter getStyleAdapter() { return Aura.get(StyleAdapter.class); } /** * Get the Servlet Util Adapter: Used to provide overrides for servlet functionality. */ public static ServletUtilAdapter getServletUtilAdapter() { return Aura.get(ServletUtilAdapter.class); } /** * Get the Definition Parser Adapter: hooks for host environment to interact with definition parsing */ public static DefinitionParserAdapter getDefinitionParserAdapter() { return Aura.get(DefinitionParserAdapter.class); } /** * Gets the Integration Service: Service that makes integrating into other containers easy. */ public static IntegrationService getIntegrationService() { return Aura.get(IntegrationService.class); } /** * Gets {@link ClientLibraryService}: service for including external client libraries (CSS or JS) */ public static ClientLibraryService getClientLibraryService() { return clientLibraryService; } /** * Gets the caching service: a general service for setting and getting arbitrary blobs based on a key * Encapsulates the access to aura's known caches. */ public static CachingService getCachingService() { return Aura.get(CachingService.class); } public static <T extends AuraServiceProvider> T get(Class<T> type) { return ServiceLocator.get().get(type); } }
aura/src/main/java/org/auraframework/Aura.java
/* * Copyright (C) 2013 salesforce.com, inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.auraframework; import javax.inject.Inject; import org.auraframework.adapter.ConfigAdapter; import org.auraframework.adapter.DefinitionParserAdapter; import org.auraframework.adapter.ExceptionAdapter; import org.auraframework.adapter.LocalizationAdapter; import org.auraframework.adapter.ServletUtilAdapter; import org.auraframework.adapter.StyleAdapter; import org.auraframework.annotations.Annotations.ServiceComponent; import org.auraframework.clientlibrary.ClientLibraryService; import org.auraframework.def.Definition; import org.auraframework.ds.serviceloader.AuraServiceProvider; import org.auraframework.instance.Application; import org.auraframework.instance.Component; import org.auraframework.instance.Instance; import org.auraframework.service.BuilderService; import org.auraframework.service.CachingService; import org.auraframework.service.ContextService; import org.auraframework.service.DefinitionService; import org.auraframework.service.InstanceService; import org.auraframework.service.IntegrationService; import org.auraframework.service.LocalizationService; import org.auraframework.service.LoggingService; import org.auraframework.service.MetricsService; import org.auraframework.service.RenderingService; import org.auraframework.service.SerializationService; import org.auraframework.service.ServerService; import org.auraframework.system.AuraContext; import org.auraframework.util.ServiceLocator; import org.auraframework.util.adapter.SourceControlAdapter; /** * Entry point for accessing Aura services */ @ServiceComponent public class Aura { private static ClientLibraryService clientLibraryService; @Inject public void setClientLibraryService(ClientLibraryService cls) { clientLibraryService = cls; } /** * Get the Builder Service: for constructing your own {@link Definition} */ public static BuilderService getBuilderService() { return Aura.get(BuilderService.class); } /** * Get the Context Service: for creating or interacting with a {@link AuraContext} A AuraContext must be started * before working using any other service. */ public static ContextService getContextService() { return Aura.get(ContextService.class); } /** * Get the Definition Service: for loading, finding or interacting with a {@link Definition} */ public static DefinitionService getDefinitionService() { return Aura.get(DefinitionService.class); } /** * Get the Logging Service: Provides Aura with a top-level Logging handler from the host environments */ public static LoggingService getLoggingService() { return Aura.get(LoggingService.class); } /** * Get the Logging Service: Provides Aura with a top-level Logging handler from the host environments */ public static MetricsService getMetricsService() { return Aura.get(MetricsService.class); } /** * Get the Instance Service: for constructing an {@link Instance} of a {@link Definition} */ public static InstanceService getInstanceService() { return Aura.get(InstanceService.class); } /** * Get the Rendering Service: for rendering a {@link Component} or {@link Application} */ public static RenderingService getRenderingService() { return Aura.get(RenderingService.class); } /** * Get the Serialization Service: for serializing things into format specified in the current {@link AuraContext} */ public static SerializationService getSerializationService() { return Aura.get(SerializationService.class); } /** * Get the Server Service: for responding to requests from a Aura Client */ public static ServerService getServerService() { return Aura.get(ServerService.class); } /** * Get the Config Adapter: Provides Aura with configuration from the host environment */ public static ConfigAdapter getConfigAdapter() { return Aura.get(ConfigAdapter.class); } /** * Get the Localization Adapter: Provides Aura with Localization configuration from the host environments */ public static LocalizationAdapter getLocalizationAdapter() { return Aura.get(LocalizationAdapter.class); } /** * Gets the Localization Service: Gets the localization configuration */ public static LocalizationService getLocalizationService() { return Aura.get(LocalizationService.class); } /** * Get the Exception Adapter: Provides Aura with a top-level Exception handler from the host environments */ public static ExceptionAdapter getExceptionAdapter() { return Aura.get(ExceptionAdapter.class); } /** * Get the Source Control Adapter : Allows interaction with the source control system. */ public static SourceControlAdapter getSourceControlAdapter() { return Aura.get(SourceControlAdapter.class); } /** * Get the Style Adapter: Used to provide CSS/Style specific functionality. */ public static StyleAdapter getStyleAdapter() { return Aura.get(StyleAdapter.class); } /** * Get the Servlet Util Adapter: Used to provide overrides for servlet functionality. */ public static ServletUtilAdapter getServletUtilAdapter() { return Aura.get(ServletUtilAdapter.class); } /** * Get the Definition Parser Adapter: hooks for host environment to interact with definition parsing */ public static DefinitionParserAdapter getDefinitionParserAdapter() { return Aura.get(DefinitionParserAdapter.class); } /** * Gets the Integration Service: Service that makes integrating into other containers easy. */ public static IntegrationService getIntegrationService() { return Aura.get(IntegrationService.class); } /** * Gets {@link ClientLibraryService}: service for including external client libraries (CSS or JS) */ public static ClientLibraryService getClientLibraryService() { return clientLibraryService; } /** * Gets the caching service: a general service for setting and getting arbitrary blobs based on a key * Encapsulates the access to aura's known caches. */ public static CachingService getCachingService() { return Aura.get(CachingService.class); } public static <T extends AuraServiceProvider> T get(Class<T> type) { return ServiceLocator.get().get(type); } }
cleanup
aura/src/main/java/org/auraframework/Aura.java
cleanup
<ide><path>ura/src/main/java/org/auraframework/Aura.java <ide> */ <ide> @ServiceComponent <ide> public class Aura { <add> <ide> private static ClientLibraryService clientLibraryService; <ide> <ide> @Inject <ide> public static LoggingService getLoggingService() { <ide> return Aura.get(LoggingService.class); <ide> } <del> <add> <ide> /** <ide> * Get the Logging Service: Provides Aura with a top-level Logging handler from the host environments <ide> */ <ide> public static ClientLibraryService getClientLibraryService() { <ide> return clientLibraryService; <ide> } <del> <add> <ide> /** <ide> * Gets the caching service: a general service for setting and getting arbitrary blobs based on a key <ide> * Encapsulates the access to aura's known caches.
JavaScript
apache-2.0
22851eeb53550b9dcf8690b487ac7ced7c989833
0
wmarques/generator-jhipster,mosoft521/generator-jhipster,rkohel/generator-jhipster,ruddell/generator-jhipster,erikkemperman/generator-jhipster,JulienMrgrd/generator-jhipster,stevehouel/generator-jhipster,robertmilowski/generator-jhipster,Tcharl/generator-jhipster,duderoot/generator-jhipster,PierreBesson/generator-jhipster,dalbelap/generator-jhipster,ruddell/generator-jhipster,siliconharborlabs/generator-jhipster,sohibegit/generator-jhipster,Tcharl/generator-jhipster,ramzimaalej/generator-jhipster,yongli82/generator-jhipster,cbornet/generator-jhipster,mraible/generator-jhipster,JulienMrgrd/generator-jhipster,siliconharborlabs/generator-jhipster,jhipster/generator-jhipster,liseri/generator-jhipster,gmarziou/generator-jhipster,ctamisier/generator-jhipster,jkutner/generator-jhipster,PierreBesson/generator-jhipster,cbornet/generator-jhipster,deepu105/generator-jhipster,hdurix/generator-jhipster,deepu105/generator-jhipster,wmarques/generator-jhipster,siliconharborlabs/generator-jhipster,deepu105/generator-jhipster,gzsombor/generator-jhipster,gmarziou/generator-jhipster,liseri/generator-jhipster,gmarziou/generator-jhipster,gzsombor/generator-jhipster,stevehouel/generator-jhipster,atomfrede/generator-jhipster,xetys/generator-jhipster,gzsombor/generator-jhipster,erikkemperman/generator-jhipster,eosimosu/generator-jhipster,erikkemperman/generator-jhipster,xetys/generator-jhipster,gmarziou/generator-jhipster,siliconharborlabs/generator-jhipster,rkohel/generator-jhipster,baskeboler/generator-jhipster,ziogiugno/generator-jhipster,robertmilowski/generator-jhipster,duderoot/generator-jhipster,wmarques/generator-jhipster,dalbelap/generator-jhipster,jhipster/generator-jhipster,gzsombor/generator-jhipster,vivekmore/generator-jhipster,mosoft521/generator-jhipster,rkohel/generator-jhipster,eosimosu/generator-jhipster,wmarques/generator-jhipster,rifatdover/generator-jhipster,robertmilowski/generator-jhipster,ramzimaalej/generator-jhipster,xetys/generator-jhipster,duderoot/generator-jhipster,vivekmore/generator-jhipster,stevehouel/generator-jhipster,stevehouel/generator-jhipster,rifatdover/generator-jhipster,danielpetisme/generator-jhipster,jkutner/generator-jhipster,baskeboler/generator-jhipster,maniacneron/generator-jhipster,PierreBesson/generator-jhipster,eosimosu/generator-jhipster,sendilkumarn/generator-jhipster,lrkwz/generator-jhipster,rkohel/generator-jhipster,robertmilowski/generator-jhipster,dynamicguy/generator-jhipster,dynamicguy/generator-jhipster,ziogiugno/generator-jhipster,cbornet/generator-jhipster,ruddell/generator-jhipster,cbornet/generator-jhipster,xetys/generator-jhipster,nkolosnjaji/generator-jhipster,atomfrede/generator-jhipster,vivekmore/generator-jhipster,JulienMrgrd/generator-jhipster,lrkwz/generator-jhipster,pascalgrimaud/generator-jhipster,dimeros/generator-jhipster,baskeboler/generator-jhipster,nkolosnjaji/generator-jhipster,vivekmore/generator-jhipster,cbornet/generator-jhipster,lrkwz/generator-jhipster,mraible/generator-jhipster,PierreBesson/generator-jhipster,sohibegit/generator-jhipster,erikkemperman/generator-jhipster,ctamisier/generator-jhipster,mosoft521/generator-jhipster,lrkwz/generator-jhipster,sohibegit/generator-jhipster,atomfrede/generator-jhipster,atomfrede/generator-jhipster,liseri/generator-jhipster,yongli82/generator-jhipster,sohibegit/generator-jhipster,PierreBesson/generator-jhipster,deepu105/generator-jhipster,jhipster/generator-jhipster,liseri/generator-jhipster,mraible/generator-jhipster,baskeboler/generator-jhipster,mraible/generator-jhipster,JulienMrgrd/generator-jhipster,rkohel/generator-jhipster,eosimosu/generator-jhipster,vivekmore/generator-jhipster,ctamisier/generator-jhipster,JulienMrgrd/generator-jhipster,Tcharl/generator-jhipster,nkolosnjaji/generator-jhipster,pascalgrimaud/generator-jhipster,maniacneron/generator-jhipster,hdurix/generator-jhipster,ziogiugno/generator-jhipster,jhipster/generator-jhipster,siliconharborlabs/generator-jhipster,danielpetisme/generator-jhipster,sendilkumarn/generator-jhipster,wmarques/generator-jhipster,dynamicguy/generator-jhipster,stevehouel/generator-jhipster,dimeros/generator-jhipster,lrkwz/generator-jhipster,pascalgrimaud/generator-jhipster,nkolosnjaji/generator-jhipster,dynamicguy/generator-jhipster,rifatdover/generator-jhipster,jkutner/generator-jhipster,dalbelap/generator-jhipster,robertmilowski/generator-jhipster,erikkemperman/generator-jhipster,danielpetisme/generator-jhipster,danielpetisme/generator-jhipster,jkutner/generator-jhipster,gmarziou/generator-jhipster,yongli82/generator-jhipster,baskeboler/generator-jhipster,hdurix/generator-jhipster,ramzimaalej/generator-jhipster,liseri/generator-jhipster,danielpetisme/generator-jhipster,sohibegit/generator-jhipster,ziogiugno/generator-jhipster,sendilkumarn/generator-jhipster,jkutner/generator-jhipster,atomfrede/generator-jhipster,dalbelap/generator-jhipster,deepu105/generator-jhipster,yongli82/generator-jhipster,yongli82/generator-jhipster,dalbelap/generator-jhipster,dimeros/generator-jhipster,ctamisier/generator-jhipster,dimeros/generator-jhipster,nkolosnjaji/generator-jhipster,jhipster/generator-jhipster,mosoft521/generator-jhipster,sendilkumarn/generator-jhipster,maniacneron/generator-jhipster,mraible/generator-jhipster,hdurix/generator-jhipster,duderoot/generator-jhipster,ruddell/generator-jhipster,pascalgrimaud/generator-jhipster,dimeros/generator-jhipster,Tcharl/generator-jhipster,hdurix/generator-jhipster,ziogiugno/generator-jhipster,Tcharl/generator-jhipster,gzsombor/generator-jhipster,maniacneron/generator-jhipster,duderoot/generator-jhipster,sendilkumarn/generator-jhipster,ctamisier/generator-jhipster,mosoft521/generator-jhipster,ruddell/generator-jhipster,eosimosu/generator-jhipster,maniacneron/generator-jhipster,pascalgrimaud/generator-jhipster
// Generated on <%= (new Date).toISOString().split('T')[0] %> using <%= pkg.name %> <%= pkg.version %> 'use strict'; var proxySnippet = require('grunt-connect-proxy/lib/utils').proxyRequest; // usemin custom step var path = require('path'); var useminAutoprefixer = { name: 'autoprefixer', createConfig: function(context, block) { var cfg = { files: [] }; var outfile = path.join(context.outDir, block.dest); var files = {}; files.dest = outfile; files.src = []; context.inFiles.forEach(function (f) { files.src.push(path.join(context.inDir, f)); }); cfg.files.push(files); context.outFiles = [block.dest]; return cfg; } }; module.exports = function (grunt) { require('load-grunt-tasks')(grunt); require('time-grunt')(grunt); grunt.initConfig({ yeoman: { // configurable paths app: require('./bower.json').appPath || 'app', dist: 'src/main/webapp/dist' }, watch: {<% if (useCompass) { %> compass: { files: ['src/main/scss/**/*.{scss,sass}'], tasks: ['compass:server'] },<% } %> styles: { files: ['src/main/webapp/assets/styles/**/*.css'] }, livereload: { options: { livereload: 35729 }, files: [ 'src/main/webapp/**/*.html', 'src/main/webapp/**/*.json', '{.tmp/,}src/main/webapp/assets/styles/**/*.css', '{.tmp/,}src/main/webapp/scripts/**/*.js', 'src/main/webapp/assets/images/**/*.{png,jpg,jpeg,gif,webp,svg}' ] } }, autoprefixer: { // not used since Uglify task does autoprefixer, // options: ['last 1 version'], // dist: { // files: [{ // expand: true, // cwd: '.tmp/styles/', // src: '**/*.css', // dest: '.tmp/styles/' // }] // } }, connect: { proxies: [ { context: '/api', host: 'localhost', port: 8080, https: false, changeOrigin: false }, { context: '/metrics', host: 'localhost', port: 8080, https: false, changeOrigin: false }, { context: '/dump', host: 'localhost', port: 8080, https: false, changeOrigin: false }, { context: '/health', host: 'localhost', port: 8080, https: false, changeOrigin: false }, { context: '/configprops', host: 'localhost', port: 8080, https: false, changeOrigin: false }, { context: '/beans', host: 'localhost', port: 8080, https: false, changeOrigin: false }, { context: '/api-docs', host: 'localhost', port: 8080, https: false, changeOrigin: false }<% if (authenticationType == 'token') { %>, { context: '/oauth/token', host: 'localhost', port: 8080, https: false, changeOrigin: false }<% } %><% if (devDatabaseType == 'h2Memory') { %>, { context: '/console', host: 'localhost', port: 8080, https: false, changeOrigin: false }<% } %> ], options: { port: 9000, // Change this to 'localhost' to deny access to the server from outside. hostname: '0.0.0.0', livereload: 35729 }, livereload: { options: { open: true, base: [ '.tmp', 'src/main/webapp' ], middleware: function (connect) { return [ proxySnippet, connect.static('.tmp'), connect.static('src/main/webapp') ]; } } }, test: { options: { port: 9001, base: [ '.tmp', 'test', 'src/main/webapp' ] } }, dist: { options: { base: '<%%= yeoman.dist %>' } } }, clean: { dist: { files: [{ dot: true, src: [ '.tmp', '<%%= yeoman.dist %>/*', '!<%%= yeoman.dist %>/.git*' ] }] }, server: '.tmp' }, jshint: { options: { jshintrc: '.jshintrc' }, all: [ 'Gruntfile.js', 'src/main/webapp/scripts/app.js', 'src/main/webapp/scripts/app/**/*.js', 'src/main/webapp/scripts/components/**/*.js' ] }, coffee: { options: { sourceMap: true, sourceRoot: '' }, dist: { files: [{ expand: true, cwd: 'src/main/webapp/scripts', src: ['scripts/app/**/*.coffee', 'scripts/components/**/*.coffee'], dest: '.tmp/scripts', ext: '.js' }] }, test: { files: [{ expand: true, cwd: 'test/spec', src: '**/*.coffee', dest: '.tmp/spec', ext: '.js' }] } },<% if (useCompass) { %> compass: { options: { sassDir: 'src/main/scss', cssDir: 'src/main/webapp/assets/styles', generatedImagesDir: '.tmp/assets/images/generated', imagesDir: 'src/main/webapp/assets/images', javascriptsDir: 'src/main/webapp/scripts', fontsDir: 'src/main/webapp/assets/fonts', importPath: 'src/main/webapp/bower_components', httpImagesPath: '/assets/images', httpGeneratedImagesPath: '/assets/images/generated', httpFontsPath: '/assets/fonts', relativeAssets: false }, dist: {}, server: { options: { debugInfo: true } } },<% } %> concat: { // not used since Uglify task does concat, // but still available if needed // dist: {} }, rev: { dist: { files: { src: [ '<%%= yeoman.dist %>/scripts/**/*.js', '<%%= yeoman.dist %>/assets/styles/**/*.css', '<%%= yeoman.dist %>/assets/images/**/*.{png,jpg,jpeg,gif,webp,svg}', '<%%= yeoman.dist %>/assets/fonts/*' ] } } }, useminPrepare: { html: 'src/main/webapp/**/*.html', options: { dest: '<%%= yeoman.dist %>', flow: { html: { steps: { js: ['concat', 'uglifyjs'], css: ['concat', useminAutoprefixer, 'cssmin'] }, post: {} } } } }, usemin: { html: ['<%%= yeoman.dist %>/**/*.html'], css: ['<%%= yeoman.dist %>/assets/styles/**/*.css'], js: ['<%%= yeoman.dist %>/scripts/**/*.js'], options: { assetsDirs: ['<%%= yeoman.dist %>', '<%%= yeoman.dist %>/assets/styles', '<%%= yeoman.dist %>/assets/images', '<%%= yeoman.dist %>/assets/fonts'], patterns: { js: [ [/(assets\/images\/.*?\.(?:gif|jpeg|jpg|png|webp|svg))/gm, 'Update the JS to reference our revved images'] ] }, dirs: ['<%%= yeoman.dist %>'] } }, imagemin: { dist: { files: [{ expand: true, cwd: 'src/main/webapp/assets/images', src: '**/*.{jpg,jpeg}', // we don't optimize PNG files as it doesn't work on Linux. If you are not on Linux, feel free to use '**/*.{png,jpg,jpeg}' dest: '<%%= yeoman.dist %>/assets/images' }] } }, svgmin: { dist: { files: [{ expand: true, cwd: 'src/main/webapp/assets/images', src: '**/*.svg', dest: '<%%= yeoman.dist %>/assets/images' }] } }, cssmin: { // By default, your `index.html` <!-- Usemin Block --> will take care of // minification. This option is pre-configured if you do not wish to use // Usemin blocks. // dist: { // files: { // '<%%= yeoman.dist %>/styles/main.css': [ // '.tmp/styles/**/*.css', // 'styles/**/*.css' // ] // } // } }, ngtemplates: { dist: { cwd: 'src/main/webapp', src: ['scripts/app/**/*.html', 'scripts/components/**/*.html',], dest: '.tmp/templates/templates.js', options: { module: '<%= angularAppName%>', usemin: 'scripts/app.js', htmlmin: { removeCommentsFromCDATA: true, // https://github.com/yeoman/grunt-usemin/issues/44 collapseWhitespace: true, collapseBooleanAttributes: true, conservativeCollapse: true, removeAttributeQuotes: true, removeRedundantAttributes: true, useShortDoctype: true, removeEmptyAttributes: true } } } }, htmlmin: { dist: { options: { removeCommentsFromCDATA: true, // https://github.com/yeoman/grunt-usemin/issues/44 collapseWhitespace: true, collapseBooleanAttributes: true, conservativeCollapse: true, removeAttributeQuotes: true, removeRedundantAttributes: true, useShortDoctype: true, removeEmptyAttributes: true, keepClosingSlash: true }, files: [{ expand: true, cwd: '<%%= yeoman.dist %>', src: ['*.html'], dest: '<%%= yeoman.dist %>' }] } }, // Put files not handled in other tasks here copy: { dist: { files: [{ expand: true, dot: true, cwd: 'src/main/webapp', dest: '<%%= yeoman.dist %>', src: [ '*.html', 'scripts/**/*.html', 'assets/images/**/*.{png,gif,webp}', 'assets/fonts/*' ] }, { expand: true, cwd: '.tmp/assets/images', dest: '<%%= yeoman.dist %>/assets/images', src: [ 'generated/*' ] }] }, generateHerokuDirectory: { expand: true, dest: 'deploy/heroku', src: [ 'pom.xml', 'src/main/**' ] }, generateOpenshiftDirectory: { expand: true, dest: 'deploy/openshift', src: [ 'pom.xml', 'src/main/**' ] } }, concurrent: { server: [<% if (useCompass) { %> 'compass:server'<% } %> ], test: [<% if (useCompass) { %> 'compass'<% } %> ], dist: [<% if (useCompass) { %> 'compass:dist',<% } %> 'imagemin', 'svgmin' ] }, karma: { unit: { configFile: 'src/test/javascript/karma.conf.js', singleRun: true } }, cdnify: { dist: { html: ['<%%= yeoman.dist %>/*.html'] } }, ngAnnotate: { dist: { files: [{ expand: true, cwd: '.tmp/concat/scripts', src: '*.js', dest: '.tmp/concat/scripts' }] } }, replace: { dist: { src: ['<%%= yeoman.dist %>/index.html'], overwrite: true, // overwrite matched source files replacements: [{ from: '<div class="development"></div>', to: '' }] } }, uglify: { // not used since Uglify task does uglify // dist: { // files: { // '<%%= yeoman.dist %>/scripts/scripts.js': [ // '<%%= yeoman.dist %>/scripts/scripts.js' // ] // } // } }, buildcontrol: { options: { commit: true, push: false, connectCommits: false, message: 'Built %sourceName% from commit %sourceCommit% on branch %sourceBranch%' }, heroku: { options: { dir: 'deploy/heroku', remote: 'heroku', branch: 'master' } }, openshift: { options: { dir: 'deploy/openshift', remote: 'openshift', branch: 'master' } } } }); grunt.registerTask('serve', function (target) { if (target === 'dist') { return grunt.task.run(['build', 'connect:dist:keepalive']); } grunt.task.run([ 'clean:server', 'concurrent:server', 'configureProxies', 'connect:livereload', 'watch' ]); }); grunt.registerTask('server', function (target) { grunt.log.warn('The `server` task has been deprecated. Use `grunt serve` to start a server.'); grunt.task.run([target ? ('serve:' + target) : 'serve']); }); grunt.registerTask('test', [ 'clean:server', 'concurrent:test', 'connect:test', 'karma' ]); grunt.registerTask('build', [ 'clean:dist', 'useminPrepare', 'ngtemplates', 'concurrent:dist', 'concat', 'autoprefixer', 'copy:dist', 'ngAnnotate', 'cssmin', 'replace', 'uglify', 'rev', 'usemin', 'htmlmin' ]); grunt.registerTask('buildHeroku', [ 'test', 'build', 'copy:generateHerokuDirectory', ]); grunt.registerTask('deployHeroku', [ 'test', 'build', 'copy:generateHerokuDirectory', 'buildcontrol:heroku' ]); grunt.registerTask('buildOpenshift', [ 'test', 'build', 'copy:generateOpenshiftDirectory', ]); grunt.registerTask('deployOpenshift', [ 'test', 'build', 'copy:generateOpenshiftDirectory', 'buildcontrol:openshift' ]); grunt.registerTask('default', [ 'test', 'build' ]); };
app/templates/Gruntfile.js
// Generated on <%= (new Date).toISOString().split('T')[0] %> using <%= pkg.name %> <%= pkg.version %> 'use strict'; var proxySnippet = require('grunt-connect-proxy/lib/utils').proxyRequest; // usemin custom step var path = require('path'); var useminAutoprefixer = { name: 'autoprefixer', createConfig: function(context, block) { var cfg = { files: [] }; var outfile = path.join(context.outDir, block.dest); var files = {}; files.dest = outfile; files.src = []; context.inFiles.forEach(function (f) { files.src.push(path.join(context.inDir, f)); }); cfg.files.push(files); context.outFiles = [block.dest]; return cfg; } }; module.exports = function (grunt) { require('load-grunt-tasks')(grunt); require('time-grunt')(grunt); grunt.initConfig({ yeoman: { // configurable paths app: require('./bower.json').appPath || 'app', dist: 'src/main/webapp/dist' }, watch: {<% if (useCompass) { %> compass: { files: ['src/main/scss/**/*.{scss,sass}'], tasks: ['compass:server'] },<% } %> styles: { files: ['src/main/webapp/assets/styles/**/*.css'] }, livereload: { options: { livereload: 35729 }, files: [ 'src/main/webapp/**/*.html', 'src/main/webapp/**/*.json', '{.tmp/,}src/main/webapp/assets/styles/**/*.css', '{.tmp/,}src/main/webapp/scripts/**/*.js', 'src/main/webapp/assets/images/**/*.{png,jpg,jpeg,gif,webp,svg}' ] } }, autoprefixer: { // not used since Uglify task does autoprefixer, // options: ['last 1 version'], // dist: { // files: [{ // expand: true, // cwd: '.tmp/styles/', // src: '**/*.css', // dest: '.tmp/styles/' // }] // } }, connect: { proxies: [ { context: '/api', host: 'localhost', port: 8080, https: false, changeOrigin: false }, { context: '/metrics', host: 'localhost', port: 8080, https: false, changeOrigin: false }, { context: '/dump', host: 'localhost', port: 8080, https: false, changeOrigin: false }, { context: '/health', host: 'localhost', port: 8080, https: false, changeOrigin: false }, { context: '/configprops', host: 'localhost', port: 8080, https: false, changeOrigin: false }, { context: '/beans', host: 'localhost', port: 8080, https: false, changeOrigin: false }, { context: '/api-docs', host: 'localhost', port: 8080, https: false, changeOrigin: false }<% if (authenticationType == 'token') { %>, { context: '/oauth/token', host: 'localhost', port: 8080, https: false, changeOrigin: false }<% } %><% if (devDatabaseType == 'h2Memory') { %>, { context: '/console', host: 'localhost', port: 8080, https: false, changeOrigin: false }<% } %> ], options: { port: 9000, // Change this to 'localhost' to deny access to the server from outside. hostname: '0.0.0.0', livereload: 35729 }, livereload: { options: { open: true, base: [ '.tmp', 'src/main/webapp' ], middleware: function (connect) { return [ proxySnippet, connect.static('.tmp'), connect.static('src/main/webapp') ]; } } }, test: { options: { port: 9001, base: [ '.tmp', 'test', 'src/main/webapp' ] } }, dist: { options: { base: '<%%= yeoman.dist %>' } } }, clean: { dist: { files: [{ dot: true, src: [ '.tmp', '<%%= yeoman.dist %>/*', '!<%%= yeoman.dist %>/.git*' ] }] }, server: '.tmp' }, jshint: { options: { jshintrc: '.jshintrc' }, all: [ 'Gruntfile.js', 'src/main/webapp/scripts/app.js', 'src/main/webapp/scripts/app/**/*.js', 'src/main/webapp/scripts/components/**/*.js' ] }, coffee: { options: { sourceMap: true, sourceRoot: '' }, dist: { files: [{ expand: true, cwd: 'src/main/webapp/scripts', src: ['scripts/app/**/*.coffee', 'scripts/components/**/*.coffee'], dest: '.tmp/scripts', ext: '.js' }] }, test: { files: [{ expand: true, cwd: 'test/spec', src: '**/*.coffee', dest: '.tmp/spec', ext: '.js' }] } },<% if (useCompass) { %> compass: { options: { sassDir: 'src/main/scss', cssDir: 'src/main/webapp/assets/styles', generatedImagesDir: '.tmp/assets/images/generated', imagesDir: 'src/main/webapp/assets/images', javascriptsDir: 'src/main/webapp/scripts', fontsDir: 'src/main/webapp/assets/fonts', importPath: 'src/main/webapp/bower_components', httpImagesPath: '/assets/images', httpGeneratedImagesPath: '/assets/images/generated', httpFontsPath: '/assets/fonts', relativeAssets: false }, dist: {}, server: { options: { debugInfo: true } } },<% } %> concat: { // not used since Uglify task does concat, // but still available if needed // dist: {} }, rev: { dist: { files: { src: [ '<%%= yeoman.dist %>/scripts/**/*.js', '<%%= yeoman.dist %>/assets/styles/**/*.css', '<%%= yeoman.dist %>/assets/images/**/*.{png,jpg,jpeg,gif,webp,svg}', '<%%= yeoman.dist %>/assets/fonts/*' ] } } }, useminPrepare: { html: 'src/main/webapp/**/*.html', options: { dest: '<%%= yeoman.dist %>', flow: { html: { steps: { js: ['concat', 'uglifyjs'], css: ['concat', useminAutoprefixer, 'cssmin'] }, post: {} } } } }, usemin: { html: ['<%%= yeoman.dist %>/**/*.html'], css: ['<%%= yeoman.dist %>/assets/styles/**/*.css'], js: ['<%%= yeoman.dist %>/scripts/**/*.js'], options: { assetsDirs: ['<%%= yeoman.dist %>', '<%%= yeoman.dist %>/assets/styles', '<%%= yeoman.dist %>/assets/images', '<%%= yeoman.dist %>/assets/fonts'], patterns: { js: [ [/(assets\/images\/.*?\.(?:gif|jpeg|jpg|png|webp|svg))/gm, 'Update the JS to reference our revved images'] ] }, dirs: ['<%%= yeoman.dist %>'] } }, imagemin: { dist: { files: [{ expand: true, cwd: 'src/main/webapp/assets/images', src: '**/*.{jpg,jpeg}', // we don't optimize PNG files as it doesn't work on Linux. If you are not on Linux, feel free to use '**/*.{png,jpg,jpeg}' dest: '<%%= yeoman.dist %>/assets/images' }] } }, svgmin: { dist: { files: [{ expand: true, cwd: 'src/main/webapp/assets/images', src: '**/*.svg', dest: '<%%= yeoman.dist %>/assets/images' }] } }, cssmin: { // By default, your `index.html` <!-- Usemin Block --> will take care of // minification. This option is pre-configured if you do not wish to use // Usemin blocks. // dist: { // files: { // '<%%= yeoman.dist %>/styles/main.css': [ // '.tmp/styles/**/*.css', // 'styles/**/*.css' // ] // } // } }, ngtemplates: { dist: { cwd: 'src/main/webapp', src: ['scripts/app/**/*.html', 'scripts/components/**/*.html',], dest: '.tmp/templates/templates.js', options: { module: '<%= angularAppName%>', usemin: 'scripts/app.js', htmlmin: { removeCommentsFromCDATA: true, // https://github.com/yeoman/grunt-usemin/issues/44 collapseWhitespace: true, collapseBooleanAttributes: true, conservativeCollapse: true, removeAttributeQuotes: true, removeRedundantAttributes: true, useShortDoctype: true, removeEmptyAttributes: true } } } }, htmlmin: { dist: { options: { removeCommentsFromCDATA: true, // https://github.com/yeoman/grunt-usemin/issues/44 collapseWhitespace: true, collapseBooleanAttributes: true, conservativeCollapse: true, removeAttributeQuotes: true, removeRedundantAttributes: true, useShortDoctype: true, removeEmptyAttributes: true, keepClosingSlash: true }, files: [{ expand: true, cwd: '<%%= yeoman.dist %>', src: ['*.html'], dest: '<%%= yeoman.dist %>' }] } }, // Put files not handled in other tasks here copy: { dist: { files: [{ expand: true, dot: true, cwd: 'src/main/webapp', dest: '<%%= yeoman.dist %>', src: [ '*.html', 'scripts/**/*.html', 'assets/images/**/*.{png,gif,webp}', 'assets/fonts/*' ] }, { expand: true, cwd: '.tmp/assets/images', dest: '<%%= yeoman.dist %>/assets/images', src: [ 'generated/*' ] }] }, generateHerokuDirectory: { expand: true, dest: 'deploy/heroku', src: [ 'pom.xml', 'src/main/**' ] }, generateOpenshiftDirectory: { expand: true, dest: 'deploy/openshift', src: [ 'pom.xml', 'src/main/**' ] } }, concurrent: { server: [<% if (useCompass) { %> 'compass:server'<% } %> ], test: [<% if (useCompass) { %> 'compass'<% } %> ], dist: [<% if (useCompass) { %> 'compass:dist',<% } %> 'imagemin', 'svgmin' ] }, karma: { unit: { configFile: 'src/test/javascript/karma.conf.js', singleRun: true } }, cdnify: { dist: { html: ['<%%= yeoman.dist %>/*.html'] } }, ngAnnotate: { dist: { files: [{ expand: true, cwd: '.tmp/concat/scripts', src: '*.js', dest: '.tmp/concat/scripts' }] } }, replace: { dist: { src: ['<%%= yeoman.dist %>/index.html'], overwrite: true, // overwrite matched source files replacements: [{ from: '<div class="development"></div>', to: '' }] } }, uglify: { // not used since Uglify task does uglify // dist: { // files: { // '<%%= yeoman.dist %>/scripts/scripts.js': [ // '<%%= yeoman.dist %>/scripts/scripts.js' // ] // } // } }, buildcontrol: { options: { commit: true, push: false, connectCommits: false, message: 'Built %sourceName% from commit %sourceCommit% on branch %sourceBranch%' }, heroku: { options: { dir: 'deploy/heroku', remote: 'heroku', branch: 'master' } }, openshift: { options: { dir: 'deploy/openshift', remote: 'openshift', branch: 'master' } } } }); grunt.registerTask('server', function (target) { if (target === 'dist') { return grunt.task.run(['build', 'connect:dist:keepalive']); } grunt.task.run([ 'clean:server', 'concurrent:server', 'configureProxies', 'connect:livereload', 'watch' ]); }); grunt.registerTask('test', [ 'clean:server', 'concurrent:test', 'connect:test', 'karma' ]); grunt.registerTask('build', [ 'clean:dist', 'useminPrepare', 'ngtemplates', 'concurrent:dist', 'concat', 'autoprefixer', 'copy:dist', 'ngAnnotate', 'cssmin', 'replace', 'uglify', 'rev', 'usemin', 'htmlmin' ]); grunt.registerTask('buildHeroku', [ 'test', 'build', 'copy:generateHerokuDirectory', ]); grunt.registerTask('deployHeroku', [ 'test', 'build', 'copy:generateHerokuDirectory', 'buildcontrol:heroku' ]); grunt.registerTask('buildOpenshift', [ 'test', 'build', 'copy:generateOpenshiftDirectory', ]); grunt.registerTask('deployOpenshift', [ 'test', 'build', 'copy:generateOpenshiftDirectory', 'buildcontrol:openshift' ]); grunt.registerTask('default', [ 'test', 'build' ]); };
Fixes #960, renamed 'grunt server' task to 'grunt serve'
app/templates/Gruntfile.js
Fixes #960, renamed 'grunt server' task to 'grunt serve'
<ide><path>pp/templates/Gruntfile.js <ide> } <ide> }); <ide> <del> grunt.registerTask('server', function (target) { <add> grunt.registerTask('serve', function (target) { <ide> if (target === 'dist') { <ide> return grunt.task.run(['build', 'connect:dist:keepalive']); <ide> } <ide> 'connect:livereload', <ide> 'watch' <ide> ]); <add> }); <add> <add> grunt.registerTask('server', function (target) { <add> grunt.log.warn('The `server` task has been deprecated. Use `grunt serve` to start a server.'); <add> grunt.task.run([target ? ('serve:' + target) : 'serve']); <ide> }); <ide> <ide> grunt.registerTask('test', [
Java
apache-2.0
ce7948d6e72f2399caeeb279e1702225c89cdad3
0
alibaba/canal,alibaba/canal,alibaba/canal,alibaba/canal,alibaba/canal
package com.alibaba.otter.canal.client.adapter.support; import java.util.*; import com.alibaba.otter.canal.protocol.CanalEntry; import com.alibaba.otter.canal.protocol.FlatMessage; import com.alibaba.otter.canal.protocol.Message; /** * Message对象解析工具类 * * @author rewerma 2018-8-19 下午06:14:23 * @version 1.0.0 */ public class MessageUtil { public static List<Dml> parse4Dml(String destination, String groupId, Message message) { if (message == null) { return null; } List<CanalEntry.Entry> entries = message.getEntries(); List<Dml> dmls = new ArrayList<Dml>(entries.size()); for (CanalEntry.Entry entry : entries) { if (entry.getEntryType() == CanalEntry.EntryType.TRANSACTIONBEGIN || entry.getEntryType() == CanalEntry.EntryType.TRANSACTIONEND) { continue; } CanalEntry.RowChange rowChange; try { rowChange = CanalEntry.RowChange.parseFrom(entry.getStoreValue()); } catch (Exception e) { throw new RuntimeException("ERROR ## parser of eromanga-event has an error , data:" + entry.toString(), e); } CanalEntry.EventType eventType = rowChange.getEventType(); final Dml dml = new Dml(); dml.setIsDdl(rowChange.getIsDdl()); dml.setDestination(destination); dml.setGroupId(groupId); dml.setDatabase(entry.getHeader().getSchemaName()); dml.setTable(entry.getHeader().getTableName()); dml.setType(eventType.toString()); dml.setEs(entry.getHeader().getExecuteTime()); dml.setIsDdl(rowChange.getIsDdl()); dml.setTs(System.currentTimeMillis()); dml.setSql(rowChange.getSql()); dmls.add(dml); List<Map<String, Object>> data = new ArrayList<>(); List<Map<String, Object>> old = new ArrayList<>(); if (!rowChange.getIsDdl()) { Set<String> updateSet = new HashSet<>(); dml.setPkNames(new ArrayList<>()); int i = 0; for (CanalEntry.RowData rowData : rowChange.getRowDatasList()) { if (eventType != CanalEntry.EventType.INSERT && eventType != CanalEntry.EventType.UPDATE && eventType != CanalEntry.EventType.DELETE) { continue; } Map<String, Object> row = new LinkedHashMap<>(); List<CanalEntry.Column> columns; if (eventType == CanalEntry.EventType.DELETE) { columns = rowData.getBeforeColumnsList(); } else { columns = rowData.getAfterColumnsList(); } for (CanalEntry.Column column : columns) { if (i == 0) { if (column.getIsKey()) { dml.getPkNames().add(column.getName()); } } if (column.getIsNull()) { row.put(column.getName(), null); } else { row.put(column.getName(), JdbcTypeUtil.typeConvert(dml.getTable(), column.getName(), column.getValue(), column.getSqlType(), column.getMysqlType())); } // 获取update为true的字段 if (column.getUpdated()) { updateSet.add(column.getName()); } } if (!row.isEmpty()) { data.add(row); } if (eventType == CanalEntry.EventType.UPDATE) { Map<String, Object> rowOld = new LinkedHashMap<>(); for (CanalEntry.Column column : rowData.getBeforeColumnsList()) { if (updateSet.contains(column.getName())) { if (column.getIsNull()) { rowOld.put(column.getName(), null); } else { rowOld.put(column.getName(), JdbcTypeUtil.typeConvert(dml.getTable(), column.getName(), column.getValue(), column.getSqlType(), column.getMysqlType())); } } } // update操作将记录修改前的值 if (!rowOld.isEmpty()) { old.add(rowOld); } } i++; } if (!data.isEmpty()) { dml.setData(data); } if (!old.isEmpty()) { dml.setOld(old); } } } return dmls; } public static List<Dml> flatMessage2Dml(String destination, String groupId, List<FlatMessage> flatMessages) { List<Dml> dmls = new ArrayList<Dml>(flatMessages.size()); for (FlatMessage flatMessage : flatMessages) { Dml dml = flatMessage2Dml(destination, groupId, flatMessage); if (dml != null) { dmls.add(dml); } } return dmls; } public static Dml flatMessage2Dml(String destination, String groupId, FlatMessage flatMessage) { if (flatMessage == null) { return null; } Dml dml = new Dml(); dml.setDestination(destination); dml.setGroupId(groupId); dml.setDatabase(flatMessage.getDatabase()); dml.setTable(flatMessage.getTable()); dml.setPkNames(flatMessage.getPkNames()); dml.setIsDdl(flatMessage.getIsDdl()); dml.setType(flatMessage.getType()); dml.setTs(flatMessage.getTs()); dml.setEs(flatMessage.getEs()); dml.setSql(flatMessage.getSql()); // if (flatMessage.getSqlType() == null || flatMessage.getMysqlType() == null) { // throw new RuntimeException("SqlType or mysqlType is null"); // } List<Map<String, String>> data = flatMessage.getData(); if (data != null) { dml.setData(changeRows(dml.getTable(), data, flatMessage.getSqlType(), flatMessage.getMysqlType())); } List<Map<String, String>> old = flatMessage.getOld(); if (old != null) { dml.setOld(changeRows(dml.getTable(), old, flatMessage.getSqlType(), flatMessage.getMysqlType())); } return dml; } private static List<Map<String, Object>> changeRows(String table, List<Map<String, String>> rows, Map<String, Integer> sqlTypes, Map<String, String> mysqlTypes) { List<Map<String, Object>> result = new ArrayList<>(); for (Map<String, String> row : rows) { Map<String, Object> resultRow = new LinkedHashMap<>(); for (Map.Entry<String, String> entry : row.entrySet()) { String columnName = entry.getKey(); String columnValue = entry.getValue(); Integer sqlType = sqlTypes.get(columnName); if (sqlType == null) { continue; } String mysqlType = mysqlTypes.get(columnName); if (mysqlType == null) { continue; } Object finalValue = JdbcTypeUtil.typeConvert(table, columnName, columnValue, sqlType, mysqlType); resultRow.put(columnName, finalValue); } result.add(resultRow); } return result; } }
client-adapter/common/src/main/java/com/alibaba/otter/canal/client/adapter/support/MessageUtil.java
package com.alibaba.otter.canal.client.adapter.support; import java.util.*; import com.alibaba.otter.canal.protocol.CanalEntry; import com.alibaba.otter.canal.protocol.FlatMessage; import com.alibaba.otter.canal.protocol.Message; /** * Message对象解析工具类 * * @author rewerma 2018-8-19 下午06:14:23 * @version 1.0.0 */ public class MessageUtil { public static List<Dml> parse4Dml(String destination, String groupId, Message message) { if (message == null) { return null; } List<CanalEntry.Entry> entries = message.getEntries(); List<Dml> dmls = new ArrayList<Dml>(entries.size()); for (CanalEntry.Entry entry : entries) { if (entry.getEntryType() == CanalEntry.EntryType.TRANSACTIONBEGIN || entry.getEntryType() == CanalEntry.EntryType.TRANSACTIONEND) { continue; } CanalEntry.RowChange rowChange; try { rowChange = CanalEntry.RowChange.parseFrom(entry.getStoreValue()); } catch (Exception e) { throw new RuntimeException("ERROR ## parser of eromanga-event has an error , data:" + entry.toString(), e); } CanalEntry.EventType eventType = rowChange.getEventType(); final Dml dml = new Dml(); dml.setIsDdl(rowChange.getIsDdl()); dml.setDestination(destination); dml.setGroupId(groupId); dml.setDatabase(entry.getHeader().getSchemaName()); dml.setTable(entry.getHeader().getTableName()); dml.setType(eventType.toString()); dml.setEs(entry.getHeader().getExecuteTime()); dml.setIsDdl(rowChange.getIsDdl()); dml.setTs(System.currentTimeMillis()); dml.setSql(rowChange.getSql()); dmls.add(dml); List<Map<String, Object>> data = new ArrayList<>(); List<Map<String, Object>> old = new ArrayList<>(); if (!rowChange.getIsDdl()) { Set<String> updateSet = new HashSet<>(); dml.setPkNames(new ArrayList<>()); int i = 0; for (CanalEntry.RowData rowData : rowChange.getRowDatasList()) { if (eventType != CanalEntry.EventType.INSERT && eventType != CanalEntry.EventType.UPDATE && eventType != CanalEntry.EventType.DELETE) { continue; } Map<String, Object> row = new LinkedHashMap<>(); List<CanalEntry.Column> columns; if (eventType == CanalEntry.EventType.DELETE) { columns = rowData.getBeforeColumnsList(); } else { columns = rowData.getAfterColumnsList(); } for (CanalEntry.Column column : columns) { if (i == 0) { if (column.getIsKey()) { dml.getPkNames().add(column.getName()); } } row.put(column.getName(), JdbcTypeUtil.typeConvert(dml.getTable(),column.getName(), column.getValue(), column.getSqlType(), column.getMysqlType())); // 获取update为true的字段 if (column.getUpdated()) { updateSet.add(column.getName()); } } if (!row.isEmpty()) { data.add(row); } if (eventType == CanalEntry.EventType.UPDATE) { Map<String, Object> rowOld = new LinkedHashMap<>(); for (CanalEntry.Column column : rowData.getBeforeColumnsList()) { if (updateSet.contains(column.getName())) { rowOld.put(column.getName(), JdbcTypeUtil.typeConvert(dml.getTable(),column.getName(), column.getValue(), column.getSqlType(), column.getMysqlType())); } } // update操作将记录修改前的值 if (!rowOld.isEmpty()) { old.add(rowOld); } } i++; } if (!data.isEmpty()) { dml.setData(data); } if (!old.isEmpty()) { dml.setOld(old); } } } return dmls; } public static List<Dml> flatMessage2Dml(String destination, String groupId, List<FlatMessage> flatMessages) { List<Dml> dmls = new ArrayList<Dml>(flatMessages.size()); for (FlatMessage flatMessage : flatMessages) { Dml dml = flatMessage2Dml(destination, groupId, flatMessage); if (dml != null) { dmls.add(dml); } } return dmls; } public static Dml flatMessage2Dml(String destination, String groupId, FlatMessage flatMessage) { if (flatMessage == null) { return null; } Dml dml = new Dml(); dml.setDestination(destination); dml.setGroupId(groupId); dml.setDatabase(flatMessage.getDatabase()); dml.setTable(flatMessage.getTable()); dml.setPkNames(flatMessage.getPkNames()); dml.setIsDdl(flatMessage.getIsDdl()); dml.setType(flatMessage.getType()); dml.setTs(flatMessage.getTs()); dml.setEs(flatMessage.getEs()); dml.setSql(flatMessage.getSql()); // if (flatMessage.getSqlType() == null || flatMessage.getMysqlType() == null) { // throw new RuntimeException("SqlType or mysqlType is null"); // } List<Map<String, String>> data = flatMessage.getData(); if (data != null) { dml.setData(changeRows(dml.getTable(), data, flatMessage.getSqlType(), flatMessage.getMysqlType())); } List<Map<String, String>> old = flatMessage.getOld(); if (old != null) { dml.setOld(changeRows(dml.getTable(), old, flatMessage.getSqlType(), flatMessage.getMysqlType())); } return dml; } private static List<Map<String, Object>> changeRows(String table, List<Map<String, String>> rows, Map<String, Integer> sqlTypes, Map<String, String> mysqlTypes) { List<Map<String, Object>> result = new ArrayList<>(); for (Map<String, String> row : rows) { Map<String, Object> resultRow = new LinkedHashMap<>(); for (Map.Entry<String, String> entry : row.entrySet()) { String columnName = entry.getKey(); String columnValue = entry.getValue(); Integer sqlType = sqlTypes.get(columnName); if (sqlType == null) { continue; } String mysqlType = mysqlTypes.get(columnName); if (mysqlType == null) { continue; } Object finalValue = JdbcTypeUtil.typeConvert(table, columnName, columnValue, sqlType, mysqlType); resultRow.put(columnName, finalValue); } result.add(resultRow); } return result; } }
fix Message转Dml对null值的bug (#1808) * Message转Dml对null值的判断 * Message转Dml对null值的判断 * Message转Dml对null值的判断
client-adapter/common/src/main/java/com/alibaba/otter/canal/client/adapter/support/MessageUtil.java
fix Message转Dml对null值的bug (#1808)
<ide><path>lient-adapter/common/src/main/java/com/alibaba/otter/canal/client/adapter/support/MessageUtil.java <ide> dml.getPkNames().add(column.getName()); <ide> } <ide> } <del> row.put(column.getName(), <del> JdbcTypeUtil.typeConvert(dml.getTable(),column.getName(), <del> column.getValue(), <del> column.getSqlType(), <del> column.getMysqlType())); <add> if (column.getIsNull()) { <add> row.put(column.getName(), null); <add> } else { <add> row.put(column.getName(), <add> JdbcTypeUtil.typeConvert(dml.getTable(), <add> column.getName(), <add> column.getValue(), <add> column.getSqlType(), <add> column.getMysqlType())); <add> } <ide> // 获取update为true的字段 <ide> if (column.getUpdated()) { <ide> updateSet.add(column.getName()); <ide> Map<String, Object> rowOld = new LinkedHashMap<>(); <ide> for (CanalEntry.Column column : rowData.getBeforeColumnsList()) { <ide> if (updateSet.contains(column.getName())) { <del> rowOld.put(column.getName(), <del> JdbcTypeUtil.typeConvert(dml.getTable(),column.getName(), <del> column.getValue(), <del> column.getSqlType(), <del> column.getMysqlType())); <add> if (column.getIsNull()) { <add> rowOld.put(column.getName(), null); <add> } else { <add> rowOld.put(column.getName(), <add> JdbcTypeUtil.typeConvert(dml.getTable(), <add> column.getName(), <add> column.getValue(), <add> column.getSqlType(), <add> column.getMysqlType())); <add> } <ide> } <ide> } <ide> // update操作将记录修改前的值 <ide> return dml; <ide> } <ide> <del> private static List<Map<String, Object>> changeRows(String table, List<Map<String, String>> rows, Map<String, Integer> sqlTypes, <del> Map<String, String> mysqlTypes) { <add> private static List<Map<String, Object>> changeRows(String table, List<Map<String, String>> rows, <add> Map<String, Integer> sqlTypes, Map<String, String> mysqlTypes) { <ide> List<Map<String, Object>> result = new ArrayList<>(); <ide> for (Map<String, String> row : rows) { <ide> Map<String, Object> resultRow = new LinkedHashMap<>();
Java
agpl-3.0
5455ddc6b8d3a75f81e45885c278eed1cc80bc08
0
elki-project/elki,elki-project/elki,elki-project/elki
package de.lmu.ifi.dbs.elki.visualization.css; import java.util.Collection; import java.util.HashMap; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Text; import de.lmu.ifi.dbs.elki.visualization.svg.SVGUtil; /** * Manager class to track CSS classes used in a particular SVG document. * * @author Erich Schubert */ public class CSSClassManager { /** * Store the contained CSS classes. */ private HashMap<String, CSSClass> store = new HashMap<String, CSSClass>(); /** * Serial version. */ private static final long serialVersionUID = 8807736974456191901L; /** * Add a single class to the map. * * @param clss * @return existing (old) class * @throws CSSNamingConflict when a class of the same name but different owner object exists. */ public CSSClass addClass(CSSClass clss) throws CSSNamingConflict { CSSClass existing = store.get(clss.getName()); if (existing != null && existing.getOwner() != null && existing.getOwner() != clss.getOwner()) { throw new CSSNamingConflict("CSS class naming conflict between "+clss.getOwner().toString()+" and "+existing.getOwner().toString()); } return store.put(clss.getName(), clss); } /** * Retrieve a single class by name and owner * * @param name * @param owner * @return existing (old) class * @throws CSSNamingConflict if an owner was specified and doesn't match */ public CSSClass getClass(String name, Object owner) throws CSSNamingConflict { CSSClass existing = store.get(name); // Not found. if (existing == null) { return null; } // Different owner if (owner != null && existing.getOwner() != owner) { throw new CSSNamingConflict("CSS class naming conflict between "+owner.toString()+" and "+existing.getOwner().toString()); } return existing; } /** * Retrieve a single class by name only * * @param name * @return existing (old) class */ public CSSClass getClass(String name) { return store.get(name); } /** * Check if a name is already used in the classes. * * @param name * @return true if the class name is already used. */ public boolean contains(String name) { return store.containsKey(name); } /** * Serialize managed CSS classes to rule file. * * @param buf String buffer */ public void serialize(StringBuffer buf) { for (CSSClass clss : store.values()) { clss.appendCSSDefinition(buf); } } /** * Get all CSS classes in this manager. * * @return CSS classes. */ public Collection<CSSClass> getClasses() { return store.values(); } /** * Check compatibility */ public boolean testMergeable(CSSClassManager other) { for (CSSClass clss : other.getClasses()) { CSSClass existing = store.get(clss.getName()); // Check for a naming conflict. if (existing != null && existing.getOwner() != null && clss.getOwner() != null && existing.getOwner() != clss.getOwner()) { return false; } } return true; } /** * Merge CSS classes, for example to merge two plots. * * @throws CSSNamingConflict If there is a naming conflict. */ public boolean mergeCSSFrom(CSSClassManager other) throws CSSNamingConflict { for (CSSClass clss : other.getClasses()) { this.addClass(clss); } return true; } /** * Class to signal a CSS naming conflict. * */ public class CSSNamingConflict extends Exception { /** * Serial version UID */ private static final long serialVersionUID = 4163822727195636747L; /** * Exception to signal a CSS naming conflict. * * @param msg Exception message */ public CSSNamingConflict(String msg) { super(msg); } } /** * Update the text contents of an existing style element. * * @param document Document element (factory) * @param style Style element */ public void updateStyleElement(Document document, Element style) { StringBuffer buf = new StringBuffer(); serialize(buf); Text cont = document.createTextNode(buf.toString()); while (style.hasChildNodes()) { style.removeChild(style.getFirstChild()); } style.appendChild(cont); } /** * Make a (filled) CSS style element for the given document. * * @param document Document * @return Style element */ public Element makeStyleElement(Document document) { Element style = SVGUtil.makeStyleElement(document); updateStyleElement(document, style); return style; } }
src/de/lmu/ifi/dbs/elki/visualization/css/CSSClassManager.java
package de.lmu.ifi.dbs.elki.visualization.css; import java.util.Collection; import java.util.HashMap; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Text; import de.lmu.ifi.dbs.elki.visualization.svg.SVGUtil; /** * Manager class to track CSS classes used in a particular SVG document. * * @author Erich Schubert */ public class CSSClassManager { /** * Store the contained CSS classes. */ private HashMap<String, CSSClass> store = new HashMap<String, CSSClass>(); /** * Serial version. */ private static final long serialVersionUID = 8807736974456191901L; /** * Add a single class to the map. * * @param clss * @return existing (old) class * @throws CSSNamingConflict when a class of the same name but different owner object exists. */ public CSSClass addClass(CSSClass clss) throws CSSNamingConflict { CSSClass existing = store.get(clss.getName()); if (existing != null && existing.getOwner() != null && existing.getOwner() != clss.getOwner()) { throw new CSSNamingConflict("CSS class naming conflict between "+clss.getOwner().toString()+" and "+existing.getOwner().toString()); } return store.put(clss.getName(), clss); } /** * Check if a name is already used in the classes. * * @param name * @return true if the class name is already used. */ public boolean contains(String name) { return store.containsKey(name); } /** * Serialize managed CSS classes to rule file. * * @param buf String buffer */ public void serialize(StringBuffer buf) { for (CSSClass clss : store.values()) { clss.appendCSSDefinition(buf); } } /** * Get all CSS classes in this manager. * * @return CSS classes. */ public Collection<CSSClass> getClasses() { return store.values(); } /** * Check compatibility */ public boolean testMergeable(CSSClassManager other) { for (CSSClass clss : other.getClasses()) { CSSClass existing = store.get(clss.getName()); // Check for a naming conflict. if (existing != null && existing.getOwner() != null && clss.getOwner() != null && existing.getOwner() != clss.getOwner()) { return false; } } return true; } /** * Merge CSS classes, for example to merge two plots. * * @throws CSSNamingConflict If there is a naming conflict. */ public boolean mergeCSSFrom(CSSClassManager other) throws CSSNamingConflict { for (CSSClass clss : other.getClasses()) { this.addClass(clss); } return true; } /** * Class to signal a CSS naming conflict. * */ public class CSSNamingConflict extends Exception { /** * Serial version UID */ private static final long serialVersionUID = 4163822727195636747L; /** * Exception to signal a CSS naming conflict. * * @param msg Exception message */ public CSSNamingConflict(String msg) { super(msg); } } /** * Update the text contents of an existing style element. * * @param document Document element (factory) * @param style Style element */ public void updateStyleElement(Document document, Element style) { StringBuffer buf = new StringBuffer(); serialize(buf); Text cont = document.createTextNode(buf.toString()); while (style.hasChildNodes()) { style.removeChild(style.getFirstChild()); } style.appendChild(cont); } /** * Make a (filled) CSS style element for the given document. * * @param document Document * @return Style element */ public Element makeStyleElement(Document document) { Element style = SVGUtil.makeStyleElement(document); updateStyleElement(document, style); return style; } }
Add CSS class accessor methods.
src/de/lmu/ifi/dbs/elki/visualization/css/CSSClassManager.java
Add CSS class accessor methods.
<ide><path>rc/de/lmu/ifi/dbs/elki/visualization/css/CSSClassManager.java <ide> throw new CSSNamingConflict("CSS class naming conflict between "+clss.getOwner().toString()+" and "+existing.getOwner().toString()); <ide> } <ide> return store.put(clss.getName(), clss); <add> } <add> <add> /** <add> * Retrieve a single class by name and owner <add> * <add> * @param name <add> * @param owner <add> * @return existing (old) class <add> * @throws CSSNamingConflict if an owner was specified and doesn't match <add> */ <add> public CSSClass getClass(String name, Object owner) throws CSSNamingConflict { <add> CSSClass existing = store.get(name); <add> // Not found. <add> if (existing == null) { <add> return null; <add> } <add> // Different owner <add> if (owner != null && existing.getOwner() != owner) { <add> throw new CSSNamingConflict("CSS class naming conflict between "+owner.toString()+" and "+existing.getOwner().toString()); <add> } <add> return existing; <add> } <add> <add> /** <add> * Retrieve a single class by name only <add> * <add> * @param name <add> * @return existing (old) class <add> */ <add> public CSSClass getClass(String name) { <add> return store.get(name); <ide> } <ide> <ide> /**
Java
bsd-3-clause
f490642f3d73bc1b77d02f3aab9fc27ff2721224
0
threerings/ooo-util
// // ooo-util - a place for OOO utilities // Copyright (C) 2011 Three Rings Design, Inc., All Rights Reserved // http://github.com/threerings/ooo-util/blob/master/LICENSE package com.threerings.servlet.util; import com.samskivert.util.LogBuilder; /** * Indicates that a converter couldn't handle a parameter value in {@link Parameters}. */ public class ConversionFailedException extends RuntimeException { public ConversionFailedException (Throwable cause) { this(cause, ""); } /** * Creates an exception message with the given base message and key value pairs as formatted * by {@link LogBuilder}. */ public ConversionFailedException (Throwable cause, Object msg, Object...args) { this(msg, args); initCause(cause); } public ConversionFailedException (Object msg, Object...args) { _builder = new LogBuilder(msg, args); } public ConversionFailedException () { this(""); } /** * Adds the given key value pairs to the message. */ public void append (Object... args) { _builder.append(args); } @Override public String getMessage () { return _builder.toString(); } protected final LogBuilder _builder; }
src/main/java/com/threerings/servlet/util/ConversionFailedException.java
// // ooo-util - a place for OOO utilities // Copyright (C) 2011 Three Rings Design, Inc., All Rights Reserved // http://github.com/threerings/ooo-util/blob/master/LICENSE package com.threerings.servlet.util; import com.samskivert.util.LogBuilder; /** * Indicates that a converter couldn't handle a parameter value in {@Parameters}. */ public class ConversionFailedException extends RuntimeException { public ConversionFailedException (Throwable cause) { this(cause, ""); } /** * Creates an exception message with the given base message and key value pairs as formatted * by {@link LogBuilder}. */ public ConversionFailedException (Throwable cause, Object msg, Object...args) { this(msg, args); initCause(cause); } public ConversionFailedException (Object msg, Object...args) { _builder = new LogBuilder(msg, args); } public ConversionFailedException () { this(""); } /** * Adds the given key value pairs to the message. */ public void append (Object... args) { _builder.append(args); } @Override public String getMessage () { return _builder.toString(); } protected final LogBuilder _builder; }
Fix javadoc.
src/main/java/com/threerings/servlet/util/ConversionFailedException.java
Fix javadoc.
<ide><path>rc/main/java/com/threerings/servlet/util/ConversionFailedException.java <ide> import com.samskivert.util.LogBuilder; <ide> <ide> /** <del> * Indicates that a converter couldn't handle a parameter value in {@Parameters}. <add> * Indicates that a converter couldn't handle a parameter value in {@link Parameters}. <ide> */ <ide> public class ConversionFailedException extends RuntimeException <ide> {
Java
lgpl-2.1
c03af8628952917f3f477361df2b7e8af6b25c40
0
xwiki-contrib/oidc
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.xwiki.contrib.oidc.auth.internal; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.net.URLConnection; import java.security.Principal; import java.util.Arrays; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.stream.Collectors; import javax.inject.Inject; import javax.inject.Provider; import javax.inject.Singleton; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang3.RegExUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.exception.ExceptionUtils; import org.apache.commons.text.StringSubstitutor; import org.securityfilter.realm.SimplePrincipal; import org.slf4j.Logger; import org.xwiki.component.annotation.Component; import org.xwiki.component.manager.ComponentManager; import org.xwiki.context.concurrent.ExecutionContextRunnable; import org.xwiki.contrib.oidc.OIDCUserInfo; import org.xwiki.contrib.oidc.auth.internal.OIDCClientConfiguration.GroupMapping; import org.xwiki.contrib.oidc.auth.store.OIDCUserStore; import org.xwiki.contrib.oidc.event.OIDCUserEventData; import org.xwiki.contrib.oidc.event.OIDCUserUpdated; import org.xwiki.contrib.oidc.event.OIDCUserUpdating; import org.xwiki.contrib.oidc.provider.internal.OIDCException; import org.xwiki.model.reference.DocumentReference; import org.xwiki.model.reference.SpaceReference; import org.xwiki.observation.ObservationManager; import org.xwiki.query.QueryException; import com.nimbusds.jwt.PlainJWT; import com.nimbusds.oauth2.sdk.ParseException; import com.nimbusds.oauth2.sdk.http.HTTPRequest; import com.nimbusds.oauth2.sdk.http.HTTPResponse; import com.nimbusds.oauth2.sdk.token.BearerAccessToken; import com.nimbusds.openid.connect.sdk.LogoutRequest; import com.nimbusds.openid.connect.sdk.UserInfoErrorResponse; import com.nimbusds.openid.connect.sdk.UserInfoRequest; import com.nimbusds.openid.connect.sdk.UserInfoResponse; import com.nimbusds.openid.connect.sdk.UserInfoSuccessResponse; import com.nimbusds.openid.connect.sdk.claims.Address; import com.nimbusds.openid.connect.sdk.claims.ClaimsSet; import com.nimbusds.openid.connect.sdk.claims.IDTokenClaimsSet; import com.nimbusds.openid.connect.sdk.claims.UserInfo; import com.xpn.xwiki.XWikiContext; import com.xpn.xwiki.XWikiException; import com.xpn.xwiki.doc.XWikiDocument; import com.xpn.xwiki.objects.BaseObject; import com.xpn.xwiki.objects.classes.BaseClass; import com.xpn.xwiki.user.api.XWikiRightService; import com.xpn.xwiki.web.XWikiRequest; /** * Various tools to manipulate users. * * @version $Id$ * @since 1.2 */ @Component(roles = OIDCUserManager.class) @Singleton public class OIDCUserManager { @Inject private Provider<XWikiContext> xcontextProvider; @Inject private OIDCClientConfiguration configuration; @Inject private OIDCUserStore store; @Inject private ObservationManager observation; @Inject private ComponentManager componentManager; @Inject private Logger logger; private Executor executor = Executors.newFixedThreadPool(1); private static final String XWIKI_GROUP_MEMBERFIELD = "member"; private static final String XWIKI_GROUP_PREFIX = "XWiki."; public void updateUserInfoAsync() throws URISyntaxException { final Endpoint userInfoEndpoint = this.configuration.getUserInfoOIDCEndpoint(); final IDTokenClaimsSet idToken = this.configuration.getIdToken(); final BearerAccessToken accessToken = this.configuration.getAccessToken(); this.executor.execute(new ExecutionContextRunnable(() -> { try { updateUserInfo(userInfoEndpoint, idToken, accessToken); } catch (Exception e) { logger.error("Failed to update user informations", e); } }, this.componentManager)); } public void checkUpdateUserInfo() { Date date = this.configuration.removeUserInfoExpirationDate(); if (date != null) { if (date.before(new Date())) { try { updateUserInfoAsync(); } catch (Exception e) { this.logger.error("Failed to update user informations", e); } // Restart user information expiration counter this.configuration.resetUserInfoExpirationDate(); } else { // Put back the date this.configuration.setUserInfoExpirationDate(date); } } } public Principal updateUserInfo(BearerAccessToken accessToken) throws URISyntaxException, IOException, ParseException, OIDCException, XWikiException, QueryException { Principal principal = updateUserInfo(this.configuration.getUserInfoOIDCEndpoint(), this.configuration.getIdToken(), accessToken); // Restart user information expiration counter this.configuration.resetUserInfoExpirationDate(); return principal; } public Principal updateUserInfo(Endpoint userInfoEndpoint, IDTokenClaimsSet idToken, BearerAccessToken accessToken) throws IOException, ParseException, OIDCException, XWikiException, QueryException { // Get OIDC user info this.logger.debug("OIDC user info request ({},{})", userInfoEndpoint, accessToken); UserInfoRequest userinfoRequest = new UserInfoRequest(userInfoEndpoint.getURI(), this.configuration.getUserInfoEndPointMethod(), accessToken); HTTPRequest userinfoHTTP = userinfoRequest.toHTTPRequest(); userInfoEndpoint.prepare(userinfoHTTP); this.logger.debug("OIDC user info request ({}?{},{})", userinfoHTTP.getURL(), userinfoHTTP.getQuery(), userinfoHTTP.getHeaderMap()); HTTPResponse httpResponse = userinfoHTTP.send(); this.logger.debug("OIDF user info response ({})", httpResponse.getContent()); UserInfoResponse userinfoResponse = UserInfoResponse.parse(httpResponse); if (!userinfoResponse.indicatesSuccess()) { UserInfoErrorResponse error = (UserInfoErrorResponse) userinfoResponse; throw new OIDCException("Failed to get user info", error.getErrorObject()); } UserInfoSuccessResponse userinfoSuccessResponse = (UserInfoSuccessResponse) userinfoResponse; UserInfo userInfo = userinfoSuccessResponse.getUserInfo(); // Update/Create XWiki user return updateUser(idToken, userInfo); } private int sendLogout() { int ret = 0; Endpoint logoutURI = null; try { logoutURI = this.configuration.getLogoutOIDCEndpoint(); } catch (Exception e) { // TODO: log something ? } if (logoutURI != null) { try { ret = sendLogout(logoutURI, this.configuration.getIdToken()); } catch (Exception e) { // TODO: log something ? } } else { this.logger.debug("Don't send OIDC logout request: no OIDC logout URI set"); } return ret; } private int sendLogout(Endpoint logoutEndpoint, IDTokenClaimsSet idToken) throws IOException, ParseException { LogoutRequest logoutRequest = new LogoutRequest(logoutEndpoint.getURI(), new PlainJWT(idToken.toJWTClaimsSet())); HTTPRequest logoutHTTP = logoutRequest.toHTTPRequest(); logoutEndpoint.prepare(logoutHTTP); this.logger.debug("OIDC logout request ({}?{},{})", logoutHTTP.getURL(), logoutHTTP.getQuery(), logoutHTTP.getHeaderMap()); HTTPResponse httpResponse = logoutHTTP.send(); this.logger.debug("OIDC logout response ({})", httpResponse.getContent()); return httpResponse.getStatusCode(); } private void checkAllowedGroups(UserInfo userInfo) throws OIDCException { List<String> providerGroups = null; Object providerGroupsObj = getClaim(this.configuration.getGroupClaim(), userInfo); if (this.configuration.getGroupSeparator()!=null) { providerGroups = Arrays.asList(StringUtils.split(providerGroupsObj.toString(), this.configuration.getGroupSeparator())); } else { providerGroups = (List<String>)providerGroupsObj; } String groupPrefix = this.configuration.getGroupPrefix(); if (!StringUtils.isEmpty(groupPrefix)) { providerGroups = providerGroups.stream() .filter(item -> item.startsWith(groupPrefix)) .map(item -> StringUtils.replace(item, groupPrefix, "")) .collect(Collectors.toList()); } if (providerGroups != null) { // Check allowed groups List<String> allowedGroups = this.configuration.getAllowedGroups(); if (allowedGroups != null) { if (!CollectionUtils.containsAny(providerGroups, allowedGroups)) { // Allowed groups have priority over forbidden groups throw new OIDCException( "The user is not allowed to authenticate because it's not a member of the following groups: " + allowedGroups); } return; } // Check forbidden groups List<String> forbiddenGroups = this.configuration.getForbiddenGroups(); if (forbiddenGroups != null && CollectionUtils.containsAny(providerGroups, forbiddenGroups)) { throw new OIDCException( "The user is not allowed to authenticate because it's a member of one of the following groups: " + forbiddenGroups); } } } private <T> T getClaim(String claim, ClaimsSet claims) { T value = (T) claims.getClaim(claim); // When it's not a proper OIDC claim try to find in a sub element of the JSON if (value == null) { value = (T) getJSONElement(claim, claims.toJSONObject()); } return value; } private <T> T getJSONElement(String pattern, Map<String, ?> json) { int index = pattern.indexOf('.'); String key; String patternEnd; if (index != -1) { key = pattern.substring(0, index); patternEnd = pattern.length() == (index + 1) ? null : pattern.substring(index + 1); } else { key = pattern; patternEnd = null; } Object value = json.get(key); if (patternEnd == null) { return (T) value; } if (value instanceof Map) { return (T) getJSONElement(patternEnd, (Map) value); } return (T) value; } public Principal updateUser(IDTokenClaimsSet idToken, UserInfo userInfo) throws XWikiException, QueryException, OIDCException { // Check allowed/forbidden groups checkAllowedGroups(userInfo); Map<String, String> formatMap = createFormatMap(idToken, userInfo); // Change the default StringSubstitutor behavior to produce an empty String instead of an unresolved pattern by // default StringSubstitutor substitutor = new StringSubstitutor(new OIDCStringLookup(formatMap)); String formattedSubject = formatSubjec(substitutor); XWikiDocument userDocument = this.store.searchDocument(idToken.getIssuer().getValue(), formattedSubject); XWikiDocument modifiableDocument; boolean newUser; if (userDocument == null) { userDocument = getNewUserDocument(substitutor); newUser = true; modifiableDocument = userDocument; } else { // Don't change the document author to not change document execution right newUser = false; modifiableDocument = userDocument.clone(); } XWikiContext xcontext = this.xcontextProvider.get(); // Set user fields BaseClass userClass = xcontext.getWiki().getUserClass(xcontext); BaseObject userObject = modifiableDocument.getXObject(userClass.getDocumentReference(), true, xcontext); // Make sure the user is active by default userObject.set("active", 1, xcontext); // Address Address address = userInfo.getAddress(); if (address != null) { userObject.set("address", address.getFormatted(), xcontext); } // Email if (userInfo.getEmailAddress() != null) { userObject.set("email", userInfo.getEmailAddress(), xcontext); } // Last name if (userInfo.getFamilyName() != null) { userObject.set("last_name", userInfo.getFamilyName(), xcontext); } // First name if (userInfo.getGivenName() != null) { userObject.set("first_name", userInfo.getGivenName(), xcontext); } // Phone if (userInfo.getPhoneNumber() != null) { userObject.set("phone", userInfo.getPhoneNumber(), xcontext); } // Default locale if (userInfo.getLocale() != null) { userObject.set("default_language", Locale.forLanguageTag(userInfo.getLocale()).toString(), xcontext); } // Time Zone if (userInfo.getZoneinfo() != null) { userObject.set("timezone", userInfo.getZoneinfo(), xcontext); } // Website if (userInfo.getWebsite() != null) { userObject.set("blog", userInfo.getWebsite().toString(), xcontext); } // Avatar if (userInfo.getPicture() != null) { try { String filename = FilenameUtils.getName(userInfo.getPicture().toString()); URLConnection connection = userInfo.getPicture().toURL().openConnection(); connection.setRequestProperty("User-Agent", this.getClass().getPackage().getImplementationTitle() + '/' + this.getClass().getPackage().getImplementationVersion()); try (InputStream content = connection.getInputStream()) { modifiableDocument.setAttachment(filename, content, xcontext); } userObject.set("avatar", filename, xcontext); } catch (IOException e) { this.logger.warn("Failed to get user avatar from URL [{}]: {}", userInfo.getPicture(), ExceptionUtils.getRootCauseMessage(e)); } } // XWiki claims updateXWikiClaims(modifiableDocument, userClass, userObject, userInfo, xcontext); // Set OIDC fields this.store.updateOIDCUser(modifiableDocument, idToken.getIssuer().getValue(), formattedSubject); // Configured user mapping updateUserMapping(modifiableDocument, userClass, userObject, xcontext, substitutor); // Data to send with the event OIDCUserEventData eventData = new OIDCUserEventData(new NimbusOIDCIdToken(idToken), new NimbusOIDCUserInfo(userInfo)); // Notify this.observation.notify(new OIDCUserUpdating(modifiableDocument.getDocumentReference()), modifiableDocument, eventData); boolean userUpdated = false; // Apply the modifications if (newUser || userDocument.apply(modifiableDocument)) { String comment; if (newUser) { comment = "Create user from OpenID Connect"; } else { comment = "Update user from OpenID Connect"; } xcontext.getWiki().saveDocument(userDocument, comment, xcontext); // Now let's add the new user to XWiki.XWikiAllGroup if (newUser) { xcontext.getWiki().setUserDefaultGroup(userDocument.getFullName(), xcontext); } userUpdated = true; } // Sync user groups with the provider if (this.configuration.isGroupSync()) { userUpdated = updateGroupMembership(userInfo, userDocument, xcontext); } // Notify if (userUpdated) { this.observation.notify(new OIDCUserUpdated(userDocument.getDocumentReference()), userDocument, eventData); } return new SimplePrincipal(userDocument.getPrefixedFullName()); } private void updateUserMapping(XWikiDocument userDocument, BaseClass userClass, BaseObject userObject, XWikiContext xcontext, StringSubstitutor substitutor) { Map<String, String> mapping = this.configuration.getUserMapping(); if (mapping != null) { for (Map.Entry<String, String> entry : mapping.entrySet()) { String xwikiProperty = entry.getKey(); String oidcFormat = entry.getValue(); String oidcValue = substitutor.replace(oidcFormat); setValue(userDocument, userClass, userObject, xwikiProperty, oidcValue, xcontext); } } } private boolean updateGroupMembership(UserInfo userInfo, XWikiDocument userDocument, XWikiContext xcontext) throws XWikiException { String groupClaim = this.configuration.getGroupClaim(); this.logger.debug("Getting groups sent by the provider associated with claim [{}]", groupClaim); List<String> providerGroups = null; Object providerGroupsObj = getClaim(this.configuration.getGroupClaim(), userInfo); if (this.configuration.getGroupSeparator()!=null) { providerGroups = Arrays.asList(StringUtils.split(providerGroupsObj.toString(), this.configuration.getGroupSeparator())); } else { providerGroups = (List<String>)providerGroupsObj; } String groupPrefix = this.configuration.getGroupPrefix(); if (!StringUtils.isEmpty(groupPrefix)) { providerGroups = providerGroups.stream() .filter(item -> item.startsWith(groupPrefix)) .map(item -> StringUtils.replace(item, groupPrefix, "")) .collect(Collectors.toList()); } if (providerGroups != null) { this.logger.debug("The provider sent the following groups: {}", providerGroups); return syncXWikiGroupsMembership(userDocument.getFullName(), providerGroups, xcontext); } else { this.logger.debug("The provider did not sent any group"); } return false; } /** * Remove user name from provided XWiki group. * * @param xwikiUserName the full name of the user. * @param xwikiGroupName the name of the group. * @param context the XWiki context. */ protected void removeUserFromXWikiGroup(String xwikiUserName, String xwikiGroupName, XWikiContext context) { this.logger.debug("Removing user from [{}] ...", xwikiGroupName); try { BaseClass groupClass = context.getWiki().getGroupClass(context); // Get the XWiki document holding the objects comprising the group membership list XWikiDocument groupDoc = context.getWiki().getDocument(xwikiGroupName, context); synchronized (groupDoc) { // Get and remove the specific group membership object for the user BaseObject groupObj = groupDoc.getXObject(groupClass.getDocumentReference(), XWIKI_GROUP_MEMBERFIELD, xwikiUserName); groupDoc.removeXObject(groupObj); // Save modifications context.getWiki().saveDocument(groupDoc, context); } } catch (Exception e) { this.logger.error("Failed to remove user [{}] from group [{}]", xwikiUserName, xwikiGroupName, e); } } /** * Add user name into provided XWiki group. * * @param xwikiUserName the full name of the user. * @param xwikiGroupName the name of the group. * @param context the XWiki context. */ protected void addUserToXWikiGroup(String xwikiUserName, String xwikiGroupName, XWikiContext context) { try { BaseClass groupClass = context.getWiki().getGroupClass(context); // Get document representing group XWikiDocument groupDoc = context.getWiki().getDocument(xwikiGroupName, context); this.logger.debug("Adding user [{}] to xwiki group [{}]", xwikiUserName, xwikiGroupName); synchronized (groupDoc) { // Make extra sure the group cannot contain duplicate (even if this method is not supposed to be called // in this case) List<BaseObject> xobjects = groupDoc.getXObjects(groupClass.getDocumentReference()); if (xobjects != null) { for (BaseObject memberObj : xobjects) { if (memberObj != null) { String existingMember = memberObj.getStringValue(XWIKI_GROUP_MEMBERFIELD); if (existingMember != null && existingMember.equals(xwikiUserName)) { this.logger.warn("User [{}] already exist in group [{}]", xwikiUserName, groupDoc.getDocumentReference()); return; } } } } // Add a member object to document BaseObject memberObj = groupDoc.newXObject(groupClass.getDocumentReference(), context); Map<String, String> map = new HashMap<>(); map.put(XWIKI_GROUP_MEMBERFIELD, xwikiUserName); groupClass.fromMap(map, memberObj); // Save modifications context.getWiki().saveDocument(groupDoc, context); } this.logger.debug("Finished adding user [{}] to xwiki group [{}]", xwikiUserName, xwikiGroupName); } catch (Exception e) { this.logger.error("Failed to add a user [{}] to a group [{}]", xwikiUserName, xwikiGroupName, e); } } /** * Synchronize user XWiki membership with the Open ID xwiki_groups claim. * * @param xwikiUserName the name of the user. * @param providerGroups the Open ID xwiki_groups claim. * @param context the XWiki context. * @throws XWikiException error when synchronizing user membership. */ public Boolean syncXWikiGroupsMembership(String xwikiUserName, List<String> providerGroups, XWikiContext context) throws XWikiException { Boolean userUpdated = false; this.logger.debug("Updating group membership for the user [{}]", xwikiUserName); Collection<String> xwikiUserGroupList = context.getWiki().getGroupService(context).getAllGroupsNamesForMember(xwikiUserName, 0, 0, context); this.logger.debug("The user belongs to following XWiki groups: {}", xwikiUserGroupList); GroupMapping groupMapping = this.configuration.getGroupMapping(); // Add missing group membership for (String providerGroupName : providerGroups) { if (groupMapping == null) { String xwikiGroup = this.configuration.toXWikiGroup(providerGroupName); if (!xwikiUserGroupList.contains(xwikiGroup)) { addUserToXWikiGroup(xwikiUserName, xwikiGroup, context); userUpdated = true; } } else { Set<String> mappedGroups = groupMapping.fromProvider(providerGroupName); if (mappedGroups != null) { for (String mappedGroup : mappedGroups) { if (!xwikiUserGroupList.contains(mappedGroup)) { addUserToXWikiGroup(xwikiUserName, mappedGroup, context); userUpdated = true; } } } } } // Remove group membership for (String xwikiGroupName : xwikiUserGroupList) { if (groupMapping == null) { if (!providerGroups.contains(xwikiGroupName) && !providerGroups.contains(xwikiGroupName.substring(XWIKI_GROUP_PREFIX.length()))) { removeUserFromXWikiGroup(xwikiUserName, xwikiGroupName, context); userUpdated = true; } } else { Set<String> mappedGroups = groupMapping.fromXWiki(xwikiGroupName); if (mappedGroups != null && !CollectionUtils.containsAny(providerGroups, mappedGroups)) { removeUserFromXWikiGroup(xwikiUserName, xwikiGroupName, context); userUpdated = true; } } } return userUpdated; } private void updateXWikiClaims(XWikiDocument userDocument, BaseClass userClass, BaseObject userObject, UserInfo userInfo, XWikiContext xcontext) { this.logger.debug("Updating XWiki claims"); for (Map.Entry<String, Object> entry : userInfo.toJSONObject().entrySet()) { if (entry.getKey().startsWith(OIDCUserInfo.CLAIMPREFIX_XWIKI_USER)) { String xwikiKey = entry.getKey().substring(OIDCUserInfo.CLAIMPREFIX_XWIKI_USER.length()); setValue(userDocument, userClass, userObject, xwikiKey, entry.getValue(), xcontext); } } } private void setValue(XWikiDocument userDocument, BaseClass userClass, BaseObject userObject, String xwikiKey, Object value, XWikiContext xcontext) { // Try in the user object if (userClass.getField(xwikiKey) != null) { setValue(userObject, xwikiKey, value, xcontext); return; } // Try in the whole user document BaseObject xobject = userDocument.getFirstObject(xwikiKey); if (xobject != null) { setValue(xobject, xwikiKey, value, xcontext); } } private void setValue(BaseObject xobject, String key, Object value, XWikiContext xcontext) { Object cleanValue; if (value instanceof List) { cleanValue = value; } else { // Go through String to be safe // TODO: find a more effective converter (the best would be to userObject#set to be stronger) cleanValue = Objects.toString(value); } xobject.set(key, cleanValue, xcontext); } private XWikiDocument getNewUserDocument(StringSubstitutor substitutor) throws XWikiException { XWikiContext xcontext = this.xcontextProvider.get(); // TODO: add support for subwikis SpaceReference spaceReference = new SpaceReference(xcontext.getMainXWiki(), "XWiki"); // Generate default document name String documentName = formatXWikiUserName(substitutor); // Find not already existing document DocumentReference reference = new DocumentReference(documentName, spaceReference); XWikiDocument document = xcontext.getWiki().getDocument(reference, xcontext); for (int index = 0; !document.isNew(); ++index) { reference = new DocumentReference(documentName + '-' + index, spaceReference); document = xcontext.getWiki().getDocument(reference, xcontext); } // Initialize document document.setCreator(XWikiRightService.SUPERADMIN_USER); document.setAuthorReference(document.getCreatorReference()); document.setContentAuthorReference(document.getCreatorReference()); xcontext.getWiki().protectUserPage(document.getFullName(), "edit", document, xcontext); return document; } private String clean(String str) { return RegExUtils.removePattern(str, "[\\.\\:\\s,@\\^]"); } private void putVariable(Map<String, String> map, String key, String value) { if (value != null) { map.put(key, value); map.put(key + ".lowerCase", value.toLowerCase()); map.put(key + "._lowerCase", value.toLowerCase()); map.put(key + ".upperCase", value.toUpperCase()); map.put(key + "._upperCase", value.toUpperCase()); String cleanValue = clean(value); map.put(key + ".clean", cleanValue); map.put(key + "._clean", cleanValue); map.put(key + ".clean.lowerCase", cleanValue.toLowerCase()); map.put(key + "._clean._lowerCase", cleanValue.toLowerCase()); map.put(key + ".clean.upperCase", cleanValue.toUpperCase()); map.put(key + "._clean._upperCase", cleanValue.toUpperCase()); } } private Map<String, String> createFormatMap(IDTokenClaimsSet idToken, UserInfo userInfo) { Map<String, String> formatMap = new HashMap<>(); // User informations putVariable(formatMap, "oidc.user.subject", userInfo.getSubject().getValue()); if (userInfo.getPreferredUsername() != null) { putVariable(formatMap, "oidc.user.preferredUsername", userInfo.getPreferredUsername()); } else { putVariable(formatMap, "oidc.user.preferredUsername", userInfo.getSubject().getValue()); } putVariable(formatMap, "oidc.user.mail", userInfo.getEmailAddress() == null ? "" : userInfo.getEmailAddress()); putVariable(formatMap, "oidc.user.familyName", userInfo.getFamilyName()); putVariable(formatMap, "oidc.user.givenName", userInfo.getGivenName()); // Provider (only XWiki OIDC providers) URL providerURL = this.configuration.getXWikiProvider(); if (providerURL != null) { putVariable(formatMap, "oidc.provider", providerURL.toString()); putVariable(formatMap, "oidc.provider.host", providerURL.getHost()); putVariable(formatMap, "oidc.provider.path", providerURL.getPath()); putVariable(formatMap, "oidc.provider.protocol", providerURL.getProtocol()); putVariable(formatMap, "oidc.provider.port", String.valueOf(providerURL.getPort())); } // Issuer putVariable(formatMap, "oidc.issuer", idToken.getIssuer().getValue()); try { URI issuerURI = new URI(idToken.getIssuer().getValue()); putVariable(formatMap, "oidc.issuer.host", issuerURI.getHost()); putVariable(formatMap, "oidc.issuer.path", issuerURI.getPath()); putVariable(formatMap, "oidc.issuer.scheme", issuerURI.getScheme()); putVariable(formatMap, "oidc.issuer.port", String.valueOf(issuerURI.getPort())); } catch (URISyntaxException e) { // TODO: log something ? } // Inject the whole JSON addJSON("oidc.user.", userInfo.toJSONObject(), formatMap); return formatMap; } private void addJSON(String prefix, Map<String, ?> json, Map<String, String> formatMap) { for (Map.Entry<String, ?> entry : json.entrySet()) { if (entry.getValue() != null) { if (entry.getValue() instanceof Map) { addJSON(prefix + entry.getKey() + '.', (Map) entry.getValue(), formatMap); } else { putVariable(formatMap, prefix + entry.getKey(), entry.getValue().toString()); } } } } private String formatXWikiUserName(StringSubstitutor substitutor) { return substitutor.replace(this.configuration.getXWikiUserNameFormater()); } private String formatSubjec(StringSubstitutor substitutor) { return substitutor.replace(this.configuration.getSubjectFormater()); } public void logout() { XWikiRequest request = this.xcontextProvider.get().getRequest(); // Send logout request this.sendLogout(); // TODO: remove cookies // Make sure the session is free from anything related to a previously authenticated user (i.e. in case we are // just after a logout) request.getSession().removeAttribute(OIDCClientConfiguration.PROP_SESSION_ACCESSTOKEN); request.getSession().removeAttribute(OIDCClientConfiguration.PROP_SESSION_IDTOKEN); request.getSession().removeAttribute(OIDCClientConfiguration.PROP_ENDPOINT_AUTHORIZATION); request.getSession().removeAttribute(OIDCClientConfiguration.PROP_ENDPOINT_TOKEN); request.getSession().removeAttribute(OIDCClientConfiguration.PROP_ENDPOINT_USERINFO); request.getSession().removeAttribute(OIDCClientConfiguration.PROP_IDTOKENCLAIMS); request.getSession().removeAttribute(OIDCClientConfiguration.PROP_INITIAL_REQUEST); request.getSession().removeAttribute(OIDCClientConfiguration.PROP_XWIKIPROVIDER); request.getSession().removeAttribute(OIDCClientConfiguration.PROP_STATE); request.getSession().removeAttribute(OIDCClientConfiguration.PROP_USER_NAMEFORMATER); request.getSession().removeAttribute(OIDCClientConfiguration.PROP_USER_SUBJECTFORMATER); request.getSession().removeAttribute(OIDCClientConfiguration.PROP_USERINFOCLAIMS); } }
oidc-authenticator/src/main/java/org/xwiki/contrib/oidc/auth/internal/OIDCUserManager.java
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.xwiki.contrib.oidc.auth.internal; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.net.URLConnection; import java.security.Principal; import java.util.Arrays; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.stream.Collectors; import javax.inject.Inject; import javax.inject.Provider; import javax.inject.Singleton; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang3.RegExUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.exception.ExceptionUtils; import org.apache.commons.text.StringSubstitutor; import org.securityfilter.realm.SimplePrincipal; import org.slf4j.Logger; import org.xwiki.component.annotation.Component; import org.xwiki.component.manager.ComponentManager; import org.xwiki.context.concurrent.ExecutionContextRunnable; import org.xwiki.contrib.oidc.OIDCUserInfo; import org.xwiki.contrib.oidc.auth.internal.OIDCClientConfiguration.GroupMapping; import org.xwiki.contrib.oidc.auth.store.OIDCUserStore; import org.xwiki.contrib.oidc.event.OIDCUserEventData; import org.xwiki.contrib.oidc.event.OIDCUserUpdated; import org.xwiki.contrib.oidc.event.OIDCUserUpdating; import org.xwiki.contrib.oidc.provider.internal.OIDCException; import org.xwiki.model.reference.DocumentReference; import org.xwiki.model.reference.SpaceReference; import org.xwiki.observation.ObservationManager; import org.xwiki.query.QueryException; import com.nimbusds.jwt.PlainJWT; import com.nimbusds.oauth2.sdk.ParseException; import com.nimbusds.oauth2.sdk.http.HTTPRequest; import com.nimbusds.oauth2.sdk.http.HTTPResponse; import com.nimbusds.oauth2.sdk.token.BearerAccessToken; import com.nimbusds.openid.connect.sdk.LogoutRequest; import com.nimbusds.openid.connect.sdk.UserInfoErrorResponse; import com.nimbusds.openid.connect.sdk.UserInfoRequest; import com.nimbusds.openid.connect.sdk.UserInfoResponse; import com.nimbusds.openid.connect.sdk.UserInfoSuccessResponse; import com.nimbusds.openid.connect.sdk.claims.Address; import com.nimbusds.openid.connect.sdk.claims.ClaimsSet; import com.nimbusds.openid.connect.sdk.claims.IDTokenClaimsSet; import com.nimbusds.openid.connect.sdk.claims.UserInfo; import com.xpn.xwiki.XWikiContext; import com.xpn.xwiki.XWikiException; import com.xpn.xwiki.doc.XWikiDocument; import com.xpn.xwiki.objects.BaseObject; import com.xpn.xwiki.objects.classes.BaseClass; import com.xpn.xwiki.user.api.XWikiRightService; import com.xpn.xwiki.web.XWikiRequest; /** * Various tools to manipulate users. * * @version $Id$ * @since 1.2 */ @Component(roles = OIDCUserManager.class) @Singleton public class OIDCUserManager { @Inject private Provider<XWikiContext> xcontextProvider; @Inject private OIDCClientConfiguration configuration; @Inject private OIDCUserStore store; @Inject private ObservationManager observation; @Inject private ComponentManager componentManager; @Inject private Logger logger; private Executor executor = Executors.newFixedThreadPool(1); private static final String XWIKI_GROUP_MEMBERFIELD = "member"; private static final String XWIKI_GROUP_PREFIX = "XWiki."; public void updateUserInfoAsync() throws URISyntaxException { final Endpoint userInfoEndpoint = this.configuration.getUserInfoOIDCEndpoint(); final IDTokenClaimsSet idToken = this.configuration.getIdToken(); final BearerAccessToken accessToken = this.configuration.getAccessToken(); this.executor.execute(new ExecutionContextRunnable(() -> { try { updateUserInfo(userInfoEndpoint, idToken, accessToken); } catch (Exception e) { logger.error("Failed to update user informations", e); } }, this.componentManager)); } public void checkUpdateUserInfo() { Date date = this.configuration.removeUserInfoExpirationDate(); if (date != null) { if (date.before(new Date())) { try { updateUserInfoAsync(); } catch (Exception e) { this.logger.error("Failed to update user informations", e); } // Restart user information expiration counter this.configuration.resetUserInfoExpirationDate(); } else { // Put back the date this.configuration.setUserInfoExpirationDate(date); } } } public Principal updateUserInfo(BearerAccessToken accessToken) throws URISyntaxException, IOException, ParseException, OIDCException, XWikiException, QueryException { Principal principal = updateUserInfo(this.configuration.getUserInfoOIDCEndpoint(), this.configuration.getIdToken(), accessToken); // Restart user information expiration counter this.configuration.resetUserInfoExpirationDate(); return principal; } public Principal updateUserInfo(Endpoint userInfoEndpoint, IDTokenClaimsSet idToken, BearerAccessToken accessToken) throws IOException, ParseException, OIDCException, XWikiException, QueryException { // Get OIDC user info this.logger.debug("OIDC user info request ({},{})", userInfoEndpoint, accessToken); UserInfoRequest userinfoRequest = new UserInfoRequest(userInfoEndpoint.getURI(), this.configuration.getUserInfoEndPointMethod(), accessToken); HTTPRequest userinfoHTTP = userinfoRequest.toHTTPRequest(); userInfoEndpoint.prepare(userinfoHTTP); this.logger.debug("OIDC user info request ({}?{},{})", userinfoHTTP.getURL(), userinfoHTTP.getQuery(), userinfoHTTP.getHeaderMap()); HTTPResponse httpResponse = userinfoHTTP.send(); this.logger.debug("OIDF user info response ({})", httpResponse.getContent()); UserInfoResponse userinfoResponse = UserInfoResponse.parse(httpResponse); if (!userinfoResponse.indicatesSuccess()) { UserInfoErrorResponse error = (UserInfoErrorResponse) userinfoResponse; throw new OIDCException("Failed to get user info", error.getErrorObject()); } UserInfoSuccessResponse userinfoSuccessResponse = (UserInfoSuccessResponse) userinfoResponse; UserInfo userInfo = userinfoSuccessResponse.getUserInfo(); // Update/Create XWiki user return updateUser(idToken, userInfo); } private int sendLogout() { int ret = 0; Endpoint logoutURI = null; try { logoutURI = this.configuration.getLogoutOIDCEndpoint(); } catch (Exception e) { // TODO: log something ? } if (logoutURI != null) { try { ret = sendLogout(logoutURI, this.configuration.getIdToken()); } catch (Exception e) { // TODO: log something ? } } else { this.logger.debug("Don't send OIDC logout request: no OIDC logout URI set"); } return ret; } private int sendLogout(Endpoint logoutEndpoint, IDTokenClaimsSet idToken) throws IOException, ParseException { LogoutRequest logoutRequest = new LogoutRequest(logoutEndpoint.getURI(), new PlainJWT(idToken.toJWTClaimsSet())); HTTPRequest logoutHTTP = logoutRequest.toHTTPRequest(); logoutEndpoint.prepare(logoutHTTP); this.logger.debug("OIDC logout request ({}?{},{})", logoutHTTP.getURL(), logoutHTTP.getQuery(), logoutHTTP.getHeaderMap()); HTTPResponse httpResponse = logoutHTTP.send(); this.logger.debug("OIDC logout response ({})", httpResponse.getContent()); return httpResponse.getStatusCode(); } private void checkAllowedGroups(UserInfo userInfo) throws OIDCException { List<String> providerGroups = null; Object providerGroupsObj = getClaim(this.configuration.getGroupClaim(), userInfo); if (this.configuration.isGroupCommaDelimited()) { providerGroups = Arrays.asList(StringUtils.split(providerGroupsObj.toString(), ",")); } else { providerGroups = (List<String>)providerGroupsObj; } String groupPrefix = this.configuration.getGroupPrefix(); if (!StringUtils.isEmpty(groupPrefix)) { providerGroups = providerGroups.stream() .filter(item -> item.startsWith(groupPrefix)) .map(item -> StringUtils.replace(item, groupPrefix, "")) .collect(Collectors.toList()); } if (providerGroups != null) { // Check allowed groups List<String> allowedGroups = this.configuration.getAllowedGroups(); if (allowedGroups != null) { if (!CollectionUtils.containsAny(providerGroups, allowedGroups)) { // Allowed groups have priority over forbidden groups throw new OIDCException( "The user is not allowed to authenticate because it's not a member of the following groups: " + allowedGroups); } return; } // Check forbidden groups List<String> forbiddenGroups = this.configuration.getForbiddenGroups(); if (forbiddenGroups != null && CollectionUtils.containsAny(providerGroups, forbiddenGroups)) { throw new OIDCException( "The user is not allowed to authenticate because it's a member of one of the following groups: " + forbiddenGroups); } } } private <T> T getClaim(String claim, ClaimsSet claims) { T value = (T) claims.getClaim(claim); // When it's not a proper OIDC claim try to find in a sub element of the JSON if (value == null) { value = (T) getJSONElement(claim, claims.toJSONObject()); } return value; } private <T> T getJSONElement(String pattern, Map<String, ?> json) { int index = pattern.indexOf('.'); String key; String patternEnd; if (index != -1) { key = pattern.substring(0, index); patternEnd = pattern.length() == (index + 1) ? null : pattern.substring(index + 1); } else { key = pattern; patternEnd = null; } Object value = json.get(key); if (patternEnd == null) { return (T) value; } if (value instanceof Map) { return (T) getJSONElement(patternEnd, (Map) value); } return (T) value; } public Principal updateUser(IDTokenClaimsSet idToken, UserInfo userInfo) throws XWikiException, QueryException, OIDCException { // Check allowed/forbidden groups checkAllowedGroups(userInfo); Map<String, String> formatMap = createFormatMap(idToken, userInfo); // Change the default StringSubstitutor behavior to produce an empty String instead of an unresolved pattern by // default StringSubstitutor substitutor = new StringSubstitutor(new OIDCStringLookup(formatMap)); String formattedSubject = formatSubjec(substitutor); XWikiDocument userDocument = this.store.searchDocument(idToken.getIssuer().getValue(), formattedSubject); XWikiDocument modifiableDocument; boolean newUser; if (userDocument == null) { userDocument = getNewUserDocument(substitutor); newUser = true; modifiableDocument = userDocument; } else { // Don't change the document author to not change document execution right newUser = false; modifiableDocument = userDocument.clone(); } XWikiContext xcontext = this.xcontextProvider.get(); // Set user fields BaseClass userClass = xcontext.getWiki().getUserClass(xcontext); BaseObject userObject = modifiableDocument.getXObject(userClass.getDocumentReference(), true, xcontext); // Make sure the user is active by default userObject.set("active", 1, xcontext); // Address Address address = userInfo.getAddress(); if (address != null) { userObject.set("address", address.getFormatted(), xcontext); } // Email if (userInfo.getEmailAddress() != null) { userObject.set("email", userInfo.getEmailAddress(), xcontext); } // Last name if (userInfo.getFamilyName() != null) { userObject.set("last_name", userInfo.getFamilyName(), xcontext); } // First name if (userInfo.getGivenName() != null) { userObject.set("first_name", userInfo.getGivenName(), xcontext); } // Phone if (userInfo.getPhoneNumber() != null) { userObject.set("phone", userInfo.getPhoneNumber(), xcontext); } // Default locale if (userInfo.getLocale() != null) { userObject.set("default_language", Locale.forLanguageTag(userInfo.getLocale()).toString(), xcontext); } // Time Zone if (userInfo.getZoneinfo() != null) { userObject.set("timezone", userInfo.getZoneinfo(), xcontext); } // Website if (userInfo.getWebsite() != null) { userObject.set("blog", userInfo.getWebsite().toString(), xcontext); } // Avatar if (userInfo.getPicture() != null) { try { String filename = FilenameUtils.getName(userInfo.getPicture().toString()); URLConnection connection = userInfo.getPicture().toURL().openConnection(); connection.setRequestProperty("User-Agent", this.getClass().getPackage().getImplementationTitle() + '/' + this.getClass().getPackage().getImplementationVersion()); try (InputStream content = connection.getInputStream()) { modifiableDocument.setAttachment(filename, content, xcontext); } userObject.set("avatar", filename, xcontext); } catch (IOException e) { this.logger.warn("Failed to get user avatar from URL [{}]: {}", userInfo.getPicture(), ExceptionUtils.getRootCauseMessage(e)); } } // XWiki claims updateXWikiClaims(modifiableDocument, userClass, userObject, userInfo, xcontext); // Set OIDC fields this.store.updateOIDCUser(modifiableDocument, idToken.getIssuer().getValue(), formattedSubject); // Configured user mapping updateUserMapping(modifiableDocument, userClass, userObject, xcontext, substitutor); // Data to send with the event OIDCUserEventData eventData = new OIDCUserEventData(new NimbusOIDCIdToken(idToken), new NimbusOIDCUserInfo(userInfo)); // Notify this.observation.notify(new OIDCUserUpdating(modifiableDocument.getDocumentReference()), modifiableDocument, eventData); boolean userUpdated = false; // Apply the modifications if (newUser || userDocument.apply(modifiableDocument)) { String comment; if (newUser) { comment = "Create user from OpenID Connect"; } else { comment = "Update user from OpenID Connect"; } xcontext.getWiki().saveDocument(userDocument, comment, xcontext); // Now let's add the new user to XWiki.XWikiAllGroup if (newUser) { xcontext.getWiki().setUserDefaultGroup(userDocument.getFullName(), xcontext); } userUpdated = true; } // Sync user groups with the provider if (this.configuration.isGroupSync()) { userUpdated = updateGroupMembership(userInfo, userDocument, xcontext); } // Notify if (userUpdated) { this.observation.notify(new OIDCUserUpdated(userDocument.getDocumentReference()), userDocument, eventData); } return new SimplePrincipal(userDocument.getPrefixedFullName()); } private void updateUserMapping(XWikiDocument userDocument, BaseClass userClass, BaseObject userObject, XWikiContext xcontext, StringSubstitutor substitutor) { Map<String, String> mapping = this.configuration.getUserMapping(); if (mapping != null) { for (Map.Entry<String, String> entry : mapping.entrySet()) { String xwikiProperty = entry.getKey(); String oidcFormat = entry.getValue(); String oidcValue = substitutor.replace(oidcFormat); setValue(userDocument, userClass, userObject, xwikiProperty, oidcValue, xcontext); } } } private boolean updateGroupMembership(UserInfo userInfo, XWikiDocument userDocument, XWikiContext xcontext) throws XWikiException { String groupClaim = this.configuration.getGroupClaim(); this.logger.debug("Getting groups sent by the provider associated with claim [{}]", groupClaim); List<String> providerGroups = null; Object providerGroupsObj = getClaim(this.configuration.getGroupClaim(), userInfo); if (this.configuration.isGroupCommaDelimited()) { providerGroups = Arrays.asList(StringUtils.split(providerGroupsObj.toString(), ",")); } else { providerGroups = (List<String>)providerGroupsObj; } String groupPrefix = this.configuration.getGroupPrefix(); if (!StringUtils.isEmpty(groupPrefix)) { providerGroups = providerGroups.stream() .filter(item -> item.startsWith(groupPrefix)) .map(item -> StringUtils.replace(item, groupPrefix, "")) .collect(Collectors.toList()); } if (providerGroups != null) { this.logger.debug("The provider sent the following groups: {}", providerGroups); return syncXWikiGroupsMembership(userDocument.getFullName(), providerGroups, xcontext); } else { this.logger.debug("The provider did not sent any group"); } return false; } /** * Remove user name from provided XWiki group. * * @param xwikiUserName the full name of the user. * @param xwikiGroupName the name of the group. * @param context the XWiki context. */ protected void removeUserFromXWikiGroup(String xwikiUserName, String xwikiGroupName, XWikiContext context) { this.logger.debug("Removing user from [{}] ...", xwikiGroupName); try { BaseClass groupClass = context.getWiki().getGroupClass(context); // Get the XWiki document holding the objects comprising the group membership list XWikiDocument groupDoc = context.getWiki().getDocument(xwikiGroupName, context); synchronized (groupDoc) { // Get and remove the specific group membership object for the user BaseObject groupObj = groupDoc.getXObject(groupClass.getDocumentReference(), XWIKI_GROUP_MEMBERFIELD, xwikiUserName); groupDoc.removeXObject(groupObj); // Save modifications context.getWiki().saveDocument(groupDoc, context); } } catch (Exception e) { this.logger.error("Failed to remove user [{}] from group [{}]", xwikiUserName, xwikiGroupName, e); } } /** * Add user name into provided XWiki group. * * @param xwikiUserName the full name of the user. * @param xwikiGroupName the name of the group. * @param context the XWiki context. */ protected void addUserToXWikiGroup(String xwikiUserName, String xwikiGroupName, XWikiContext context) { try { BaseClass groupClass = context.getWiki().getGroupClass(context); // Get document representing group XWikiDocument groupDoc = context.getWiki().getDocument(xwikiGroupName, context); this.logger.debug("Adding user [{}] to xwiki group [{}]", xwikiUserName, xwikiGroupName); synchronized (groupDoc) { // Make extra sure the group cannot contain duplicate (even if this method is not supposed to be called // in this case) List<BaseObject> xobjects = groupDoc.getXObjects(groupClass.getDocumentReference()); if (xobjects != null) { for (BaseObject memberObj : xobjects) { if (memberObj != null) { String existingMember = memberObj.getStringValue(XWIKI_GROUP_MEMBERFIELD); if (existingMember != null && existingMember.equals(xwikiUserName)) { this.logger.warn("User [{}] already exist in group [{}]", xwikiUserName, groupDoc.getDocumentReference()); return; } } } } // Add a member object to document BaseObject memberObj = groupDoc.newXObject(groupClass.getDocumentReference(), context); Map<String, String> map = new HashMap<>(); map.put(XWIKI_GROUP_MEMBERFIELD, xwikiUserName); groupClass.fromMap(map, memberObj); // Save modifications context.getWiki().saveDocument(groupDoc, context); } this.logger.debug("Finished adding user [{}] to xwiki group [{}]", xwikiUserName, xwikiGroupName); } catch (Exception e) { this.logger.error("Failed to add a user [{}] to a group [{}]", xwikiUserName, xwikiGroupName, e); } } /** * Synchronize user XWiki membership with the Open ID xwiki_groups claim. * * @param xwikiUserName the name of the user. * @param providerGroups the Open ID xwiki_groups claim. * @param context the XWiki context. * @throws XWikiException error when synchronizing user membership. */ public Boolean syncXWikiGroupsMembership(String xwikiUserName, List<String> providerGroups, XWikiContext context) throws XWikiException { Boolean userUpdated = false; this.logger.debug("Updating group membership for the user [{}]", xwikiUserName); Collection<String> xwikiUserGroupList = context.getWiki().getGroupService(context).getAllGroupsNamesForMember(xwikiUserName, 0, 0, context); this.logger.debug("The user belongs to following XWiki groups: {}", xwikiUserGroupList); GroupMapping groupMapping = this.configuration.getGroupMapping(); // Add missing group membership for (String providerGroupName : providerGroups) { if (groupMapping == null) { String xwikiGroup = this.configuration.toXWikiGroup(providerGroupName); if (!xwikiUserGroupList.contains(xwikiGroup)) { addUserToXWikiGroup(xwikiUserName, xwikiGroup, context); userUpdated = true; } } else { Set<String> mappedGroups = groupMapping.fromProvider(providerGroupName); if (mappedGroups != null) { for (String mappedGroup : mappedGroups) { if (!xwikiUserGroupList.contains(mappedGroup)) { addUserToXWikiGroup(xwikiUserName, mappedGroup, context); userUpdated = true; } } } } } // Remove group membership for (String xwikiGroupName : xwikiUserGroupList) { if (groupMapping == null) { if (!providerGroups.contains(xwikiGroupName) && !providerGroups.contains(xwikiGroupName.substring(XWIKI_GROUP_PREFIX.length()))) { removeUserFromXWikiGroup(xwikiUserName, xwikiGroupName, context); userUpdated = true; } } else { Set<String> mappedGroups = groupMapping.fromXWiki(xwikiGroupName); if (mappedGroups != null && !CollectionUtils.containsAny(providerGroups, mappedGroups)) { removeUserFromXWikiGroup(xwikiUserName, xwikiGroupName, context); userUpdated = true; } } } return userUpdated; } private void updateXWikiClaims(XWikiDocument userDocument, BaseClass userClass, BaseObject userObject, UserInfo userInfo, XWikiContext xcontext) { this.logger.debug("Updating XWiki claims"); for (Map.Entry<String, Object> entry : userInfo.toJSONObject().entrySet()) { if (entry.getKey().startsWith(OIDCUserInfo.CLAIMPREFIX_XWIKI_USER)) { String xwikiKey = entry.getKey().substring(OIDCUserInfo.CLAIMPREFIX_XWIKI_USER.length()); setValue(userDocument, userClass, userObject, xwikiKey, entry.getValue(), xcontext); } } } private void setValue(XWikiDocument userDocument, BaseClass userClass, BaseObject userObject, String xwikiKey, Object value, XWikiContext xcontext) { // Try in the user object if (userClass.getField(xwikiKey) != null) { setValue(userObject, xwikiKey, value, xcontext); return; } // Try in the whole user document BaseObject xobject = userDocument.getFirstObject(xwikiKey); if (xobject != null) { setValue(xobject, xwikiKey, value, xcontext); } } private void setValue(BaseObject xobject, String key, Object value, XWikiContext xcontext) { Object cleanValue; if (value instanceof List) { cleanValue = value; } else { // Go through String to be safe // TODO: find a more effective converter (the best would be to userObject#set to be stronger) cleanValue = Objects.toString(value); } xobject.set(key, cleanValue, xcontext); } private XWikiDocument getNewUserDocument(StringSubstitutor substitutor) throws XWikiException { XWikiContext xcontext = this.xcontextProvider.get(); // TODO: add support for subwikis SpaceReference spaceReference = new SpaceReference(xcontext.getMainXWiki(), "XWiki"); // Generate default document name String documentName = formatXWikiUserName(substitutor); // Find not already existing document DocumentReference reference = new DocumentReference(documentName, spaceReference); XWikiDocument document = xcontext.getWiki().getDocument(reference, xcontext); for (int index = 0; !document.isNew(); ++index) { reference = new DocumentReference(documentName + '-' + index, spaceReference); document = xcontext.getWiki().getDocument(reference, xcontext); } // Initialize document document.setCreator(XWikiRightService.SUPERADMIN_USER); document.setAuthorReference(document.getCreatorReference()); document.setContentAuthorReference(document.getCreatorReference()); xcontext.getWiki().protectUserPage(document.getFullName(), "edit", document, xcontext); return document; } private String clean(String str) { return RegExUtils.removePattern(str, "[\\.\\:\\s,@\\^]"); } private void putVariable(Map<String, String> map, String key, String value) { if (value != null) { map.put(key, value); map.put(key + ".lowerCase", value.toLowerCase()); map.put(key + "._lowerCase", value.toLowerCase()); map.put(key + ".upperCase", value.toUpperCase()); map.put(key + "._upperCase", value.toUpperCase()); String cleanValue = clean(value); map.put(key + ".clean", cleanValue); map.put(key + "._clean", cleanValue); map.put(key + ".clean.lowerCase", cleanValue.toLowerCase()); map.put(key + "._clean._lowerCase", cleanValue.toLowerCase()); map.put(key + ".clean.upperCase", cleanValue.toUpperCase()); map.put(key + "._clean._upperCase", cleanValue.toUpperCase()); } } private Map<String, String> createFormatMap(IDTokenClaimsSet idToken, UserInfo userInfo) { Map<String, String> formatMap = new HashMap<>(); // User informations putVariable(formatMap, "oidc.user.subject", userInfo.getSubject().getValue()); if (userInfo.getPreferredUsername() != null) { putVariable(formatMap, "oidc.user.preferredUsername", userInfo.getPreferredUsername()); } else { putVariable(formatMap, "oidc.user.preferredUsername", userInfo.getSubject().getValue()); } putVariable(formatMap, "oidc.user.mail", userInfo.getEmailAddress() == null ? "" : userInfo.getEmailAddress()); putVariable(formatMap, "oidc.user.familyName", userInfo.getFamilyName()); putVariable(formatMap, "oidc.user.givenName", userInfo.getGivenName()); // Provider (only XWiki OIDC providers) URL providerURL = this.configuration.getXWikiProvider(); if (providerURL != null) { putVariable(formatMap, "oidc.provider", providerURL.toString()); putVariable(formatMap, "oidc.provider.host", providerURL.getHost()); putVariable(formatMap, "oidc.provider.path", providerURL.getPath()); putVariable(formatMap, "oidc.provider.protocol", providerURL.getProtocol()); putVariable(formatMap, "oidc.provider.port", String.valueOf(providerURL.getPort())); } // Issuer putVariable(formatMap, "oidc.issuer", idToken.getIssuer().getValue()); try { URI issuerURI = new URI(idToken.getIssuer().getValue()); putVariable(formatMap, "oidc.issuer.host", issuerURI.getHost()); putVariable(formatMap, "oidc.issuer.path", issuerURI.getPath()); putVariable(formatMap, "oidc.issuer.scheme", issuerURI.getScheme()); putVariable(formatMap, "oidc.issuer.port", String.valueOf(issuerURI.getPort())); } catch (URISyntaxException e) { // TODO: log something ? } // Inject the whole JSON addJSON("oidc.user.", userInfo.toJSONObject(), formatMap); return formatMap; } private void addJSON(String prefix, Map<String, ?> json, Map<String, String> formatMap) { for (Map.Entry<String, ?> entry : json.entrySet()) { if (entry.getValue() != null) { if (entry.getValue() instanceof Map) { addJSON(prefix + entry.getKey() + '.', (Map) entry.getValue(), formatMap); } else { putVariable(formatMap, prefix + entry.getKey(), entry.getValue().toString()); } } } } private String formatXWikiUserName(StringSubstitutor substitutor) { return substitutor.replace(this.configuration.getXWikiUserNameFormater()); } private String formatSubjec(StringSubstitutor substitutor) { return substitutor.replace(this.configuration.getSubjectFormater()); } public void logout() { XWikiRequest request = this.xcontextProvider.get().getRequest(); // Send logout request this.sendLogout(); // TODO: remove cookies // Make sure the session is free from anything related to a previously authenticated user (i.e. in case we are // just after a logout) request.getSession().removeAttribute(OIDCClientConfiguration.PROP_SESSION_ACCESSTOKEN); request.getSession().removeAttribute(OIDCClientConfiguration.PROP_SESSION_IDTOKEN); request.getSession().removeAttribute(OIDCClientConfiguration.PROP_ENDPOINT_AUTHORIZATION); request.getSession().removeAttribute(OIDCClientConfiguration.PROP_ENDPOINT_TOKEN); request.getSession().removeAttribute(OIDCClientConfiguration.PROP_ENDPOINT_USERINFO); request.getSession().removeAttribute(OIDCClientConfiguration.PROP_IDTOKENCLAIMS); request.getSession().removeAttribute(OIDCClientConfiguration.PROP_INITIAL_REQUEST); request.getSession().removeAttribute(OIDCClientConfiguration.PROP_XWIKIPROVIDER); request.getSession().removeAttribute(OIDCClientConfiguration.PROP_STATE); request.getSession().removeAttribute(OIDCClientConfiguration.PROP_USER_NAMEFORMATER); request.getSession().removeAttribute(OIDCClientConfiguration.PROP_USER_SUBJECTFORMATER); request.getSession().removeAttribute(OIDCClientConfiguration.PROP_USERINFOCLAIMS); } }
replace tabs with whitespaces
oidc-authenticator/src/main/java/org/xwiki/contrib/oidc/auth/internal/OIDCUserManager.java
replace tabs with whitespaces
<ide><path>idc-authenticator/src/main/java/org/xwiki/contrib/oidc/auth/internal/OIDCUserManager.java <ide> <ide> private void checkAllowedGroups(UserInfo userInfo) throws OIDCException <ide> { <del> List<String> providerGroups = null; <add> List<String> providerGroups = null; <ide> Object providerGroupsObj = getClaim(this.configuration.getGroupClaim(), userInfo); <del> if (this.configuration.isGroupCommaDelimited()) { <del> providerGroups = Arrays.asList(StringUtils.split(providerGroupsObj.toString(), ",")); <add> if (this.configuration.getGroupSeparator()!=null) { <add> providerGroups = Arrays.asList(StringUtils.split(providerGroupsObj.toString(), this.configuration.getGroupSeparator())); <ide> } else { <del> providerGroups = (List<String>)providerGroupsObj; <add> providerGroups = (List<String>)providerGroupsObj; <ide> } <ide> String groupPrefix = this.configuration.getGroupPrefix(); <ide> if (!StringUtils.isEmpty(groupPrefix)) { <del> providerGroups = providerGroups.stream() <del> .filter(item -> item.startsWith(groupPrefix)) <del> .map(item -> StringUtils.replace(item, groupPrefix, "")) <del> .collect(Collectors.toList()); <add> providerGroups = providerGroups.stream() <add> .filter(item -> item.startsWith(groupPrefix)) <add> .map(item -> StringUtils.replace(item, groupPrefix, "")) <add> .collect(Collectors.toList()); <ide> } <ide> <ide> if (providerGroups != null) { <ide> <ide> this.logger.debug("Getting groups sent by the provider associated with claim [{}]", groupClaim); <ide> <del> List<String> providerGroups = null; <add> List<String> providerGroups = null; <ide> Object providerGroupsObj = getClaim(this.configuration.getGroupClaim(), userInfo); <del> if (this.configuration.isGroupCommaDelimited()) { <del> providerGroups = Arrays.asList(StringUtils.split(providerGroupsObj.toString(), ",")); <add> if (this.configuration.getGroupSeparator()!=null) { <add> providerGroups = Arrays.asList(StringUtils.split(providerGroupsObj.toString(), this.configuration.getGroupSeparator())); <ide> } else { <del> providerGroups = (List<String>)providerGroupsObj; <add> providerGroups = (List<String>)providerGroupsObj; <ide> } <ide> String groupPrefix = this.configuration.getGroupPrefix(); <ide> if (!StringUtils.isEmpty(groupPrefix)) { <del> providerGroups = providerGroups.stream() <del> .filter(item -> item.startsWith(groupPrefix)) <del> .map(item -> StringUtils.replace(item, groupPrefix, "")) <del> .collect(Collectors.toList()); <add> providerGroups = providerGroups.stream() <add> .filter(item -> item.startsWith(groupPrefix)) <add> .map(item -> StringUtils.replace(item, groupPrefix, "")) <add> .collect(Collectors.toList()); <ide> } <ide> <ide> if (providerGroups != null) {
Java
apache-2.0
cbed084873ab6d55c9f3f26cf1750489aedfac50
0
eayun/ovirt-engine,OpenUniversity/ovirt-engine,yapengsong/ovirt-engine,zerodengxinchao/ovirt-engine,yingyun001/ovirt-engine,walteryang47/ovirt-engine,yapengsong/ovirt-engine,yingyun001/ovirt-engine,halober/ovirt-engine,OpenUniversity/ovirt-engine,walteryang47/ovirt-engine,walteryang47/ovirt-engine,eayun/ovirt-engine,eayun/ovirt-engine,yapengsong/ovirt-engine,halober/ovirt-engine,walteryang47/ovirt-engine,zerodengxinchao/ovirt-engine,yapengsong/ovirt-engine,yapengsong/ovirt-engine,zerodengxinchao/ovirt-engine,yingyun001/ovirt-engine,eayun/ovirt-engine,zerodengxinchao/ovirt-engine,OpenUniversity/ovirt-engine,eayun/ovirt-engine,zerodengxinchao/ovirt-engine,halober/ovirt-engine,OpenUniversity/ovirt-engine,yingyun001/ovirt-engine,halober/ovirt-engine,yingyun001/ovirt-engine,walteryang47/ovirt-engine,OpenUniversity/ovirt-engine
package org.ovirt.engine.core.bll; import org.ovirt.engine.core.common.action.VmOperationParameterBase; import org.ovirt.engine.core.common.businessentities.VM; import org.ovirt.engine.core.common.businessentities.VMStatus; import org.ovirt.engine.core.compat.Guid; import org.ovirt.engine.core.utils.log.Log; import org.ovirt.engine.core.utils.log.LogFactory; public abstract class VmOperationCommandBase<T extends VmOperationParameterBase> extends VmCommand<T> { // The log: private static final Log log = LogFactory.getLog(VmOperationCommandBase.class); /** * Constructor for command creation when compensation is applied on startup * * @param commandId */ protected VmOperationCommandBase(Guid commandId) { super(commandId); } public VmOperationCommandBase(T parameters) { super(parameters); } @Override protected void executeVmCommand() { if (getRunningOnVds()) { perform(); return; } setActionReturnValue((getVm() != null) ? getVm().getStatus() : VMStatus.Down); } /** * This method checks if the virtual machine is running in some host. It also * has the side effect of storing the reference to the host inside the command. * * @return <code>true</code> if the virtual machine is running in a any host, * <code>false</code> otherwise */ protected boolean getRunningOnVds() { // We will need the virtual machine and the status, so it is worth saving references: final VM vm = getVm(); final VMStatus status = vm.getStatus(); // If the status of the machine implies that it is not running in a host then // there is no need to find the id of the host: if (!status.isRunningOrPaused() && status != VMStatus.NotResponding) { return false; } // Find the id of the host where the machine is running: Guid hostId = vm.getRunOnVds(); if (hostId == null) { log.warnFormat("Strange, according to the status \"{0}\" virtual machine \"{1}\" should be running in a host but it isn't.", status, vm.getId()); return false; } // Find the reference to the host using the id that we got before (setting // the host to null is required in order to make sure that the host is // reloaded from the database): setVdsId(new Guid(hostId.toString())); setVds(null); if (getVds() == null) { log.warnFormat("Strange, virtual machine \"{0}\" is is running in host \"{1}\" but that host can't be found.", vm.getId(), hostId); return false; } // If we are here everything went right, so the machine is running in // a host: return true; } protected abstract void perform(); }
backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/VmOperationCommandBase.java
package org.ovirt.engine.core.bll; import org.ovirt.engine.core.common.action.VmOperationParameterBase; import org.ovirt.engine.core.common.businessentities.VM; import org.ovirt.engine.core.common.businessentities.VMStatus; import org.ovirt.engine.core.compat.Guid; import org.ovirt.engine.core.utils.log.Log; import org.ovirt.engine.core.utils.log.LogFactory; public abstract class VmOperationCommandBase<T extends VmOperationParameterBase> extends VmCommand<T> { // The log: private static final Log log = LogFactory.getLog(VmOperationCommandBase.class); /** * Constructor for command creation when compensation is applied on startup * * @param commandId */ protected VmOperationCommandBase(Guid commandId) { super(commandId); } public VmOperationCommandBase(T parameters) { super(parameters); } @Override protected void executeVmCommand() { if (GetRunningOnVds()) { perform(); return; } setActionReturnValue((getVm() != null) ? getVm().getStatus() : VMStatus.Down); } /** * This method checks if the virtual machine is running in some host. It also * has the side effect of storing the reference to the host inside the command. * * @return <code>true</code> if the virtual machine is running in a any host, * <code>false</code> otherwise */ protected boolean GetRunningOnVds() { // We will need the virtual machine and the status, so it is worth saving references: final VM vm = getVm(); final VMStatus status = vm.getStatus(); // If the status of the machine implies that it is not running in a host then // there is no need to find the id of the host: if (!status.isRunningOrPaused() && status != VMStatus.NotResponding) { return false; } // Find the id of the host where the machine is running: Guid hostId = vm.getRunOnVds(); if (hostId == null) { log.warnFormat("Strange, according to the status \"{0}\" virtual machine \"{1}\" should be running in a host but it isn't.", status, vm.getId()); return false; } // Find the reference to the host using the id that we got before (setting // the host to null is required in order to make sure that the host is // reloaded from the database): setVdsId(new Guid(hostId.toString())); setVds(null); if (getVds() == null) { log.warnFormat("Strange, virtual machine \"{0}\" is is running in host \"{1}\" but that host can't be found.", vm.getId(), hostId); return false; } // If we are here everything went right, so the machine is running in // a host: return true; } protected abstract void perform(); }
core: rename method to lowercase in VmOperationCommandBase Change-Id: I87b7f3377bf8f754a7c227f63d4088b5a53b56e1 Signed-off-by: Alissa Bonas <[email protected]>
backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/VmOperationCommandBase.java
core: rename method to lowercase in VmOperationCommandBase
<ide><path>ackend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/VmOperationCommandBase.java <ide> <ide> @Override <ide> protected void executeVmCommand() { <del> if (GetRunningOnVds()) { <add> if (getRunningOnVds()) { <ide> perform(); <ide> return; <ide> } <ide> * @return <code>true</code> if the virtual machine is running in a any host, <ide> * <code>false</code> otherwise <ide> */ <del> protected boolean GetRunningOnVds() { <add> protected boolean getRunningOnVds() { <ide> // We will need the virtual machine and the status, so it is worth saving references: <ide> final VM vm = getVm(); <ide> final VMStatus status = vm.getStatus();
JavaScript
mit
96e0e92fe771fc7dbac646e056dfc05509d3d2cc
0
mikeymicrophone/blue-ridge,wycats/blue-ridge,wycats/blue-ridge,wycats/blue-ridge,relevance/blue-ridge,relevance/blue-ridge,infopark/vendor_blue-ridge,mikeymicrophone/blue-ridge,wycats/blue-ridge,infopark/vendor_blue-ridge
/* * env.rhino.js */ var __env__ = {}; (function($env){ //You can emulate different user agents by overriding these after loading env $env.appCodeName = "EnvJS";//eg "Mozilla" $env.appName = "Resig/20070309 BirdDog/0.0.0.1";//eg "Gecko/20070309 Firefox/2.0.0.3" //set this to true and see profile/profile.js to select which methods //to profile $env.profile = false; $env.debug = function(){}; $env.log = function(){}; //uncomment this if you want to get some internal log statementes // $env.log = print; $env.log("Initializing Rhino Platform Env"); $env.error = function(msg, e){ print("ERROR! : " + msg); print(e||""); }; $env.lineSource = function(e){ return e.rhinoException?e.rhinoException.lineSource():"(line ?)"; }; $env.hashCode = function(obj){ return obj?obj.hashCode().toString():null; }; //For Java the window.location object is a java.net.URL $env.location = function(path, base){ var protocol = new RegExp('(^\\w*\:)'); var m = protocol.exec(path); if(m&&m.length>1){ return new java.net.URL(path).toString(); }else if(base){ return new java.net.URL(base + '/' + path).toString(); }else{ //return an absolute url from a relative to the file system return new java.io.File(path).toURL().toString(); } }; //For Java the window.timer is created using the java.lang.Thread in combination //with the java.lang.Runnable $env.timer = function(fn, time){ return new java.lang.Thread(new java.lang.Runnable({ run: function(){ while (true){ java.lang.Thread.currentThread().sleep(time); fn(); } } })); }; //Since we're running in rhino I guess we can safely assume //java is 'enabled'. I'm sure this requires more thought //than I've given it here $env.javaEnabled = true; //Used in the XMLHttpRquest implementation to run a // request in a seperate thread $env.runAsync = function(fn){ (new java.lang.Thread(new java.lang.Runnable({ run: fn }))).start(); }; //Used to write to a local file $env.writeToFile = function(text, url){ var out = new java.io.FileWriter( new java.io.File( new java.net.URI(url.toString()))); out.write( text, 0, text.length ); out.flush(); out.close(); }; //Used to delete a local file $env.deleteFile = function(url){ var file = new java.io.File( new java.net.URI( url ) ); file["delete"](); }; $env.connection = function(xhr, responseHandler){ var url = java.net.URL(xhr.url);//, $w.location); var connection; if ( /^file\:/.test(url) ) { if ( xhr.method == "PUT" ) { var text = data || "" ; $env.writeToFile(text, url); } else if ( xhr.method == "DELETE" ) { $env.deleteFile(url); } else { connection = url.openConnection(); connection.connect(); } } else { connection = url.openConnection(); connection.setRequestMethod( xhr.method ); // Add headers to Java connection for (var header in xhr.headers){ connection.addRequestProperty(header, xhr.headers[header]); }connection.connect(); // Stick the response headers into responseHeaders for (var i = 0; ; i++) { var headerName = connection.getHeaderFieldKey(i); var headerValue = connection.getHeaderField(i); if (!headerName && !headerValue) break; if (headerName) xhr.responseHeaders[headerName] = headerValue; } } if(connection){ xhr.readyState = 4; xhr.status = parseInt(connection.responseCode,10) || undefined; xhr.statusText = connection.responseMessage || ""; var contentEncoding = connection.getContentEncoding() || "utf-8", stream = (contentEncoding.equalsIgnoreCase("gzip") || contentEncoding.equalsIgnoreCase("decompress") )? new java.util.zip.GZIPInputStream(connection.getInputStream()) : connection.getInputStream(), baos = new java.io.ByteArrayOutputStream(), buffer = java.lang.reflect.Array.newInstance(java.lang.Byte.TYPE, 1024), length, responseXML = null; while ((length = stream.read(buffer)) != -1) { baos.write(buffer, 0, length); } baos.close(); stream.close(); xhr.responseText = java.nio.charset.Charset.forName(contentEncoding). decode(java.nio.ByteBuffer.wrap(baos.toByteArray())).toString(); } if(responseHandler){ responseHandler(); } }; var htmlDocBuilder = Packages.javax.xml.parsers.DocumentBuilderFactory.newInstance(); htmlDocBuilder.setNamespaceAware(false); htmlDocBuilder.setValidating(false); $env.parseHTML = function(htmlstring){ return htmlDocBuilder.newDocumentBuilder().parse( new java.io.ByteArrayInputStream( (new java.lang.String(htmlstring)).getBytes("UTF8"))); }; var xmlDocBuilder = Packages.javax.xml.parsers.DocumentBuilderFactory.newInstance(); xmlDocBuilder.setNamespaceAware(true); xmlDocBuilder.setValidating(true); $env.parseXML = function(xmlstring){ return xmlDocBuilder.newDocumentBuilder().parse( new java.io.ByteArrayInputStream( (new java.lang.String(xmlstring)).getBytes("UTF8"))); }; $env.xpath = function(expression, doc){ return Packages.javax.xml.xpath. XPathFactory.newInstance().newXPath(). evaluate(expression, doc, javax.xml.xpath.XPathConstants.NODESET); }; $env.os_name = java.lang.System.getProperty("os.name"); $env.os_arch = java.lang.System.getProperty("os.arch"); $env.os_version = java.lang.System.getProperty("os.version"); $env.lang = java.lang.System.getProperty("user.lang"); $env.platform = "Rhino ";//how do we get the version $env.safeScript = function(){ //do nothing }; $env.loadLocalScripts = function(script){ try{ if(script.type == 'text/javascript'){ if(script.src){ print("loading script :" + script.src); load($env.location(script.src, window.location + '/../')); }else{ print("loading script :" + script.text); eval(script.text); } } }catch(e){ print("Error loading script." , e); } }; })(__env__);/* * policy.js */ var __policy__ = {}; (function($policy, $env){ //you can change these to $env.safeScript to avoid loading scripts //or change to $env.loadLocalScripts to load local scripts $policy.loadScripts = $env.safeScript; })(__policy__, __env__);/* * Pure JavaScript Browser Environment * By John Resig <http://ejohn.org/> * Copyright 2008 John Resig, under the MIT License */ // The Window Object var __this__ = this; this.__defineGetter__('window', function(){ return __this__; }); try{ (function($w, $env, $policy){ /* * window.js * - this file will be wrapped in a closure providing the window object as $w */ // a logger or empty function available to all modules. var $log = $env.log, $error = $env.error, $debug = $env.debug; //The version of this application var $version = "0.1"; //This should be hooked to git or svn or whatever var $revision = "0.0.0.0"; //These descriptions of window properties are taken loosely David Flanagan's //'JavaScript - The Definitive Guide' (O'Reilly) /**> $cookies - see cookie.js <*/ // read only boolean specifies whether the window has been closed var $closed = false; // a read/write string that specifies the default message that appears in the status line var $defaultStatus = "Done"; // a read-only reference to the Document object belonging to this window /**> $document - See document.js <*/ //IE only, refers to the most recent event object - this maybe be removed after review var $event = null; //A read-only array of window objects var $frames = []; // a read-only reference to the History object /**> $history - see location.js <**/ // read-only properties that specify the height and width, in pixels var $innerHeight = 600, $innerWidth = 800; // a read-only reference to the Location object. the location object does expose read/write properties /**> $location - see location.js <**/ // a read only property specifying the name of the window. Can be set when using open() // and may be used when specifying the target attribute of links var $name = 'Resig Env Browser'; // a read-only reference to the Navigator object /**> $navigator - see navigator.js <**/ // a read/write reference to the Window object that contained the script that called open() to //open this browser window. This property is valid only for top-level window objects. var $opener; // Read-only properties that specify the total height and width, in pixels, of the browser window. // These dimensions include the height and width of the menu bar, toolbars, scrollbars, window // borders and so on. These properties are not supported by IE and IE offers no alternative // properties; var $outerHeight = $innerHeight, $outerWidth = $innerWidth; // Read-only properties that specify the number of pixels that the current document has been scrolled //to the right and down. These are not supported by IE. var $pageXOffset = 0, $pageYOffset = 0; //A read-only reference to the Window object that contains this window or frame. If the window is // a top-level window, parent refers to the window itself. If this window is a frame, this property // refers to the window or frame that conatins it. var $parent; // a read-only refernce to the Screen object that specifies information about the screen: // the number of available pixels and the number of available colors. /**> $screen - see screen.js <**/ // read only properties that specify the coordinates of the upper-left corner of the screen. var $screenX = 0, $screenY = 0; var $screenLeft = $screenX, $screenTop = $screenY; // a read-only refernce to this window itself. var $self; // a read/write string that specifies the current contents of the status line. var $status = ''; // a read-only reference to the top-level window that contains this window. If this // window is a top-level window it is simply a refernce to itself. If this window // is a frame, the top property refers to the top-level window that contains the frame. var $top; // the window property is identical to the self property. var $window = $w; $log("Initializing Window."); __extend__($w,{ get closed(){return $closed;}, get defaultStatus(){return $defaultStatus;}, set defaultStatus(_defaultStatus){$defaultStatus = _defaultStatus;}, //get document(){return $document;}, - see document.js get event(){return $event;}, get frames(){return $frames;}, //get history(){return $history;}, - see location.js get innerHeight(){return $innerHeight;}, get innerWidth(){return $innerWidth;}, get clientHeight(){return $innerHeight;}, get clientWidth(){return $innerWidth;}, //get location(){return $location;}, see location.js get name(){return $name;}, //get navigator(){return $navigator;}, see navigator.js get opener(){return $opener;}, get outerHeight(){return $outerHeight;}, get outerWidth(){return $outerWidth;}, get pageXOffest(){return $pageXOffset;}, get pageYOffset(){return $pageYOffset;}, get parent(){return $parent;}, //get screen(){return $screen;}, see screen.js get screenLeft(){return $screenLeft;}, get screenTop(){return $screenTop;}, get screenX(){return $screenX;}, get screenY(){return $screenY;}, get self(){return $self;}, get status(){return $status;}, set status(_status){$status = _status;}, get top(){return $top || $window;}, get window(){return $window;} }); $w.open = function(url, name, features, replace){ //TODO }; $w.close = function(){ //TODO }; /* Time related functions - see timer.js * - clearTimeout * - clearInterval * - setTimeout * - setInterval */ /* * Events related functions - see event.js * - addEventListener * - attachEvent * - detachEvent * - removeEventListener * * These functions are identical to the Element equivalents. */ /* * UIEvents related functions - see uievent.js * - blur * - focus * * These functions are identical to the Element equivalents. */ /* Dialog related functions - see dialog.js * - alert * - confirm * - prompt */ /* Screen related functions - see screen.js * - moveBy * - moveTo * - print * - resizeBy * - resizeTo * - scrollBy * - scrollTo */ /* CSS related functions - see css.js * - getComputedStyle */ /* * Shared utility methods */ // Helper method for extending one object with another. function __extend__(a,b) { for ( var i in b ) { var g = b.__lookupGetter__(i), s = b.__lookupSetter__(i); if ( g || s ) { if ( g ) a.__defineGetter__(i, g); if ( s ) a.__defineSetter__(i, s); } else a[i] = b[i]; } return a; }; // from ariel flesler http://flesler.blogspot.com/2008/11/fast-trim-function-for-javascript.html // this might be a good utility function to provide in the env.core // as in might be useful to the parser and other areas as well function trim( str ){ var start = -1, end = str.length; /*jsl:ignore*/ while( str.charCodeAt(--end) < 33 ); while( str.charCodeAt(++start) < 33 ); /*jsl:end*/ return str.slice( start, end + 1 ); }; //from jQuery function __setArray__( target, array ) { // Resetting the length to 0, then using the native Array push // is a super-fast way to populate an object with array-like properties target.length = 0; Array.prototype.push.apply( target, array ); }; $log("Defining NodeList"); /* * NodeList - DOM Level 2 */ $w.__defineGetter__('NodeList', function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); /** * @class DOMNodeList - provides the abstraction of an ordered collection of nodes * * @author Jon van Noort ([email protected]) * * @param ownerDocument : DOMDocument - the ownerDocument * @param parentNode : DOMNode - the node that the DOMNodeList is attached to (or null) */ var DOMNodeList = function(ownerDocument, parentNode) { //$log("\t\tcreating dom nodelist"); var nodes = []; this.length = 0; this.parentNode = parentNode; this.ownerDocument = ownerDocument; this._readonly = false; __setArray__(this, nodes); //$log("\t\tfinished creating dom nodelist"); }; __extend__(DOMNodeList.prototype, { item : function(index) { var ret = null; //$log("NodeList item("+index+") = " + this[index]); if ((index >= 0) && (index < this.length)) { // bounds check ret = this[index]; // return selected Node } return ret; // if the index is out of bounds, default value null is returned }, get xml() { var ret = ""; // create string containing the concatenation of the string values of each child for (var i=0; i < this.length; i++) { if(this[i].nodeType == DOMNode.TEXT_NODE && i>0 && this[i-1].nodeType == DOMNode.TEXT_NODE){ //add a single space between adjacent text nodes ret += " "+this[i].xml; }else{ ret += this[i].xml; } } return ret; }, toString: function(){ return "[ "+(this.length > 0?Array.prototype.join.apply(this, [", "]):"Empty NodeList")+" ]"; } }); /** * @method DOMNodeList._findItemIndex - find the item index of the node with the specified internal id * @author Jon van Noort ([email protected]) * @param id : int - unique internal id * @return : int */ var __findItemIndex__ = function (nodelist, id) { var ret = -1; // test that id is valid if (id > -1) { for (var i=0; i<nodelist.length; i++) { // compare id to each node's _id if (nodelist[i]._id == id) { // found it! ret = i; break; } } } return ret; // if node is not found, default value -1 is returned }; /** * @method DOMNodeList._insertBefore - insert the specified Node into the NodeList before the specified index * Used by DOMNode.insertBefore(). Note: DOMNode.insertBefore() is responsible for Node Pointer surgery * DOMNodeList._insertBefore() simply modifies the internal data structure (Array). * * @author Jon van Noort ([email protected]) * @param newChild : DOMNode - the Node to be inserted * @param refChildIndex : int - the array index to insert the Node before */ var __insertBefore__ = function(nodelist, newChild, refChildIndex) { if ((refChildIndex >= 0) && (refChildIndex < nodelist.length)) { // bounds check if (newChild.nodeType == DOMNode.DOCUMENT_FRAGMENT_NODE) { // node is a DocumentFragment // append the children of DocumentFragment Array.prototype.splice.apply(nodelist,[refChildIndex, 0].concat(newChild.childNodes)); } else { // append the newChild Array.prototype.splice.apply(nodelist,[refChildIndex, 0, newChild]); } } //$log("__insertBefore__ : length " + nodelist.length + " all -> " + document.all.length); }; /** * @method DOMNodeList._replaceChild - replace the specified Node in the NodeList at the specified index * Used by DOMNode.replaceChild(). Note: DOMNode.replaceChild() is responsible for Node Pointer surgery * DOMNodeList._replaceChild() simply modifies the internal data structure (Array). * * @author Jon van Noort ([email protected]) * @param newChild : DOMNode - the Node to be inserted * @param refChildIndex : int - the array index to hold the Node */ var __replaceChild__ = function(nodelist, newChild, refChildIndex) { var ret = null; if ((refChildIndex >= 0) && (refChildIndex < nodelist.length)) { // bounds check ret = nodelist[refChildIndex]; // preserve old child for return if (newChild.nodeType == DOMNode.DOCUMENT_FRAGMENT_NODE) { // node is a DocumentFragment // get array containing children prior to refChild Array.prototype.splice.apply(nodelist,[refChildIndex, 1].concat(newChild.childNodes)); } else { // simply replace node in array (links between Nodes are made at higher level) nodelist[refChildIndex] = newChild; } } //$log("__replaceChild__ : length " + nodelist.length + " all -> " + document.all.length); return ret; // return replaced node }; /** * @method DOMNodeList._removeChild - remove the specified Node in the NodeList at the specified index * Used by DOMNode.removeChild(). Note: DOMNode.removeChild() is responsible for Node Pointer surgery * DOMNodeList._replaceChild() simply modifies the internal data structure (Array). * * @author Jon van Noort ([email protected]) * @param refChildIndex : int - the array index holding the Node to be removed */ var __removeChild__ = function(nodelist, refChildIndex) { var ret = null; if (refChildIndex > -1) { // found it! ret = nodelist[refChildIndex]; // return removed node // rebuild array without removed child Array.prototype.splice.apply(nodelist,[refChildIndex, 1]); } //$log("__removeChild__ : length " + nodelist.length + " all -> " + document.all.length); return ret; // return removed node }; /** * @method DOMNodeList._appendChild - append the specified Node to the NodeList * Used by DOMNode.appendChild(). Note: DOMNode.appendChild() is responsible for Node Pointer surgery * DOMNodeList._appendChild() simply modifies the internal data structure (Array). * * @author Jon van Noort ([email protected]) * @param newChild : DOMNode - the Node to be inserted */ var __appendChild__ = function(nodelist, newChild) { if (newChild.nodeType == DOMNode.DOCUMENT_FRAGMENT_NODE) { // node is a DocumentFragment // append the children of DocumentFragment Array.prototype.push.apply(nodelist, newChild.childNodes); } else { // simply add node to array (links between Nodes are made at higher level) Array.prototype.push.apply(nodelist, [newChild]); } //$log("__appendChild__ : length " + nodelist.length + " all -> " + document.all.length); }; /** * @method DOMNodeList._cloneNodes - Returns a NodeList containing clones of the Nodes in this NodeList * * @author Jon van Noort ([email protected]) * @param deep : boolean - If true, recursively clone the subtree under each of the nodes; * if false, clone only the nodes themselves (and their attributes, if it is an Element). * @param parentNode : DOMNode - the new parent of the cloned NodeList * @return : DOMNodeList - NodeList containing clones of the Nodes in this NodeList */ var __cloneNodes__ = function(nodelist, deep, parentNode) { var cloneNodeList = new DOMNodeList(nodelist.ownerDocument, parentNode); // create list containing clones of each child for (var i=0; i < nodelist.length; i++) { __appendChild__(cloneNodeList, nodelist[i].cloneNode(deep)); } return cloneNodeList; }; /** * @class DOMNamedNodeMap - used to represent collections of nodes that can be accessed by name * typically a set of Element attributes * * @extends DOMNodeList - note W3C spec says that this is not the case, * but we need an item() method identicle to DOMNodeList's, so why not? * @author Jon van Noort ([email protected]) * @param ownerDocument : DOMDocument - the ownerDocument * @param parentNode : DOMNode - the node that the DOMNamedNodeMap is attached to (or null) */ var DOMNamedNodeMap = function(ownerDocument, parentNode) { //$log("\t\tcreating dom namednodemap"); this.DOMNodeList = DOMNodeList; this.DOMNodeList(ownerDocument, parentNode); __setArray__(this, []); }; DOMNamedNodeMap.prototype = new DOMNodeList; __extend__(DOMNamedNodeMap.prototype, { getNamedItem : function(name) { var ret = null; // test that Named Node exists var itemIndex = __findNamedItemIndex__(this, name); if (itemIndex > -1) { // found it! ret = this[itemIndex]; // return NamedNode } return ret; // if node is not found, default value null is returned }, setNamedItem : function(arg) { // test for exceptions if (this.ownerDocument.implementation.errorChecking) { // throw Exception if arg was not created by this Document if (this.ownerDocument != arg.ownerDocument) { throw(new DOMException(DOMException.WRONG_DOCUMENT_ERR)); } // throw Exception if DOMNamedNodeMap is readonly if (this._readonly || (this.parentNode && this.parentNode._readonly)) { throw(new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR)); } // throw Exception if arg is already an attribute of another Element object if (arg.ownerElement && (arg.ownerElement != this.parentNode)) { throw(new DOMException(DOMException.INUSE_ATTRIBUTE_ERR)); } } // get item index var itemIndex = __findNamedItemIndex__(this, arg.name); var ret = null; if (itemIndex > -1) { // found it! ret = this[itemIndex]; // use existing Attribute // throw Exception if DOMAttr is readonly if (this.ownerDocument.implementation.errorChecking && ret._readonly) { throw(new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR)); } else { this[itemIndex] = arg; // over-write existing NamedNode } } else { // add new NamedNode Array.prototype.push.apply(this, [arg]); } arg.ownerElement = this.parentNode; // update ownerElement return ret; // return old node or null }, removeNamedItem : function(name) { var ret = null; // test for exceptions // throw Exception if DOMNamedNodeMap is readonly if (this.ownerDocument.implementation.errorChecking && (this._readonly || (this.parentNode && this.parentNode._readonly))) { throw(new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR)); } // get item index var itemIndex = __findNamedItemIndex__(this, name); // throw Exception if there is no node named name in this map if (this.ownerDocument.implementation.errorChecking && (itemIndex < 0)) { throw(new DOMException(DOMException.NOT_FOUND_ERR)); } // get Node var oldNode = this[itemIndex]; // throw Exception if Node is readonly if (this.ownerDocument.implementation.errorChecking && oldNode._readonly) { throw(new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR)); } // return removed node return __removeChild__(this, itemIndex); }, getNamedItemNS : function(namespaceURI, localName) { var ret = null; // test that Named Node exists var itemIndex = __findNamedItemNSIndex__(this, namespaceURI, localName); if (itemIndex > -1) { // found it! ret = this[itemIndex]; // return NamedNode } return ret; // if node is not found, default value null is returned }, setNamedItemNS : function(arg) { // test for exceptions if (this.ownerDocument.implementation.errorChecking) { // throw Exception if DOMNamedNodeMap is readonly if (this._readonly || (this.parentNode && this.parentNode._readonly)) { throw(new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR)); } // throw Exception if arg was not created by this Document if (this.ownerDocument != arg.ownerDocument) { throw(new DOMException(DOMException.WRONG_DOCUMENT_ERR)); } // throw Exception if arg is already an attribute of another Element object if (arg.ownerElement && (arg.ownerElement != this.parentNode)) { throw(new DOMException(DOMException.INUSE_ATTRIBUTE_ERR)); } } // get item index var itemIndex = __findNamedItemNSIndex__(this, arg.namespaceURI, arg.localName); var ret = null; if (itemIndex > -1) { // found it! ret = this[itemIndex]; // use existing Attribute // throw Exception if DOMAttr is readonly if (this.ownerDocument.implementation.errorChecking && ret._readonly) { throw(new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR)); } else { this[itemIndex] = arg; // over-write existing NamedNode } }else { // add new NamedNode Array.prototype.push.apply(this, [arg]); } arg.ownerElement = this.parentNode; return ret; // return old node or null }, removeNamedItemNS : function(namespaceURI, localName) { var ret = null; // test for exceptions // throw Exception if DOMNamedNodeMap is readonly if (this.ownerDocument.implementation.errorChecking && (this._readonly || (this.parentNode && this.parentNode._readonly))) { throw(new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR)); } // get item index var itemIndex = __findNamedItemNSIndex__(this, namespaceURI, localName); // throw Exception if there is no matching node in this map if (this.ownerDocument.implementation.errorChecking && (itemIndex < 0)) { throw(new DOMException(DOMException.NOT_FOUND_ERR)); } // get Node var oldNode = this[itemIndex]; // throw Exception if Node is readonly if (this.ownerDocument.implementation.errorChecking && oldNode._readonly) { throw(new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR)); } return __removeChild__(this, itemIndex); // return removed node }, get xml() { var ret = ""; // create string containing concatenation of all (but last) Attribute string values (separated by spaces) for (var i=0; i < this.length -1; i++) { ret += this[i].xml +" "; } // add last Attribute to string (without trailing space) if (this.length > 0) { ret += this[this.length -1].xml; } return ret; } }); /** * @method DOMNamedNodeMap._findNamedItemIndex - find the item index of the node with the specified name * * @author Jon van Noort ([email protected]) * @param name : string - the name of the required node * @param isnsmap : if its a DOMNamespaceNodeMap * @return : int */ var __findNamedItemIndex__ = function(namednodemap, name, isnsmap) { var ret = -1; // loop through all nodes for (var i=0; i<namednodemap.length; i++) { // compare name to each node's nodeName if(isnsmap){ if (namednodemap[i].localName == localName) { // found it! ret = i; break; } }else{ if (namednodemap[i].name == name) { // found it! ret = i; break; } } } return ret; // if node is not found, default value -1 is returned }; /** * @method DOMNamedNodeMap._findNamedItemNSIndex - find the item index of the node with the specified namespaceURI and localName * * @author Jon van Noort ([email protected]) * @param namespaceURI : string - the namespace URI of the required node * @param localName : string - the local name of the required node * @return : int */ var __findNamedItemNSIndex__ = function(namednodemap, namespaceURI, localName) { var ret = -1; // test that localName is not null if (localName) { // loop through all nodes for (var i=0; i<namednodemap.length; i++) { // compare name to each node's namespaceURI and localName if ((namednodemap[i].namespaceURI == namespaceURI) && (namednodemap[i].localName == localName)) { ret = i; // found it! break; } } } return ret; // if node is not found, default value -1 is returned }; /** * @method DOMNamedNodeMap._hasAttribute - Returns true if specified node exists * * @author Jon van Noort ([email protected]) * @param name : string - the name of the required node * @return : boolean */ var __hasAttribute__ = function(namednodemap, name) { var ret = false; // test that Named Node exists var itemIndex = __findNamedItemIndex__(namednodemap, name); if (itemIndex > -1) { // found it! ret = true; // return true } return ret; // if node is not found, default value false is returned } /** * @method DOMNamedNodeMap._hasAttributeNS - Returns true if specified node exists * * @author Jon van Noort ([email protected]) * @param namespaceURI : string - the namespace URI of the required node * @param localName : string - the local name of the required node * @return : boolean */ var __hasAttributeNS__ = function(namednodemap, namespaceURI, localName) { var ret = false; // test that Named Node exists var itemIndex = __findNamedItemNSIndex__(namednodemap, namespaceURI, localName); if (itemIndex > -1) { // found it! ret = true; // return true } return ret; // if node is not found, default value false is returned } /** * @method DOMNamedNodeMap._cloneNodes - Returns a NamedNodeMap containing clones of the Nodes in this NamedNodeMap * * @author Jon van Noort ([email protected]) * @param parentNode : DOMNode - the new parent of the cloned NodeList * @param isnsmap : bool - is this a DOMNamespaceNodeMap * @return : DOMNamedNodeMap - NamedNodeMap containing clones of the Nodes in this DOMNamedNodeMap */ var __cloneNamedNodes__ = function(namednodemap, parentNode, isnsmap) { var cloneNamedNodeMap = isnsmap? new DOMNamespaceNodeMap(namednodemap.ownerDocument, parentNode): new DOMNamedNodeMap(namednodemap.ownerDocument, parentNode); // create list containing clones of all children for (var i=0; i < namednodemap.length; i++) { $log("cloning node in named node map :" + namednodemap[i]); __appendChild__(cloneNamedNodeMap, namednodemap[i].cloneNode(false)); } return cloneNamedNodeMap; }; /** * @class DOMNamespaceNodeMap - used to represent collections of namespace nodes that can be accessed by name * typically a set of Element attributes * * @extends DOMNamedNodeMap * * @author Jon van Noort ([email protected]) * * @param ownerDocument : DOMDocument - the ownerDocument * @param parentNode : DOMNode - the node that the DOMNamespaceNodeMap is attached to (or null) */ var DOMNamespaceNodeMap = function(ownerDocument, parentNode) { //$log("\t\t\tcreating dom namespacednodemap"); this.DOMNamedNodeMap = DOMNamedNodeMap; this.DOMNamedNodeMap(ownerDocument, parentNode); __setArray__(this, []); }; DOMNamespaceNodeMap.prototype = new DOMNamedNodeMap; __extend__(DOMNamespaceNodeMap.prototype, { get xml() { var ret = ""; // identify namespaces declared local to this Element (ie, not inherited) for (var ind = 0; ind < this.length; ind++) { // if namespace declaration does not exist in the containing node's, parentNode's namespaces var ns = null; try { var ns = this.parentNode.parentNode._namespaces.getNamedItem(this[ind].localName); } catch (e) { //breaking to prevent default namespace being inserted into return value break; } if (!(ns && (""+ ns.nodeValue == ""+ this[ind].nodeValue))) { // display the namespace declaration ret += this[ind].xml +" "; } } return ret; } }); $log("Defining Node"); /* * Node - DOM Level 2 */ $w.__defineGetter__('Node', function(){ return __extend__(function(){ throw new Error("Object cannot be created in this context"); } , { ELEMENT_NODE :1, ATTRIBUTE_NODE :2, TEXT_NODE :3, CDATA_SECTION_NODE: 4, PROCESSING_INSTRUCTION_NODE: 7, COMMENT_NODE: 8, DOCUMENT_NODE: 9, DOCUMENT_TYPE_NODE: 10, DOCUMENT_FRAGMENT_NODE: 11 }); }); /** * @class DOMNode - The Node interface is the primary datatype for the entire Document Object Model. * It represents a single node in the document tree. * @author Jon van Noort ([email protected]), David Joham ([email protected]) and Scott Severtson * @param ownerDocument : DOMDocument - The Document object associated with this node. */ var DOMNode = function(ownerDocument) { //$log("\tcreating dom node"); if (ownerDocument) { this._id = ownerDocument._genId(); // generate unique internal id } this.namespaceURI = ""; // The namespace URI of this node (Level 2) this.prefix = ""; // The namespace prefix of this node (Level 2) this.localName = ""; // The localName of this node (Level 2) this.nodeName = ""; // The name of this node this.nodeValue = ""; // The value of this node // The parent of this node. All nodes, except Document, DocumentFragment, and Attr may have a parent. // However, if a node has just been created and not yet added to the tree, or if it has been removed from the tree, this is null this.parentNode = null; // A NodeList that contains all children of this node. If there are no children, this is a NodeList containing no nodes. // The content of the returned NodeList is "live" in the sense that, for instance, changes to the children of the node object // that it was created from are immediately reflected in the nodes returned by the NodeList accessors; // it is not a static snapshot of the content of the node. This is true for every NodeList, including the ones returned by the getElementsByTagName method. this.childNodes = new DOMNodeList(ownerDocument, this); this.firstChild = null; // The first child of this node. If there is no such node, this is null this.lastChild = null; // The last child of this node. If there is no such node, this is null. this.previousSibling = null; // The node immediately preceding this node. If there is no such node, this is null. this.nextSibling = null; // The node immediately following this node. If there is no such node, this is null. this.attributes = new DOMNamedNodeMap(ownerDocument, this); // A NamedNodeMap containing the attributes of this node (if it is an Element) or null otherwise. this.ownerDocument = ownerDocument; // The Document object associated with this node this._namespaces = new DOMNamespaceNodeMap(ownerDocument, this); // The namespaces in scope for this node this._readonly = false; }; // nodeType constants DOMNode.ELEMENT_NODE = 1; DOMNode.ATTRIBUTE_NODE = 2; DOMNode.TEXT_NODE = 3; DOMNode.CDATA_SECTION_NODE = 4; DOMNode.ENTITY_REFERENCE_NODE = 5; DOMNode.ENTITY_NODE = 6; DOMNode.PROCESSING_INSTRUCTION_NODE = 7; DOMNode.COMMENT_NODE = 8; DOMNode.DOCUMENT_NODE = 9; DOMNode.DOCUMENT_TYPE_NODE = 10; DOMNode.DOCUMENT_FRAGMENT_NODE = 11; DOMNode.NOTATION_NODE = 12; DOMNode.NAMESPACE_NODE = 13; __extend__(DOMNode.prototype, { hasAttributes : function() { if (this.attributes.length == 0) { return false; }else{ return true; } }, insertBefore : function(newChild, refChild) { var prevNode; // test for exceptions if (this.ownerDocument.implementation.errorChecking) { // throw Exception if DOMNode is readonly if (this._readonly) { throw(new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR)); } // throw Exception if newChild was not created by this Document if (this.ownerDocument != newChild.ownerDocument) { throw(new DOMException(DOMException.WRONG_DOCUMENT_ERR)); } // throw Exception if the node is an ancestor if (__isAncestor__(this, newChild)) { throw(new DOMException(DOMException.HIERARCHY_REQUEST_ERR)); } } if (refChild) { // if refChild is specified, insert before it // find index of refChild var itemIndex = __findItemIndex__(this.childNodes, refChild._id); // throw Exception if there is no child node with this id if (this.ownerDocument.implementation.errorChecking && (itemIndex < 0)) { throw(new DOMException(DOMException.NOT_FOUND_ERR)); } // if the newChild is already in the tree, var newChildParent = newChild.parentNode; if (newChildParent) { // remove it newChildParent.removeChild(newChild); } // insert newChild into childNodes __insertBefore__(this.childNodes, newChild, __findItemIndex__(this.childNodes, refChild._id)); // do node pointer surgery prevNode = refChild.previousSibling; // handle DocumentFragment if (newChild.nodeType == DOMNode.DOCUMENT_FRAGMENT_NODE) { if (newChild.childNodes.length > 0) { // set the parentNode of DocumentFragment's children for (var ind = 0; ind < newChild.childNodes.length; ind++) { newChild.childNodes[ind].parentNode = this; } // link refChild to last child of DocumentFragment refChild.previousSibling = newChild.childNodes[newChild.childNodes.length-1]; } }else { newChild.parentNode = this; // set the parentNode of the newChild refChild.previousSibling = newChild; // link refChild to newChild } }else { // otherwise, append to end prevNode = this.lastChild; this.appendChild(newChild); } if (newChild.nodeType == DOMNode.DOCUMENT_FRAGMENT_NODE) { // do node pointer surgery for DocumentFragment if (newChild.childNodes.length > 0) { if (prevNode) { prevNode.nextSibling = newChild.childNodes[0]; }else { // this is the first child in the list this.firstChild = newChild.childNodes[0]; } newChild.childNodes[0].previousSibling = prevNode; newChild.childNodes[newChild.childNodes.length-1].nextSibling = refChild; } }else { // do node pointer surgery for newChild if (prevNode) { prevNode.nextSibling = newChild; }else { // this is the first child in the list this.firstChild = newChild; } newChild.previousSibling = prevNode; newChild.nextSibling = refChild; } return newChild; }, replaceChild : function(newChild, oldChild) { var ret = null; // test for exceptions if (this.ownerDocument.implementation.errorChecking) { // throw Exception if DOMNode is readonly if (this._readonly) { throw(new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR)); } // throw Exception if newChild was not created by this Document if (this.ownerDocument != newChild.ownerDocument) { throw(new DOMException(DOMException.WRONG_DOCUMENT_ERR)); } // throw Exception if the node is an ancestor if (__isAncestor__(this, newChild)) { throw(new DOMException(DOMException.HIERARCHY_REQUEST_ERR)); } } // get index of oldChild var index = __findItemIndex__(this.childNodes, oldChild._id); // throw Exception if there is no child node with this id if (this.ownerDocument.implementation.errorChecking && (index < 0)) { throw(new DOMException(DOMException.NOT_FOUND_ERR)); } // if the newChild is already in the tree, var newChildParent = newChild.parentNode; if (newChildParent) { // remove it newChildParent.removeChild(newChild); } // add newChild to childNodes ret = __replaceChild__(this.childNodes,newChild, index); if (newChild.nodeType == DOMNode.DOCUMENT_FRAGMENT_NODE) { // do node pointer surgery for Document Fragment if (newChild.childNodes.length > 0) { for (var ind = 0; ind < newChild.childNodes.length; ind++) { newChild.childNodes[ind].parentNode = this; } if (oldChild.previousSibling) { oldChild.previousSibling.nextSibling = newChild.childNodes[0]; } else { this.firstChild = newChild.childNodes[0]; } if (oldChild.nextSibling) { oldChild.nextSibling.previousSibling = newChild; } else { this.lastChild = newChild.childNodes[newChild.childNodes.length-1]; } newChild.childNodes[0].previousSibling = oldChild.previousSibling; newChild.childNodes[newChild.childNodes.length-1].nextSibling = oldChild.nextSibling; } } else { // do node pointer surgery for newChild newChild.parentNode = this; if (oldChild.previousSibling) { oldChild.previousSibling.nextSibling = newChild; }else{ this.firstChild = newChild; } if (oldChild.nextSibling) { oldChild.nextSibling.previousSibling = newChild; }else{ this.lastChild = newChild; } newChild.previousSibling = oldChild.previousSibling; newChild.nextSibling = oldChild.nextSibling; } //this.removeChild(oldChild); return ret; }, removeChild : function(oldChild) { // throw Exception if DOMNamedNodeMap is readonly if (this.ownerDocument.implementation.errorChecking && (this._readonly || oldChild._readonly)) { throw(new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR)); } // get index of oldChild var itemIndex = __findItemIndex__(this.childNodes, oldChild._id); // throw Exception if there is no child node with this id if (this.ownerDocument.implementation.errorChecking && (itemIndex < 0)) { throw(new DOMException(DOMException.NOT_FOUND_ERR)); } // remove oldChild from childNodes __removeChild__(this.childNodes, itemIndex); // do node pointer surgery oldChild.parentNode = null; if (oldChild.previousSibling) { oldChild.previousSibling.nextSibling = oldChild.nextSibling; }else { this.firstChild = oldChild.nextSibling; } if (oldChild.nextSibling) { oldChild.nextSibling.previousSibling = oldChild.previousSibling; }else { this.lastChild = oldChild.previousSibling; } oldChild.previousSibling = null; oldChild.nextSibling = null; /*if(oldChild.ownerDocument == document){ $log("removeChild : all -> " + document.all.length); }*/ return oldChild; }, appendChild : function(newChild) { // test for exceptions if (this.ownerDocument.implementation.errorChecking) { // throw Exception if Node is readonly if (this._readonly) { throw(new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR)); } // throw Exception if arg was not created by this Document if (this.ownerDocument != newChild.ownerDocument) { throw(new DOMException(DOMException.WRONG_DOCUMENT_ERR)); } // throw Exception if the node is an ancestor if (__isAncestor__(this, newChild)) { throw(new DOMException(DOMException.HIERARCHY_REQUEST_ERR)); } } // if the newChild is already in the tree, var newChildParent = newChild.parentNode; if (newChildParent) { // remove it newChildParent.removeChild(newChild); } // add newChild to childNodes __appendChild__(this.childNodes, newChild); if (newChild.nodeType == DOMNode.DOCUMENT_FRAGMENT_NODE) { // do node pointer surgery for DocumentFragment if (newChild.childNodes.length > 0) { for (var ind = 0; ind < newChild.childNodes.length; ind++) { newChild.childNodes[ind].parentNode = this; } if (this.lastChild) { this.lastChild.nextSibling = newChild.childNodes[0]; newChild.childNodes[0].previousSibling = this.lastChild; this.lastChild = newChild.childNodes[newChild.childNodes.length-1]; } else { this.lastChild = newChild.childNodes[newChild.childNodes.length-1]; this.firstChild = newChild.childNodes[0]; } } } else { // do node pointer surgery for newChild newChild.parentNode = this; if (this.lastChild) { this.lastChild.nextSibling = newChild; newChild.previousSibling = this.lastChild; this.lastChild = newChild; } else { this.lastChild = newChild; this.firstChild = newChild; } } return newChild; }, hasChildNodes : function() { return (this.childNodes.length > 0); }, cloneNode: function(deep) { // use importNode to clone this Node //do not throw any exceptions //$log("cloning node"); try { return this.ownerDocument.importNode(this, deep); } catch (e) { //there shouldn't be any exceptions, but if there are, return null return null; } }, normalize : function() { var inode; var nodesToRemove = new DOMNodeList(); if (this.nodeType == DOMNode.ELEMENT_NODE || this.nodeType == DOMNode.DOCUMENT_NODE) { var adjacentTextNode = null; // loop through all childNodes for(var i = 0; i < this.childNodes.length; i++) { inode = this.childNodes.item(i); if (inode.nodeType == DOMNode.TEXT_NODE) { // this node is a text node if (inode.length < 1) { // this text node is empty __appendChild__(nodesToRemove, inode); // add this node to the list of nodes to be remove }else { if (adjacentTextNode) { // if previous node was also text adjacentTextNode.appendData(inode.data); // merge the data in adjacent text nodes __appendChild__(nodesToRemove, inode); // add this node to the list of nodes to be removed }else { adjacentTextNode = inode; // remember this node for next cycle } } } else { adjacentTextNode = null; // (soon to be) previous node is not a text node inode.normalize(); // normalise non Text childNodes } } // remove redundant Text Nodes for(var i = 0; i < nodesToRemove.length; i++) { inode = nodesToRemove.item(i); inode.parentNode.removeChild(inode); } } }, isSupported : function(feature, version) { // use Implementation.hasFeature to determin if this feature is supported return this.ownerDocument.implementation.hasFeature(feature, version); }, getElementsByTagName : function(tagname) { // delegate to _getElementsByTagNameRecursive //$log("getElementsByTagName("+tagname+")"); return __getElementsByTagNameRecursive__(this, tagname, new DOMNodeList(this.ownerDocument)); }, getElementsByTagNameNS : function(namespaceURI, localName) { // delegate to _getElementsByTagNameNSRecursive return __getElementsByTagNameNSRecursive__(this, namespaceURI, localName, new DOMNodeList(this.ownerDocument)); }, importNode : function(importedNode, deep) { var importNode; //$log("importing node " + importedNode + "(?deep = "+deep+")"); //there is no need to perform namespace checks since everything has already gone through them //in order to have gotten into the DOM in the first place. The following line //turns namespace checking off in ._isValidNamespace this.ownerDocument._performingImportNodeOperation = true; //try { if (importedNode.nodeType == DOMNode.ELEMENT_NODE) { if (!this.ownerDocument.implementation.namespaceAware) { // create a local Element (with the name of the importedNode) importNode = this.ownerDocument.createElement(importedNode.tagName); // create attributes matching those of the importedNode for(var i = 0; i < importedNode.attributes.length; i++) { importNode.setAttribute(importedNode.attributes.item(i).name, importedNode.attributes.item(i).value); } }else { // create a local Element (with the name & namespaceURI of the importedNode) importNode = this.ownerDocument.createElementNS(importedNode.namespaceURI, importedNode.nodeName); // create attributes matching those of the importedNode for(var i = 0; i < importedNode.attributes.length; i++) { importNode.setAttributeNS(importedNode.attributes.item(i).namespaceURI, importedNode.attributes.item(i).name, importedNode.attributes.item(i).value); } // create namespace definitions matching those of the importedNode for(var i = 0; i < importedNode._namespaces.length; i++) { importNode._namespaces[i] = this.ownerDocument.createNamespace(importedNode._namespaces.item(i).localName); importNode._namespaces[i].value = importedNode._namespaces.item(i).value; } } } else if (importedNode.nodeType == DOMNode.ATTRIBUTE_NODE) { if (!this.ownerDocument.implementation.namespaceAware) { // create a local Attribute (with the name of the importedAttribute) importNode = this.ownerDocument.createAttribute(importedNode.name); } else { // create a local Attribute (with the name & namespaceURI of the importedAttribute) importNode = this.ownerDocument.createAttributeNS(importedNode.namespaceURI, importedNode.nodeName); // create namespace definitions matching those of the importedAttribute for(var i = 0; i < importedNode._namespaces.length; i++) { importNode._namespaces[i] = this.ownerDocument.createNamespace(importedNode._namespaces.item(i).localName); importNode._namespaces[i].value = importedNode._namespaces.item(i).value; } } // set the value of the local Attribute to match that of the importedAttribute importNode.value = importedNode.value; } else if (importedNode.nodeType == DOMNode.DOCUMENT_FRAGMENT) { // create a local DocumentFragment importNode = this.ownerDocument.createDocumentFragment(); } else if (importedNode.nodeType == DOMNode.NAMESPACE_NODE) { // create a local NamespaceNode (with the same name & value as the importedNode) importNode = this.ownerDocument.createNamespace(importedNode.nodeName); importNode.value = importedNode.value; } else if (importedNode.nodeType == DOMNode.TEXT_NODE) { // create a local TextNode (with the same data as the importedNode) importNode = this.ownerDocument.createTextNode(importedNode.data); } else if (importedNode.nodeType == DOMNode.CDATA_SECTION_NODE) { // create a local CDATANode (with the same data as the importedNode) importNode = this.ownerDocument.createCDATASection(importedNode.data); } else if (importedNode.nodeType == DOMNode.PROCESSING_INSTRUCTION_NODE) { // create a local ProcessingInstruction (with the same target & data as the importedNode) importNode = this.ownerDocument.createProcessingInstruction(importedNode.target, importedNode.data); } else if (importedNode.nodeType == DOMNode.COMMENT_NODE) { // create a local Comment (with the same data as the importedNode) importNode = this.ownerDocument.createComment(importedNode.data); } else { // throw Exception if nodeType is not supported throw(new DOMException(DOMException.NOT_SUPPORTED_ERR)); } if (deep) { // recurse childNodes for(var i = 0; i < importedNode.childNodes.length; i++) { importNode.appendChild(this.ownerDocument.importNode(importedNode.childNodes.item(i), true)); } } //reset _performingImportNodeOperation this.ownerDocument._performingImportNodeOperation = false; return importNode; /*} catch (eAny) { //reset _performingImportNodeOperation this.ownerDocument._performingImportNodeOperation = false; //re-throw the exception throw eAny; }//djotemp*/ }, contains : function(node){ while(node && node != this ){ node = node.parentNode; } return !!node; }, compareDocumentPosition : function(b){ var a = this; var number = (a != b && a.contains(b) && 16) + (a != b && b.contains(a) && 8); //find position of both var all = document.getElementsByTagName("*"); var my_location = 0, node_location = 0; for(var i=0; i < all.length; i++){ if(all[i] == a) my_location = i; if(all[i] == b) node_location = i; if(my_location && node_location) break; } number += (my_location < node_location && 4) number += (my_location > node_location && 2) return number; } }); /** * @method DOMNode._getElementsByTagNameRecursive - implements getElementsByTagName() * @param elem : DOMElement - The element which are checking and then recursing into * @param tagname : string - The name of the tag to match on. The special value "*" matches all tags * @param nodeList : DOMNodeList - The accumulating list of matching nodes * * @return : DOMNodeList */ var __getElementsByTagNameRecursive__ = function (elem, tagname, nodeList) { //$log("__getElementsByTagNameRecursive__("+elem._id+")"); if (elem.nodeType == DOMNode.ELEMENT_NODE || elem.nodeType == DOMNode.DOCUMENT_NODE) { if((elem.nodeName.toUpperCase() == tagname.toUpperCase()) || (tagname == "*")) { //$log("found node by name " + tagname); __appendChild__(nodeList, elem); // add matching node to nodeList } // recurse childNodes for(var i = 0; i < elem.childNodes.length; i++) { nodeList = __getElementsByTagNameRecursive__(elem.childNodes.item(i), tagname, nodeList); } } return nodeList; }; /** * @method DOMNode._getElementsByTagNameNSRecursive - implements getElementsByTagName() * * @param elem : DOMElement - The element which are checking and then recursing into * @param namespaceURI : string - the namespace URI of the required node * @param localName : string - the local name of the required node * @param nodeList : DOMNodeList - The accumulating list of matching nodes * * @return : DOMNodeList */ var __getElementsByTagNameNSRecursive__ = function(elem, namespaceURI, localName, nodeList) { if (elem.nodeType == DOMNode.ELEMENT_NODE || elem.nodeType == DOMNode.DOCUMENT_NODE) { if (((elem.namespaceURI == namespaceURI) || (namespaceURI == "*")) && ((elem.localName == localName) || (localName == "*"))) { __appendChild__(nodeList, elem); // add matching node to nodeList } // recurse childNodes for(var i = 0; i < elem.childNodes.length; i++) { nodeList = __getElementsByTagNameNSRecursive__(elem.childNodes.item(i), namespaceURI, localName, nodeList); } } return nodeList; }; /** * @method DOMNode._isAncestor - returns true if node is ancestor of target * @param target : DOMNode - The node we are using as context * @param node : DOMNode - The candidate ancestor node * @return : boolean */ var __isAncestor__ = function(target, node) { // if this node matches, return true, // otherwise recurse up (if there is a parentNode) return ((target == node) || ((target.parentNode) && (__isAncestor__(target.parentNode, node)))); } /** * @class DOMNamespace - The Namespace interface represents an namespace in an Element object * * @extends DOMNode * @author Jon van Noort ([email protected]) * @param ownerDocument : DOMDocument - The Document object associated with this node. */ var DOMNamespace = function(ownerDocument) { this.DOMNode = DOMNode; this.DOMNode(ownerDocument); this.name = ""; // the name of this attribute // If this attribute was explicitly given a value in the original document, this is true; otherwise, it is false. // Note that the implementation is in charge of this attribute, not the user. // If the user changes the value of the attribute (even if it ends up having the same value as the default value) // then the specified flag is automatically flipped to true this.specified = false; }; DOMNamespace.prototype = new DOMNode; __extend__(DOMNamespace.prototype, { get value(){ // the value of the attribute is returned as a string return this.nodeValue; }, set value(value){ this.nodeValue = String(value); }, get nodeType(){ return DOMNode.NAMESPACE_NODE; }, get xml(){ var ret = ""; // serialize Namespace Declaration if (this.nodeName != "") { ret += this.nodeName +"=\""+ __escapeXML__(this.nodeValue) +"\""; } else { // handle default namespace ret += "xmlns=\""+ __escapeXML__(this.nodeValue) +"\""; } return ret; }, toString: function(){ return "Namespace #" + this.id; } }); $debug("Defining CharacterData"); /* * CharacterData - DOM Level 2 */ $w.__defineGetter__("CharacterData", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); /** * @class DOMCharacterData - parent abstract class for DOMText and DOMComment * @extends DOMNode * @author Jon van Noort ([email protected]) * @param ownerDocument : DOMDocument - The Document object associated with this node. */ var DOMCharacterData = function(ownerDocument) { this.DOMNode = DOMNode; this.DOMNode(ownerDocument); }; DOMCharacterData.prototype = new DOMNode; __extend__(DOMCharacterData.prototype,{ get data(){ return String(this.nodeValue); }, set data(data){ this.nodeValue = String(data); }, get length(){return this.nodeValue.length;}, appendData: function(arg){ // throw Exception if DOMCharacterData is readonly if (this.ownerDocument.implementation.errorChecking && this._readonly) { throw(new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR)); } // append data this.data = "" + this.data + arg; }, deleteData: function(offset, count){ // throw Exception if DOMCharacterData is readonly if (this.ownerDocument.implementation.errorChecking && this._readonly) { throw(new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR)); } if (this.data) { // throw Exception if offset is negative or greater than the data length, if (this.ownerDocument.implementation.errorChecking && ((offset < 0) || (offset > this.data.length) || (count < 0))) { throw(new DOMException(DOMException.INDEX_SIZE_ERR)); } // delete data if(!count || (offset + count) > this.data.length) { this.data = this.data.substring(0, offset); }else { this.data = this.data.substring(0, offset).concat(this.data.substring(offset + count)); } } }, insertData: function(offset, arg){ // throw Exception if DOMCharacterData is readonly if(this.ownerDocument.implementation.errorChecking && this._readonly){ throw(new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR)); } if(this.data){ // throw Exception if offset is negative or greater than the data length, if (this.ownerDocument.implementation.errorChecking && ((offset < 0) || (offset > this.data.length))) { throw(new DOMException(DOMException.INDEX_SIZE_ERR)); } // insert data this.data = this.data.substring(0, offset).concat(arg, this.data.substring(offset)); }else { // throw Exception if offset is negative or greater than the data length, if (this.ownerDocument.implementation.errorChecking && (offset != 0)) { throw(new DOMException(DOMException.INDEX_SIZE_ERR)); } // set data this.data = arg; } }, replaceData: function(offset, count, arg){ // throw Exception if DOMCharacterData is readonly if (this.ownerDocument.implementation.errorChecking && this._readonly) { throw(new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR)); } if (this.data) { // throw Exception if offset is negative or greater than the data length, if (this.ownerDocument.implementation.errorChecking && ((offset < 0) || (offset > this.data.length) || (count < 0))) { throw(new DOMException(DOMException.INDEX_SIZE_ERR)); } // replace data this.data = this.data.substring(0, offset).concat(arg, this.data.substring(offset + count)); }else { // set data this.data = arg; } }, substringData: function(offset, count){ var ret = null; if (this.data) { // throw Exception if offset is negative or greater than the data length, // or the count is negative if (this.ownerDocument.implementation.errorChecking && ((offset < 0) || (offset > this.data.length) || (count < 0))) { throw(new DOMException(DOMException.INDEX_SIZE_ERR)); } // if count is not specified if (!count) { ret = this.data.substring(offset); // default to 'end of string' }else{ ret = this.data.substring(offset, offset + count); } } return ret; } }); $log("Defining Text"); /* * Text - DOM Level 2 */ $w.__defineGetter__("Text", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); /** * @class DOMText - The Text interface represents the textual content (termed character data in XML) of an Element or Attr. * If there is no markup inside an element's content, the text is contained in a single object implementing the Text interface * that is the only child of the element. If there is markup, it is parsed into a list of elements and Text nodes that form the * list of children of the element. * @extends DOMCharacterData * @author Jon van Noort ([email protected]) and David Joham ([email protected]) * @param ownerDocument : DOMDocument - The Document object associated with this node. */ DOMText = function(ownerDocument) { this.DOMCharacterData = DOMCharacterData; this.DOMCharacterData(ownerDocument); this.nodeName = "#text"; }; DOMText.prototype = new DOMCharacterData; __extend__(DOMText.prototype,{ //Breaks this Text node into two Text nodes at the specified offset, // keeping both in the tree as siblings. This node then only contains all the content up to the offset point. // And a new Text node, which is inserted as the next sibling of this node, contains all the content at and after the offset point. splitText : function(offset) { var data, inode; // test for exceptions if (this.ownerDocument.implementation.errorChecking) { // throw Exception if Node is readonly if (this._readonly) { throw(new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR)); } // throw Exception if offset is negative or greater than the data length, if ((offset < 0) || (offset > this.data.length)) { throw(new DOMException(DOMException.INDEX_SIZE_ERR)); } } if (this.parentNode) { // get remaining string (after offset) data = this.substringData(offset); // create new TextNode with remaining string inode = this.ownerDocument.createTextNode(data); // attach new TextNode if (this.nextSibling) { this.parentNode.insertBefore(inode, this.nextSibling); } else { this.parentNode.appendChild(inode); } // remove remaining string from original TextNode this.deleteData(offset); } return inode; }, get nodeType(){ return DOMNode.TEXT_NODE; }, get xml(){ return __escapeXML__(""+ this.nodeValue); }, toString: function(){ return "Text #" + this._id; } }); $log("Defining CDATASection"); /* * CDATASection - DOM Level 2 */ $w.__defineGetter__("CDATASection", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); /** * @class DOMCDATASection - CDATA sections are used to escape blocks of text containing characters that would otherwise be regarded as markup. * The only delimiter that is recognized in a CDATA section is the "\]\]\>" string that ends the CDATA section * @extends DOMCharacterData * @author Jon van Noort ([email protected]) and David Joham ([email protected]) * @param ownerDocument : DOMDocument - The Document object associated with this node. */ var DOMCDATASection = function(ownerDocument) { this.DOMText = DOMText; this.DOMText(ownerDocument); this.nodeName = "#cdata-section"; }; DOMCDATASection.prototype = new DOMText; __extend__(DOMCDATASection.prototype,{ get nodeType(){ return DOMNode.CDATA_SECTION_NODE; }, get xml(){ return "<![CDATA[" + this.nodeValue + "]]>"; }, toString : function(){ return "CDATA #"+this._id; } });$log("Defining Comment"); /* * Comment - DOM Level 2 */ $w.__defineGetter__("Comment", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); /** * @class DOMComment - This represents the content of a comment, i.e., all the characters between the starting '<!--' and ending '-->' * @extends DOMCharacterData * @author Jon van Noort ([email protected]) * @param ownerDocument : DOMDocument - The Document object associated with this node. */ var DOMComment = function(ownerDocument) { this.DOMCharacterData = DOMCharacterData; this.DOMCharacterData(ownerDocument); this.nodeName = "#comment"; }; DOMComment.prototype = new DOMCharacterData; __extend__(DOMComment.prototype, { get nodeType(){ return DOMNode.COMMENT_NODE; }, get xml(){ return "<!-- " + this.nodeValue + " -->"; }, toString : function(){ return "Comment #"+this._id; } }); $log("Defining DocumentType"); ;/* * DocumentType - DOM Level 2 */ $w.__defineGetter__('DocumentType', function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); var DOMDocumentType = function() { $error("DOMDocumentType.constructor(): Not Implemented" ); };$log("Defining Attr"); /* * Attr - DOM Level 2 */ $w.__defineGetter__("Attr", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); /** * @class DOMAttr - The Attr interface represents an attribute in an Element object * @extends DOMNode * @author Jon van Noort ([email protected]) * @param ownerDocument : DOMDocument - The Document object associated with this node. */ var DOMAttr = function(ownerDocument) { //$log("\tcreating dom attribute"); this.DOMNode = DOMNode; this.DOMNode(ownerDocument); this.specified = false; this.ownerElement = null; // set when Attr is added to NamedNodeMap //$log("\tfincished creating dom attribute " + this); }; DOMAttr.prototype = new DOMNode; __extend__(DOMAttr.prototype, { // the name of this attribute get name(){ return this.nodeName; }, set name(name){ this.nodeName = name; }, // the value of the attribute is returned as a string get value(){ return this.nodeValue; }, set value(value){ // throw Exception if Attribute is readonly if (this.ownerDocument.implementation.errorChecking && this._readonly) { throw(new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR)); } // delegate to node this.specified = (this.value.length > 0); this.nodeValue = value; }, get nodeType(){ return DOMNode.ATTRIBUTE_NODE; }, get xml(){ return this.nodeName + "='" + this.nodeValue + "' "; }, toString : function(){ return "Attr #" + this._id + " " + this.name; } }); $log("Defining Element"); /* * Element - DOM Level 2 */ $w.__defineGetter__("Element", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); /** * @class DOMElement - By far the vast majority of objects (apart from text) that authors encounter * when traversing a document are Element nodes. * @extends DOMNode * @author Jon van Noort ([email protected]) and David Joham ([email protected]) * @param ownerDocument : DOMDocument - The Document object associated with this node. */ var DOMElement = function(ownerDocument) { //$log("\tcreating dom element"); this.DOMNode = DOMNode; this.DOMNode(ownerDocument); this.id = ""; // the ID of the element //$log("\nfinished creating dom element " + this); }; DOMElement.prototype = new DOMNode; __extend__(DOMElement.prototype, { // The name of the element. get tagName(){ return this.nodeName; }, set tagName(name){ this.nodeName = name; }, addEventListener : function(){ window.addEventListener.apply(this, arguments) }, removeEventListener : function(){ window.removeEventListener.apply(this, arguments) }, dispatchEvent : function(){ window.dispatchEvent.apply(this, arguments) }, getAttribute: function(name) { var ret = null; // if attribute exists, use it var attr = this.attributes.getNamedItem(name); if (attr) { ret = attr.value; } return ret; // if Attribute exists, return its value, otherwise, return "" }, setAttribute : function (name, value) { // if attribute exists, use it var attr = this.attributes.getNamedItem(name); var value = new String(value); //I had to add this check becuase as the script initializes //the id may be set in the constructor, and the html element //overrides the id property with a getter/setter. if(this.ownerDocument){ if (!attr) { attr = this.ownerDocument.createAttribute(name); // otherwise create it } // test for exceptions if (this.ownerDocument.implementation.errorChecking) { // throw Exception if Attribute is readonly if (attr._readonly) { throw(new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR)); } // throw Exception if the value string contains an illegal character if (!__isValidString__(value)) { throw(new DOMException(DOMException.INVALID_CHARACTER_ERR)); } } if (__isIdDeclaration__(name)) { this.id = value; // cache ID for getElementById() } // assign values to properties (and aliases) attr.value = value; // update .specified if (value.length > 0) { attr.specified = true; }else { attr.specified = false; } // add/replace Attribute in NamedNodeMap this.attributes.setNamedItem(attr); } }, removeAttribute : function removeAttribute(name) { // delegate to DOMNamedNodeMap.removeNamedItem return this.attributes.removeNamedItem(name); }, getAttributeNode : function getAttributeNode(name) { // delegate to DOMNamedNodeMap.getNamedItem return this.attributes.getNamedItem(name); }, setAttributeNode: function(newAttr) { // if this Attribute is an ID if (__isIdDeclaration__(newAttr.name)) { this.id = newAttr.value; // cache ID for getElementById() } // delegate to DOMNamedNodeMap.setNamedItem return this.attributes.setNamedItem(newAttr); }, removeAttributeNode: function(oldAttr) { // throw Exception if Attribute is readonly if (this.ownerDocument.implementation.errorChecking && oldAttr._readonly) { throw(new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR)); } // get item index var itemIndex = this.attributes._findItemIndex(oldAttr._id); // throw Exception if node does not exist in this map if (this.ownerDocument.implementation.errorChecking && (itemIndex < 0)) { throw(new DOMException(DOMException.NOT_FOUND_ERR)); } return this.attributes._removeChild(itemIndex); }, getAttributeNS : function(namespaceURI, localName) { var ret = ""; // delegate to DOMNAmedNodeMap.getNamedItemNS var attr = this.attributes.getNamedItemNS(namespaceURI, localName); if (attr) { ret = attr.value; } return ret; // if Attribute exists, return its value, otherwise return "" }, setAttributeNS : function(namespaceURI, qualifiedName, value) { // call DOMNamedNodeMap.getNamedItem var attr = this.attributes.getNamedItem(namespaceURI, qualifiedName); if (!attr) { // if Attribute exists, use it // otherwise create it attr = this.ownerDocument.createAttributeNS(namespaceURI, qualifiedName); } var value = String(value); // test for exceptions if (this.ownerDocument.implementation.errorChecking) { // throw Exception if Attribute is readonly if (attr._readonly) { throw(new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR)); } // throw Exception if the Namespace is invalid if (!__isValidNamespace__(namespaceURI, qualifiedName)) { throw(new DOMException(DOMException.NAMESPACE_ERR)); } // throw Exception if the value string contains an illegal character if (!__isValidString__(value)) { throw(new DOMException(DOMException.INVALID_CHARACTER_ERR)); } } // if this Attribute is an ID if (__isIdDeclaration__(name)) { this.id = value; // cache ID for getElementById() } // assign values to properties (and aliases) attr.value = value; attr.nodeValue = value; // update .specified if (value.length > 0) { attr.specified = true; }else { attr.specified = false; } // delegate to DOMNamedNodeMap.setNamedItem this.attributes.setNamedItemNS(attr); }, removeAttributeNS : function(namespaceURI, localName) { // delegate to DOMNamedNodeMap.removeNamedItemNS return this.attributes.removeNamedItemNS(namespaceURI, localName); }, getAttributeNodeNS : function(namespaceURI, localName) { // delegate to DOMNamedNodeMap.getNamedItemNS return this.attributes.getNamedItemNS(namespaceURI, localName); }, setAttributeNodeNS : function(newAttr) { // if this Attribute is an ID if ((newAttr.prefix == "") && __isIdDeclaration__(newAttr.name)) { this.id = String(newAttr.value); // cache ID for getElementById() } // delegate to DOMNamedNodeMap.setNamedItemNS return this.attributes.setNamedItemNS(newAttr); }, hasAttribute : function(name) { // delegate to DOMNamedNodeMap._hasAttribute return __hasAttribute__(this.attributes,name); }, hasAttributeNS : function(namespaceURI, localName) { // delegate to DOMNamedNodeMap._hasAttributeNS return __hasAttributeNS__(this.attributes, namespaceURI, localName); }, get nodeType(){ return DOMNode.ELEMENT_NODE; }, get xml() { var ret = ""; // serialize namespace declarations var ns = this._namespaces.xml; if (ns.length > 0) ns = " "+ ns; // serialize Attribute declarations var attrs = this.attributes.xml; if (attrs.length > 0) attrs = " "+ attrs; // serialize this Element ret += "<" + this.nodeName.toLowerCase() + ns + attrs +">"; ret += this.childNodes.xml; ret += "</" + this.nodeName.toLowerCase()+">"; return ret; }, toString : function(){ return "Element #"+this._id + " "+ this.tagName + (this.id?" => "+this.id:''); } }); /** * @class DOMException - raised when an operation is impossible to perform * @author Jon van Noort ([email protected]) * @param code : int - the exception code (one of the DOMException constants) */ var DOMException = function(code) { this.code = code; }; // DOMException constants // Introduced in DOM Level 1: DOMException.INDEX_SIZE_ERR = 1; DOMException.DOMSTRING_SIZE_ERR = 2; DOMException.HIERARCHY_REQUEST_ERR = 3; DOMException.WRONG_DOCUMENT_ERR = 4; DOMException.INVALID_CHARACTER_ERR = 5; DOMException.NO_DATA_ALLOWED_ERR = 6; DOMException.NO_MODIFICATION_ALLOWED_ERR = 7; DOMException.NOT_FOUND_ERR = 8; DOMException.NOT_SUPPORTED_ERR = 9; DOMException.INUSE_ATTRIBUTE_ERR = 10; // Introduced in DOM Level 2: DOMException.INVALID_STATE_ERR = 11; DOMException.SYNTAX_ERR = 12; DOMException.INVALID_MODIFICATION_ERR = 13; DOMException.NAMESPACE_ERR = 14; DOMException.INVALID_ACCESS_ERR = 15; $log("Defining DocumentFragment"); /* * DocumentFragment - DOM Level 2 */ $w.__defineGetter__("DocumentFragment", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); /** * @class DOMDocumentFragment - DocumentFragment is a "lightweight" or "minimal" Document object. * @extends DOMNode * @author Jon van Noort ([email protected]) and David Joham ([email protected]) * @param ownerDocument : DOMDocument - The Document object associated with this node. */ var DOMDocumentFragment = function(ownerDocument) { this.DOMNode = DOMNode; this.DOMNode(ownerDocument); this.nodeName = "#document-fragment"; }; DOMDocumentFragment.prototype = new DOMNode; __extend__(DOMDocumentFragment.prototype,{ get nodeType(){ return DOMNode.DOCUMENT_FRAGMENT_NODE; }, get xml(){ var xml = "", count = this.childNodes.length; // create string concatenating the serialized ChildNodes for (var i = 0; i < count; i++) { xml += this.childNodes.item(i).xml; } return xml; }, toString : function(){ return "DocumentFragment #"+this._id; } }); $log("Defining ProcessingInstruction"); /* * ProcessingInstruction - DOM Level 2 */ $w.__defineGetter__('ProcessingInstruction', function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); /** * @class DOMProcessingInstruction - The ProcessingInstruction interface represents a "processing instruction", * used in XML as a way to keep processor-specific information in the text of the document * @extends DOMNode * @author Jon van Noort ([email protected]) * @param ownerDocument : DOMDocument - The Document object associated with this node. */ var DOMProcessingInstruction = function(ownerDocument) { this.DOMNode = DOMNode; this.DOMNode(ownerDocument); }; DOMProcessingInstruction.prototype = new DOMNode; __extend__(DOMProcessingInstruction.prototype, { get data(){ return this.nodeValue; }, set data(data){ // throw Exception if DOMNode is readonly if (this.ownerDocument.implementation.errorChecking && this._readonly) { throw(new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR)); } this.nodeValue = data; }, get target(){ // The target of this processing instruction. // XML defines this as being the first token following the markup that begins the processing instruction. // The content of this processing instruction. return this.nodeName; }, get nodeType(){ return DOMNode.PROCESSING_INSTRUCTION_NODE; }, get xml(){ return "<?" + this.nodeName +" "+ this.nodeValue + " ?>"; }, toString : function(){ return "ProcessingInstruction #"+this._id; } }); $log("Defining DOMParser"); /* * DOMParser */ var DOMParser = function(){}; __extend__(DOMParser.prototype,{ parseFromString: function(xmlString){ //$log("Parsing XML String: " +xmlString); return document.implementation.createDocument().loadXML(xmlString); } }); $log("Initializing Internal DOMParser."); //keep one around for internal use $domparser = new DOMParser(); $w.__defineGetter__('DOMParser', DOMParser); // ========================================================================= // // xmlsax.js - an XML SAX parser in JavaScript. // // version 3.1 // // ========================================================================= // // Copyright (C) 2001 - 2002 David Joham ([email protected]) and Scott Severtson // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // // Visit the XML for <SCRIPT> home page at http://xmljs.sourceforge.net // // CONSTANTS var whitespace = "\n\r\t "; /** * function: this is the constructor to the XMLP Object * Author: Scott Severtson * Description:XMLP is a pull-based parser. The calling application passes in a XML string * to the constructor, then repeatedly calls .next() to parse the next segment. * .next() returns a flag indicating what type of segment was found, and stores * data temporarily in couple member variables (name, content, array of * attributes), which can be accessed by several .get____() methods. * * Basically, XMLP is the lowest common denominator parser - an very simple * API which other wrappers can be built against. **/ var XMLP = function(strXML) { // Normalize line breaks strXML = SAXStrings.replace(strXML, null, null, "\r\n", "\n"); strXML = SAXStrings.replace(strXML, null, null, "\r", "\n"); this.m_xml = strXML; this.m_iP = 0; this.m_iState = XMLP._STATE_PROLOG; this.m_stack = new Stack(); this._clearAttributes(); }; // CONSTANTS (these must be below the constructor) XMLP._NONE = 0; XMLP._ELM_B = 1; XMLP._ELM_E = 2; XMLP._ELM_EMP = 3; XMLP._ATT = 4; XMLP._TEXT = 5; XMLP._ENTITY = 6; XMLP._PI = 7; XMLP._CDATA = 8; XMLP._COMMENT = 9; XMLP._DTD = 10; XMLP._ERROR = 11; XMLP._CONT_XML = 0; XMLP._CONT_ALT = 1; XMLP._ATT_NAME = 0; XMLP._ATT_VAL = 1; XMLP._STATE_PROLOG = 1; XMLP._STATE_DOCUMENT = 2; XMLP._STATE_MISC = 3; XMLP._errs = new Array(); XMLP._errs[XMLP.ERR_CLOSE_PI = 0 ] = "PI: missing closing sequence"; XMLP._errs[XMLP.ERR_CLOSE_DTD = 1 ] = "DTD: missing closing sequence"; XMLP._errs[XMLP.ERR_CLOSE_COMMENT = 2 ] = "Comment: missing closing sequence"; XMLP._errs[XMLP.ERR_CLOSE_CDATA = 3 ] = "CDATA: missing closing sequence"; XMLP._errs[XMLP.ERR_CLOSE_ELM = 4 ] = "Element: missing closing sequence"; XMLP._errs[XMLP.ERR_CLOSE_ENTITY = 5 ] = "Entity: missing closing sequence"; XMLP._errs[XMLP.ERR_PI_TARGET = 6 ] = "PI: target is required"; XMLP._errs[XMLP.ERR_ELM_EMPTY = 7 ] = "Element: cannot be both empty and closing"; XMLP._errs[XMLP.ERR_ELM_NAME = 8 ] = "Element: name must immediatly follow \"<\""; XMLP._errs[XMLP.ERR_ELM_LT_NAME = 9 ] = "Element: \"<\" not allowed in element names"; XMLP._errs[XMLP.ERR_ATT_VALUES = 10] = "Attribute: values are required and must be in quotes"; XMLP._errs[XMLP.ERR_ATT_LT_NAME = 11] = "Element: \"<\" not allowed in attribute names"; XMLP._errs[XMLP.ERR_ATT_LT_VALUE = 12] = "Attribute: \"<\" not allowed in attribute values"; XMLP._errs[XMLP.ERR_ATT_DUP = 13] = "Attribute: duplicate attributes not allowed"; XMLP._errs[XMLP.ERR_ENTITY_UNKNOWN = 14] = "Entity: unknown entity"; XMLP._errs[XMLP.ERR_INFINITELOOP = 15] = "Infininte loop"; XMLP._errs[XMLP.ERR_DOC_STRUCTURE = 16] = "Document: only comments, processing instructions, or whitespace allowed outside of document element"; XMLP._errs[XMLP.ERR_ELM_NESTING = 17] = "Element: must be nested correctly"; XMLP.prototype._addAttribute = function(name, value) { this.m_atts[this.m_atts.length] = new Array(name, value); } XMLP.prototype._checkStructure = function(iEvent) { if(XMLP._STATE_PROLOG == this.m_iState) { if((XMLP._TEXT == iEvent) || (XMLP._ENTITY == iEvent)) { if(SAXStrings.indexOfNonWhitespace(this.getContent(), this.getContentBegin(), this.getContentEnd()) != -1) { return this._setErr(XMLP.ERR_DOC_STRUCTURE); } } if((XMLP._ELM_B == iEvent) || (XMLP._ELM_EMP == iEvent)) { this.m_iState = XMLP._STATE_DOCUMENT; // Don't return - fall through to next state } } if(XMLP._STATE_DOCUMENT == this.m_iState) { if((XMLP._ELM_B == iEvent) || (XMLP._ELM_EMP == iEvent)) { this.m_stack.push(this.getName()); } if((XMLP._ELM_E == iEvent) || (XMLP._ELM_EMP == iEvent)) { var strTop = this.m_stack.pop(); if((strTop == null) || (strTop != this.getName())) { return this._setErr(XMLP.ERR_ELM_NESTING); } } if(this.m_stack.count() == 0) { this.m_iState = XMLP._STATE_MISC; return iEvent; } } if(XMLP._STATE_MISC == this.m_iState) { if((XMLP._ELM_B == iEvent) || (XMLP._ELM_E == iEvent) || (XMLP._ELM_EMP == iEvent) || (XMLP.EVT_DTD == iEvent)) { return this._setErr(XMLP.ERR_DOC_STRUCTURE); } if((XMLP._TEXT == iEvent) || (XMLP._ENTITY == iEvent)) { if(SAXStrings.indexOfNonWhitespace(this.getContent(), this.getContentBegin(), this.getContentEnd()) != -1) { return this._setErr(XMLP.ERR_DOC_STRUCTURE); } } } return iEvent; } XMLP.prototype._clearAttributes = function() { this.m_atts = new Array(); } XMLP.prototype._findAttributeIndex = function(name) { for(var i = 0; i < this.m_atts.length; i++) { if(this.m_atts[i][XMLP._ATT_NAME] == name) { return i; } } return -1; } XMLP.prototype.getAttributeCount = function() { return this.m_atts ? this.m_atts.length : 0; } XMLP.prototype.getAttributeName = function(index) { return ((index < 0) || (index >= this.m_atts.length)) ? null : this.m_atts[index][XMLP._ATT_NAME]; } XMLP.prototype.getAttributeValue = function(index) { return ((index < 0) || (index >= this.m_atts.length)) ? null : __unescapeXML__(this.m_atts[index][XMLP._ATT_VAL]); } XMLP.prototype.getAttributeValueByName = function(name) { return this.getAttributeValue(this._findAttributeIndex(name)); } XMLP.prototype.getColumnNumber = function() { return SAXStrings.getColumnNumber(this.m_xml, this.m_iP); } XMLP.prototype.getContent = function() { return (this.m_cSrc == XMLP._CONT_XML) ? this.m_xml : this.m_cAlt; } XMLP.prototype.getContentBegin = function() { return this.m_cB; } XMLP.prototype.getContentEnd = function() { return this.m_cE; } XMLP.prototype.getLineNumber = function() { return SAXStrings.getLineNumber(this.m_xml, this.m_iP); } XMLP.prototype.getName = function() { return this.m_name; } XMLP.prototype.next = function() { return this._checkStructure(this._parse()); } XMLP.prototype._parse = function() { if(this.m_iP == this.m_xml.length) { return XMLP._NONE; } if(this.m_iP == this.m_xml.indexOf("<", this.m_iP)){ if(this.m_xml.charAt(this.m_iP+1) == "?") { return this._parsePI(this.m_iP + 2); } else if(this.m_xml.charAt(this.m_iP+1) == "!") { if(this.m_xml.charAt(this.m_iP+2) == "D") { return this._parseDTD(this.m_iP + 9); } else if(this.m_xml.charAt(this.m_iP+2) == "-") { return this._parseComment(this.m_iP + 4); } else if(this.m_xml.charAt(this.m_iP+2) == "[") { return this._parseCDATA(this.m_iP + 9); } } else{ return this._parseElement(this.m_iP + 1); } } else if(this.m_iP == this.m_xml.indexOf("&", this.m_iP)) { return this._parseEntity(this.m_iP + 1); } else{ return this._parseText(this.m_iP); } } XMLP.prototype._parseAttribute = function(iB, iE) { var iNB, iNE, iEq, iVB, iVE; var cQuote, strN, strV; this.m_cAlt = ""; //resets the value so we don't use an old one by accident (see testAttribute7 in the test suite) iNB = SAXStrings.indexOfNonWhitespace(this.m_xml, iB, iE); if((iNB == -1) ||(iNB >= iE)) { return iNB; } iEq = this.m_xml.indexOf("=", iNB); if((iEq == -1) || (iEq > iE)) { return this._setErr(XMLP.ERR_ATT_VALUES); } iNE = SAXStrings.lastIndexOfNonWhitespace(this.m_xml, iNB, iEq); iVB = SAXStrings.indexOfNonWhitespace(this.m_xml, iEq + 1, iE); if((iVB == -1) ||(iVB > iE)) { return this._setErr(XMLP.ERR_ATT_VALUES); } cQuote = this.m_xml.charAt(iVB); if(_SAXStrings.QUOTES.indexOf(cQuote) == -1) { return this._setErr(XMLP.ERR_ATT_VALUES); } iVE = this.m_xml.indexOf(cQuote, iVB + 1); if((iVE == -1) ||(iVE > iE)) { return this._setErr(XMLP.ERR_ATT_VALUES); } strN = this.m_xml.substring(iNB, iNE + 1); strV = this.m_xml.substring(iVB + 1, iVE); if(strN.indexOf("<") != -1) { return this._setErr(XMLP.ERR_ATT_LT_NAME); } if(strV.indexOf("<") != -1) { return this._setErr(XMLP.ERR_ATT_LT_VALUE); } strV = SAXStrings.replace(strV, null, null, "\n", " "); strV = SAXStrings.replace(strV, null, null, "\t", " "); iRet = this._replaceEntities(strV); if(iRet == XMLP._ERROR) { return iRet; } strV = this.m_cAlt; if(this._findAttributeIndex(strN) == -1) { this._addAttribute(strN, strV); }else { return this._setErr(XMLP.ERR_ATT_DUP); } this.m_iP = iVE + 2; return XMLP._ATT; } XMLP.prototype._parseCDATA = function(iB) { var iE = this.m_xml.indexOf("]]>", iB); if (iE == -1) { return this._setErr(XMLP.ERR_CLOSE_CDATA); } this._setContent(XMLP._CONT_XML, iB, iE); this.m_iP = iE + 3; return XMLP._CDATA; } XMLP.prototype._parseComment = function(iB) { var iE = this.m_xml.indexOf("-" + "->", iB); if (iE == -1) { return this._setErr(XMLP.ERR_CLOSE_COMMENT); } this._setContent(XMLP._CONT_XML, iB, iE); this.m_iP = iE + 3; return XMLP._COMMENT; } XMLP.prototype._parseDTD = function(iB) { // Eat DTD var iE, strClose, iInt, iLast; iE = this.m_xml.indexOf(">", iB); if(iE == -1) { return this._setErr(XMLP.ERR_CLOSE_DTD); } iInt = this.m_xml.indexOf("[", iB); strClose = ((iInt != -1) && (iInt < iE)) ? "]>" : ">"; while(true) { // DEBUG: Remove /*if(iE == iLast) { return this._setErr(XMLP.ERR_INFINITELOOP); } iLast = iE;*/ // DEBUG: Remove End iE = this.m_xml.indexOf(strClose, iB); if(iE == -1) { return this._setErr(XMLP.ERR_CLOSE_DTD); } // Make sure it is not the end of a CDATA section if (this.m_xml.substring(iE - 1, iE + 2) != "]]>") { break; } } this.m_iP = iE + strClose.length; return XMLP._DTD; } XMLP.prototype._parseElement = function(iB) { var iE, iDE, iNE, iRet; var iType, strN, iLast; iDE = iE = this.m_xml.indexOf(">", iB); if(iE == -1) { return this._setErr(XMLP.ERR_CLOSE_ELM); } if(this.m_xml.charAt(iB) == "/") { iType = XMLP._ELM_E; iB++; } else { iType = XMLP._ELM_B; } if(this.m_xml.charAt(iE - 1) == "/") { if(iType == XMLP._ELM_E) { return this._setErr(XMLP.ERR_ELM_EMPTY); } iType = XMLP._ELM_EMP; iDE--; } iDE = SAXStrings.lastIndexOfNonWhitespace(this.m_xml, iB, iDE); //djohack //hack to allow for elements with single character names to be recognized /*if (iE - iB != 1 ) { if(SAXStrings.indexOfNonWhitespace(this.m_xml, iB, iDE) != iB) { return this._setErr(XMLP.ERR_ELM_NAME); } }*/ // end hack -- original code below /* if(SAXStrings.indexOfNonWhitespace(this.m_xml, iB, iDE) != iB) return this._setErr(XMLP.ERR_ELM_NAME); */ this._clearAttributes(); iNE = SAXStrings.indexOfWhitespace(this.m_xml, iB, iDE); if(iNE == -1) { iNE = iDE + 1; } else { this.m_iP = iNE; while(this.m_iP < iDE) { // DEBUG: Remove //if(this.m_iP == iLast) return this._setErr(XMLP.ERR_INFINITELOOP); //iLast = this.m_iP; // DEBUG: Remove End iRet = this._parseAttribute(this.m_iP, iDE); if(iRet == XMLP._ERROR) return iRet; } } strN = this.m_xml.substring(iB, iNE); /*if(strN.indexOf("<") != -1) { return this._setErr(XMLP.ERR_ELM_LT_NAME); }*/ this.m_name = strN; this.m_iP = iE + 1; return iType; } XMLP.prototype._parseEntity = function(iB) { var iE = this.m_xml.indexOf(";", iB); if(iE == -1) { return this._setErr(XMLP.ERR_CLOSE_ENTITY); } this.m_iP = iE + 1; return this._replaceEntity(this.m_xml, iB, iE); } XMLP.prototype._parsePI = function(iB) { var iE, iTB, iTE, iCB, iCE; iE = this.m_xml.indexOf("?>", iB); if(iE == -1) { return this._setErr(XMLP.ERR_CLOSE_PI); } iTB = SAXStrings.indexOfNonWhitespace(this.m_xml, iB, iE); if(iTB == -1) { return this._setErr(XMLP.ERR_PI_TARGET); } iTE = SAXStrings.indexOfWhitespace(this.m_xml, iTB, iE); if(iTE == -1) { iTE = iE; } iCB = SAXStrings.indexOfNonWhitespace(this.m_xml, iTE, iE); if(iCB == -1) { iCB = iE; } iCE = SAXStrings.lastIndexOfNonWhitespace(this.m_xml, iCB, iE); if(iCE == -1) { iCE = iE - 1; } this.m_name = this.m_xml.substring(iTB, iTE); this._setContent(XMLP._CONT_XML, iCB, iCE + 1); this.m_iP = iE + 2; return XMLP._PI; } XMLP.prototype._parseText = function(iB) { var iE, iEE; iE = this.m_xml.indexOf("<", iB); if(iE == -1) { iE = this.m_xml.length; } iEE = this.m_xml.indexOf("&", iB); if((iEE != -1) && (iEE <= iE)) { iE = iEE; } this._setContent(XMLP._CONT_XML, iB, iE); this.m_iP = iE; return XMLP._TEXT; } XMLP.prototype._replaceEntities = function(strD, iB, iE) { if(SAXStrings.isEmpty(strD)) return ""; iB = iB || 0; iE = iE || strD.length; var iEB, iEE, strRet = ""; iEB = strD.indexOf("&", iB); iEE = iB; while((iEB > 0) && (iEB < iE)) { strRet += strD.substring(iEE, iEB); iEE = strD.indexOf(";", iEB) + 1; if((iEE == 0) || (iEE > iE)) { return this._setErr(XMLP.ERR_CLOSE_ENTITY); } iRet = this._replaceEntity(strD, iEB + 1, iEE - 1); if(iRet == XMLP._ERROR) { return iRet; } strRet += this.m_cAlt; iEB = strD.indexOf("&", iEE); } if(iEE != iE) { strRet += strD.substring(iEE, iE); } this._setContent(XMLP._CONT_ALT, strRet); return XMLP._ENTITY; } XMLP.prototype._replaceEntity = function(strD, iB, iE) { if(SAXStrings.isEmpty(strD)) return -1; iB = iB || 0; iE = iE || strD.length; switch(strD.substring(iB, iE)) { case "amp": strEnt = "&"; break; case "lt": strEnt = "<"; break; case "gt": strEnt = ">"; break; case "apos": strEnt = "'"; break; case "quot": strEnt = "\""; break; default: if(strD.charAt(iB) == "#") { strEnt = String.fromCharCode(parseInt(strD.substring(iB + 1, iE))); } else { return this._setErr(XMLP.ERR_ENTITY_UNKNOWN); } break; } this._setContent(XMLP._CONT_ALT, strEnt); return XMLP._ENTITY; } XMLP.prototype._setContent = function(iSrc) { var args = arguments; if(XMLP._CONT_XML == iSrc) { this.m_cAlt = null; this.m_cB = args[1]; this.m_cE = args[2]; } else { this.m_cAlt = args[1]; this.m_cB = 0; this.m_cE = args[1].length; } this.m_cSrc = iSrc; } XMLP.prototype._setErr = function(iErr) { var strErr = XMLP._errs[iErr]; this.m_cAlt = strErr; this.m_cB = 0; this.m_cE = strErr.length; this.m_cSrc = XMLP._CONT_ALT; return XMLP._ERROR; } /** * function: SAXDriver * Author: Scott Severtson * Description: * SAXDriver is an object that basically wraps an XMLP instance, and provides an * event-based interface for parsing. This is the object users interact with when coding * with XML for <SCRIPT> **/ var SAXDriver = function() { this.m_hndDoc = null; this.m_hndErr = null; this.m_hndLex = null; } // CONSTANTS SAXDriver.DOC_B = 1; SAXDriver.DOC_E = 2; SAXDriver.ELM_B = 3; SAXDriver.ELM_E = 4; SAXDriver.CHARS = 5; SAXDriver.PI = 6; SAXDriver.CD_B = 7; SAXDriver.CD_E = 8; SAXDriver.CMNT = 9; SAXDriver.DTD_B = 10; SAXDriver.DTD_E = 11; SAXDriver.prototype.parse = function(strD) { var parser = new XMLP(strD); if(this.m_hndDoc && this.m_hndDoc.setDocumentLocator) { this.m_hndDoc.setDocumentLocator(this); } this.m_parser = parser; this.m_bErr = false; if(!this.m_bErr) { this._fireEvent(SAXDriver.DOC_B); } this._parseLoop(); if(!this.m_bErr) { this._fireEvent(SAXDriver.DOC_E); } this.m_xml = null; this.m_iP = 0; } SAXDriver.prototype.setDocumentHandler = function(hnd) { this.m_hndDoc = hnd; } SAXDriver.prototype.setErrorHandler = function(hnd) { this.m_hndErr = hnd; } SAXDriver.prototype.setLexicalHandler = function(hnd) { this.m_hndLex = hnd; } /** * LOCATOR/PARSE EXCEPTION INTERFACE ***/ SAXDriver.prototype.getColumnNumber = function() { return this.m_parser.getColumnNumber(); } SAXDriver.prototype.getLineNumber = function() { return this.m_parser.getLineNumber(); } SAXDriver.prototype.getMessage = function() { return this.m_strErrMsg; } SAXDriver.prototype.getPublicId = function() { return null; } SAXDriver.prototype.getSystemId = function() { return null; } /*** * Attribute List Interface **/ SAXDriver.prototype.getLength = function() { return this.m_parser.getAttributeCount(); } SAXDriver.prototype.getName = function(index) { return this.m_parser.getAttributeName(index); } SAXDriver.prototype.getValue = function(index) { return this.m_parser.getAttributeValue(index); } SAXDriver.prototype.getValueByName = function(name) { return this.m_parser.getAttributeValueByName(name); } /*** * Private functions **/ SAXDriver.prototype._fireError = function(strMsg) { this.m_strErrMsg = strMsg; this.m_bErr = true; if(this.m_hndErr && this.m_hndErr.fatalError) { this.m_hndErr.fatalError(this); } } // end function _fireError SAXDriver.prototype._fireEvent = function(iEvt) { var hnd, func, args = arguments, iLen = args.length - 1; if(this.m_bErr) return; if(SAXDriver.DOC_B == iEvt) { func = "startDocument"; hnd = this.m_hndDoc; } else if (SAXDriver.DOC_E == iEvt) { func = "endDocument"; hnd = this.m_hndDoc; } else if (SAXDriver.ELM_B == iEvt) { func = "startElement"; hnd = this.m_hndDoc; } else if (SAXDriver.ELM_E == iEvt) { func = "endElement"; hnd = this.m_hndDoc; } else if (SAXDriver.CHARS == iEvt) { func = "characters"; hnd = this.m_hndDoc; } else if (SAXDriver.PI == iEvt) { func = "processingInstruction"; hnd = this.m_hndDoc; } else if (SAXDriver.CD_B == iEvt) { func = "startCDATA"; hnd = this.m_hndLex; } else if (SAXDriver.CD_E == iEvt) { func = "endCDATA"; hnd = this.m_hndLex; } else if (SAXDriver.CMNT == iEvt) { func = "comment"; hnd = this.m_hndLex; } if(hnd && hnd[func]) { if(0 == iLen) { hnd[func](); } else if (1 == iLen) { hnd[func](args[1]); } else if (2 == iLen) { hnd[func](args[1], args[2]); } else if (3 == iLen) { hnd[func](args[1], args[2], args[3]); } } } // end function _fireEvent SAXDriver.prototype._parseLoop = function(parser) { var iEvent, parser; parser = this.m_parser; while(!this.m_bErr) { iEvent = parser.next(); if(iEvent == XMLP._ELM_B) { this._fireEvent(SAXDriver.ELM_B, parser.getName(), this); } else if(iEvent == XMLP._ELM_E) { this._fireEvent(SAXDriver.ELM_E, parser.getName()); } else if(iEvent == XMLP._ELM_EMP) { this._fireEvent(SAXDriver.ELM_B, parser.getName(), this); this._fireEvent(SAXDriver.ELM_E, parser.getName()); } else if(iEvent == XMLP._TEXT) { this._fireEvent(SAXDriver.CHARS, parser.getContent(), parser.getContentBegin(), parser.getContentEnd() - parser.getContentBegin()); } else if(iEvent == XMLP._ENTITY) { this._fireEvent(SAXDriver.CHARS, parser.getContent(), parser.getContentBegin(), parser.getContentEnd() - parser.getContentBegin()); } else if(iEvent == XMLP._PI) { this._fireEvent(SAXDriver.PI, parser.getName(), parser.getContent().substring(parser.getContentBegin(), parser.getContentEnd())); } else if(iEvent == XMLP._CDATA) { this._fireEvent(SAXDriver.CD_B); this._fireEvent(SAXDriver.CHARS, parser.getContent(), parser.getContentBegin(), parser.getContentEnd() - parser.getContentBegin()); this._fireEvent(SAXDriver.CD_E); } else if(iEvent == XMLP._COMMENT) { this._fireEvent(SAXDriver.CMNT, parser.getContent(), parser.getContentBegin(), parser.getContentEnd() - parser.getContentBegin()); } else if(iEvent == XMLP._DTD) { } else if(iEvent == XMLP._ERROR) { this._fireError(parser.getContent()); } else if(iEvent == XMLP._NONE) { return; } } } // end function _parseLoop /** * function: SAXStrings * Author: Scott Severtson * Description: a useful object containing string manipulation functions **/ var _SAXStrings = function() {}; _SAXStrings.WHITESPACE = " \t\n\r"; _SAXStrings.NONWHITESPACE = /\S/; _SAXStrings.QUOTES = "\"'"; _SAXStrings.prototype.getColumnNumber = function(strD, iP) { if((strD === null) || (strD.length === 0)) { return -1; } iP = iP || strD.length; var arrD = strD.substring(0, iP).split("\n"); var strLine = arrD[arrD.length - 1]; arrD.length--; var iLinePos = arrD.join("\n").length; return iP - iLinePos; } // end function getColumnNumber _SAXStrings.prototype.getLineNumber = function(strD, iP) { if((strD === null) || (strD.length === 0)) { return -1; } iP = iP || strD.length; return strD.substring(0, iP).split("\n").length } // end function getLineNumber _SAXStrings.prototype.indexOfNonWhitespace = function(strD, iB, iE) { if((strD === null) || (strD.length === 0)) { return -1; } iB = iB || 0; iE = iE || strD.length; //var i = strD.substring(iB, iE).search(_SAXStrings.NONWHITESPACE); //return i < 0 ? i : iB + i; while( strD.charCodeAt(iB++) < 33 ); return (iB > iE)?-1:iB-1; /*for(var i = iB; i < iE; i++){ if(_SAXStrings.WHITESPACE.indexOf(strD.charAt(i)) == -1) { return i; } } return -1;*/ } // end function indexOfNonWhitespace _SAXStrings.prototype.indexOfWhitespace = function(strD, iB, iE) { if((strD === null) || (strD.length === 0)) { return -1; } iB = iB || 0; iE = iE || strD.length; while( strD.charCodeAt(iB++) >= 33 ); return (iB > iE)?-1:iB-1; /*for(var i = iB; i < iE; i++) { if(_SAXStrings.WHITESPACE.indexOf(strD.charAt(i)) != -1) { return i; } } return -1;*/ } // end function indexOfWhitespace _SAXStrings.prototype.isEmpty = function(strD) { return (strD == null) || (strD.length == 0); } _SAXStrings.prototype.lastIndexOfNonWhitespace = function(strD, iB, iE) { if((strD === null) || (strD.length === 0)) { return -1; } iB = iB || 0; iE = iE || strD.length; while( (iE >= iB) && strD.charCodeAt(--iE) < 33 ); return (iE < iB)?-1:iE; /*for(var i = iE - 1; i >= iB; i--){ if(_SAXStrings.WHITESPACE.indexOf(strD.charAt(i)) == -1){ return i; } } return -1;*/ } _SAXStrings.prototype.replace = function(strD, iB, iE, strF, strR) { if((strD == null) || (strD.length == 0)) { return ""; } iB = iB || 0; iE = iE || strD.length; return strD.substring(iB, iE).split(strF).join(strR); }; var SAXStrings = new _SAXStrings(); /*************************************************************************************************************** Stack: A simple stack class, used for verifying document structure. Author: Scott Severtson *****************************************************************************************************************/ var Stack = function() { this.m_arr = new Array(); }; __extend__(Stack.prototype, { clear : function() { this.m_arr = new Array(); }, count : function() { return this.m_arr.length; }, destroy : function() { this.m_arr = null; }, peek : function() { if(this.m_arr.length == 0) { return null; } return this.m_arr[this.m_arr.length - 1]; }, pop : function() { if(this.m_arr.length == 0) { return null; } var o = this.m_arr[this.m_arr.length - 1]; this.m_arr.length--; return o; }, push : function(o) { this.m_arr[this.m_arr.length] = o; } }); /** * function: isEmpty * Author: [email protected] * Description: convenience function to identify an empty string **/ function isEmpty(str) { return (str==null) || (str.length==0); }; /** * function __escapeXML__ * author: David Joham [email protected] * @param str : string - The string to be escaped * @return : string - The escaped string */ var escAmpRegEx = /&/g; var escLtRegEx = /</g; var escGtRegEx = />/g; var quotRegEx = /"/g; var aposRegEx = /'/g; function __escapeXML__(str) { str = str.replace(escAmpRegEx, "&amp;"). replace(escLtRegEx, "&lt;"). replace(escGtRegEx, "&gt;"). replace(quotRegEx, "&quot;"). replace(aposRegEx, "&apos;"); return str; }; /** * function __unescapeXML__ * author: David Joham [email protected] * @param str : string - The string to be unescaped * @return : string - The unescaped string */ var unescAmpRegEx = /&amp;/g; var unescLtRegEx = /&lt;/g; var unescGtRegEx = /&gt;/g; var unquotRegEx = /&quot;/g; var unaposRegEx = /&apos;/g; function __unescapeXML__(str) { str = str.replace(unescAmpRegEx, "&"). replace(unescLtRegEx, "<"). replace(unescGtRegEx, ">"). replace(unquotRegEx, "\""). replace(unaposRegEx, "'"); return str; }; //DOMImplementation $log("Defining DOMImplementation"); $w.__defineGetter__("DOMImplementation", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); /** * @class DOMImplementation - provides a number of methods for performing operations * that are independent of any particular instance of the document object model. * * @author Jon van Noort ([email protected]) */ var DOMImplementation = function() { this.preserveWhiteSpace = false; // by default, ignore whitespace this.namespaceAware = true; // by default, handle namespaces this.errorChecking = true; // by default, test for exceptions }; __extend__(DOMImplementation.prototype,{ // @param feature : string - The package name of the feature to test. // the legal only values are "XML" and "CORE" (case-insensitive). // @param version : string - This is the version number of the package // name to test. In Level 1, this is the string "1.0".* // @return : boolean hasFeature : function(feature, version) { var ret = false; if (feature.toLowerCase() == "xml") { ret = (!version || (version == "1.0") || (version == "2.0")); } else if (feature.toLowerCase() == "core") { ret = (!version || (version == "2.0")); } return ret; }, createDocumentType : function(qname, publicid, systemid){ return new DOMDocumentType(); }, createDocument : function(nsuri, qname, doctype){ //TODO - this currently returns an empty doc //but needs to handle the args return new HTMLDocument($implementation); }, translateErrCode : function(code) { //convert DOMException Code to human readable error message; var msg = ""; switch (code) { case DOMException.INDEX_SIZE_ERR : // 1 msg = "INDEX_SIZE_ERR: Index out of bounds"; break; case DOMException.DOMSTRING_SIZE_ERR : // 2 msg = "DOMSTRING_SIZE_ERR: The resulting string is too long to fit in a DOMString"; break; case DOMException.HIERARCHY_REQUEST_ERR : // 3 msg = "HIERARCHY_REQUEST_ERR: The Node can not be inserted at this location"; break; case DOMException.WRONG_DOCUMENT_ERR : // 4 msg = "WRONG_DOCUMENT_ERR: The source and the destination Documents are not the same"; break; case DOMException.INVALID_CHARACTER_ERR : // 5 msg = "INVALID_CHARACTER_ERR: The string contains an invalid character"; break; case DOMException.NO_DATA_ALLOWED_ERR : // 6 msg = "NO_DATA_ALLOWED_ERR: This Node / NodeList does not support data"; break; case DOMException.NO_MODIFICATION_ALLOWED_ERR : // 7 msg = "NO_MODIFICATION_ALLOWED_ERR: This object cannot be modified"; break; case DOMException.NOT_FOUND_ERR : // 8 msg = "NOT_FOUND_ERR: The item cannot be found"; break; case DOMException.NOT_SUPPORTED_ERR : // 9 msg = "NOT_SUPPORTED_ERR: This implementation does not support function"; break; case DOMException.INUSE_ATTRIBUTE_ERR : // 10 msg = "INUSE_ATTRIBUTE_ERR: The Attribute has already been assigned to another Element"; break; // Introduced in DOM Level 2: case DOMException.INVALID_STATE_ERR : // 11 msg = "INVALID_STATE_ERR: The object is no longer usable"; break; case DOMException.SYNTAX_ERR : // 12 msg = "SYNTAX_ERR: Syntax error"; break; case DOMException.INVALID_MODIFICATION_ERR : // 13 msg = "INVALID_MODIFICATION_ERR: Cannot change the type of the object"; break; case DOMException.NAMESPACE_ERR : // 14 msg = "NAMESPACE_ERR: The namespace declaration is incorrect"; break; case DOMException.INVALID_ACCESS_ERR : // 15 msg = "INVALID_ACCESS_ERR: The object does not support this function"; break; default : msg = "UNKNOWN: Unknown Exception Code ("+ code +")"; } return msg; } }); /** * Defined 'globally' to this scope. Remember everything is wrapped in a closure so this doesnt show up * in the outer most global scope. */ /** * process SAX events * * @author Jon van Noort ([email protected]), David Joham ([email protected]) and Scott Severtson * * @param impl : DOMImplementation * @param doc : DOMDocument - the Document to contain the parsed XML string * @param p : XMLP - the SAX Parser * * @return : DOMDocument */ function __parseLoop__(impl, doc, p) { var iEvt, iNode, iAttr, strName; iNodeParent = doc; var el_close_count = 0; var entitiesList = new Array(); var textNodesList = new Array(); // if namespaceAware, add default namespace if (impl.namespaceAware) { var iNS = doc.createNamespace(""); // add the default-default namespace iNS.value = "http://www.w3.org/2000/xmlns/"; doc._namespaces.setNamedItem(iNS); } // loop until SAX parser stops emitting events while(true) { // get next event iEvt = p.next(); if (iEvt == XMLP._ELM_B) { // Begin-Element Event var pName = p.getName(); // get the Element name pName = trim(pName, true, true); // strip spaces from Element name if (!impl.namespaceAware) { iNode = doc.createElement(p.getName()); // create the Element // add attributes to Element for(var i = 0; i < p.getAttributeCount(); i++) { strName = p.getAttributeName(i); // get Attribute name iAttr = iNode.getAttributeNode(strName); // if Attribute exists, use it if(!iAttr) { iAttr = doc.createAttribute(strName); // otherwise create it } iAttr.value = p.getAttributeValue(i); // set Attribute value iNode.setAttributeNode(iAttr); // attach Attribute to Element } } else { // Namespace Aware // create element (with empty namespaceURI, // resolve after namespace 'attributes' have been parsed) iNode = doc.createElementNS("", p.getName()); // duplicate ParentNode's Namespace definitions iNode._namespaces = __cloneNamedNodes__(iNodeParent._namespaces, iNode); // add attributes to Element for(var i = 0; i < p.getAttributeCount(); i++) { strName = p.getAttributeName(i); // get Attribute name // if attribute is a namespace declaration if (__isNamespaceDeclaration__(strName)) { // parse Namespace Declaration var namespaceDec = __parseNSName__(strName); if (strName != "xmlns") { iNS = doc.createNamespace(strName); // define namespace } else { iNS = doc.createNamespace(""); // redefine default namespace } iNS.value = p.getAttributeValue(i); // set value = namespaceURI iNode._namespaces.setNamedItem(iNS); // attach namespace to namespace collection } else { // otherwise, it is a normal attribute iAttr = iNode.getAttributeNode(strName); // if Attribute exists, use it if(!iAttr) { iAttr = doc.createAttributeNS("", strName); // otherwise create it } iAttr.value = p.getAttributeValue(i); // set Attribute value iNode.setAttributeNodeNS(iAttr); // attach Attribute to Element if (__isIdDeclaration__(strName)) { iNode.id = p.getAttributeValue(i); // cache ID for getElementById() } } } // resolve namespaceURIs for this Element if (iNode._namespaces.getNamedItem(iNode.prefix)) { iNode.namespaceURI = iNode._namespaces.getNamedItem(iNode.prefix).value; } // for this Element's attributes for (var i = 0; i < iNode.attributes.length; i++) { if (iNode.attributes.item(i).prefix != "") { // attributes do not have a default namespace if (iNode._namespaces.getNamedItem(iNode.attributes.item(i).prefix)) { iNode.attributes.item(i).namespaceURI = iNode._namespaces.getNamedItem(iNode.attributes.item(i).prefix).value; } } } } // if this is the Root Element if (iNodeParent.nodeType == DOMNode.DOCUMENT_NODE) { iNodeParent.documentElement = iNode; // register this Element as the Document.documentElement } iNodeParent.appendChild(iNode); // attach Element to parentNode iNodeParent = iNode; // descend one level of the DOM Tree } else if(iEvt == XMLP._ELM_E) { // End-Element Event iNodeParent = iNodeParent.parentNode; // ascend one level of the DOM Tree } else if(iEvt == XMLP._ELM_EMP) { // Empty Element Event pName = p.getName(); // get the Element name pName = trim(pName, true, true); // strip spaces from Element name if (!impl.namespaceAware) { iNode = doc.createElement(pName); // create the Element // add attributes to Element for(var i = 0; i < p.getAttributeCount(); i++) { strName = p.getAttributeName(i); // get Attribute name iAttr = iNode.getAttributeNode(strName); // if Attribute exists, use it if(!iAttr) { iAttr = doc.createAttribute(strName); // otherwise create it } iAttr.value = p.getAttributeValue(i); // set Attribute value iNode.setAttributeNode(iAttr); // attach Attribute to Element } } else { // Namespace Aware // create element (with empty namespaceURI, // resolve after namespace 'attributes' have been parsed) iNode = doc.createElementNS("", p.getName()); // duplicate ParentNode's Namespace definitions iNode._namespaces = __cloneNamedNodes__(iNodeParent._namespaces, iNode); // add attributes to Element for(var i = 0; i < p.getAttributeCount(); i++) { strName = p.getAttributeName(i); // get Attribute name // if attribute is a namespace declaration if (__isNamespaceDeclaration__(strName)) { // parse Namespace Declaration var namespaceDec = __parseNSName__(strName); if (strName != "xmlns") { iNS = doc.createNamespace(strName); // define namespace } else { iNS = doc.createNamespace(""); // redefine default namespace } iNS.value = p.getAttributeValue(i); // set value = namespaceURI iNode._namespaces.setNamedItem(iNS); // attach namespace to namespace collection } else { // otherwise, it is a normal attribute iAttr = iNode.getAttributeNode(strName); // if Attribute exists, use it if(!iAttr) { iAttr = doc.createAttributeNS("", strName); // otherwise create it } iAttr.value = p.getAttributeValue(i); // set Attribute value iNode.setAttributeNodeNS(iAttr); // attach Attribute to Element if (__isIdDeclaration__(strName)) { iNode.id = p.getAttributeValue(i); // cache ID for getElementById() } } } // resolve namespaceURIs for this Element if (iNode._namespaces.getNamedItem(iNode.prefix)) { iNode.namespaceURI = iNode._namespaces.getNamedItem(iNode.prefix).value; } // for this Element's attributes for (var i = 0; i < iNode.attributes.length; i++) { if (iNode.attributes.item(i).prefix != "") { // attributes do not have a default namespace if (iNode._namespaces.getNamedItem(iNode.attributes.item(i).prefix)) { iNode.attributes.item(i).namespaceURI = iNode._namespaces.getNamedItem(iNode.attributes.item(i).prefix).value; } } } } // if this is the Root Element if (iNodeParent.nodeType == DOMNode.DOCUMENT_NODE) { iNodeParent.documentElement = iNode; // register this Element as the Document.documentElement } iNodeParent.appendChild(iNode); // attach Element to parentNode } else if(iEvt == XMLP._TEXT || iEvt == XMLP._ENTITY) { // TextNode and entity Events // get Text content var pContent = p.getContent().substring(p.getContentBegin(), p.getContentEnd()); if (!impl.preserveWhiteSpace ) { if (trim(pContent, true, true) == "") { pContent = ""; //this will cause us not to create the text node below } } if (pContent.length > 0) { // ignore empty TextNodes var textNode = doc.createTextNode(pContent); iNodeParent.appendChild(textNode); // attach TextNode to parentNode //the sax parser breaks up text nodes when it finds an entity. For //example hello&lt;there will fire a text, an entity and another text //this sucks for the dom parser because it looks to us in this logic //as three text nodes. I fix this by keeping track of the entity nodes //and when we're done parsing, calling normalize on their parent to //turn the multiple text nodes into one, which is what DOM users expect //the code to do this is at the bottom of this function if (iEvt == XMLP._ENTITY) { entitiesList[entitiesList.length] = textNode; } else { //I can't properly decide how to handle preserve whitespace //until the siblings of the text node are built due to //the entitiy handling described above. I don't know that this //will be all of the text node or not, so trimming is not appropriate //at this time. Keep a list of all the text nodes for now //and we'll process the preserve whitespace stuff at a later time. textNodesList[textNodesList.length] = textNode; } } } else if(iEvt == XMLP._PI) { // ProcessingInstruction Event // attach ProcessingInstruction to parentNode iNodeParent.appendChild(doc.createProcessingInstruction(p.getName(), p.getContent().substring(p.getContentBegin(), p.getContentEnd()))); } else if(iEvt == XMLP._CDATA) { // CDATA Event // get CDATA data pContent = p.getContent().substring(p.getContentBegin(), p.getContentEnd()); if (!impl.preserveWhiteSpace) { pContent = trim(pContent, true, true); // trim whitespace pContent.replace(/ +/g, ' '); // collapse multiple spaces to 1 space } if (pContent.length > 0) { // ignore empty CDATANodes iNodeParent.appendChild(doc.createCDATASection(pContent)); // attach CDATA to parentNode } } else if(iEvt == XMLP._COMMENT) { // Comment Event // get COMMENT data var pContent = p.getContent().substring(p.getContentBegin(), p.getContentEnd()); if (!impl.preserveWhiteSpace) { pContent = trim(pContent, true, true); // trim whitespace pContent.replace(/ +/g, ' '); // collapse multiple spaces to 1 space } if (pContent.length > 0) { // ignore empty CommentNodes iNodeParent.appendChild(doc.createComment(pContent)); // attach Comment to parentNode } } else if(iEvt == XMLP._DTD) { // ignore DTD events } else if(iEvt == XMLP._ERROR) { $error("Fatal Error: " + p.getContent() + "\nLine: " + p.getLineNumber() + "\nColumn: " + p.getColumnNumber() + "\n"); throw(new DOMException(DOMException.SYNTAX_ERR)); } else if(iEvt == XMLP._NONE) { // no more events if (iNodeParent == doc) { // confirm that we have recursed back up to root break; } else { throw(new DOMException(DOMException.SYNTAX_ERR)); // one or more Tags were not closed properly } } } //normalize any entities in the DOM to a single textNode for (var i = 0; i < entitiesList.length; i++) { var entity = entitiesList[i]; //its possible (if for example two entities were in the //same domnode, that the normalize on the first entitiy //will remove the parent for the second. Only do normalize //if I can find a parent node var parentNode = entity.parentNode; if (parentNode) { parentNode.normalize(); //now do whitespace (if necessary) //it was not done for text nodes that have entities if(!impl.preserveWhiteSpace) { var children = parentNode.childNodes; for ( var j = 0; j < children.length; j++) { var child = children.item(j); if (child.nodeType == DOMNode.TEXT_NODE) { var childData = child.data; childData.replace(/\s/g, ' '); child.data = childData; } } } } } //do the preserve whitespace processing on the rest of the text nodes //It's possible (due to the processing above) that the node will have been //removed from the tree. Only do whitespace checking if parentNode is not null. //This may duplicate the whitespace processing for some nodes that had entities in them //but there's no way around that if (!impl.preserveWhiteSpace) { for (var i = 0; i < textNodesList.length; i++) { var node = textNodesList[i]; if (node.parentNode != null) { var nodeData = node.data; nodeData.replace(/\s/g, ' '); node.data = nodeData; } } } }; /** * @method DOMImplementation._isNamespaceDeclaration - Return true, if attributeName is a namespace declaration * @author Jon van Noort ([email protected]) * @param attributeName : string - the attribute name * @return : boolean */ function __isNamespaceDeclaration__(attributeName) { // test if attributeName is 'xmlns' return (attributeName.indexOf('xmlns') > -1); }; /** * @method DOMImplementation._isIdDeclaration - Return true, if attributeName is an id declaration * @author Jon van Noort ([email protected]) * @param attributeName : string - the attribute name * @return : boolean */ function __isIdDeclaration__(attributeName) { // test if attributeName is 'id' (case insensitive) return (attributeName.toLowerCase() == 'id'); }; /** * @method DOMImplementation._isValidName - Return true, * if name contains no invalid characters * @author Jon van Noort ([email protected]) * @param name : string - the candidate name * @return : boolean */ function __isValidName__(name) { // test if name contains only valid characters return name.match(re_validName); }; var re_validName = /^[a-zA-Z_:][a-zA-Z0-9\.\-_:]*$/; /** * @method DOMImplementation._isValidString - Return true, if string does not contain any illegal chars * All of the characters 0 through 31 and character 127 are nonprinting control characters. * With the exception of characters 09, 10, and 13, (Ox09, Ox0A, and Ox0D) * Note: different from _isValidName in that ValidStrings may contain spaces * @author Jon van Noort ([email protected]) * @param name : string - the candidate string * @return : boolean */ function __isValidString__(name) { // test that string does not contains invalid characters return (name.search(re_invalidStringChars) < 0); }; var re_invalidStringChars = /\x01|\x02|\x03|\x04|\x05|\x06|\x07|\x08|\x0B|\x0C|\x0E|\x0F|\x10|\x11|\x12|\x13|\x14|\x15|\x16|\x17|\x18|\x19|\x1A|\x1B|\x1C|\x1D|\x1E|\x1F|\x7F/; /** * @method DOMImplementation._parseNSName - parse the namespace name. * if there is no colon, the * @author Jon van Noort ([email protected]) * @param qualifiedName : string - The qualified name * @return : NSName - [ .prefix : string - The prefix part of the qname .namespaceName : string - The namespaceURI part of the qname ] */ function __parseNSName__(qualifiedName) { var resultNSName = new Object(); resultNSName.prefix = qualifiedName; // unless the qname has a namespaceName, the prefix is the entire String resultNSName.namespaceName = ""; // split on ':' var delimPos = qualifiedName.indexOf(':'); if (delimPos > -1) { // get prefix resultNSName.prefix = qualifiedName.substring(0, delimPos); // get namespaceName resultNSName.namespaceName = qualifiedName.substring(delimPos +1, qualifiedName.length); } return resultNSName; }; /** * @method DOMImplementation._parseQName - parse the qualified name * @author Jon van Noort ([email protected]) * @param qualifiedName : string - The qualified name * @return : QName */ function __parseQName__(qualifiedName) { var resultQName = new Object(); resultQName.localName = qualifiedName; // unless the qname has a prefix, the local name is the entire String resultQName.prefix = ""; // split on ':' var delimPos = qualifiedName.indexOf(':'); if (delimPos > -1) { // get prefix resultQName.prefix = qualifiedName.substring(0, delimPos); // get localName resultQName.localName = qualifiedName.substring(delimPos +1, qualifiedName.length); } return resultQName; }; $log("Initializing document.implementation"); var $implementation = new DOMImplementation(); $implementation.namespaceAware = false; $implementation.errorChecking = false;$log("Defining Document"); /* * Document - DOM Level 2 * The Document object is not directly */ $w.__defineGetter__('Document', function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); /** * @class DOMDocument - The Document interface represents the entire HTML or XML document. * Conceptually, it is the root of the document tree, and provides the primary access to the document's data. * * @extends DOMNode * @author Jon van Noort ([email protected]) * @param implementation : DOMImplementation - the creator Implementation */ var DOMDocument = function(implementation) { //$log("\tcreating dom document"); this.DOMNode = DOMNode; this.DOMNode(this); this.doctype = null; // The Document Type Declaration (see DocumentType) associated with this document this.implementation = implementation; // The DOMImplementation object that handles this document. this.documentElement = null; // This is a convenience attribute that allows direct access to the child node that is the root element of the document //this.all = new Array(); // The list of all Elements this.nodeName = "#document"; this._id = 0; this._lastId = 0; this._parseComplete = false; // initially false, set to true by parser this._url = ""; this.ownerDocument = this; this._performingImportNodeOperation = false; //$log("\tfinished creating dom document " + this); }; DOMDocument.prototype = new DOMNode; __extend__(DOMDocument.prototype, { addEventListener : function(){ window.addEventListener.apply(this, arguments) }, removeEventListener : function(){ window.removeEventListener.apply(this, arguments) }, attachEvent : function(){ window.addEventListener.apply(this, arguments) }, detachEvent : function(){ window.removeEventListener.apply(this, arguments) }, dispatchEvent : function(){ window.dispatchEvent.apply(this, arguments) }, get styleSheets(){ return [];/*TODO*/ }, get all(){ return this.getElementsByTagName("*"); }, loadXML : function(xmlStr) { // create SAX Parser var parser = new XMLP(String(xmlStr)); // create DOM Document var doc = new HTMLDocument(this.implementation); // populate Document with Parsed Nodes try { __parseLoop__(this.implementation, doc, parser); //HTMLtoDOM(xmlStr, doc); } catch (e) { $error(this.implementation.translateErrCode(e.code)) } // set parseComplete flag, (Some validation Rules are relaxed if this is false) doc._parseComplete = true; if(this === $document){ $log("Setting internal window.document"); $document = doc; } return doc; }, load: function(url){ $log("Loading url into DOM Document: "+ url + " - (Asynch? "+$w.document.async+")"); var _this = this; var xhr = new XMLHttpRequest(); xhr.open("GET", url, $w.document.async); xhr.onreadystatechange = function(){ try{ _this.loadXML(xhr.responseText); }catch(e){ $error("Error Parsing XML - ",e); _this.loadXML( "<html><head></head><body>"+ "<h1>Parse Error</h1>"+ "<p>"+e.toString()+"</p>"+ "</body></html>"); } _this._url = url; $log("Sucessfully loaded document."); var event = document.createEvent(); event.initEvent("load"); $w.dispatchEvent( event ); }; xhr.send(); }, createEvent : function(eventType){ var event; if(eventType === "UIEvents"){ event = new UIEvent();} else if(eventType === "MouseEvents"){ event = new MouseEvent();} else{ event = new Event(); } return event; }, createExpression : function(xpath, nsuriMap){ return null;/*TODO*/ }, createElement : function(tagName) { //$log("DOMDocument.createElement( "+tagName+" )"); // throw Exception if the tagName string contains an illegal character if (this.ownerDocument.implementation.errorChecking && (!__isValidName__(tagName))) { throw(new DOMException(DOMException.INVALID_CHARACTER_ERR)); } // create DOMElement specifying 'this' as ownerDocument var node = new DOMElement(this); // assign values to properties (and aliases) node.tagName = tagName; return node; }, createDocumentFragment : function() { // create DOMDocumentFragment specifying 'this' as ownerDocument var node = new DOMDocumentFragment(this); return node; }, createTextNode: function(data) { // create DOMText specifying 'this' as ownerDocument var node = new DOMText(this); // assign values to properties (and aliases) node.data = data; return node; }, createComment : function(data) { // create DOMComment specifying 'this' as ownerDocument var node = new DOMComment(this); // assign values to properties (and aliases) node.data = data; return node; }, createCDATASection : function(data) { // create DOMCDATASection specifying 'this' as ownerDocument var node = new DOMCDATASection(this); // assign values to properties (and aliases) node.data = data; return node; }, createProcessingInstruction : function(target, data) { // throw Exception if the target string contains an illegal character if (this.ownerDocument.implementation.errorChecking && (!__isValidName__(target))) { throw(new DOMException(DOMException.INVALID_CHARACTER_ERR)); } // create DOMProcessingInstruction specifying 'this' as ownerDocument var node = new DOMProcessingInstruction(this); // assign values to properties (and aliases) node.target = target; node.data = data; return node; }, createAttribute : function(name) { // throw Exception if the name string contains an illegal character if (this.ownerDocument.implementation.errorChecking && (!__isValidName__(name))) { throw(new DOMException(DOMException.INVALID_CHARACTER_ERR)); } // create DOMAttr specifying 'this' as ownerDocument var node = new DOMAttr(this); // assign values to properties (and aliases) node.name = name; return node; }, createElementNS : function(namespaceURI, qualifiedName) { //$log("DOMDocument.createElement( "+namespaceURI+", "+qualifiedName+" )"); // test for exceptions if (this.ownerDocument.implementation.errorChecking) { // throw Exception if the Namespace is invalid if (!__isValidNamespace__(this, namespaceURI, qualifiedName)) { throw(new DOMException(DOMException.NAMESPACE_ERR)); } // throw Exception if the qualifiedName string contains an illegal character if (!__isValidName__(qualifiedName)) { throw(new DOMException(DOMException.INVALID_CHARACTER_ERR)); } } // create DOMElement specifying 'this' as ownerDocument var node = new DOMElement(this); var qname = __parseQName__(qualifiedName); // assign values to properties (and aliases) node.namespaceURI = namespaceURI; node.prefix = qname.prefix; node.localName = qname.localName; node.tagName = qualifiedName; return node; }, createAttributeNS : function(namespaceURI, qualifiedName) { // test for exceptions if (this.ownerDocument.implementation.errorChecking) { // throw Exception if the Namespace is invalid if (!__isValidNamespace__(this, namespaceURI, qualifiedName, true)) { throw(new DOMException(DOMException.NAMESPACE_ERR)); } // throw Exception if the qualifiedName string contains an illegal character if (!__isValidName__(qualifiedName)) { throw(new DOMException(DOMException.INVALID_CHARACTER_ERR)); } } // create DOMAttr specifying 'this' as ownerDocument var node = new DOMAttr(this); var qname = __parseQName__(qualifiedName); // assign values to properties (and aliases) node.namespaceURI = namespaceURI; node.prefix = qname.prefix; node.localName = qname.localName; node.name = qualifiedName; node.nodeValue = ""; return node; }, createNamespace : function(qualifiedName) { // create DOMNamespace specifying 'this' as ownerDocument var node = new DOMNamespace(this); var qname = __parseQName__(qualifiedName); // assign values to properties (and aliases) node.prefix = qname.prefix; node.localName = qname.localName; node.name = qualifiedName; node.nodeValue = ""; return node; }, getElementById : function(elementId) { var retNode = null, node; // loop through all Elements in the 'all' collection var all = this.all; for (var i=0; i < all.length; i++) { node = all[i]; // if id matches & node is alive (ie, connected (in)directly to the documentElement) if (node.id == elementId) { if((node.ownerDocument.documentElement._id == this.documentElement._id)){ retNode = node; //$log("Found node with id = " + node.id); break; } } } if(retNode == null){$log("Couldn't find id " + elementId);} return retNode; }, normalizeDocument: function(){ this.documentElement.normalize(); }, get nodeType(){ return DOMNode.DOCUMENT_NODE; }, get xml(){ return this.documentElement.xml; }, toString: function(){ return "Document" + (typeof this._url == "string" ? ": " + this._url : ""); }, get defaultView(){ //TODO: why isnt this just 'return $w;'? return { getComputedStyle: function(elem){ return { getPropertyValue: function(prop){ prop = prop.replace(/\-(\w)/g,function(m,c){ return c.toUpperCase(); }); var val = elem.style[prop]; if ( prop == "opacity" && val == "" ){ val = "1"; }return val; }}; }}; }, _genId : function() { this._lastId += 1; // increment lastId (to generate unique id) return this._lastId; } }); var __isValidNamespace__ = function(doc, namespaceURI, qualifiedName, isAttribute) { if (doc._performingImportNodeOperation == true) { //we're doing an importNode operation (or a cloneNode) - in both cases, there //is no need to perform any namespace checking since the nodes have to have been valid //to have gotten into the DOM in the first place return true; } var valid = true; // parse QName var qName = __parseQName__(qualifiedName); //only check for namespaces if we're finished parsing if (this._parseComplete == true) { // if the qualifiedName is malformed if (qName.localName.indexOf(":") > -1 ){ valid = false; } if ((valid) && (!isAttribute)) { // if the namespaceURI is not null if (!namespaceURI) { valid = false; } } // if the qualifiedName has a prefix if ((valid) && (qName.prefix == "")) { valid = false; } } // if the qualifiedName has a prefix that is "xml" and the namespaceURI is // different from "http://www.w3.org/XML/1998/namespace" [Namespaces]. if ((valid) && (qName.prefix == "xml") && (namespaceURI != "http://www.w3.org/XML/1998/namespace")) { valid = false; } return valid; }; $log("Defining HTMLDocument"); /* * HTMLDocument - DOM Level 2 * The Document object is not directly */ $w.__defineGetter__("HTMLDocument", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); /** * @class HTMLDocument - The Document interface represents the entire HTML or XML document. * Conceptually, it is the root of the document tree, and provides the primary access to the document's data. * * @extends DOMDocument */ var HTMLDocument = function(implementation) { this.DOMDocument = DOMDocument; this.DOMDocument(implementation); this.title = ""; this._refferer = ""; this._domain; this._open = false; }; HTMLDocument.prototype = new DOMDocument; __extend__(HTMLDocument.prototype, { createElement: function(tagName){ //$log("HTMLDocument.createElement( "+tagName+" )"); // throw Exception if the tagName string contains an illegal character if (this.ownerDocument.implementation.errorChecking && (!__isValidName__(tagName))) { throw(new DOMException(DOMException.INVALID_CHARACTER_ERR)); } tagName = tagName.toUpperCase(); //$log("HTMLDocument.createElement( "+tagName+" )"); // create DOMElement specifying 'this' as ownerDocument //This is an html document so we need to use explicit interfaces per the if( tagName.match(/^A$/)) {node = new HTMLAnchorElement(this);} else if(tagName.match(/AREA/)) {node = new HTMLAreaElement(this);} else if(tagName.match(/BASE/)) {node = new HTMLBaseElement(this);} else if(tagName.match(/BLOCKQUOTE|Q/)) {node = new HTMLQuoteElement(this);} else if(tagName.match(/BODY/)) {node = new HTMLElement(this);} else if(tagName.match(/BR/)) {node = new HTMLElement(this);} else if(tagName.match(/BUTTON/)) {node = new HTMLButtonElement(this);} else if(tagName.match(/CAPTION/)) {node = new HTMLElement(this);} else if(tagName.match(/COL|COLGROUP/)) {node = new HTMLTableColElement(this);} else if(tagName.match(/DEL|INS/)) {node = new HTMLModElement(this);} else if(tagName.match(/DIV/)) {node = new HTMLElement(this);} else if(tagName.match(/DL/)) {node = new HTMLElement(this);} else if(tagName.match(/FIELDSET/)) {node = new HTMLFieldSetElement(this);} else if(tagName.match(/FORM/)) {node = new HTMLFormElement(this);} else if(tagName.match(/^FRAME$/)) {node = new HTMLFrameElement(this);} else if(tagName.match(/FRAMESET/)) {node = new HTMLFrameSetElement(this);} else if(tagName.match(/H1|H2|H3|H4|H5|H6/)) {node = new HTMLElement(this);} else if(tagName.match(/HEAD/)) {node = new HTMLHeadElement(this);} else if(tagName.match(/HR/)) {node = new HTMLElement(this);} else if(tagName.match(/HTML/)) {node = new HTMLElement(this);} else if(tagName.match(/IFRAME/)) {node = new HTMLIFrameElement(this);} else if(tagName.match(/IMG/)) {node = new HTMLImageElement(this);} else if(tagName.match(/INPUT/)) {node = new HTMLInputElement(this);} else if(tagName.match(/LABEL/)) {node = new HTMLLabelElement(this);} else if(tagName.match(/LEGEND/)) {node = new HTMLLegendElement(this);} else if(tagName.match(/^LI$/)) {node = new HTMLElement(this);} else if(tagName.match(/LINK/)) {node = new HTMLLinkElement(this);} else if(tagName.match(/MAP/)) {node = new HTMLMapElement(this);} else if(tagName.match(/META/)) {node = new HTMLMetaElement(this);} else if(tagName.match(/OBJECT/)) {node = new HTMLObjectElement(this);} else if(tagName.match(/OL/)) {node = new HTMLElement(this);} else if(tagName.match(/OPTGROUP/)) {node = new HTMLOptGroupElement(this);} else if(tagName.match(/OPTION/)) {node = new HTMLOptionElement(this);;} else if(tagName.match(/^P$/)) {node = new HTMLElement(this);} else if(tagName.match(/PARAM/)) {node = new HTMLParamElement(this);} else if(tagName.match(/PRE/)) {node = new HTMLElement(this);} else if(tagName.match(/SCRIPT/)) {node = new HTMLScriptElement(this);} else if(tagName.match(/SELECT/)) {node = new HTMLSelectElement(this);} else if(tagName.match(/STYLE/)) {node = new HTMLStyleElement(this);} else if(tagName.match(/TABLE/)) {node = new HTMLElement(this);} else if(tagName.match(/TBODY|TFOOT|THEAD/)) {node = new HTMLElement(this);} else if(tagName.match(/TD|TH/)) {node = new HTMLElement(this);} else if(tagName.match(/TEXTAREA/)) {node = new HTMLElement(this);} else if(tagName.match(/TITLE/)) {node = new HTMLElement(this);} else if(tagName.match(/TR/)) {node = new HTMLElement(this);} else if(tagName.match(/UL/)) {node = new HTMLElement(this);} else{ node = new HTMLElement(this); } // assign values to properties (and aliases) node.tagName = tagName; return node; }, get anchors(){ return new HTMLCollection(this.getElementsByTagName('a'), 'Anchor'); }, get applets(){ return new HTMLCollection(this.getElementsByTagName('applet'), 'Applet'); }, get body(){ var nodelist = this.getElementsByTagName('body'); return nodelist.item(0); }, set body(html){ return this.replaceNode(this.body,html); }, //set/get cookie see cookie.js get domain(){ return this._domain||window.location.domain; }, set domain(){ /* TODO - requires a bit of thought to enforce domain restrictions */ return; }, get forms(){ $log("document.forms"); return new HTMLCollection(this.getElementsByTagName('form'), 'Form'); }, get images(){ return new HTMLCollection(this.getElementsByTagName('img'), 'Image'); }, get lastModified(){ /* TODO */ return this._lastModified; }, get links(){ return new HTMLCollection(this.getElementsByTagName('a'), 'Link'); }, get location(){ return $w.location }, get referrer(){ /* TODO */ return this._refferer; }, get URL(){ /* TODO*/ return this._url; }, close : function(){ /* TODO */ this._open = false; }, getElementsByName : function(name){ //$debug("document.getElementsByName ( "+name+" )"); //returns a real Array + the DOMNodeList var retNodes = __extend__([],new DOMNodeList(this, this.documentElement)), node; // loop through all Elements in the 'all' collection var all = this.all; for (var i=0; i < all.length; i++) { node = all[i]; if (node.nodeType == DOMNode.ELEMENT_NODE && node.getAttribute('name') == name) { //$log("Found node by name " + name); retNodes.push(node); } } return retNodes; }, open : function(){ /* TODO */ this._open = true; }, write: function(htmlstring){ /* TODO */ return; }, writeln: function(htmlstring){ this.write(htmlstring+'\n'); }, toString: function(){ return "Document" + (typeof this._url == "string" ? ": " + this._url : ""); }, get innerHTML(){ return this.documentElement.outerHTML; }, get __html__(){ return true; } }); //This is useful as html elements that modify the dom must also run through the new //nodes and determine if they are javascript tags and load it. This is really the fun //parts! ;) function __execScripts__( node ) { if ( node.nodeName == "SCRIPT" ) { if ( !node.getAttribute("src") ) { eval.call( window, node.textContent ); } } else { var scripts = node.getElementsByTagName("script"); for ( var i = 0; i < scripts.length; i++ ) { __execScripts__( node ); } } };$log("Defining HTMLElement"); /* * HTMLElement - DOM Level 2 */ $w.__defineGetter__("HTMLElement", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); var HTMLElement = function(ownerDocument) { //$log("\tcreating html element"); this.DOMElement = DOMElement; this.DOMElement(ownerDocument); //$log("\nfinished creating html element"); this.$css2props = null; }; HTMLElement.prototype = new DOMElement; __extend__(HTMLElement.prototype, { get className() { return this.getAttribute("class")||""; }, set className(val) { return this.setAttribute("class",trim(val)); }, get dir() { return this.getAttribute("dir")||"ltr"; }, set dir(val) { return this.setAttribute("dir",val); }, get innerHTML(){ return this.childNodes.xml; }, set innerHTML(html){ //$debug("htmlElement.innerHTML("+html+")"); //Should be replaced with HTMLPARSER usage var doc = new DOMParser(). parseFromString('<div>'+html+'</div>'); var parent = this.ownerDocument.importNode(doc.documentElement, true); //$log("\n\nIMPORTED HTML:\n\n"+nodes.xml); while(this.firstChild != null){ //$log('innerHTML - removing child '+ this.firstChild.xml); this.removeChild( this.firstChild ); } while(parent.firstChild != null){ //$log('innerHTML - appending child '+ parent.firstChild.xml); this.appendChild( parent.removeChild( parent.firstChild ) ); } //Mark for garbage collection doc = null; }, get lang() { return this.getAttribute("lang")||""; }, set lang(val) { return this.setAttribute("lang",val); }, get offsetHeight(){ return Number(this.style["height"].replace("px","")); }, get offsetWidth(){ return Number(this.style["width"].replace("px","")); }, offsetLeft: 0, offsetRight: 0, get offsetParent(){ /* TODO */ return; }, set offsetParent(element){ /* TODO */ return; }, scrollHeight: 0, scrollWidth: 0, scrollLeft: 0, scrollRight: 0, get style(){ if(this.$css2props === null){ $log("Initializing new css2props for html element : " + this.getAttribute("style")); this.$css2props = new CSS2Properties({ cssText:this.getAttribute("style") }); } return this.$css2props }, get title() { return this.getAttribute("title")||""; }, set title(val) { return this.setAttribute("title",val); }, //Not in the specs but I'll leave it here for now. get outerHTML(){ return this.xml; }, scrollIntoView: function(){ /*TODO*/ return; }, onclick: function(event){ try{ eval(this.getAttribute('onclick')); }catch(e){ $error(e); } }, ondblclick: function(event){ try{ eval(this.getAttribute('ondblclick')); }catch(e){ $error(e) } }, onkeydown: function(event){ try{ eval(this.getAttribute('onkeydown')); }catch(e){ $error(e); } }, onkeypress: function(event){ try{ eval(this.getAttribute('onkeypress')); }catch(e){ $error(e);}}, onkeyup: function(event){ try{ eval(this.getAttribute('onkeyup')); }catch(e){ $error(e);}}, onmousedown: function(event){ try{ eval(this.getAttribute('onmousedown')); }catch(e){ $error(e);}}, onmousemove: function(event){ try{ eval(this.getAttribute('onmousemove')); }catch(e){ $error(e);}}, onmouseout: function(event){ try{ eval(this.getAttribute('onmouseout')); }catch(e){ $error(e);}}, onmouseover: function(event){ try{ eval(this.getAttribute('onmouseover')); }catch(e){ $error(e);}}, onmouseup: function(event){ try{ eval(this.getAttribute('onmouseup')); }catch(e){ $error(e);}} }); var __registerEventAttrs__ = function(elm){ if(elm.hasAttribute('onclick')){ elm.addEventListener('click', elm.onclick ); } if(elm.hasAttribute('ondblclick')){ elm.addEventListener('dblclick', elm.onclick ); } if(elm.hasAttribute('onkeydown')){ elm.addEventListener('keydown', elm.onclick ); } if(elm.hasAttribute('onkeypress')){ elm.addEventListener('keypress', elm.onclick ); } if(elm.hasAttribute('onkeyup')){ elm.addEventListener('keyup', elm.onclick ); } if(elm.hasAttribute('onmousedown')){ elm.addEventListener('mousedown', elm.onclick ); } if(elm.hasAttribute('onmousemove')){ elm.addEventListener('mousemove', elm.onclick ); } if(elm.hasAttribute('onmouseout')){ elm.addEventListener('mouseout', elm.onclick ); } if(elm.hasAttribute('onmouseover')){ elm.addEventListener('mouseover', elm.onclick ); } if(elm.hasAttribute('onmouseup')){ elm.addEventListener('mouseup', elm.onclick ); } return elm; }; var __click__ = function(element){ var event = new Event({ target:element, currentTarget:element }); event.initEvent("click"); element.dispatchEvent(event); }; var __submit__ = function(element){ var event = new Event({ target:element, currentTarget:element }); event.initEvent("submit"); element.dispatchEvent(event); }; var __focus__ = function(element){ var event = new Event({ target:element, currentTarget:element }); event.initEvent("focus"); element.dispatchEvent(event); }; var __blur__ = function(element){ var event = new Event({ target:element, currentTarget:element }); event.initEvent("blur"); element.dispatchEvent(event); }; $log("Defining HTMLCollection"); /* * HTMLCollection - DOM Level 2 */ $w.__defineGetter__("HTMLCollection", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); /*var HTMLCollection = function(nodelist, type){ var $items = [], $item, i; if(type === "Anchor" ){ for(i=0;i<nodelist.length;i++){ //The name property is required to be add to the collection if(nodelist.item(i).name){ item = new nodelist.item(i); $items.push(item); this[nodelist.item(i).name] = item; } } }else if(type === "Link"){ for(i=0;i<nodelist.length;i++){ //The name property is required to be add to the collection if(nodelist.item(i).href){ item = new nodelist.item(i); $items.push(item); this[nodelist.item(i).name] = item; } } }else if(type === "Form"){ for(i=0;i<nodelist.length;i++){ //The name property is required to be add to the collection if(nodelist.item(i).href){ item = new nodelist.item(i); $items.push(item); this[nodelist.item(i).name] = item; } } } setArray(this, $items); return __extend__(this, { item : function(i){return this[i];}, namedItem : function(name){return this[name];} }); };*/ $log("Defining HTMLAnchorElement"); /* * HTMLAnchorElement - DOM Level 2 */ $w.__defineGetter__("HTMLAnchorElement", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); var HTMLAnchorElement = function(ownerDocument) { //$log("creating anchor element"); this.HTMLElement = HTMLElement; this.HTMLElement(ownerDocument); }; HTMLAnchorElement.prototype = new HTMLElement; __extend__(HTMLAnchorElement.prototype, { get accessKey() { return this.getAttribute("accesskey") || ""; }, set accessKey(val) { return this.setAttribute("accesskey",val); }, get charset() { return this.getAttribute("charset") || ""; }, set charset(val) { return this.setAttribute("charset",val); }, get coords() { return this.getAttribute("coords") || ""; }, set coords(val) { return this.setAttribute("coords",val); }, get href() { return this.getAttribute("href") || ""; }, set href(val) { return this.setAttribute("href",val); }, get hreflang() { return this.getAttribute("hreflang") || ""; }, set hreflang(val) { return this.setAttribute("hreflang",val); }, get name() { return this.getAttribute("name") || ""; }, set name(val) { return this.setAttribute("name",val); }, get rel() { return this.getAttribute("rel") || ""; }, set rel(val) { return this.setAttribute("rel",val); }, get rev() { return this.getAttribute("rev") || ""; }, set rev(val) { return this.setAttribute("rev",val); }, get shape() { return this.getAttribute("shape") || ""; }, set shape(val) { return this.setAttribute("shape",val); }, get tabIndex() { return this.getAttribute("tabindex") || ""; }, set tabIndex(val) { return this.setAttribute("tabindex",val); }, get target() { return this.getAttribute("target") || ""; }, set target(val) { return this.setAttribute("target",val); }, get type() { return this.getAttribute("type") || ""; }, set type(val) { return this.setAttribute("type",val); }, blur:function(){ __blur__(this); }, focus:function(){ __focus__(this); } }); $log("Defining Anchor"); /* * Anchor - DOM Level 2 */ $w.__defineGetter__("Anchor", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); var Anchor = function(ownerDocument) { //$log("creating anchor element"); this.HTMLAnchorElement = HTMLAnchorElement; this.HTMLAnchorElement(ownerDocument); }; Anchor.prototype = new Anchor; (function(){ //static regular expressions var hash = new RegExp('(\\#.*)'), hostname = new RegExp('\/\/([^\:\/]+)'), pathname = new RegExp('(\/[^\\?\\#]*)'), port = new RegExp('\:(\\d+)\/'), protocol = new RegExp('(^\\w*\:)'), search = new RegExp('(\\?[^\\#]*)'); __extend__(Anchor.prototype, { get hash(){ var m = hash.exec(this.href); return m&&m.length>1?m[1]:""; }, set hash(_hash){ //setting the hash is the only property of the location object //that doesn't cause the window to reload _hash = _hash.indexOf('#')===0?_hash:"#"+_hash; this.href = this.protocol + this.host + this.pathname + this.search + _hash; }, get host(){ return this.hostname + (this.port !== "")?":"+this.port:""; }, set host(_host){ this.href = this.protocol + _host + this.pathname + this.search + this.hash; }, get hostname(){ var m = hostname.exec(this.href); return m&&m.length>1?m[1]:""; }, set hostname(_hostname){ this.href = this.protocol + _hostname + ((this.port==="")?"":(":"+this.port)) + this.pathname + this.search + this.hash; }, get pathname(){ var m = this.href; m = pathname.exec(m.substring(m.indexOf(this.hostname))); return m&&m.length>1?m[1]:"/"; }, set pathname(_pathname){ this.href = this.protocol + this.host + _pathname + this.search + this.hash; }, get port(){ var m = port.exec(this.href); return m&&m.length>1?m[1]:""; }, set port(_port){ this.href = this.protocol + this.hostname + ":"+_port + this.pathname + this.search + this.hash; }, get protocol(){ return protocol.exec(this.href)[0]; }, set protocol(_protocol){ this.href = _protocol + this.host + this.pathname + this.search + this.hash; }, get search(){ var m = search.exec(this.href); return m&&m.length>1?m[1]:""; }, set search(_search){ this.href = this.protocol + this.host + this.pathname + _search + this.hash; } }); })(); $log("Defining HTMLAreaElement"); /* * HTMLAreaElement - DOM Level 2 */ $w.__defineGetter__("HTMLAreaElement", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); var HTMLAreaElement = function(ownerDocument) { //$log("creating anchor element"); this.HTMLElement = HTMLElement; this.HTMLElement(ownerDocument); }; HTMLAreaElement.prototype = new HTMLElement; __extend__(HTMLAreaElement.prototype, { get accessKey(){ return this.getAttribute('accesskey'); }, set accessKey(value){ this.setAttribute('accesskey',value); }, get alt(){ return this.getAttribute('alt'); }, set alt(value){ this.setAttribute('alt',value); }, get coords(){ return this.getAttribute('coords'); }, set coords(value){ this.setAttribute('coords',value); }, get href(){ return this.getAttribute('href'); }, set href(value){ this.setAttribute('href',value); }, get noHref(){ return this.hasAttribute('href'); }, get shape(){ //TODO return 0; }, get tabIndex(){ return this.getAttribute('tabindex'); }, set tabIndex(value){ this.setAttribute('tabindex',value); }, get target(){ return this.getAttribute('target'); }, set target(value){ this.setAttribute('target',value); } }); $log("Defining HTMLBaseElement"); /* * HTMLBaseElement - DOM Level 2 */ $w.__defineGetter__("HTMLBaseElement", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); var HTMLBaseElement = function(ownerDocument) { //$log("creating anchor element"); this.HTMLElement = HTMLElement; this.HTMLElement(ownerDocument); }; HTMLBaseElement.prototype = new HTMLElement; __extend__(HTMLBaseElement.prototype, { get href(){ return this.getAttribute('href'); }, set href(value){ this.setAttribute('href',value); }, get target(){ return this.getAttribute('target'); }, set target(value){ this.setAttribute('target',value); } }); $log("Defining HTMLQuoteElement"); /* * HTMLQuoteElement - DOM Level 2 */ $w.__defineGetter__("HTMLQuoteElement", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); var HTMLQuoteElement = function(ownerDocument) { //$log("creating anchor element"); this.HTMLElement = HTMLElement; this.HTMLElement(ownerDocument); }; HTMLQuoteElement.prototype = new HTMLElement; __extend__(HTMLQuoteElement.prototype, { get cite(){ return this.getAttribute('cite'); }, set cite(value){ this.setAttribute('cite',value); } }); $log("Defining HTMLButtonElement"); /* * HTMLButtonElement - DOM Level 2 */ $w.__defineGetter__("HTMLButtonElement", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); var HTMLButtonElement = function(ownerDocument) { //$log("creating anchor element"); this.HTMLElement = HTMLElement; this.HTMLElement(ownerDocument); }; HTMLButtonElement.prototype = new HTMLElement; __extend__(HTMLButtonElement.prototype, { get form(){ var parent = this.parent; while(parent.nodeName.toLowerCase() != 'form'){ parent = parent.parent; } return parent; }, get accessKey(){ return this.getAttribute('accesskey'); }, set accessKey(value){ this.setAttribute('accesskey',value); }, get tabIndex(){ return Number(this.getAttribute('tabindex')); }, set tabIndex(value){ this.setAttribute('tabindex',Number(value)); }, get type(){ return this.getAttribute('type'); }, set type(value){ this.setAttribute('type',value); }, get value(){ return this.getAttribute('value'); }, set value(value){ this.setAttribute('value',value); } }); $log("Defining HTMLTableColElement"); /* * HTMLTableColElement - DOM Level 2 */ $w.__defineGetter__("HTMLTableColElement", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); var HTMLTableColElement = function(ownerDocument) { //$log("creating anchor element"); this.HTMLElement = HTMLElement; this.HTMLElement(ownerDocument); }; HTMLTableColElement.prototype = new HTMLElement; __extend__(HTMLTableColElement.prototype, { get align(){ return this.getAttribute('align'); }, set align(value){ this.setAttribute('align', value); }, get ch(){ return this.getAttribute('ch'); }, set ch(value){ this.setAttribute('ch', value); }, get chOff(){ return this.getAttribute('ch'); }, set chOff(value){ this.setAttribute('ch', value); }, get span(){ return this.getAttribute('span'); }, set span(value){ this.setAttribute('span', value); }, get vAlign(){ return this.getAttribute('valign'); }, set vAlign(value){ this.setAttribute('valign', value); }, get width(){ return this.getAttribute('width'); }, set width(value){ this.setAttribute('width', value); } }); $log("Defining HTMLModElement"); /* * HTMLModElement - DOM Level 2 */ $w.__defineGetter__("HTMLModElement", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); var HTMLModElement = function(ownerDocument) { //$log("creating anchor element"); this.HTMLElement = HTMLElement; this.HTMLElement(ownerDocument); }; HTMLModElement.prototype = new HTMLElement; __extend__(HTMLModElement.prototype, { get cite(){ return this.getAttribute('cite'); }, set cite(value){ this.setAttribute('cite', value); }, get dateTime(){ return this.getAttribute('datetime'); }, set dateTime(value){ this.setAttribute('datetime', value); } }); $log("Defining HTMLFieldSetElement"); /* * HTMLFieldSetElement - DOM Level 2 */ $w.__defineGetter__("HTMLFieldSetElement", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); var HTMLFieldSetElement = function(ownerDocument) { //$log("creating anchor element"); this.HTMLElement = HTMLElement; this.HTMLElement(ownerDocument); }; HTMLFieldSetElement.prototype = new HTMLElement; __extend__(HTMLFieldSetElement.prototype, { get form(){ var parent = this.parent; while(parent.nodeName.toLowerCase() != 'form'){ parent = parent.parent; } return parent; } }); $log("Defining HTMLFormElement"); /* * HTMLAnchorElement - DOM Level 2 */ $w.__defineGetter__("Form", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); $w.__defineGetter__("HTMLFormElement", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); var HTMLFormElement = function(ownerDocument){ this.HTMLElement = HTMLElement; this.HTMLElement(ownerDocument); }; HTMLFormElement.prototype = new HTMLElement; __extend__(HTMLFormElement.prototype,{ get acceptCharset(){ return this.getAttribute('accept-charset'); }, set acceptCharset(acceptCharset){ this.setAttribute('accept-charset', acceptCharset); }, get action(){ return this.getAttribute('action'); }, set action(action){ this.setAttribute('action', action); }, get elements() { return this.getElementsByTagName("*"); }, get enctype(){ return this.getAttribute('enctype'); }, set enctype(enctype){ this.setAttribute('enctype', enctype); }, get length() { return this.elements.length; }, get method(){ return this.getAttribute('method'); }, set method(action){ this.setAttribute('method', method); }, get name() { return this.getAttribute("name") || ""; }, set name(val) { return this.setAttribute("name",val); }, get target() { return this.getAttribute("target") || ""; }, set target(val) { return this.setAttribute("target",val); }, submit:function(){ __submit__(this); }, reset:function(){ __reset__(this); } }); $log("Defining HTMLFrameElement"); /* * HTMLFrameElement - DOM Level 2 */ $w.__defineGetter__("HTMLFrameElement", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); var HTMLFrameElement = function(ownerDocument) { //$log("creating frame element"); this.HTMLElement = HTMLElement; this.HTMLElement(ownerDocument); }; HTMLFrameElement.prototype = new HTMLElement; __extend__(HTMLFrameElement.prototype, { get frameBorder(){ return this.getAttribute('border')||""; }, set frameBorder(value){ this.setAttribute('border', value); }, get longDesc(){ return this.getAttribute('longdesc')||""; }, set longDesc(value){ this.setAttribute('longdesc', value); }, get marginHeight(){ return this.getAttribute('marginheight')||""; }, set marginHeight(value){ this.setAttribute('marginheight', value); }, get marginWidth(){ return this.getAttribute('marginwidth')||""; }, set marginWidth(value){ this.setAttribute('marginwidth', value); }, get name(){ return this.getAttribute('name')||""; }, set name(value){ this.setAttribute('name', value); }, get noResize(){ return this.getAttribute('noresize')||""; }, set noResize(value){ this.setAttribute('noresize', value); }, get scrolling(){ return this.getAttribute('scrolling')||""; }, set scrolling(value){ this.setAttribute('scrolling', value); }, get src(){ return this.getAttribute('src')||""; }, set src(value){ this.setAttribute('src', value); }, get contentDocument(){ $log("getting content document for (i)frame"); if(!this._content){ this._content = new HTMLDocument($implementation); if(this.src.length > 0){ $log("Loading frame content from " + this.src); try{ this._content.load(this.src); }catch(e){ $error("failed to load " + this.src); } } } return true; } }); $log("Defining HTMLFrameSetElement"); /* * HTMLFrameSetElement - DOM Level 2 */ $w.__defineGetter__("HTMLFrameSetElement", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); var HTMLFrameSetElement = function(ownerDocument) { //$log("creating anchor element"); this.HTMLElement = HTMLElement; this.HTMLElement(ownerDocument); }; HTMLFrameSetElement.prototype = new HTMLElement; __extend__(HTMLFrameSetElement.prototype, { get cols(){ return this.getAttribute('cols'); }, set cols(value){ this.setAttribute('cols', value); }, get rows(){ return this.getAttribute('rows'); }, set rows(value){ this.setAttribute('rows', value); } }); $log("Defining HTMLHeadElement"); /* * HTMLHeadElement - DOM Level 2 */ $w.__defineGetter__("HTMLHeadElement", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); var HTMLHeadElement = function(ownerDocument) { this.HTMLElement = HTMLElement; this.HTMLElement(ownerDocument); }; HTMLHeadElement.prototype = new HTMLElement; __extend__(HTMLHeadElement.prototype, { get profile(){ return this.getAttribute('profile'); }, set profile(value){ this.setAttribute('profile', value); }, }); $log("Defining HTMLIFrameElement"); /* * HTMLIFrameElement - DOM Level 2 */ $w.__defineGetter__("HTMLIFrameElement", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); var HTMLIFrameElement = function(ownerDocument) { //$log("creating iframe element"); this.HTMLFrameElement = HTMLFrameElement; this.HTMLFrameElement(ownerDocument); }; HTMLIFrameElement.prototype = new HTMLFrameElement; __extend__(HTMLIFrameElement.prototype, { get height() { return this.getAttribute("height") || ""; }, set height(val) { return this.setAttribute("height",val); }, get width() { return this.getAttribute("width") || ""; }, set width(val) { return this.setAttribute("width",val); } }); $log("Defining HTMLImageElement"); /* * HTMLImageElement - DOM Level 2 */ $w.__defineGetter__("HTMLImageElement", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); var HTMLImageElement = function(ownerDocument) { this.HTMLElement = HTMLElement; this.HTMLElement(ownerDocument); }; HTMLImageElement.prototype = new HTMLElement; __extend__(HTMLImageElement.prototype, { get alt(){ return this.getAttribute('alt'); }, set alt(value){ this.setAttribute('alt', value); }, get height(){ return this.getAttribute('height'); }, set height(value){ this.setAttribute('height', value); }, get isMap(){ return this.hasAttribute('map'); }, set useMap(value){ this.setAttribute('map', value); }, get longDesc(){ return this.getAttribute('longdesc'); }, set longDesc(value){ this.setAttribute('longdesc', value); }, get name(){ return this.getAttribute('name'); }, set name(value){ this.setAttribute('name', value); }, get src(){ return this.getAttribute('src'); }, set src(value){ this.setAttribute('src', value); }, get width(){ return this.getAttribute('width'); }, set width(value){ this.setAttribute('width', value); } }); $log("Defining HTMLInputElement"); /* * HTMLInputElement - DOM Level 2 */ $w.__defineGetter__("HTMLInputElement", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); var HTMLInputElement = function(ownerDocument) { //$log("creating anchor element"); this.HTMLElement = HTMLElement; this.HTMLElement(ownerDocument); }; HTMLInputElement.prototype = new HTMLElement; __extend__(HTMLInputElement.prototype, { get defaultValue(){ return this.getAttribute('defaultValue'); }, set defaultValue(value){ this.setAttribute('defaultValue', value); }, get defaultChecked(){ return this.getAttribute('defaultChecked'); }, get form(){ var parent = this.parent; while(parent.nodeName.toLowerCase() != 'form'){ parent = parent.parent; } return parent; }, get accessKey(){ return this.getAttribute('accesskey'); }, set accessKey(value){ this.setAttribute('accesskey',value); }, get access(){ return this.getAttribute('access'); }, set access(value){ this.setAttribute('access', value); }, get alt(){ return this.getAttribute('alt'); }, set alt(value){ this.setAttribute('alt', value); }, get checked(){ return (this.getAttribute('checked')==='checked'); }, set checked(){ this.setAttribute('checked', 'checked'); }, get disabled(){ return (this.getAttribute('disabled')==='disabled'); }, set disabled(value){ this.setAttribute('disabled', 'disabled'); }, get maxLength(){ return Number(this.getAttribute('maxlength')||'0'); }, set maxLength(value){ this.setAttribute('maxlength', value); }, get name(){ return this.getAttribute('name')||''; }, set name(value){ this.setAttribute('name', value); }, get readOnly(){ return (this.getAttribute('readonly')==='readonly'); }, set readOnly(value){ this.setAttribute('readonly', 'readonly'); }, get size(){ return this.getAttribute('size'); }, set size(value){ this.setAttribute('size', value); }, get src(){ return this.getAttribute('src'); }, set src(value){ this.setAttribute('src', value); }, get tabIndex(){ return Number(this.getAttribute('tabindex')); }, set tabIndex(value){ this.setAttribute('tabindex',Number(value)); }, get type(){ return this.getAttribute('type'); }, set type(value){ this.setAttribute('type',value); }, get useMap(){ return this.getAttribute('map'); }, get value(){ return this.getAttribute('value'); }, set value(value){ this.setAttribute('value',value); }, blur:function(){ __blur__(this); }, focus:function(){ __focus__(this); }, select:function(){ __select__(this); }, click:function(){ __click__(this); } }); $log("Defining HTMLLabelElement"); /* * HTMLLabelElement - DOM Level 2 */ $w.__defineGetter__("HTMLLabelElement", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); var HTMLLabelElement = function(ownerDocument) { this.HTMLElement = HTMLElement; this.HTMLElement(ownerDocument); }; HTMLLabelElement.prototype = new HTMLElement; __extend__(HTMLLabelElement.prototype, { get form(){ var parent = this.parent; while(parent.nodeName.toLowerCase() != 'form'){ parent = parent.parent; } return parent; }, get accessKey(){ return this.getAttribute('accesskey'); }, set accessKey(value){ this.setAttribute('accesskey',value); }, get htmlFor(){ return this.getAttribute('for'); }, set htmlFor(value){ this.setAttribute('for',value); }, }); $log("Defining HTMLLegendElement"); /* * HTMLLegendElement - DOM Level 2 */ $w.__defineGetter__("HTMLLegendElement", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); var HTMLLegendElement = function(ownerDocument) { this.HTMLElement = HTMLElement; this.HTMLElement(ownerDocument); }; HTMLLegendElement.prototype = new HTMLElement; __extend__(HTMLLegendElement.prototype, { get form(){ var parent = this.parent; while(parent.nodeName.toLowerCase() != 'form'){ parent = parent.parent; } return parent; }, get accessKey(){ return this.getAttribute('accesskey'); }, set accessKey(value){ this.setAttribute('accesskey',value); } }); /** * Link - HTMLElement */ $w.__defineGetter__("Link", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); $log("Defining HTMLLinkElement"); /* * HTMLLinkElement - DOM Level 2 */ $w.__defineGetter__("HTMLLinkElement", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); var HTMLLinkElement = function(ownerDocument) { //$log("creating anchor element"); this.HTMLElement = HTMLElement; this.HTMLElement(ownerDocument); }; HTMLLinkElement.prototype = new HTMLElement; __extend__(HTMLLinkElement.prototype, { get disabled(){ return this.getAttribute('disabled'); }, set disabled(value){ this.setAttribute('disabled',value); }, get charset(){ return this.getAttribute('charset'); }, set charset(value){ this.setAttribute('charset',value); }, get href(){ return this.getAttribute('href'); }, set href(value){ this.setAttribute('href',value); }, get hreflang(){ return this.getAttribute('hreflang'); }, set hreflang(value){ this.setAttribute('hreflang',value); }, get media(){ return this.getAttribute('media'); }, set media(value){ this.setAttribute('media',value); }, get rel(){ return this.getAttribute('rel'); }, set rel(value){ this.setAttribute('rel',value); }, get rev(){ return this.getAttribute('rev'); }, set rev(value){ this.setAttribute('rev',value); }, get target(){ return this.getAttribute('target'); }, set target(value){ this.setAttribute('target',value); }, get type(){ return this.getAttribute('type'); }, set type(value){ this.setAttribute('type',value); } }); $log("Defining HTMLMapElement"); /* * HTMLMapElement - DOM Level 2 */ $w.__defineGetter__("HTMLMapElement", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); var HTMLMapElement = function(ownerDocument) { //$log("creating anchor element"); this.HTMLElement = HTMLElement; this.HTMLElement(ownerDocument); }; HTMLMapElement.prototype = new HTMLElement; __extend__(HTMLMapElement.prototype, { get areas(){ return this.getElementsByTagName('area'); }, get name(){ return this.getAttribute('name'); }, set name(value){ this.setAttribute('name',value); } }); $log("Defining HTMLMetaElement"); /* * HTMLMetaElement - DOM Level 2 */ $w.__defineGetter__("HTMLMetaElement", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); var HTMLMetaElement = function(ownerDocument) { this.HTMLElement = HTMLElement; this.HTMLElement(ownerDocument); }; HTMLMetaElement.prototype = new HTMLElement; __extend__(HTMLMetaElement.prototype, { get content(){ return this.getAttribute('content'); }, set content(value){ this.setAttribute('content',value); }, get httpEquiv(){ return this.getAttribute('http-equiv'); }, set httpEquiv(value){ this.setAttribute('http-equiv',value); }, get name(){ return this.getAttribute('name'); }, set name(value){ this.setAttribute('name',value); }, get scheme(){ return this.getAttribute('scheme'); }, set scheme(value){ this.setAttribute('scheme',value); } }); $log("Defining HTMLObjectElement"); /* * HTMLObjectElement - DOM Level 2 */ $w.__defineGetter__("HTMLObjectElement", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); var HTMLObjectElement = function(ownerDocument) { //$log("creating anchor element"); this.HTMLElement = HTMLElement; this.HTMLElement(ownerDocument); }; HTMLObjectElement.prototype = new HTMLElement; __extend__(HTMLObjectElement.prototype, { get code(){ return this.getAttribute('code'); }, set code(value){ this.setAttribute('code',value); }, get archive(){ return this.getAttribute('archive'); }, set archive(value){ this.setAttribute('archive',value); }, get codeBase(){ return this.getAttribute('codebase'); }, set codeBase(value){ this.setAttribute('codebase',value); }, get codeType(){ return this.getAttribute('codetype'); }, set codeType(value){ this.setAttribute('codetype',value); }, get data(){ return this.getAttribute('data'); }, set data(value){ this.setAttribute('data',value); }, get declare(){ return this.getAttribute('declare'); }, set declare(value){ this.setAttribute('declare',value); }, get height(){ return this.getAttribute('height'); }, set height(value){ this.setAttribute('height',value); }, get standby(){ return this.getAttribute('standby'); }, set standby(value){ this.setAttribute('standby',value); }, get tabIndex(){ return this.getAttribute('tabindex'); }, set tabIndex(value){ this.setAttribute('tabindex',value); }, get type(){ return this.getAttribute('type'); }, set type(value){ this.setAttribute('type',value); }, get useMap(){ return this.getAttribute('usemap'); }, set useMap(value){ this.setAttribute('usemap',value); }, get width(){ return this.getAttribute('width'); }, set width(value){ this.setAttribute('width',value); }, get contentDocument(){ return this.ownerDocument; } }); $log("Defining HTMLOptGroupElement"); /* * HTMLOptGroupElement - DOM Level 2 */ $w.__defineGetter__("HTMLOptGroupElement", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); var HTMLOptGroupElement = function(ownerDocument) { //$log("creating anchor element"); this.HTMLElement = HTMLElement; this.HTMLElement(ownerDocument); }; HTMLOptGroupElement.prototype = new HTMLElement; __extend__(HTMLOptGroupElement.prototype, { get disabled(){ return this.getAttribute('disabled'); }, set disabled(value){ this.setAttribute('disabled',value); }, get label(){ return this.getAttribute('label'); }, set label(value){ this.setAttribute('label',value); }, }); $log("Defining HTMLOptionElement"); /* * HTMLOptionElement - DOM Level 2 */ $w.__defineGetter__("HTMLOptionElement", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); var HTMLOptionElement = function(ownerDocument) { //$log("creating anchor element"); this.HTMLElement = HTMLElement; this.HTMLElement(ownerDocument); }; HTMLOptionElement.prototype = new HTMLElement; __extend__(HTMLOptionElement.prototype, { get form(){ var parent = this.parent; while(parent.nodeName.toLowerCase() != 'form'){ parent = parent.parent; } return parent; }, get defaultSelected(){ return this.getAttribute('defaultSelected'); }, set defaultSelected(value){ this.setAttribute('defaultSelected',value); }, get text(){ return this.nodeValue; }, get index(){ var options = this.parent.childNodes; for(var i; i<options.length;i++){ if(this == options[i]) return i; } return -1; }, get disabled(){ return this.getAttribute('disabled'); }, set disabled(value){ this.setAttribute('disabled',value); }, get label(){ return this.getAttribute('label'); }, set label(value){ this.setAttribute('label',value); }, get selected(){ return (this.getAttribute('selected')==='selected'); }, set selected(){ this.setAttribute('selected','selected'); }, get value(){ return this.getAttribute('value'); }, set value(value){ this.setAttribute('value',value); } }); $log("Defining HTMLParamElement"); /* * HTMLParamElement - DOM Level 2 */ $w.__defineGetter__("HTMLParamElement", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); var HTMLParamElement = function(ownerDocument) { //$log("creating anchor element"); this.HTMLElement = HTMLElement; this.HTMLElement(ownerDocument); }; HTMLParamElement.prototype = new HTMLElement; __extend__(HTMLParamElement.prototype, { get name(){ return this.getAttribute('name'); }, set name(value){ this.setAttribute('name',value); }, get type(){ return this.getAttribute('type'); }, set type(value){ this.setAttribute('type',value); }, get value(){ return this.getAttribute('value'); }, set value(value){ this.setAttribute('value',value); }, get valueType(){ return this.getAttribute('valuetype'); }, set valueType(value){ this.setAttribute('valuetype',value); }, }); $log("Defining HTMLScriptElement"); /* * HTMLScriptElement - DOM Level 2 */ $w.__defineGetter__("HTMLScriptElement", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); var HTMLScriptElement = function(ownerDocument) { //$log("creating anchor element"); this.HTMLElement = HTMLElement; this.HTMLElement(ownerDocument); $log("loading script via policy"); var _this = this; $w.setTimeout(function(){ $policy.loadScripts(_this); }, 1); }; HTMLScriptElement.prototype = new HTMLElement; __extend__(HTMLScriptElement.prototype, { get text(){ return this.nodeValue; }, get htmlFor(){ return this.getAttribute('for'); }, set htmlFor(value){ this.setAttribute('for',value); }, get event(){ return this.getAttribute('event'); }, set event(value){ this.setAttribute('event',value); }, get charset(){ return this.getAttribute('charset'); }, set charset(value){ this.setAttribute('charset',value); }, get defer(){ return this.getAttribute('defer'); }, set defer(value){ this.setAttribute('defer',value); }, get src(){ return this.getAttribute('src'); }, set src(value){ this.setAttribute('src',value); }, get type(){ return this.getAttribute('type'); }, set type(value){ this.setAttribute('type',value); } }); $log("Defining HTMLSelectElement"); /* * HTMLSelectElement - DOM Level 2 */ $w.__defineGetter__("HTMLSelectElement", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); var HTMLSelectElement = function(ownerDocument) { //$log("creating anchor element"); this.HTMLElement = HTMLElement; this.HTMLElement(ownerDocument); }; HTMLSelectElement.prototype = new HTMLElement; __extend__(HTMLSelectElement.prototype, { get type(){ return this.getAttribute('type'); }, get selectedIndex(){ var options = this.options; for(var i=0;i<options.length;i++){ if(options[i].selected){ return i; } }; return -1; }, set selectedIndex(value){ this.options[Number(value)].selected = 'selected'; }, get value(){ return this.getAttribute('value')||''; }, set value(value){ this.setAttribute('value',value); }, get length(){ return this.options.length; }, get form(){ var parent = this.parent; while(parent.nodeName.toLowerCase() != 'form'){ parent = parent.parent; } return parent; }, get options(){ return this.getElementsByTagName('option'); }, get disabled(){ return (this.getAttribute('disabled')==='disabled'); }, set disabled(){ this.setAttribute('disabled','disabled'); }, get multiple(){ return this.getAttribute('multiple'); }, set multiple(value){ this.setAttribute('multiple',value); }, get name(){ return this.getAttribute('name')||''; }, set name(value){ this.setAttribute('name',value); }, get size(){ return Number(this.getAttribute('size')); }, set size(value){ this.setAttribute('size',value); }, get tabIndex(){ return Number(this.getAttribute('tabindex')); }, set tabIndex(value){ this.setAttribute('tabindex',value); }, add : function(){ __add__(this); }, remove : function(){ __remove__(this); }, blur: function(){ __blur__(this); }, focus: function(){ __focus__(this); } }); $log("Defining HTMLStyleElement"); /* * HTMLStyleElement - DOM Level 2 */ $w.__defineGetter__("HTMLStyleElement", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); var HTMLStyleElement = function(ownerDocument) { //$log("creating anchor element"); this.HTMLElement = HTMLElement; this.HTMLElement(ownerDocument); }; HTMLStyleElement.prototype = new HTMLElement; __extend__(HTMLStyleElement.prototype, { get disabled(){ return this.getAttribute('disabled'); }, set disabled(value){ this.setAttribute('disabled',value); }, get media(){ return this.getAttribute('media'); }, set media(value){ this.setAttribute('media',value); }, get type(){ return this.getAttribute('type'); }, set type(value){ this.setAttribute('type',value); }, }); $log("Defining Event"); /* * event.js */ $w.__defineGetter__("Event", function(){ __extend__(this,{ CAPTURING_PHASE : 1, AT_TARGET : 2, BUBBLING_PHASE : 3 }); return function(){ throw new Error("Object cannot be created in this context"); }; }); var Event = function(options){ if(options === undefined){options={target:window,currentTarget:window};} __extend__(this,{ CAPTURING_PHASE : 1, AT_TARGET : 2, BUBBLING_PHASE : 3 }); $log("Creating new Event"); var $bubbles = options.bubbles?options.bubbles:true, $cancelable = options.cancelable?options.cancelable:true, $currentTarget = options.currentTarget?options.currentTarget:null, $eventPhase = options.eventPhase?options.eventPhase:Event.CAPTURING_PHASE, $target = options.eventPhase?options.eventPhase:document, $timestamp = options.timestamp?options.timestamp:new Date().getTime().toString(), $type = options.type?options.type:""; return __extend__(this,{ get bubbles(){return $bubbles;}, get cancelable(){return $cancelable;}, get currentTarget(){return $currentTarget;}, get eventPhase(){return $eventPhase;}, get target(){return $target;}, get timestamp(){return $timestamp;}, get type(){return $type;}, initEvent: function(type,bubbles,cancelable){ $type=type?type:$type; $bubbles=bubbles?bubbles:$bubbles; $cancelable=cancelable?cancelable:$cancelable; }, preventDefault: function(){return;/* TODO */}, stopPropagation: function(){return;/* TODO */} }); }; $log("Defining MouseEvent"); /* * mouseevent.js */ $log("Defining MouseEvent"); /* * uievent.js */ var $onblur, $onfocus, $onresize;/* * CSS2Properties - DOM Level 2 CSS */ $w.__defineGetter__("CSS2Properties", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); var CSS2Properties = function(options){ __extend__(this, __supportedStyles__); __cssTextToStyles__(this, options.cssText?options.cssText:""); }; //__extend__(CSS2Properties.prototype, __supportedStyles__); __extend__(CSS2Properties.prototype, { get cssText(){ return Array.prototype.apply.join(this,[';\n']); }, set cssText(cssText){ __cssTextToStyles__(this, cssText); }, getPropertyCSSValue : function(){ }, getPropertyPriority : function(){ }, getPropertyValue : function(name){ var camelCase = name.replace(/\-(\w)/g, function(all, letter){ return letter.toUpperCase(); }); var i, value = this[camelCase]; if(value === undefined){ for(i=0;i<this.length;i++){ if(this[i]===name){ return this[i]; } } } return value; }, item : function(index){ return this[index]; }, removeProperty: function(){ }, setProperty: function(){ }, toString:function(){ if (this.length >0){ return "{\n\t"+Array.prototype.join.apply(this,[';\n\t'])+"}\n"; }else{ return ''; } } }); var __cssTextToStyles__ = function(css2props, cssText){ var styleArray=[]; var style, name, value, camelCaseName, w3cName, styles = cssText.split(';'); for ( var i = 0; i < styles.length; i++ ) { //$log("Adding style property " + styles[i]); style = styles[i].split(':'); if ( style.length == 2 ){ //keep a reference to the original name of the style which was set //this is the w3c style setting method. styleArray[styleArray.length] = w3cName = styles[i]; //camel case for dash case value = trim(style[1]); camelCaseName = trim(style[0].replace(/\-(\w)/g, function(all, letter){ return letter.toUpperCase(); })); //$log('CSS Style Name: ' + camelCaseName); if(css2props[camelCaseName]!==undefined){ //set the value internally with camelcase name //$log('Setting css ' + camelCaseName + ' to ' + value); css2props[camelCaseName] = value; }; } } __setArray__(css2props, styleArray); }; //Obviously these arent all supported but by commenting out various sections //this provides a single location to configure what is exposed as supported. //These will likely need to be functional getters/setters in the future to deal with //the variation on input formulations var __supportedStyles__ = { azimuth: "", background: "", backgroundAttachment: "", backgroundColor: "", backgroundImage: "", backgroundPosition: "", backgroundRepeat: "", border: "", borderBottom: "", borderBottomColor: "", borderBottomStyle: "", borderBottomWidth: "", borderCollapse: "", borderColor: "", borderLeft: "", borderLeftColor: "", borderLeftStyle: "", borderLeftWidth: "", borderRight: "", borderRightColor: "", borderRightStyle: "", borderRightWidth: "", borderSpacing: "", borderStyle: "", borderTop: "", borderTopColor: "", borderTopStyle: "", borderTopWidth: "", borderWidth: "", bottom: "", captionSide: "", clear: "", clip: "", color: "", content: "", counterIncrement: "", counterReset: "", cssFloat: "", cue: "", cueAfter: "", cueBefore: "", cursor: "", direction: "", display: "", elevation: "", emptyCells: "", font: "", fontFamily: "", fontSize: "", fontSizeAdjust: "", fontStretch: "", fontStyle: "", fontVariant: "", fontWeight: "", height: "", left: "", letterSpacing: "", lineHeight: "", listStyle: "", listStyleImage: "", listStylePosition: "", listStyleType: "", margin: "", marginBottom: "", marginLeft: "", marginRight: "", marginTop: "", markerOffset: "", marks: "", maxHeight: "", maxWidth: "", minHeight: "", minWidth: "", opacity: 1, orphans: "", outline: "", outlineColor: "", outlineOffset: "", outlineStyle: "", outlineWidth: "", overflow: "", overflowX: "", overflowY: "", padding: "", paddingBottom: "", paddingLeft: "", paddingRight: "", paddingTop: "", page: "", pageBreakAfter: "", pageBreakBefore: "", pageBreakInside: "", pause: "", pauseAfter: "", pauseBefore: "", pitch: "", pitchRange: "", position: "", quotes: "", richness: "", right: "", size: "", speak: "", speakHeader: "", speakNumeral: "", speakPunctuation: "", speechRate: "", stress: "", tableLayout: "", textAlign: "", textDecoration: "", textIndent: "", textShadow: "", textTransform: "", top: "", unicodeBidi: "", verticalAlign: "", visibility: "", voiceFamily: "", volume: "", whiteSpace: "", widows: "", width: "", wordSpacing: "", zIndex: "" };/* * CSSRule - DOM Level 2 */ $w.__defineGetter__("CSSRule", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); var CSSRule = function(options){ var $style, $selectorText = options.selectorText?options.selectorText:""; $style = new CSS2Properties({cssText:options.cssText?options.cssText:null}); return __extend__(this, { get style(){return $style;}, get selectorText(){return $selectorText;}, set selectorText(selectorText){$selectorText = selectorText;} }); }; /* * CSSStyleSheet - DOM Level 2 */ $w.__defineGetter__("CSSStyleSheet", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); var CSSStyleSheet = function(options){ var $cssRules, $disabled = options.disabled?options.disabled:false, $href = options.href?options.href:null, $parentStyleSheet = options.parentStyleSheet?options.parentStyleSheet:null, $title = options.title?options.title:"", $type = "text/css"; function parseStyleSheet(text){ //this is pretty ugly, but text is the entire text of a stylesheet var cssRules = []; if (!text) text = ""; text = trim(text.replace(/\/\*(\r|\n|.)*\*\//g,"")); // TODO: @import ? var blocks = text.split("}"); blocks.pop(); var i, len = blocks.length; var definition_block, properties, selectors; for (i=0; i<len; i++){ definition_block = blocks[i].split("{"); if(definition_block.length === 2){ selectors = definition_block[0].split(","); for(var j=0;j<selectors.length;j++){ cssRules.push(new CSSRule({ selectorText:selectors[j], cssText:definition_block[1] })); } __setArray__($cssRules, cssRules); } } }; parseStyleSheet(options.text); return __extend__(this, { get cssRules(){return $cssRules;}, get rule(){return $cssRules;},//IE - may be deprecated get href(){return $href;}, get parentStyleSheet(){return $parentStyleSheet;}, get title(){return $title;}, get type(){return $type;}, addRule: function(selector, style, index){/*TODO*/}, deleteRule: function(index){/*TODO*/}, insertRule: function(rule, index){/*TODO*/}, removeRule: function(index){this.deleteRule(index);}//IE - may be deprecated }); }; /* * location.js * - requires env */ $log("Initializing Window Location."); //the current location var $location = $env.location('./'); $w.__defineSetter__("location", function(url){ //$w.onunload(); $location = $env.location(url); setHistory($location); $w.document.load($location); }); $w.__defineGetter__("location", function(url){ var hash = new RegExp('(\\#.*)'), hostname = new RegExp('\/\/([^\:\/]+)'), pathname = new RegExp('(\/[^\\?\\#]*)'), port = new RegExp('\:(\\d+)\/'), protocol = new RegExp('(^\\w*\:)'), search = new RegExp('(\\?[^\\#]*)'); return { get hash(){ var m = hash.exec(this.href); return m&&m.length>1?m[1]:""; }, set hash(_hash){ //setting the hash is the only property of the location object //that doesn't cause the window to reload _hash = _hash.indexOf('#')===0?_hash:"#"+_hash; $location = this.protocol + this.host + this.pathname + this.search + _hash; setHistory(_hash, "hash"); }, get host(){ return this.hostname + (this.port !== "")?":"+this.port:""; }, set host(_host){ $w.location = this.protocol + _host + this.pathname + this.search + this.hash; }, get hostname(){ var m = hostname.exec(this.href); return m&&m.length>1?m[1]:""; }, set hostname(_hostname){ $w.location = this.protocol + _hostname + ((this.port==="")?"":(":"+this.port)) + this.pathname + this.search + this.hash; }, get href(){ //This is the only env specific function return $location; }, set href(url){ $w.location = url; }, get pathname(){ var m = this.href; m = pathname.exec(m.substring(m.indexOf(this.hostname))); return m&&m.length>1?m[1]:"/"; }, set pathname(_pathname){ $w.location = this.protocol + this.host + _pathname + this.search + this.hash; }, get port(){ var m = port.exec(this.href); return m&&m.length>1?m[1]:""; }, set port(_port){ $w.location = this.protocol + this.hostname + ":"+_port + this.pathname + this.search + this.hash; }, get protocol(){ return protocol.exec(this.href)[0]; }, set protocol(_protocol){ $w.location = _protocol + this.host + this.pathname + this.search + this.hash; }, get search(){ var m = search.exec(this.href); return m&&m.length>1?m[1]:""; }, set search(_search){ $w.location = this.protocol + this.host + this.pathname + _search + this.hash; }, toString: function(){ return this.href; }, reload: function(force){ //TODO }, replace: function(url){ //TODO } }; }); /* * history.js */ $log("Initializing Window History."); $currentHistoryIndex = 0; $history = []; // Browser History $w.__defineGetter__("history", function(){ return { get length(){ return $history.length; }, back : function(count){ if(count){ go(-count); }else{go(-1);} }, forward : function(count){ if(count){ go(count); }else{go(1);} }, go : function(target){ if(typeof target == "number"){ target = $currentHistoryIndex+target; if(target > -1 && target < $history.length){ if($history[target].location == "hash"){ $w.location.hash = $history[target].value; }else{ $w.location = $history[target].value; } $currentHistoryIndex = target; //remove the last item added to the history //since we are moving inside the history $history.pop(); } }else{ //TODO: walk throu the history and find the 'best match' } } }; }); //Here locationPart is the particutlar method/attribute // of the location object that was modified. This allows us // to modify the correct portion of the location object // when we navigate the history var setHistory = function( value, locationPart){ $log("adding value to history: " +value); $currentHistoryIndex++; $history.push({ location: locationPart||"href", value: value }); }; /* * navigator.js * - requires env */ $log("Initializing Window Navigator."); var $appCodeName = $env.appCodeName;//eg "Mozilla" var $appName = $env.appName;//eg "Gecko/20070309 Firefox/2.0.0.3" // Browser Navigator $w.__defineGetter__("navigator", function(){ return { get appCodeName(){ return $appCodeName; }, get appName(){ return $appName; }, get appVersion(){ return $version +" ("+ $w.navigator.platform +"; "+ "U; "+//? $env.os_name+" "+$env.os_arch+" "+$env.os_version+"; "+ $env.lang+"; "+ "rv:"+$revision+ ")"; }, get cookieEnabled(){ return true; }, get mimeTypes(){ return []; }, get platform(){ return $env.platform; }, get plugins(){ return []; }, get userAgent(){ return $w.navigator.appCodeName + "/" + $w.navigator.appVersion + " " + $w.navigator.appName; }, javaEnabled : function(){ return $env.javaEnabled; } }; }); /* * timer.js */ $log("Initializing Window Timer."); //private var $timers = []; $w.setTimeout = function(fn, time){ var num; return num = window.setInterval(function(){ fn(); window.clearInterval(num); }, time); }; window.setInterval = function(fn, time){ var num = $timers.length; if (typeof fn == 'string') { var fnstr = fn; fn = function() { eval(fnstr); }; } if(time===0){ fn(); }else{ $timers[num] = $env.timer(fn, time); $timers[num].start(); } return num; }; window.clearInterval = window.clearTimeout = function(num){ if ( $timers[num] ) { $timers[num].stop(); delete $timers[num]; } }; /* * event.js */ // Window Events $log("Initializing Window Event."); var $events = [], $onerror, $onload, $onunload; $w.addEventListener = function(type, fn){ $log("adding event listener " + type); if ( !this.uuid ) { this.uuid = $events.length; $events[this.uuid] = {}; } if ( !$events[this.uuid][type] ){ $events[this.uuid][type] = []; } if ( $events[this.uuid][type].indexOf( fn ) < 0 ){ $events[this.uuid][type].push( fn ); } }; $w.removeEventListener = function(type, fn){ if ( !this.uuid ) { this.uuid = $events.length; $events[this.uuid] = {}; } if ( !$events[this.uuid][type] ){ $events[this.uuid][type] = []; } $events[this.uuid][type] = $events[this.uuid][type].filter(function(f){ return f != fn; }); }; $w.dispatchEvent = function(event){ $log("dispatching event " + event.type); //the window scope defines the $event object, for IE(^^^) compatibility; $event = event; if(!event.target) event.target = this; if ( event.type ) { if ( this.uuid && $events[this.uuid][event.type] ) { var _this = this; $events[this.uuid][event.type].forEach(function(fn){ fn.call( _this, event ); }); } if ( this["on" + event.type] ) this["on" + event.type].call( _this, event ); } if(this.parentNode){ this.parentNode.dispatchEvent.call(this.parentNode,event); } }; $w.__defineGetter__('onerror', function(){ return function(){ //$w.dispatchEvent('error'); }; }); $w.__defineSetter__('onerror', function(fn){ //$w.addEventListener('error', fn); }); /*$w.__defineGetter__('onload', function(){ return function(){ //var event = document.createEvent(); //event.initEvent("load"); //$w.dispatchEvent(event); }; }); $w.__defineSetter__('onload', function(fn){ //$w.addEventListener('load', fn); }); $w.__defineGetter__('onunload', function(){ return function(){ //$w.dispatchEvent('unload'); }; }); $w.__defineSetter__('onunload', function(fn){ //$w.addEventListener('unload', fn); });*//* * xhr.js */ $log("Initializing Window XMLHttpRequest."); // XMLHttpRequest // Originally implemented by Yehuda Katz $w.XMLHttpRequest = function(){ this.headers = {}; this.responseHeaders = {}; }; XMLHttpRequest.prototype = { open: function(method, url, async, user, password){ this.readyState = 1; if (async === false ){ this.async = false; }else{ this.async = true; } this.method = method || "GET"; this.url = $env.location(url); this.onreadystatechange(); }, setRequestHeader: function(header, value){ this.headers[header] = value; }, getResponseHeader: function(header){ }, send: function(data){ var self = this; function makeRequest(){ $env.connection(self, function(){ var responseXML = null; self.__defineGetter__("responseXML", function(){ if ( self.responseText.match(/^\s*</) ) { if(responseXML){return responseXML;} else{ try { $log("parsing response text into xml document"); responseXML = $domparser.parseFromString(self.responseText); return responseXML; } catch(e) { return null;/*TODO: need to flag an error here*/} } }else{return null;} }); }); self.onreadystatechange(); } if (this.async){ $log("XHR sending asynch;"); $env.runAsync(makeRequest); }else{ $log("XHR sending synch;"); makeRequest(); } }, abort: function(){ //TODO }, onreadystatechange: function(){ //TODO }, getResponseHeader: function(header){ var rHeader, returnedHeaders; if (this.readyState < 3){ throw new Error("INVALID_STATE_ERR"); } else { returnedHeaders = []; for (rHeader in this.responseHeaders) { if (rHeader.match(new RegExp(header, "i"))) returnedHeaders.push(this.responseHeaders[rHeader]); } if (returnedHeaders.length){ return returnedHeaders.join(", "); } }return null; }, getAllResponseHeaders: function(){ var header, returnedHeaders = []; if (this.readyState < 3){ throw new Error("INVALID_STATE_ERR"); } else { for (header in this.responseHeaders){ returnedHeaders.push( header + ": " + this.responseHeaders[header] ); } }return returnedHeaders.join("\r\n"); }, async: true, readyState: 0, responseText: "", status: 0 };/* * css.js */ $log("Initializing Window CSS"); // returns a CSS2Properties object that represents the style // attributes and values used to render the specified element in this // window. Any length values are always expressed in pixel, or // absolute values. $w.getComputedStyle = function(elt, pseudo_elt){ //TODO //this is a naive implementation $log("Getting computed style"); return elt?elt.style:new CSS2Properties({cssText:""}); };/* * screen.js */ $log("Initializing Window Screen."); var $availHeight = 600, $availWidth = 800, $colorDepth = 16, $height = 600, $width = 800; $w.__defineGetter__("screen", function(){ return { get availHeight(){return $availHeight;}, get availWidth(){return $availWidth;}, get colorDepth(){return $colorDepth;}, get height(){return $height;}, get width(){return $width;} }; }); $w.moveBy = function(dx,dy){ //TODO }; $w.moveTo = function(x,y) { //TODO }; /*$w.print = function(){ //TODO };*/ $w.resizeBy = function(dw, dh){ $w.resizeTo($width+dw,$height+dh); }; $w.resizeTo = function(width, height){ $width = (width <= $availWidth) ? width : $availWidth; $height = (height <= $availHeight) ? height : $availHeight; }; $w.scroll = function(x,y){ //TODO }; $w.scrollBy = function(dx, dy){ //TODO }; $w.scrollTo = function(x,y){ //TODO };/* * dialog.js */ $log("Initializing Window Dialogs."); $w.alert = function(message){ //TODO }; $w.confirm = function(question){ //TODO }; $w.prompt = function(message, defaultMsg){ //TODO };/** * jQuery AOP - jQuery plugin to add features of aspect-oriented programming (AOP) to jQuery. * http://jquery-aop.googlecode.com/ * * Licensed under the MIT license: * http://www.opensource.org/licenses/mit-license.php * * Version: 1.1 */ window.$profiler; (function() { var _after = 1; var _before = 2; var _around = 3; var _intro = 4; var _regexEnabled = true; /** * Private weaving function. */ var weaveOne = function(source, method, advice) { var old = source[method]; var aspect; if (advice.type == _after) aspect = function() { var returnValue = old.apply(this, arguments); return advice.value.apply(this, [returnValue, method]); }; else if (advice.type == _before) aspect = function() { advice.value.apply(this, [arguments, method]); return old.apply(this, arguments); }; else if (advice.type == _intro) aspect = function() { return advice.value.apply(this, arguments); }; else if (advice.type == _around) { aspect = function() { var invocation = { object: this, args: arguments }; return advice.value.apply(invocation.object, [{ arguments: invocation.args, method: method, proceed : function() { return old.apply(invocation.object, invocation.args); } }] ); }; } aspect.unweave = function() { source[method] = old; pointcut = source = aspect = old = null; }; source[method] = aspect; return aspect; }; /** * Private weaver and pointcut parser. */ var weave = function(pointcut, advice) { var source = (typeof(pointcut.target.prototype) != 'undefined') ? pointcut.target.prototype : pointcut.target; var advices = []; // If it's not an introduction and no method was found, try with regex... if (advice.type != _intro && typeof(source[pointcut.method]) == 'undefined') { for (var method in source) { if (source[method] != null && source[method] instanceof Function && method.match(pointcut.method)) { advices[advices.length] = weaveOne(source, method, advice); } } if (advices.length == 0) throw 'No method: ' + pointcut.method; } else { // Return as an array of one element advices[0] = weaveOne(source, pointcut.method, advice); } return _regexEnabled ? advices : advices[0]; }; window.$profiler = { /** * Creates an advice after the defined point-cut. The advice will be executed after the point-cut method * has completed execution successfully, and will receive one parameter with the result of the execution. * This function returns an array of weaved aspects (Function). * * @example jQuery.aop.after( {target: window, method: 'MyGlobalMethod'}, function(result) { alert('Returned: ' + result); } ); * @result Array<Function> * * @example jQuery.aop.after( {target: String, method: 'indexOf'}, function(index) { alert('Result found at: ' + index + ' on:' + this); } ); * @result Array<Function> * * @name after * @param Map pointcut Definition of the point-cut to apply the advice. A point-cut is the definition of the object/s and method/s to be weaved. * @option Object target Target object to be weaved. * @option String method Name of the function to be weaved. Regex are supported, but not on built-in objects. * @param Function advice Function containing the code that will get called after the execution of the point-cut. It receives one parameter * with the result of the point-cut's execution. * * @type Array<Function> * @cat Plugins/General */ after : function(pointcut, advice) { return weave( pointcut, { type: _after, value: advice } ); }, /** * Creates an advice before the defined point-cut. The advice will be executed before the point-cut method * but cannot modify the behavior of the method, or prevent its execution. * This function returns an array of weaved aspects (Function). * * @example jQuery.aop.before( {target: window, method: 'MyGlobalMethod'}, function() { alert('About to execute MyGlobalMethod'); } ); * @result Array<Function> * * @example jQuery.aop.before( {target: String, method: 'indexOf'}, function(index) { alert('About to execute String.indexOf on: ' + this); } ); * @result Array<Function> * * @name before * @param Map pointcut Definition of the point-cut to apply the advice. A point-cut is the definition of the object/s and method/s to be weaved. * @option Object target Target object to be weaved. * @option String method Name of the function to be weaved. Regex are supported, but not on built-in objects. * @param Function advice Function containing the code that will get called before the execution of the point-cut. * * @type Array<Function> * @cat Plugins/General */ before : function(pointcut, advice) { return weave( pointcut, { type: _before, value: advice } ); }, /** * Creates an advice 'around' the defined point-cut. This type of advice can control the point-cut method execution by calling * the functions '.proceed()' on the 'invocation' object, and also, can modify the arguments collection before sending them to the function call. * This function returns an array of weaved aspects (Function). * * @example jQuery.aop.around( {target: window, method: 'MyGlobalMethod'}, function(invocation) { * alert('# of Arguments: ' + invocation.arguments.length); * return invocation.proceed(); * } ); * @result Array<Function> * * @example jQuery.aop.around( {target: String, method: 'indexOf'}, function(invocation) { * alert('Searching: ' + invocation.arguments[0] + ' on: ' + this); * return invocation.proceed(); * } ); * @result Array<Function> * * @example jQuery.aop.around( {target: window, method: /Get(\d+)/}, function(invocation) { * alert('Executing ' + invocation.method); * return invocation.proceed(); * } ); * @desc Matches all global methods starting with 'Get' and followed by a number. * @result Array<Function> * * * @name around * @param Map pointcut Definition of the point-cut to apply the advice. A point-cut is the definition of the object/s and method/s to be weaved. * @option Object target Target object to be weaved. * @option String method Name of the function to be weaved. Regex are supported, but not on built-in objects. * @param Function advice Function containing the code that will get called around the execution of the point-cut. This advice will be called with one * argument containing one function '.proceed()', the collection of arguments '.arguments', and the matched method name '.method'. * * @type Array<Function> * @cat Plugins/General */ around : function(pointcut, advice) { return weave( pointcut, { type: _around, value: advice } ); }, /** * Creates an introduction on the defined point-cut. This type of advice replaces any existing methods with the same * name. To restore them, just unweave it. * This function returns an array with only one weaved aspect (Function). * * @example jQuery.aop.introduction( {target: window, method: 'MyGlobalMethod'}, function(result) { alert('Returned: ' + result); } ); * @result Array<Function> * * @example jQuery.aop.introduction( {target: String, method: 'log'}, function() { alert('Console: ' + this); } ); * @result Array<Function> * * @name introduction * @param Map pointcut Definition of the point-cut to apply the advice. A point-cut is the definition of the object/s and method/s to be weaved. * @option Object target Target object to be weaved. * @option String method Name of the function to be weaved. * @param Function advice Function containing the code that will be executed on the point-cut. * * @type Array<Function> * @cat Plugins/General */ introduction : function(pointcut, advice) { return weave( pointcut, { type: _intro, value: advice } ); }, /** * Configures global options. * * @name setup * @param Map settings Configuration options. * @option Boolean regexMatch Enables/disables regex matching of method names. * * @example jQuery.aop.setup( { regexMatch: false } ); * @desc Disable regex matching. * * @type Void * @cat Plugins/General */ setup: function(settings) { _regexEnabled = settings.regexMatch; } }; })(); var $profile = window.$profile = {}; var __profile__ = function(id, invocation){ var start = new Date().getTime(); var retval = invocation.proceed(); var finish = new Date().getTime(); $profile[id] = $profile[id] ? $profile[id] : {}; $profile[id].callCount = $profile[id].callCount !== undefined ? $profile[id].callCount+1 : 0; $profile[id].times = $profile[id].times ? $profile[id].times : []; $profile[id].times[$profile[id].callCount++] = (finish-start); return retval; }; window.$profiler.stats = function(raw){ var max = 0, avg = -1, min = 10000000, own = 0; for(var i = 0;i<raw.length;i++){ if(raw[i] > 0){ own += raw[i]; }; if(raw[i] > max){ max = raw[i]; } if(raw[i] < min){ min = raw[i]; } } avg = Math.floor(own/raw.length); return { min: min, max: max, avg: avg, own: own }; }; if(__env__.profile){ /** * CSS2Properties */ window.$profiler.around({ target: CSS2Properties, method:"getPropertyCSSValue"}, function(invocation) { return __profile__("CSS2Properties.getPropertyCSSValue", invocation); }); window.$profiler.around({ target: CSS2Properties, method:"getPropertyPriority"}, function(invocation) { return __profile__("CSS2Properties.getPropertyPriority", invocation); }); window.$profiler.around({ target: CSS2Properties, method:"getPropertyValue"}, function(invocation) { return __profile__("CSS2Properties.getPropertyValue", invocation); }); window.$profiler.around({ target: CSS2Properties, method:"item"}, function(invocation) { return __profile__("CSS2Properties.item", invocation); }); window.$profiler.around({ target: CSS2Properties, method:"removeProperty"}, function(invocation) { return __profile__("CSS2Properties.removeProperty", invocation); }); window.$profiler.around({ target: CSS2Properties, method:"setProperty"}, function(invocation) { return __profile__("CSS2Properties.setProperty", invocation); }); window.$profiler.around({ target: CSS2Properties, method:"toString"}, function(invocation) { return __profile__("CSS2Properties.toString", invocation); }); /** * DOMNode */ window.$profiler.around({ target: DOMNode, method:"hasAttributes"}, function(invocation) { return __profile__("DOMNode.hasAttributes", invocation); }); window.$profiler.around({ target: DOMNode, method:"insertBefore"}, function(invocation) { return __profile__("DOMNode.insertBefore", invocation); }); window.$profiler.around({ target: DOMNode, method:"replaceChild"}, function(invocation) { return __profile__("DOMNode.replaceChild", invocation); }); window.$profiler.around({ target: DOMNode, method:"removeChild"}, function(invocation) { return __profile__("DOMNode.removeChild", invocation); }); window.$profiler.around({ target: DOMNode, method:"replaceChild"}, function(invocation) { return __profile__("DOMNode.replaceChild", invocation); }); window.$profiler.around({ target: DOMNode, method:"appendChild"}, function(invocation) { return __profile__("DOMNode.appendChild", invocation); }); window.$profiler.around({ target: DOMNode, method:"hasChildNodes"}, function(invocation) { return __profile__("DOMNode.hasChildNodes", invocation); }); window.$profiler.around({ target: DOMNode, method:"cloneNode"}, function(invocation) { return __profile__("DOMNode.cloneNode", invocation); }); window.$profiler.around({ target: DOMNode, method:"normalize"}, function(invocation) { return __profile__("DOMNode.normalize", invocation); }); window.$profiler.around({ target: DOMNode, method:"isSupported"}, function(invocation) { return __profile__("DOMNode.isSupported", invocation); }); window.$profiler.around({ target: DOMNode, method:"getElementsByTagName"}, function(invocation) { return __profile__("DOMNode.getElementsByTagName", invocation); }); window.$profiler.around({ target: DOMNode, method:"getElementsByTagNameNS"}, function(invocation) { return __profile__("DOMNode.getElementsByTagNameNS", invocation); }); window.$profiler.around({ target: DOMNode, method:"importNode"}, function(invocation) { return __profile__("DOMNode.importNode", invocation); }); window.$profiler.around({ target: DOMNode, method:"contains"}, function(invocation) { return __profile__("DOMNode.contains", invocation); }); window.$profiler.around({ target: DOMNode, method:"compareDocumentPosition"}, function(invocation) { return __profile__("DOMNode.compareDocumentPosition", invocation); }); /** * DOMDocument */ window.$profiler.around({ target: DOMDocument, method:"addEventListener"}, function(invocation) { return __profile__("DOMDocument.addEventListener", invocation); }); window.$profiler.around({ target: DOMDocument, method:"removeEventListener"}, function(invocation) { return __profile__("DOMDocument.removeEventListener", invocation); }); window.$profiler.around({ target: DOMDocument, method:"attachEvent"}, function(invocation) { return __profile__("DOMDocument.attachEvent", invocation); }); window.$profiler.around({ target: DOMDocument, method:"detachEvent"}, function(invocation) { return __profile__("DOMDocument.detachEvent", invocation); }); window.$profiler.around({ target: DOMDocument, method:"dispatchEvent"}, function(invocation) { return __profile__("DOMDocument.dispatchEvent", invocation); }); window.$profiler.around({ target: DOMDocument, method:"loadXML"}, function(invocation) { return __profile__("DOMDocument.loadXML", invocation); }); window.$profiler.around({ target: DOMDocument, method:"load"}, function(invocation) { return __profile__("DOMDocument.load", invocation); }); window.$profiler.around({ target: DOMDocument, method:"createEvent"}, function(invocation) { return __profile__("DOMDocument.createEvent", invocation); }); window.$profiler.around({ target: DOMDocument, method:"createExpression"}, function(invocation) { return __profile__("DOMDocument.createExpression", invocation); }); window.$profiler.around({ target: DOMDocument, method:"createElement"}, function(invocation) { return __profile__("DOMDocument.createElement", invocation); }); window.$profiler.around({ target: DOMDocument, method:"createDocumentFragment"}, function(invocation) { return __profile__("DOMDocument.createDocumentFragment", invocation); }); window.$profiler.around({ target: DOMDocument, method:"createTextNode"}, function(invocation) { return __profile__("DOMDocument.createTextNode", invocation); }); window.$profiler.around({ target: DOMDocument, method:"createComment"}, function(invocation) { return __profile__("DOMDocument.createComment", invocation); }); window.$profiler.around({ target: DOMDocument, method:"createCDATASection"}, function(invocation) { return __profile__("DOMDocument.createCDATASection", invocation); }); window.$profiler.around({ target: DOMDocument, method:"createProcessingInstruction"}, function(invocation) { return __profile__("DOMDocument.createProcessingInstruction", invocation); }); window.$profiler.around({ target: DOMDocument, method:"createAttribute"}, function(invocation) { return __profile__("DOMDocument.createAttribute", invocation); }); window.$profiler.around({ target: DOMDocument, method:"createElementNS"}, function(invocation) { return __profile__("DOMDocument.createElementNS", invocation); }); window.$profiler.around({ target: DOMDocument, method:"createAttributeNS"}, function(invocation) { return __profile__("DOMDocument.createAttributeNS", invocation); }); window.$profiler.around({ target: DOMDocument, method:"createNamespace"}, function(invocation) { return __profile__("DOMDocument.createNamespace", invocation); }); window.$profiler.around({ target: DOMDocument, method:"getElementById"}, function(invocation) { return __profile__("DOMDocument.getElementById", invocation); }); window.$profiler.around({ target: DOMDocument, method:"normalizeDocument"}, function(invocation) { return __profile__("DOMDocument.normalizeDocument", invocation); }); /** * HTMLDocument */ window.$profiler.around({ target: HTMLDocument, method:"createElement"}, function(invocation) { return __profile__("HTMLDocument.createElement", invocation); }); /** * DOMParser */ window.$profiler.around({ target: DOMParser, method:"parseFromString"}, function(invocation) { return __profile__("DOMParser.parseFromString", invocation); }); /** * DOMNodeList */ window.$profiler.around({ target: DOMNodeList, method:"item"}, function(invocation) { return __profile__("DOMNode.item", invocation); }); window.$profiler.around({ target: DOMNodeList, method:"toString"}, function(invocation) { return __profile__("DOMNode.toString", invocation); }); /** * XMLP */ window.$profiler.around({ target: XMLP, method:"_addAttribute"}, function(invocation) { return __profile__("XMLP._addAttribute", invocation); }); window.$profiler.around({ target: XMLP, method:"_checkStructure"}, function(invocation) { return __profile__("XMLP._checkStructure", invocation); }); window.$profiler.around({ target: XMLP, method:"_clearAttributes"}, function(invocation) { return __profile__("XMLP._clearAttributes", invocation); }); window.$profiler.around({ target: XMLP, method:"_findAttributeIndex"}, function(invocation) { return __profile__("XMLP._findAttributeIndex", invocation); }); window.$profiler.around({ target: XMLP, method:"getAttributeCount"}, function(invocation) { return __profile__("XMLP.getAttributeCount", invocation); }); window.$profiler.around({ target: XMLP, method:"getAttributeName"}, function(invocation) { return __profile__("XMLP.getAttributeName", invocation); }); window.$profiler.around({ target: XMLP, method:"getAttributeValue"}, function(invocation) { return __profile__("XMLP.getAttributeValue", invocation); }); window.$profiler.around({ target: XMLP, method:"getAttributeValueByName"}, function(invocation) { return __profile__("XMLP.getAttributeValueByName", invocation); }); window.$profiler.around({ target: XMLP, method:"getColumnNumber"}, function(invocation) { return __profile__("XMLP.getColumnNumber", invocation); }); window.$profiler.around({ target: XMLP, method:"getContentBegin"}, function(invocation) { return __profile__("XMLP.getContentBegin", invocation); }); window.$profiler.around({ target: XMLP, method:"getContentEnd"}, function(invocation) { return __profile__("XMLP.getContentEnd", invocation); }); window.$profiler.around({ target: XMLP, method:"getLineNumber"}, function(invocation) { return __profile__("XMLP.getLineNumber", invocation); }); window.$profiler.around({ target: XMLP, method:"getName"}, function(invocation) { return __profile__("XMLP.getName", invocation); }); window.$profiler.around({ target: XMLP, method:"next"}, function(invocation) { return __profile__("XMLP.next", invocation); }); window.$profiler.around({ target: XMLP, method:"_parse"}, function(invocation) { return __profile__("XMLP._parse", invocation); }); window.$profiler.around({ target: XMLP, method:"_parse"}, function(invocation) { return __profile__("XMLP._parse", invocation); }); window.$profiler.around({ target: XMLP, method:"_parseAttribute"}, function(invocation) { return __profile__("XMLP._parseAttribute", invocation); }); window.$profiler.around({ target: XMLP, method:"_parseCDATA"}, function(invocation) { return __profile__("XMLP._parseCDATA", invocation); }); window.$profiler.around({ target: XMLP, method:"_parseComment"}, function(invocation) { return __profile__("XMLP._parseComment", invocation); }); window.$profiler.around({ target: XMLP, method:"_parseDTD"}, function(invocation) { return __profile__("XMLP._parseDTD", invocation); }); window.$profiler.around({ target: XMLP, method:"_parseElement"}, function(invocation) { return __profile__("XMLP._parseElement", invocation); }); window.$profiler.around({ target: XMLP, method:"_parseEntity"}, function(invocation) { return __profile__("XMLP._parseEntity", invocation); }); window.$profiler.around({ target: XMLP, method:"_parsePI"}, function(invocation) { return __profile__("XMLP._parsePI", invocation); }); window.$profiler.around({ target: XMLP, method:"_parseText"}, function(invocation) { return __profile__("XMLP._parseText", invocation); }); window.$profiler.around({ target: XMLP, method:"_replaceEntities"}, function(invocation) { return __profile__("XMLP._replaceEntities", invocation); }); window.$profiler.around({ target: XMLP, method:"_replaceEntity"}, function(invocation) { return __profile__("XMLP._replaceEntity", invocation); }); window.$profiler.around({ target: XMLP, method:"_setContent"}, function(invocation) { return __profile__("XMLP._setContent", invocation); }); window.$profiler.around({ target: XMLP, method:"_setErr"}, function(invocation) { return __profile__("XMLP._setErr", invocation); }); /** * SAXDriver */ window.$profiler.around({ target: SAXDriver, method:"parse"}, function(invocation) { return __profile__("SAXDriver.parse", invocation); }); window.$profiler.around({ target: SAXDriver, method:"setDocumentHandler"}, function(invocation) { return __profile__("SAXDriver.setDocumentHandler", invocation); }); window.$profiler.around({ target: SAXDriver, method:"setErrorHandler"}, function(invocation) { return __profile__("SAXDriver.setErrorHandler", invocation); }); window.$profiler.around({ target: SAXDriver, method:"setLexicalHandler"}, function(invocation) { return __profile__("SAXDriver.setLexicalHandler", invocation); }); window.$profiler.around({ target: SAXDriver, method:"getColumnNumber"}, function(invocation) { return __profile__("SAXDriver.getColumnNumber", invocation); }); window.$profiler.around({ target: SAXDriver, method:"getLineNumber"}, function(invocation) { return __profile__("SAXDriver.getLineNumber", invocation); }); window.$profiler.around({ target: SAXDriver, method:"getMessage"}, function(invocation) { return __profile__("SAXDriver.getMessage", invocation); }); window.$profiler.around({ target: SAXDriver, method:"getPublicId"}, function(invocation) { return __profile__("SAXDriver.getPublicId", invocation); }); window.$profiler.around({ target: SAXDriver, method:"getSystemId"}, function(invocation) { return __profile__("SAXDriver.getSystemId", invocation); }); window.$profiler.around({ target: SAXDriver, method:"getLength"}, function(invocation) { return __profile__("SAXDriver.getLength", invocation); }); window.$profiler.around({ target: SAXDriver, method:"getName"}, function(invocation) { return __profile__("SAXDriver.getName", invocation); }); window.$profiler.around({ target: SAXDriver, method:"getValue"}, function(invocation) { return __profile__("SAXDriver.getValue", invocation); }); window.$profiler.around({ target: SAXDriver, method:"getValueByName"}, function(invocation) { return __profile__("SAXDriver.getValueByName", invocation); }); window.$profiler.around({ target: SAXDriver, method:"_fireError"}, function(invocation) { return __profile__("SAXDriver._fireError", invocation); }); window.$profiler.around({ target: SAXDriver, method:"_fireEvent"}, function(invocation) { return __profile__("SAXDriver._fireEvent", invocation); }); window.$profiler.around({ target: SAXDriver, method:"_parseLoop"}, function(invocation) { return __profile__("SAXDriver._parseLoop", invocation); }); /** * SAXStrings */ window.$profiler.around({ target: SAXStrings, method:"getColumnNumber"}, function(invocation) { return __profile__("SAXStrings.getColumnNumber", invocation); }); window.$profiler.around({ target: SAXStrings, method:"getLineNumber"}, function(invocation) { return __profile__("SAXStrings.getLineNumber", invocation); }); window.$profiler.around({ target: SAXStrings, method:"indexOfNonWhitespace"}, function(invocation) { return __profile__("SAXStrings.indexOfNonWhitespace", invocation); }); window.$profiler.around({ target: SAXStrings, method:"indexOfWhitespace"}, function(invocation) { return __profile__("SAXStrings.indexOfWhitespace", invocation); }); window.$profiler.around({ target: SAXStrings, method:"isEmpty"}, function(invocation) { return __profile__("SAXStrings.isEmpty", invocation); }); window.$profiler.around({ target: SAXStrings, method:"lastIndexOfNonWhitespace"}, function(invocation) { return __profile__("SAXStrings.lastIndexOfNonWhitespace", invocation); }); window.$profiler.around({ target: SAXStrings, method:"replace"}, function(invocation) { return __profile__("SAXStrings.replace", invocation); }); /** * Stack - SAX Utility window.$profiler.around({ target: Stack, method:"clear"}, function(invocation) { return __profile__("Stack.clear", invocation); }); window.$profiler.around({ target: Stack, method:"count"}, function(invocation) { return __profile__("Stack.count", invocation); }); window.$profiler.around({ target: Stack, method:"destroy"}, function(invocation) { return __profile__("Stack.destroy", invocation); }); window.$profiler.around({ target: Stack, method:"peek"}, function(invocation) { return __profile__("Stack.peek", invocation); }); window.$profiler.around({ target: Stack, method:"pop"}, function(invocation) { return __profile__("Stack.pop", invocation); }); window.$profiler.around({ target: Stack, method:"push"}, function(invocation) { return __profile__("Stack.push", invocation); }); */ } /* * document.js * * DOM Level 2 /DOM level 3 (partial) * * This file adds the document object to the window and allows you * you to set the window.document using an html string or dom object. * */ // read only reference to the Document object $log("Initializing window.document."); var $async = false; __extend__(HTMLDocument.prototype, { get async(){ return $async;}, set async(async){ $async = async; }, get baseURI(){ return $env.location('./'); }, get URL(){ return $w.location.href; } }); var $document = new HTMLDocument($implementation); $w.__defineGetter__("document", function(){ return $document; }); $log("Defining document.cookie"); /* * cookie.js * - requires env */ var $cookies = { persistent:{ //domain - key on domain name { //path - key on path { //name - key on name { //value : cookie value //other cookie properties //} //} //} //expire - provides a timestamp for expiring the cookie //cookie - the cookie! }, temporary:{//transient is a reserved word :( //like above } }; //HTMLDocument cookie document.__defineSetter__("cookie", function(cookie){ var i,name,value,properties = {},attr,attrs = cookie.split(";"); //for now the strategy is to simply create a json object //and post it to a file in the .cookies.js file. I hate parsing //dates so I decided not to implement support for 'expires' //(which is deprecated) and instead focus on the easier 'max-age' //(which succeeds 'expires') cookie = {};//keyword properties of the cookie for(i=0;i<attrs.length;i++){ attr = attrs[i].split("="); if(attr.length > 0){ name = trim(attr[0]); value = trim(attr[1]); if(name=='max-age'){ //we'll have to set a timer to check these //and garbage collect expired cookies cookie[name] = parseInt(value, 10); } else if(name=='domain'){ if(domainValid(value)){ cookie['domain']=value; }else{ cookie['domain']=$w.location.domain; } } else if(name=='path'){ //not sure of any special logic for path cookie['path'] = value; } else { //its not a cookie keyword so store it in our array of properties //and we'll serialize individually in a moment properties[name] = value; } }else{ if(attr[0] == 'secure'){ cookie[attr[0]] = true; } } } if(!cookie['max-age']){ //it's a transient cookie so it only lasts as long as //the window.location remains the same mergeCookie($cookies.temporary, cookie, properties); }else if(cookie['max-age']===0){ //delete the cookies //TODO }else{ //the cookie is persistent mergeCookie($cookies.persistent, cookie, properties); persistCookies(); } }); document.__defineGetter__("cookie", function(c){ //The cookies that are returned must belong to the same domain //and be at or below the current window.location.path. Also //we must check to see if the cookie was set to 'secure' in which //case we must check our current location.protocol to make sure it's //https: var allcookies = [], i; //TODO }); var domainValid = function(domain){ //make sure the domain //TODO }; var mergeCookie = function(target, cookie, properties){ var name, now; if(!target[cookie.domain]){ target[cookie.domain] = {}; } if(!target[cookie.domain][cookie.path]){ target[cookie.domain][cookie.path] = {}; } for(name in properties){ now = new Date().getTime(); target[cookie.domain][cookie.path][name] = { value:properties[name], "@env:secure":cookie.secure, "@env:max-age":cookie['max-age'], "@env:date-created":now, "@env:expiration":now + cookie['max-age'] }; } }; var persistCookies = function(){ //TODO //I think it should be done via $env so it can be customized }; var loadCookies = function(){ //TODO //should also be configurable via $env }; //We simply use the default ajax get to load the .cookies.js file //if it doesn't exist we create it with a post. Cookies are maintained //in memory, but serialized with each set. $log("Loading Cookies"); try{ //TODO - load cookies loadCookies(); }catch(e){ //TODO - fail gracefully } /* * outro.js */ })(window, __env__, __policy__); }catch(e){ __env__.error("ERROR LOADING ENV : " + e + "\nLINE SOURCE:\n" +__env__.lineSource(e)); }
lib/env.rhino.js
/* * env.rhino.js */ var __env__ = {}; (function($env){ $env.debug = function(){}; $env.log = function(){}; //uncomment this if you want to get some internal log statementes //$env.log = print; $env.log("Initializing Rhino Platform Env"); $env.error = function(msg, e){ print("ERROR! : " + msg); print(e); }; $env.lineSource = function(e){ return e.rhinoException.lineSource(); }; $env.hashCode = function(obj){ return obj?obj.hashCode().toString():null; }; //For Java the window.location object is a java.net.URL $env.location = function(path, base){ var protocol = new RegExp('(^\\w*\:)'); var m = protocol.exec(path); if(m&&m.length>1){ return new java.net.URL(path).toString(); }else if(base){ return new java.net.URL(base + '/' + path).toString(); }else{ //return an absolute url from a relative to the file system return new java.io.File(path).toURL().toString(); } }; //For Java the window.timer is created using the java.lang.Thread in combination //with the java.lang.Runnable $env.timer = function(fn, time){ return new java.lang.Thread(new java.lang.Runnable({ run: function(){ while (true){ java.lang.Thread.currentThread().sleep(time); fn(); } } })); }; //Since we're running in rhino I guess we can safely assume //java is 'enabled'. I'm sure this requires more thought //than I've given it here $env.javaEnabled = true; //Used in the XMLHttpRquest implementation to run a // request in a seperate thread $env.runAsync = function(fn){ (new java.lang.Thread(new java.lang.Runnable({ run: fn }))).start(); }; //Used to write to a local file $env.writeToFile = function(text, url){ var out = new java.io.FileWriter( new java.io.File( new java.net.URI(url.toString()))); out.write( text, 0, text.length ); out.flush(); out.close(); }; //Used to delete a local file $env.deleteFile = function(url){ var file = new java.io.File( new java.net.URI( url ) ); file["delete"](); }; $env.connection = function(xhr, responseHandler){ var url = java.net.URL(xhr.url);//, $w.location); var connection; if ( /^file\:/.test(url) ) { if ( xhr.method == "PUT" ) { var text = data || "" ; $env.writeToFile(text, url); } else if ( xhr.method == "DELETE" ) { $env.deleteFile(url); } else { connection = url.openConnection(); connection.connect(); } } else { connection = url.openConnection(); connection.setRequestMethod( xhr.method ); // Add headers to Java connection for (var header in xhr.headers){ connection.addRequestProperty(header, xhr.headers[header]); }connection.connect(); // Stick the response headers into responseHeaders for (var i = 0; ; i++) { var headerName = connection.getHeaderFieldKey(i); var headerValue = connection.getHeaderField(i); if (!headerName && !headerValue) break; if (headerName) xhr.responseHeaders[headerName] = headerValue; } } if(connection){ xhr.readyState = 4; xhr.status = parseInt(connection.responseCode,10) || undefined; xhr.statusText = connection.responseMessage || ""; var contentEncoding = connection.getContentEncoding() || "utf-8", stream = (contentEncoding.equalsIgnoreCase("gzip") || contentEncoding.equalsIgnoreCase("decompress") )? new java.util.zip.GZIPInputStream(connection.getInputStream()) : connection.getInputStream(), baos = new java.io.ByteArrayOutputStream(), buffer = java.lang.reflect.Array.newInstance(java.lang.Byte.TYPE, 1024), length, responseXML = null; while ((length = stream.read(buffer)) != -1) { baos.write(buffer, 0, length); } baos.close(); stream.close(); xhr.responseText = java.nio.charset.Charset.forName(contentEncoding). decode(java.nio.ByteBuffer.wrap(baos.toByteArray())).toString(); } if(responseHandler){ responseHandler(); } }; var htmlDocBuilder = Packages.javax.xml.parsers.DocumentBuilderFactory.newInstance(); htmlDocBuilder.setNamespaceAware(false); htmlDocBuilder.setValidating(false); $env.parseHTML = function(htmlstring){ return htmlDocBuilder.newDocumentBuilder().parse( new java.io.ByteArrayInputStream( (new java.lang.String(htmlstring)).getBytes("UTF8"))); }; var xmlDocBuilder = Packages.javax.xml.parsers.DocumentBuilderFactory.newInstance(); xmlDocBuilder.setNamespaceAware(true); xmlDocBuilder.setValidating(true); $env.parseXML = function(xmlstring){ return xmlDocBuilder.newDocumentBuilder().parse( new java.io.ByteArrayInputStream( (new java.lang.String(xmlstring)).getBytes("UTF8"))); }; $env.xpath = function(expression, doc){ return Packages.javax.xml.xpath. XPathFactory.newInstance().newXPath(). evaluate(expression, doc, javax.xml.xpath.XPathConstants.NODESET); }; $env.os_name = java.lang.System.getProperty("os.name"); $env.os_arch = java.lang.System.getProperty("os.arch"); $env.os_version = java.lang.System.getProperty("os.version"); $env.lang = java.lang.System.getProperty("user.lang"); $env.platform = "Rhino ";//how do we get the version $env.loadScripts = safeScript; function safeScript(){ //do nothing }; function localScripts(){ //try loading locally var scripts = document.getElementsByTagName('script'); for(var i=0;i<scipts.length;i++){ if(scripts[i].getAttribute('type') == 'text/javascript'){ try{ load(scripts[i].src); }catch(e){ $error("Error loading script." , e); } } } }; })(__env__);/* * Pure JavaScript Browser Environment * By John Resig <http://ejohn.org/> * Copyright 2008 John Resig, under the MIT License */ // The Window Object var __this__ = this; this.__defineGetter__('window', function(){ return __this__; }); try{ (function($w, $env){ /* * window.js * - this file will be wrapped in a closure providing the window object as $w */ // a logger or empty function available to all modules. var $log = $env.log, $error = $env.error, $debug = $env.debug; //The version of this application var $version = "0.1"; //This should be hooked to git or svn or whatever var $revision = "0.0.0.0"; //These descriptions of window properties are taken loosely David Flanagan's //'JavaScript - The Definitive Guide' (O'Reilly) /**> $cookies - see cookie.js <*/ // read only boolean specifies whether the window has been closed var $closed = false; // a read/write string that specifies the default message that appears in the status line var $defaultStatus = "Done"; // a read-only reference to the Document object belonging to this window /**> $document - See document.js <*/ //IE only, refers to the most recent event object - this maybe be removed after review var $event = null; //A read-only array of window objects var $frames = []; // a read-only reference to the History object /**> $history - see location.js <**/ // read-only properties that specify the height and width, in pixels var $innerHeight = 600, $innerWidth = 800; // a read-only reference to the Location object. the location object does expose read/write properties /**> $location - see location.js <**/ // a read only property specifying the name of the window. Can be set when using open() // and may be used when specifying the target attribute of links var $name = 'Resig Env Browser'; // a read-only reference to the Navigator object /**> $navigator - see navigator.js <**/ // a read/write reference to the Window object that contained the script that called open() to //open this browser window. This property is valid only for top-level window objects. var $opener; // Read-only properties that specify the total height and width, in pixels, of the browser window. // These dimensions include the height and width of the menu bar, toolbars, scrollbars, window // borders and so on. These properties are not supported by IE and IE offers no alternative // properties; var $outerHeight = $innerHeight, $outerWidth = $innerWidth; // Read-only properties that specify the number of pixels that the current document has been scrolled //to the right and down. These are not supported by IE. var $pageXOffset = 0, $pageYOffest = 0; //A read-only reference to the Window object that contains this window or frame. If the window is // a top-level window, parent refers to the window itself. If this window is a frame, this property // refers to the window or frame that conatins it. var $parent; // a read-only refernce to the Screen object that specifies information about the screen: // the number of available pixels and the number of available colors. /**> $screen - see screen.js <**/ // read only properties that specify the coordinates of the upper-left corner of the screen. var $screenX = 0, $screenY = 0; var $screenLeft = $screenX, $screenTop = $screenY; // a read-only refernce to this window itself. var $self; // a read/write string that specifies the current contents of the status line. var $status = ''; // a read-only reference to the top-level window that contains this window. If this // window is a top-level window it is simply a refernce to itself. If this window // is a frame, the top property refers to the top-level window that contains the frame. var $top; // the window property is identical to the self property. var $window = $w; $log("Initializing Window."); __extend__($w,{ get closed(){return $closed;}, get defaultStatus(){return $defaultStatus;}, set defaultStatus(_defaultStatus){$defaultStatus = _defaultStatus;}, //get document(){return $document;}, - see document.js get event(){return $event;}, get frames(){return $frames;}, //get history(){return $history;}, - see location.js get innerHeight(){return $innerHeight;}, get innerWidth(){return $innerWidth;}, get clientHeight(){return $innerHeight;}, get clientWidth(){return $innerWidth;}, //get location(){return $location;}, see location.js get name(){return $name;}, //get navigator(){return $navigator;}, see navigator.js get opener(){return $opener;}, get outerHeight(){return $outerHeight;}, get outerWidth(){return $outerWidth;}, get pageXOffest(){return $pageXOffset;}, get pageYOffset(){return $pageYOffset;}, get parent(){return $parent;}, //get screen(){return $screen;}, see screen.js get screenLeft(){return $screenLeft;}, get screenTop(){return $screenTop;}, get screenX(){return $screenX;}, get screenY(){return $screenY;}, get self(){return $self;}, get status(){return $status;}, set status(_status){$status = _status;}, get top(){return $top || $window;}, get window(){return $window;} }); $w.open = function(url, name, features, replace){ //TODO }; $w.close = function(){ //TODO }; /* Time related functions - see timer.js * - clearTimeout * - clearInterval * - setTimeout * - setInterval */ /* * Events related functions - see event.js * - addEventListener * - attachEvent * - detachEvent * - removeEventListener * * These functions are identical to the Element equivalents. */ /* * UIEvents related functions - see uievent.js * - blur * - focus * * These functions are identical to the Element equivalents. */ /* Dialog related functions - see dialog.js * - alert * - confirm * - prompt */ /* Screen related functions - see screen.js * - moveBy * - moveTo * - print * - resizeBy * - resizeTo * - scrollBy * - scrollTo */ /* CSS related functions - see css.js * - getComputedStyle */ /* * Shared utility methods */ // Helper method for extending one object with another. function __extend__(a,b) { for ( var i in b ) { var g = b.__lookupGetter__(i), s = b.__lookupSetter__(i); if ( g || s ) { if ( g ) a.__defineGetter__(i, g); if ( s ) a.__defineSetter__(i, s); } else a[i] = b[i]; } return a; }; // from ariel flesler http://flesler.blogspot.com/2008/11/fast-trim-function-for-javascript.html // this might be a good utility function to provide in the env.core // as in might be useful to the parser and other areas as well function trim( str ){ var start = -1, end = str.length; /*jsl:ignore*/ while( str.charCodeAt(--end) < 33 ); while( str.charCodeAt(++start) < 33 ); /*jsl:end*/ return str.slice( start, end + 1 ); }; //from jQuery function __setArray__( target, array ) { // Resetting the length to 0, then using the native Array push // is a super-fast way to populate an object with array-like properties target.length = 0; Array.prototype.push.apply( target, array ); }; $log("Defining NodeList"); /* * NodeList - DOM Level 2 */ $w.__defineGetter__('NodeList', function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); /** * @class DOMNodeList - provides the abstraction of an ordered collection of nodes * * @author Jon van Noort ([email protected]) * * @param ownerDocument : DOMDocument - the ownerDocument * @param parentNode : DOMNode - the node that the DOMNodeList is attached to (or null) */ var DOMNodeList = function(ownerDocument, parentNode) { //$log("\t\tcreating dom nodelist"); var nodes = []; this.length = 0; this.parentNode = parentNode; this.ownerDocument = ownerDocument; this._readonly = false; __setArray__(this, nodes); //$log("\t\tfinished creating dom nodelist"); }; __extend__(DOMNodeList.prototype, { item : function(index) { var ret = null; //$log("NodeList item("+index+") = " + this[index]); if ((index >= 0) && (index < this.length)) { // bounds check ret = this[index]; // return selected Node } return ret; // if the index is out of bounds, default value null is returned }, get xml() { var ret = ""; // create string containing the concatenation of the string values of each child for (var i=0; i < this.length; i++) { if(this[i].nodeType == DOMNode.TEXT_NODE && i>0 && this[i-1].nodeType == DOMNode.TEXT_NODE){ //add a single space between adjacent text nodes ret += " "+this[i].xml; }else{ ret += this[i].xml; } } return ret; }, toString: function(){ return "[ "+(this.length > 0?Array.prototype.join.apply(this, [", "]):"Empty NodeList")+" ]"; } }); /** * @method DOMNodeList._findItemIndex - find the item index of the node with the specified internal id * @author Jon van Noort ([email protected]) * @param id : int - unique internal id * @return : int */ var __findItemIndex__ = function (nodelist, id) { var ret = -1; // test that id is valid if (id > -1) { for (var i=0; i<nodelist.length; i++) { // compare id to each node's _id if (nodelist[i]._id == id) { // found it! ret = i; break; } } } return ret; // if node is not found, default value -1 is returned }; /** * @method DOMNodeList._insertBefore - insert the specified Node into the NodeList before the specified index * Used by DOMNode.insertBefore(). Note: DOMNode.insertBefore() is responsible for Node Pointer surgery * DOMNodeList._insertBefore() simply modifies the internal data structure (Array). * * @author Jon van Noort ([email protected]) * @param newChild : DOMNode - the Node to be inserted * @param refChildIndex : int - the array index to insert the Node before */ var __insertBefore__ = function(nodelist, newChild, refChildIndex) { if ((refChildIndex >= 0) && (refChildIndex < nodelist.length)) { // bounds check if (newChild.nodeType == DOMNode.DOCUMENT_FRAGMENT_NODE) { // node is a DocumentFragment // append the children of DocumentFragment Array.prototype.splice.apply(nodelist,[refChildIndex, 0].concat(newChild.childNodes)); } else { // append the newChild Array.prototype.splice.apply(nodelist,[refChildIndex, 0, newChild]); } } //$log("__insertBefore__ : length " + nodelist.length + " all -> " + document.all.length); }; /** * @method DOMNodeList._replaceChild - replace the specified Node in the NodeList at the specified index * Used by DOMNode.replaceChild(). Note: DOMNode.replaceChild() is responsible for Node Pointer surgery * DOMNodeList._replaceChild() simply modifies the internal data structure (Array). * * @author Jon van Noort ([email protected]) * @param newChild : DOMNode - the Node to be inserted * @param refChildIndex : int - the array index to hold the Node */ var __replaceChild__ = function(nodelist, newChild, refChildIndex) { var ret = null; if ((refChildIndex >= 0) && (refChildIndex < nodelist.length)) { // bounds check ret = nodelist[refChildIndex]; // preserve old child for return if (newChild.nodeType == DOMNode.DOCUMENT_FRAGMENT_NODE) { // node is a DocumentFragment // get array containing children prior to refChild Array.prototype.splice.apply(nodelist,[refChildIndex, 1].concat(newChild.childNodes)); } else { // simply replace node in array (links between Nodes are made at higher level) nodelist[refChildIndex] = newChild; } } //$log("__replaceChild__ : length " + nodelist.length + " all -> " + document.all.length); return ret; // return replaced node }; /** * @method DOMNodeList._removeChild - remove the specified Node in the NodeList at the specified index * Used by DOMNode.removeChild(). Note: DOMNode.removeChild() is responsible for Node Pointer surgery * DOMNodeList._replaceChild() simply modifies the internal data structure (Array). * * @author Jon van Noort ([email protected]) * @param refChildIndex : int - the array index holding the Node to be removed */ var __removeChild__ = function(nodelist, refChildIndex) { var ret = null; if (refChildIndex > -1) { // found it! ret = nodelist[refChildIndex]; // return removed node // rebuild array without removed child Array.prototype.splice.apply(nodelist,[refChildIndex, 1]); } //$log("__removeChild__ : length " + nodelist.length + " all -> " + document.all.length); return ret; // return removed node }; /** * @method DOMNodeList._appendChild - append the specified Node to the NodeList * Used by DOMNode.appendChild(). Note: DOMNode.appendChild() is responsible for Node Pointer surgery * DOMNodeList._appendChild() simply modifies the internal data structure (Array). * * @author Jon van Noort ([email protected]) * @param newChild : DOMNode - the Node to be inserted */ var __appendChild__ = function(nodelist, newChild) { if (newChild.nodeType == DOMNode.DOCUMENT_FRAGMENT_NODE) { // node is a DocumentFragment // append the children of DocumentFragment Array.prototype.push.apply(nodelist, newChild.childNodes); } else { // simply add node to array (links between Nodes are made at higher level) Array.prototype.push.apply(nodelist, [newChild]); } //$log("__appendChild__ : length " + nodelist.length + " all -> " + document.all.length); }; /** * @method DOMNodeList._cloneNodes - Returns a NodeList containing clones of the Nodes in this NodeList * * @author Jon van Noort ([email protected]) * @param deep : boolean - If true, recursively clone the subtree under each of the nodes; * if false, clone only the nodes themselves (and their attributes, if it is an Element). * @param parentNode : DOMNode - the new parent of the cloned NodeList * @return : DOMNodeList - NodeList containing clones of the Nodes in this NodeList */ var __cloneNodes__ = function(nodelist, deep, parentNode) { var cloneNodeList = new DOMNodeList(nodelist.ownerDocument, parentNode); // create list containing clones of each child for (var i=0; i < nodelist.length; i++) { __appendChild__(cloneNodeList, nodelist[i].cloneNode(deep)); } return cloneNodeList; }; /** * @class DOMNamedNodeMap - used to represent collections of nodes that can be accessed by name * typically a set of Element attributes * * @extends DOMNodeList - note W3C spec says that this is not the case, * but we need an item() method identicle to DOMNodeList's, so why not? * @author Jon van Noort ([email protected]) * @param ownerDocument : DOMDocument - the ownerDocument * @param parentNode : DOMNode - the node that the DOMNamedNodeMap is attached to (or null) */ var DOMNamedNodeMap = function(ownerDocument, parentNode) { //$log("\t\tcreating dom namednodemap"); this.DOMNodeList = DOMNodeList; this.DOMNodeList(ownerDocument, parentNode); __setArray__(this, []); }; DOMNamedNodeMap.prototype = new DOMNodeList; __extend__(DOMNamedNodeMap.prototype, { getNamedItem : function(name) { var ret = null; // test that Named Node exists var itemIndex = __findNamedItemIndex__(this, name); if (itemIndex > -1) { // found it! ret = this[itemIndex]; // return NamedNode } return ret; // if node is not found, default value null is returned }, setNamedItem : function(arg) { // test for exceptions if (this.ownerDocument.implementation.errorChecking) { // throw Exception if arg was not created by this Document if (this.ownerDocument != arg.ownerDocument) { throw(new DOMException(DOMException.WRONG_DOCUMENT_ERR)); } // throw Exception if DOMNamedNodeMap is readonly if (this._readonly || (this.parentNode && this.parentNode._readonly)) { throw(new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR)); } // throw Exception if arg is already an attribute of another Element object if (arg.ownerElement && (arg.ownerElement != this.parentNode)) { throw(new DOMException(DOMException.INUSE_ATTRIBUTE_ERR)); } } // get item index var itemIndex = __findNamedItemIndex__(this, arg.name); var ret = null; if (itemIndex > -1) { // found it! ret = this[itemIndex]; // use existing Attribute // throw Exception if DOMAttr is readonly if (this.ownerDocument.implementation.errorChecking && ret._readonly) { throw(new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR)); } else { this[itemIndex] = arg; // over-write existing NamedNode } } else { // add new NamedNode Array.prototype.push.apply(this, [arg]); } arg.ownerElement = this.parentNode; // update ownerElement return ret; // return old node or null }, removeNamedItem : function(name) { var ret = null; // test for exceptions // throw Exception if DOMNamedNodeMap is readonly if (this.ownerDocument.implementation.errorChecking && (this._readonly || (this.parentNode && this.parentNode._readonly))) { throw(new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR)); } // get item index var itemIndex = __findNamedItemIndex__(this, name); // throw Exception if there is no node named name in this map if (this.ownerDocument.implementation.errorChecking && (itemIndex < 0)) { throw(new DOMException(DOMException.NOT_FOUND_ERR)); } // get Node var oldNode = this[itemIndex]; // throw Exception if Node is readonly if (this.ownerDocument.implementation.errorChecking && oldNode._readonly) { throw(new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR)); } // return removed node return __removeChild__(this, itemIndex); }, getNamedItemNS : function(namespaceURI, localName) { var ret = null; // test that Named Node exists var itemIndex = __findNamedItemNSIndex__(this, namespaceURI, localName); if (itemIndex > -1) { // found it! ret = this[itemIndex]; // return NamedNode } return ret; // if node is not found, default value null is returned }, setNamedItemNS : function(arg) { // test for exceptions if (this.ownerDocument.implementation.errorChecking) { // throw Exception if DOMNamedNodeMap is readonly if (this._readonly || (this.parentNode && this.parentNode._readonly)) { throw(new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR)); } // throw Exception if arg was not created by this Document if (this.ownerDocument != arg.ownerDocument) { throw(new DOMException(DOMException.WRONG_DOCUMENT_ERR)); } // throw Exception if arg is already an attribute of another Element object if (arg.ownerElement && (arg.ownerElement != this.parentNode)) { throw(new DOMException(DOMException.INUSE_ATTRIBUTE_ERR)); } } // get item index var itemIndex = __findNamedItemNSIndex__(this, arg.namespaceURI, arg.localName); var ret = null; if (itemIndex > -1) { // found it! ret = this[itemIndex]; // use existing Attribute // throw Exception if DOMAttr is readonly if (this.ownerDocument.implementation.errorChecking && ret._readonly) { throw(new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR)); } else { this[itemIndex] = arg; // over-write existing NamedNode } }else { // add new NamedNode Array.prototype.push.apply(this, [arg]); } arg.ownerElement = this.parentNode; return ret; // return old node or null }, removeNamedItemNS : function(namespaceURI, localName) { var ret = null; // test for exceptions // throw Exception if DOMNamedNodeMap is readonly if (this.ownerDocument.implementation.errorChecking && (this._readonly || (this.parentNode && this.parentNode._readonly))) { throw(new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR)); } // get item index var itemIndex = __findNamedItemNSIndex__(this, namespaceURI, localName); // throw Exception if there is no matching node in this map if (this.ownerDocument.implementation.errorChecking && (itemIndex < 0)) { throw(new DOMException(DOMException.NOT_FOUND_ERR)); } // get Node var oldNode = this[itemIndex]; // throw Exception if Node is readonly if (this.ownerDocument.implementation.errorChecking && oldNode._readonly) { throw(new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR)); } return __removeChild__(this, itemIndex); // return removed node }, get xml() { var ret = ""; // create string containing concatenation of all (but last) Attribute string values (separated by spaces) for (var i=0; i < this.length -1; i++) { ret += this[i].xml +" "; } // add last Attribute to string (without trailing space) if (this.length > 0) { ret += this[this.length -1].xml; } return ret; } }); /** * @method DOMNamedNodeMap._findNamedItemIndex - find the item index of the node with the specified name * * @author Jon van Noort ([email protected]) * @param name : string - the name of the required node * @param isnsmap : if its a DOMNamespaceNodeMap * @return : int */ var __findNamedItemIndex__ = function(namednodemap, name, isnsmap) { var ret = -1; // loop through all nodes for (var i=0; i<namednodemap.length; i++) { // compare name to each node's nodeName if(isnsmap){ if (namednodemap[i].localName == localName) { // found it! ret = i; break; } }else{ if (namednodemap[i].name == name) { // found it! ret = i; break; } } } return ret; // if node is not found, default value -1 is returned }; /** * @method DOMNamedNodeMap._findNamedItemNSIndex - find the item index of the node with the specified namespaceURI and localName * * @author Jon van Noort ([email protected]) * @param namespaceURI : string - the namespace URI of the required node * @param localName : string - the local name of the required node * @return : int */ var __findNamedItemNSIndex__ = function(namednodemap, namespaceURI, localName) { var ret = -1; // test that localName is not null if (localName) { // loop through all nodes for (var i=0; i<namednodemap.length; i++) { // compare name to each node's namespaceURI and localName if ((namednodemap[i].namespaceURI == namespaceURI) && (namednodemap[i].localName == localName)) { ret = i; // found it! break; } } } return ret; // if node is not found, default value -1 is returned }; /** * @method DOMNamedNodeMap._hasAttribute - Returns true if specified node exists * * @author Jon van Noort ([email protected]) * @param name : string - the name of the required node * @return : boolean */ var __hasAttribute__ = function(namednodemap, name) { var ret = false; // test that Named Node exists var itemIndex = __findNamedItemIndex__(namednodemap, name); if (itemIndex > -1) { // found it! ret = true; // return true } return ret; // if node is not found, default value false is returned } /** * @method DOMNamedNodeMap._hasAttributeNS - Returns true if specified node exists * * @author Jon van Noort ([email protected]) * @param namespaceURI : string - the namespace URI of the required node * @param localName : string - the local name of the required node * @return : boolean */ var __hasAttributeNS__ = function(namednodemap, namespaceURI, localName) { var ret = false; // test that Named Node exists var itemIndex = __findNamedItemNSIndex__(namednodemap, namespaceURI, localName); if (itemIndex > -1) { // found it! ret = true; // return true } return ret; // if node is not found, default value false is returned } /** * @method DOMNamedNodeMap._cloneNodes - Returns a NamedNodeMap containing clones of the Nodes in this NamedNodeMap * * @author Jon van Noort ([email protected]) * @param parentNode : DOMNode - the new parent of the cloned NodeList * @param isnsmap : bool - is this a DOMNamespaceNodeMap * @return : DOMNamedNodeMap - NamedNodeMap containing clones of the Nodes in this DOMNamedNodeMap */ var __cloneNamedNodes__ = function(namednodemap, parentNode, isnsmap) { var cloneNamedNodeMap = isnsmap? new DOMNamespaceNodeMap(namednodemap.ownerDocument, parentNode): new DOMNamedNodeMap(namednodemap.ownerDocument, parentNode); // create list containing clones of all children for (var i=0; i < namednodemap.length; i++) { $log("cloning node in named node map :" + namednodemap[i]); __appendChild__(cloneNamedNodeMap, namednodemap[i].cloneNode(false)); } return cloneNamedNodeMap; }; /** * @class DOMNamespaceNodeMap - used to represent collections of namespace nodes that can be accessed by name * typically a set of Element attributes * * @extends DOMNamedNodeMap * * @author Jon van Noort ([email protected]) * * @param ownerDocument : DOMDocument - the ownerDocument * @param parentNode : DOMNode - the node that the DOMNamespaceNodeMap is attached to (or null) */ var DOMNamespaceNodeMap = function(ownerDocument, parentNode) { //$log("\t\t\tcreating dom namespacednodemap"); this.DOMNamedNodeMap = DOMNamedNodeMap; this.DOMNamedNodeMap(ownerDocument, parentNode); __setArray__(this, []); }; DOMNamespaceNodeMap.prototype = new DOMNamedNodeMap; __extend__(DOMNamespaceNodeMap.prototype, { get xml() { var ret = ""; // identify namespaces declared local to this Element (ie, not inherited) for (var ind = 0; ind < this.length; ind++) { // if namespace declaration does not exist in the containing node's, parentNode's namespaces var ns = null; try { var ns = this.parentNode.parentNode._namespaces.getNamedItem(this[ind].localName); } catch (e) { //breaking to prevent default namespace being inserted into return value break; } if (!(ns && (""+ ns.nodeValue == ""+ this[ind].nodeValue))) { // display the namespace declaration ret += this[ind].xml +" "; } } return ret; } }); $log("Defining Node"); /* * Node - DOM Level 2 */ $w.__defineGetter__('Node', function(){ return __extend__(function(){ throw new Error("Object cannot be created in this context"); } , { ELEMENT_NODE :1, ATTRIBUTE_NODE :2, TEXT_NODE :3, CDATA_SECTION_NODE: 4, PROCESSING_INSTRUCTION_NODE: 7, COMMENT_NODE: 8, DOCUMENT_NODE: 9, DOCUMENT_TYPE_NODE: 10, DOCUMENT_FRAGMENT_NODE: 11 }); }); /** * @class DOMNode - The Node interface is the primary datatype for the entire Document Object Model. * It represents a single node in the document tree. * @author Jon van Noort ([email protected]), David Joham ([email protected]) and Scott Severtson * @param ownerDocument : DOMDocument - The Document object associated with this node. */ var DOMNode = function(ownerDocument) { //$log("\tcreating dom node"); if (ownerDocument) { this._id = ownerDocument._genId(); // generate unique internal id } this.namespaceURI = ""; // The namespace URI of this node (Level 2) this.prefix = ""; // The namespace prefix of this node (Level 2) this.localName = ""; // The localName of this node (Level 2) this.nodeName = ""; // The name of this node this.nodeValue = ""; // The value of this node // The parent of this node. All nodes, except Document, DocumentFragment, and Attr may have a parent. // However, if a node has just been created and not yet added to the tree, or if it has been removed from the tree, this is null this.parentNode = null; // A NodeList that contains all children of this node. If there are no children, this is a NodeList containing no nodes. // The content of the returned NodeList is "live" in the sense that, for instance, changes to the children of the node object // that it was created from are immediately reflected in the nodes returned by the NodeList accessors; // it is not a static snapshot of the content of the node. This is true for every NodeList, including the ones returned by the getElementsByTagName method. this.childNodes = new DOMNodeList(ownerDocument, this); this.firstChild = null; // The first child of this node. If there is no such node, this is null this.lastChild = null; // The last child of this node. If there is no such node, this is null. this.previousSibling = null; // The node immediately preceding this node. If there is no such node, this is null. this.nextSibling = null; // The node immediately following this node. If there is no such node, this is null. this.attributes = new DOMNamedNodeMap(ownerDocument, this); // A NamedNodeMap containing the attributes of this node (if it is an Element) or null otherwise. this.ownerDocument = ownerDocument; // The Document object associated with this node this._namespaces = new DOMNamespaceNodeMap(ownerDocument, this); // The namespaces in scope for this node this._readonly = false; }; // nodeType constants DOMNode.ELEMENT_NODE = 1; DOMNode.ATTRIBUTE_NODE = 2; DOMNode.TEXT_NODE = 3; DOMNode.CDATA_SECTION_NODE = 4; DOMNode.ENTITY_REFERENCE_NODE = 5; DOMNode.ENTITY_NODE = 6; DOMNode.PROCESSING_INSTRUCTION_NODE = 7; DOMNode.COMMENT_NODE = 8; DOMNode.DOCUMENT_NODE = 9; DOMNode.DOCUMENT_TYPE_NODE = 10; DOMNode.DOCUMENT_FRAGMENT_NODE = 11; DOMNode.NOTATION_NODE = 12; DOMNode.NAMESPACE_NODE = 13; __extend__(DOMNode.prototype, { hasAttributes : function() { if (this.attributes.length == 0) { return false; }else{ return true; } }, insertBefore : function(newChild, refChild) { var prevNode; // test for exceptions if (this.ownerDocument.implementation.errorChecking) { // throw Exception if DOMNode is readonly if (this._readonly) { throw(new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR)); } // throw Exception if newChild was not created by this Document if (this.ownerDocument != newChild.ownerDocument) { throw(new DOMException(DOMException.WRONG_DOCUMENT_ERR)); } // throw Exception if the node is an ancestor if (__isAncestor__(this, newChild)) { throw(new DOMException(DOMException.HIERARCHY_REQUEST_ERR)); } } if (refChild) { // if refChild is specified, insert before it // find index of refChild var itemIndex = __findItemIndex__(this.childNodes, refChild._id); // throw Exception if there is no child node with this id if (this.ownerDocument.implementation.errorChecking && (itemIndex < 0)) { throw(new DOMException(DOMException.NOT_FOUND_ERR)); } // if the newChild is already in the tree, var newChildParent = newChild.parentNode; if (newChildParent) { // remove it newChildParent.removeChild(newChild); } // insert newChild into childNodes __insertBefore__(this.childNodes, newChild, __findItemIndex__(this.childNodes, refChild._id)); // do node pointer surgery prevNode = refChild.previousSibling; // handle DocumentFragment if (newChild.nodeType == DOMNode.DOCUMENT_FRAGMENT_NODE) { if (newChild.childNodes.length > 0) { // set the parentNode of DocumentFragment's children for (var ind = 0; ind < newChild.childNodes.length; ind++) { newChild.childNodes[ind].parentNode = this; } // link refChild to last child of DocumentFragment refChild.previousSibling = newChild.childNodes[newChild.childNodes.length-1]; } }else { newChild.parentNode = this; // set the parentNode of the newChild refChild.previousSibling = newChild; // link refChild to newChild } }else { // otherwise, append to end prevNode = this.lastChild; this.appendChild(newChild); } if (newChild.nodeType == DOMNode.DOCUMENT_FRAGMENT_NODE) { // do node pointer surgery for DocumentFragment if (newChild.childNodes.length > 0) { if (prevNode) { prevNode.nextSibling = newChild.childNodes[0]; }else { // this is the first child in the list this.firstChild = newChild.childNodes[0]; } newChild.childNodes[0].previousSibling = prevNode; newChild.childNodes[newChild.childNodes.length-1].nextSibling = refChild; } }else { // do node pointer surgery for newChild if (prevNode) { prevNode.nextSibling = newChild; }else { // this is the first child in the list this.firstChild = newChild; } newChild.previousSibling = prevNode; newChild.nextSibling = refChild; } return newChild; }, replaceChild : function(newChild, oldChild) { var ret = null; // test for exceptions if (this.ownerDocument.implementation.errorChecking) { // throw Exception if DOMNode is readonly if (this._readonly) { throw(new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR)); } // throw Exception if newChild was not created by this Document if (this.ownerDocument != newChild.ownerDocument) { throw(new DOMException(DOMException.WRONG_DOCUMENT_ERR)); } // throw Exception if the node is an ancestor if (__isAncestor__(this, newChild)) { throw(new DOMException(DOMException.HIERARCHY_REQUEST_ERR)); } } // get index of oldChild var index = __findItemIndex__(this.childNodes, oldChild._id); // throw Exception if there is no child node with this id if (this.ownerDocument.implementation.errorChecking && (index < 0)) { throw(new DOMException(DOMException.NOT_FOUND_ERR)); } // if the newChild is already in the tree, var newChildParent = newChild.parentNode; if (newChildParent) { // remove it newChildParent.removeChild(newChild); } // add newChild to childNodes ret = __replaceChild__(this.childNodes,newChild, index); if (newChild.nodeType == DOMNode.DOCUMENT_FRAGMENT_NODE) { // do node pointer surgery for Document Fragment if (newChild.childNodes.length > 0) { for (var ind = 0; ind < newChild.childNodes.length; ind++) { newChild.childNodes[ind].parentNode = this; } if (oldChild.previousSibling) { oldChild.previousSibling.nextSibling = newChild.childNodes[0]; } else { this.firstChild = newChild.childNodes[0]; } if (oldChild.nextSibling) { oldChild.nextSibling.previousSibling = newChild; } else { this.lastChild = newChild.childNodes[newChild.childNodes.length-1]; } newChild.childNodes[0].previousSibling = oldChild.previousSibling; newChild.childNodes[newChild.childNodes.length-1].nextSibling = oldChild.nextSibling; } } else { // do node pointer surgery for newChild newChild.parentNode = this; if (oldChild.previousSibling) { oldChild.previousSibling.nextSibling = newChild; }else{ this.firstChild = newChild; } if (oldChild.nextSibling) { oldChild.nextSibling.previousSibling = newChild; }else{ this.lastChild = newChild; } newChild.previousSibling = oldChild.previousSibling; newChild.nextSibling = oldChild.nextSibling; } //this.removeChild(oldChild); return ret; }, removeChild : function(oldChild) { // throw Exception if DOMNamedNodeMap is readonly if (this.ownerDocument.implementation.errorChecking && (this._readonly || oldChild._readonly)) { throw(new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR)); } // get index of oldChild var itemIndex = __findItemIndex__(this.childNodes, oldChild._id); // throw Exception if there is no child node with this id if (this.ownerDocument.implementation.errorChecking && (itemIndex < 0)) { throw(new DOMException(DOMException.NOT_FOUND_ERR)); } // remove oldChild from childNodes __removeChild__(this.childNodes, itemIndex); // do node pointer surgery oldChild.parentNode = null; if (oldChild.previousSibling) { oldChild.previousSibling.nextSibling = oldChild.nextSibling; }else { this.firstChild = oldChild.nextSibling; } if (oldChild.nextSibling) { oldChild.nextSibling.previousSibling = oldChild.previousSibling; }else { this.lastChild = oldChild.previousSibling; } oldChild.previousSibling = null; oldChild.nextSibling = null; /*if(oldChild.ownerDocument == document){ $log("removeChild : all -> " + document.all.length); }*/ return oldChild; }, appendChild : function(newChild) { // test for exceptions if (this.ownerDocument.implementation.errorChecking) { // throw Exception if Node is readonly if (this._readonly) { throw(new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR)); } // throw Exception if arg was not created by this Document if (this.ownerDocument != newChild.ownerDocument) { throw(new DOMException(DOMException.WRONG_DOCUMENT_ERR)); } // throw Exception if the node is an ancestor if (__isAncestor__(this, newChild)) { throw(new DOMException(DOMException.HIERARCHY_REQUEST_ERR)); } } // if the newChild is already in the tree, var newChildParent = newChild.parentNode; if (newChildParent) { // remove it newChildParent.removeChild(newChild); } // add newChild to childNodes __appendChild__(this.childNodes, newChild); if (newChild.nodeType == DOMNode.DOCUMENT_FRAGMENT_NODE) { // do node pointer surgery for DocumentFragment if (newChild.childNodes.length > 0) { for (var ind = 0; ind < newChild.childNodes.length; ind++) { newChild.childNodes[ind].parentNode = this; } if (this.lastChild) { this.lastChild.nextSibling = newChild.childNodes[0]; newChild.childNodes[0].previousSibling = this.lastChild; this.lastChild = newChild.childNodes[newChild.childNodes.length-1]; } else { this.lastChild = newChild.childNodes[newChild.childNodes.length-1]; this.firstChild = newChild.childNodes[0]; } } } else { // do node pointer surgery for newChild newChild.parentNode = this; if (this.lastChild) { this.lastChild.nextSibling = newChild; newChild.previousSibling = this.lastChild; this.lastChild = newChild; } else { this.lastChild = newChild; this.firstChild = newChild; } } return newChild; }, hasChildNodes : function() { return (this.childNodes.length > 0); }, cloneNode: function(deep) { // use importNode to clone this Node //do not throw any exceptions //$log("cloning node"); try { return this.ownerDocument.importNode(this, deep); } catch (e) { //there shouldn't be any exceptions, but if there are, return null return null; } }, normalize : function() { var inode; var nodesToRemove = new DOMNodeList(); if (this.nodeType == DOMNode.ELEMENT_NODE || this.nodeType == DOMNode.DOCUMENT_NODE) { var adjacentTextNode = null; // loop through all childNodes for(var i = 0; i < this.childNodes.length; i++) { inode = this.childNodes.item(i); if (inode.nodeType == DOMNode.TEXT_NODE) { // this node is a text node if (inode.length < 1) { // this text node is empty __appendChild__(nodesToRemove, inode); // add this node to the list of nodes to be remove }else { if (adjacentTextNode) { // if previous node was also text adjacentTextNode.appendData(inode.data); // merge the data in adjacent text nodes __appendChild__(nodesToRemove, inode); // add this node to the list of nodes to be removed }else { adjacentTextNode = inode; // remember this node for next cycle } } } else { adjacentTextNode = null; // (soon to be) previous node is not a text node inode.normalize(); // normalise non Text childNodes } } // remove redundant Text Nodes for(var i = 0; i < nodesToRemove.length; i++) { inode = nodesToRemove.item(i); inode.parentNode.removeChild(inode); } } }, isSupported : function(feature, version) { // use Implementation.hasFeature to determin if this feature is supported return this.ownerDocument.implementation.hasFeature(feature, version); }, getElementsByTagName : function(tagname) { // delegate to _getElementsByTagNameRecursive //$log("getElementsByTagName("+tagname+")"); return __getElementsByTagNameRecursive__(this, tagname, new DOMNodeList(this.ownerDocument)); }, getElementsByTagNameNS : function(namespaceURI, localName) { // delegate to _getElementsByTagNameNSRecursive return __getElementsByTagNameNSRecursive__(this, namespaceURI, localName, new DOMNodeList(this.ownerDocument)); }, importNode : function(importedNode, deep) { var importNode; //$log("importing node " + importedNode + "(?deep = "+deep+")"); //there is no need to perform namespace checks since everything has already gone through them //in order to have gotten into the DOM in the first place. The following line //turns namespace checking off in ._isValidNamespace this.ownerDocument._performingImportNodeOperation = true; try { if (importedNode.nodeType == DOMNode.ELEMENT_NODE) { if (!this.ownerDocument.implementation.namespaceAware) { // create a local Element (with the name of the importedNode) importNode = this.ownerDocument.createElement(importedNode.tagName); // create attributes matching those of the importedNode for(var i = 0; i < importedNode.attributes.length; i++) { importNode.setAttribute(importedNode.attributes.item(i).name, importedNode.attributes.item(i).value); } }else { // create a local Element (with the name & namespaceURI of the importedNode) importNode = this.ownerDocument.createElementNS(importedNode.namespaceURI, importedNode.nodeName); // create attributes matching those of the importedNode for(var i = 0; i < importedNode.attributes.length; i++) { importNode.setAttributeNS(importedNode.attributes.item(i).namespaceURI, importedNode.attributes.item(i).name, importedNode.attributes.item(i).value); } // create namespace definitions matching those of the importedNode for(var i = 0; i < importedNode._namespaces.length; i++) { importNode._namespaces[i] = this.ownerDocument.createNamespace(importedNode._namespaces.item(i).localName); importNode._namespaces[i].value = importedNode._namespaces.item(i).value; } } } else if (importedNode.nodeType == DOMNode.ATTRIBUTE_NODE) { if (!this.ownerDocument.implementation.namespaceAware) { // create a local Attribute (with the name of the importedAttribute) importNode = this.ownerDocument.createAttribute(importedNode.name); } else { // create a local Attribute (with the name & namespaceURI of the importedAttribute) importNode = this.ownerDocument.createAttributeNS(importedNode.namespaceURI, importedNode.nodeName); // create namespace definitions matching those of the importedAttribute for(var i = 0; i < importedNode._namespaces.length; i++) { importNode._namespaces[i] = this.ownerDocument.createNamespace(importedNode._namespaces.item(i).localName); importNode._namespaces[i].value = importedNode._namespaces.item(i).value; } } // set the value of the local Attribute to match that of the importedAttribute importNode.value = importedNode.value; } else if (importedNode.nodeType == DOMNode.DOCUMENT_FRAGMENT) { // create a local DocumentFragment importNode = this.ownerDocument.createDocumentFragment(); } else if (importedNode.nodeType == DOMNode.NAMESPACE_NODE) { // create a local NamespaceNode (with the same name & value as the importedNode) importNode = this.ownerDocument.createNamespace(importedNode.nodeName); importNode.value = importedNode.value; } else if (importedNode.nodeType == DOMNode.TEXT_NODE) { // create a local TextNode (with the same data as the importedNode) importNode = this.ownerDocument.createTextNode(importedNode.data); } else if (importedNode.nodeType == DOMNode.CDATA_SECTION_NODE) { // create a local CDATANode (with the same data as the importedNode) importNode = this.ownerDocument.createCDATASection(importedNode.data); } else if (importedNode.nodeType == DOMNode.PROCESSING_INSTRUCTION_NODE) { // create a local ProcessingInstruction (with the same target & data as the importedNode) importNode = this.ownerDocument.createProcessingInstruction(importedNode.target, importedNode.data); } else if (importedNode.nodeType == DOMNode.COMMENT_NODE) { // create a local Comment (with the same data as the importedNode) importNode = this.ownerDocument.createComment(importedNode.data); } else { // throw Exception if nodeType is not supported throw(new DOMException(DOMException.NOT_SUPPORTED_ERR)); } if (deep) { // recurse childNodes for(var i = 0; i < importedNode.childNodes.length; i++) { importNode.appendChild(this.ownerDocument.importNode(importedNode.childNodes.item(i), true)); } } //reset _performingImportNodeOperation this.ownerDocument._performingImportNodeOperation = false; return importNode; } catch (eAny) { //reset _performingImportNodeOperation this.ownerDocument._performingImportNodeOperation = false; //re-throw the exception throw eAny; }//djotemp }, contains : function(node){ while(node && node != this ){ node = node.parentNode; } return !!node; }, compareDocumentPosition : function(b){ var a = this; var number = (a != b && a.contains(b) && 16) + (a != b && b.contains(a) && 8); //find position of both var all = document.getElementsByTagName("*"); var my_location = 0, node_location = 0; for(var i=0; i < all.length; i++){ if(all[i] == a) my_location = i; if(all[i] == b) node_location = i; if(my_location && node_location) break; } number += (my_location < node_location && 4) number += (my_location > node_location && 2) return number; } }); /** * @method DOMNode._getElementsByTagNameRecursive - implements getElementsByTagName() * @param elem : DOMElement - The element which are checking and then recursing into * @param tagname : string - The name of the tag to match on. The special value "*" matches all tags * @param nodeList : DOMNodeList - The accumulating list of matching nodes * * @return : DOMNodeList */ var __getElementsByTagNameRecursive__ = function (elem, tagname, nodeList) { //$log("__getElementsByTagNameRecursive__("+elem._id+")"); if (elem.nodeType == DOMNode.ELEMENT_NODE || elem.nodeType == DOMNode.DOCUMENT_NODE) { if((elem.nodeName.toUpperCase() == tagname.toUpperCase()) || (tagname == "*")) { //$log("found node by name " + tagname); __appendChild__(nodeList, elem); // add matching node to nodeList } // recurse childNodes for(var i = 0; i < elem.childNodes.length; i++) { nodeList = __getElementsByTagNameRecursive__(elem.childNodes.item(i), tagname, nodeList); } } return nodeList; }; /** * @method DOMNode._getElementsByTagNameNSRecursive - implements getElementsByTagName() * * @param elem : DOMElement - The element which are checking and then recursing into * @param namespaceURI : string - the namespace URI of the required node * @param localName : string - the local name of the required node * @param nodeList : DOMNodeList - The accumulating list of matching nodes * * @return : DOMNodeList */ var __getElementsByTagNameNSRecursive__ = function(elem, namespaceURI, localName, nodeList) { if (elem.nodeType == DOMNode.ELEMENT_NODE || elem.nodeType == DOMNode.DOCUMENT_NODE) { if (((elem.namespaceURI == namespaceURI) || (namespaceURI == "*")) && ((elem.localName == localName) || (localName == "*"))) { __appendChild__(nodeList, elem); // add matching node to nodeList } // recurse childNodes for(var i = 0; i < elem.childNodes.length; i++) { nodeList = __getElementsByTagNameNSRecursive__(elem.childNodes.item(i), namespaceURI, localName, nodeList); } } return nodeList; }; /** * @method DOMNode._isAncestor - returns true if node is ancestor of target * @param target : DOMNode - The node we are using as context * @param node : DOMNode - The candidate ancestor node * @return : boolean */ var __isAncestor__ = function(target, node) { // if this node matches, return true, // otherwise recurse up (if there is a parentNode) return ((target == node) || ((target.parentNode) && (__isAncestor__(target.parentNode, node)))); } /** * @class DOMNamespace - The Namespace interface represents an namespace in an Element object * * @extends DOMNode * @author Jon van Noort ([email protected]) * @param ownerDocument : DOMDocument - The Document object associated with this node. */ var DOMNamespace = function(ownerDocument) { this.DOMNode = DOMNode; this.DOMNode(ownerDocument); this.name = ""; // the name of this attribute // If this attribute was explicitly given a value in the original document, this is true; otherwise, it is false. // Note that the implementation is in charge of this attribute, not the user. // If the user changes the value of the attribute (even if it ends up having the same value as the default value) // then the specified flag is automatically flipped to true this.specified = false; }; DOMNamespace.prototype = new DOMNode; __extend__(DOMNamespace.prototype, { get value(){ // the value of the attribute is returned as a string return this.nodeValue; }, set value(value){ this.nodeValue = String(value); }, get nodeType(){ return DOMNode.NAMESPACE_NODE; }, get xml(){ var ret = ""; // serialize Namespace Declaration if (this.nodeName != "") { ret += this.nodeName +"=\""+ __escapeXML__(this.nodeValue) +"\""; } else { // handle default namespace ret += "xmlns=\""+ __escapeXML__(this.nodeValue) +"\""; } return ret; }, toString: function(){ return "Namespace #" + this.id; } }); $debug("Defining CharacterData"); /* * CharacterData - DOM Level 2 */ $w.__defineGetter__("CharacterData", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); /** * @class DOMCharacterData - parent abstract class for DOMText and DOMComment * @extends DOMNode * @author Jon van Noort ([email protected]) * @param ownerDocument : DOMDocument - The Document object associated with this node. */ var DOMCharacterData = function(ownerDocument) { this.DOMNode = DOMNode; this.DOMNode(ownerDocument); }; DOMCharacterData.prototype = new DOMNode; __extend__(DOMCharacterData.prototype,{ get data(){ return String(this.nodeValue); }, set data(data){ this.nodeValue = String(data); }, get length(){return this.nodeValue.length;}, appendData: function(arg){ // throw Exception if DOMCharacterData is readonly if (this.ownerDocument.implementation.errorChecking && this._readonly) { throw(new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR)); } // append data this.data = "" + this.data + arg; }, deleteData: function(offset, count){ // throw Exception if DOMCharacterData is readonly if (this.ownerDocument.implementation.errorChecking && this._readonly) { throw(new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR)); } if (this.data) { // throw Exception if offset is negative or greater than the data length, if (this.ownerDocument.implementation.errorChecking && ((offset < 0) || (offset > this.data.length) || (count < 0))) { throw(new DOMException(DOMException.INDEX_SIZE_ERR)); } // delete data if(!count || (offset + count) > this.data.length) { this.data = this.data.substring(0, offset); }else { this.data = this.data.substring(0, offset).concat(this.data.substring(offset + count)); } } }, insertData: function(offset, arg){ // throw Exception if DOMCharacterData is readonly if(this.ownerDocument.implementation.errorChecking && this._readonly){ throw(new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR)); } if(this.data){ // throw Exception if offset is negative or greater than the data length, if (this.ownerDocument.implementation.errorChecking && ((offset < 0) || (offset > this.data.length))) { throw(new DOMException(DOMException.INDEX_SIZE_ERR)); } // insert data this.data = this.data.substring(0, offset).concat(arg, this.data.substring(offset)); }else { // throw Exception if offset is negative or greater than the data length, if (this.ownerDocument.implementation.errorChecking && (offset != 0)) { throw(new DOMException(DOMException.INDEX_SIZE_ERR)); } // set data this.data = arg; } }, replaceData: function(offset, count, arg){ // throw Exception if DOMCharacterData is readonly if (this.ownerDocument.implementation.errorChecking && this._readonly) { throw(new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR)); } if (this.data) { // throw Exception if offset is negative or greater than the data length, if (this.ownerDocument.implementation.errorChecking && ((offset < 0) || (offset > this.data.length) || (count < 0))) { throw(new DOMException(DOMException.INDEX_SIZE_ERR)); } // replace data this.data = this.data.substring(0, offset).concat(arg, this.data.substring(offset + count)); }else { // set data this.data = arg; } }, substringData: function(offset, count){ var ret = null; if (this.data) { // throw Exception if offset is negative or greater than the data length, // or the count is negative if (this.ownerDocument.implementation.errorChecking && ((offset < 0) || (offset > this.data.length) || (count < 0))) { throw(new DOMException(DOMException.INDEX_SIZE_ERR)); } // if count is not specified if (!count) { ret = this.data.substring(offset); // default to 'end of string' }else{ ret = this.data.substring(offset, offset + count); } } return ret; } }); $log("Defining Text"); /* * Text - DOM Level 2 */ $w.__defineGetter__("Text", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); /** * @class DOMText - The Text interface represents the textual content (termed character data in XML) of an Element or Attr. * If there is no markup inside an element's content, the text is contained in a single object implementing the Text interface * that is the only child of the element. If there is markup, it is parsed into a list of elements and Text nodes that form the * list of children of the element. * @extends DOMCharacterData * @author Jon van Noort ([email protected]) and David Joham ([email protected]) * @param ownerDocument : DOMDocument - The Document object associated with this node. */ DOMText = function(ownerDocument) { this.DOMCharacterData = DOMCharacterData; this.DOMCharacterData(ownerDocument); this.nodeName = "#text"; }; DOMText.prototype = new DOMCharacterData; __extend__(DOMText.prototype,{ //Breaks this Text node into two Text nodes at the specified offset, // keeping both in the tree as siblings. This node then only contains all the content up to the offset point. // And a new Text node, which is inserted as the next sibling of this node, contains all the content at and after the offset point. splitText : function(offset) { var data, inode; // test for exceptions if (this.ownerDocument.implementation.errorChecking) { // throw Exception if Node is readonly if (this._readonly) { throw(new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR)); } // throw Exception if offset is negative or greater than the data length, if ((offset < 0) || (offset > this.data.length)) { throw(new DOMException(DOMException.INDEX_SIZE_ERR)); } } if (this.parentNode) { // get remaining string (after offset) data = this.substringData(offset); // create new TextNode with remaining string inode = this.ownerDocument.createTextNode(data); // attach new TextNode if (this.nextSibling) { this.parentNode.insertBefore(inode, this.nextSibling); } else { this.parentNode.appendChild(inode); } // remove remaining string from original TextNode this.deleteData(offset); } return inode; }, get nodeType(){ return DOMNode.TEXT_NODE; }, get xml(){ return __escapeXML__(""+ this.nodeValue); }, toString: function(){ return "Text #" + this._id; } }); $log("Defining CDATASection"); /* * CDATASection - DOM Level 2 */ $w.__defineGetter__("CDATASection", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); /** * @class DOMCDATASection - CDATA sections are used to escape blocks of text containing characters that would otherwise be regarded as markup. * The only delimiter that is recognized in a CDATA section is the "\]\]\>" string that ends the CDATA section * @extends DOMCharacterData * @author Jon van Noort ([email protected]) and David Joham ([email protected]) * @param ownerDocument : DOMDocument - The Document object associated with this node. */ var DOMCDATASection = function(ownerDocument) { this.DOMText = DOMText; this.DOMText(ownerDocument); this.nodeName = "#cdata-section"; }; DOMCDATASection.prototype = new DOMText; __extend__(DOMCDATASection.prototype,{ get nodeType(){ return DOMNode.CDATA_SECTION_NODE; }, get xml(){ return "<![CDATA[" + this.nodeValue + "]]>"; }, toString : function(){ return "CDATA #"+this._id; } });$log("Defining Comment"); /* * Comment - DOM Level 2 */ $w.__defineGetter__("Comment", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); /** * @class DOMComment - This represents the content of a comment, i.e., all the characters between the starting '<!--' and ending '-->' * @extends DOMCharacterData * @author Jon van Noort ([email protected]) * @param ownerDocument : DOMDocument - The Document object associated with this node. */ var DOMComment = function(ownerDocument) { this.DOMCharacterData = DOMCharacterData; this.DOMCharacterData(ownerDocument); this.nodeName = "#comment"; }; DOMComment.prototype = new DOMCharacterData; __extend__(DOMComment.prototype, { get nodeType(){ return DOMNode.COMMENT_NODE; }, get xml(){ return "<!-- " + this.nodeValue + " -->"; }, toString : function(){ return "Comment #"+this._id; } }); $log("Defining DocumentType"); ;/* * DocumentType - DOM Level 2 */ $w.__defineGetter__('DocumentType', function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); var DOMDocumentType = function() { $error("DOMDocumentType.constructor(): Not Implemented" ); };$log("Defining Attr"); /* * Attr - DOM Level 2 */ $w.__defineGetter__("Attr", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); /** * @class DOMAttr - The Attr interface represents an attribute in an Element object * @extends DOMNode * @author Jon van Noort ([email protected]) * @param ownerDocument : DOMDocument - The Document object associated with this node. */ var DOMAttr = function(ownerDocument) { //$log("\tcreating dom attribute"); this.DOMNode = DOMNode; this.DOMNode(ownerDocument); this.specified = false; this.ownerElement = null; // set when Attr is added to NamedNodeMap //$log("\tfincished creating dom attribute " + this); }; DOMAttr.prototype = new DOMNode; __extend__(DOMAttr.prototype, { // the name of this attribute get name(){ return this.nodeName; }, set name(name){ this.nodeName = name; }, // the value of the attribute is returned as a string get value(){ return this.nodeValue; }, set value(value){ // throw Exception if Attribute is readonly if (this.ownerDocument.implementation.errorChecking && this._readonly) { throw(new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR)); } // delegate to node this.specified = (this.value.length > 0); this.nodeValue = value; }, get nodeType(){ return DOMNode.ATTRIBUTE_NODE; }, get xml(){ return this.nodeName + "='" + this.nodeValue + "' "; }, toString : function(){ return "Attr #" + this._id + " " + this.name; } }); $log("Defining Element"); /* * Element - DOM Level 2 */ $w.__defineGetter__("Element", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); /** * @class DOMElement - By far the vast majority of objects (apart from text) that authors encounter * when traversing a document are Element nodes. * @extends DOMNode * @author Jon van Noort ([email protected]) and David Joham ([email protected]) * @param ownerDocument : DOMDocument - The Document object associated with this node. */ var DOMElement = function(ownerDocument) { //$log("\tcreating dom element"); this.DOMNode = DOMNode; this.DOMNode(ownerDocument); this.id = ""; // the ID of the element //$log("\nfinished creating dom element " + this); }; DOMElement.prototype = new DOMNode; __extend__(DOMElement.prototype, { // The name of the element. get tagName(){ return this.nodeName; }, set tagName(name){ this.nodeName = name; }, addEventListener : function(){ window.addEventListener.apply(this, arguments) }, removeEventListener : function(){ window.removeEventListener.apply(this, arguments) }, dispatchEvent : function(){ window.dispatchEvent.apply(this, arguments) }, getAttribute: function(name) { var ret = null; // if attribute exists, use it var attr = this.attributes.getNamedItem(name); if (attr) { ret = attr.value; } return ret; // if Attribute exists, return its value, otherwise, return "" }, setAttribute : function (name, value) { // if attribute exists, use it var attr = this.attributes.getNamedItem(name); var value = new String(value); //I had to add this check becuase as the script initializes //the id may be set in the constructor, and the html element //overrides the id property with a getter/setter. if(this.ownerDocument){ if (!attr) { attr = this.ownerDocument.createAttribute(name); // otherwise create it } // test for exceptions if (this.ownerDocument.implementation.errorChecking) { // throw Exception if Attribute is readonly if (attr._readonly) { throw(new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR)); } // throw Exception if the value string contains an illegal character if (!__isValidString__(value)) { throw(new DOMException(DOMException.INVALID_CHARACTER_ERR)); } } if (__isIdDeclaration__(name)) { this.id = value; // cache ID for getElementById() } // assign values to properties (and aliases) attr.value = value; // update .specified if (value.length > 0) { attr.specified = true; }else { attr.specified = false; } // add/replace Attribute in NamedNodeMap this.attributes.setNamedItem(attr); } }, removeAttribute : function removeAttribute(name) { // delegate to DOMNamedNodeMap.removeNamedItem return this.attributes.removeNamedItem(name); }, getAttributeNode : function getAttributeNode(name) { // delegate to DOMNamedNodeMap.getNamedItem return this.attributes.getNamedItem(name); }, setAttributeNode: function(newAttr) { // if this Attribute is an ID if (__isIdDeclaration__(newAttr.name)) { this.id = newAttr.value; // cache ID for getElementById() } // delegate to DOMNamedNodeMap.setNamedItem return this.attributes.setNamedItem(newAttr); }, removeAttributeNode: function(oldAttr) { // throw Exception if Attribute is readonly if (this.ownerDocument.implementation.errorChecking && oldAttr._readonly) { throw(new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR)); } // get item index var itemIndex = this.attributes._findItemIndex(oldAttr._id); // throw Exception if node does not exist in this map if (this.ownerDocument.implementation.errorChecking && (itemIndex < 0)) { throw(new DOMException(DOMException.NOT_FOUND_ERR)); } return this.attributes._removeChild(itemIndex); }, getAttributeNS : function(namespaceURI, localName) { var ret = ""; // delegate to DOMNAmedNodeMap.getNamedItemNS var attr = this.attributes.getNamedItemNS(namespaceURI, localName); if (attr) { ret = attr.value; } return ret; // if Attribute exists, return its value, otherwise return "" }, setAttributeNS : function(namespaceURI, qualifiedName, value) { // call DOMNamedNodeMap.getNamedItem var attr = this.attributes.getNamedItem(namespaceURI, qualifiedName); if (!attr) { // if Attribute exists, use it // otherwise create it attr = this.ownerDocument.createAttributeNS(namespaceURI, qualifiedName); } var value = String(value); // test for exceptions if (this.ownerDocument.implementation.errorChecking) { // throw Exception if Attribute is readonly if (attr._readonly) { throw(new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR)); } // throw Exception if the Namespace is invalid if (!__isValidNamespace__(namespaceURI, qualifiedName)) { throw(new DOMException(DOMException.NAMESPACE_ERR)); } // throw Exception if the value string contains an illegal character if (!__isValidString__(value)) { throw(new DOMException(DOMException.INVALID_CHARACTER_ERR)); } } // if this Attribute is an ID if (__isIdDeclaration__(name)) { this.id = value; // cache ID for getElementById() } // assign values to properties (and aliases) attr.value = value; attr.nodeValue = value; // update .specified if (value.length > 0) { attr.specified = true; }else { attr.specified = false; } // delegate to DOMNamedNodeMap.setNamedItem this.attributes.setNamedItemNS(attr); }, removeAttributeNS : function(namespaceURI, localName) { // delegate to DOMNamedNodeMap.removeNamedItemNS return this.attributes.removeNamedItemNS(namespaceURI, localName); }, getAttributeNodeNS : function(namespaceURI, localName) { // delegate to DOMNamedNodeMap.getNamedItemNS return this.attributes.getNamedItemNS(namespaceURI, localName); }, setAttributeNodeNS : function(newAttr) { // if this Attribute is an ID if ((newAttr.prefix == "") && __isIdDeclaration__(newAttr.name)) { this.id = String(newAttr.value); // cache ID for getElementById() } // delegate to DOMNamedNodeMap.setNamedItemNS return this.attributes.setNamedItemNS(newAttr); }, hasAttribute : function(name) { // delegate to DOMNamedNodeMap._hasAttribute return __hasAttribute__(this.attributes,name); }, hasAttributeNS : function(namespaceURI, localName) { // delegate to DOMNamedNodeMap._hasAttributeNS return __hasAttributeNS__(this.attributes, namespaceURI, localName); }, get nodeType(){ return DOMNode.ELEMENT_NODE; }, get xml() { var ret = ""; // serialize namespace declarations var ns = this._namespaces.xml; if (ns.length > 0) ns = " "+ ns; // serialize Attribute declarations var attrs = this.attributes.xml; if (attrs.length > 0) attrs = " "+ attrs; // serialize this Element ret += "<" + this.nodeName.toLowerCase() + ns + attrs +">"; ret += this.childNodes.xml; ret += "</" + this.nodeName.toLowerCase()+">"; return ret; }, toString : function(){ return "Element #"+this._id + " "+ this.tagName + (this.id?" => "+this.id:''); } }); /** * @class DOMException - raised when an operation is impossible to perform * @author Jon van Noort ([email protected]) * @param code : int - the exception code (one of the DOMException constants) */ var DOMException = function(code) { this.code = code; }; // DOMException constants // Introduced in DOM Level 1: DOMException.INDEX_SIZE_ERR = 1; DOMException.DOMSTRING_SIZE_ERR = 2; DOMException.HIERARCHY_REQUEST_ERR = 3; DOMException.WRONG_DOCUMENT_ERR = 4; DOMException.INVALID_CHARACTER_ERR = 5; DOMException.NO_DATA_ALLOWED_ERR = 6; DOMException.NO_MODIFICATION_ALLOWED_ERR = 7; DOMException.NOT_FOUND_ERR = 8; DOMException.NOT_SUPPORTED_ERR = 9; DOMException.INUSE_ATTRIBUTE_ERR = 10; // Introduced in DOM Level 2: DOMException.INVALID_STATE_ERR = 11; DOMException.SYNTAX_ERR = 12; DOMException.INVALID_MODIFICATION_ERR = 13; DOMException.NAMESPACE_ERR = 14; DOMException.INVALID_ACCESS_ERR = 15; $log("Defining DocumentFragment"); /* * DocumentFragment - DOM Level 2 */ $w.__defineGetter__("DocumentFragment", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); /** * @class DOMDocumentFragment - DocumentFragment is a "lightweight" or "minimal" Document object. * @extends DOMNode * @author Jon van Noort ([email protected]) and David Joham ([email protected]) * @param ownerDocument : DOMDocument - The Document object associated with this node. */ var DOMDocumentFragment = function(ownerDocument) { this.DOMNode = DOMNode; this.DOMNode(ownerDocument); this.nodeName = "#document-fragment"; }; DOMDocumentFragment.prototype = new DOMNode; __extend__(DOMDocumentFragment.prototype,{ get nodeType(){ return DOMNode.DOCUMENT_FRAGMENT_NODE; }, get xml(){ var xml = "", count = this.childNodes.length; // create string concatenating the serialized ChildNodes for (var i = 0; i < count; i++) { xml += this.childNodes.item(i).xml; } return xml; }, toString : function(){ return "DocumentFragment #"+this._id; } }); $log("Defining ProcessingInstruction"); /* * ProcessingInstruction - DOM Level 2 */ $w.__defineGetter__('ProcessingInstruction', function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); /** * @class DOMProcessingInstruction - The ProcessingInstruction interface represents a "processing instruction", * used in XML as a way to keep processor-specific information in the text of the document * @extends DOMNode * @author Jon van Noort ([email protected]) * @param ownerDocument : DOMDocument - The Document object associated with this node. */ var DOMProcessingInstruction = function(ownerDocument) { this.DOMNode = DOMNode; this.DOMNode(ownerDocument); }; DOMProcessingInstruction.prototype = new DOMNode; __extend__(DOMProcessingInstruction.prototype, { get data(){ return this.nodeValue; }, set data(data){ // throw Exception if DOMNode is readonly if (this.ownerDocument.implementation.errorChecking && this._readonly) { throw(new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR)); } this.nodeValue = data; }, get target(){ // The target of this processing instruction. // XML defines this as being the first token following the markup that begins the processing instruction. // The content of this processing instruction. return this.nodeName; }, get nodeType(){ return DOMNode.PROCESSING_INSTRUCTION_NODE; }, get xml(){ return "<?" + this.nodeName +" "+ this.nodeValue + " ?>"; }, toString : function(){ return "ProcessingInstruction #"+this._id; } }); $log("Defining DOMParser"); /* * DOMParser */ $w.__defineGetter__('DOMParser', function(){ return function(){ return __extend__(this, { parseFromString: function(xmlString){ //$log("Parsing XML String: " +xmlString); return document.implementation.createDocument().loadXML(xmlString); } }); }; }); $log("Initializing Internal DOMParser."); //keep one around for internal use $domparser = new DOMParser(); // ========================================================================= // // xmlsax.js - an XML SAX parser in JavaScript. // // version 3.1 // // ========================================================================= // // Copyright (C) 2001 - 2002 David Joham ([email protected]) and Scott Severtson // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // // Visit the XML for <SCRIPT> home page at http://xmljs.sourceforge.net // // CONSTANTS var whitespace = "\n\r\t "; /** * function: this is the constructor to the XMLP Object * Author: Scott Severtson * Description:XMLP is a pull-based parser. The calling application passes in a XML string * to the constructor, then repeatedly calls .next() to parse the next segment. * .next() returns a flag indicating what type of segment was found, and stores * data temporarily in couple member variables (name, content, array of * attributes), which can be accessed by several .get____() methods. * * Basically, XMLP is the lowest common denominator parser - an very simple * API which other wrappers can be built against. **/ var XMLP = function(strXML) { // Normalize line breaks strXML = SAXStrings.replace(strXML, null, null, "\r\n", "\n"); strXML = SAXStrings.replace(strXML, null, null, "\r", "\n"); this.m_xml = strXML; this.m_iP = 0; this.m_iState = XMLP._STATE_PROLOG; this.m_stack = new Stack(); this._clearAttributes(); }; // CONSTANTS (these must be below the constructor) XMLP._NONE = 0; XMLP._ELM_B = 1; XMLP._ELM_E = 2; XMLP._ELM_EMP = 3; XMLP._ATT = 4; XMLP._TEXT = 5; XMLP._ENTITY = 6; XMLP._PI = 7; XMLP._CDATA = 8; XMLP._COMMENT = 9; XMLP._DTD = 10; XMLP._ERROR = 11; XMLP._CONT_XML = 0; XMLP._CONT_ALT = 1; XMLP._ATT_NAME = 0; XMLP._ATT_VAL = 1; XMLP._STATE_PROLOG = 1; XMLP._STATE_DOCUMENT = 2; XMLP._STATE_MISC = 3; XMLP._errs = new Array(); XMLP._errs[XMLP.ERR_CLOSE_PI = 0 ] = "PI: missing closing sequence"; XMLP._errs[XMLP.ERR_CLOSE_DTD = 1 ] = "DTD: missing closing sequence"; XMLP._errs[XMLP.ERR_CLOSE_COMMENT = 2 ] = "Comment: missing closing sequence"; XMLP._errs[XMLP.ERR_CLOSE_CDATA = 3 ] = "CDATA: missing closing sequence"; XMLP._errs[XMLP.ERR_CLOSE_ELM = 4 ] = "Element: missing closing sequence"; XMLP._errs[XMLP.ERR_CLOSE_ENTITY = 5 ] = "Entity: missing closing sequence"; XMLP._errs[XMLP.ERR_PI_TARGET = 6 ] = "PI: target is required"; XMLP._errs[XMLP.ERR_ELM_EMPTY = 7 ] = "Element: cannot be both empty and closing"; XMLP._errs[XMLP.ERR_ELM_NAME = 8 ] = "Element: name must immediatly follow \"<\""; XMLP._errs[XMLP.ERR_ELM_LT_NAME = 9 ] = "Element: \"<\" not allowed in element names"; XMLP._errs[XMLP.ERR_ATT_VALUES = 10] = "Attribute: values are required and must be in quotes"; XMLP._errs[XMLP.ERR_ATT_LT_NAME = 11] = "Element: \"<\" not allowed in attribute names"; XMLP._errs[XMLP.ERR_ATT_LT_VALUE = 12] = "Attribute: \"<\" not allowed in attribute values"; XMLP._errs[XMLP.ERR_ATT_DUP = 13] = "Attribute: duplicate attributes not allowed"; XMLP._errs[XMLP.ERR_ENTITY_UNKNOWN = 14] = "Entity: unknown entity"; XMLP._errs[XMLP.ERR_INFINITELOOP = 15] = "Infininte loop"; XMLP._errs[XMLP.ERR_DOC_STRUCTURE = 16] = "Document: only comments, processing instructions, or whitespace allowed outside of document element"; XMLP._errs[XMLP.ERR_ELM_NESTING = 17] = "Element: must be nested correctly"; XMLP.prototype._addAttribute = function(name, value) { this.m_atts[this.m_atts.length] = new Array(name, value); } XMLP.prototype._checkStructure = function(iEvent) { if(XMLP._STATE_PROLOG == this.m_iState) { if((XMLP._TEXT == iEvent) || (XMLP._ENTITY == iEvent)) { if(SAXStrings.indexOfNonWhitespace(this.getContent(), this.getContentBegin(), this.getContentEnd()) != -1) { return this._setErr(XMLP.ERR_DOC_STRUCTURE); } } if((XMLP._ELM_B == iEvent) || (XMLP._ELM_EMP == iEvent)) { this.m_iState = XMLP._STATE_DOCUMENT; // Don't return - fall through to next state } } if(XMLP._STATE_DOCUMENT == this.m_iState) { if((XMLP._ELM_B == iEvent) || (XMLP._ELM_EMP == iEvent)) { this.m_stack.push(this.getName()); } if((XMLP._ELM_E == iEvent) || (XMLP._ELM_EMP == iEvent)) { var strTop = this.m_stack.pop(); if((strTop == null) || (strTop != this.getName())) { return this._setErr(XMLP.ERR_ELM_NESTING); } } if(this.m_stack.count() == 0) { this.m_iState = XMLP._STATE_MISC; return iEvent; } } if(XMLP._STATE_MISC == this.m_iState) { if((XMLP._ELM_B == iEvent) || (XMLP._ELM_E == iEvent) || (XMLP._ELM_EMP == iEvent) || (XMLP.EVT_DTD == iEvent)) { return this._setErr(XMLP.ERR_DOC_STRUCTURE); } if((XMLP._TEXT == iEvent) || (XMLP._ENTITY == iEvent)) { if(SAXStrings.indexOfNonWhitespace(this.getContent(), this.getContentBegin(), this.getContentEnd()) != -1) { return this._setErr(XMLP.ERR_DOC_STRUCTURE); } } } return iEvent; } XMLP.prototype._clearAttributes = function() { this.m_atts = new Array(); } XMLP.prototype._findAttributeIndex = function(name) { for(var i = 0; i < this.m_atts.length; i++) { if(this.m_atts[i][XMLP._ATT_NAME] == name) { return i; } } return -1; } XMLP.prototype.getAttributeCount = function() { return this.m_atts ? this.m_atts.length : 0; } XMLP.prototype.getAttributeName = function(index) { return ((index < 0) || (index >= this.m_atts.length)) ? null : this.m_atts[index][XMLP._ATT_NAME]; } XMLP.prototype.getAttributeValue = function(index) { return ((index < 0) || (index >= this.m_atts.length)) ? null : __unescapeXML__(this.m_atts[index][XMLP._ATT_VAL]); } XMLP.prototype.getAttributeValueByName = function(name) { return this.getAttributeValue(this._findAttributeIndex(name)); } XMLP.prototype.getColumnNumber = function() { return SAXStrings.getColumnNumber(this.m_xml, this.m_iP); } XMLP.prototype.getContent = function() { return (this.m_cSrc == XMLP._CONT_XML) ? this.m_xml : this.m_cAlt; } XMLP.prototype.getContentBegin = function() { return this.m_cB; } XMLP.prototype.getContentEnd = function() { return this.m_cE; } XMLP.prototype.getLineNumber = function() { return SAXStrings.getLineNumber(this.m_xml, this.m_iP); } XMLP.prototype.getName = function() { return this.m_name; } XMLP.prototype.next = function() { return this._checkStructure(this._parse()); } XMLP.prototype._parse = function() { if(this.m_iP == this.m_xml.length) { return XMLP._NONE; } if(this.m_iP == this.m_xml.indexOf("<?", this.m_iP)) { return this._parsePI (this.m_iP + 2); } else if(this.m_iP == this.m_xml.indexOf("<!DOCTYPE", this.m_iP)) { return this._parseDTD (this.m_iP + 9); } else if(this.m_iP == this.m_xml.indexOf("<!--", this.m_iP)) { return this._parseComment(this.m_iP + 4); } else if(this.m_iP == this.m_xml.indexOf("<![CDATA[", this.m_iP)) { return this._parseCDATA (this.m_iP + 9); } else if(this.m_iP == this.m_xml.indexOf("<", this.m_iP)) { return this._parseElement(this.m_iP + 1); } else if(this.m_iP == this.m_xml.indexOf("&", this.m_iP)) { return this._parseEntity (this.m_iP + 1); } else{ return this._parseText (this.m_iP); } } XMLP.prototype._parseAttribute = function(iB, iE) { var iNB, iNE, iEq, iVB, iVE; var cQuote, strN, strV; this.m_cAlt = ""; //resets the value so we don't use an old one by accident (see testAttribute7 in the test suite) iNB = SAXStrings.indexOfNonWhitespace(this.m_xml, iB, iE); if((iNB == -1) ||(iNB >= iE)) { return iNB; } iEq = this.m_xml.indexOf("=", iNB); if((iEq == -1) || (iEq > iE)) { return this._setErr(XMLP.ERR_ATT_VALUES); } iNE = SAXStrings.lastIndexOfNonWhitespace(this.m_xml, iNB, iEq); iVB = SAXStrings.indexOfNonWhitespace(this.m_xml, iEq + 1, iE); if((iVB == -1) ||(iVB > iE)) { return this._setErr(XMLP.ERR_ATT_VALUES); } cQuote = this.m_xml.charAt(iVB); if(SAXStrings.QUOTES.indexOf(cQuote) == -1) { return this._setErr(XMLP.ERR_ATT_VALUES); } iVE = this.m_xml.indexOf(cQuote, iVB + 1); if((iVE == -1) ||(iVE > iE)) { return this._setErr(XMLP.ERR_ATT_VALUES); } strN = this.m_xml.substring(iNB, iNE + 1); strV = this.m_xml.substring(iVB + 1, iVE); if(strN.indexOf("<") != -1) { return this._setErr(XMLP.ERR_ATT_LT_NAME); } if(strV.indexOf("<") != -1) { return this._setErr(XMLP.ERR_ATT_LT_VALUE); } strV = SAXStrings.replace(strV, null, null, "\n", " "); strV = SAXStrings.replace(strV, null, null, "\t", " "); iRet = this._replaceEntities(strV); if(iRet == XMLP._ERROR) { return iRet; } strV = this.m_cAlt; if(this._findAttributeIndex(strN) == -1) { this._addAttribute(strN, strV); } else { return this._setErr(XMLP.ERR_ATT_DUP); } this.m_iP = iVE + 2; return XMLP._ATT; } XMLP.prototype._parseCDATA = function(iB) { var iE = this.m_xml.indexOf("]]>", iB); if (iE == -1) { return this._setErr(XMLP.ERR_CLOSE_CDATA); } this._setContent(XMLP._CONT_XML, iB, iE); this.m_iP = iE + 3; return XMLP._CDATA; } XMLP.prototype._parseComment = function(iB) { var iE = this.m_xml.indexOf("-" + "->", iB); if (iE == -1) { return this._setErr(XMLP.ERR_CLOSE_COMMENT); } this._setContent(XMLP._CONT_XML, iB, iE); this.m_iP = iE + 3; return XMLP._COMMENT; } XMLP.prototype._parseDTD = function(iB) { // Eat DTD var iE, strClose, iInt, iLast; iE = this.m_xml.indexOf(">", iB); if(iE == -1) { return this._setErr(XMLP.ERR_CLOSE_DTD); } iInt = this.m_xml.indexOf("[", iB); strClose = ((iInt != -1) && (iInt < iE)) ? "]>" : ">"; while(true) { // DEBUG: Remove if(iE == iLast) { return this._setErr(XMLP.ERR_INFINITELOOP); } iLast = iE; // DEBUG: Remove End iE = this.m_xml.indexOf(strClose, iB); if(iE == -1) { return this._setErr(XMLP.ERR_CLOSE_DTD); } // Make sure it is not the end of a CDATA section if (this.m_xml.substring(iE - 1, iE + 2) != "]]>") { break; } } this.m_iP = iE + strClose.length; return XMLP._DTD; } XMLP.prototype._parseElement = function(iB) { var iE, iDE, iNE, iRet; var iType, strN, iLast; iDE = iE = this.m_xml.indexOf(">", iB); if(iE == -1) { return this._setErr(XMLP.ERR_CLOSE_ELM); } if(this.m_xml.charAt(iB) == "/") { iType = XMLP._ELM_E; iB++; } else { iType = XMLP._ELM_B; } if(this.m_xml.charAt(iE - 1) == "/") { if(iType == XMLP._ELM_E) { return this._setErr(XMLP.ERR_ELM_EMPTY); } iType = XMLP._ELM_EMP; iDE--; } iDE = SAXStrings.lastIndexOfNonWhitespace(this.m_xml, iB, iDE); //djohack //hack to allow for elements with single character names to be recognized if (iE - iB != 1 ) { if(SAXStrings.indexOfNonWhitespace(this.m_xml, iB, iDE) != iB) { return this._setErr(XMLP.ERR_ELM_NAME); } } // end hack -- original code below /* if(SAXStrings.indexOfNonWhitespace(this.m_xml, iB, iDE) != iB) return this._setErr(XMLP.ERR_ELM_NAME); */ this._clearAttributes(); iNE = SAXStrings.indexOfWhitespace(this.m_xml, iB, iDE); if(iNE == -1) { iNE = iDE + 1; } else { this.m_iP = iNE; while(this.m_iP < iDE) { // DEBUG: Remove if(this.m_iP == iLast) return this._setErr(XMLP.ERR_INFINITELOOP); iLast = this.m_iP; // DEBUG: Remove End iRet = this._parseAttribute(this.m_iP, iDE); if(iRet == XMLP._ERROR) return iRet; } } strN = this.m_xml.substring(iB, iNE); if(strN.indexOf("<") != -1) { return this._setErr(XMLP.ERR_ELM_LT_NAME); } this.m_name = strN; this.m_iP = iE + 1; return iType; } XMLP.prototype._parseEntity = function(iB) { var iE = this.m_xml.indexOf(";", iB); if(iE == -1) { return this._setErr(XMLP.ERR_CLOSE_ENTITY); } this.m_iP = iE + 1; return this._replaceEntity(this.m_xml, iB, iE); } XMLP.prototype._parsePI = function(iB) { var iE, iTB, iTE, iCB, iCE; iE = this.m_xml.indexOf("?>", iB); if(iE == -1) { return this._setErr(XMLP.ERR_CLOSE_PI); } iTB = SAXStrings.indexOfNonWhitespace(this.m_xml, iB, iE); if(iTB == -1) { return this._setErr(XMLP.ERR_PI_TARGET); } iTE = SAXStrings.indexOfWhitespace(this.m_xml, iTB, iE); if(iTE == -1) { iTE = iE; } iCB = SAXStrings.indexOfNonWhitespace(this.m_xml, iTE, iE); if(iCB == -1) { iCB = iE; } iCE = SAXStrings.lastIndexOfNonWhitespace(this.m_xml, iCB, iE); if(iCE == -1) { iCE = iE - 1; } this.m_name = this.m_xml.substring(iTB, iTE); this._setContent(XMLP._CONT_XML, iCB, iCE + 1); this.m_iP = iE + 2; return XMLP._PI; } XMLP.prototype._parseText = function(iB) { var iE, iEE; iE = this.m_xml.indexOf("<", iB); if(iE == -1) { iE = this.m_xml.length; } iEE = this.m_xml.indexOf("&", iB); if((iEE != -1) && (iEE <= iE)) { iE = iEE; } this._setContent(XMLP._CONT_XML, iB, iE); this.m_iP = iE; return XMLP._TEXT; } XMLP.prototype._replaceEntities = function(strD, iB, iE) { if(SAXStrings.isEmpty(strD)) return ""; iB = iB || 0; iE = iE || strD.length; var iEB, iEE, strRet = ""; iEB = strD.indexOf("&", iB); iEE = iB; while((iEB > 0) && (iEB < iE)) { strRet += strD.substring(iEE, iEB); iEE = strD.indexOf(";", iEB) + 1; if((iEE == 0) || (iEE > iE)) { return this._setErr(XMLP.ERR_CLOSE_ENTITY); } iRet = this._replaceEntity(strD, iEB + 1, iEE - 1); if(iRet == XMLP._ERROR) { return iRet; } strRet += this.m_cAlt; iEB = strD.indexOf("&", iEE); } if(iEE != iE) { strRet += strD.substring(iEE, iE); } this._setContent(XMLP._CONT_ALT, strRet); return XMLP._ENTITY; } XMLP.prototype._replaceEntity = function(strD, iB, iE) { if(SAXStrings.isEmpty(strD)) return -1; iB = iB || 0; iE = iE || strD.length; switch(strD.substring(iB, iE)) { case "amp": strEnt = "&"; break; case "lt": strEnt = "<"; break; case "gt": strEnt = ">"; break; case "apos": strEnt = "'"; break; case "quot": strEnt = "\""; break; default: if(strD.charAt(iB) == "#") { strEnt = String.fromCharCode(parseInt(strD.substring(iB + 1, iE))); } else { return this._setErr(XMLP.ERR_ENTITY_UNKNOWN); } break; } this._setContent(XMLP._CONT_ALT, strEnt); return XMLP._ENTITY; } XMLP.prototype._setContent = function(iSrc) { var args = arguments; if(XMLP._CONT_XML == iSrc) { this.m_cAlt = null; this.m_cB = args[1]; this.m_cE = args[2]; } else { this.m_cAlt = args[1]; this.m_cB = 0; this.m_cE = args[1].length; } this.m_cSrc = iSrc; } XMLP.prototype._setErr = function(iErr) { var strErr = XMLP._errs[iErr]; this.m_cAlt = strErr; this.m_cB = 0; this.m_cE = strErr.length; this.m_cSrc = XMLP._CONT_ALT; return XMLP._ERROR; } /** * function: SAXDriver * Author: Scott Severtson * Description: * SAXDriver is an object that basically wraps an XMLP instance, and provides an * event-based interface for parsing. This is the object users interact with when coding * with XML for <SCRIPT> **/ var SAXDriver = function() { this.m_hndDoc = null; this.m_hndErr = null; this.m_hndLex = null; } // CONSTANTS SAXDriver.DOC_B = 1; SAXDriver.DOC_E = 2; SAXDriver.ELM_B = 3; SAXDriver.ELM_E = 4; SAXDriver.CHARS = 5; SAXDriver.PI = 6; SAXDriver.CD_B = 7; SAXDriver.CD_E = 8; SAXDriver.CMNT = 9; SAXDriver.DTD_B = 10; SAXDriver.DTD_E = 11; SAXDriver.prototype.parse = function(strD) { var parser = new XMLP(strD); if(this.m_hndDoc && this.m_hndDoc.setDocumentLocator) { this.m_hndDoc.setDocumentLocator(this); } this.m_parser = parser; this.m_bErr = false; if(!this.m_bErr) { this._fireEvent(SAXDriver.DOC_B); } this._parseLoop(); if(!this.m_bErr) { this._fireEvent(SAXDriver.DOC_E); } this.m_xml = null; this.m_iP = 0; } SAXDriver.prototype.setDocumentHandler = function(hnd) { this.m_hndDoc = hnd; } SAXDriver.prototype.setErrorHandler = function(hnd) { this.m_hndErr = hnd; } SAXDriver.prototype.setLexicalHandler = function(hnd) { this.m_hndLex = hnd; } /** * LOCATOR/PARSE EXCEPTION INTERFACE ***/ SAXDriver.prototype.getColumnNumber = function() { return this.m_parser.getColumnNumber(); } SAXDriver.prototype.getLineNumber = function() { return this.m_parser.getLineNumber(); } SAXDriver.prototype.getMessage = function() { return this.m_strErrMsg; } SAXDriver.prototype.getPublicId = function() { return null; } SAXDriver.prototype.getSystemId = function() { return null; } /*** * Attribute List Interface **/ SAXDriver.prototype.getLength = function() { return this.m_parser.getAttributeCount(); } SAXDriver.prototype.getName = function(index) { return this.m_parser.getAttributeName(index); } SAXDriver.prototype.getValue = function(index) { return this.m_parser.getAttributeValue(index); } SAXDriver.prototype.getValueByName = function(name) { return this.m_parser.getAttributeValueByName(name); } /*** * Private functions **/ SAXDriver.prototype._fireError = function(strMsg) { this.m_strErrMsg = strMsg; this.m_bErr = true; if(this.m_hndErr && this.m_hndErr.fatalError) { this.m_hndErr.fatalError(this); } } // end function _fireError SAXDriver.prototype._fireEvent = function(iEvt) { var hnd, func, args = arguments, iLen = args.length - 1; if(this.m_bErr) return; if(SAXDriver.DOC_B == iEvt) { func = "startDocument"; hnd = this.m_hndDoc; } else if (SAXDriver.DOC_E == iEvt) { func = "endDocument"; hnd = this.m_hndDoc; } else if (SAXDriver.ELM_B == iEvt) { func = "startElement"; hnd = this.m_hndDoc; } else if (SAXDriver.ELM_E == iEvt) { func = "endElement"; hnd = this.m_hndDoc; } else if (SAXDriver.CHARS == iEvt) { func = "characters"; hnd = this.m_hndDoc; } else if (SAXDriver.PI == iEvt) { func = "processingInstruction"; hnd = this.m_hndDoc; } else if (SAXDriver.CD_B == iEvt) { func = "startCDATA"; hnd = this.m_hndLex; } else if (SAXDriver.CD_E == iEvt) { func = "endCDATA"; hnd = this.m_hndLex; } else if (SAXDriver.CMNT == iEvt) { func = "comment"; hnd = this.m_hndLex; } if(hnd && hnd[func]) { if(0 == iLen) { hnd[func](); } else if (1 == iLen) { hnd[func](args[1]); } else if (2 == iLen) { hnd[func](args[1], args[2]); } else if (3 == iLen) { hnd[func](args[1], args[2], args[3]); } } } // end function _fireEvent SAXDriver.prototype._parseLoop = function(parser) { var iEvent, parser; parser = this.m_parser; while(!this.m_bErr) { iEvent = parser.next(); if(iEvent == XMLP._ELM_B) { this._fireEvent(SAXDriver.ELM_B, parser.getName(), this); } else if(iEvent == XMLP._ELM_E) { this._fireEvent(SAXDriver.ELM_E, parser.getName()); } else if(iEvent == XMLP._ELM_EMP) { this._fireEvent(SAXDriver.ELM_B, parser.getName(), this); this._fireEvent(SAXDriver.ELM_E, parser.getName()); } else if(iEvent == XMLP._TEXT) { this._fireEvent(SAXDriver.CHARS, parser.getContent(), parser.getContentBegin(), parser.getContentEnd() - parser.getContentBegin()); } else if(iEvent == XMLP._ENTITY) { this._fireEvent(SAXDriver.CHARS, parser.getContent(), parser.getContentBegin(), parser.getContentEnd() - parser.getContentBegin()); } else if(iEvent == XMLP._PI) { this._fireEvent(SAXDriver.PI, parser.getName(), parser.getContent().substring(parser.getContentBegin(), parser.getContentEnd())); } else if(iEvent == XMLP._CDATA) { this._fireEvent(SAXDriver.CD_B); this._fireEvent(SAXDriver.CHARS, parser.getContent(), parser.getContentBegin(), parser.getContentEnd() - parser.getContentBegin()); this._fireEvent(SAXDriver.CD_E); } else if(iEvent == XMLP._COMMENT) { this._fireEvent(SAXDriver.CMNT, parser.getContent(), parser.getContentBegin(), parser.getContentEnd() - parser.getContentBegin()); } else if(iEvent == XMLP._DTD) { } else if(iEvent == XMLP._ERROR) { this._fireError(parser.getContent()); } else if(iEvent == XMLP._NONE) { return; } } } // end function _parseLoop /** * function: SAXStrings * Author: Scott Severtson * Description: a useful object containing string manipulation functions **/ var SAXStrings = function() {}; SAXStrings.WHITESPACE = " \t\n\r"; SAXStrings.QUOTES = "\"'"; SAXStrings.getColumnNumber = function(strD, iP) { if(SAXStrings.isEmpty(strD)) { return -1; } iP = iP || strD.length; var arrD = strD.substring(0, iP).split("\n"); var strLine = arrD[arrD.length - 1]; arrD.length--; var iLinePos = arrD.join("\n").length; return iP - iLinePos; } // end function getColumnNumber SAXStrings.getLineNumber = function(strD, iP) { if(SAXStrings.isEmpty(strD)) { return -1; } iP = iP || strD.length; return strD.substring(0, iP).split("\n").length } // end function getLineNumber SAXStrings.indexOfNonWhitespace = function(strD, iB, iE) { if(SAXStrings.isEmpty(strD)) { return -1; } iB = iB || 0; iE = iE || strD.length; for(var i = iB; i < iE; i++){ if(SAXStrings.WHITESPACE.indexOf(strD.charAt(i)) == -1) { return i; } } return -1; } // end function indexOfNonWhitespace SAXStrings.indexOfWhitespace = function(strD, iB, iE) { if(SAXStrings.isEmpty(strD)) { return -1; } iB = iB || 0; iE = iE || strD.length; for(var i = iB; i < iE; i++) { if(SAXStrings.WHITESPACE.indexOf(strD.charAt(i)) != -1) { return i; } } return -1; } // end function indexOfWhitespace SAXStrings.isEmpty = function(strD) { return (strD == null) || (strD.length == 0); } SAXStrings.lastIndexOfNonWhitespace = function(strD, iB, iE) { if(SAXStrings.isEmpty(strD)) { return -1; } iB = iB || 0; iE = iE || strD.length; for(var i = iE - 1; i >= iB; i--){ if(SAXStrings.WHITESPACE.indexOf(strD.charAt(i)) == -1){ return i; } } return -1; } SAXStrings.replace = function(strD, iB, iE, strF, strR) { if(SAXStrings.isEmpty(strD)) { return ""; } iB = iB || 0; iE = iE || strD.length; return strD.substring(iB, iE).split(strF).join(strR); } /*************************************************************************************************************** Stack: A simple stack class, used for verifying document structure. Author: Scott Severtson *****************************************************************************************************************/ var Stack = function() { this.m_arr = new Array(); }; __extend__(Stack.prototype, { clear : function() { this.m_arr = new Array(); }, count : function() { return this.m_arr.length; }, destroy : function() { this.m_arr = null; }, peek : function() { if(this.m_arr.length == 0) { return null; } return this.m_arr[this.m_arr.length - 1]; }, pop : function() { if(this.m_arr.length == 0) { return null; } var o = this.m_arr[this.m_arr.length - 1]; this.m_arr.length--; return o; }, push : function(o) { this.m_arr[this.m_arr.length] = o; } }); /** * function: isEmpty * Author: [email protected] * Description: convenience function to identify an empty string **/ function isEmpty(str) { return (str==null) || (str.length==0); }; /** * function __escapeXML__ * author: David Joham [email protected] * @param str : string - The string to be escaped * @return : string - The escaped string */ var escAmpRegEx = /&/g; var escLtRegEx = /</g; var escGtRegEx = />/g; var quotRegEx = /"/g; var aposRegEx = /'/g; function __escapeXML__(str) { str = str.replace(escAmpRegEx, "&amp;"). replace(escLtRegEx, "&lt;"). replace(escGtRegEx, "&gt;"). replace(quotRegEx, "&quot;"). replace(aposRegEx, "&apos;"); return str; }; /** * function __unescapeXML__ * author: David Joham [email protected] * @param str : string - The string to be unescaped * @return : string - The unescaped string */ var unescAmpRegEx = /&amp;/g; var unescLtRegEx = /&lt;/g; var unescGtRegEx = /&gt;/g; var unquotRegEx = /&quot;/g; var unaposRegEx = /&apos;/g; function __unescapeXML__(str) { str = str.replace(unescAmpRegEx, "&"). replace(unescLtRegEx, "<"). replace(unescGtRegEx, ">"). replace(unquotRegEx, "\""). replace(unaposRegEx, "'"); return str; }; //DOMImplementation $log("Defining DOMImplementation"); $w.__defineGetter__("DOMImplementation", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); /** * @class DOMImplementation - provides a number of methods for performing operations * that are independent of any particular instance of the document object model. * * @author Jon van Noort ([email protected]) */ var DOMImplementation = function() { this.preserveWhiteSpace = false; // by default, ignore whitespace this.namespaceAware = true; // by default, handle namespaces this.errorChecking = true; // by default, test for exceptions }; __extend__(DOMImplementation.prototype,{ // @param feature : string - The package name of the feature to test. // the legal only values are "XML" and "CORE" (case-insensitive). // @param version : string - This is the version number of the package // name to test. In Level 1, this is the string "1.0".* // @return : boolean hasFeature : function(feature, version) { var ret = false; if (feature.toLowerCase() == "xml") { ret = (!version || (version == "1.0") || (version == "2.0")); } else if (feature.toLowerCase() == "core") { ret = (!version || (version == "2.0")); } return ret; }, createDocumentType : function(qname, publicid, systemid){ return new DOMDocumentType(); }, createDocument : function(nsuri, qname, doctype){ //TODO - this currently returns an empty doc //but needs to handle the args return new HTMLDocument($implementation); }, translateErrCode : function(code) { //convert DOMException Code to human readable error message; var msg = ""; switch (code) { case DOMException.INDEX_SIZE_ERR : // 1 msg = "INDEX_SIZE_ERR: Index out of bounds"; break; case DOMException.DOMSTRING_SIZE_ERR : // 2 msg = "DOMSTRING_SIZE_ERR: The resulting string is too long to fit in a DOMString"; break; case DOMException.HIERARCHY_REQUEST_ERR : // 3 msg = "HIERARCHY_REQUEST_ERR: The Node can not be inserted at this location"; break; case DOMException.WRONG_DOCUMENT_ERR : // 4 msg = "WRONG_DOCUMENT_ERR: The source and the destination Documents are not the same"; break; case DOMException.INVALID_CHARACTER_ERR : // 5 msg = "INVALID_CHARACTER_ERR: The string contains an invalid character"; break; case DOMException.NO_DATA_ALLOWED_ERR : // 6 msg = "NO_DATA_ALLOWED_ERR: This Node / NodeList does not support data"; break; case DOMException.NO_MODIFICATION_ALLOWED_ERR : // 7 msg = "NO_MODIFICATION_ALLOWED_ERR: This object cannot be modified"; break; case DOMException.NOT_FOUND_ERR : // 8 msg = "NOT_FOUND_ERR: The item cannot be found"; break; case DOMException.NOT_SUPPORTED_ERR : // 9 msg = "NOT_SUPPORTED_ERR: This implementation does not support function"; break; case DOMException.INUSE_ATTRIBUTE_ERR : // 10 msg = "INUSE_ATTRIBUTE_ERR: The Attribute has already been assigned to another Element"; break; // Introduced in DOM Level 2: case DOMException.INVALID_STATE_ERR : // 11 msg = "INVALID_STATE_ERR: The object is no longer usable"; break; case DOMException.SYNTAX_ERR : // 12 msg = "SYNTAX_ERR: Syntax error"; break; case DOMException.INVALID_MODIFICATION_ERR : // 13 msg = "INVALID_MODIFICATION_ERR: Cannot change the type of the object"; break; case DOMException.NAMESPACE_ERR : // 14 msg = "NAMESPACE_ERR: The namespace declaration is incorrect"; break; case DOMException.INVALID_ACCESS_ERR : // 15 msg = "INVALID_ACCESS_ERR: The object does not support this function"; break; default : msg = "UNKNOWN: Unknown Exception Code ("+ code +")"; } return msg; } }); /** * Defined 'globally' to this scope. Remember everything is wrapped in a closure so this doesnt show up * in the outer most global scope. */ /** * process SAX events * * @author Jon van Noort ([email protected]), David Joham ([email protected]) and Scott Severtson * * @param impl : DOMImplementation * @param doc : DOMDocument - the Document to contain the parsed XML string * @param p : XMLP - the SAX Parser * * @return : DOMDocument */ function __parseLoop__(impl, doc, p) { var iEvt, iNode, iAttr, strName; iNodeParent = doc; var el_close_count = 0; var entitiesList = new Array(); var textNodesList = new Array(); // if namespaceAware, add default namespace if (impl.namespaceAware) { var iNS = doc.createNamespace(""); // add the default-default namespace iNS.value = "http://www.w3.org/2000/xmlns/"; doc._namespaces.setNamedItem(iNS); } // loop until SAX parser stops emitting events while(true) { // get next event iEvt = p.next(); if (iEvt == XMLP._ELM_B) { // Begin-Element Event var pName = p.getName(); // get the Element name pName = trim(pName, true, true); // strip spaces from Element name if (!impl.namespaceAware) { iNode = doc.createElement(p.getName()); // create the Element // add attributes to Element for(var i = 0; i < p.getAttributeCount(); i++) { strName = p.getAttributeName(i); // get Attribute name iAttr = iNode.getAttributeNode(strName); // if Attribute exists, use it if(!iAttr) { iAttr = doc.createAttribute(strName); // otherwise create it } iAttr.value = p.getAttributeValue(i); // set Attribute value iNode.setAttributeNode(iAttr); // attach Attribute to Element } } else { // Namespace Aware // create element (with empty namespaceURI, // resolve after namespace 'attributes' have been parsed) iNode = doc.createElementNS("", p.getName()); // duplicate ParentNode's Namespace definitions iNode._namespaces = __cloneNamedNodes__(iNodeParent._namespaces, iNode); // add attributes to Element for(var i = 0; i < p.getAttributeCount(); i++) { strName = p.getAttributeName(i); // get Attribute name // if attribute is a namespace declaration if (__isNamespaceDeclaration__(strName)) { // parse Namespace Declaration var namespaceDec = __parseNSName__(strName); if (strName != "xmlns") { iNS = doc.createNamespace(strName); // define namespace } else { iNS = doc.createNamespace(""); // redefine default namespace } iNS.value = p.getAttributeValue(i); // set value = namespaceURI iNode._namespaces.setNamedItem(iNS); // attach namespace to namespace collection } else { // otherwise, it is a normal attribute iAttr = iNode.getAttributeNode(strName); // if Attribute exists, use it if(!iAttr) { iAttr = doc.createAttributeNS("", strName); // otherwise create it } iAttr.value = p.getAttributeValue(i); // set Attribute value iNode.setAttributeNodeNS(iAttr); // attach Attribute to Element if (__isIdDeclaration__(strName)) { iNode.id = p.getAttributeValue(i); // cache ID for getElementById() } } } // resolve namespaceURIs for this Element if (iNode._namespaces.getNamedItem(iNode.prefix)) { iNode.namespaceURI = iNode._namespaces.getNamedItem(iNode.prefix).value; } // for this Element's attributes for (var i = 0; i < iNode.attributes.length; i++) { if (iNode.attributes.item(i).prefix != "") { // attributes do not have a default namespace if (iNode._namespaces.getNamedItem(iNode.attributes.item(i).prefix)) { iNode.attributes.item(i).namespaceURI = iNode._namespaces.getNamedItem(iNode.attributes.item(i).prefix).value; } } } } // if this is the Root Element if (iNodeParent.nodeType == DOMNode.DOCUMENT_NODE) { iNodeParent.documentElement = iNode; // register this Element as the Document.documentElement } iNodeParent.appendChild(iNode); // attach Element to parentNode iNodeParent = iNode; // descend one level of the DOM Tree } else if(iEvt == XMLP._ELM_E) { // End-Element Event iNodeParent = iNodeParent.parentNode; // ascend one level of the DOM Tree } else if(iEvt == XMLP._ELM_EMP) { // Empty Element Event pName = p.getName(); // get the Element name pName = trim(pName, true, true); // strip spaces from Element name if (!impl.namespaceAware) { iNode = doc.createElement(pName); // create the Element // add attributes to Element for(var i = 0; i < p.getAttributeCount(); i++) { strName = p.getAttributeName(i); // get Attribute name iAttr = iNode.getAttributeNode(strName); // if Attribute exists, use it if(!iAttr) { iAttr = doc.createAttribute(strName); // otherwise create it } iAttr.value = p.getAttributeValue(i); // set Attribute value iNode.setAttributeNode(iAttr); // attach Attribute to Element } } else { // Namespace Aware // create element (with empty namespaceURI, // resolve after namespace 'attributes' have been parsed) iNode = doc.createElementNS("", p.getName()); // duplicate ParentNode's Namespace definitions iNode._namespaces = __cloneNamedNodes__(iNodeParent._namespaces, iNode); // add attributes to Element for(var i = 0; i < p.getAttributeCount(); i++) { strName = p.getAttributeName(i); // get Attribute name // if attribute is a namespace declaration if (__isNamespaceDeclaration__(strName)) { // parse Namespace Declaration var namespaceDec = __parseNSName__(strName); if (strName != "xmlns") { iNS = doc.createNamespace(strName); // define namespace } else { iNS = doc.createNamespace(""); // redefine default namespace } iNS.value = p.getAttributeValue(i); // set value = namespaceURI iNode._namespaces.setNamedItem(iNS); // attach namespace to namespace collection } else { // otherwise, it is a normal attribute iAttr = iNode.getAttributeNode(strName); // if Attribute exists, use it if(!iAttr) { iAttr = doc.createAttributeNS("", strName); // otherwise create it } iAttr.value = p.getAttributeValue(i); // set Attribute value iNode.setAttributeNodeNS(iAttr); // attach Attribute to Element if (__isIdDeclaration__(strName)) { iNode.id = p.getAttributeValue(i); // cache ID for getElementById() } } } // resolve namespaceURIs for this Element if (iNode._namespaces.getNamedItem(iNode.prefix)) { iNode.namespaceURI = iNode._namespaces.getNamedItem(iNode.prefix).value; } // for this Element's attributes for (var i = 0; i < iNode.attributes.length; i++) { if (iNode.attributes.item(i).prefix != "") { // attributes do not have a default namespace if (iNode._namespaces.getNamedItem(iNode.attributes.item(i).prefix)) { iNode.attributes.item(i).namespaceURI = iNode._namespaces.getNamedItem(iNode.attributes.item(i).prefix).value; } } } } // if this is the Root Element if (iNodeParent.nodeType == DOMNode.DOCUMENT_NODE) { iNodeParent.documentElement = iNode; // register this Element as the Document.documentElement } iNodeParent.appendChild(iNode); // attach Element to parentNode } else if(iEvt == XMLP._TEXT || iEvt == XMLP._ENTITY) { // TextNode and entity Events // get Text content var pContent = p.getContent().substring(p.getContentBegin(), p.getContentEnd()); if (!impl.preserveWhiteSpace ) { if (trim(pContent, true, true) == "") { pContent = ""; //this will cause us not to create the text node below } } if (pContent.length > 0) { // ignore empty TextNodes var textNode = doc.createTextNode(pContent); iNodeParent.appendChild(textNode); // attach TextNode to parentNode //the sax parser breaks up text nodes when it finds an entity. For //example hello&lt;there will fire a text, an entity and another text //this sucks for the dom parser because it looks to us in this logic //as three text nodes. I fix this by keeping track of the entity nodes //and when we're done parsing, calling normalize on their parent to //turn the multiple text nodes into one, which is what DOM users expect //the code to do this is at the bottom of this function if (iEvt == XMLP._ENTITY) { entitiesList[entitiesList.length] = textNode; } else { //I can't properly decide how to handle preserve whitespace //until the siblings of the text node are built due to //the entitiy handling described above. I don't know that this //will be all of the text node or not, so trimming is not appropriate //at this time. Keep a list of all the text nodes for now //and we'll process the preserve whitespace stuff at a later time. textNodesList[textNodesList.length] = textNode; } } } else if(iEvt == XMLP._PI) { // ProcessingInstruction Event // attach ProcessingInstruction to parentNode iNodeParent.appendChild(doc.createProcessingInstruction(p.getName(), p.getContent().substring(p.getContentBegin(), p.getContentEnd()))); } else if(iEvt == XMLP._CDATA) { // CDATA Event // get CDATA data pContent = p.getContent().substring(p.getContentBegin(), p.getContentEnd()); if (!impl.preserveWhiteSpace) { pContent = trim(pContent, true, true); // trim whitespace pContent.replace(/ +/g, ' '); // collapse multiple spaces to 1 space } if (pContent.length > 0) { // ignore empty CDATANodes iNodeParent.appendChild(doc.createCDATASection(pContent)); // attach CDATA to parentNode } } else if(iEvt == XMLP._COMMENT) { // Comment Event // get COMMENT data var pContent = p.getContent().substring(p.getContentBegin(), p.getContentEnd()); if (!impl.preserveWhiteSpace) { pContent = trim(pContent, true, true); // trim whitespace pContent.replace(/ +/g, ' '); // collapse multiple spaces to 1 space } if (pContent.length > 0) { // ignore empty CommentNodes iNodeParent.appendChild(doc.createComment(pContent)); // attach Comment to parentNode } } else if(iEvt == XMLP._DTD) { // ignore DTD events } else if(iEvt == XMLP._ERROR) { $error("Fatal Error: " + p.getContent() + "\nLine: " + p.getLineNumber() + "\nColumn: " + p.getColumnNumber() + "\n"); throw(new DOMException(DOMException.SYNTAX_ERR)); } else if(iEvt == XMLP._NONE) { // no more events if (iNodeParent == doc) { // confirm that we have recursed back up to root break; } else { throw(new DOMException(DOMException.SYNTAX_ERR)); // one or more Tags were not closed properly } } } //normalize any entities in the DOM to a single textNode for (var i = 0; i < entitiesList.length; i++) { var entity = entitiesList[i]; //its possible (if for example two entities were in the //same domnode, that the normalize on the first entitiy //will remove the parent for the second. Only do normalize //if I can find a parent node var parentNode = entity.parentNode; if (parentNode) { parentNode.normalize(); //now do whitespace (if necessary) //it was not done for text nodes that have entities if(!impl.preserveWhiteSpace) { var children = parentNode.childNodes; for ( var j = 0; j < children.length; j++) { var child = children.item(j); if (child.nodeType == DOMNode.TEXT_NODE) { var childData = child.data; childData.replace(/\s/g, ' '); child.data = childData; } } } } } //do the preserve whitespace processing on the rest of the text nodes //It's possible (due to the processing above) that the node will have been //removed from the tree. Only do whitespace checking if parentNode is not null. //This may duplicate the whitespace processing for some nodes that had entities in them //but there's no way around that if (!impl.preserveWhiteSpace) { for (var i = 0; i < textNodesList.length; i++) { var node = textNodesList[i]; if (node.parentNode != null) { var nodeData = node.data; nodeData.replace(/\s/g, ' '); node.data = nodeData; } } } }; /** * @method DOMImplementation._isNamespaceDeclaration - Return true, if attributeName is a namespace declaration * @author Jon van Noort ([email protected]) * @param attributeName : string - the attribute name * @return : boolean */ function __isNamespaceDeclaration__(attributeName) { // test if attributeName is 'xmlns' return (attributeName.indexOf('xmlns') > -1); }; /** * @method DOMImplementation._isIdDeclaration - Return true, if attributeName is an id declaration * @author Jon van Noort ([email protected]) * @param attributeName : string - the attribute name * @return : boolean */ function __isIdDeclaration__(attributeName) { // test if attributeName is 'id' (case insensitive) return (attributeName.toLowerCase() == 'id'); }; /** * @method DOMImplementation._isValidName - Return true, * if name contains no invalid characters * @author Jon van Noort ([email protected]) * @param name : string - the candidate name * @return : boolean */ function __isValidName__(name) { // test if name contains only valid characters return name.match(re_validName); }; var re_validName = /^[a-zA-Z_:][a-zA-Z0-9\.\-_:]*$/; /** * @method DOMImplementation._isValidString - Return true, if string does not contain any illegal chars * All of the characters 0 through 31 and character 127 are nonprinting control characters. * With the exception of characters 09, 10, and 13, (Ox09, Ox0A, and Ox0D) * Note: different from _isValidName in that ValidStrings may contain spaces * @author Jon van Noort ([email protected]) * @param name : string - the candidate string * @return : boolean */ function __isValidString__(name) { // test that string does not contains invalid characters return (name.search(re_invalidStringChars) < 0); }; var re_invalidStringChars = /\x01|\x02|\x03|\x04|\x05|\x06|\x07|\x08|\x0B|\x0C|\x0E|\x0F|\x10|\x11|\x12|\x13|\x14|\x15|\x16|\x17|\x18|\x19|\x1A|\x1B|\x1C|\x1D|\x1E|\x1F|\x7F/; /** * @method DOMImplementation._parseNSName - parse the namespace name. * if there is no colon, the * @author Jon van Noort ([email protected]) * @param qualifiedName : string - The qualified name * @return : NSName - [ .prefix : string - The prefix part of the qname .namespaceName : string - The namespaceURI part of the qname ] */ function __parseNSName__(qualifiedName) { var resultNSName = new Object(); resultNSName.prefix = qualifiedName; // unless the qname has a namespaceName, the prefix is the entire String resultNSName.namespaceName = ""; // split on ':' var delimPos = qualifiedName.indexOf(':'); if (delimPos > -1) { // get prefix resultNSName.prefix = qualifiedName.substring(0, delimPos); // get namespaceName resultNSName.namespaceName = qualifiedName.substring(delimPos +1, qualifiedName.length); } return resultNSName; }; /** * @method DOMImplementation._parseQName - parse the qualified name * @author Jon van Noort ([email protected]) * @param qualifiedName : string - The qualified name * @return : QName */ function __parseQName__(qualifiedName) { var resultQName = new Object(); resultQName.localName = qualifiedName; // unless the qname has a prefix, the local name is the entire String resultQName.prefix = ""; // split on ':' var delimPos = qualifiedName.indexOf(':'); if (delimPos > -1) { // get prefix resultQName.prefix = qualifiedName.substring(0, delimPos); // get localName resultQName.localName = qualifiedName.substring(delimPos +1, qualifiedName.length); } return resultQName; }; $log("Initializing document.implementation"); var $implementation = new DOMImplementation(); $implementation.namespaceAware = false; $implementation.errorChecking = false;$log("Defining Document"); /* * Document - DOM Level 2 * The Document object is not directly */ $w.__defineGetter__('Document', function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); /** * @class DOMDocument - The Document interface represents the entire HTML or XML document. * Conceptually, it is the root of the document tree, and provides the primary access to the document's data. * * @extends DOMNode * @author Jon van Noort ([email protected]) * @param implementation : DOMImplementation - the creator Implementation */ var DOMDocument = function(implementation) { //$log("\tcreating dom document"); this.DOMNode = DOMNode; this.DOMNode(this); this.doctype = null; // The Document Type Declaration (see DocumentType) associated with this document this.implementation = implementation; // The DOMImplementation object that handles this document. this.documentElement = null; // This is a convenience attribute that allows direct access to the child node that is the root element of the document //this.all = new Array(); // The list of all Elements this.nodeName = "#document"; this._id = 0; this._lastId = 0; this._parseComplete = false; // initially false, set to true by parser this._url = ""; this.ownerDocument = this; this._performingImportNodeOperation = false; //$log("\tfinished creating dom document " + this); }; DOMDocument.prototype = new DOMNode; __extend__(DOMDocument.prototype, { addEventListener : function(){ window.addEventListener.apply(this, arguments) }, removeEventListener : function(){ window.removeEventListener.apply(this, arguments) }, attachEvent : function(){ window.addEventListener.apply(this, arguments) }, detachEvent : function(){ window.removeEventListener.apply(this, arguments) }, dispatchEvent : function(){ window.dispatchEvent.apply(this, arguments) }, get styleSheets(){ return [];/*TODO*/ }, get all(){ return this.getElementsByTagName("*"); }, loadXML : function(xmlStr) { // create SAX Parser var parser; try { parser = new XMLP(String(xmlStr)); }catch (e) { $error("Error Creating the SAX Parser. \n\n\t"+e+"\n\n\t Did you include xmlsax.js or tinyxmlsax.js\ in your web page?\nThe SAX parser is needed to populate XML for <SCRIPT>'s \ W3C DOM Parser with data."); } // create DOM Document var doc = new HTMLDocument(this.implementation); // populate Document with Parsed Nodes try { __parseLoop__(this.implementation, doc, parser); } catch (e) { $error(this.implementation.translateErrCode(e.code)) } // set parseComplete flag, (Some validation Rules are relaxed if this is false) doc._parseComplete = true; if(this === $document){ $log("Setting internal window.document"); $document = doc; } return doc; }, load: function(url){ $log("Loading url into DOM Document: "+ url + " - (Asynch? "+$w.document.async+")"); var _this = this; var xhr = new XMLHttpRequest(); xhr.open("GET", url, $w.document.async); xhr.onreadystatechange = function(){ try{ _this.loadXML(xhr.responseText); }catch(e){ $error("Error Parsing XML - ",e); _this.loadXML( "<html><head></head><body>"+ "<h1>Parse Error</h1>"+ "<p>"+e.toString()+"</p>"+ "</body></html>"); } $env.loadScripts(); _this._url = url; $log("Sucessfully loaded document."); var event = document.createEvent(); event.initEvent("load"); $w.dispatchEvent( event ); }; xhr.send(); }, createEvent : function(eventType){ var event; if(eventType === "UIEvents"){ event = new UIEvent();} else if(eventType === "MouseEvents"){ event = new MouseEvent();} else{ event = new Event(); } return event; }, createExpression : function(xpath, nsuriMap){ return null;/*TODO*/ }, createElement : function(tagName) { //$log("DOMDocument.createElement( "+tagName+" )"); // throw Exception if the tagName string contains an illegal character if (this.ownerDocument.implementation.errorChecking && (!__isValidName__(tagName))) { throw(new DOMException(DOMException.INVALID_CHARACTER_ERR)); } // create DOMElement specifying 'this' as ownerDocument var node = new DOMElement(this); // assign values to properties (and aliases) node.tagName = tagName; return node; }, createDocumentFragment : function() { // create DOMDocumentFragment specifying 'this' as ownerDocument var node = new DOMDocumentFragment(this); return node; }, createTextNode: function(data) { // create DOMText specifying 'this' as ownerDocument var node = new DOMText(this); // assign values to properties (and aliases) node.data = data; return node; }, createComment : function(data) { // create DOMComment specifying 'this' as ownerDocument var node = new DOMComment(this); // assign values to properties (and aliases) node.data = data; return node; }, createCDATASection : function(data) { // create DOMCDATASection specifying 'this' as ownerDocument var node = new DOMCDATASection(this); // assign values to properties (and aliases) node.data = data; return node; }, createProcessingInstruction : function(target, data) { // throw Exception if the target string contains an illegal character if (this.ownerDocument.implementation.errorChecking && (!__isValidName__(target))) { throw(new DOMException(DOMException.INVALID_CHARACTER_ERR)); } // create DOMProcessingInstruction specifying 'this' as ownerDocument var node = new DOMProcessingInstruction(this); // assign values to properties (and aliases) node.target = target; node.data = data; return node; }, createAttribute : function(name) { // throw Exception if the name string contains an illegal character if (this.ownerDocument.implementation.errorChecking && (!__isValidName__(name))) { throw(new DOMException(DOMException.INVALID_CHARACTER_ERR)); } // create DOMAttr specifying 'this' as ownerDocument var node = new DOMAttr(this); // assign values to properties (and aliases) node.name = name; return node; }, createElementNS : function(namespaceURI, qualifiedName) { //$log("DOMDocument.createElement( "+namespaceURI+", "+qualifiedName+" )"); // test for exceptions if (this.ownerDocument.implementation.errorChecking) { // throw Exception if the Namespace is invalid if (!__isValidNamespace__(this, namespaceURI, qualifiedName)) { throw(new DOMException(DOMException.NAMESPACE_ERR)); } // throw Exception if the qualifiedName string contains an illegal character if (!__isValidName__(qualifiedName)) { throw(new DOMException(DOMException.INVALID_CHARACTER_ERR)); } } // create DOMElement specifying 'this' as ownerDocument var node = new DOMElement(this); var qname = __parseQName__(qualifiedName); // assign values to properties (and aliases) node.namespaceURI = namespaceURI; node.prefix = qname.prefix; node.localName = qname.localName; node.tagName = qualifiedName; return node; }, createAttributeNS : function(namespaceURI, qualifiedName) { // test for exceptions if (this.ownerDocument.implementation.errorChecking) { // throw Exception if the Namespace is invalid if (!__isValidNamespace__(this, namespaceURI, qualifiedName, true)) { throw(new DOMException(DOMException.NAMESPACE_ERR)); } // throw Exception if the qualifiedName string contains an illegal character if (!__isValidName__(qualifiedName)) { throw(new DOMException(DOMException.INVALID_CHARACTER_ERR)); } } // create DOMAttr specifying 'this' as ownerDocument var node = new DOMAttr(this); var qname = __parseQName__(qualifiedName); // assign values to properties (and aliases) node.namespaceURI = namespaceURI; node.prefix = qname.prefix; node.localName = qname.localName; node.name = qualifiedName; node.nodeValue = ""; return node; }, createNamespace : function(qualifiedName) { // create DOMNamespace specifying 'this' as ownerDocument var node = new DOMNamespace(this); var qname = __parseQName__(qualifiedName); // assign values to properties (and aliases) node.prefix = qname.prefix; node.localName = qname.localName; node.name = qualifiedName; node.nodeValue = ""; return node; }, getElementById : function(elementId) { var retNode = null, node; // loop through all Elements in the 'all' collection var all = this.all; for (var i=0; i < all.length; i++) { node = all[i]; // if id matches & node is alive (ie, connected (in)directly to the documentElement) if (node.id == elementId) { if((node.ownerDocument.documentElement._id == this.documentElement._id)){ retNode = node; //$log("Found node with id = " + node.id); break; } } } if(retNode == null){$log("Couldn't find id " + elementId);} return retNode; }, normalizeDocument: function(){ this.documentElement.normalize(); }, get nodeType(){ return DOMNode.DOCUMENT_NODE; }, get xml(){ return this.documentElement.xml; }, toString: function(){ return "Document" + (typeof this._url == "string" ? ": " + this._url : ""); }, get defaultView(){ //TODO: why isnt this just 'return $w;'? return { getComputedStyle: function(elem){ return { getPropertyValue: function(prop){ prop = prop.replace(/\-(\w)/g,function(m,c){ return c.toUpperCase(); }); var val = elem.style[prop]; if ( prop == "opacity" && val == "" ){ val = "1"; }return val; }}; }}; }, _genId : function() { this._lastId += 1; // increment lastId (to generate unique id) return this._lastId; } }); var __isValidNamespace__ = function(doc, namespaceURI, qualifiedName, isAttribute) { if (doc._performingImportNodeOperation == true) { //we're doing an importNode operation (or a cloneNode) - in both cases, there //is no need to perform any namespace checking since the nodes have to have been valid //to have gotten into the DOM in the first place return true; } var valid = true; // parse QName var qName = __parseQName__(qualifiedName); //only check for namespaces if we're finished parsing if (this._parseComplete == true) { // if the qualifiedName is malformed if (qName.localName.indexOf(":") > -1 ){ valid = false; } if ((valid) && (!isAttribute)) { // if the namespaceURI is not null if (!namespaceURI) { valid = false; } } // if the qualifiedName has a prefix if ((valid) && (qName.prefix == "")) { valid = false; } } // if the qualifiedName has a prefix that is "xml" and the namespaceURI is // different from "http://www.w3.org/XML/1998/namespace" [Namespaces]. if ((valid) && (qName.prefix == "xml") && (namespaceURI != "http://www.w3.org/XML/1998/namespace")) { valid = false; } return valid; }; $log("Defining HTMLDocument"); /* * HTMLDocument - DOM Level 2 * The Document object is not directly */ $w.__defineGetter__("HTMLDocument", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); /** * @class HTMLDocument - The Document interface represents the entire HTML or XML document. * Conceptually, it is the root of the document tree, and provides the primary access to the document's data. * * @extends DOMDocument */ var HTMLDocument = function(implementation) { this.DOMDocument = DOMDocument; this.DOMDocument(implementation); this.title = ""; this._refferer = ""; this._domain; this._open = false; }; HTMLDocument.prototype = new DOMDocument; __extend__(HTMLDocument.prototype, { createElement: function(tagName){ //$log("HTMLDocument.createElement( "+tagName+" )"); // throw Exception if the tagName string contains an illegal character if (this.ownerDocument.implementation.errorChecking && (!__isValidName__(tagName))) { throw(new DOMException(DOMException.INVALID_CHARACTER_ERR)); } tagName = tagName.toUpperCase(); //$log("HTMLDocument.createElement( "+tagName+" )"); // create DOMElement specifying 'this' as ownerDocument //This is an html document so we need to use explicit interfaces per the if( tagName.match(/^A$/)) {node = new HTMLAnchorElement(this);} else if(tagName.match(/AREA/)) {node = new HTMLAreaElement(this);} else if(tagName.match(/BASE/)) {node = new HTMLBaseElement(this);} else if(tagName.match(/BLOCKQUOTE|Q/)) {node = new HTMLQuoteElement(this);} else if(tagName.match(/BODY/)) {node = new HTMLElement(this);} else if(tagName.match(/BR/)) {node = new HTMLElement(this);} else if(tagName.match(/BUTTON/)) {node = new HTMLButtonElement(this);} else if(tagName.match(/CAPTION/)) {node = new HTMLElement(this);} else if(tagName.match(/COL|COLGROUP/)) {node = new HTMLTableColElement(this);} else if(tagName.match(/DEL|INS/)) {node = new HTMLModElement(this);} else if(tagName.match(/DIV/)) {node = new HTMLElement(this);} else if(tagName.match(/DL/)) {node = new HTMLElement(this);} else if(tagName.match(/FIELDSET/)) {node = new HTMLFieldSetElement(this);} else if(tagName.match(/FORM/)) {node = new HTMLFormElement(this);} else if(tagName.match(/^FRAME$/)) {node = new HTMLFrameElement(this);} else if(tagName.match(/FRAMESET/)) {node = new HTMLFrameSetElement(this);} else if(tagName.match(/H1|H2|H3|H4|H5|H6/)) {node = new HTMLElement(this);} else if(tagName.match(/HEAD/)) {node = new HTMLHeadElement(this);} else if(tagName.match(/HR/)) {node = new HTMLElement(this);} else if(tagName.match(/HTML/)) {node = new HTMLElement(this);} else if(tagName.match(/IFRAME/)) {node = new HTMLIFrameElement(this);} else if(tagName.match(/IMG/)) {node = new HTMLImageElement(this);} else if(tagName.match(/INPUT/)) {node = new HTMLInputElement(this);} else if(tagName.match(/LABEL/)) {node = new HTMLLabelElement(this);} else if(tagName.match(/LEGEND/)) {node = new HTMLLegendElement(this);} else if(tagName.match(/^LI$/)) {node = new HTMLElement(this);} else if(tagName.match(/LINK/)) {node = new HTMLLinkElement(this);} else if(tagName.match(/MAP/)) {node = new HTMLMapElement(this);} else if(tagName.match(/META/)) {node = new HTMLMetaElement(this);} else if(tagName.match(/OBJECT/)) {node = new HTMLObjectElement(this);} else if(tagName.match(/OL/)) {node = new HTMLElement(this);} else if(tagName.match(/OPTGROUP/)) {node = new HTMLOptGroupElement(this);} else if(tagName.match(/OPTION/)) {node = new HTMLOptionElement(this);;} else if(tagName.match(/^P$/)) {node = new HTMLElement(this);} else if(tagName.match(/PARAM/)) {node = new HTMLParamElement(this);} else if(tagName.match(/PRE/)) {node = new HTMLElement(this);} else if(tagName.match(/SCRIPT/)) {node = new HTMLScriptElement(this);} else if(tagName.match(/SELECT/)) {node = new HTMLSelectElement(this);} else if(tagName.match(/STYLE/)) {node = new HTMLStyleElement(this);} else if(tagName.match(/TABLE/)) {node = new HTMLElement(this);} else if(tagName.match(/TBODY|TFOOT|THEAD/)) {node = new HTMLElement(this);} else if(tagName.match(/TD|TH/)) {node = new HTMLElement(this);} else if(tagName.match(/TEXTAREA/)) {node = new HTMLElement(this);} else if(tagName.match(/TITLE/)) {node = new HTMLElement(this);} else if(tagName.match(/TR/)) {node = new HTMLElement(this);} else if(tagName.match(/UL/)) {node = new HTMLElement(this);} else{ node = new HTMLElement(this); } // assign values to properties (and aliases) node.tagName = tagName; return node; }, get anchors(){ return new HTMLCollection(this.getElementsByTagName('a'), 'Anchor'); }, get applets(){ return new HTMLCollection(this.getElementsByTagName('applet'), 'Applet'); }, get body(){ var nodelist = this.getElementsByTagName('body'); return nodelist.item(0); }, set body(html){ return this.replaceNode(this.body,html); }, //set/get cookie see cookie.js get domain(){ return this._domain||window.location.domain; }, set domain(){ /* TODO - requires a bit of thought to enforce domain restrictions */ return; }, get forms(){ $log("document.forms"); return new HTMLCollection(this.getElementsByTagName('form'), 'Form'); }, get images(){ return new HTMLCollection(this.getElementsByTagName('img'), 'Image'); }, get lastModified(){ /* TODO */ return this._lastModified; }, get links(){ return new HTMLCollection(this.getElementsByTagName('a'), 'Link'); }, get location(){ return $w.location }, get referrer(){ /* TODO */ return this._refferer; }, get URL(){ /* TODO*/ return this._url; }, close : function(){ /* TODO */ this._open = false; }, getElementsByName : function(name){ //$debug("document.getElementsByName ( "+name+" )"); //returns a real Array + the DOMNodeList var retNodes = __extend__([],new DOMNodeList(this, this.documentElement)), node; // loop through all Elements in the 'all' collection var all = this.all; for (var i=0; i < all.length; i++) { node = all[i]; if (node.nodeType == DOMNode.ELEMENT_NODE && node.getAttribute('name') == name) { //$log("Found node by name " + name); retNodes.push(node); } } return retNodes; }, open : function(){ /* TODO */ this._open = true; }, write: function(htmlstring){ /* TODO */ return; }, writeln: function(htmlstring){ this.write(htmlstring+'\n'); }, toString: function(){ return "Document" + (typeof this._url == "string" ? ": " + this._url : ""); }, get innerHTML(){ return this.documentElement.outerHTML; }, get __html__(){ return true; } }); //This is useful as html elements that modify the dom must also run through the new //nodes and determine if they are javascript tags and load it. This is really the fun //parts! ;) function __execScripts__( node ) { if ( node.nodeName == "SCRIPT" ) { if ( !node.getAttribute("src") ) { eval.call( window, node.textContent ); } } else { var scripts = node.getElementsByTagName("script"); for ( var i = 0; i < scripts.length; i++ ) { __execScripts__( node ); } } };$log("Defining HTMLElement"); /* * HTMLElement - DOM Level 2 */ $w.__defineGetter__("HTMLElement", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); var HTMLElement = function(ownerDocument) { //$log("\tcreating html element"); this.DOMElement = DOMElement; this.DOMElement(ownerDocument); //$log("\nfinished creating html element"); this.$css2props = null; }; HTMLElement.prototype = new DOMElement; __extend__(HTMLElement.prototype, { get className() { return this.getAttribute("class")||""; }, set className(val) { return this.setAttribute("class",trim(val)); }, get dir() { return this.getAttribute("dir")||"ltr"; }, set dir(val) { return this.setAttribute("dir",val); }, get innerHTML(){ return this.childNodes.xml; }, set innerHTML(html){ //$debug("htmlElement.innerHTML("+html+")"); //Should be replaced with HTMLPARSER usage //html = (html?html:"").replace(/<\/?([A-Z]+)/g, function(m){ // return m.toLowerCase(); //}).replace(/&nbsp;/g, " "); var doc = new DOMParser(). parseFromString('<div>'+html+'</div>'); var parent = this.ownerDocument.importNode(doc.documentElement, true); //$log("\n\nIMPORTED HTML:\n\n"+nodes.xml); while(this.firstChild != null){ //$log('innerHTML - removing child '+ this.firstChild.xml); this.removeChild( this.firstChild ); } while(parent.firstChild != null){ //$log('innerHTML - appending child '+ parent.firstChild.xml); this.appendChild( parent.removeChild( parent.firstChild ) ); } //Mark for garbage collection doc = null; }, get lang() { return this.getAttribute("lang")||""; }, set lang(val) { return this.setAttribute("lang",val); }, get offsetHeight(){ return Number(this.style["height"].replace("px","")); }, get offsetWidth(){ return Number(this.style["width"].replace("px","")); }, offsetLeft: 0, offsetRight: 0, get offsetParent(){ /* TODO */ return; }, set offsetParent(element){ /* TODO */ return; }, scrollHeight: 0, scrollWidth: 0, scrollLeft: 0, scrollRight: 0, get style(){ if(this.$css2props === null){ $log("Initializing new css2props for html element : " + this.getAttribute("style")); this.$css2props = new CSS2Properties({ cssText:this.getAttribute("style") }); } return this.$css2props }, get title() { return this.getAttribute("title")||""; }, set title(val) { return this.setAttribute("title",val); }, //Not in the specs but I'll leave it here for now. get outerHTML(){ return this.xml; }, scrollIntoView: function(){ /*TODO*/ return; }, onclick: function(event){ try{ eval(this.getAttribute('onclick')); }catch(e){ $error(e); } }, ondblclick: function(event){ try{ eval(this.getAttribute('ondblclick')); }catch(e){ $error(e) } }, onkeydown: function(event){ try{ eval(this.getAttribute('onkeydown')); }catch(e){ $error(e); } }, onkeypress: function(event){ try{ eval(this.getAttribute('onkeypress')); }catch(e){ $error(e);}}, onkeyup: function(event){ try{ eval(this.getAttribute('onkeyup')); }catch(e){ $error(e);}}, onmousedown: function(event){ try{ eval(this.getAttribute('onmousedown')); }catch(e){ $error(e);}}, onmousemove: function(event){ try{ eval(this.getAttribute('onmousemove')); }catch(e){ $error(e);}}, onmouseout: function(event){ try{ eval(this.getAttribute('onmouseout')); }catch(e){ $error(e);}}, onmouseover: function(event){ try{ eval(this.getAttribute('onmouseover')); }catch(e){ $error(e);}}, onmouseup: function(event){ try{ eval(this.getAttribute('onmouseup')); }catch(e){ $error(e);}} }); var __registerEventAttrs__ = function(elm){ if(elm.hasAttribute('onclick')){ elm.addEventListener('click', elm.onclick ); } if(elm.hasAttribute('ondblclick')){ elm.addEventListener('dblclick', elm.onclick ); } if(elm.hasAttribute('onkeydown')){ elm.addEventListener('keydown', elm.onclick ); } if(elm.hasAttribute('onkeypress')){ elm.addEventListener('keypress', elm.onclick ); } if(elm.hasAttribute('onkeyup')){ elm.addEventListener('keyup', elm.onclick ); } if(elm.hasAttribute('onmousedown')){ elm.addEventListener('mousedown', elm.onclick ); } if(elm.hasAttribute('onmousemove')){ elm.addEventListener('mousemove', elm.onclick ); } if(elm.hasAttribute('onmouseout')){ elm.addEventListener('mouseout', elm.onclick ); } if(elm.hasAttribute('onmouseover')){ elm.addEventListener('mouseover', elm.onclick ); } if(elm.hasAttribute('onmouseup')){ elm.addEventListener('mouseup', elm.onclick ); } return elm; }; var __click__ = function(element){ var event = new Event({ target:element, currentTarget:element }); event.initEvent("click"); element.dispatchEvent(event); }; var __submit__ = function(element){ var event = new Event({ target:element, currentTarget:element }); event.initEvent("submit"); element.dispatchEvent(event); }; var __focus__ = function(element){ var event = new Event({ target:element, currentTarget:element }); event.initEvent("focus"); element.dispatchEvent(event); }; var __blur__ = function(element){ var event = new Event({ target:element, currentTarget:element }); event.initEvent("blur"); element.dispatchEvent(event); }; $log("Defining HTMLCollection"); /* * HTMLCollection - DOM Level 2 */ $w.__defineGetter__("HTMLCollection", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); /*var HTMLCollection = function(nodelist, type){ var $items = [], $item, i; if(type === "Anchor" ){ for(i=0;i<nodelist.length;i++){ //The name property is required to be add to the collection if(nodelist.item(i).name){ item = new nodelist.item(i); $items.push(item); this[nodelist.item(i).name] = item; } } }else if(type === "Link"){ for(i=0;i<nodelist.length;i++){ //The name property is required to be add to the collection if(nodelist.item(i).href){ item = new nodelist.item(i); $items.push(item); this[nodelist.item(i).name] = item; } } }else if(type === "Form"){ for(i=0;i<nodelist.length;i++){ //The name property is required to be add to the collection if(nodelist.item(i).href){ item = new nodelist.item(i); $items.push(item); this[nodelist.item(i).name] = item; } } } setArray(this, $items); return __extend__(this, { item : function(i){return this[i];}, namedItem : function(name){return this[name];} }); };*/ $log("Defining HTMLAnchorElement"); /* * HTMLAnchorElement - DOM Level 2 */ $w.__defineGetter__("HTMLAnchorElement", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); var HTMLAnchorElement = function(ownerDocument) { //$log("creating anchor element"); this.HTMLElement = HTMLElement; this.HTMLElement(ownerDocument); }; HTMLAnchorElement.prototype = new HTMLElement; __extend__(HTMLAnchorElement.prototype, { get accessKey() { return this.getAttribute("accesskey") || ""; }, set accessKey(val) { return this.setAttribute("accesskey",val); }, get charset() { return this.getAttribute("charset") || ""; }, set charset(val) { return this.setAttribute("charset",val); }, get coords() { return this.getAttribute("coords") || ""; }, set coords(val) { return this.setAttribute("coords",val); }, get href() { return this.getAttribute("href") || ""; }, set href(val) { return this.setAttribute("href",val); }, get hreflang() { return this.getAttribute("hreflang") || ""; }, set hreflang(val) { return this.setAttribute("hreflang",val); }, get name() { return this.getAttribute("name") || ""; }, set name(val) { return this.setAttribute("name",val); }, get rel() { return this.getAttribute("rel") || ""; }, set rel(val) { return this.setAttribute("rel",val); }, get rev() { return this.getAttribute("rev") || ""; }, set rev(val) { return this.setAttribute("rev",val); }, get shape() { return this.getAttribute("shape") || ""; }, set shape(val) { return this.setAttribute("shape",val); }, get tabIndex() { return this.getAttribute("tabindex") || ""; }, set tabIndex(val) { return this.setAttribute("tabindex",val); }, get target() { return this.getAttribute("target") || ""; }, set target(val) { return this.setAttribute("target",val); }, get type() { return this.getAttribute("type") || ""; }, set type(val) { return this.setAttribute("type",val); }, blur:function(){ __blur__(this); }, focus:function(){ __focus__(this); } }); $log("Defining Anchor"); /* * Anchor - DOM Level 2 */ $w.__defineGetter__("Anchor", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); var Anchor = function(ownerDocument) { //$log("creating anchor element"); this.HTMLAnchorElement = HTMLAnchorElement; this.HTMLAnchorElement(ownerDocument); }; Anchor.prototype = new Anchor; (function(){ //static regular expressions var hash = new RegExp('(\\#.*)'), hostname = new RegExp('\/\/([^\:\/]+)'), pathname = new RegExp('(\/[^\\?\\#]*)'), port = new RegExp('\:(\\d+)\/'), protocol = new RegExp('(^\\w*\:)'), search = new RegExp('(\\?[^\\#]*)'); __extend__(Anchor.prototype, { get hash(){ var m = hash.exec(this.href); return m&&m.length>1?m[1]:""; }, set hash(_hash){ //setting the hash is the only property of the location object //that doesn't cause the window to reload _hash = _hash.indexOf('#')===0?_hash:"#"+_hash; this.href = this.protocol + this.host + this.pathname + this.search + _hash; }, get host(){ return this.hostname + (this.port !== "")?":"+this.port:""; }, set host(_host){ this.href = this.protocol + _host + this.pathname + this.search + this.hash; }, get hostname(){ var m = hostname.exec(this.href); return m&&m.length>1?m[1]:""; }, set hostname(_hostname){ this.href = this.protocol + _hostname + ((this.port==="")?"":(":"+this.port)) + this.pathname + this.search + this.hash; }, get pathname(){ var m = this.href; m = pathname.exec(m.substring(m.indexOf(this.hostname))); return m&&m.length>1?m[1]:"/"; }, set pathname(_pathname){ this.href = this.protocol + this.host + _pathname + this.search + this.hash; }, get port(){ var m = port.exec(this.href); return m&&m.length>1?m[1]:""; }, set port(_port){ this.href = this.protocol + this.hostname + ":"+_port + this.pathname + this.search + this.hash; }, get protocol(){ return protocol.exec(this.href)[0]; }, set protocol(_protocol){ this.href = _protocol + this.host + this.pathname + this.search + this.hash; }, get search(){ var m = search.exec(this.href); return m&&m.length>1?m[1]:""; }, set search(_search){ this.href = this.protocol + this.host + this.pathname + _search + this.hash; } }); })(); $log("Defining HTMLAreaElement"); /* * HTMLAreaElement - DOM Level 2 */ $w.__defineGetter__("HTMLAreaElement", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); var HTMLAreaElement = function(ownerDocument) { //$log("creating anchor element"); this.HTMLElement = HTMLElement; this.HTMLElement(ownerDocument); }; HTMLAreaElement.prototype = new HTMLElement; __extend__(HTMLAreaElement.prototype, { get accessKey(){ return this.getAttribute('accesskey'); }, set accessKey(value){ this.setAttribute('accesskey',value); }, get alt(){ return this.getAttribute('alt'); }, set alt(value){ this.setAttribute('alt',value); }, get coords(){ return this.getAttribute('coords'); }, set coords(value){ this.setAttribute('coords',value); }, get href(){ return this.getAttribute('href'); }, set href(value){ this.setAttribute('href',value); }, get noHref(){ return this.hasAttribute('href'); }, get shape(){ //TODO return 0; }, get tabIndex(){ return this.getAttribute('tabindex'); }, set tabIndex(value){ this.setAttribute('tabindex',value); }, get target(){ return this.getAttribute('target'); }, set target(value){ this.setAttribute('target',value); } }); $log("Defining HTMLBaseElement"); /* * HTMLBaseElement - DOM Level 2 */ $w.__defineGetter__("HTMLBaseElement", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); var HTMLBaseElement = function(ownerDocument) { //$log("creating anchor element"); this.HTMLElement = HTMLElement; this.HTMLElement(ownerDocument); }; HTMLBaseElement.prototype = new HTMLElement; __extend__(HTMLBaseElement.prototype, { get href(){ return this.getAttribute('href'); }, set href(value){ this.setAttribute('href',value); }, get target(){ return this.getAttribute('target'); }, set target(value){ this.setAttribute('target',value); } }); $log("Defining HTMLQuoteElement"); /* * HTMLQuoteElement - DOM Level 2 */ $w.__defineGetter__("HTMLQuoteElement", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); var HTMLQuoteElement = function(ownerDocument) { //$log("creating anchor element"); this.HTMLElement = HTMLElement; this.HTMLElement(ownerDocument); }; HTMLQuoteElement.prototype = new HTMLElement; __extend__(HTMLQuoteElement.prototype, { get cite(){ return this.getAttribute('cite'); }, set cite(value){ this.setAttribute('cite',value); } }); $log("Defining HTMLButtonElement"); /* * HTMLButtonElement - DOM Level 2 */ $w.__defineGetter__("HTMLButtonElement", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); var HTMLButtonElement = function(ownerDocument) { //$log("creating anchor element"); this.HTMLElement = HTMLElement; this.HTMLElement(ownerDocument); }; HTMLButtonElement.prototype = new HTMLElement; __extend__(HTMLButtonElement.prototype, { get form(){ var parent = this.parent; while(parent.nodeName.toLowerCase() != 'form'){ parent = parent.parent; } return parent; }, get accessKey(){ return this.getAttribute('accesskey'); }, set accessKey(value){ this.setAttribute('accesskey',value); }, get tabIndex(){ return Number(this.getAttribute('tabindex')); }, set tabIndex(value){ this.setAttribute('tabindex',Number(value)); }, get type(){ return this.getAttribute('type'); }, set type(value){ this.setAttribute('type',value); }, get value(){ return this.getAttribute('value'); }, set value(value){ this.setAttribute('value',value); } }); $log("Defining HTMLTableColElement"); /* * HTMLTableColElement - DOM Level 2 */ $w.__defineGetter__("HTMLTableColElement", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); var HTMLTableColElement = function(ownerDocument) { //$log("creating anchor element"); this.HTMLElement = HTMLElement; this.HTMLElement(ownerDocument); }; HTMLTableColElement.prototype = new HTMLElement; __extend__(HTMLTableColElement.prototype, { get align(){ return this.getAttribute('align'); }, set align(value){ this.setAttribute('align', value); }, get ch(){ return this.getAttribute('ch'); }, set ch(value){ this.setAttribute('ch', value); }, get chOff(){ return this.getAttribute('ch'); }, set chOff(value){ this.setAttribute('ch', value); }, get span(){ return this.getAttribute('span'); }, set span(value){ this.setAttribute('span', value); }, get vAlign(){ return this.getAttribute('valign'); }, set vAlign(value){ this.setAttribute('valign', value); }, get width(){ return this.getAttribute('width'); }, set width(value){ this.setAttribute('width', value); } }); $log("Defining HTMLModElement"); /* * HTMLModElement - DOM Level 2 */ $w.__defineGetter__("HTMLModElement", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); var HTMLModElement = function(ownerDocument) { //$log("creating anchor element"); this.HTMLElement = HTMLElement; this.HTMLElement(ownerDocument); }; HTMLModElement.prototype = new HTMLElement; __extend__(HTMLModElement.prototype, { get cite(){ return this.getAttribute('cite'); }, set cite(value){ this.setAttribute('cite', value); }, get dateTime(){ return this.getAttribute('datetime'); }, set dateTime(value){ this.setAttribute('datetime', value); } }); $log("Defining HTMLFieldSetElement"); /* * HTMLFieldSetElement - DOM Level 2 */ $w.__defineGetter__("HTMLFieldSetElement", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); var HTMLFieldSetElement = function(ownerDocument) { //$log("creating anchor element"); this.HTMLElement = HTMLElement; this.HTMLElement(ownerDocument); }; HTMLFieldSetElement.prototype = new HTMLElement; __extend__(HTMLFieldSetElement.prototype, { get form(){ var parent = this.parent; while(parent.nodeName.toLowerCase() != 'form'){ parent = parent.parent; } return parent; } }); $log("Defining HTMLFormElement"); /* * HTMLAnchorElement - DOM Level 2 */ $w.__defineGetter__("Form", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); $w.__defineGetter__("HTMLFormElement", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); var HTMLFormElement = function(ownerDocument){ this.HTMLElement = HTMLElement; this.HTMLElement(ownerDocument); }; HTMLFormElement.prototype = new HTMLElement; __extend__(HTMLFormElement.prototype,{ get acceptCharset(){ return this.getAttribute('accept-charset'); }, set acceptCharset(acceptCharset){ this.setAttribute('accept-charset', acceptCharset); }, get action(){ return this.getAttribute('action'); }, set action(action){ this.setAttribute('action', action); }, get elements() { return this.getElementsByTagName("*"); }, get enctype(){ return this.getAttribute('enctype'); }, set enctype(enctype){ this.setAttribute('enctype', enctype); }, get length() { return this.elements.length; }, get method(){ return this.getAttribute('method'); }, set method(action){ this.setAttribute('method', method); }, get name() { return this.getAttribute("name") || ""; }, set name(val) { return this.setAttribute("name",val); }, get target() { return this.getAttribute("target") || ""; }, set target(val) { return this.setAttribute("target",val); }, submit:function(){ __submit__(this); }, reset:function(){ __reset__(this); } }); $log("Defining HTMLFrameElement"); /* * HTMLFrameElement - DOM Level 2 */ $w.__defineGetter__("HTMLFrameElement", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); var HTMLFrameElement = function(ownerDocument) { //$log("creating frame element"); this.HTMLElement = HTMLElement; this.HTMLElement(ownerDocument); }; HTMLFrameElement.prototype = new HTMLElement; __extend__(HTMLFrameElement.prototype, { get frameBorder(){ return this.getAttribute('border')||""; }, set frameBorder(value){ this.setAttribute('border', value); }, get longDesc(){ return this.getAttribute('longdesc')||""; }, set longDesc(value){ this.setAttribute('longdesc', value); }, get marginHeight(){ return this.getAttribute('marginheight')||""; }, set marginHeight(value){ this.setAttribute('marginheight', value); }, get marginWidth(){ return this.getAttribute('marginwidth')||""; }, set marginWidth(value){ this.setAttribute('marginwidth', value); }, get name(){ return this.getAttribute('name')||""; }, set name(value){ this.setAttribute('name', value); }, get noResize(){ return this.getAttribute('noresize')||""; }, set noResize(value){ this.setAttribute('noresize', value); }, get scrolling(){ return this.getAttribute('scrolling')||""; }, set scrolling(value){ this.setAttribute('scrolling', value); }, get src(){ return this.getAttribute('src')||""; }, set src(value){ this.setAttribute('src', value); }, get contentDocument(){ $log("getting content document for (i)frame"); if(!this._content){ this._content = new HTMLDocument($implementation); if(this.src.length > 0){ $log("Loading frame content from " + this.src); try{ this._content.load(this.src); }catch(e){ $error("failed to load " + this.src); } } } return true; } }); $log("Defining HTMLFrameSetElement"); /* * HTMLFrameSetElement - DOM Level 2 */ $w.__defineGetter__("HTMLFrameSetElement", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); var HTMLFrameSetElement = function(ownerDocument) { //$log("creating anchor element"); this.HTMLElement = HTMLElement; this.HTMLElement(ownerDocument); }; HTMLFrameSetElement.prototype = new HTMLElement; __extend__(HTMLFrameSetElement.prototype, { get cols(){ return this.getAttribute('cols'); }, set cols(value){ this.setAttribute('cols', value); }, get rows(){ return this.getAttribute('rows'); }, set rows(value){ this.setAttribute('rows', value); } }); $log("Defining HTMLHeadElement"); /* * HTMLHeadElement - DOM Level 2 */ $w.__defineGetter__("HTMLHeadElement", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); var HTMLHeadElement = function(ownerDocument) { this.HTMLElement = HTMLElement; this.HTMLElement(ownerDocument); }; HTMLHeadElement.prototype = new HTMLElement; __extend__(HTMLHeadElement.prototype, { get profile(){ return this.getAttribute('profile'); }, set profile(value){ this.setAttribute('profile', value); }, }); $log("Defining HTMLIFrameElement"); /* * HTMLIFrameElement - DOM Level 2 */ $w.__defineGetter__("HTMLIFrameElement", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); var HTMLIFrameElement = function(ownerDocument) { //$log("creating iframe element"); this.HTMLFrameElement = HTMLFrameElement; this.HTMLFrameElement(ownerDocument); }; HTMLIFrameElement.prototype = new HTMLFrameElement; __extend__(HTMLIFrameElement.prototype, { get height() { return this.getAttribute("height") || ""; }, set height(val) { return this.setAttribute("height",val); }, get width() { return this.getAttribute("width") || ""; }, set width(val) { return this.setAttribute("width",val); } }); $log("Defining HTMLImageElement"); /* * HTMLImageElement - DOM Level 2 */ $w.__defineGetter__("HTMLImageElement", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); var HTMLImageElement = function(ownerDocument) { this.HTMLElement = HTMLElement; this.HTMLElement(ownerDocument); }; HTMLImageElement.prototype = new HTMLElement; __extend__(HTMLImageElement.prototype, { get alt(){ return this.getAttribute('alt'); }, set alt(value){ this.setAttribute('alt', value); }, get height(){ return this.getAttribute('height'); }, set height(value){ this.setAttribute('height', value); }, get isMap(){ return this.hasAttribute('map'); }, set useMap(value){ this.setAttribute('map', value); }, get longDesc(){ return this.getAttribute('longdesc'); }, set longDesc(value){ this.setAttribute('longdesc', value); }, get name(){ return this.getAttribute('name'); }, set name(value){ this.setAttribute('name', value); }, get src(){ return this.getAttribute('src'); }, set src(value){ this.setAttribute('src', value); }, get width(){ return this.getAttribute('width'); }, set width(value){ this.setAttribute('width', value); } }); $log("Defining HTMLInputElement"); /* * HTMLInputElement - DOM Level 2 */ $w.__defineGetter__("HTMLInputElement", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); var HTMLInputElement = function(ownerDocument) { //$log("creating anchor element"); this.HTMLElement = HTMLElement; this.HTMLElement(ownerDocument); }; HTMLInputElement.prototype = new HTMLElement; __extend__(HTMLInputElement.prototype, { get defaultValue(){ return this.getAttribute('defaultValue'); }, set defaultValue(value){ this.setAttribute('defaultValue', value); }, get defaultChecked(){ return this.getAttribute('defaultChecked'); }, get form(){ var parent = this.parent; while(parent.nodeName.toLowerCase() != 'form'){ parent = parent.parent; } return parent; }, get accessKey(){ return this.getAttribute('accesskey'); }, set accessKey(value){ this.setAttribute('accesskey',value); }, get access(){ return this.getAttribute('access'); }, set access(value){ this.setAttribute('access', value); }, get alt(){ return this.getAttribute('alt'); }, set alt(value){ this.setAttribute('alt', value); }, get checked(){ return (this.getAttribute('checked')==='checked'); }, set checked(){ this.setAttribute('checked', 'checked'); }, get disabled(){ return (this.getAttribute('disabled')==='disabled'); }, set disabled(value){ this.setAttribute('disabled', 'disabled'); }, get maxLength(){ return Number(this.getAttribute('maxlength')||'0'); }, set maxLength(value){ this.setAttribute('maxlength', value); }, get name(){ return this.getAttribute('name')||''; }, set name(value){ this.setAttribute('name', value); }, get readOnly(){ return (this.getAttribute('readonly')==='readonly'); }, set readOnly(value){ this.setAttribute('readonly', 'readonly'); }, get size(){ return this.getAttribute('size'); }, set size(value){ this.setAttribute('size', value); }, get src(){ return this.getAttribute('src'); }, set src(value){ this.setAttribute('src', value); }, get tabIndex(){ return Number(this.getAttribute('tabindex')); }, set tabIndex(value){ this.setAttribute('tabindex',Number(value)); }, get type(){ return this.getAttribute('type'); }, set type(value){ this.setAttribute('type',value); }, get useMap(){ return this.getAttribute('map'); }, get value(){ return this.getAttribute('value'); }, set value(value){ this.setAttribute('value',value); }, blur:function(){ __blur__(this); }, focus:function(){ __focus__(this); }, select:function(){ __select__(this); }, click:function(){ __click__(this); } }); $log("Defining HTMLLabelElement"); /* * HTMLLabelElement - DOM Level 2 */ $w.__defineGetter__("HTMLLabelElement", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); var HTMLLabelElement = function(ownerDocument) { this.HTMLElement = HTMLElement; this.HTMLElement(ownerDocument); }; HTMLLabelElement.prototype = new HTMLElement; __extend__(HTMLLabelElement.prototype, { get form(){ var parent = this.parent; while(parent.nodeName.toLowerCase() != 'form'){ parent = parent.parent; } return parent; }, get accessKey(){ return this.getAttribute('accesskey'); }, set accessKey(value){ this.setAttribute('accesskey',value); }, get htmlFor(){ return this.getAttribute('for'); }, set htmlFor(value){ this.setAttribute('for',value); }, }); $log("Defining HTMLLegendElement"); /* * HTMLLegendElement - DOM Level 2 */ $w.__defineGetter__("HTMLLegendElement", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); var HTMLLegendElement = function(ownerDocument) { this.HTMLElement = HTMLElement; this.HTMLElement(ownerDocument); }; HTMLLegendElement.prototype = new HTMLElement; __extend__(HTMLLegendElement.prototype, { get form(){ var parent = this.parent; while(parent.nodeName.toLowerCase() != 'form'){ parent = parent.parent; } return parent; }, get accessKey(){ return this.getAttribute('accesskey'); }, set accessKey(value){ this.setAttribute('accesskey',value); } }); /** * Link - HTMLElement */ $w.__defineGetter__("Link", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); $log("Defining HTMLLinkElement"); /* * HTMLLinkElement - DOM Level 2 */ $w.__defineGetter__("HTMLLinkElement", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); var HTMLLinkElement = function(ownerDocument) { //$log("creating anchor element"); this.HTMLElement = HTMLElement; this.HTMLElement(ownerDocument); }; HTMLLinkElement.prototype = new HTMLElement; __extend__(HTMLLinkElement.prototype, { get disabled(){ return this.getAttribute('disabled'); }, set disabled(value){ this.setAttribute('disabled',value); }, get charset(){ return this.getAttribute('charset'); }, set charset(value){ this.setAttribute('charset',value); }, get href(){ return this.getAttribute('href'); }, set href(value){ this.setAttribute('href',value); }, get hreflang(){ return this.getAttribute('hreflang'); }, set hreflang(value){ this.setAttribute('hreflang',value); }, get media(){ return this.getAttribute('media'); }, set media(value){ this.setAttribute('media',value); }, get rel(){ return this.getAttribute('rel'); }, set rel(value){ this.setAttribute('rel',value); }, get rev(){ return this.getAttribute('rev'); }, set rev(value){ this.setAttribute('rev',value); }, get target(){ return this.getAttribute('target'); }, set target(value){ this.setAttribute('target',value); }, get type(){ return this.getAttribute('type'); }, set type(value){ this.setAttribute('type',value); } }); $log("Defining HTMLMapElement"); /* * HTMLMapElement - DOM Level 2 */ $w.__defineGetter__("HTMLMapElement", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); var HTMLMapElement = function(ownerDocument) { //$log("creating anchor element"); this.HTMLElement = HTMLElement; this.HTMLElement(ownerDocument); }; HTMLMapElement.prototype = new HTMLElement; __extend__(HTMLMapElement.prototype, { get areas(){ return this.getElementsByTagName('area'); }, get name(){ return this.getAttribute('name'); }, set name(value){ this.setAttribute('name',value); } }); $log("Defining HTMLMetaElement"); /* * HTMLMetaElement - DOM Level 2 */ $w.__defineGetter__("HTMLMetaElement", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); var HTMLMetaElement = function(ownerDocument) { this.HTMLElement = HTMLElement; this.HTMLElement(ownerDocument); }; HTMLMetaElement.prototype = new HTMLElement; __extend__(HTMLMetaElement.prototype, { get content(){ return this.getAttribute('content'); }, set content(value){ this.setAttribute('content',value); }, get httpEquiv(){ return this.getAttribute('http-equiv'); }, set httpEquiv(value){ this.setAttribute('http-equiv',value); }, get name(){ return this.getAttribute('name'); }, set name(value){ this.setAttribute('name',value); }, get scheme(){ return this.getAttribute('scheme'); }, set scheme(value){ this.setAttribute('scheme',value); } }); $log("Defining HTMLObjectElement"); /* * HTMLObjectElement - DOM Level 2 */ $w.__defineGetter__("HTMLObjectElement", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); var HTMLObjectElement = function(ownerDocument) { //$log("creating anchor element"); this.HTMLElement = HTMLElement; this.HTMLElement(ownerDocument); }; HTMLObjectElement.prototype = new HTMLElement; __extend__(HTMLObjectElement.prototype, { get code(){ return this.getAttribute('code'); }, set code(value){ this.setAttribute('code',value); }, get archive(){ return this.getAttribute('archive'); }, set archive(value){ this.setAttribute('archive',value); }, get codeBase(){ return this.getAttribute('codebase'); }, set codeBase(value){ this.setAttribute('codebase',value); }, get codeType(){ return this.getAttribute('codetype'); }, set codeType(value){ this.setAttribute('codetype',value); }, get data(){ return this.getAttribute('data'); }, set data(value){ this.setAttribute('data',value); }, get declare(){ return this.getAttribute('declare'); }, set declare(value){ this.setAttribute('declare',value); }, get height(){ return this.getAttribute('height'); }, set height(value){ this.setAttribute('height',value); }, get standby(){ return this.getAttribute('standby'); }, set standby(value){ this.setAttribute('standby',value); }, get tabIndex(){ return this.getAttribute('tabindex'); }, set tabIndex(value){ this.setAttribute('tabindex',value); }, get type(){ return this.getAttribute('type'); }, set type(value){ this.setAttribute('type',value); }, get useMap(){ return this.getAttribute('usemap'); }, set useMap(value){ this.setAttribute('usemap',value); }, get width(){ return this.getAttribute('width'); }, set width(value){ this.setAttribute('width',value); }, get contentDocument(){ return this.ownerDocument; } }); $log("Defining HTMLOptGroupElement"); /* * HTMLOptGroupElement - DOM Level 2 */ $w.__defineGetter__("HTMLOptGroupElement", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); var HTMLOptGroupElement = function(ownerDocument) { //$log("creating anchor element"); this.HTMLElement = HTMLElement; this.HTMLElement(ownerDocument); }; HTMLOptGroupElement.prototype = new HTMLElement; __extend__(HTMLOptGroupElement.prototype, { get disabled(){ return this.getAttribute('disabled'); }, set disabled(value){ this.setAttribute('disabled',value); }, get label(){ return this.getAttribute('label'); }, set label(value){ this.setAttribute('label',value); }, }); $log("Defining HTMLOptionElement"); /* * HTMLOptionElement - DOM Level 2 */ $w.__defineGetter__("HTMLOptionElement", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); var HTMLOptionElement = function(ownerDocument) { //$log("creating anchor element"); this.HTMLElement = HTMLElement; this.HTMLElement(ownerDocument); }; HTMLOptionElement.prototype = new HTMLElement; __extend__(HTMLOptionElement.prototype, { get form(){ var parent = this.parent; while(parent.nodeName.toLowerCase() != 'form'){ parent = parent.parent; } return parent; }, get defaultSelected(){ return this.getAttribute('defaultSelected'); }, set defaultSelected(value){ this.setAttribute('defaultSelected',value); }, get text(){ return this.nodeValue; }, get index(){ var options = this.parent.childNodes; for(var i; i<options.length;i++){ if(this == options[i]) return i; } return -1; }, get disabled(){ return this.getAttribute('disabled'); }, set disabled(value){ this.setAttribute('disabled',value); }, get label(){ return this.getAttribute('label'); }, set label(value){ this.setAttribute('label',value); }, get selected(){ return (this.getAttribute('selected')==='selected'); }, set selected(){ this.setAttribute('selected','selected'); }, get value(){ return this.getAttribute('value'); }, set value(value){ this.setAttribute('value',value); } }); $log("Defining HTMLParamElement"); /* * HTMLParamElement - DOM Level 2 */ $w.__defineGetter__("HTMLParamElement", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); var HTMLParamElement = function(ownerDocument) { //$log("creating anchor element"); this.HTMLElement = HTMLElement; this.HTMLElement(ownerDocument); }; HTMLParamElement.prototype = new HTMLElement; __extend__(HTMLParamElement.prototype, { get name(){ return this.getAttribute('name'); }, set name(value){ this.setAttribute('name',value); }, get type(){ return this.getAttribute('type'); }, set type(value){ this.setAttribute('type',value); }, get value(){ return this.getAttribute('value'); }, set value(value){ this.setAttribute('value',value); }, get valueType(){ return this.getAttribute('valuetype'); }, set valueType(value){ this.setAttribute('valuetype',value); }, }); $log("Defining HTMLScriptElement"); /* * HTMLScriptElement - DOM Level 2 */ $w.__defineGetter__("HTMLScriptElement", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); var HTMLScriptElement = function(ownerDocument) { //$log("creating anchor element"); this.HTMLElement = HTMLElement; this.HTMLElement(ownerDocument); }; HTMLScriptElement.prototype = new HTMLElement; __extend__(HTMLScriptElement.prototype, { get text(){ return this.nodeValue; }, get htmlFor(){ return this.getAttribute('for'); }, set htmlFor(value){ this.setAttribute('for',value); }, get event(){ return this.getAttribute('event'); }, set event(value){ this.setAttribute('event',value); }, get charset(){ return this.getAttribute('charset'); }, set charset(value){ this.setAttribute('charset',value); }, get defer(){ return this.getAttribute('defer'); }, set defer(value){ this.setAttribute('defer',value); }, get src(){ return this.getAttribute('src'); }, set src(value){ this.setAttribute('src',value); }, get type(){ return this.getAttribute('type'); }, set type(value){ this.setAttribute('type',value); } }); $log("Defining HTMLSelectElement"); /* * HTMLSelectElement - DOM Level 2 */ $w.__defineGetter__("HTMLSelectElement", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); var HTMLSelectElement = function(ownerDocument) { //$log("creating anchor element"); this.HTMLElement = HTMLElement; this.HTMLElement(ownerDocument); }; HTMLSelectElement.prototype = new HTMLElement; __extend__(HTMLSelectElement.prototype, { get type(){ return this.getAttribute('type'); }, get selectedIndex(){ var options = this.options; for(var i=0;i<options.length;i++){ if(options[i].selected){ return i; } }; return -1; }, set selectedIndex(value){ this.options[Number(value)].selected = 'selected'; }, get value(){ return this.getAttribute('value')||''; }, set value(value){ this.setAttribute('value',value); }, get length(){ return this.options.length; }, get form(){ var parent = this.parent; while(parent.nodeName.toLowerCase() != 'form'){ parent = parent.parent; } return parent; }, get options(){ return this.getElementsByTagName('option'); }, get disabled(){ return (this.getAttribute('disabled')==='disabled'); }, set disabled(){ this.setAttribute('disabled','disabled'); }, get multiple(){ return this.getAttribute('multiple'); }, set multiple(value){ this.setAttribute('multiple',value); }, get name(){ return this.getAttribute('name')||''; }, set name(value){ this.setAttribute('name',value); }, get size(){ return Number(this.getAttribute('size')); }, set size(value){ this.setAttribute('size',value); }, get tabIndex(){ return Number(this.getAttribute('tabindex')); }, set tabIndex(value){ this.setAttribute('tabindex',value); }, add : function(){ __add__(this); }, remove : function(){ __remove__(this); }, blur: function(){ __blur__(this); }, focus: function(){ __focus__(this); } }); $log("Defining HTMLStyleElement"); /* * HTMLStyleElement - DOM Level 2 */ $w.__defineGetter__("HTMLStyleElement", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); var HTMLStyleElement = function(ownerDocument) { //$log("creating anchor element"); this.HTMLElement = HTMLElement; this.HTMLElement(ownerDocument); }; HTMLStyleElement.prototype = new HTMLElement; __extend__(HTMLStyleElement.prototype, { get disabled(){ return this.getAttribute('disabled'); }, set disabled(value){ this.setAttribute('disabled',value); }, get media(){ return this.getAttribute('media'); }, set media(value){ this.setAttribute('media',value); }, get type(){ return this.getAttribute('type'); }, set type(value){ this.setAttribute('type',value); }, }); $log("Defining Event"); /* * event.js */ $w.__defineGetter__("Event", function(){ __extend__(this,{ CAPTURING_PHASE : 1, AT_TARGET : 2, BUBBLING_PHASE : 3 }); return function(){ throw new Error("Object cannot be created in this context"); }; }); var Event = function(options){ if(options === undefined){options={target:window,currentTarget:window};} __extend__(this,{ CAPTURING_PHASE : 1, AT_TARGET : 2, BUBBLING_PHASE : 3 }); $log("Creating new Event"); var $bubbles = options.bubbles?options.bubbles:true, $cancelable = options.cancelable?options.cancelable:true, $currentTarget = options.currentTarget?options.currentTarget:null, $eventPhase = options.eventPhase?options.eventPhase:Event.CAPTURING_PHASE, $target = options.eventPhase?options.eventPhase:document, $timestamp = options.timestamp?options.timestamp:new Date().getTime().toString(), $type = options.type?options.type:""; return __extend__(this,{ get bubbles(){return $bubbles;}, get cancelable(){return $cancelable;}, get currentTarget(){return $currentTarget;}, get eventPhase(){return $eventPhase;}, get target(){return $target;}, get timestamp(){return $timestamp;}, get type(){return $type;}, initEvent: function(type,bubbles,cancelable){ $type=type?type:$type; $bubbles=bubbles?bubbles:$bubbles; $cancelable=cancelable?cancelable:$cancelable; }, preventDefault: function(){return;/* TODO */}, stopPropagation: function(){return;/* TODO */} }); }; $log("Defining MouseEvent"); /* * mouseevent.js */ $log("Defining MouseEvent"); /* * uievent.js */ var $onblur, $onfocus, $onresize;/* * CSS2Properties - DOM Level 2 CSS */ $w.__defineGetter__("CSS2Properties", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); var CSS2Properties = function(options){ __extend__(this, __supportedStyles__); __cssTextToStyles__(this, options.cssText?options.cssText:""); }; //__extend__(CSS2Properties.prototype, __supportedStyles__); __extend__(CSS2Properties.prototype, { get cssText(){ return Array.prototype.apply.join(this,[';\n']); }, set cssText(cssText){ __cssTextToStyles__(this, cssText); }, getPropertyCSSValue : function(){ }, getPropertyPriority : function(){ }, getPropertyValue : function(name){ var camelCase = name.replace(/\-(\w)/g, function(all, letter){ return letter.toUpperCase(); }); var i, value = this[camelCase]; if(value === undefined){ for(i=0;i<this.length;i++){ if(this[i]===name){ return this[i]; } } } return value; }, item : function(index){ return this[index]; }, removeProperty: function(){ }, setProperty: function(){ }, toString:function(){ if (this.length >0){ return "{\n\t"+Array.prototype.join.apply(this,[';\n\t'])+"}\n"; }else{ return ''; } } }); var __cssTextToStyles__ = function(css2props, cssText){ var styleArray=[]; var style, name, value, camelCaseName, w3cName, styles = cssText.split(';'); for ( var i = 0; i < styles.length; i++ ) { //$log("Adding style property " + styles[i]); style = styles[i].split(':'); if ( style.length == 2 ){ //keep a reference to the original name of the style which was set //this is the w3c style setting method. styleArray[styleArray.length] = w3cName = styles[i]; //camel case for dash case value = trim(style[1]); camelCaseName = trim(style[0].replace(/\-(\w)/g, function(all, letter){ return letter.toUpperCase(); })); //$log('CSS Style Name: ' + camelCaseName); if(css2props[camelCaseName]!==undefined){ //set the value internally with camelcase name //$log('Setting css ' + camelCaseName + ' to ' + value); css2props[camelCaseName] = value; }; } } __setArray__(css2props, styleArray); }; //Obviously these arent all supported but by commenting out various sections //this provides a single location to configure what is exposed as supported. //These will likely need to be functional getters/setters in the future to deal with //the variation on input formulations var __supportedStyles__ = { azimuth: "", background: "", backgroundAttachment: "", backgroundColor: "", backgroundImage: "", backgroundPosition: "", backgroundRepeat: "", border: "", borderBottom: "", borderBottomColor: "", borderBottomStyle: "", borderBottomWidth: "", borderCollapse: "", borderColor: "", borderLeft: "", borderLeftColor: "", borderLeftStyle: "", borderLeftWidth: "", borderRight: "", borderRightColor: "", borderRightStyle: "", borderRightWidth: "", borderSpacing: "", borderStyle: "", borderTop: "", borderTopColor: "", borderTopStyle: "", borderTopWidth: "", borderWidth: "", bottom: "", captionSide: "", clear: "", clip: "", color: "", content: "", counterIncrement: "", counterReset: "", cssFloat: "", cue: "", cueAfter: "", cueBefore: "", cursor: "", direction: "", display: "", elevation: "", emptyCells: "", font: "", fontFamily: "", fontSize: "", fontSizeAdjust: "", fontStretch: "", fontStyle: "", fontVariant: "", fontWeight: "", height: "", left: "", letterSpacing: "", lineHeight: "", listStyle: "", listStyleImage: "", listStylePosition: "", listStyleType: "", margin: "", marginBottom: "", marginLeft: "", marginRight: "", marginTop: "", markerOffset: "", marks: "", maxHeight: "", maxWidth: "", minHeight: "", minWidth: "", opacity: 1, orphans: "", outline: "", outlineColor: "", outlineOffset: "", outlineStyle: "", outlineWidth: "", overflow: "", overflowX: "", overflowY: "", padding: "", paddingBottom: "", paddingLeft: "", paddingRight: "", paddingTop: "", page: "", pageBreakAfter: "", pageBreakBefore: "", pageBreakInside: "", pause: "", pauseAfter: "", pauseBefore: "", pitch: "", pitchRange: "", position: "", quotes: "", richness: "", right: "", size: "", speak: "", speakHeader: "", speakNumeral: "", speakPunctuation: "", speechRate: "", stress: "", tableLayout: "", textAlign: "", textDecoration: "", textIndent: "", textShadow: "", textTransform: "", top: "", unicodeBidi: "", verticalAlign: "", visibility: "", voiceFamily: "", volume: "", whiteSpace: "", widows: "", width: "", wordSpacing: "", zIndex: "" };/* * CSSRule - DOM Level 2 */ $w.__defineGetter__("CSSRule", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); var CSSRule = function(options){ var $style, $selectorText = options.selectorText?options.selectorText:""; $style = new CSS2Properties({cssText:options.cssText?options.cssText:null}); return __extend__(this, { get style(){return $style;}, get selectorText(){return $selectorText;}, set selectorText(selectorText){$selectorText = selectorText;} }); }; /* * CSSStyleSheet - DOM Level 2 */ $w.__defineGetter__("CSSStyleSheet", function(){ return function(){ throw new Error("Object cannot be created in this context"); }; }); var CSSStyleSheet = function(options){ var $cssRules, $disabled = options.disabled?options.disabled:false, $href = options.href?options.href:null, $parentStyleSheet = options.parentStyleSheet?options.parentStyleSheet:null, $title = options.title?options.title:"", $type = "text/css"; function parseStyleSheet(text){ //this is pretty ugly, but text is the entire text of a stylesheet var cssRules = []; if (!text) text = ""; text = trim(text.replace(/\/\*(\r|\n|.)*\*\//g,"")); // TODO: @import ? var blocks = text.split("}"); blocks.pop(); var i, len = blocks.length; var definition_block, properties, selectors; for (i=0; i<len; i++){ definition_block = blocks[i].split("{"); if(definition_block.length === 2){ selectors = definition_block[0].split(","); for(var j=0;j<selectors.length;j++){ cssRules.push(new CSSRule({ selectorText:selectors[j], cssText:definition_block[1] })); } __setArray__($cssRules, cssRules); } } }; parseStyleSheet(options.text); return __extend__(this, { get cssRules(){return $cssRules;}, get rule(){return $cssRules;},//IE - may be deprecated get href(){return $href;}, get parentStyleSheet(){return $parentStyleSheet;}, get title(){return $title;}, get type(){return $type;}, addRule: function(selector, style, index){/*TODO*/}, deleteRule: function(index){/*TODO*/}, insertRule: function(rule, index){/*TODO*/}, removeRule: function(index){this.deleteRule(index);}//IE - may be deprecated }); }; /* * location.js * - requires env */ $log("Initializing Window Location."); //the current location var $location = $env.location('./'); $w.__defineSetter__("location", function(url){ //$w.onunload(); $w.document.load(url); $location = url; setHistory($location); }); $w.__defineGetter__("location", function(url){ var hash = new RegExp('(\\#.*)'), hostname = new RegExp('\/\/([^\:\/]+)'), pathname = new RegExp('(\/[^\\?\\#]*)'), port = new RegExp('\:(\\d+)\/'), protocol = new RegExp('(^\\w*\:)'), search = new RegExp('(\\?[^\\#]*)'); return { get hash(){ var m = hash.exec(this.href); return m&&m.length>1?m[1]:""; }, set hash(_hash){ //setting the hash is the only property of the location object //that doesn't cause the window to reload _hash = _hash.indexOf('#')===0?_hash:"#"+_hash; $location = this.protocol + this.host + this.pathname + this.search + _hash; setHistory(_hash, "hash"); }, get host(){ return this.hostname + (this.port !== "")?":"+this.port:""; }, set host(_host){ $w.location = this.protocol + _host + this.pathname + this.search + this.hash; }, get hostname(){ var m = hostname.exec(this.href); return m&&m.length>1?m[1]:""; }, set hostname(_hostname){ $w.location = this.protocol + _hostname + ((this.port==="")?"":(":"+this.port)) + this.pathname + this.search + this.hash; }, get href(){ //This is the only env specific function return $location; }, set href(url){ $w.location = url; }, get pathname(){ var m = this.href; m = pathname.exec(m.substring(m.indexOf(this.hostname))); return m&&m.length>1?m[1]:"/"; }, set pathname(_pathname){ $w.location = this.protocol + this.host + _pathname + this.search + this.hash; }, get port(){ var m = port.exec(this.href); return m&&m.length>1?m[1]:""; }, set port(_port){ $w.location = this.protocol + this.hostname + ":"+_port + this.pathname + this.search + this.hash; }, get protocol(){ return protocol.exec(this.href)[0]; }, set protocol(_protocol){ $w.location = _protocol + this.host + this.pathname + this.search + this.hash; }, get search(){ var m = search.exec(this.href); return m&&m.length>1?m[1]:""; }, set search(_search){ $w.location = this.protocol + this.host + this.pathname + _search + this.hash; }, toString: function(){ return this.href; }, reload: function(force){ //TODO }, replace: function(url){ //TODO } }; }); /* * history.js */ $log("Initializing Window History."); $currentHistoryIndex = 0; $history = []; // Browser History $w.__defineGetter__("history", function(){ return { get length(){ return $history.length; }, back : function(count){ if(count){ go(-count); }else{go(-1);} }, forward : function(count){ if(count){ go(count); }else{go(1);} }, go : function(target){ if(typeof target == "number"){ target = $currentHistoryIndex+target; if(target > -1 && target < $history.length){ if($history[target].location == "hash"){ $w.location.hash = $history[target].value; }else{ $w.location = $history[target].value; } $currentHistoryIndex = target; //remove the last item added to the history //since we are moving inside the history $history.pop(); } }else{ //TODO: walk throu the history and find the 'best match' } } }; }); //Here locationPart is the particutlar method/attribute // of the location object that was modified. This allows us // to modify the correct portion of the location object // when we navigate the history var setHistory = function( value, locationPart){ $log("adding value to history: " +value); $currentHistoryIndex++; $history.push({ location: locationPart||"href", value: value }); }; /* * navigator.js * - requires env */ $log("Initializing Window Navigator."); var $appCodeName = "EnvJS";//eg "Mozilla" var $appName = "Resig/20070309 BirdDog/0.0.0.1";//eg "Gecko/20070309 Firefox/2.0.0.3" // Browser Navigator $w.__defineGetter__("navigator", function(){ return { get appCodeName(){ return $appCodeName; }, get appName(){ return $appName; }, get appVersion(){ return $version +" ("+ $w.navigator.platform +"; "+ "U; "+//? $env.os_name+" "+$env.os_arch+" "+$env.os_version+"; "+ $env.lang+"; "+ "rv:"+$revision+ ")"; }, get cookieEnabled(){ return true; }, get mimeTypes(){ return []; }, get platform(){ return $env.platform; }, get plugins(){ return []; }, get userAgent(){ return $w.navigator.appCodeName + "/" + $w.navigator.appVersion + " " + $w.navigator.appName; }, javaEnabled : function(){ return $env.javaEnabled; } }; }); /* * timer.js */ $log("Initializing Window Timer."); //private var $timers = []; $w.setTimeout = function(fn, time){ var num; return num = window.setInterval(function(){ fn(); window.clearInterval(num); }, time); }; window.setInterval = function(fn, time){ var num = $timers.length; if (typeof fn == 'string') { var fnstr = fn; fn = function() { eval(fnstr); }; } if(time===0){ fn(); }else{ $timers[num] = $env.timer(fn, time); $timers[num].start(); } return num; }; window.clearInterval = window.clearTimeout = function(num){ if ( $timers[num] ) { $timers[num].stop(); delete $timers[num]; } }; /* * event.js */ // Window Events $log("Initializing Window Event."); var $events = [], $onerror, $onload, $onunload; $w.addEventListener = function(type, fn){ $log("adding event listener " + type); if ( !this.uuid ) { this.uuid = $events.length; $events[this.uuid] = {}; } if ( !$events[this.uuid][type] ){ $events[this.uuid][type] = []; } if ( $events[this.uuid][type].indexOf( fn ) < 0 ){ $events[this.uuid][type].push( fn ); } }; $w.removeEventListener = function(type, fn){ if ( !this.uuid ) { this.uuid = $events.length; $events[this.uuid] = {}; } if ( !$events[this.uuid][type] ){ $events[this.uuid][type] = []; } $events[this.uuid][type] = $events[this.uuid][type].filter(function(f){ return f != fn; }); }; $w.dispatchEvent = function(event){ $log("dispatching event " + event.type); //the window scope defines the $event object, for IE(^^^) compatibility; $event = event; if(!event.target) event.target = this; if ( event.type ) { if ( this.uuid && $events[this.uuid][event.type] ) { var _this = this; $events[this.uuid][event.type].forEach(function(fn){ fn.call( _this, event ); }); } if ( this["on" + event.type] ) this["on" + event.type].call( _this, event ); } if(this.parentNode){ this.parentNode.dispatchEvent.call(this.parentNode,event); } }; $w.__defineGetter__('onerror', function(){ return function(){ //$w.dispatchEvent('error'); }; }); $w.__defineSetter__('onerror', function(fn){ //$w.addEventListener('error', fn); }); /*$w.__defineGetter__('onload', function(){ return function(){ //var event = document.createEvent(); //event.initEvent("load"); //$w.dispatchEvent(event); }; }); $w.__defineSetter__('onload', function(fn){ //$w.addEventListener('load', fn); }); $w.__defineGetter__('onunload', function(){ return function(){ //$w.dispatchEvent('unload'); }; }); $w.__defineSetter__('onunload', function(fn){ //$w.addEventListener('unload', fn); });*//* * xhr.js */ $log("Initializing Window XMLHttpRequest."); // XMLHttpRequest // Originally implemented by Yehuda Katz $w.XMLHttpRequest = function(){ this.headers = {}; this.responseHeaders = {}; }; XMLHttpRequest.prototype = { open: function(method, url, async, user, password){ this.readyState = 1; if (async === false ){ this.async = false; }else{ this.async = true; } this.method = method || "GET"; this.url = $env.location(url); this.onreadystatechange(); }, setRequestHeader: function(header, value){ this.headers[header] = value; }, getResponseHeader: function(header){ }, send: function(data){ var self = this; function makeRequest(){ $env.connection(self, function(){ var responseXML = null; self.__defineGetter__("responseXML", function(){ if ( self.responseText.match(/^\s*</) ) { if(responseXML){return responseXML;} else{ try { $log("parsing response text into xml document"); responseXML = $domparser.parseFromString(self.responseText); return responseXML; } catch(e) { return null;/*TODO: need to flag an error here*/} } }else{return null;} }); }); self.onreadystatechange(); } if (this.async){ $log("XHR sending asynch;"); $env.runAsync(makeRequest); }else{ $log("XHR sending synch;"); makeRequest(); } }, abort: function(){ //TODO }, onreadystatechange: function(){ //TODO }, getResponseHeader: function(header){ var rHeader, returnedHeaders; if (this.readyState < 3){ throw new Error("INVALID_STATE_ERR"); } else { returnedHeaders = []; for (rHeader in this.responseHeaders) { if (rHeader.match(new RegExp(header, "i"))) returnedHeaders.push(this.responseHeaders[rHeader]); } if (returnedHeaders.length){ return returnedHeaders.join(", "); } }return null; }, getAllResponseHeaders: function(){ var header, returnedHeaders = []; if (this.readyState < 3){ throw new Error("INVALID_STATE_ERR"); } else { for (header in this.responseHeaders){ returnedHeaders.push( header + ": " + this.responseHeaders[header] ); } }return returnedHeaders.join("\r\n"); }, async: true, readyState: 0, responseText: "", status: 0 };/* * css.js */ $log("Initializing Window CSS"); // returns a CSS2Properties object that represents the style // attributes and values used to render the specified element in this // window. Any length values are always expressed in pixel, or // absolute values. $w.getComputedStyle = function(elt, pseudo_elt){ //TODO //this is a naive implementation $log("Getting computed style"); return elt?elt.style:new CSS2Properties({cssText:""}); };/* * screen.js */ $log("Initializing Window Screen."); var $availHeight = 600, $availWidth = 800, $colorDepth = 16, $height = 600, $width = 800; $w.__defineGetter__("screen", function(){ return { get availHeight(){return $availHeight;}, get availWidth(){return $availWidth;}, get colorDepth(){return $colorDepth;}, get height(){return $height;}, get width(){return $width;} }; }); $w.moveBy = function(dx,dy){ //TODO }; $w.moveTo = function(x,y) { //TODO }; /*$w.print = function(){ //TODO };*/ $w.resizeBy = function(dw, dh){ $w.resizeTo($width+dw,$height+dh); }; $w.resizeTo = function(width, height){ $width = (width <= $availWidth) ? width : $availWidth; $height = (height <= $availHeight) ? height : $availHeight; }; $w.scroll = function(x,y){ //TODO }; $w.scrollBy = function(dx, dy){ //TODO }; $w.scrollTo = function(x,y){ //TODO };/* * dialog.js */ $log("Initializing Window Dialogs."); $w.alert = function(message){ //TODO }; $w.confirm = function(question){ //TODO }; $w.prompt = function(message, defaultMsg){ //TODO };/* * document.js * * DOM Level 2 /DOM level 3 (partial) * * This file adds the document object to the window and allows you * you to set the window.document using an html string or dom object. * */ // read only reference to the Document object $log("Initializing window.document."); var $async = false; __extend__(HTMLDocument.prototype, { get async(){ return $async;}, set async(async){ $async = async; }, get baseURI(){ return $env.location('./'); }, get URL(){ return $w.location.href; } }); var $document = new HTMLDocument($implementation); $w.__defineGetter__("document", function(){ return $document; }); $log("Defining document.cookie"); /* * cookie.js * - requires env */ var $cookies = { persistent:{ //domain - key on domain name { //path - key on path { //name - key on name { //value : cookie value //other cookie properties //} //} //} //expire - provides a timestamp for expiring the cookie //cookie - the cookie! }, temporary:{//transient is a reserved word :( //like above } }; //HTMLDocument cookie document.__defineSetter__("cookie", function(cookie){ var i,name,value,properties = {},attr,attrs = cookie.split(";"); //for now the strategy is to simply create a json object //and post it to a file in the .cookies.js file. I hate parsing //dates so I decided not to implement support for 'expires' //(which is deprecated) and instead focus on the easier 'max-age' //(which succeeds 'expires') cookie = {};//keyword properties of the cookie for(i=0;i<attrs.length;i++){ attr = attrs[i].split("="); if(attr.length > 0){ name = trim(attr[0]); value = trim(attr[1]); if(name=='max-age'){ //we'll have to set a timer to check these //and garbage collect expired cookies cookie[name] = parseInt(value, 10); } else if(name=='domain'){ if(domainValid(value)){ cookie['domain']=value; }else{ cookie['domain']=$w.location.domain; } } else if(name=='path'){ //not sure of any special logic for path cookie['path'] = value; } else { //its not a cookie keyword so store it in our array of properties //and we'll serialize individually in a moment properties[name] = value; } }else{ if(attr[0] == 'secure'){ cookie[attr[0]] = true; } } } if(!cookie['max-age']){ //it's a transient cookie so it only lasts as long as //the window.location remains the same mergeCookie($cookies.temporary, cookie, properties); }else if(cookie['max-age']===0){ //delete the cookies //TODO }else{ //the cookie is persistent mergeCookie($cookies.persistent, cookie, properties); persistCookies(); } }); document.__defineGetter__("cookie", function(c){ //The cookies that are returned must belong to the same domain //and be at or below the current window.location.path. Also //we must check to see if the cookie was set to 'secure' in which //case we must check our current location.protocol to make sure it's //https: var allcookies = [], i; //TODO }); var domainValid = function(domain){ //make sure the domain //TODO }; var mergeCookie = function(target, cookie, properties){ var name, now; if(!target[cookie.domain]){ target[cookie.domain] = {}; } if(!target[cookie.domain][cookie.path]){ target[cookie.domain][cookie.path] = {}; } for(name in properties){ now = new Date().getTime(); target[cookie.domain][cookie.path][name] = { value:properties[name], "@env:secure":cookie.secure, "@env:max-age":cookie['max-age'], "@env:date-created":now, "@env:expiration":now + cookie['max-age'] }; } }; var persistCookies = function(){ //TODO //I think it should be done via $env so it can be customized }; var loadCookies = function(){ //TODO //should also be configurable via $env }; //We simply use the default ajax get to load the .cookies.js file //if it doesn't exist we create it with a post. Cookies are maintained //in memory, but serialized with each set. $log("Loading Cookies"); try{ //TODO - load cookies loadCookies(); }catch(e){ //TODO - fail gracefully } /* * outro.js */ })(window, __env__); }catch(e){ __env__.error("ERROR LOADING ENV : " + e + "\nLINE SOURCE:\n" +__env__.lineSource(e)); }
Updated env.rhino.js to Chris Thatcher's latest branch.
lib/env.rhino.js
Updated env.rhino.js to Chris Thatcher's latest branch.
<ide><path>ib/env.rhino.js <ide> */ <ide> var __env__ = {}; <ide> (function($env){ <del> <del> $env.debug = function(){}; <del> <del> $env.log = function(){}; <del> //uncomment this if you want to get some internal log statementes <del> //$env.log = print; <del> $env.log("Initializing Rhino Platform Env"); <del> <del> $env.error = function(msg, e){ <del> print("ERROR! : " + msg); <del> print(e); <del> }; <del> <del> $env.lineSource = function(e){ <del> return e.rhinoException.lineSource(); <del> }; <del> <del> $env.hashCode = function(obj){ <del> return obj?obj.hashCode().toString():null; <del> }; <add> <add> //You can emulate different user agents by overriding these after loading env <add> $env.appCodeName = "EnvJS";//eg "Mozilla" <add> $env.appName = "Resig/20070309 BirdDog/0.0.0.1";//eg "Gecko/20070309 Firefox/2.0.0.3" <add> <add> //set this to true and see profile/profile.js to select which methods <add> //to profile <add> $env.profile = false; <add> <add> $env.debug = function(){}; <add> <add> $env.log = function(){}; <add> //uncomment this if you want to get some internal log statementes <add> // $env.log = print; <add> $env.log("Initializing Rhino Platform Env"); <add> <add> $env.error = function(msg, e){ <add> print("ERROR! : " + msg); <add> print(e||""); <add> }; <add> <add> $env.lineSource = function(e){ <add> return e.rhinoException?e.rhinoException.lineSource():"(line ?)"; <add> }; <add> <add> $env.hashCode = function(obj){ <add> return obj?obj.hashCode().toString():null; <add> }; <add> <ide> //For Java the window.location object is a java.net.URL <ide> $env.location = function(path, base){ <ide> var protocol = new RegExp('(^\\w*\:)'); <ide> $env.lang = java.lang.System.getProperty("user.lang"); <ide> $env.platform = "Rhino ";//how do we get the version <ide> <del> <del> $env.loadScripts = safeScript; <del> function safeScript(){ <add> $env.safeScript = function(){ <ide> //do nothing <ide> }; <ide> <del> function localScripts(){ <del> //try loading locally <del> var scripts = document.getElementsByTagName('script'); <del> for(var i=0;i<scipts.length;i++){ <del> if(scripts[i].getAttribute('type') == 'text/javascript'){ <del> try{ <del> load(scripts[i].src); <del> }catch(e){ <del> $error("Error loading script." , e); <del> } <add> <add> $env.loadLocalScripts = function(script){ <add> try{ <add> if(script.type == 'text/javascript'){ <add> if(script.src){ <add> print("loading script :" + script.src); <add> load($env.location(script.src, window.location + '/../')); <add> }else{ <add> print("loading script :" + script.text); <add> eval(script.text); <add> } <ide> } <add> }catch(e){ <add> print("Error loading script." , e); <ide> } <ide> }; <add> <ide> })(__env__);/* <add>* policy.js <add>*/ <add>var __policy__ = {}; <add>(function($policy, $env){ <add> <add> //you can change these to $env.safeScript to avoid loading scripts <add> //or change to $env.loadLocalScripts to load local scripts <add> $policy.loadScripts = $env.safeScript; <add> <add>})(__policy__, __env__);/* <ide> * Pure JavaScript Browser Environment <ide> * By John Resig <http://ejohn.org/> <ide> * Copyright 2008 John Resig, under the MIT License <ide> return __this__; <ide> }); <ide> try{ <del>(function($w, $env){ <add>(function($w, $env, $policy){ <ide> /* <ide> * window.js <ide> * - this file will be wrapped in a closure providing the window object as $w <ide> <ide> // Read-only properties that specify the number of pixels that the current document has been scrolled <ide> //to the right and down. These are not supported by IE. <del>var $pageXOffset = 0, $pageYOffest = 0; <add>var $pageXOffset = 0, $pageYOffset = 0; <ide> <ide> //A read-only reference to the Window object that contains this window or frame. If the window is <ide> // a top-level window, parent refers to the window itself. If this window is a frame, this property <ide> this.firstChild = newChild; <ide> } <ide> } <del> <ide> return newChild; <ide> }, <ide> hasChildNodes : function() { <ide> //turns namespace checking off in ._isValidNamespace <ide> this.ownerDocument._performingImportNodeOperation = true; <ide> <del> try { <add> //try { <ide> if (importedNode.nodeType == DOMNode.ELEMENT_NODE) { <ide> if (!this.ownerDocument.implementation.namespaceAware) { <ide> // create a local Element (with the name of the importedNode) <ide> //reset _performingImportNodeOperation <ide> this.ownerDocument._performingImportNodeOperation = false; <ide> return importNode; <del> } catch (eAny) { <add> /*} catch (eAny) { <ide> //reset _performingImportNodeOperation <ide> this.ownerDocument._performingImportNodeOperation = false; <ide> <ide> //re-throw the exception <ide> throw eAny; <del> }//djotemp <add> }//djotemp*/ <ide> }, <ide> contains : function(node){ <ide> while(node && node != this ){ <ide> <ide> return nodeList; <ide> }; <del> <ide> <ide> /** <ide> * @method DOMNode._getElementsByTagNameNSRecursive - implements getElementsByTagName() <ide> /* <ide> * DOMParser <ide> */ <del>$w.__defineGetter__('DOMParser', function(){ <del> return function(){ <del> return __extend__(this, { <del> parseFromString: function(xmlString){ <add> <add>var DOMParser = function(){}; <add>__extend__(DOMParser.prototype,{ <add> parseFromString: function(xmlString){ <ide> //$log("Parsing XML String: " +xmlString); <ide> return document.implementation.createDocument().loadXML(xmlString); <del> } <del> }); <del> }; <add> } <ide> }); <ide> <ide> $log("Initializing Internal DOMParser."); <ide> //keep one around for internal use <ide> $domparser = new DOMParser(); <ide> <add>$w.__defineGetter__('DOMParser', DOMParser); <ide> // ========================================================================= <ide> // <ide> // xmlsax.js - an XML SAX parser in JavaScript. <ide> if(this.m_iP == this.m_xml.length) { <ide> return XMLP._NONE; <ide> } <del> <del> if(this.m_iP == this.m_xml.indexOf("<?", this.m_iP)) { <del> return this._parsePI (this.m_iP + 2); <del> } <del> else if(this.m_iP == this.m_xml.indexOf("<!DOCTYPE", this.m_iP)) { <del> return this._parseDTD (this.m_iP + 9); <del> } <del> else if(this.m_iP == this.m_xml.indexOf("<!--", this.m_iP)) { <del> return this._parseComment(this.m_iP + 4); <del> } <del> else if(this.m_iP == this.m_xml.indexOf("<![CDATA[", this.m_iP)) { <del> return this._parseCDATA (this.m_iP + 9); <del> } <del> else if(this.m_iP == this.m_xml.indexOf("<", this.m_iP)) { <del> return this._parseElement(this.m_iP + 1); <del> } <del> else if(this.m_iP == this.m_xml.indexOf("&", this.m_iP)) { <del> return this._parseEntity (this.m_iP + 1); <add> <add> if(this.m_iP == this.m_xml.indexOf("<", this.m_iP)){ <add> if(this.m_xml.charAt(this.m_iP+1) == "?") { <add> return this._parsePI(this.m_iP + 2); <add> } <add> else if(this.m_xml.charAt(this.m_iP+1) == "!") { <add> if(this.m_xml.charAt(this.m_iP+2) == "D") { <add> return this._parseDTD(this.m_iP + 9); <add> } <add> else if(this.m_xml.charAt(this.m_iP+2) == "-") { <add> return this._parseComment(this.m_iP + 4); <add> } <add> else if(this.m_xml.charAt(this.m_iP+2) == "[") { <add> return this._parseCDATA(this.m_iP + 9); <add> } <add> } <add> else{ <add> return this._parseElement(this.m_iP + 1); <add> } <add> } <add> else if(this.m_iP == this.m_xml.indexOf("&", this.m_iP)) { <add> return this._parseEntity(this.m_iP + 1); <ide> } <ide> else{ <del> return this._parseText (this.m_iP); <add> return this._parseText(this.m_iP); <ide> } <ide> <ide> <ide> } <ide> <ide> cQuote = this.m_xml.charAt(iVB); <del> if(SAXStrings.QUOTES.indexOf(cQuote) == -1) { <add> if(_SAXStrings.QUOTES.indexOf(cQuote) == -1) { <ide> return this._setErr(XMLP.ERR_ATT_VALUES); <ide> } <ide> <ide> <ide> if(this._findAttributeIndex(strN) == -1) { <ide> this._addAttribute(strN, strV); <del> } <del> else { <add> }else { <ide> return this._setErr(XMLP.ERR_ATT_DUP); <ide> } <ide> <ide> <ide> while(true) { <ide> // DEBUG: Remove <del> if(iE == iLast) { <add> /*if(iE == iLast) { <ide> return this._setErr(XMLP.ERR_INFINITELOOP); <ide> } <ide> <del> iLast = iE; <add> iLast = iE;*/ <ide> // DEBUG: Remove End <ide> <ide> iE = this.m_xml.indexOf(strClose, iB); <ide> //djohack <ide> //hack to allow for elements with single character names to be recognized <ide> <del> if (iE - iB != 1 ) { <add> /*if (iE - iB != 1 ) { <ide> if(SAXStrings.indexOfNonWhitespace(this.m_xml, iB, iDE) != iB) { <ide> return this._setErr(XMLP.ERR_ELM_NAME); <ide> } <del> } <add> }*/ <ide> // end hack -- original code below <ide> <ide> /* <ide> this.m_iP = iNE; <ide> while(this.m_iP < iDE) { <ide> // DEBUG: Remove <del> if(this.m_iP == iLast) return this._setErr(XMLP.ERR_INFINITELOOP); <del> iLast = this.m_iP; <add> //if(this.m_iP == iLast) return this._setErr(XMLP.ERR_INFINITELOOP); <add> //iLast = this.m_iP; <ide> // DEBUG: Remove End <ide> <ide> <ide> <ide> strN = this.m_xml.substring(iB, iNE); <ide> <del> if(strN.indexOf("<") != -1) { <add> /*if(strN.indexOf("<") != -1) { <ide> return this._setErr(XMLP.ERR_ELM_LT_NAME); <del> } <add> }*/ <ide> <ide> this.m_name = strN; <ide> this.m_iP = iE + 1; <ide> * Description: a useful object containing string manipulation functions <ide> **/ <ide> <del>var SAXStrings = function() {}; <del> <del> <del>SAXStrings.WHITESPACE = " \t\n\r"; <del>SAXStrings.QUOTES = "\"'"; <del> <del> <del>SAXStrings.getColumnNumber = function(strD, iP) { <del> if(SAXStrings.isEmpty(strD)) { <add>var _SAXStrings = function() {}; <add> <add> <add>_SAXStrings.WHITESPACE = " \t\n\r"; <add>_SAXStrings.NONWHITESPACE = /\S/; <add>_SAXStrings.QUOTES = "\"'"; <add> <add> <add>_SAXStrings.prototype.getColumnNumber = function(strD, iP) { <add> if((strD === null) || (strD.length === 0)) { <ide> return -1; <ide> } <ide> iP = iP || strD.length; <ide> } // end function getColumnNumber <ide> <ide> <del>SAXStrings.getLineNumber = function(strD, iP) { <del> if(SAXStrings.isEmpty(strD)) { <add>_SAXStrings.prototype.getLineNumber = function(strD, iP) { <add> if((strD === null) || (strD.length === 0)) { <ide> return -1; <ide> } <ide> iP = iP || strD.length; <ide> } // end function getLineNumber <ide> <ide> <del>SAXStrings.indexOfNonWhitespace = function(strD, iB, iE) { <del> if(SAXStrings.isEmpty(strD)) { <add>_SAXStrings.prototype.indexOfNonWhitespace = function(strD, iB, iE) { <add> if((strD === null) || (strD.length === 0)) { <ide> return -1; <ide> } <ide> iB = iB || 0; <ide> iE = iE || strD.length; <ide> <del> for(var i = iB; i < iE; i++){ <del> if(SAXStrings.WHITESPACE.indexOf(strD.charAt(i)) == -1) { <add> //var i = strD.substring(iB, iE).search(_SAXStrings.NONWHITESPACE); <add> //return i < 0 ? i : iB + i; <add> <add> while( strD.charCodeAt(iB++) < 33 ); <add> return (iB > iE)?-1:iB-1; <add> /*for(var i = iB; i < iE; i++){ <add> if(_SAXStrings.WHITESPACE.indexOf(strD.charAt(i)) == -1) { <ide> return i; <ide> } <ide> } <del> return -1; <add> return -1;*/ <ide> <ide> } // end function indexOfNonWhitespace <ide> <ide> <del>SAXStrings.indexOfWhitespace = function(strD, iB, iE) { <del> if(SAXStrings.isEmpty(strD)) { <add>_SAXStrings.prototype.indexOfWhitespace = function(strD, iB, iE) { <add> if((strD === null) || (strD.length === 0)) { <ide> return -1; <ide> } <ide> iB = iB || 0; <ide> iE = iE || strD.length; <ide> <del> for(var i = iB; i < iE; i++) { <del> if(SAXStrings.WHITESPACE.indexOf(strD.charAt(i)) != -1) { <add> <add> while( strD.charCodeAt(iB++) >= 33 ); <add> return (iB > iE)?-1:iB-1; <add> <add> /*for(var i = iB; i < iE; i++) { <add> if(_SAXStrings.WHITESPACE.indexOf(strD.charAt(i)) != -1) { <ide> return i; <ide> } <ide> } <del> return -1; <add> return -1;*/ <ide> } // end function indexOfWhitespace <ide> <ide> <del>SAXStrings.isEmpty = function(strD) { <add>_SAXStrings.prototype.isEmpty = function(strD) { <ide> <ide> return (strD == null) || (strD.length == 0); <ide> <ide> } <ide> <ide> <del>SAXStrings.lastIndexOfNonWhitespace = function(strD, iB, iE) { <del> if(SAXStrings.isEmpty(strD)) { <add>_SAXStrings.prototype.lastIndexOfNonWhitespace = function(strD, iB, iE) { <add> if((strD === null) || (strD.length === 0)) { <ide> return -1; <ide> } <ide> iB = iB || 0; <ide> iE = iE || strD.length; <ide> <del> for(var i = iE - 1; i >= iB; i--){ <del> if(SAXStrings.WHITESPACE.indexOf(strD.charAt(i)) == -1){ <add> while( (iE >= iB) && strD.charCodeAt(--iE) < 33 ); <add> return (iE < iB)?-1:iE; <add> <add> /*for(var i = iE - 1; i >= iB; i--){ <add> if(_SAXStrings.WHITESPACE.indexOf(strD.charAt(i)) == -1){ <ide> return i; <ide> } <ide> } <del> return -1; <add> return -1;*/ <ide> } <ide> <ide> <del>SAXStrings.replace = function(strD, iB, iE, strF, strR) { <del> if(SAXStrings.isEmpty(strD)) { <add>_SAXStrings.prototype.replace = function(strD, iB, iE, strF, strR) { <add> if((strD == null) || (strD.length == 0)) { <ide> return ""; <ide> } <ide> iB = iB || 0; <ide> <ide> return strD.substring(iB, iE).split(strF).join(strR); <ide> <del>} <add>}; <add> <add>var SAXStrings = new _SAXStrings(); <ide> <ide> <ide> <ide> }, <ide> loadXML : function(xmlStr) { <ide> // create SAX Parser <del> var parser; <del> <del> try { <del> parser = new XMLP(String(xmlStr)); <del> }catch (e) { <del> $error("Error Creating the SAX Parser. \n\n\t"+e+"\n\n\t Did you include xmlsax.js or tinyxmlsax.js\ <del> in your web page?\nThe SAX parser is needed to populate XML for <SCRIPT>'s \ <del> W3C DOM Parser with data."); <del> } <add> var parser = new XMLP(String(xmlStr)); <add> <ide> // create DOM Document <ide> var doc = new HTMLDocument(this.implementation); <ide> // populate Document with Parsed Nodes <ide> try { <ide> __parseLoop__(this.implementation, doc, parser); <add> //HTMLtoDOM(xmlStr, doc); <ide> } catch (e) { <ide> $error(this.implementation.translateErrCode(e.code)) <ide> } <ide> "<p>"+e.toString()+"</p>"+ <ide> "</body></html>"); <ide> } <del> $env.loadScripts(); <ide> _this._url = url; <ide> $log("Sucessfully loaded document."); <ide> var event = document.createEvent(); <ide> throw new Error("Object cannot be created in this context"); <ide> }; <ide> }); <add> <ide> var HTMLElement = function(ownerDocument) { <ide> //$log("\tcreating html element"); <ide> this.DOMElement = DOMElement; <ide> set innerHTML(html){ <ide> //$debug("htmlElement.innerHTML("+html+")"); <ide> //Should be replaced with HTMLPARSER usage <del> //html = (html?html:"").replace(/<\/?([A-Z]+)/g, function(m){ <del> // return m.toLowerCase(); <del> //}).replace(/&nbsp;/g, " "); <del> var doc = new DOMParser(). <add> var doc = new DOMParser(). <ide> parseFromString('<div>'+html+'</div>'); <ide> var parent = this.ownerDocument.importNode(doc.documentElement, true); <ide> <ide> //$log("creating anchor element"); <ide> this.HTMLElement = HTMLElement; <ide> this.HTMLElement(ownerDocument); <add> $log("loading script via policy"); <add> var _this = this; <add> $w.setTimeout(function(){ <add> $policy.loadScripts(_this); <add> }, 1); <ide> }; <ide> HTMLScriptElement.prototype = new HTMLElement; <ide> __extend__(HTMLScriptElement.prototype, { <ide> <ide> $w.__defineSetter__("location", function(url){ <ide> //$w.onunload(); <del> $w.document.load(url); <del> $location = url; <add> $location = $env.location(url); <ide> setHistory($location); <add> $w.document.load($location); <ide> }); <ide> <ide> $w.__defineGetter__("location", function(url){ <ide> */ <ide> $log("Initializing Window Navigator."); <ide> <del>var $appCodeName = "EnvJS";//eg "Mozilla" <del>var $appName = "Resig/20070309 BirdDog/0.0.0.1";//eg "Gecko/20070309 Firefox/2.0.0.3" <add>var $appCodeName = $env.appCodeName;//eg "Mozilla" <add>var $appName = $env.appName;//eg "Gecko/20070309 Firefox/2.0.0.3" <ide> <ide> // Browser Navigator <ide> $w.__defineGetter__("navigator", function(){ <ide> <ide> $w.prompt = function(message, defaultMsg){ <ide> //TODO <del>};/* <add>};/** <add>* jQuery AOP - jQuery plugin to add features of aspect-oriented programming (AOP) to jQuery. <add>* http://jquery-aop.googlecode.com/ <add>* <add>* Licensed under the MIT license: <add>* http://www.opensource.org/licenses/mit-license.php <add>* <add>* Version: 1.1 <add>*/ <add>window.$profiler; <add> <add>(function() { <add> <add> var _after = 1; <add> var _before = 2; <add> var _around = 3; <add> var _intro = 4; <add> var _regexEnabled = true; <add> <add> /** <add> * Private weaving function. <add> */ <add> var weaveOne = function(source, method, advice) { <add> <add> var old = source[method]; <add> <add> var aspect; <add> if (advice.type == _after) <add> aspect = function() { <add> var returnValue = old.apply(this, arguments); <add> return advice.value.apply(this, [returnValue, method]); <add> }; <add> else if (advice.type == _before) <add> aspect = function() { <add> advice.value.apply(this, [arguments, method]); <add> return old.apply(this, arguments); <add> }; <add> else if (advice.type == _intro) <add> aspect = function() { <add> return advice.value.apply(this, arguments); <add> }; <add> else if (advice.type == _around) { <add> aspect = function() { <add> var invocation = { object: this, args: arguments }; <add> return advice.value.apply(invocation.object, [{ arguments: invocation.args, method: method, proceed : <add> function() { <add> return old.apply(invocation.object, invocation.args); <add> } <add> }] ); <add> }; <add> } <add> <add> aspect.unweave = function() { <add> source[method] = old; <add> pointcut = source = aspect = old = null; <add> }; <add> <add> source[method] = aspect; <add> <add> return aspect; <add> <add> }; <add> <add> <add> /** <add> * Private weaver and pointcut parser. <add> */ <add> var weave = function(pointcut, advice) <add> { <add> <add> var source = (typeof(pointcut.target.prototype) != 'undefined') ? pointcut.target.prototype : pointcut.target; <add> var advices = []; <add> <add> // If it's not an introduction and no method was found, try with regex... <add> if (advice.type != _intro && typeof(source[pointcut.method]) == 'undefined') <add> { <add> <add> for (var method in source) <add> { <add> if (source[method] != null && source[method] instanceof Function && method.match(pointcut.method)) <add> { <add> advices[advices.length] = weaveOne(source, method, advice); <add> } <add> } <add> <add> if (advices.length == 0) <add> throw 'No method: ' + pointcut.method; <add> <add> } <add> else <add> { <add> // Return as an array of one element <add> advices[0] = weaveOne(source, pointcut.method, advice); <add> } <add> <add> return _regexEnabled ? advices : advices[0]; <add> <add> }; <add> <add> window.$profiler = <add> { <add> /** <add> * Creates an advice after the defined point-cut. The advice will be executed after the point-cut method <add> * has completed execution successfully, and will receive one parameter with the result of the execution. <add> * This function returns an array of weaved aspects (Function). <add> * <add> * @example jQuery.aop.after( {target: window, method: 'MyGlobalMethod'}, function(result) { alert('Returned: ' + result); } ); <add> * @result Array<Function> <add> * <add> * @example jQuery.aop.after( {target: String, method: 'indexOf'}, function(index) { alert('Result found at: ' + index + ' on:' + this); } ); <add> * @result Array<Function> <add> * <add> * @name after <add> * @param Map pointcut Definition of the point-cut to apply the advice. A point-cut is the definition of the object/s and method/s to be weaved. <add> * @option Object target Target object to be weaved. <add> * @option String method Name of the function to be weaved. Regex are supported, but not on built-in objects. <add> * @param Function advice Function containing the code that will get called after the execution of the point-cut. It receives one parameter <add> * with the result of the point-cut's execution. <add> * <add> * @type Array<Function> <add> * @cat Plugins/General <add> */ <add> after : function(pointcut, advice) <add> { <add> return weave( pointcut, { type: _after, value: advice } ); <add> }, <add> <add> /** <add> * Creates an advice before the defined point-cut. The advice will be executed before the point-cut method <add> * but cannot modify the behavior of the method, or prevent its execution. <add> * This function returns an array of weaved aspects (Function). <add> * <add> * @example jQuery.aop.before( {target: window, method: 'MyGlobalMethod'}, function() { alert('About to execute MyGlobalMethod'); } ); <add> * @result Array<Function> <add> * <add> * @example jQuery.aop.before( {target: String, method: 'indexOf'}, function(index) { alert('About to execute String.indexOf on: ' + this); } ); <add> * @result Array<Function> <add> * <add> * @name before <add> * @param Map pointcut Definition of the point-cut to apply the advice. A point-cut is the definition of the object/s and method/s to be weaved. <add> * @option Object target Target object to be weaved. <add> * @option String method Name of the function to be weaved. Regex are supported, but not on built-in objects. <add> * @param Function advice Function containing the code that will get called before the execution of the point-cut. <add> * <add> * @type Array<Function> <add> * @cat Plugins/General <add> */ <add> before : function(pointcut, advice) <add> { <add> return weave( pointcut, { type: _before, value: advice } ); <add> }, <add> <add> <add> /** <add> * Creates an advice 'around' the defined point-cut. This type of advice can control the point-cut method execution by calling <add> * the functions '.proceed()' on the 'invocation' object, and also, can modify the arguments collection before sending them to the function call. <add> * This function returns an array of weaved aspects (Function). <add> * <add> * @example jQuery.aop.around( {target: window, method: 'MyGlobalMethod'}, function(invocation) { <add> * alert('# of Arguments: ' + invocation.arguments.length); <add> * return invocation.proceed(); <add> * } ); <add> * @result Array<Function> <add> * <add> * @example jQuery.aop.around( {target: String, method: 'indexOf'}, function(invocation) { <add> * alert('Searching: ' + invocation.arguments[0] + ' on: ' + this); <add> * return invocation.proceed(); <add> * } ); <add> * @result Array<Function> <add> * <add> * @example jQuery.aop.around( {target: window, method: /Get(\d+)/}, function(invocation) { <add> * alert('Executing ' + invocation.method); <add> * return invocation.proceed(); <add> * } ); <add> * @desc Matches all global methods starting with 'Get' and followed by a number. <add> * @result Array<Function> <add> * <add> * <add> * @name around <add> * @param Map pointcut Definition of the point-cut to apply the advice. A point-cut is the definition of the object/s and method/s to be weaved. <add> * @option Object target Target object to be weaved. <add> * @option String method Name of the function to be weaved. Regex are supported, but not on built-in objects. <add> * @param Function advice Function containing the code that will get called around the execution of the point-cut. This advice will be called with one <add> * argument containing one function '.proceed()', the collection of arguments '.arguments', and the matched method name '.method'. <add> * <add> * @type Array<Function> <add> * @cat Plugins/General <add> */ <add> around : function(pointcut, advice) <add> { <add> return weave( pointcut, { type: _around, value: advice } ); <add> }, <add> <add> /** <add> * Creates an introduction on the defined point-cut. This type of advice replaces any existing methods with the same <add> * name. To restore them, just unweave it. <add> * This function returns an array with only one weaved aspect (Function). <add> * <add> * @example jQuery.aop.introduction( {target: window, method: 'MyGlobalMethod'}, function(result) { alert('Returned: ' + result); } ); <add> * @result Array<Function> <add> * <add> * @example jQuery.aop.introduction( {target: String, method: 'log'}, function() { alert('Console: ' + this); } ); <add> * @result Array<Function> <add> * <add> * @name introduction <add> * @param Map pointcut Definition of the point-cut to apply the advice. A point-cut is the definition of the object/s and method/s to be weaved. <add> * @option Object target Target object to be weaved. <add> * @option String method Name of the function to be weaved. <add> * @param Function advice Function containing the code that will be executed on the point-cut. <add> * <add> * @type Array<Function> <add> * @cat Plugins/General <add> */ <add> introduction : function(pointcut, advice) <add> { <add> return weave( pointcut, { type: _intro, value: advice } ); <add> }, <add> <add> /** <add> * Configures global options. <add> * <add> * @name setup <add> * @param Map settings Configuration options. <add> * @option Boolean regexMatch Enables/disables regex matching of method names. <add> * <add> * @example jQuery.aop.setup( { regexMatch: false } ); <add> * @desc Disable regex matching. <add> * <add> * @type Void <add> * @cat Plugins/General <add> */ <add> setup: function(settings) <add> { <add> _regexEnabled = settings.regexMatch; <add> } <add> }; <add> <add>})(); <add> <add> <add>var $profile = window.$profile = {}; <add> <add> <add>var __profile__ = function(id, invocation){ <add> var start = new Date().getTime(); <add> var retval = invocation.proceed(); <add> var finish = new Date().getTime(); <add> $profile[id] = $profile[id] ? $profile[id] : {}; <add> $profile[id].callCount = $profile[id].callCount !== undefined ? <add> $profile[id].callCount+1 : 0; <add> $profile[id].times = $profile[id].times ? $profile[id].times : []; <add> $profile[id].times[$profile[id].callCount++] = (finish-start); <add> return retval; <add>}; <add> <add> <add>window.$profiler.stats = function(raw){ <add> var max = 0, <add> avg = -1, <add> min = 10000000, <add> own = 0; <add> for(var i = 0;i<raw.length;i++){ <add> if(raw[i] > 0){ <add> own += raw[i]; <add> }; <add> if(raw[i] > max){ <add> max = raw[i]; <add> } <add> if(raw[i] < min){ <add> min = raw[i]; <add> } <add> } <add> avg = Math.floor(own/raw.length); <add> return { <add> min: min, <add> max: max, <add> avg: avg, <add> own: own <add> }; <add>}; <add> <add>if(__env__.profile){ <add> /** <add> * CSS2Properties <add> */ <add> window.$profiler.around({ target: CSS2Properties, method:"getPropertyCSSValue"}, function(invocation) { <add> return __profile__("CSS2Properties.getPropertyCSSValue", invocation); <add> }); <add> window.$profiler.around({ target: CSS2Properties, method:"getPropertyPriority"}, function(invocation) { <add> return __profile__("CSS2Properties.getPropertyPriority", invocation); <add> }); <add> window.$profiler.around({ target: CSS2Properties, method:"getPropertyValue"}, function(invocation) { <add> return __profile__("CSS2Properties.getPropertyValue", invocation); <add> }); <add> window.$profiler.around({ target: CSS2Properties, method:"item"}, function(invocation) { <add> return __profile__("CSS2Properties.item", invocation); <add> }); <add> window.$profiler.around({ target: CSS2Properties, method:"removeProperty"}, function(invocation) { <add> return __profile__("CSS2Properties.removeProperty", invocation); <add> }); <add> window.$profiler.around({ target: CSS2Properties, method:"setProperty"}, function(invocation) { <add> return __profile__("CSS2Properties.setProperty", invocation); <add> }); <add> window.$profiler.around({ target: CSS2Properties, method:"toString"}, function(invocation) { <add> return __profile__("CSS2Properties.toString", invocation); <add> }); <add> <add> <add> /** <add> * DOMNode <add> */ <add> <add> window.$profiler.around({ target: DOMNode, method:"hasAttributes"}, function(invocation) { <add> return __profile__("DOMNode.hasAttributes", invocation); <add> }); <add> window.$profiler.around({ target: DOMNode, method:"insertBefore"}, function(invocation) { <add> return __profile__("DOMNode.insertBefore", invocation); <add> }); <add> window.$profiler.around({ target: DOMNode, method:"replaceChild"}, function(invocation) { <add> return __profile__("DOMNode.replaceChild", invocation); <add> }); <add> window.$profiler.around({ target: DOMNode, method:"removeChild"}, function(invocation) { <add> return __profile__("DOMNode.removeChild", invocation); <add> }); <add> window.$profiler.around({ target: DOMNode, method:"replaceChild"}, function(invocation) { <add> return __profile__("DOMNode.replaceChild", invocation); <add> }); <add> window.$profiler.around({ target: DOMNode, method:"appendChild"}, function(invocation) { <add> return __profile__("DOMNode.appendChild", invocation); <add> }); <add> window.$profiler.around({ target: DOMNode, method:"hasChildNodes"}, function(invocation) { <add> return __profile__("DOMNode.hasChildNodes", invocation); <add> }); <add> window.$profiler.around({ target: DOMNode, method:"cloneNode"}, function(invocation) { <add> return __profile__("DOMNode.cloneNode", invocation); <add> }); <add> window.$profiler.around({ target: DOMNode, method:"normalize"}, function(invocation) { <add> return __profile__("DOMNode.normalize", invocation); <add> }); <add> window.$profiler.around({ target: DOMNode, method:"isSupported"}, function(invocation) { <add> return __profile__("DOMNode.isSupported", invocation); <add> }); <add> window.$profiler.around({ target: DOMNode, method:"getElementsByTagName"}, function(invocation) { <add> return __profile__("DOMNode.getElementsByTagName", invocation); <add> }); <add> window.$profiler.around({ target: DOMNode, method:"getElementsByTagNameNS"}, function(invocation) { <add> return __profile__("DOMNode.getElementsByTagNameNS", invocation); <add> }); <add> window.$profiler.around({ target: DOMNode, method:"importNode"}, function(invocation) { <add> return __profile__("DOMNode.importNode", invocation); <add> }); <add> window.$profiler.around({ target: DOMNode, method:"contains"}, function(invocation) { <add> return __profile__("DOMNode.contains", invocation); <add> }); <add> window.$profiler.around({ target: DOMNode, method:"compareDocumentPosition"}, function(invocation) { <add> return __profile__("DOMNode.compareDocumentPosition", invocation); <add> }); <add> <add> <add> /** <add> * DOMDocument <add> */ <add> window.$profiler.around({ target: DOMDocument, method:"addEventListener"}, function(invocation) { <add> return __profile__("DOMDocument.addEventListener", invocation); <add> }); <add> window.$profiler.around({ target: DOMDocument, method:"removeEventListener"}, function(invocation) { <add> return __profile__("DOMDocument.removeEventListener", invocation); <add> }); <add> window.$profiler.around({ target: DOMDocument, method:"attachEvent"}, function(invocation) { <add> return __profile__("DOMDocument.attachEvent", invocation); <add> }); <add> window.$profiler.around({ target: DOMDocument, method:"detachEvent"}, function(invocation) { <add> return __profile__("DOMDocument.detachEvent", invocation); <add> }); <add> window.$profiler.around({ target: DOMDocument, method:"dispatchEvent"}, function(invocation) { <add> return __profile__("DOMDocument.dispatchEvent", invocation); <add> }); <add> window.$profiler.around({ target: DOMDocument, method:"loadXML"}, function(invocation) { <add> return __profile__("DOMDocument.loadXML", invocation); <add> }); <add> window.$profiler.around({ target: DOMDocument, method:"load"}, function(invocation) { <add> return __profile__("DOMDocument.load", invocation); <add> }); <add> window.$profiler.around({ target: DOMDocument, method:"createEvent"}, function(invocation) { <add> return __profile__("DOMDocument.createEvent", invocation); <add> }); <add> window.$profiler.around({ target: DOMDocument, method:"createExpression"}, function(invocation) { <add> return __profile__("DOMDocument.createExpression", invocation); <add> }); <add> window.$profiler.around({ target: DOMDocument, method:"createElement"}, function(invocation) { <add> return __profile__("DOMDocument.createElement", invocation); <add> }); <add> window.$profiler.around({ target: DOMDocument, method:"createDocumentFragment"}, function(invocation) { <add> return __profile__("DOMDocument.createDocumentFragment", invocation); <add> }); <add> window.$profiler.around({ target: DOMDocument, method:"createTextNode"}, function(invocation) { <add> return __profile__("DOMDocument.createTextNode", invocation); <add> }); <add> window.$profiler.around({ target: DOMDocument, method:"createComment"}, function(invocation) { <add> return __profile__("DOMDocument.createComment", invocation); <add> }); <add> window.$profiler.around({ target: DOMDocument, method:"createCDATASection"}, function(invocation) { <add> return __profile__("DOMDocument.createCDATASection", invocation); <add> }); <add> window.$profiler.around({ target: DOMDocument, method:"createProcessingInstruction"}, function(invocation) { <add> return __profile__("DOMDocument.createProcessingInstruction", invocation); <add> }); <add> window.$profiler.around({ target: DOMDocument, method:"createAttribute"}, function(invocation) { <add> return __profile__("DOMDocument.createAttribute", invocation); <add> }); <add> window.$profiler.around({ target: DOMDocument, method:"createElementNS"}, function(invocation) { <add> return __profile__("DOMDocument.createElementNS", invocation); <add> }); <add> window.$profiler.around({ target: DOMDocument, method:"createAttributeNS"}, function(invocation) { <add> return __profile__("DOMDocument.createAttributeNS", invocation); <add> }); <add> window.$profiler.around({ target: DOMDocument, method:"createNamespace"}, function(invocation) { <add> return __profile__("DOMDocument.createNamespace", invocation); <add> }); <add> window.$profiler.around({ target: DOMDocument, method:"getElementById"}, function(invocation) { <add> return __profile__("DOMDocument.getElementById", invocation); <add> }); <add> window.$profiler.around({ target: DOMDocument, method:"normalizeDocument"}, function(invocation) { <add> return __profile__("DOMDocument.normalizeDocument", invocation); <add> }); <add> <add> <add> /** <add> * HTMLDocument <add> */ <add> window.$profiler.around({ target: HTMLDocument, method:"createElement"}, function(invocation) { <add> return __profile__("HTMLDocument.createElement", invocation); <add> }); <add> <add> /** <add> * DOMParser <add> */ <add> window.$profiler.around({ target: DOMParser, method:"parseFromString"}, function(invocation) { <add> return __profile__("DOMParser.parseFromString", invocation); <add> }); <add> <add> /** <add> * DOMNodeList <add> */ <add> window.$profiler.around({ target: DOMNodeList, method:"item"}, function(invocation) { <add> return __profile__("DOMNode.item", invocation); <add> }); <add> window.$profiler.around({ target: DOMNodeList, method:"toString"}, function(invocation) { <add> return __profile__("DOMNode.toString", invocation); <add> }); <add> <add> /** <add> * XMLP <add> */ <add> window.$profiler.around({ target: XMLP, method:"_addAttribute"}, function(invocation) { <add> return __profile__("XMLP._addAttribute", invocation); <add> }); <add> window.$profiler.around({ target: XMLP, method:"_checkStructure"}, function(invocation) { <add> return __profile__("XMLP._checkStructure", invocation); <add> }); <add> window.$profiler.around({ target: XMLP, method:"_clearAttributes"}, function(invocation) { <add> return __profile__("XMLP._clearAttributes", invocation); <add> }); <add> window.$profiler.around({ target: XMLP, method:"_findAttributeIndex"}, function(invocation) { <add> return __profile__("XMLP._findAttributeIndex", invocation); <add> }); <add> window.$profiler.around({ target: XMLP, method:"getAttributeCount"}, function(invocation) { <add> return __profile__("XMLP.getAttributeCount", invocation); <add> }); <add> window.$profiler.around({ target: XMLP, method:"getAttributeName"}, function(invocation) { <add> return __profile__("XMLP.getAttributeName", invocation); <add> }); <add> window.$profiler.around({ target: XMLP, method:"getAttributeValue"}, function(invocation) { <add> return __profile__("XMLP.getAttributeValue", invocation); <add> }); <add> window.$profiler.around({ target: XMLP, method:"getAttributeValueByName"}, function(invocation) { <add> return __profile__("XMLP.getAttributeValueByName", invocation); <add> }); <add> window.$profiler.around({ target: XMLP, method:"getColumnNumber"}, function(invocation) { <add> return __profile__("XMLP.getColumnNumber", invocation); <add> }); <add> window.$profiler.around({ target: XMLP, method:"getContentBegin"}, function(invocation) { <add> return __profile__("XMLP.getContentBegin", invocation); <add> }); <add> window.$profiler.around({ target: XMLP, method:"getContentEnd"}, function(invocation) { <add> return __profile__("XMLP.getContentEnd", invocation); <add> }); <add> window.$profiler.around({ target: XMLP, method:"getLineNumber"}, function(invocation) { <add> return __profile__("XMLP.getLineNumber", invocation); <add> }); <add> window.$profiler.around({ target: XMLP, method:"getName"}, function(invocation) { <add> return __profile__("XMLP.getName", invocation); <add> }); <add> window.$profiler.around({ target: XMLP, method:"next"}, function(invocation) { <add> return __profile__("XMLP.next", invocation); <add> }); <add> window.$profiler.around({ target: XMLP, method:"_parse"}, function(invocation) { <add> return __profile__("XMLP._parse", invocation); <add> }); <add> window.$profiler.around({ target: XMLP, method:"_parse"}, function(invocation) { <add> return __profile__("XMLP._parse", invocation); <add> }); <add> window.$profiler.around({ target: XMLP, method:"_parseAttribute"}, function(invocation) { <add> return __profile__("XMLP._parseAttribute", invocation); <add> }); <add> window.$profiler.around({ target: XMLP, method:"_parseCDATA"}, function(invocation) { <add> return __profile__("XMLP._parseCDATA", invocation); <add> }); <add> window.$profiler.around({ target: XMLP, method:"_parseComment"}, function(invocation) { <add> return __profile__("XMLP._parseComment", invocation); <add> }); <add> window.$profiler.around({ target: XMLP, method:"_parseDTD"}, function(invocation) { <add> return __profile__("XMLP._parseDTD", invocation); <add> }); <add> window.$profiler.around({ target: XMLP, method:"_parseElement"}, function(invocation) { <add> return __profile__("XMLP._parseElement", invocation); <add> }); <add> window.$profiler.around({ target: XMLP, method:"_parseEntity"}, function(invocation) { <add> return __profile__("XMLP._parseEntity", invocation); <add> }); <add> window.$profiler.around({ target: XMLP, method:"_parsePI"}, function(invocation) { <add> return __profile__("XMLP._parsePI", invocation); <add> }); <add> window.$profiler.around({ target: XMLP, method:"_parseText"}, function(invocation) { <add> return __profile__("XMLP._parseText", invocation); <add> }); <add> window.$profiler.around({ target: XMLP, method:"_replaceEntities"}, function(invocation) { <add> return __profile__("XMLP._replaceEntities", invocation); <add> }); <add> window.$profiler.around({ target: XMLP, method:"_replaceEntity"}, function(invocation) { <add> return __profile__("XMLP._replaceEntity", invocation); <add> }); <add> window.$profiler.around({ target: XMLP, method:"_setContent"}, function(invocation) { <add> return __profile__("XMLP._setContent", invocation); <add> }); <add> window.$profiler.around({ target: XMLP, method:"_setErr"}, function(invocation) { <add> return __profile__("XMLP._setErr", invocation); <add> }); <add> <add> <add> /** <add> * SAXDriver <add> */ <add> window.$profiler.around({ target: SAXDriver, method:"parse"}, function(invocation) { <add> return __profile__("SAXDriver.parse", invocation); <add> }); <add> window.$profiler.around({ target: SAXDriver, method:"setDocumentHandler"}, function(invocation) { <add> return __profile__("SAXDriver.setDocumentHandler", invocation); <add> }); <add> window.$profiler.around({ target: SAXDriver, method:"setErrorHandler"}, function(invocation) { <add> return __profile__("SAXDriver.setErrorHandler", invocation); <add> }); <add> window.$profiler.around({ target: SAXDriver, method:"setLexicalHandler"}, function(invocation) { <add> return __profile__("SAXDriver.setLexicalHandler", invocation); <add> }); <add> window.$profiler.around({ target: SAXDriver, method:"getColumnNumber"}, function(invocation) { <add> return __profile__("SAXDriver.getColumnNumber", invocation); <add> }); <add> window.$profiler.around({ target: SAXDriver, method:"getLineNumber"}, function(invocation) { <add> return __profile__("SAXDriver.getLineNumber", invocation); <add> }); <add> window.$profiler.around({ target: SAXDriver, method:"getMessage"}, function(invocation) { <add> return __profile__("SAXDriver.getMessage", invocation); <add> }); <add> window.$profiler.around({ target: SAXDriver, method:"getPublicId"}, function(invocation) { <add> return __profile__("SAXDriver.getPublicId", invocation); <add> }); <add> window.$profiler.around({ target: SAXDriver, method:"getSystemId"}, function(invocation) { <add> return __profile__("SAXDriver.getSystemId", invocation); <add> }); <add> window.$profiler.around({ target: SAXDriver, method:"getLength"}, function(invocation) { <add> return __profile__("SAXDriver.getLength", invocation); <add> }); <add> window.$profiler.around({ target: SAXDriver, method:"getName"}, function(invocation) { <add> return __profile__("SAXDriver.getName", invocation); <add> }); <add> window.$profiler.around({ target: SAXDriver, method:"getValue"}, function(invocation) { <add> return __profile__("SAXDriver.getValue", invocation); <add> }); <add> window.$profiler.around({ target: SAXDriver, method:"getValueByName"}, function(invocation) { <add> return __profile__("SAXDriver.getValueByName", invocation); <add> }); <add> window.$profiler.around({ target: SAXDriver, method:"_fireError"}, function(invocation) { <add> return __profile__("SAXDriver._fireError", invocation); <add> }); <add> window.$profiler.around({ target: SAXDriver, method:"_fireEvent"}, function(invocation) { <add> return __profile__("SAXDriver._fireEvent", invocation); <add> }); <add> window.$profiler.around({ target: SAXDriver, method:"_parseLoop"}, function(invocation) { <add> return __profile__("SAXDriver._parseLoop", invocation); <add> }); <add> <add> /** <add> * SAXStrings <add> */ <add> window.$profiler.around({ target: SAXStrings, method:"getColumnNumber"}, function(invocation) { <add> return __profile__("SAXStrings.getColumnNumber", invocation); <add> }); <add> window.$profiler.around({ target: SAXStrings, method:"getLineNumber"}, function(invocation) { <add> return __profile__("SAXStrings.getLineNumber", invocation); <add> }); <add> window.$profiler.around({ target: SAXStrings, method:"indexOfNonWhitespace"}, function(invocation) { <add> return __profile__("SAXStrings.indexOfNonWhitespace", invocation); <add> }); <add> window.$profiler.around({ target: SAXStrings, method:"indexOfWhitespace"}, function(invocation) { <add> return __profile__("SAXStrings.indexOfWhitespace", invocation); <add> }); <add> window.$profiler.around({ target: SAXStrings, method:"isEmpty"}, function(invocation) { <add> return __profile__("SAXStrings.isEmpty", invocation); <add> }); <add> window.$profiler.around({ target: SAXStrings, method:"lastIndexOfNonWhitespace"}, function(invocation) { <add> return __profile__("SAXStrings.lastIndexOfNonWhitespace", invocation); <add> }); <add> window.$profiler.around({ target: SAXStrings, method:"replace"}, function(invocation) { <add> return __profile__("SAXStrings.replace", invocation); <add> }); <add> <add> /** <add> * Stack - SAX Utility <add> window.$profiler.around({ target: Stack, method:"clear"}, function(invocation) { <add> return __profile__("Stack.clear", invocation); <add> }); <add> window.$profiler.around({ target: Stack, method:"count"}, function(invocation) { <add> return __profile__("Stack.count", invocation); <add> }); <add> window.$profiler.around({ target: Stack, method:"destroy"}, function(invocation) { <add> return __profile__("Stack.destroy", invocation); <add> }); <add> window.$profiler.around({ target: Stack, method:"peek"}, function(invocation) { <add> return __profile__("Stack.peek", invocation); <add> }); <add> window.$profiler.around({ target: Stack, method:"pop"}, function(invocation) { <add> return __profile__("Stack.pop", invocation); <add> }); <add> window.$profiler.around({ target: Stack, method:"push"}, function(invocation) { <add> return __profile__("Stack.push", invocation); <add> }); <add> */ <add>} <add> <add>/* <ide> * document.js <ide> * <ide> * DOM Level 2 /DOM level 3 (partial) <ide> get URL(){ return $w.location.href; } <ide> }); <ide> <add> <ide> <ide> var $document = new HTMLDocument($implementation); <ide> $w.__defineGetter__("document", function(){ <ide> * outro.js <ide> */ <ide> <del>})(window, __env__); <add>})(window, __env__, __policy__); <ide> <ide> }catch(e){ <ide> __env__.error("ERROR LOADING ENV : " + e + "\nLINE SOURCE:\n" +__env__.lineSource(e));
Java
apache-2.0
c77ec6c5e48c89ae2b641aa58e50b207d3edeaf0
0
fusesource/jansi,fusesource/jansi,fusesource/jansi
/*-------------------------------------------------------------------------- * Copyright 2007 Taro L. Saito * * 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.fusesource.jansi.internal; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.Properties; import java.util.Random; /** * Set the system properties, org.jansi.lib.path, org.jansi.lib.name, * appropriately so that jansi can find *.dll, *.jnilib and * *.so files, according to the current OS (win, linux, mac). * <p/> * The library files are automatically extracted from this project's package * (JAR). * <p/> * usage: call {@link #initialize()} before using Jansi. */ public class JansiLoader { private static boolean extracted = false; private static String nativeLibraryPath; private static String nativeLibrarySourceUrl; /** * Loads Jansi native library. * * @return True if jansi native library is successfully loaded; false * otherwise. */ public static synchronized boolean initialize() { // only cleanup before the first extract if (!extracted) { cleanup(); } try { loadJansiNativeLibrary(); } catch (Exception e) { throw new RuntimeException("Unable to load jansi native library", e); } return extracted; } public static String getNativeLibraryPath() { return nativeLibraryPath; } public static String getNativeLibrarySourceUrl() { return nativeLibrarySourceUrl; } private static File getTempDir() { return new File(System.getProperty("jansi.tmpdir", System.getProperty("java.io.tmpdir"))); } /** * Deleted old native libraries e.g. on Windows the DLL file is not removed * on VM-Exit (bug #80) */ static void cleanup() { String tempFolder = getTempDir().getAbsolutePath(); File dir = new File(tempFolder); File[] nativeLibFiles = dir.listFiles(new FilenameFilter() { private final String searchPattern = "jansi-" + getVersion(); public boolean accept(File dir, String name) { return name.startsWith(searchPattern) && !name.endsWith(".lck"); } }); if (nativeLibFiles != null) { for (File nativeLibFile : nativeLibFiles) { File lckFile = new File(nativeLibFile.getAbsolutePath() + ".lck"); if (!lckFile.exists()) { try { nativeLibFile.delete(); } catch (SecurityException e) { System.err.println("Failed to delete old native lib" + e.getMessage()); } } } } } private static int readNBytes(InputStream in, byte[] b) throws IOException { int n = 0; int len = b.length; while (n < len) { int count = in.read(b, n, len - n); if (count <= 0) break; n += count; } return n; } private static String contentsEquals(InputStream in1, InputStream in2) throws IOException { byte[] buffer1 = new byte[8192]; byte[] buffer2 = new byte[8192]; int numRead1; int numRead2; while (true) { numRead1 = readNBytes(in1, buffer1); numRead2 = readNBytes(in2, buffer2); if (numRead1 > 0) { if (numRead2 <= 0) { return "EOF on second stream but not first"; } if (numRead2 != numRead1) { return "Read size different (" + numRead1 + " vs " + numRead2 + ")"; } // Otherwise same number of bytes read if (!Arrays.equals(buffer1, buffer2)) { return "Content differs"; } // Otherwise same bytes read, so continue ... } else { // Nothing more in stream 1 ... if (numRead2 > 0) { return "EOF on first stream but not second"; } else { return null; } } } } /** * Extracts and loads the specified library file to the target folder * * @param libFolderForCurrentOS Library path. * @param libraryFileName Library name. * @param targetFolder Target folder. * @return */ private static boolean extractAndLoadLibraryFile(String libFolderForCurrentOS, String libraryFileName, String targetFolder) { String nativeLibraryFilePath = libFolderForCurrentOS + "/" + libraryFileName; // Include architecture name in temporary filename in order to avoid conflicts // when multiple JVMs with different architectures running at the same time String uuid = randomUUID(); String extractedLibFileName = String.format("jansi-%s-%s-%s", getVersion(), uuid, libraryFileName); String extractedLckFileName = extractedLibFileName + ".lck"; File extractedLibFile = new File(targetFolder, extractedLibFileName); File extractedLckFile = new File(targetFolder, extractedLckFileName); try { // Extract a native library file into the target directory InputStream in = JansiLoader.class.getResourceAsStream(nativeLibraryFilePath); try { if (!extractedLckFile.exists()) { new FileOutputStream(extractedLckFile).close(); } OutputStream out = new FileOutputStream(extractedLibFile); try { copy(in, out); } finally { out.close(); } } finally { // Delete the extracted lib file on JVM exit. extractedLibFile.deleteOnExit(); extractedLckFile.deleteOnExit(); in.close(); } // Set executable (x) flag to enable Java to load the native library extractedLibFile.setReadable(true); extractedLibFile.setWritable(true, true); extractedLibFile.setExecutable(true); // Check whether the contents are properly copied from the resource folder InputStream nativeIn = JansiLoader.class.getResourceAsStream(nativeLibraryFilePath); try { InputStream extractedLibIn = new FileInputStream(extractedLibFile); try { String eq = contentsEquals(nativeIn, extractedLibIn); if (eq != null) { throw new RuntimeException(String.format("Failed to write a native library file at %s because %s", extractedLibFile, eq)); } } finally { extractedLibIn.close(); } } finally { nativeIn.close(); } // Load library if (loadNativeLibrary(extractedLibFile)) { nativeLibrarySourceUrl = JansiLoader.class.getResource(nativeLibraryFilePath).toExternalForm(); return true; } } catch (IOException e) { System.err.println(e.getMessage()); } return false; } private static String randomUUID() { return Long.toHexString(new Random().nextLong()); } private static void copy(InputStream in, OutputStream out) throws IOException { byte[] buf = new byte[8192]; int n; while ((n = in.read(buf)) > 0) { out.write(buf, 0, n); } } /** * Loads native library using the given path and name of the library. * * @param libPath Path of the native library. * @return True for successfully loading; false otherwise. */ private static boolean loadNativeLibrary(File libPath) { if (libPath.exists()) { try { String path = libPath.getAbsolutePath(); System.load(path); nativeLibraryPath = path; return true; } catch (UnsatisfiedLinkError e) { System.err.println("Failed to load native library:" + libPath.getName() + ". osinfo: " + OSInfo.getNativeLibFolderPathForCurrentOS()); System.err.println(e); return false; } } else { return false; } } /** * Loads jansi library using given path and name of the library. * * @throws */ private static void loadJansiNativeLibrary() throws Exception { if (extracted) { return; } List<String> triedPaths = new LinkedList<String>(); // Try loading library from library.jansi.path library path */ String jansiNativeLibraryPath = System.getProperty("library.jansi.path"); String jansiNativeLibraryName = System.getProperty("library.jansi.name"); if (jansiNativeLibraryName == null) { jansiNativeLibraryName = System.mapLibraryName("jansi"); if (jansiNativeLibraryName != null && jansiNativeLibraryName.endsWith(".dylib")) { jansiNativeLibraryName = jansiNativeLibraryName.replace(".dylib", ".jnilib"); } } if (jansiNativeLibraryPath != null) { String withOs = jansiNativeLibraryPath + "/" + OSInfo.getNativeLibFolderPathForCurrentOS(); if (loadNativeLibrary(new File(withOs, jansiNativeLibraryName))) { extracted = true; return; } else { triedPaths.add(withOs); } if (loadNativeLibrary(new File(jansiNativeLibraryPath, jansiNativeLibraryName))) { extracted = true; return; } else { triedPaths.add(jansiNativeLibraryPath); } } // Load the os-dependent library from the jar file String packagePath = JansiLoader.class.getPackage().getName().replace('.', '/'); jansiNativeLibraryPath = String.format("/%s/native/%s", packagePath, OSInfo.getNativeLibFolderPathForCurrentOS()); boolean hasNativeLib = hasResource(jansiNativeLibraryPath + "/" + jansiNativeLibraryName); if (hasNativeLib) { // temporary library folder String tempFolder = getTempDir().getAbsolutePath(); // Try extracting the library from jar if (extractAndLoadLibraryFile(jansiNativeLibraryPath, jansiNativeLibraryName, tempFolder)) { extracted = true; return; } else { triedPaths.add(jansiNativeLibraryPath); } } // As a last resort try from java.library.path String javaLibraryPath = System.getProperty("java.library.path", ""); for (String ldPath : javaLibraryPath.split(File.pathSeparator)) { if (ldPath.isEmpty()) { continue; } if (loadNativeLibrary(new File(ldPath, jansiNativeLibraryName))) { extracted = true; return; } else { triedPaths.add(ldPath); } } extracted = false; throw new Exception(String.format("No native library found for os.name=%s, os.arch=%s, paths=[%s]", OSInfo.getOSName(), OSInfo.getArchName(), join(triedPaths, File.pathSeparator))); } private static boolean hasResource(String path) { return JansiLoader.class.getResource(path) != null; } /** * @return The major version of the jansi library. */ public static int getMajorVersion() { String[] c = getVersion().split("\\."); return (c.length > 0) ? Integer.parseInt(c[0]) : 1; } /** * @return The minor version of the jansi library. */ public static int getMinorVersion() { String[] c = getVersion().split("\\."); return (c.length > 1) ? Integer.parseInt(c[1]) : 0; } /** * @return The version of the jansi library. */ public static String getVersion() { URL versionFile = JansiLoader.class.getResource("/META-INF/maven/org.fusesource.jansi/jansi/pom.properties"); String version = "unknown"; try { if (versionFile != null) { Properties versionData = new Properties(); versionData.load(versionFile.openStream()); version = versionData.getProperty("version", version); version = version.trim().replaceAll("[^0-9\\.]", ""); } } catch (IOException e) { System.err.println(e); } return version; } private static String join(List<String> list, String separator) { StringBuilder sb = new StringBuilder(); boolean first = true; for (String item : list) { if (first) first = false; else sb.append(separator); sb.append(item); } return sb.toString(); } }
src/main/java/org/fusesource/jansi/internal/JansiLoader.java
/*-------------------------------------------------------------------------- * Copyright 2007 Taro L. Saito * * 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.fusesource.jansi.internal; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.Properties; import java.util.UUID; /** * Set the system properties, org.jansi.lib.path, org.jansi.lib.name, * appropriately so that jansi can find *.dll, *.jnilib and * *.so files, according to the current OS (win, linux, mac). * <p/> * The library files are automatically extracted from this project's package * (JAR). * <p/> * usage: call {@link #initialize()} before using Jansi. */ public class JansiLoader { private static boolean extracted = false; private static String nativeLibraryPath; private static String nativeLibrarySourceUrl; /** * Loads Jansi native library. * * @return True if jansi native library is successfully loaded; false * otherwise. */ public static synchronized boolean initialize() { // only cleanup before the first extract if (!extracted) { cleanup(); } try { loadJansiNativeLibrary(); } catch (Exception e) { throw new RuntimeException("Unable to load jansi native library", e); } return extracted; } public static String getNativeLibraryPath() { return nativeLibraryPath; } public static String getNativeLibrarySourceUrl() { return nativeLibrarySourceUrl; } private static File getTempDir() { return new File(System.getProperty("jansi.tmpdir", System.getProperty("java.io.tmpdir"))); } /** * Deleted old native libraries e.g. on Windows the DLL file is not removed * on VM-Exit (bug #80) */ static void cleanup() { String tempFolder = getTempDir().getAbsolutePath(); File dir = new File(tempFolder); File[] nativeLibFiles = dir.listFiles(new FilenameFilter() { private final String searchPattern = "jansi-" + getVersion(); public boolean accept(File dir, String name) { return name.startsWith(searchPattern) && !name.endsWith(".lck"); } }); if (nativeLibFiles != null) { for (File nativeLibFile : nativeLibFiles) { File lckFile = new File(nativeLibFile.getAbsolutePath() + ".lck"); if (!lckFile.exists()) { try { nativeLibFile.delete(); } catch (SecurityException e) { System.err.println("Failed to delete old native lib" + e.getMessage()); } } } } } private static int readNBytes(InputStream in, byte[] b) throws IOException { int n = 0; int len = b.length; while (n < len) { int count = in.read(b, n, len - n); if (count <= 0) break; n += count; } return n; } private static String contentsEquals(InputStream in1, InputStream in2) throws IOException { byte[] buffer1 = new byte[8192]; byte[] buffer2 = new byte[8192]; int numRead1; int numRead2; while (true) { numRead1 = readNBytes(in1, buffer1); numRead2 = readNBytes(in2, buffer2); if (numRead1 > 0) { if (numRead2 <= 0) { return "EOF on second stream but not first"; } if (numRead2 != numRead1) { return "Read size different (" + numRead1 + " vs " + numRead2 + ")"; } // Otherwise same number of bytes read if (!Arrays.equals(buffer1, buffer2)) { return "Content differs"; } // Otherwise same bytes read, so continue ... } else { // Nothing more in stream 1 ... if (numRead2 > 0) { return "EOF on first stream but not second"; } else { return null; } } } } /** * Extracts and loads the specified library file to the target folder * * @param libFolderForCurrentOS Library path. * @param libraryFileName Library name. * @param targetFolder Target folder. * @return */ private static boolean extractAndLoadLibraryFile(String libFolderForCurrentOS, String libraryFileName, String targetFolder) { String nativeLibraryFilePath = libFolderForCurrentOS + "/" + libraryFileName; // Include architecture name in temporary filename in order to avoid conflicts // when multiple JVMs with different architectures running at the same time String uuid = UUID.randomUUID().toString(); String extractedLibFileName = String.format("jansi-%s-%s-%s", getVersion(), uuid, libraryFileName); String extractedLckFileName = extractedLibFileName + ".lck"; File extractedLibFile = new File(targetFolder, extractedLibFileName); File extractedLckFile = new File(targetFolder, extractedLckFileName); try { // Extract a native library file into the target directory InputStream in = JansiLoader.class.getResourceAsStream(nativeLibraryFilePath); try { if (!extractedLckFile.exists()) { new FileOutputStream(extractedLckFile).close(); } OutputStream out = new FileOutputStream(extractedLibFile); try { copy(in, out); } finally { out.close(); } } finally { // Delete the extracted lib file on JVM exit. extractedLibFile.deleteOnExit(); extractedLckFile.deleteOnExit(); in.close(); } // Set executable (x) flag to enable Java to load the native library extractedLibFile.setReadable(true); extractedLibFile.setWritable(true, true); extractedLibFile.setExecutable(true); // Check whether the contents are properly copied from the resource folder InputStream nativeIn = JansiLoader.class.getResourceAsStream(nativeLibraryFilePath); try { InputStream extractedLibIn = new FileInputStream(extractedLibFile); try { String eq = contentsEquals(nativeIn, extractedLibIn); if (eq != null) { throw new RuntimeException(String.format("Failed to write a native library file at %s because %s", extractedLibFile, eq)); } } finally { extractedLibIn.close(); } } finally { nativeIn.close(); } // Load library if (loadNativeLibrary(extractedLibFile)) { nativeLibrarySourceUrl = JansiLoader.class.getResource(nativeLibraryFilePath).toExternalForm(); return true; } } catch (IOException e) { System.err.println(e.getMessage()); } return false; } private static void copy(InputStream in, OutputStream out) throws IOException { byte[] buf = new byte[8192]; int n; while ((n = in.read(buf)) > 0) { out.write(buf, 0, n); } } /** * Loads native library using the given path and name of the library. * * @param libPath Path of the native library. * @return True for successfully loading; false otherwise. */ private static boolean loadNativeLibrary(File libPath) { if (libPath.exists()) { try { String path = libPath.getAbsolutePath(); System.load(path); nativeLibraryPath = path; return true; } catch (UnsatisfiedLinkError e) { System.err.println("Failed to load native library:" + libPath.getName() + ". osinfo: " + OSInfo.getNativeLibFolderPathForCurrentOS()); System.err.println(e); return false; } } else { return false; } } /** * Loads jansi library using given path and name of the library. * * @throws */ private static void loadJansiNativeLibrary() throws Exception { if (extracted) { return; } List<String> triedPaths = new LinkedList<String>(); // Try loading library from library.jansi.path library path */ String jansiNativeLibraryPath = System.getProperty("library.jansi.path"); String jansiNativeLibraryName = System.getProperty("library.jansi.name"); if (jansiNativeLibraryName == null) { jansiNativeLibraryName = System.mapLibraryName("jansi"); if (jansiNativeLibraryName != null && jansiNativeLibraryName.endsWith(".dylib")) { jansiNativeLibraryName = jansiNativeLibraryName.replace(".dylib", ".jnilib"); } } if (jansiNativeLibraryPath != null) { String withOs = jansiNativeLibraryPath + "/" + OSInfo.getNativeLibFolderPathForCurrentOS(); if (loadNativeLibrary(new File(withOs, jansiNativeLibraryName))) { extracted = true; return; } else { triedPaths.add(withOs); } if (loadNativeLibrary(new File(jansiNativeLibraryPath, jansiNativeLibraryName))) { extracted = true; return; } else { triedPaths.add(jansiNativeLibraryPath); } } // Load the os-dependent library from the jar file String packagePath = JansiLoader.class.getPackage().getName().replace('.', '/'); jansiNativeLibraryPath = String.format("/%s/native/%s", packagePath, OSInfo.getNativeLibFolderPathForCurrentOS()); boolean hasNativeLib = hasResource(jansiNativeLibraryPath + "/" + jansiNativeLibraryName); if (hasNativeLib) { // temporary library folder String tempFolder = getTempDir().getAbsolutePath(); // Try extracting the library from jar if (extractAndLoadLibraryFile(jansiNativeLibraryPath, jansiNativeLibraryName, tempFolder)) { extracted = true; return; } else { triedPaths.add(jansiNativeLibraryPath); } } // As a last resort try from java.library.path String javaLibraryPath = System.getProperty("java.library.path", ""); for (String ldPath : javaLibraryPath.split(File.pathSeparator)) { if (ldPath.isEmpty()) { continue; } if (loadNativeLibrary(new File(ldPath, jansiNativeLibraryName))) { extracted = true; return; } else { triedPaths.add(ldPath); } } extracted = false; throw new Exception(String.format("No native library found for os.name=%s, os.arch=%s, paths=[%s]", OSInfo.getOSName(), OSInfo.getArchName(), join(triedPaths, File.pathSeparator))); } private static boolean hasResource(String path) { return JansiLoader.class.getResource(path) != null; } /** * @return The major version of the jansi library. */ public static int getMajorVersion() { String[] c = getVersion().split("\\."); return (c.length > 0) ? Integer.parseInt(c[0]) : 1; } /** * @return The minor version of the jansi library. */ public static int getMinorVersion() { String[] c = getVersion().split("\\."); return (c.length > 1) ? Integer.parseInt(c[1]) : 0; } /** * @return The version of the jansi library. */ public static String getVersion() { URL versionFile = JansiLoader.class.getResource("/META-INF/maven/org.fusesource.jansi/jansi/pom.properties"); String version = "unknown"; try { if (versionFile != null) { Properties versionData = new Properties(); versionData.load(versionFile.openStream()); version = versionData.getProperty("version", version); version = version.trim().replaceAll("[^0-9\\.]", ""); } } catch (IOException e) { System.err.println(e); } return version; } private static String join(List<String> list, String separator) { StringBuilder sb = new StringBuilder(); boolean first = true; for (String item : list) { if (first) first = false; else sb.append(separator); sb.append(item); } return sb.toString(); } }
Just use a plain random to avoid a dependency on SecureRandom
src/main/java/org/fusesource/jansi/internal/JansiLoader.java
Just use a plain random to avoid a dependency on SecureRandom
<ide><path>rc/main/java/org/fusesource/jansi/internal/JansiLoader.java <ide> *--------------------------------------------------------------------------*/ <ide> package org.fusesource.jansi.internal; <ide> <del>import java.io.BufferedOutputStream; <ide> import java.io.File; <ide> import java.io.FileInputStream; <ide> import java.io.FileOutputStream; <ide> import java.util.LinkedList; <ide> import java.util.List; <ide> import java.util.Properties; <del>import java.util.UUID; <add>import java.util.Random; <ide> <ide> /** <ide> * Set the system properties, org.jansi.lib.path, org.jansi.lib.name, <ide> String nativeLibraryFilePath = libFolderForCurrentOS + "/" + libraryFileName; <ide> // Include architecture name in temporary filename in order to avoid conflicts <ide> // when multiple JVMs with different architectures running at the same time <del> String uuid = UUID.randomUUID().toString(); <add> String uuid = randomUUID(); <ide> String extractedLibFileName = String.format("jansi-%s-%s-%s", getVersion(), uuid, libraryFileName); <ide> String extractedLckFileName = extractedLibFileName + ".lck"; <ide> <ide> return false; <ide> } <ide> <add> private static String randomUUID() { <add> return Long.toHexString(new Random().nextLong()); <add> } <add> <ide> private static void copy(InputStream in, OutputStream out) throws IOException { <ide> byte[] buf = new byte[8192]; <ide> int n;
Java
agpl-3.0
4d1b7189300e0be5b3694df8a980241b1fe7595f
0
m-sc/yamcs,dhosa/yamcs,dhosa/yamcs,bitblit11/yamcs,fqqb/yamcs,bitblit11/yamcs,bitblit11/yamcs,dhosa/yamcs,bitblit11/yamcs,m-sc/yamcs,m-sc/yamcs,fqqb/yamcs,m-sc/yamcs,yamcs/yamcs,yamcs/yamcs,dhosa/yamcs,m-sc/yamcs,dhosa/yamcs,fqqb/yamcs,m-sc/yamcs,yamcs/yamcs,fqqb/yamcs,yamcs/yamcs,fqqb/yamcs,bitblit11/yamcs,yamcs/yamcs,yamcs/yamcs,fqqb/yamcs
package org.yamcs; import org.yamcs.api.AbstractEventProducer; import org.yamcs.archive.EventRecorder; import org.yamcs.protobuf.Yamcs.Event; import org.yamcs.time.TimeService; import org.yamcs.utils.TimeEncoding; import org.yamcs.yarch.Stream; import org.yamcs.yarch.Tuple; import org.yamcs.yarch.TupleDefinition; import org.yamcs.yarch.YarchDatabase; /** * Event producer used from inside Yamcs to report events. * It writes directly to the realtime_event stream * * * @author nm * */ public class StreamEventProducer extends AbstractEventProducer { final Stream realtimeEventStream; final TupleDefinition tdef; final TimeService timeService; public StreamEventProducer(String yamcsInstance) { realtimeEventStream = YarchDatabase.getInstance(yamcsInstance).getStream(EventRecorder.REALTIME_EVENT_STREAM_NAME); if(realtimeEventStream==null) throw new ConfigurationException("Cannot find a stream named "+EventRecorder.REALTIME_EVENT_STREAM_NAME); tdef=realtimeEventStream.getDefinition(); timeService = YamcsServer.getTimeService(yamcsInstance); } @Override public void sendEvent(Event event) { Tuple t=new Tuple(tdef, new Object[]{event.getGenerationTime(), event.getSource(), event.getSeqNumber(), event}); realtimeEventStream.emitTuple(t); } @Override public void close() { } @Override public long getMissionTime() { long t; if(timeService==null) { t = TimeEncoding.getWallclockTime(); } else { t= timeService.getMissionTime(); } return t; } }
yamcs-core/src/main/java/org/yamcs/StreamEventProducer.java
package org.yamcs; import org.hornetq.api.core.HornetQException; import org.yamcs.api.AbstractEventProducer; import org.yamcs.archive.EventRecorder; import org.yamcs.protobuf.Yamcs.Event; import org.yamcs.time.TimeService; import org.yamcs.utils.TimeEncoding; import org.yamcs.yarch.Stream; import org.yamcs.yarch.Tuple; import org.yamcs.yarch.TupleDefinition; import org.yamcs.yarch.YarchDatabase; /** * Event producer used from inside Yamcs to report events. * It writes directly to the realtime_event stream * * * @author nm * */ public class StreamEventProducer extends AbstractEventProducer { final Stream realtimeEventStream; final TupleDefinition tdef; final TimeService timeService; public StreamEventProducer(String yamcsInstance) { realtimeEventStream = YarchDatabase.getInstance(yamcsInstance).getStream(EventRecorder.REALTIME_EVENT_STREAM_NAME); if(realtimeEventStream==null) throw new ConfigurationException("Cannot find a stream named "+EventRecorder.REALTIME_EVENT_STREAM_NAME); tdef=realtimeEventStream.getDefinition(); timeService = YamcsServer.getTimeService(yamcsInstance); } @Override public void sendEvent(Event event) { Tuple t=new Tuple(tdef, new Object[]{event.getGenerationTime(), event.getSource(), event.getSeqNumber(), event}); realtimeEventStream.emitTuple(t); } @Override public void close() { } @Override public long getMissionTime() { long t; if(timeService==null) { t = TimeEncoding.getWallclockTime(); } else { t= timeService.getMissionTime(); } return t; } }
cleanup
yamcs-core/src/main/java/org/yamcs/StreamEventProducer.java
cleanup
<ide><path>amcs-core/src/main/java/org/yamcs/StreamEventProducer.java <ide> package org.yamcs; <ide> <del>import org.hornetq.api.core.HornetQException; <ide> import org.yamcs.api.AbstractEventProducer; <ide> import org.yamcs.archive.EventRecorder; <ide> import org.yamcs.protobuf.Yamcs.Event;
Java
mit
34060b1357a867eeb990e77195dba0330dfb1ab9
0
ruuvi/Android_RuuvitagScanner,ruuvi/Android_RuuvitagScanner,io53/Android_RuuvitagScanner,io53/Android_RuuvitagScanner
package com.ruuvi.tag.feature.main; import android.Manifest; import android.app.AlarmManager; import android.app.Fragment; import android.app.PendingIntent; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.PowerManager; import android.os.SystemClock; import android.preference.PreferenceManager; import android.provider.Settings; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutionException; import com.ruuvi.tag.R; import com.ruuvi.tag.model.RuuviTag; import com.ruuvi.tag.scanning.BackgroundScanner; import com.ruuvi.tag.util.DataUpdateListener; import com.ruuvi.tag.scanning.RuuviTagListener; import com.ruuvi.tag.scanning.RuuviTagScanner; import com.ruuvi.tag.util.Utils; public class MainActivity extends AppCompatActivity implements RuuviTagListener { private static final String BATTERY_ASKED_PREF = "BATTERY_ASKED_PREF"; private DrawerLayout drawerLayout; private RuuviTagScanner scanner; public List<RuuviTag> myRuuviTags = new ArrayList<>(); public List<RuuviTag> otherRuuviTags = new ArrayList<>(); private DataUpdateListener fragmentWithCallback; private Handler handler; SharedPreferences settings; private Runnable updater = new Runnable() { @Override public void run() { if (fragmentWithCallback != null) fragmentWithCallback.dataUpdated(); handler.postDelayed(updater, 1000); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); drawerLayout = findViewById(R.id.main_drawerLayout); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); toolbar.setLogo(R.drawable.logo); handler = new Handler(); settings = PreferenceManager.getDefaultSharedPreferences(this); myRuuviTags = RuuviTag.getAll(); scanner = new RuuviTagScanner(this, getApplicationContext()); ActionBarDrawerToggle drawerToggle = new ActionBarDrawerToggle( this, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close ); drawerLayout.addDrawerListener(drawerToggle); if (getSupportActionBar() != null) { getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setHomeButtonEnabled(true); } drawerToggle.syncState(); ListView drawerListView = findViewById(R.id.navigationDrawer_listView); drawerListView.setAdapter( new ArrayAdapter<>( this, android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.navigation_items) ) ); drawerListView.setOnItemClickListener(drawerItemClicked); setBackgroundScanning(false); openFragment(1); } AdapterView.OnItemClickListener drawerItemClicked = new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { // TODO: 10/10/17 make this in a sane way openFragment(i); } }; private void setBackgroundScanning(boolean restartFlag) { PendingIntent pendingIntent = getPendingIntent(); boolean shouldRun = settings.getBoolean("pref_bgscan", false); boolean isRunning = pendingIntent != null; if (isRunning && (!shouldRun || restartFlag)) { AlarmManager am = (AlarmManager) getApplicationContext() .getSystemService(ALARM_SERVICE); am.cancel(pendingIntent); pendingIntent.cancel(); isRunning = false; } if (shouldRun && !isRunning) { int scanInterval = Integer.parseInt(settings.getString("pref_scaninterval", "300")) * 1000; if (scanInterval < 15 * 1000) scanInterval = 15 * 1000; boolean batterySaving = settings.getBoolean("pref_bgscan_battery_saving", false); Intent intent = new Intent(getApplicationContext(), BackgroundScanner.class); PendingIntent sender = PendingIntent.getBroadcast(getApplicationContext(), BackgroundScanner.REQUEST_CODE, intent, 0); AlarmManager am = (AlarmManager) getApplicationContext() .getSystemService(ALARM_SERVICE); if (batterySaving) { am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), scanInterval, sender); } else { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { checkAndAskForBatteryOptimization(); am.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + scanInterval, sender); } else { am.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + scanInterval, sender); } } } } private void checkAndAskForBatteryOptimization() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !hasShownBatteryOptimizationDialog()) { PowerManager powerManager = (PowerManager) getApplicationContext().getSystemService(POWER_SERVICE); String packageName = getPackageName(); // this below does not seems to work on my device if (!powerManager.isIgnoringBatteryOptimizations(packageName)) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(getString(R.string.battery_optimization_request)) .setPositiveButton(getString(R.string.yes), batteryDialogClick) .setNegativeButton(getString(R.string.no), batteryDialogClick) .show(); BatteryOptimizationDialogShown(); } } } DialogInterface.OnClickListener batteryDialogClick = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { switch (which) { case DialogInterface.BUTTON_POSITIVE: Intent intent = new Intent(); intent.setAction(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS); startActivity(intent); break; case DialogInterface.BUTTON_NEGATIVE: break; } } }; private PendingIntent getPendingIntent() { Intent intent = new Intent(getApplicationContext(), BackgroundScanner.class); return PendingIntent.getBroadcast(getApplicationContext(), BackgroundScanner.REQUEST_CODE, intent, PendingIntent.FLAG_NO_CREATE); } @Override protected void onStart() { //Intent intent = new Intent(MainActivity.this, ScannerService.class); //startService(intent); super.onStart(); } @Override protected void onResume() { super.onResume(); // Permission check for Marshmallow and newer int permissionCoarseLocation = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION); int permissionWriteExternal = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE); List<String> listPermissionsNeeded = new ArrayList<>(); if(permissionCoarseLocation != PackageManager.PERMISSION_GRANTED) { listPermissionsNeeded.add(Manifest.permission.ACCESS_COARSE_LOCATION); } if(permissionWriteExternal != PackageManager.PERMISSION_GRANTED) { listPermissionsNeeded.add(Manifest.permission.WRITE_EXTERNAL_STORAGE); } if(!listPermissionsNeeded.isEmpty()) { ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), 1); } else { settings.registerOnSharedPreferenceChangeListener(preferenceChangeListener); refrshTagLists(); scanner.start(); handler.post(updater); } } private void refrshTagLists() { myRuuviTags.clear(); myRuuviTags.addAll(RuuviTag.getAll()); otherRuuviTags.clear(); } @Override protected void onPause() { super.onPause(); settings.unregisterOnSharedPreferenceChangeListener(preferenceChangeListener); scanner.stop(); handler.removeCallbacks(updater); for (RuuviTag tag: myRuuviTags) { tag.update(); } } @Override protected void onStop() { super.onStop(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. //getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); return super.onOptionsItemSelected(item); } public void openFragment(int type) { Fragment fragment = null; switch (type) { case 1: refrshTagLists(); fragment = new DashboardFragment(); fragmentWithCallback = (DataUpdateListener)fragment; break; case 2: setTitle(getResources().getStringArray(R.array.navigation_items)[type]); fragment = new SettingsFragment(); fragmentWithCallback = null; break; case 3: setTitle(getResources().getStringArray(R.array.navigation_items)[type]); fragment = new AboutFragment(); fragmentWithCallback = null; break; default: setTitle(getResources().getStringArray(R.array.navigation_items)[type]); refrshTagLists(); fragment = new AddTagFragment(); fragmentWithCallback = (DataUpdateListener)fragment; type = 0; break; } getFragmentManager().beginTransaction() .replace(R.id.main_contentFrame, fragment) .commit(); if (type == 1 && getSupportActionBar() != null) { getSupportActionBar().setIcon(R.drawable.logo); } else if (getSupportActionBar() != null) { getSupportActionBar().setIcon(null); } setTitle(getResources().getStringArray(R.array.navigation_items_titles)[type]); drawerLayout.closeDrawers(); } @Override public void tagFound(RuuviTag tag) { for (RuuviTag myTag: myRuuviTags) { if (myTag.id.equals(tag.id)) { myTag.updateDataFrom(tag); if (fragmentWithCallback != null) { fragmentWithCallback.dataUpdated(); } return; } } for (RuuviTag myTag: otherRuuviTags) { if (myTag.id.equals(tag.id)) { myTag.updateDataFrom(tag); Utils.sortTagsByRssi(otherRuuviTags); if (fragmentWithCallback != null) { fragmentWithCallback.dataUpdated(); } return; } } otherRuuviTags.add(tag); } public void BatteryOptimizationDialogShown() { SharedPreferences.Editor editor = settings.edit(); editor.putBoolean(BATTERY_ASKED_PREF, true); editor.apply(); } public boolean hasShownBatteryOptimizationDialog() { return settings.getBoolean(BATTERY_ASKED_PREF, false); } public SharedPreferences.OnSharedPreferenceChangeListener preferenceChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener() { @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { setBackgroundScanning(true); } }; }
app/src/main/java/com/ruuvi/tag/feature/main/MainActivity.java
package com.ruuvi.tag.feature.main; import android.Manifest; import android.app.AlarmManager; import android.app.Fragment; import android.app.PendingIntent; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.PowerManager; import android.os.SystemClock; import android.preference.PreferenceManager; import android.provider.Settings; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutionException; import com.ruuvi.tag.R; import com.ruuvi.tag.model.RuuviTag; import com.ruuvi.tag.scanning.BackgroundScanner; import com.ruuvi.tag.util.DataUpdateListener; import com.ruuvi.tag.scanning.RuuviTagListener; import com.ruuvi.tag.scanning.RuuviTagScanner; import com.ruuvi.tag.util.Utils; public class MainActivity extends AppCompatActivity implements RuuviTagListener { private static final String BATTERY_ASKED_PREF = "BATTERY_ASKED_PREF"; private DrawerLayout drawerLayout; private RuuviTagScanner scanner; public List<RuuviTag> myRuuviTags = new ArrayList<>(); public List<RuuviTag> otherRuuviTags = new ArrayList<>(); private DataUpdateListener fragmentWithCallback; private Handler handler; SharedPreferences settings; private Runnable updater = new Runnable() { @Override public void run() { if (fragmentWithCallback != null) fragmentWithCallback.dataUpdated(); handler.postDelayed(updater, 1000); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); drawerLayout = findViewById(R.id.main_drawerLayout); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); toolbar.setLogo(R.drawable.logo); handler = new Handler(); settings = PreferenceManager.getDefaultSharedPreferences(this); myRuuviTags = RuuviTag.getAll(); scanner = new RuuviTagScanner(this, getApplicationContext()); ActionBarDrawerToggle drawerToggle = new ActionBarDrawerToggle( this, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close ); drawerLayout.addDrawerListener(drawerToggle); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setHomeButtonEnabled(true); drawerToggle.syncState(); ListView drawerListView = findViewById(R.id.navigationDrawer_listView); drawerListView.setAdapter( new ArrayAdapter<>( this, android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.navigation_items) ) ); drawerListView.setOnItemClickListener(drawerItemClicked); setBackgroundScanning(false); openFragment(1); } AdapterView.OnItemClickListener drawerItemClicked = new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { // TODO: 10/10/17 make this in a sane way openFragment(i); } }; private void setBackgroundScanning(boolean restartFlag) { PendingIntent pendingIntent = getPendingIntent(); boolean shouldRun = settings.getBoolean("pref_bgscan", false); boolean isRunning = pendingIntent != null; if (isRunning && (!shouldRun || restartFlag)) { AlarmManager am = (AlarmManager) getApplicationContext() .getSystemService(ALARM_SERVICE); am.cancel(pendingIntent); pendingIntent.cancel(); isRunning = false; } if (shouldRun && !isRunning) { int scanInterval = Integer.parseInt(settings.getString("pref_scaninterval", "300")) * 1000; if (scanInterval < 15 * 1000) scanInterval = 15 * 1000; boolean batterySaving = settings.getBoolean("pref_bgscan_battery_saving", false); Intent intent = new Intent(getApplicationContext(), BackgroundScanner.class); PendingIntent sender = PendingIntent.getBroadcast(getApplicationContext(), BackgroundScanner.REQUEST_CODE, intent, 0); AlarmManager am = (AlarmManager) getApplicationContext() .getSystemService(ALARM_SERVICE); if (batterySaving) { am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), scanInterval, sender); } else { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { checkAndAskForBatteryOptimization(); am.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + scanInterval, sender); } else { am.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + scanInterval, sender); } } } } private void checkAndAskForBatteryOptimization() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !hasShownBatteryOptimizationDialog()) { PowerManager powerManager = (PowerManager) getApplicationContext().getSystemService(POWER_SERVICE); String packageName = getPackageName(); // this below does not seems to work on my device if (!powerManager.isIgnoringBatteryOptimizations(packageName)) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(getString(R.string.battery_optimization_request)) .setPositiveButton(getString(R.string.yes), batteryDialogClick) .setNegativeButton(getString(R.string.no), batteryDialogClick) .show(); BatteryOptimizationDialogShown(); } } } DialogInterface.OnClickListener batteryDialogClick = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { switch (which) { case DialogInterface.BUTTON_POSITIVE: Intent intent = new Intent(); intent.setAction(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS); startActivity(intent); break; case DialogInterface.BUTTON_NEGATIVE: break; } } }; private PendingIntent getPendingIntent() { Intent intent = new Intent(getApplicationContext(), BackgroundScanner.class); return PendingIntent.getBroadcast(getApplicationContext(), BackgroundScanner.REQUEST_CODE, intent, PendingIntent.FLAG_NO_CREATE); } @Override protected void onStart() { //Intent intent = new Intent(MainActivity.this, ScannerService.class); //startService(intent); super.onStart(); } @Override protected void onResume() { super.onResume(); // Permission check for Marshmallow and newer int permissionCoarseLocation = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION); int permissionWriteExternal = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE); List<String> listPermissionsNeeded = new ArrayList<>(); if(permissionCoarseLocation != PackageManager.PERMISSION_GRANTED) { listPermissionsNeeded.add(Manifest.permission.ACCESS_COARSE_LOCATION); } if(permissionWriteExternal != PackageManager.PERMISSION_GRANTED) { listPermissionsNeeded.add(Manifest.permission.WRITE_EXTERNAL_STORAGE); } if(!listPermissionsNeeded.isEmpty()) { ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), 1); } else { settings.registerOnSharedPreferenceChangeListener(preferenceChangeListener); refrshTagLists(); scanner.start(); handler.post(updater); } } private void refrshTagLists() { myRuuviTags.clear(); myRuuviTags.addAll(RuuviTag.getAll()); otherRuuviTags.clear(); } @Override protected void onPause() { super.onPause(); settings.unregisterOnSharedPreferenceChangeListener(preferenceChangeListener); scanner.stop(); handler.removeCallbacks(updater); for (RuuviTag tag: myRuuviTags) { tag.update(); } } @Override protected void onStop() { super.onStop(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. //getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); return super.onOptionsItemSelected(item); } public void openFragment(int type) { Fragment fragment = null; switch (type) { case 1: refrshTagLists(); fragment = new DashboardFragment(); fragmentWithCallback = (DataUpdateListener)fragment; break; case 2: setTitle(getResources().getStringArray(R.array.navigation_items)[type]); fragment = new SettingsFragment(); fragmentWithCallback = null; break; case 3: setTitle(getResources().getStringArray(R.array.navigation_items)[type]); fragment = new AboutFragment(); fragmentWithCallback = null; break; default: setTitle(getResources().getStringArray(R.array.navigation_items)[type]); refrshTagLists(); fragment = new AddTagFragment(); fragmentWithCallback = (DataUpdateListener)fragment; type = 0; break; } getFragmentManager().beginTransaction() .replace(R.id.main_contentFrame, fragment) .commit(); if (type == 1 && getSupportActionBar() != null) { getSupportActionBar().setIcon(R.drawable.logo); } else if (getSupportActionBar() != null) { getSupportActionBar().setIcon(null); } setTitle(getResources().getStringArray(R.array.navigation_items_titles)[type]); drawerLayout.closeDrawers(); } @Override public void tagFound(RuuviTag tag) { for (RuuviTag myTag: myRuuviTags) { if (myTag.id.equals(tag.id)) { myTag.updateDataFrom(tag); if (fragmentWithCallback != null) { fragmentWithCallback.dataUpdated(); } return; } } for (RuuviTag myTag: otherRuuviTags) { if (myTag.id.equals(tag.id)) { myTag.updateDataFrom(tag); Utils.sortTagsByRssi(otherRuuviTags); if (fragmentWithCallback != null) { fragmentWithCallback.dataUpdated(); } return; } } otherRuuviTags.add(tag); } public void BatteryOptimizationDialogShown() { SharedPreferences.Editor editor = settings.edit(); editor.putBoolean(BATTERY_ASKED_PREF, true); editor.apply(); } public boolean hasShownBatteryOptimizationDialog() { return settings.getBoolean(BATTERY_ASKED_PREF, false); } public SharedPreferences.OnSharedPreferenceChangeListener preferenceChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener() { @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { setBackgroundScanning(true); } }; }
another nullcheck for actionbar things
app/src/main/java/com/ruuvi/tag/feature/main/MainActivity.java
another nullcheck for actionbar things
<ide><path>pp/src/main/java/com/ruuvi/tag/feature/main/MainActivity.java <ide> ); <ide> <ide> drawerLayout.addDrawerListener(drawerToggle); <del> getSupportActionBar().setDisplayHomeAsUpEnabled(true); <del> getSupportActionBar().setHomeButtonEnabled(true); <add> if (getSupportActionBar() != null) { <add> getSupportActionBar().setDisplayHomeAsUpEnabled(true); <add> getSupportActionBar().setHomeButtonEnabled(true); <add> } <ide> drawerToggle.syncState(); <ide> <ide> ListView drawerListView = findViewById(R.id.navigationDrawer_listView);
Java
apache-2.0
error: pathspec 'java/episim-model/src/test/java/nl/rivm/cib/episim/model/EcosystemScenarioTest.java' did not match any file(s) known to git
f8ab4d0a4838f71426f3d30f06cdf502635aefed
1
krevelen/rivm-episim,krevelen/epidemes,krevelen/rivm-episim,krevelen/epidemes,krevelen/epidemes,krevelen/rivm-episim,krevelen/rivm-episim
/* $Id$ * * Part of ZonMW project no. 50-53000-98-156 * * @license * 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. * * Copyright (c) 2016 RIVM National Institute for Health and Environment */ package nl.rivm.cib.episim.model; import static org.aeonbits.owner.util.Collections.entry; import java.util.Collections; import java.util.Date; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import javax.measure.unit.NonSI; import org.aeonbits.owner.ConfigCache; import org.apache.logging.log4j.Logger; import org.junit.Test; import io.coala.dsol3.Dsol3Config; import io.coala.enterprise.CompositeActor; import io.coala.enterprise.CoordinationFact; import io.coala.enterprise.CoordinationFactType; import io.coala.enterprise.Organization; import io.coala.log.LogUtil; import io.coala.time.Duration; import io.coala.time.Scheduler; import io.coala.time.Timing; import io.coala.time.Units; import net.jodah.concurrentunit.Waiter; import nl.rivm.cib.episim.model.scenario.Scenario; import nl.rivm.cib.episim.model.scenario.ScenarioConfig; /** * {@link EcosystemScenarioTest} * * @version $Id$ * @author Rick van Krevelen */ public class EcosystemScenarioTest { /** */ private static final Logger LOG = LogUtil .getLogger( EcosystemScenarioTest.class ); public static class EcosystemScenario implements Scenario { interface BirthFact extends CoordinationFact { // empty } // FIXME @InjectLogger private static final Logger LOG = LogUtil .getLogger( EcosystemScenario.class ); // FIXME @Inject private Scheduler scheduler; // FIXME @Inject private CoordinationFact.Factory factFactory = new CoordinationFact.SimpleFactory(); @Override public Scheduler scheduler() { return this.scheduler; } @Override public void init( final Scheduler scheduler ) throws Exception { LOG.info( "initializing..." ); this.scheduler = scheduler; final ScenarioConfig config = ConfigCache .getOrCreate( ScenarioConfig.class ); final Date offset = config.offset().toDate(); scheduler.time().subscribe( t -> { LOG.trace( "t={}, date: {}", t.prettify( Units.DAYS, 2 ), t.prettify( offset ) ); }, e -> { LOG.error( "Problem in model", e ); }, () -> { LOG.info( "completed, t={}", scheduler.now() ); } ); // create organization final Organization org1 = Organization.of( scheduler, "ind1", this.factFactory ); final CompositeActor sales = org1.actor( "sales" ); // add business rule(s) sales.on( BirthFact.class, org1.id(), fact -> { sales.after( Duration.of( 1, NonSI.DAY ) ).call( t -> { final BirthFact response = sales.createResponse( fact, CoordinationFactType.STATED, true, null, Collections .singletonMap( "myParam1", "myValue1" ) ); LOG.trace( "t={}, {} responded: {} for incoming: {}", t, sales.id(), response, fact ); // throw new Exception(); } ); } ); // observe generated facts org1.outgoing().subscribe( fact -> { LOG.trace( "t={}, outgoing: {}", org1.now(), fact ); } ); org1.outgoing( BirthFact.class, CoordinationFactType.REQUESTED ) .doOnNext( f -> { org1.consume( f ); } ).subscribe(); // spawn initial transactions with self // FIXME recursive splitting to async stream join scheduler.atEach( Timing.of( "0 0 0 14 * ? *" ).asObservable( offset ), t -> { sales.createRequest( BirthFact.class, org1.id(), null, t.add( 1 ), Collections.singletonMap( "myParam2", "myValue2" ) ); } ); } } @Test public void testEcosystem() throws TimeoutException, InstantiationException, IllegalAccessException { final ScenarioConfig config = ConfigCache .getOrCreate( ScenarioConfig.class, Collections.singletonMap( ScenarioConfig.INITIALIZER_KEY, EcosystemScenario.class.getName() ) ); final Dsol3Config dsol = Dsol3Config.of( entry( Dsol3Config.ID_KEY, "ecosystemTest" ), entry( Dsol3Config.START_TIME_KEY, "0 " + config.duration().unwrap().getUnit() ), entry( Dsol3Config.RUN_LENGTH_KEY, config.duration().unwrap().getValue().toString() ) ); LOG.info( "Starting ecosystem test, config: {}", config.toYAML() ); final Scheduler scheduler = dsol.create( config.initializer() ); final Waiter waiter = new Waiter(); scheduler.time().subscribe( time -> { // virtual time passes... }, error -> { waiter.rethrow( error ); }, () -> { waiter.resume(); } ); scheduler.resume(); waiter.await( 1, TimeUnit.SECONDS ); LOG.info( "Ecosystem test complete" ); } }
java/episim-model/src/test/java/nl/rivm/cib/episim/model/EcosystemScenarioTest.java
Added EcosystemTest stub, to experiment with Enterprise Ontology
java/episim-model/src/test/java/nl/rivm/cib/episim/model/EcosystemScenarioTest.java
Added EcosystemTest stub, to experiment with Enterprise Ontology
<ide><path>ava/episim-model/src/test/java/nl/rivm/cib/episim/model/EcosystemScenarioTest.java <add>/* $Id$ <add> * <add> * Part of ZonMW project no. 50-53000-98-156 <add> * <add> * @license <add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not <add> * use this file except in compliance with the License. You may obtain a copy <add> * of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT <add> * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the <add> * License for the specific language governing permissions and limitations under <add> * the License. <add> * <add> * Copyright (c) 2016 RIVM National Institute for Health and Environment <add> */ <add>package nl.rivm.cib.episim.model; <add> <add>import static org.aeonbits.owner.util.Collections.entry; <add> <add>import java.util.Collections; <add>import java.util.Date; <add>import java.util.concurrent.TimeUnit; <add>import java.util.concurrent.TimeoutException; <add> <add>import javax.measure.unit.NonSI; <add> <add>import org.aeonbits.owner.ConfigCache; <add>import org.apache.logging.log4j.Logger; <add>import org.junit.Test; <add> <add>import io.coala.dsol3.Dsol3Config; <add>import io.coala.enterprise.CompositeActor; <add>import io.coala.enterprise.CoordinationFact; <add>import io.coala.enterprise.CoordinationFactType; <add>import io.coala.enterprise.Organization; <add>import io.coala.log.LogUtil; <add>import io.coala.time.Duration; <add>import io.coala.time.Scheduler; <add>import io.coala.time.Timing; <add>import io.coala.time.Units; <add>import net.jodah.concurrentunit.Waiter; <add>import nl.rivm.cib.episim.model.scenario.Scenario; <add>import nl.rivm.cib.episim.model.scenario.ScenarioConfig; <add> <add>/** <add> * {@link EcosystemScenarioTest} <add> * <add> * @version $Id$ <add> * @author Rick van Krevelen <add> */ <add>public class EcosystemScenarioTest <add>{ <add> <add> /** */ <add> private static final Logger LOG = LogUtil <add> .getLogger( EcosystemScenarioTest.class ); <add> <add> public static class EcosystemScenario implements Scenario <add> { <add> <add> interface BirthFact extends CoordinationFact <add> { <add> // empty <add> } <add> <add> // FIXME @InjectLogger <add> private static final Logger LOG = LogUtil <add> .getLogger( EcosystemScenario.class ); <add> <add> // FIXME @Inject <add> private Scheduler scheduler; <add> <add> // FIXME @Inject <add> private CoordinationFact.Factory factFactory = new CoordinationFact.SimpleFactory(); <add> <add> @Override <add> public Scheduler scheduler() <add> { <add> return this.scheduler; <add> } <add> <add> @Override <add> public void init( final Scheduler scheduler ) throws Exception <add> { <add> LOG.info( "initializing..." ); <add> this.scheduler = scheduler; <add> <add> final ScenarioConfig config = ConfigCache <add> .getOrCreate( ScenarioConfig.class ); <add> final Date offset = config.offset().toDate(); <add> scheduler.time().subscribe( t -> <add> { <add> LOG.trace( "t={}, date: {}", t.prettify( Units.DAYS, 2 ), <add> t.prettify( offset ) ); <add> }, e -> <add> { <add> LOG.error( "Problem in model", e ); <add> }, () -> <add> { <add> LOG.info( "completed, t={}", scheduler.now() ); <add> } ); <add> <add> // create organization <add> final Organization org1 = Organization.of( scheduler, "ind1", <add> this.factFactory ); <add> final CompositeActor sales = org1.actor( "sales" ); <add> <add> // add business rule(s) <add> sales.on( BirthFact.class, org1.id(), fact -> <add> { <add> sales.after( Duration.of( 1, NonSI.DAY ) ).call( t -> <add> { <add> final BirthFact response = sales.createResponse( fact, <add> CoordinationFactType.STATED, true, null, Collections <add> .singletonMap( "myParam1", "myValue1" ) ); <add> LOG.trace( "t={}, {} responded: {} for incoming: {}", t, <add> sales.id(), response, fact ); <add>// throw new Exception(); <add> } ); <add> } ); <add> <add> // observe generated facts <add> org1.outgoing().subscribe( fact -> <add> { <add> LOG.trace( "t={}, outgoing: {}", org1.now(), fact ); <add> } ); <add> <add> org1.outgoing( BirthFact.class, CoordinationFactType.REQUESTED ) <add> .doOnNext( f -> <add> { <add> org1.consume( f ); <add> } ).subscribe(); <add> <add> // spawn initial transactions with self <add> // FIXME recursive splitting to async stream join <add> scheduler.atEach( <add> Timing.of( "0 0 0 14 * ? *" ).asObservable( offset ), t -> <add> { <add> sales.createRequest( BirthFact.class, org1.id(), null, <add> t.add( 1 ), Collections.singletonMap( <add> "myParam2", "myValue2" ) ); <add> } ); <add> } <add> } <add> <add> @Test <add> public void testEcosystem() <add> throws TimeoutException, InstantiationException, IllegalAccessException <add> { <add> final ScenarioConfig config = ConfigCache <add> .getOrCreate( ScenarioConfig.class, <add> Collections.singletonMap( <add> ScenarioConfig.INITIALIZER_KEY, <add> EcosystemScenario.class.getName() ) ); <add> <add> final Dsol3Config dsol = Dsol3Config.of( <add> entry( Dsol3Config.ID_KEY, "ecosystemTest" ), <add> entry( Dsol3Config.START_TIME_KEY, <add> "0 " + config.duration().unwrap().getUnit() ), <add> entry( Dsol3Config.RUN_LENGTH_KEY, <add> config.duration().unwrap().getValue().toString() ) ); <add> LOG.info( "Starting ecosystem test, config: {}", config.toYAML() ); <add> final Scheduler scheduler = dsol.create( config.initializer() ); <add> <add> final Waiter waiter = new Waiter(); <add> scheduler.time().subscribe( time -> <add> { <add> // virtual time passes... <add> }, error -> <add> { <add> waiter.rethrow( error ); <add> }, () -> <add> { <add> waiter.resume(); <add> } ); <add> scheduler.resume(); <add> waiter.await( 1, TimeUnit.SECONDS ); <add> LOG.info( "Ecosystem test complete" ); <add> } <add> <add>}
Java
apache-2.0
4c73227b1b3975989427adf13e186042569a7fb2
0
whumph/sakai,noondaysun/sakai,frasese/sakai,duke-compsci290-spring2016/sakai,introp-software/sakai,bzhouduke123/sakai,ouit0408/sakai,hackbuteer59/sakai,bkirschn/sakai,Fudan-University/sakai,frasese/sakai,puramshetty/sakai,puramshetty/sakai,Fudan-University/sakai,frasese/sakai,OpenCollabZA/sakai,clhedrick/sakai,bkirschn/sakai,tl-its-umich-edu/sakai,tl-its-umich-edu/sakai,puramshetty/sakai,wfuedu/sakai,duke-compsci290-spring2016/sakai,liubo404/sakai,duke-compsci290-spring2016/sakai,clhedrick/sakai,liubo404/sakai,colczr/sakai,introp-software/sakai,hackbuteer59/sakai,puramshetty/sakai,hackbuteer59/sakai,ktakacs/sakai,noondaysun/sakai,kwedoff1/sakai,liubo404/sakai,bkirschn/sakai,ktakacs/sakai,kingmook/sakai,udayg/sakai,ktakacs/sakai,joserabal/sakai,OpenCollabZA/sakai,ktakacs/sakai,buckett/sakai-gitflow,willkara/sakai,pushyamig/sakai,conder/sakai,Fudan-University/sakai,bzhouduke123/sakai,bzhouduke123/sakai,colczr/sakai,OpenCollabZA/sakai,rodriguezdevera/sakai,zqian/sakai,frasese/sakai,pushyamig/sakai,lorenamgUMU/sakai,noondaysun/sakai,bzhouduke123/sakai,clhedrick/sakai,whumph/sakai,colczr/sakai,introp-software/sakai,surya-janani/sakai,surya-janani/sakai,kingmook/sakai,frasese/sakai,duke-compsci290-spring2016/sakai,rodriguezdevera/sakai,joserabal/sakai,ouit0408/sakai,ktakacs/sakai,ktakacs/sakai,willkara/sakai,duke-compsci290-spring2016/sakai,lorenamgUMU/sakai,conder/sakai,wfuedu/sakai,noondaysun/sakai,zqian/sakai,wfuedu/sakai,rodriguezdevera/sakai,OpenCollabZA/sakai,bzhouduke123/sakai,conder/sakai,buckett/sakai-gitflow,kwedoff1/sakai,buckett/sakai-gitflow,puramshetty/sakai,whumph/sakai,colczr/sakai,bkirschn/sakai,udayg/sakai,hackbuteer59/sakai,whumph/sakai,whumph/sakai,udayg/sakai,kingmook/sakai,willkara/sakai,whumph/sakai,wfuedu/sakai,Fudan-University/sakai,kingmook/sakai,introp-software/sakai,willkara/sakai,bzhouduke123/sakai,willkara/sakai,noondaysun/sakai,joserabal/sakai,hackbuteer59/sakai,duke-compsci290-spring2016/sakai,wfuedu/sakai,wfuedu/sakai,zqian/sakai,OpenCollabZA/sakai,kwedoff1/sakai,joserabal/sakai,ouit0408/sakai,pushyamig/sakai,introp-software/sakai,frasese/sakai,liubo404/sakai,bkirschn/sakai,tl-its-umich-edu/sakai,kingmook/sakai,conder/sakai,liubo404/sakai,introp-software/sakai,Fudan-University/sakai,surya-janani/sakai,kwedoff1/sakai,hackbuteer59/sakai,clhedrick/sakai,surya-janani/sakai,bkirschn/sakai,udayg/sakai,colczr/sakai,puramshetty/sakai,conder/sakai,tl-its-umich-edu/sakai,OpenCollabZA/sakai,whumph/sakai,rodriguezdevera/sakai,rodriguezdevera/sakai,tl-its-umich-edu/sakai,clhedrick/sakai,kingmook/sakai,colczr/sakai,joserabal/sakai,zqian/sakai,pushyamig/sakai,liubo404/sakai,hackbuteer59/sakai,surya-janani/sakai,lorenamgUMU/sakai,Fudan-University/sakai,surya-janani/sakai,liubo404/sakai,lorenamgUMU/sakai,whumph/sakai,conder/sakai,liubo404/sakai,noondaysun/sakai,lorenamgUMU/sakai,buckett/sakai-gitflow,zqian/sakai,introp-software/sakai,wfuedu/sakai,OpenCollabZA/sakai,udayg/sakai,joserabal/sakai,ouit0408/sakai,bzhouduke123/sakai,wfuedu/sakai,conder/sakai,tl-its-umich-edu/sakai,kwedoff1/sakai,ouit0408/sakai,duke-compsci290-spring2016/sakai,conder/sakai,ktakacs/sakai,kingmook/sakai,puramshetty/sakai,kingmook/sakai,frasese/sakai,pushyamig/sakai,rodriguezdevera/sakai,surya-janani/sakai,kwedoff1/sakai,clhedrick/sakai,zqian/sakai,OpenCollabZA/sakai,surya-janani/sakai,introp-software/sakai,puramshetty/sakai,willkara/sakai,lorenamgUMU/sakai,tl-its-umich-edu/sakai,zqian/sakai,joserabal/sakai,pushyamig/sakai,zqian/sakai,rodriguezdevera/sakai,rodriguezdevera/sakai,bzhouduke123/sakai,colczr/sakai,willkara/sakai,clhedrick/sakai,ouit0408/sakai,udayg/sakai,noondaysun/sakai,bkirschn/sakai,ouit0408/sakai,Fudan-University/sakai,lorenamgUMU/sakai,pushyamig/sakai,buckett/sakai-gitflow,buckett/sakai-gitflow,pushyamig/sakai,hackbuteer59/sakai,noondaysun/sakai,udayg/sakai,buckett/sakai-gitflow,tl-its-umich-edu/sakai,bkirschn/sakai,willkara/sakai,udayg/sakai,clhedrick/sakai,Fudan-University/sakai,kwedoff1/sakai,ouit0408/sakai,kwedoff1/sakai,colczr/sakai,buckett/sakai-gitflow,duke-compsci290-spring2016/sakai,joserabal/sakai,frasese/sakai,ktakacs/sakai,lorenamgUMU/sakai
/********************************************************************************** * $URL$ * $Id$ *********************************************************************************** * * Copyright (c) 2004, 2005, 2006, 2007, 2008, 2009 The Sakai Foundation * * Licensed under the Educational Community 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.opensource.org/licenses/ECL-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.sakaiproject.tool.assessment.services; import java.math.BigDecimal; import java.text.DecimalFormat; import java.text.NumberFormat; import java.text.ParseException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Map.Entry; import java.util.Random; import java.util.Set; import java.util.StringTokenizer; import java.util.TreeSet; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.commons.math.complex.Complex; import org.apache.commons.math.complex.ComplexFormat; import org.apache.commons.math.util.MathUtils; import org.sakaiproject.event.cover.EventTrackingService; import org.sakaiproject.service.gradebook.shared.GradebookExternalAssessmentService; import org.sakaiproject.spring.SpringBeanLocator; import org.sakaiproject.tool.assessment.data.dao.grading.AssessmentGradingData; import org.sakaiproject.tool.assessment.data.dao.grading.ItemGradingAttachment; import org.sakaiproject.tool.assessment.data.dao.grading.ItemGradingData; import org.sakaiproject.tool.assessment.data.dao.grading.MediaData; import org.sakaiproject.tool.assessment.data.ifc.assessment.AnswerIfc; import org.sakaiproject.tool.assessment.data.ifc.assessment.AssessmentIfc; import org.sakaiproject.tool.assessment.data.ifc.assessment.EvaluationModelIfc; import org.sakaiproject.tool.assessment.data.ifc.assessment.ItemDataIfc; import org.sakaiproject.tool.assessment.data.ifc.assessment.ItemMetaDataIfc; import org.sakaiproject.tool.assessment.data.ifc.assessment.ItemTextIfc; import org.sakaiproject.tool.assessment.data.ifc.assessment.PublishedAssessmentIfc; import org.sakaiproject.tool.assessment.data.ifc.grading.StudentGradingSummaryIfc; import org.sakaiproject.tool.assessment.data.ifc.shared.TypeIfc; import org.sakaiproject.tool.assessment.facade.AgentFacade; import org.sakaiproject.tool.assessment.facade.GradebookFacade; import org.sakaiproject.tool.assessment.facade.TypeFacade; import org.sakaiproject.tool.assessment.facade.TypeFacadeQueriesAPI; import org.sakaiproject.tool.assessment.integration.context.IntegrationContextFactory; import org.sakaiproject.tool.assessment.integration.helper.ifc.GradebookServiceHelper; import org.sakaiproject.tool.assessment.services.assessment.PublishedAssessmentService; import org.sakaiproject.tool.assessment.util.SamigoExpressionError; import org.sakaiproject.tool.assessment.util.SamigoExpressionParser; /** * The GradingService calls the back end to get/store grading information. * It also calculates scores for autograded types. */ public class GradingService { /** * Key for a complext numeric answer e.g. 9+9i */ public static final String ANSWER_TYPE_COMPLEX = "COMPLEX"; /** * key for a real number representation e.g 1 or 10E5 */ public static final String ANSWER_TYPE_REAL = "REAL"; // CALCULATED_QUESTION final String OPEN_BRACKET = "\\{"; final String CLOSE_BRACKET = "\\}"; final String CALCULATION_OPEN = "[["; // not regex safe final String CALCULATION_CLOSE = "]]"; // not regex safe /** * regular expression for matching the contents of a variable or formula name * in Calculated Questions * NOTE: Old regex: ([\\w\\s\\.\\-\\^\\$\\!\\&\\@\\?\\*\\%\\(\\)\\+=#`~&:;|,/<>\\[\\]\\\\\\'\"]+?) * was way too complicated. */ final String CALCQ_VAR_FORM_NAME = "[a-zA-Z][^\\{\\}]*?"; // non-greedy (must start wtih alpha) final String CALCQ_VAR_FORM_NAME_EXPRESSION = "("+CALCQ_VAR_FORM_NAME+")"; // variable match - (?<!\{)\{([^\{\}]+?)\}(?!\}) - means any sequence inside braces without a braces before or after final Pattern CALCQ_ANSWER_PATTERN = Pattern.compile("(?<!\\{)" + OPEN_BRACKET + CALCQ_VAR_FORM_NAME_EXPRESSION + CLOSE_BRACKET + "(?!\\})"); final Pattern CALCQ_FORMULA_PATTERN = Pattern.compile(OPEN_BRACKET + OPEN_BRACKET + CALCQ_VAR_FORM_NAME_EXPRESSION + CLOSE_BRACKET + CLOSE_BRACKET); final Pattern CALCQ_FORMULA_SPLIT_PATTERN = Pattern.compile("(" + OPEN_BRACKET + OPEN_BRACKET + CALCQ_VAR_FORM_NAME + CLOSE_BRACKET + CLOSE_BRACKET + ")"); final Pattern CALCQ_CALCULATION_PATTERN = Pattern.compile("\\[\\[([^\\[\\]]+?)\\]\\]?"); // non-greedy private static Log log = LogFactory.getLog(GradingService.class); /** * Get all scores for a published assessment from the back end. */ public ArrayList getTotalScores(String publishedId, String which) { ArrayList results = null; try { results = new ArrayList(PersistenceService.getInstance(). getAssessmentGradingFacadeQueries().getTotalScores(publishedId, which)); } catch (Exception e) { e.printStackTrace(); } return results; } public ArrayList getTotalScores(String publishedId, String which, boolean getSubmittedOnly) { ArrayList results = null; try { results = new ArrayList(PersistenceService.getInstance(). getAssessmentGradingFacadeQueries().getTotalScores(publishedId, which, getSubmittedOnly)); } catch (Exception e) { e.printStackTrace(); } return results; } /** * Get all submissions for a published assessment from the back end. */ public List getAllSubmissions(String publishedId) { List results = null; try { results = PersistenceService.getInstance(). getAssessmentGradingFacadeQueries().getAllSubmissions(publishedId); } catch (Exception e) { e.printStackTrace(); } return results; } public List getAllAssessmentGradingData(Long publishedId) { List results = null; try { results = PersistenceService.getInstance(). getAssessmentGradingFacadeQueries().getAllAssessmentGradingData(publishedId); } catch (Exception e) { e.printStackTrace(); } return results; } public ArrayList getHighestAssessmentGradingList(Long publishedId) { ArrayList results = null; try { results = new ArrayList(PersistenceService.getInstance(). getAssessmentGradingFacadeQueries().getHighestAssessmentGradingList(publishedId)); } catch (Exception e) { e.printStackTrace(); } return results; } public List getHighestSubmittedOrGradedAssessmentGradingList(Long publishedId) { ArrayList results = null; try { results = new ArrayList(PersistenceService.getInstance(). getAssessmentGradingFacadeQueries().getHighestSubmittedOrGradedAssessmentGradingList(publishedId)); } catch (Exception e) { e.printStackTrace(); } return results; } public ArrayList getLastAssessmentGradingList(Long publishedId) { ArrayList results = null; try { results = new ArrayList(PersistenceService.getInstance(). getAssessmentGradingFacadeQueries().getLastAssessmentGradingList(publishedId)); } catch (Exception e) { e.printStackTrace(); } return results; } public List getLastSubmittedAssessmentGradingList(Long publishedId) { List results = null; try { results = PersistenceService.getInstance(). getAssessmentGradingFacadeQueries().getLastSubmittedAssessmentGradingList(publishedId); } catch (Exception e) { e.printStackTrace(); } return results; } public List getLastSubmittedOrGradedAssessmentGradingList(Long publishedId) { List results = null; try { results = PersistenceService.getInstance(). getAssessmentGradingFacadeQueries().getLastSubmittedOrGradedAssessmentGradingList(publishedId); } catch (Exception e) { e.printStackTrace(); } return results; } public void saveTotalScores(ArrayList gdataList, PublishedAssessmentIfc pub) { //log.debug("**** GradingService: saveTotalScores"); try { AssessmentGradingData gdata = null; if (gdataList.size()>0) gdata = (AssessmentGradingData) gdataList.get(0); else return; Integer scoringType = getScoringType(pub); ArrayList oldList = getAssessmentGradingsByScoringType( scoringType, gdata.getPublishedAssessmentId()); for (int i=0; i<gdataList.size(); i++){ AssessmentGradingData ag = (AssessmentGradingData)gdataList.get(i); saveOrUpdateAssessmentGrading(ag); EventTrackingService.post(EventTrackingService.newEvent("sam.total.score.update", "siteId=" + AgentFacade.getCurrentSiteId() + ", gradedBy=" + AgentFacade.getAgentString() + ", assessmentGradingId=" + ag.getAssessmentGradingId() + ", totalAutoScore=" + ag.getTotalAutoScore() + ", totalOverrideScore=" + ag.getTotalOverrideScore() + ", FinalScore=" + ag.getFinalScore() + ", comments=" + ag.getComments() , true)); } // no need to notify gradebook if this submission is not for grade // we only want to notify GB when there are changes ArrayList newList = getAssessmentGradingsByScoringType( scoringType, gdata.getPublishedAssessmentId()); ArrayList l = getListForGradebookNotification(newList, oldList); notifyGradebook(l, pub); } catch (GradebookServiceException ge) { log.error("GradebookServiceException" + ge); throw ge; } } private ArrayList getListForGradebookNotification( ArrayList newList, ArrayList oldList){ ArrayList l = new ArrayList(); HashMap h = new HashMap(); for (int i=0; i<oldList.size(); i++){ AssessmentGradingData ag = (AssessmentGradingData)oldList.get(i); h.put(ag.getAssessmentGradingId(), ag); } for (int i=0; i<newList.size(); i++){ AssessmentGradingData a = (AssessmentGradingData) newList.get(i); Object o = h.get(a.getAssessmentGradingId()); if (o == null){ // this does not exist in old list, so include it for update l.add(a); } else{ // if new is different from old, include it for update AssessmentGradingData b = (AssessmentGradingData) o; if ((a.getFinalScore()!=null && b.getFinalScore()!=null) && !a.getFinalScore().equals(b.getFinalScore())) l.add(a); } } return l; } public ArrayList getAssessmentGradingsByScoringType( Integer scoringType, Long publishedAssessmentId){ List l = null; // get the list of highest score if ((scoringType).equals(EvaluationModelIfc.HIGHEST_SCORE)){ l = getHighestSubmittedOrGradedAssessmentGradingList(publishedAssessmentId); } // get the list of last score else if ((scoringType).equals(EvaluationModelIfc.LAST_SCORE)) { l = getLastSubmittedOrGradedAssessmentGradingList(publishedAssessmentId); } else { l = getTotalScores(publishedAssessmentId.toString(), "3", false); } return new ArrayList(l); } public Integer getScoringType(PublishedAssessmentIfc pub){ Integer scoringType = null; EvaluationModelIfc e = pub.getEvaluationModel(); if ( e!=null ){ scoringType = e.getScoringType(); } return scoringType; } private boolean updateGradebook(AssessmentGradingData data, PublishedAssessmentIfc pub){ // no need to notify gradebook if this submission is not for grade boolean forGrade = (Boolean.TRUE).equals(data.getForGrade()); boolean toGradebook = false; EvaluationModelIfc e = pub.getEvaluationModel(); if ( e!=null ){ String toGradebookString = e.getToGradeBook(); toGradebook = toGradebookString.equals(EvaluationModelIfc.TO_DEFAULT_GRADEBOOK.toString()); } return (forGrade && toGradebook); } private void notifyGradebook(ArrayList l, PublishedAssessmentIfc pub){ for (int i=0; i<l.size(); i++){ notifyGradebook((AssessmentGradingData)l.get(i), pub); } } /** * Get the score information for each item from the assessment score. */ public HashMap getItemScores(Long publishedId, Long itemId, String which) { try { return (HashMap) PersistenceService.getInstance(). getAssessmentGradingFacadeQueries() .getItemScores(publishedId, itemId, which); } catch (Exception e) { e.printStackTrace(); return new HashMap(); } } public HashMap getItemScores(Long publishedId, Long itemId, String which, boolean loadItemGradingAttachment) { try { return (HashMap) PersistenceService.getInstance(). getAssessmentGradingFacadeQueries() .getItemScores(publishedId, itemId, which, loadItemGradingAttachment); } catch (Exception e) { e.printStackTrace(); return new HashMap(); } } public HashMap getItemScores(Long itemId, List scores, boolean loadItemGradingAttachment) { try { return (HashMap) PersistenceService.getInstance(). getAssessmentGradingFacadeQueries() .getItemScores(itemId, scores, loadItemGradingAttachment); } catch (Exception e) { e.printStackTrace(); return new HashMap(); } } /** * Get the last set of itemgradingdata for a student per assessment */ public HashMap getLastItemGradingData(String publishedId, String agentId) { try { return (HashMap) PersistenceService.getInstance(). getAssessmentGradingFacadeQueries() .getLastItemGradingData(Long.valueOf(publishedId), agentId); } catch (Exception e) { e.printStackTrace(); return new HashMap(); } } /** * Get the grading data for a given submission */ public HashMap getStudentGradingData(String assessmentGradingId) { try { return (HashMap) PersistenceService.getInstance(). getAssessmentGradingFacadeQueries() .getStudentGradingData(assessmentGradingId); } catch (Exception e) { e.printStackTrace(); return new HashMap(); } } /** * Get the last submission for a student per assessment */ public HashMap getSubmitData(String publishedId, String agentId, Integer scoringoption, String assessmentGradingId) { try { Long gradingId = null; if (assessmentGradingId != null) gradingId = Long.valueOf(assessmentGradingId); return (HashMap) PersistenceService.getInstance(). getAssessmentGradingFacadeQueries().getSubmitData(Long.valueOf(publishedId), agentId, scoringoption, gradingId); } catch (Exception e) { e.printStackTrace(); return new HashMap(); } } public String getTextForId(Long typeId) { TypeFacadeQueriesAPI typeFacadeQueries = PersistenceService.getInstance().getTypeFacadeQueries(); TypeFacade type = typeFacadeQueries.getTypeFacadeById(typeId); return (type.getKeyword()); } public int getSubmissionSizeOfPublishedAssessment(String publishedAssessmentId) { try{ return PersistenceService.getInstance(). getAssessmentGradingFacadeQueries() .getSubmissionSizeOfPublishedAssessment(Long.valueOf( publishedAssessmentId)); } catch(Exception e) { e.printStackTrace(); return 0; } } public Long saveMedia(byte[] media, String mimeType){ return PersistenceService.getInstance().getAssessmentGradingFacadeQueries(). saveMedia(media, mimeType); } public Long saveMedia(MediaData mediaData){ return PersistenceService.getInstance().getAssessmentGradingFacadeQueries(). saveMedia(mediaData); } public MediaData getMedia(String mediaId){ return PersistenceService.getInstance().getAssessmentGradingFacadeQueries(). getMedia(Long.valueOf(mediaId)); } public ArrayList getMediaArray(String itemGradingId){ return PersistenceService.getInstance().getAssessmentGradingFacadeQueries(). getMediaArray(Long.valueOf(itemGradingId)); } public ArrayList getMediaArray2(String itemGradingId){ return PersistenceService.getInstance().getAssessmentGradingFacadeQueries(). getMediaArray2(Long.valueOf(itemGradingId)); } public ArrayList getMediaArray(ItemGradingData i){ return PersistenceService.getInstance().getAssessmentGradingFacadeQueries(). getMediaArray(i); } public HashMap getMediaItemGradingHash(Long assessmentGradingId) { return PersistenceService.getInstance().getAssessmentGradingFacadeQueries(). getMediaItemGradingHash(assessmentGradingId); } public List<MediaData> getMediaArray(String publishedId, String publishItemId, String which){ return PersistenceService.getInstance().getAssessmentGradingFacadeQueries(). getMediaArray(Long.valueOf(publishedId), Long.valueOf(publishItemId), which); } public ItemGradingData getLastItemGradingDataByAgent(String publishedItemId, String agentId) { try { return PersistenceService.getInstance().getAssessmentGradingFacadeQueries(). getLastItemGradingDataByAgent(Long.valueOf(publishedItemId), agentId); } catch (Exception e) { e.printStackTrace(); return null; } } public ItemGradingData getItemGradingData(String assessmentGradingId, String publishedItemId) { try { return PersistenceService.getInstance().getAssessmentGradingFacadeQueries(). getItemGradingData(Long.valueOf(assessmentGradingId), Long.valueOf(publishedItemId)); } catch (Exception e) { e.printStackTrace(); return null; } } public AssessmentGradingData load(String assessmentGradingId) { return load(assessmentGradingId, true); } public AssessmentGradingData load(String assessmentGradingId, boolean loadGradingAttachment) { try{ return PersistenceService.getInstance().getAssessmentGradingFacadeQueries(). load(Long.valueOf(assessmentGradingId), loadGradingAttachment); } catch(Exception e) { log.error(e); throw new RuntimeException(e); } } public ItemGradingData getItemGrading(String itemGradingId) { try{ return PersistenceService.getInstance().getAssessmentGradingFacadeQueries(). getItemGrading(Long.valueOf(itemGradingId)); } catch(Exception e) { log.error(e); throw new Error(e); } } public AssessmentGradingData getLastAssessmentGradingByAgentId(String publishedAssessmentId, String agentIdString) { try{ return PersistenceService.getInstance().getAssessmentGradingFacadeQueries(). getLastAssessmentGradingByAgentId(Long.valueOf(publishedAssessmentId), agentIdString); } catch(Exception e) { log.error(e); throw new RuntimeException(e); } } public AssessmentGradingData getLastSavedAssessmentGradingByAgentId(String publishedAssessmentId, String agentIdString) { try{ return PersistenceService.getInstance().getAssessmentGradingFacadeQueries(). getLastSavedAssessmentGradingByAgentId(Long.valueOf(publishedAssessmentId), agentIdString); } catch(Exception e) { log.error(e); throw new RuntimeException(e); } } public AssessmentGradingData getLastSubmittedAssessmentGradingByAgentId(String publishedAssessmentId, String agentIdString, String assessmentGradingId) { AssessmentGradingData assessmentGranding = null; try { if (assessmentGradingId != null) { assessmentGranding = PersistenceService.getInstance().getAssessmentGradingFacadeQueries(). getLastSubmittedAssessmentGradingByAgentId(Long.valueOf(publishedAssessmentId), agentIdString, Long.valueOf(assessmentGradingId)); } else { assessmentGranding = PersistenceService.getInstance().getAssessmentGradingFacadeQueries(). getLastSubmittedAssessmentGradingByAgentId(Long.valueOf(publishedAssessmentId), agentIdString, null); } } catch(Exception e) { log.error(e); throw new RuntimeException(e); } return assessmentGranding; } public void saveItemGrading(ItemGradingData item) { try { PersistenceService.getInstance(). getAssessmentGradingFacadeQueries().saveItemGrading(item); } catch (Exception e) { e.printStackTrace(); } } public void saveOrUpdateAssessmentGrading(AssessmentGradingData assessment) { try { /* // Comment out the whole IF section because the only thing we do here is to // update the itemGradingSet. However, this update is redundant as it will // be updated in saveOrUpdateAssessmentGrading(assessment). if (assessment.getAssessmentGradingId()!=null && assessment.getAssessmentGradingId().longValue()>0){ //1. if assessmentGrading contain itemGrading, we want to insert/update itemGrading first Set itemGradingSet = assessment.getItemGradingSet(); Iterator iter = itemGradingSet.iterator(); while (iter.hasNext()) { ItemGradingData itemGradingData = (ItemGradingData) iter.next(); log.debug("date = " + itemGradingData.getSubmittedDate()); } // The following line seems redundant. I cannot see a reason why we need to save the itmeGradingSet // here and then again in following saveOrUpdateAssessmentGrading(assessment). Comment it out. //saveOrUpdateAll(itemGradingSet); } */ // this will update itemGradingSet and assessmentGrading. May as well, otherwise I would have // to reload assessment again PersistenceService.getInstance(). getAssessmentGradingFacadeQueries().saveOrUpdateAssessmentGrading(assessment); } catch (Exception e) { e.printStackTrace(); } } // This API only touch SAM_ASSESSMENTGRADING_T. No data gets inserted/updated in SAM_ITEMGRADING_T public void saveOrUpdateAssessmentGradingOnly(AssessmentGradingData assessment) { Set origItemGradingSet = assessment.getItemGradingSet(); HashSet h = new HashSet(origItemGradingSet); // Clear the itemGradingSet so no data gets inserted/updated in SAM_ITEMGRADING_T; origItemGradingSet.clear(); int size = assessment.getItemGradingSet().size(); log.debug("before persist to db: size = " + size); try { PersistenceService.getInstance().getAssessmentGradingFacadeQueries().saveOrUpdateAssessmentGrading(assessment); } catch (Exception e) { e.printStackTrace(); } finally { // Restore the original itemGradingSet back assessment.setItemGradingSet(h); size = assessment.getItemGradingSet().size(); log.debug("after persist to db: size = " + size); } } public List getAssessmentGradingIds(String publishedItemId){ try{ return PersistenceService.getInstance().getAssessmentGradingFacadeQueries(). getAssessmentGradingIds(Long.valueOf(publishedItemId)); } catch(Exception e) { log.error(e); throw new RuntimeException(e); } } public AssessmentGradingData getHighestAssessmentGrading(String publishedAssessmentId, String agentId){ try{ return PersistenceService.getInstance().getAssessmentGradingFacadeQueries(). getHighestAssessmentGrading(Long.valueOf(publishedAssessmentId), agentId); } catch(Exception e) { log.error(e); throw new RuntimeException(e); } } public AssessmentGradingData getHighestSubmittedAssessmentGrading(String publishedAssessmentId, String agentId, String assessmentGradingId){ AssessmentGradingData assessmentGrading = null; try { if (assessmentGradingId != null) { assessmentGrading = PersistenceService.getInstance().getAssessmentGradingFacadeQueries(). getHighestSubmittedAssessmentGrading(Long.valueOf(publishedAssessmentId), agentId, Long.valueOf(assessmentGradingId)); } else { assessmentGrading = PersistenceService.getInstance().getAssessmentGradingFacadeQueries(). getHighestSubmittedAssessmentGrading(Long.valueOf(publishedAssessmentId), agentId, null); } } catch(Exception e) { log.error(e); throw new RuntimeException(e); } return assessmentGrading; } public AssessmentGradingData getHighestSubmittedAssessmentGrading(String publishedAssessmentId, String agentId){ return getHighestSubmittedAssessmentGrading(publishedAssessmentId, agentId, null); } public Set getItemGradingSet(String assessmentGradingId){ try{ return PersistenceService.getInstance().getAssessmentGradingFacadeQueries(). getItemGradingSet(Long.valueOf(assessmentGradingId)); } catch(Exception e){ log.error(e); throw new RuntimeException(e); } } public HashMap getAssessmentGradingByItemGradingId(String publishedAssessmentId){ try{ return PersistenceService.getInstance().getAssessmentGradingFacadeQueries(). getAssessmentGradingByItemGradingId(Long.valueOf(publishedAssessmentId)); } catch(Exception e){ log.error(e); throw new RuntimeException(e); } } public void updateItemScore(ItemGradingData gdata, double scoreDifference, PublishedAssessmentIfc pub){ try { AssessmentGradingData adata = load(gdata.getAssessmentGradingId().toString()); adata.setItemGradingSet(getItemGradingSet(adata.getAssessmentGradingId().toString())); Set itemGradingSet = adata.getItemGradingSet(); Iterator iter = itemGradingSet.iterator(); double totalAutoScore = 0; double totalOverrideScore = adata.getTotalOverrideScore().doubleValue(); while (iter.hasNext()){ ItemGradingData i = (ItemGradingData)iter.next(); if (i.getItemGradingId().equals(gdata.getItemGradingId())){ i.setAutoScore(gdata.getAutoScore()); i.setComments(gdata.getComments()); i.setGradedBy(AgentFacade.getAgentString()); i.setGradedDate(new Date()); } if (i.getAutoScore()!=null) totalAutoScore += i.getAutoScore().doubleValue(); } adata.setTotalAutoScore( Double.valueOf(totalAutoScore)); if (Double.compare((totalAutoScore+totalOverrideScore),Double.valueOf("0").doubleValue())<0){ adata.setFinalScore(Double.valueOf("0")); }else{ adata.setFinalScore(Double.valueOf(totalAutoScore+totalOverrideScore)); } saveOrUpdateAssessmentGrading(adata); if (scoreDifference != 0){ notifyGradebookByScoringType(adata, pub); } } catch (GradebookServiceException ge) { ge.printStackTrace(); throw ge; } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } } /** * Assume this is a new item. */ public void storeGrades(AssessmentGradingData data, PublishedAssessmentIfc pub, HashMap publishedItemHash, HashMap publishedItemTextHash, HashMap publishedAnswerHash, HashMap invalidFINMap, ArrayList invalidSALengthList) throws GradebookServiceException, FinFormatException { log.debug("storeGrades: data.getSubmittedDate()" + data.getSubmittedDate()); storeGrades(data, false, pub, publishedItemHash, publishedItemTextHash, publishedAnswerHash, true, invalidFINMap, invalidSALengthList); } /** * Assume this is a new item. */ public void storeGrades(AssessmentGradingData data, PublishedAssessmentIfc pub, HashMap publishedItemHash, HashMap publishedItemTextHash, HashMap publishedAnswerHash, boolean persistToDB, HashMap invalidFINMap, ArrayList invalidSALengthList) throws GradebookServiceException, FinFormatException { log.debug("storeGrades (not persistToDB) : data.getSubmittedDate()" + data.getSubmittedDate()); storeGrades(data, false, pub, publishedItemHash, publishedItemTextHash, publishedAnswerHash, persistToDB, invalidFINMap, invalidSALengthList); } public void storeGrades(AssessmentGradingData data, boolean regrade, PublishedAssessmentIfc pub, HashMap publishedItemHash, HashMap publishedItemTextHash, HashMap publishedAnswerHash, boolean persistToDB) throws GradebookServiceException, FinFormatException { log.debug("storeGrades (not persistToDB) : data.getSubmittedDate()" + data.getSubmittedDate()); storeGrades(data, regrade, pub, publishedItemHash, publishedItemTextHash, publishedAnswerHash, persistToDB, null, null); } /** * This is the big, complicated mess where we take all the items in * an assessment, store the grading data, auto-grade it, and update * everything. * * If regrade is true, we just recalculate the graded score. If it's * false, we do everything from scratch. */ public void storeGrades(AssessmentGradingData data, boolean regrade, PublishedAssessmentIfc pub, HashMap publishedItemHash, HashMap publishedItemTextHash, HashMap publishedAnswerHash, boolean persistToDB, HashMap invalidFINMap, ArrayList invalidSALengthList) throws GradebookServiceException, FinFormatException { log.debug("****x1. regrade ="+regrade+" "+(new Date()).getTime()); try { String agent = data.getAgentId(); // note that this itemGradingSet is a partial set of answer submitted. it contains only // newly submitted answers, updated answers and MCMR/FIB/FIN answers ('cos we need the old ones to // calculate scores for new ones) Set<ItemGradingData> itemGradingSet = data.getItemGradingSet(); if (itemGradingSet == null) itemGradingSet = new HashSet<ItemGradingData>(); log.debug("****itemGrading size="+itemGradingSet.size()); List<ItemGradingData> tempItemGradinglist = new ArrayList<ItemGradingData>(itemGradingSet); // CALCULATED_QUESTION - if this is a calc question. Carefully sort the list of answers if (isCalcQuestion(tempItemGradinglist, publishedItemHash)) { Collections.sort(tempItemGradinglist, new Comparator<ItemGradingData>(){ public int compare(ItemGradingData o1, ItemGradingData o2) { ItemGradingData gradeData1 = o1; ItemGradingData gradeData2 = o2; // protect against blank ones in samigo initial setup. if (gradeData1 == null) return -1; if (gradeData2 == null) return 1; if (gradeData1.getPublishedAnswerId() == null) return -1; if (gradeData2.getPublishedAnswerId() == null) return 1; return gradeData1.getPublishedAnswerId().compareTo(gradeData2.getPublishedAnswerId()); } }); } Iterator<ItemGradingData> iter = tempItemGradinglist.iterator(); // fibEmiAnswersMap contains a map of HashSet of answers for a FIB or EMI item, // key =itemid, value= HashSet of answers for each item. // For FIB: This is used to keep track of answers we have already used for // mutually exclusive multiple answer type of FIB, such as // The flag of the US is {red|white|blue},{red|white|blue}, and {red|white|blue}. // so if the first blank has an answer 'red', the 'red' answer should // not be included in the answers for the other mutually exclusive blanks. // For EMI: This keeps track of how many answers were given so we don't give // extra marks for to many answers. Map fibEmiAnswersMap = new HashMap(); Map<Long, Map<Long,Set<EMIScore>>> emiScoresMap = new HashMap<Long, Map<Long,Set<EMIScore>>>(); //change algorithm based on each question (SAK-1930 & IM271559) -cwen HashMap totalItems = new HashMap(); log.debug("****x2. "+(new Date()).getTime()); double autoScore = (double) 0; Long itemId = (long)0; int calcQuestionAnswerSequence = 1; // sequence of answers for CALCULATED_QUESTION while(iter.hasNext()) { ItemGradingData itemGrading = iter.next(); // CALCULATED_QUESTION - We increment this so we that calculated // questions can know where we are in the sequence of answers. if (itemGrading.getPublishedItemId().equals(itemId)) { calcQuestionAnswerSequence++; } else { calcQuestionAnswerSequence = 1; } itemId = itemGrading.getPublishedItemId(); ItemDataIfc item = (ItemDataIfc) publishedItemHash.get(itemId); if (item == null) { //this probably shouldn't happen log.error("unable to retrive itemDataIfc for: " + publishedItemHash.get(itemId)); continue; } Long itemType = item.getTypeId(); autoScore = (double) 0; itemGrading.setAssessmentGradingId(data.getAssessmentGradingId()); //itemGrading.setSubmittedDate(new Date()); itemGrading.setAgentId(agent); itemGrading.setOverrideScore(Double.valueOf(0)); if (itemType == 5 && itemGrading.getAnswerText() != null) { String processedAnswerText = itemGrading.getAnswerText().replaceAll("\r", "").replaceAll("\n", ""); if (processedAnswerText.length() > 32000) { if (invalidSALengthList != null) { invalidSALengthList.add(item.getItemId()); } } } // note that totalItems & fibAnswersMap would be modified by the following method try { autoScore = getScoreByQuestionType(itemGrading, item, itemType, publishedItemTextHash, totalItems, fibEmiAnswersMap, emiScoresMap, publishedAnswerHash, regrade, calcQuestionAnswerSequence); } catch (FinFormatException e) { autoScore = 0d; if (invalidFINMap != null) { if (invalidFINMap.containsKey(itemId)) { ArrayList list = (ArrayList) invalidFINMap.get(itemId); list.add(itemGrading.getItemGradingId()); } else { ArrayList list = new ArrayList(); list.add(itemGrading.getItemGradingId()); invalidFINMap.put(itemId, list); } } } log.debug("**!regrade, autoScore="+autoScore); if (!(TypeIfc.MULTIPLE_CORRECT).equals(itemType) && !(TypeIfc.EXTENDED_MATCHING_ITEMS).equals(itemType)) totalItems.put(itemId, Double.valueOf(autoScore)); if (regrade && TypeIfc.AUDIO_RECORDING.equals(itemType)) itemGrading.setAttemptsRemaining(item.getTriesAllowed()); itemGrading.setAutoScore(Double.valueOf(autoScore)); } if ((invalidFINMap != null && invalidFINMap.size() > 0) || (invalidSALengthList != null && invalidSALengthList.size() > 0)) { return; } // Added persistToDB because if we don't save data to DB later, we shouldn't update the assessment // submittedDate either. The date should be sync in delivery bean and DB // This is for DeliveryBean.checkDataIntegrity() if (!regrade && persistToDB) { data.setSubmittedDate(new Date()); setIsLate(data, pub); } log.debug("****x3. "+(new Date()).getTime()); List<ItemGradingData> emiItemGradings = new ArrayList<ItemGradingData>(); // the following procedure ensure total score awarded per question is no less than 0 // this probably only applies to MCMR question type - daisyf iter = itemGradingSet.iterator(); //since the itr goes through each answer (multiple answers for a signle mc question), keep track //of its total score by itemId -> autoScore[]{user's score, total possible} Map<Long, Double[]> mcmcAllOrNothingCheck = new HashMap<Long, Double[]>(); //get item information to check if it's MCMS and Not Partial Credit Long itemType2 = -1l; String mcmsPartialCredit = ""; double itemScore = -1; while(iter.hasNext()) { ItemGradingData itemGrading = iter.next(); itemId = itemGrading.getPublishedItemId(); ItemDataIfc item = (ItemDataIfc) publishedItemHash.get(itemId); //SAM-1724 it's possible the item is not in the hash -DH if (item == null) { log.error("unable to retrive itemDataIfc for: " + publishedItemHash.get(itemId)); continue; } itemType2 = item.getTypeId(); //get item information to check if it's MCMS and Not Partial Credit mcmsPartialCredit = item.getItemMetaDataByLabel(ItemMetaDataIfc.MCMS_PARTIAL_CREDIT); itemScore = item.getScore(); //double autoScore = (double) 0; // this does not apply to EMI // just create a short-list and handle differently below if ((TypeIfc.EXTENDED_MATCHING_ITEMS).equals(itemType2)) { emiItemGradings.add(itemGrading); continue; } double eachItemScore = ((Double) totalItems.get(itemId)).doubleValue(); if((eachItemScore < 0) && !((TypeIfc.MULTIPLE_CHOICE).equals(itemType2)||(TypeIfc.TRUE_FALSE).equals(itemType2))) { itemGrading.setAutoScore( Double.valueOf(0)); } //keep track of MCMC answer's total score in order to check for all or nothing if(TypeIfc.MULTIPLE_CORRECT.equals(itemType2) && "false".equals(mcmsPartialCredit)){ Double accumulatedScore = itemGrading.getAutoScore(); if(mcmcAllOrNothingCheck.containsKey(itemId)){ Double[] accumulatedScoreArr = mcmcAllOrNothingCheck.get(itemId); accumulatedScore += accumulatedScoreArr[0]; } mcmcAllOrNothingCheck.put(itemId, new Double[]{accumulatedScore, item.getScore()}); } } log.debug("****x3.1 "+(new Date()).getTime()); // Loop 1: this procedure ensure total score awarded per EMI item // is correct // For emi's there are multiple gradings per item per question, // for the grading we only know scores after grading so we need // to reset the grading score here to the correct scores // this currently only applies to EMI question type if (emiItemGradings != null && !emiItemGradings.isEmpty()) { Map<Long, Map<Long, Map<Long, EMIScore>>> emiOrderedScoresMap = reorderEMIScoreMap(emiScoresMap); iter = emiItemGradings.iterator(); while (iter.hasNext()) { ItemGradingData itemGrading = iter.next(); //SAM-2016 check for Nullity if (itemGrading == null) { log.warn("Map contains null itemgrading!"); continue; } Map<Long, Map<Long, EMIScore>> innerMap = emiOrderedScoresMap .get(itemGrading.getPublishedItemId()); if (innerMap == null) { log.warn("Inner map is empty!"); continue; } Map<Long, EMIScore> scoreMap = innerMap .get(itemGrading.getPublishedItemTextId()); if (scoreMap == null) { log.warn("Score map is empty!"); continue; } EMIScore score = scoreMap .get(itemGrading.getPublishedAnswerId()); if (score == null) { //its possible! SAM-2016 log.warn("we can't find a score for answer: " + itemGrading.getPublishedAnswerId()); continue; } itemGrading.setAutoScore(emiOrderedScoresMap .get(itemGrading.getPublishedItemId()) .get(itemGrading.getPublishedItemTextId()) .get(itemGrading.getPublishedAnswerId()).effectiveScore); } } // if it's MCMS and Not Partial Credit and the score isn't 100% (totalAutoScoreCheck != itemScore), // that means the user didn't answer all of the correct answers only. // We need to set their score to 0 for all ItemGrading items for(Entry<Long, Double[]> entry : mcmcAllOrNothingCheck.entrySet()){ if(!(MathUtils.equalsIncludingNaN(entry.getValue()[0], entry.getValue()[1], 0.0001))){ //reset all scores to 0 since the user didn't get all correct answers iter = itemGradingSet.iterator(); while(iter.hasNext()){ ItemGradingData itemGrading = iter.next(); if(itemGrading.getPublishedItemId().equals(entry.getKey())){ itemGrading.setAutoScore(Double.valueOf(0)); } } } } log.debug("****x4. "+(new Date()).getTime()); // save#1: this itemGrading Set is a partial set of answers submitted. it contains new answers and // updated old answers and FIB answers ('cos we need the old answer to calculate the score for new // ones). we need to be cheap, we don't want to update record that hasn't been // changed. Yes, assessmentGrading's total score will be out of sync at this point, I am afraid. It // would be in sync again once the whole method is completed sucessfully. if (persistToDB) { saveOrUpdateAll(itemGradingSet); } log.debug("****x5. "+(new Date()).getTime()); // save#2: now, we need to get the full set so we can calculate the total score accumulate for the // whole assessment. Set fullItemGradingSet = getItemGradingSet(data.getAssessmentGradingId().toString()); double totalAutoScore = getTotalAutoScore(fullItemGradingSet); data.setTotalAutoScore( Double.valueOf(totalAutoScore)); //log.debug("**#1 total AutoScore"+totalAutoScore); if (Double.compare((totalAutoScore + data.getTotalOverrideScore().doubleValue()),new Double("0").doubleValue())<0){ data.setFinalScore( Double.valueOf("0")); }else{ data.setFinalScore(Double.valueOf(totalAutoScore + data.getTotalOverrideScore().doubleValue())); } log.debug("****x6. "+(new Date()).getTime()); } catch (GradebookServiceException ge) { ge.printStackTrace(); throw ge; } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } // save#3: itemGradingSet has been saved above so just need to update assessmentGrading // therefore setItemGradingSet as empty first - daisyf // however, if we do not persit to DB, we want to keep itemGradingSet with data for later use // Because if itemGradingSet is not saved to DB, we cannot go to DB to get it. We have to // get it through data. if (persistToDB) { data.setItemGradingSet(new HashSet()); saveOrUpdateAssessmentGrading(data); log.debug("****x7. "+(new Date()).getTime()); if (!regrade) { notifyGradebookByScoringType(data, pub); } } log.debug("****x8. "+(new Date()).getTime()); // I am not quite sure what the following code is doing... I modified this based on my assumption: // If this happens dring regrade, we don't want to clean these data up // We only want to clean them out in delivery if (!regrade && Boolean.TRUE.equals(data.getForGrade())) { // remove the assessmentGradingData created during gradiing (by updatding total score page) removeUnsubmittedAssessmentGradingData(data); } } private double getTotalAutoScore(Set itemGradingSet){ //log.debug("*** no. of itemGrading="+itemGradingSet.size()); double totalAutoScore =0; Iterator iter = itemGradingSet.iterator(); while (iter.hasNext()){ ItemGradingData i = (ItemGradingData)iter.next(); //log.debug(i.getItemGradingId()+"->"+i.getAutoScore()); if (i.getAutoScore()!=null) totalAutoScore += i.getAutoScore().doubleValue(); } return totalAutoScore; } private void notifyGradebookByScoringType(AssessmentGradingData data, PublishedAssessmentIfc pub){ Integer scoringType = pub.getEvaluationModel().getScoringType(); if (updateGradebook(data, pub)){ AssessmentGradingData d = data; // data is the last submission // need to decide what to tell gradebook if ((scoringType).equals(EvaluationModelIfc.HIGHEST_SCORE)) d = getHighestSubmittedAssessmentGrading(pub.getPublishedAssessmentId().toString(), data.getAgentId()); notifyGradebook(d, pub); } } private double getScoreByQuestionType(ItemGradingData itemGrading, ItemDataIfc item, Long itemType, Map publishedItemTextHash, Map totalItems, Map fibAnswersMap, Map<Long, Map<Long,Set<EMIScore>>> emiScoresMap, HashMap publishedAnswerHash, boolean regrade, int calcQuestionAnswerSequence) throws FinFormatException { //double score = (double) 0; double initScore = (double) 0; double autoScore = (double) 0; double accumelateScore = (double) 0; Long itemId = item.getItemId(); int type = itemType.intValue(); switch (type){ case 1: // MC Single Correct if(item.getPartialCreditFlag()) autoScore = getAnswerScoreMCQ(itemGrading, publishedAnswerHash); else{ autoScore = getAnswerScore(itemGrading, publishedAnswerHash); } //overridescore if (itemGrading.getOverrideScore() != null) autoScore += itemGrading.getOverrideScore().doubleValue(); totalItems.put(itemId, new Double(autoScore)); break;// MC Single Correct case 12: // MC Multiple Correct Single Selection case 3: // MC Survey case 4: // True/False autoScore = getAnswerScore(itemGrading, publishedAnswerHash); //overridescore if (itemGrading.getOverrideScore() != null) autoScore += itemGrading.getOverrideScore().doubleValue(); totalItems.put(itemId, Double.valueOf(autoScore)); break; case 2: // MC Multiple Correct ItemTextIfc itemText = (ItemTextIfc) publishedItemTextHash.get(itemGrading.getPublishedItemTextId()); List answerArray = itemText.getAnswerArray(); int correctAnswers = 0; if (answerArray != null){ for (int i =0; i<answerArray.size(); i++){ AnswerIfc a = (AnswerIfc) answerArray.get(i); if (a.getIsCorrect().booleanValue()) correctAnswers++; } } initScore = getAnswerScore(itemGrading, publishedAnswerHash); if (initScore > 0) autoScore = initScore / correctAnswers; else autoScore = (getTotalCorrectScore(itemGrading, publishedAnswerHash) / correctAnswers) * ((double) -1); //overridescore? if (itemGrading.getOverrideScore() != null) autoScore += itemGrading.getOverrideScore().doubleValue(); if (!totalItems.containsKey(itemId)){ totalItems.put(itemId, Double.valueOf(autoScore)); //log.debug("****0. first answer score = "+autoScore); } else{ accumelateScore = ((Double)totalItems.get(itemId)).doubleValue(); //log.debug("****1. before adding new score = "+accumelateScore); //log.debug("****2. this answer score = "+autoScore); accumelateScore += autoScore; //log.debug("****3. add 1+2 score = "+accumelateScore); totalItems.put(itemId, Double.valueOf(accumelateScore)); //log.debug("****4. what did we put in = "+((Double)totalItems.get(itemId)).doubleValue()); } break; case 9: // Matching initScore = getAnswerScore(itemGrading, publishedAnswerHash); if (initScore > 0) { int nonDistractors = 0; Iterator<ItemTextIfc> itemIter = item.getItemTextArraySorted().iterator(); while (itemIter.hasNext()) { ItemTextIfc curItem = itemIter.next(); if (!isDistractor(curItem)) { nonDistractors++; } } autoScore = initScore / nonDistractors; } //overridescore? if (itemGrading.getOverrideScore() != null) autoScore += itemGrading.getOverrideScore().doubleValue(); if (!totalItems.containsKey(itemId)) totalItems.put(itemId, Double.valueOf(autoScore)); else { accumelateScore = ((Double)totalItems.get(itemId)).doubleValue(); accumelateScore += autoScore; totalItems.put(itemId, Double.valueOf(accumelateScore)); } break; case 8: // FIB autoScore = getFIBScore(itemGrading, fibAnswersMap, item, publishedAnswerHash) / (double) ((ItemTextIfc) item.getItemTextSet().toArray()[0]).getAnswerSet().size(); //overridescore - cwen if (itemGrading.getOverrideScore() != null) autoScore += itemGrading.getOverrideScore().doubleValue(); if (!totalItems.containsKey(itemId)) totalItems.put(itemId, Double.valueOf(autoScore)); else { accumelateScore = ((Double)totalItems.get(itemId)).doubleValue(); accumelateScore += autoScore; totalItems.put(itemId, Double.valueOf(accumelateScore)); } break; case 15: // CALCULATED_QUESTION case 11: // FIN try { if (type == 15) { // CALCULATED_QUESTION Map<Integer, String> calculatedAnswersMap = getCalculatedAnswersMap(itemGrading, item); int numAnswers = calculatedAnswersMap.size(); autoScore = getCalcQScore(itemGrading, item, calculatedAnswersMap, calcQuestionAnswerSequence ) / (double) numAnswers; } else { autoScore = getFINScore(itemGrading, item, publishedAnswerHash) / (double) ((ItemTextIfc) item.getItemTextSet().toArray()[0]).getAnswerSet().size(); } } catch (FinFormatException e) { throw e; } //overridescore - cwen if (itemGrading.getOverrideScore() != null) autoScore += itemGrading.getOverrideScore().doubleValue(); if (!totalItems.containsKey(itemId)) totalItems.put(itemId, Double.valueOf(autoScore)); else { accumelateScore = ((Double)totalItems.get(itemId)).doubleValue(); accumelateScore += autoScore; totalItems.put(itemId, Double.valueOf(accumelateScore)); } break; case 14: // EMI autoScore = getEMIScore(itemGrading, itemId, totalItems, emiScoresMap, publishedItemTextHash, publishedAnswerHash); break; case 5: // SAQ case 6: // file upload case 7: // audio recording //overridescore - cwen if (regrade && itemGrading.getAutoScore() != null) { autoScore = itemGrading.getAutoScore(); } if (itemGrading.getOverrideScore() != null) autoScore += itemGrading.getOverrideScore().doubleValue(); if (!totalItems.containsKey(itemId)) totalItems.put(itemId, Double.valueOf(autoScore)); else { accumelateScore = ((Double)totalItems.get(itemId)).doubleValue(); accumelateScore += autoScore; totalItems.put(itemId, Double.valueOf(accumelateScore)); } break; } return autoScore; } /** * This grades multiple choice and true false questions. Since * multiple choice/multiple select has a separate ItemGradingData for * each choice, they're graded the same way the single choice are. * Choices should be given negative score values if one wants them * to lose points for the wrong choice. */ public double getAnswerScore(ItemGradingData data, Map publishedAnswerHash) { AnswerIfc answer = (AnswerIfc) publishedAnswerHash.get(data.getPublishedAnswerId()); if (answer == null || answer.getScore() == null) { return (double) 0; } ItemDataIfc item = (ItemDataIfc) answer.getItem(); Long itemType = item.getTypeId(); if (answer.getIsCorrect() == null || !answer.getIsCorrect().booleanValue()) { // return (double) 0; // Para que descuente (For discount) if ((TypeIfc.EXTENDED_MATCHING_ITEMS).equals(itemType)||(TypeIfc.MULTIPLE_CHOICE).equals(itemType)||(TypeIfc.TRUE_FALSE).equals(itemType)){ return (Math.abs(answer.getDiscount().doubleValue()) * ((double) -1)); }else{ return (double) 0; } } return answer.getScore().doubleValue(); } public void notifyGradebook(AssessmentGradingData data, PublishedAssessmentIfc pub) throws GradebookServiceException { // If the assessment is published to the gradebook, make sure to update the scores in the gradebook String toGradebook = pub.getEvaluationModel().getToGradeBook(); GradebookExternalAssessmentService g = null; boolean integrated = IntegrationContextFactory.getInstance().isIntegrated(); if (integrated) { g = (GradebookExternalAssessmentService) SpringBeanLocator.getInstance(). getBean("org.sakaiproject.service.gradebook.GradebookExternalAssessmentService"); } GradebookServiceHelper gbsHelper = IntegrationContextFactory.getInstance().getGradebookServiceHelper(); PublishedAssessmentService publishedAssessmentService = new PublishedAssessmentService(); String currentSiteId = publishedAssessmentService.getPublishedAssessmentSiteId(pub.getPublishedAssessmentId().toString()); if (gbsHelper.gradebookExists(GradebookFacade.getGradebookUId(currentSiteId), g) && toGradebook.equals(EvaluationModelIfc.TO_DEFAULT_GRADEBOOK.toString())){ if(log.isDebugEnabled()) log.debug("Attempting to update a score in the gradebook"); // add retry logic to resolve deadlock problem while sending grades to gradebook Double originalFinalScore = data.getFinalScore(); int retryCount = PersistenceService.getInstance().getPersistenceHelper().getRetryCount().intValue(); while (retryCount > 0){ try { // Send the average score if average was selected for multiple submissions Integer scoringType = pub.getEvaluationModel().getScoringType(); if (scoringType.equals(EvaluationModelIfc.AVERAGE_SCORE)) { // status = 5: there is no submission but grader update something in the score page if(data.getStatus() ==5) { data.setFinalScore(data.getFinalScore()); } else { Double averageScore = PersistenceService.getInstance().getAssessmentGradingFacadeQueries(). getAverageSubmittedAssessmentGrading(Long.valueOf(pub.getPublishedAssessmentId()), data.getAgentId()); data.setFinalScore(averageScore); } } gbsHelper.updateExternalAssessmentScore(data, g); retryCount = 0; } catch (org.sakaiproject.service.gradebook.shared.AssessmentNotFoundException ante) { log.warn("problem sending grades to gradebook: " + ante.getMessage()); if (AssessmentIfc.RETRACT_FOR_EDIT_STATUS.equals(pub.getStatus())) { retryCount = retry(retryCount, ante, pub, true); } else { // Otherwise, do the same exeption handling as others retryCount = retry(retryCount, ante, pub, false); } } catch (Exception e) { retryCount = retry(retryCount, e, pub, false); } } // change the final score back to the original score since it may set to average score. // data.getFinalScore() != originalFinalScore if(!(MathUtils.equalsIncludingNaN(data.getFinalScore(), originalFinalScore, 0.0001))) { data.setFinalScore(originalFinalScore); } } else { if(log.isDebugEnabled()) log.debug("Not updating the gradebook. toGradebook = " + toGradebook); } } private int retry(int retryCount, Exception e, PublishedAssessmentIfc pub, boolean retractForEditStatus) { log.warn("retrying...sending grades to gradebook. "); log.warn("retry...."); retryCount--; try { int deadlockInterval = PersistenceService.getInstance().getPersistenceHelper().getDeadlockInterval().intValue(); Thread.sleep(deadlockInterval); } catch(InterruptedException ex){ log.warn(ex.getMessage()); } if (retryCount==0) { if (retractForEditStatus) { // This happens in following scenario: // 1. The assessment is active and has "None" for GB setting // 2. Instructor retracts it for edit and update the to "Send to GB" // 3. Instructor updates something on the total Score page // Because the GB will not be created until the assessment gets republished, // "AssessmentNotFoundException" will be thrown here. Since, this is the expected // exception, we simply log a debug message without retrying or notifying the user. // Of course, you can argue about what if the assessment gets deleted by other cause. // But I would say the major cause would be this "retract" scenario. Also, without knowing // the change history of the assessment, I think this is the best handling. log.info("We quietly sallow the AssessmentNotFoundException excption here. Published Assessment Name: " + pub.getTitle()); } else { // after retries, still failed updating gradebook log.warn("After all retries, still failed ... Now throw error to UI"); throw new GradebookServiceException(e); } } return retryCount; } /** * This grades Fill In Blank questions. (see SAK-1685) * There will be two valid cases for scoring when there are multiple fill * in blanks in a question: * Case 1- There are different sets of answers (a set can contain one or more * item) for each blank (e.g. The {dog|coyote|wolf} howls and the {lion|cougar} * roars.) In this case each blank is tested for correctness independently. * Case 2-There is the same set of answers for each blank: e.g. The flag of the US * is {red|white|blue},{red|white|blue}, and {red|white|blue}. * These are the only two valid types of questions. When authoring, it is an * ERROR to include: * (1) a mixture of independent answer and common answer blanks * (e.g. The {dog|coyote|wolf} howls at the {red|white|blue}, {red|white|blue}, * and {red|white|blue} flag.) * (2) more than one set of blanks with a common answer ((e.g. The US flag * is {red|white|blue}, {red|white|blue}, and {red|white|blue} and the Italian * flag is {red|white|greem}, {red|white|greem}, and {red|white|greem}.) * These two invalid questions specifications should be authored as two * separate questions. Here are the definition and 12 cases I came up with (lydia, 01/2006): single answers : roses are {red} and vilets are {blue} multiple answers : {dogs|cats} have 4 legs multiple answers , mutually exclusive, all answers must be identical, can be in diff. orders : US flag has {red|blue|white} and {red |white|blue} and {blue|red|white} colors multiple answers , mutually non-exclusive : {dogs|cats} have 4 legs and {dogs|cats} can be pets. wildcard uses * to mean one of more characters -. wildcard single answer, case sensitive -. wildcard single answer, case insensitive -. single answer, no wildcard , case sensitive -. single answer, no wildcard , case insensitive -. multiple answer, mutually non-exclusive, no wildcard , case sensitive -. multiple answer, mutually non-exclusive, no wildcard , case in sensitive -. multiple answer, mutually non-exclusive, wildcard , case sensitive -. multiple answer, mutually non-exclusive, wildcard , case insensitive -. multiple answer, mutually exclusive, no wildcard , case sensitive -. multiple answer, mutually exclusive, no wildcard , case in sensitive -. multiple answer, mutually exclusive, wildcard , case sensitive -. multiple answer, mutually exclusive, wildcard , case insensitive */ public double getFIBScore(ItemGradingData data, Map fibmap, ItemDataIfc itemdata, Map publishedAnswerHash) { String studentanswer = ""; boolean matchresult = false; double totalScore = (double) 0; data.setIsCorrect(Boolean.FALSE); if (data.getPublishedAnswerId() == null) { return totalScore; } AnswerIfc answerIfc = (AnswerIfc) publishedAnswerHash.get(data.getPublishedAnswerId()); if (answerIfc == null) { return totalScore; } String answertext = answerIfc.getText(); Long itemId = itemdata.getItemId(); String casesensitive = itemdata.getItemMetaDataByLabel(ItemMetaDataIfc.CASE_SENSITIVE_FOR_FIB); String mutuallyexclusive = itemdata.getItemMetaDataByLabel(ItemMetaDataIfc.MUTUALLY_EXCLUSIVE_FOR_FIB); //Set answerSet = new HashSet(); if (answertext != null) { StringTokenizer st = new StringTokenizer(answertext, "|"); while (st.hasMoreTokens()) { String answer = st.nextToken().trim(); if ("true".equalsIgnoreCase(casesensitive)) { if (data.getAnswerText() != null){ studentanswer= data.getAnswerText().trim(); matchresult = fibmatch(answer, studentanswer, true); } } // if case sensitive else { // case insensitive , if casesensitive is false, or null, or "". if (data.getAnswerText() != null){ studentanswer= data.getAnswerText().trim(); matchresult = fibmatch(answer, studentanswer, false); } } // else , case insensitive if (matchresult){ boolean alreadyused=false; // add check for mutual exclusive if ("true".equalsIgnoreCase(mutuallyexclusive)) { // check if answers are already used. Set answer_used_sofar = (HashSet) fibmap.get(itemId); if ((answer_used_sofar!=null) && ( answer_used_sofar.contains(studentanswer.toLowerCase()))){ // already used, so it's a wrong answer for mutually exclusive questions alreadyused=true; } else { // not used, it's a good answer, now add this to the already_used list. // we only store lowercase strings in the fibmap. if (answer_used_sofar==null) { answer_used_sofar = new HashSet(); } answer_used_sofar.add(studentanswer.toLowerCase()); fibmap.put(itemId, answer_used_sofar); } } if (!alreadyused) { totalScore += ((AnswerIfc) publishedAnswerHash.get(data.getPublishedAnswerId())).getScore().doubleValue(); data.setIsCorrect(Boolean.TRUE); } // SAK-3005: quit if answer is correct, e.g. if you answered A for {a|A}, you already scored break; } } } return totalScore; } public boolean getFIBResult(ItemGradingData data, HashMap fibmap, ItemDataIfc itemdata, HashMap publishedAnswerHash) { // this method is similiar to getFIBScore(), except it returns true/false for the answer, not scores. // may be able to refactor code out to be reused, but totalscores for mutually exclusive case is a bit tricky. String studentanswer = ""; boolean matchresult = false; if (data.getPublishedAnswerId() == null) { return matchresult; } AnswerIfc answerIfc = (AnswerIfc) publishedAnswerHash.get(data.getPublishedAnswerId()); if (answerIfc == null) { return matchresult; } String answertext = answerIfc.getText(); Long itemId = itemdata.getItemId(); String casesensitive = itemdata.getItemMetaDataByLabel(ItemMetaDataIfc.CASE_SENSITIVE_FOR_FIB); String mutuallyexclusive = itemdata.getItemMetaDataByLabel(ItemMetaDataIfc.MUTUALLY_EXCLUSIVE_FOR_FIB); //Set answerSet = new HashSet(); if (answertext != null) { StringTokenizer st = new StringTokenizer(answertext, "|"); while (st.hasMoreTokens()) { String answer = st.nextToken().trim(); if ("true".equalsIgnoreCase(casesensitive)) { if (data.getAnswerText() != null){ studentanswer= data.getAnswerText().trim(); matchresult = fibmatch(answer, studentanswer, true); } } // if case sensitive else { // case insensitive , if casesensitive is false, or null, or "". if (data.getAnswerText() != null){ studentanswer= data.getAnswerText().trim(); matchresult = fibmatch(answer, studentanswer, false); } } // else , case insensitive if (matchresult){ boolean alreadyused=false; // add check for mutual exclusive if ("true".equalsIgnoreCase(mutuallyexclusive)) { // check if answers are already used. Set answer_used_sofar = (HashSet) fibmap.get(itemId); if ((answer_used_sofar!=null) && ( answer_used_sofar.contains(studentanswer.toLowerCase()))){ // already used, so it's a wrong answer for mutually exclusive questions alreadyused=true; } else { // not used, it's a good answer, now add this to the already_used list. // we only store lowercase strings in the fibmap. if (answer_used_sofar==null) { answer_used_sofar = new HashSet(); } answer_used_sofar.add(studentanswer.toLowerCase()); fibmap.put(itemId, answer_used_sofar); } } if (alreadyused) { matchresult = false; } break; } } } return matchresult; } public double getFINScore(ItemGradingData data, ItemDataIfc itemdata, Map publishedAnswerHash) throws FinFormatException { data.setIsCorrect(Boolean.FALSE); double totalScore = (double) 0; boolean matchresult = getFINResult(data, itemdata, publishedAnswerHash); if (matchresult){ totalScore += ((AnswerIfc) publishedAnswerHash.get(data.getPublishedAnswerId())).getScore().doubleValue(); data.setIsCorrect(Boolean.TRUE); } return totalScore; } public boolean getFINResult (ItemGradingData data, ItemDataIfc itemdata, Map publishedAnswerHash) throws FinFormatException { String studentanswer = ""; boolean range; boolean matchresult = false; ComplexFormat complexFormat = new ComplexFormat(); Complex answerComplex = null; Complex studentAnswerComplex = null; BigDecimal answerNum = null, answer1Num = null, answer2Num = null, studentAnswerNum = null; if (data.getPublishedAnswerId() == null) { return false; } AnswerIfc answerIfc = (AnswerIfc) publishedAnswerHash.get(data.getPublishedAnswerId()); if (answerIfc == null) { return matchresult; } String answertext = answerIfc.getText(); if (answertext != null) { StringTokenizer st = new StringTokenizer(answertext, "|"); range = false; if (st.countTokens() > 1) { range = true; } String studentAnswerText = null; if (data.getAnswerText() != null) { studentAnswerText = data.getAnswerText().trim().replace(',','.'); // in Spain, comma is used as a decimal point } if (range) { String answer1 = st.nextToken().trim(); String answer2 = st.nextToken().trim(); if (answer1 != null){ answer1 = answer1.trim().replace(',','.'); // in Spain, comma is used as a decimal point } if (answer2 != null){ answer2 = answer2.trim().replace(',','.'); // in Spain, comma is used as a decimal point } try { answer1Num = new BigDecimal(answer1); answer2Num = new BigDecimal(answer2); } catch (Exception e) { log.debug("Number is not BigDecimal: " + answer1 + " or " + answer2); } Map map = validate(studentAnswerText); studentAnswerNum = (BigDecimal) map.get(ANSWER_TYPE_REAL); matchresult = (answer1Num != null && answer2Num != null && studentAnswerNum != null && (answer1Num.compareTo(studentAnswerNum) <= 0) && (answer2Num.compareTo(studentAnswerNum) >= 0)); } else { // not range String answer = st.nextToken().trim(); if (answer != null){ answer = answer.trim().replace(',','.'); // in Spain, comma is used as a decimal point } try { answerNum = new BigDecimal(answer); } catch(NumberFormatException ex) { log.debug("Number is not BigDecimal: " + answer); } try { answerComplex = complexFormat.parse(answer); } catch(ParseException ex) { log.debug("Number is not Complex: " + answer); } if (data.getAnswerText() != null) { Map map = validate(studentAnswerText); if (answerNum != null) { studentAnswerNum = (BigDecimal) map.get(ANSWER_TYPE_REAL); matchresult = (studentAnswerNum != null && answerNum.compareTo(studentAnswerNum) == 0); } else if (answerComplex != null) { studentAnswerComplex = (Complex) map.get(ANSWER_TYPE_COMPLEX); matchresult = (studentAnswerComplex != null && answerComplex.equals(studentAnswerComplex)); } } } } return matchresult; } /** * Validate a students numeric answer * @param The answer to validate * @return a Map containing either Real or Complex answer keyed by {@link #ANSWER_TYPE_REAL} or {@link #ANSWER_TYPE_COMPLEX} */ public Map validate(String value) { HashMap map = new HashMap(); if (value == null || value.trim().equals("")) { return map; } String trimmedValue = value.trim(); boolean isComplex = true; boolean isRealNumber = true; BigDecimal studentAnswerReal = null; try { studentAnswerReal = new BigDecimal(trimmedValue); } catch (Exception e) { isRealNumber = false; } // Test for complex number only if it is not a BigDecimal Complex studentAnswerComplex = null; if (!isRealNumber) { try { DecimalFormat df = (DecimalFormat)NumberFormat.getNumberInstance(Locale.US); df.setGroupingUsed(false); // Numerical format ###.## (decimal symbol is the point) ComplexFormat complexFormat = new ComplexFormat(df); studentAnswerComplex = complexFormat.parse(trimmedValue); // This is because there is a bug parsing complex number. 9i is parsed as 9 if (studentAnswerComplex.getImaginary() == 0 && trimmedValue.contains("i")) { isComplex = false; } } catch (Exception e) { isComplex = false; } } Boolean isValid = isComplex || isRealNumber; if (!isValid) { throw new FinFormatException("Not a valid FIN Input. studentanswer=" + trimmedValue); } if (isRealNumber) { map.put(ANSWER_TYPE_REAL, studentAnswerReal); } else if (isComplex) { map.put(ANSWER_TYPE_COMPLEX, studentAnswerComplex); } return map; } /** * EMI score processing * */ private double getEMIScore(ItemGradingData itemGrading, Long itemId, Map totalItems, Map<Long, Map<Long, Set<EMIScore>>> emiScoresMap, Map publishedItemTextHash, Map publishedAnswerHash) { log.debug("getEMIScore( " + itemGrading +", " + itemId); double autoScore = 0.0; if (!totalItems.containsKey(itemId)) { totalItems.put(itemId, new HashMap()); emiScoresMap.put(itemId, new HashMap<Long, Set<EMIScore>>()); } autoScore = getAnswerScore(itemGrading, publishedAnswerHash); AnswerIfc answer = (AnswerIfc) publishedAnswerHash.get(itemGrading .getPublishedAnswerId()); if (answer == null) { //its possible we have an orphaned object ... log.warn("could not find answer: " + itemGrading .getPublishedAnswerId() + ", for item " + itemGrading.getItemGradingId()); return 0.0; } Long itemTextId = itemGrading.getPublishedItemTextId(); // update the fibEmiAnswersMap so we can keep track // of how many answers were given Map<Long, Set<EMIScore>> emiItemScoresMap = emiScoresMap.get(itemId); // place the answer scores in a sorted set. // so now we can mark the correct ones and discount the extra incorrect // ones. Set<EMIScore> scores = null; if (emiItemScoresMap.containsKey(itemTextId)) { scores = emiItemScoresMap.get(itemTextId); } else { scores = new TreeSet<EMIScore>(); emiItemScoresMap.put(itemTextId, scores); } scores.add(new EMIScore(itemId, itemTextId, itemGrading .getPublishedAnswerId(), answer.getIsCorrect(), autoScore)); ItemTextIfc itemText = (ItemTextIfc) publishedItemTextHash.get(itemTextId); int numberCorrectAnswers = itemText.getEmiCorrectOptionLabels() .length(); Integer requiredCount = itemText.getRequiredOptionsCount(); // re-calculate the scores over for the whole item autoScore = 0.0; int c = 0; for (EMIScore s : scores) { c++; s.effectiveScore = 0.0; if (c <= numberCorrectAnswers && c <= requiredCount) { // if correct and in count then add score s.effectiveScore = s.correct ? s.score : 0.0; } else if (c > numberCorrectAnswers) { // if incorrect and over count add discount s.effectiveScore = !s.correct ? s.score : 0.0; } if (autoScore + s.effectiveScore < 0.0) { // the current item tipped it to negative, // we cannot do this, so add zero s.effectiveScore = 0.0; } autoScore += s.effectiveScore; } // override score if (itemGrading.getOverrideScore() != null) autoScore += itemGrading.getOverrideScore().doubleValue(); HashMap totalItemTextScores = (HashMap) totalItems.get(itemId); totalItemTextScores.put(itemTextId, Double.valueOf(autoScore)); return autoScore; } /** * CALCULATED_QUESTION * Returns a double score value for the ItemGrading element being scored for a Calculated Question * * @param calcQuestionAnswerSequence the order of answers in the list * @return score for the item. */ public double getCalcQScore(ItemGradingData data, ItemDataIfc itemdata, Map<Integer, String> calculatedAnswersMap, int calcQuestionAnswerSequence) { double totalScore = (double) 0; if (data.getAnswerText() == null) return totalScore; // zero for blank if (!calculatedAnswersMap.containsKey(calcQuestionAnswerSequence)) { return totalScore; } // this variable should look something like this "42.1|2,2" String allAnswerText = calculatedAnswersMap.get(calcQuestionAnswerSequence).toString(); // NOTE: this correctAnswer will already have been trimmed to the appropriate number of decimals BigDecimal correctAnswer = new BigDecimal(getAnswerExpression(allAnswerText)); // Determine if the acceptable variance is a constant or a % of the answer String varianceString = allAnswerText.substring(allAnswerText.indexOf("|")+1, allAnswerText.indexOf(",")); BigDecimal acceptableVariance = BigDecimal.ZERO; if (varianceString.contains("%")){ double percentage = Double.valueOf(varianceString.substring(0, varianceString.indexOf("%"))); acceptableVariance = correctAnswer.multiply( new BigDecimal(percentage / 100) ); } else { acceptableVariance = new BigDecimal(varianceString); } String userAnswerString = data.getAnswerText().replaceAll(",", "").trim(); BigDecimal userAnswer; try { userAnswer = new BigDecimal(userAnswerString); } catch(NumberFormatException nfe) { return totalScore; // zero because it's not even a number! } //double userAnswer = Double.valueOf(userAnswerString); // this compares the correctAnswer against the userAnsewr BigDecimal answerDiff = (correctAnswer.subtract(userAnswer)); boolean closeEnough = (answerDiff.abs().compareTo(acceptableVariance.abs()) <= 0); if (closeEnough){ totalScore += itemdata.getScore(); } return totalScore; } public double getTotalCorrectScore(ItemGradingData data, Map publishedAnswerHash) { AnswerIfc answer = (AnswerIfc) publishedAnswerHash.get(data.getPublishedAnswerId()); if (answer == null || answer.getScore() == null) return (double) 0; return answer.getScore().doubleValue(); } private void setIsLate(AssessmentGradingData data, PublishedAssessmentIfc pub){ // If submit from timeout popup, we don't record LATE if (data.getSubmitFromTimeoutPopup()) { data.setIsLate( Boolean.valueOf(false)); } else { if (pub.getAssessmentAccessControl() != null && pub.getAssessmentAccessControl().getDueDate() != null && pub.getAssessmentAccessControl().getDueDate().before(new Date())) data.setIsLate(Boolean.TRUE); else data.setIsLate( Boolean.valueOf(false)); } if (data.getForGrade().booleanValue()) data.setStatus( Integer.valueOf(1)); data.setTotalOverrideScore(Double.valueOf(0)); } public void deleteAll(Collection c) { try { PersistenceService.getInstance(). getAssessmentGradingFacadeQueries().deleteAll(c); } catch (Exception e) { e.printStackTrace(); } } /* Note: * assessmentGrading contains set of itemGrading that are not saved in the DB yet */ public void updateAssessmentGradingScore(AssessmentGradingData adata, PublishedAssessmentIfc pub){ try { Set itemGradingSet = adata.getItemGradingSet(); Iterator iter = itemGradingSet.iterator(); double totalAutoScore = 0; double totalOverrideScore = adata.getTotalOverrideScore().doubleValue(); while (iter.hasNext()){ ItemGradingData i = (ItemGradingData)iter.next(); if (i.getAutoScore()!=null) totalAutoScore += i.getAutoScore().doubleValue(); } double oldAutoScore = adata.getTotalAutoScore().doubleValue(); double scoreDifference = totalAutoScore - oldAutoScore; adata.setTotalAutoScore(Double.valueOf(totalAutoScore)); if (Double.compare((totalAutoScore+totalOverrideScore),Double.valueOf("0").doubleValue())<0){ adata.setFinalScore(Double.valueOf("0")); }else{ adata.setFinalScore(Double.valueOf(totalAutoScore+totalOverrideScore)); } saveOrUpdateAssessmentGrading(adata); if (scoreDifference != 0){ notifyGradebookByScoringType(adata, pub); } } catch (GradebookServiceException ge) { ge.printStackTrace(); throw ge; } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } } public void saveOrUpdateAll(Collection c) { try { PersistenceService.getInstance(). getAssessmentGradingFacadeQueries().saveOrUpdateAll(c); } catch (Exception e) { e.printStackTrace(); } } public PublishedAssessmentIfc getPublishedAssessmentByAssessmentGradingId(String id){ PublishedAssessmentIfc pub = null; try { pub = PersistenceService.getInstance(). getAssessmentGradingFacadeQueries().getPublishedAssessmentByAssessmentGradingId(Long.valueOf(id)); } catch (Exception e) { e.printStackTrace(); } return pub; } public PublishedAssessmentIfc getPublishedAssessmentByPublishedItemId(String publishedItemId){ PublishedAssessmentIfc pub = null; try { pub = PersistenceService.getInstance(). getAssessmentGradingFacadeQueries().getPublishedAssessmentByPublishedItemId(Long.valueOf(publishedItemId)); } catch (Exception e) { e.printStackTrace(); } return pub; } public ArrayList getLastItemGradingDataPosition(Long assessmentGradingId, String agentId) { ArrayList results = null; try { results = PersistenceService.getInstance(). getAssessmentGradingFacadeQueries().getLastItemGradingDataPosition(assessmentGradingId, agentId); } catch (Exception e) { e.printStackTrace(); } return results; } public List getPublishedItemIds(Long assessmentGradingId) { List results = null; try { results = PersistenceService.getInstance(). getAssessmentGradingFacadeQueries().getPublishedItemIds(assessmentGradingId); } catch (Exception e) { e.printStackTrace(); } return results; } public HashSet getItemSet(Long publishedAssessmentId, Long sectionId) { HashSet results = null; try { results = PersistenceService.getInstance(). getAssessmentGradingFacadeQueries().getItemSet(publishedAssessmentId, sectionId); } catch (Exception e) { e.printStackTrace(); } return results; } public Long getTypeId(Long itemGradingId) { Long typeId = null; try { typeId = PersistenceService.getInstance(). getAssessmentGradingFacadeQueries().getTypeId(itemGradingId); } catch (Exception e) { e.printStackTrace(); } return typeId; } public boolean fibmatch(String answer, String input, boolean casesensitive) { try { StringBuilder regex_quotebuf = new StringBuilder(); String REGEX = answer.replaceAll("\\*", "|*|"); String[] oneblank = REGEX.split("\\|"); for (int j = 0; j < oneblank.length; j++) { if ("*".equals(oneblank[j])) { regex_quotebuf.append(".+"); } else { regex_quotebuf.append(Pattern.quote(oneblank[j])); } } String regex_quote = regex_quotebuf.toString(); Pattern p; if (casesensitive){ p = Pattern.compile(regex_quote ); } else { p = Pattern.compile(regex_quote,Pattern.CASE_INSENSITIVE|Pattern.UNICODE_CASE); } Matcher m = p.matcher(input); boolean result = m.matches(); return result; } catch (Exception e){ return false; } } public List getAllAssessmentGradingByAgentId(Long publishedAssessmentId, String agentIdString) { List results = null; try { results = PersistenceService.getInstance(). getAssessmentGradingFacadeQueries().getAllAssessmentGradingByAgentId(publishedAssessmentId, agentIdString); } catch (Exception e) { e.printStackTrace(); } return results; } public List<ItemGradingData> getAllItemGradingDataForItemInGrading(Long assesmentGradingId, Long publihsedItemId) { List<ItemGradingData> results = new ArrayList<ItemGradingData>(); results = PersistenceService.getInstance().getAssessmentGradingFacadeQueries().getAllItemGradingDataForItemInGrading(assesmentGradingId, publihsedItemId); return results; } public HashMap getSiteSubmissionCountHash(String siteId) { HashMap results = new HashMap(); try { results = PersistenceService.getInstance(). getAssessmentGradingFacadeQueries().getSiteSubmissionCountHash(siteId); } catch (Exception e) { e.printStackTrace(); } return results; } public HashMap getSiteInProgressCountHash(final String siteId) { HashMap results = new HashMap(); try { results = PersistenceService.getInstance(). getAssessmentGradingFacadeQueries().getSiteInProgressCountHash(siteId); } catch (Exception e) { e.printStackTrace(); } return results; } public int getActualNumberRetake(Long publishedAssessmentId, String agentIdString) { int actualNumberReatke = 0; try { actualNumberReatke = PersistenceService.getInstance(). getAssessmentGradingFacadeQueries().getActualNumberRetake(publishedAssessmentId, agentIdString); } catch (Exception e) { e.printStackTrace(); } return actualNumberReatke; } public HashMap getActualNumberRetakeHash(String agentIdString) { HashMap actualNumberReatkeHash = new HashMap(); try { actualNumberReatkeHash = PersistenceService.getInstance(). getAssessmentGradingFacadeQueries().getActualNumberRetakeHash(agentIdString); } catch (Exception e) { e.printStackTrace(); } return actualNumberReatkeHash; } public HashMap getSiteActualNumberRetakeHash(String siteIdString) { HashMap numberRetakeHash = new HashMap(); try { numberRetakeHash = PersistenceService.getInstance(). getAssessmentGradingFacadeQueries().getSiteActualNumberRetakeHash(siteIdString); } catch (Exception e) { e.printStackTrace(); } return numberRetakeHash; } public List getStudentGradingSummaryData(Long publishedAssessmentId, String agentIdString) { List results = null; try { results = PersistenceService.getInstance(). getAssessmentGradingFacadeQueries().getStudentGradingSummaryData(publishedAssessmentId, agentIdString); } catch (Exception e) { e.printStackTrace(); } return results; } public int getNumberRetake(Long publishedAssessmentId, String agentIdString) { int numberRetake = 0; try { numberRetake = PersistenceService.getInstance(). getAssessmentGradingFacadeQueries().getNumberRetake(publishedAssessmentId, agentIdString); } catch (Exception e) { e.printStackTrace(); } return numberRetake; } public HashMap getNumberRetakeHash(String agentIdString) { HashMap numberRetakeHash = new HashMap(); try { numberRetakeHash = PersistenceService.getInstance(). getAssessmentGradingFacadeQueries().getNumberRetakeHash(agentIdString); } catch (Exception e) { e.printStackTrace(); } return numberRetakeHash; } public HashMap getSiteNumberRetakeHash(String siteIdString) { HashMap siteActualNumberRetakeList = new HashMap(); try { siteActualNumberRetakeList = PersistenceService.getInstance(). getAssessmentGradingFacadeQueries().getSiteNumberRetakeHash(siteIdString); } catch (Exception e) { e.printStackTrace(); } return siteActualNumberRetakeList; } public void saveStudentGradingSummaryData(StudentGradingSummaryIfc studentGradingSummaryData) { try { PersistenceService.getInstance().getAssessmentGradingFacadeQueries().saveStudentGradingSummaryData(studentGradingSummaryData); } catch (Exception e) { e.printStackTrace(); } } public int getLateSubmissionsNumberByAgentId(Long publishedAssessmentId, String agentIdString, Date dueDate) { int numberRetake = 0; try { numberRetake = PersistenceService.getInstance(). getAssessmentGradingFacadeQueries().getLateSubmissionsNumberByAgentId(publishedAssessmentId, agentIdString, dueDate); } catch (Exception e) { e.printStackTrace(); } return numberRetake; } /** * * @param publishedAssessmentId * @param anonymous * @param audioMessage * @param fileUploadMessage * @param noSubmissionMessage * @param showPartAndTotalScoreSpreadsheetColumns * @param poolString * @param partString * @param questionString * @param textString * @param rationaleString * @param itemGradingCommentsString * @param useridMap * @return a list of responses or null if there are none */ public List getExportResponsesData(String publishedAssessmentId, boolean anonymous, String audioMessage, String fileUploadMessage, String noSubmissionMessage, boolean showPartAndTotalScoreSpreadsheetColumns, String poolString, String partString, String questionString, String textString, String rationaleString, String itemGradingCommentsString, Map useridMap) { List list = null; try { list = PersistenceService.getInstance(). getAssessmentGradingFacadeQueries().getExportResponsesData(publishedAssessmentId, anonymous,audioMessage, fileUploadMessage, noSubmissionMessage, showPartAndTotalScoreSpreadsheetColumns, poolString, partString, questionString, textString, rationaleString, itemGradingCommentsString, useridMap); } catch (Exception e) { e.printStackTrace(); } return list; } private void removeUnsubmittedAssessmentGradingData(AssessmentGradingData data){ try { PersistenceService.getInstance(). getAssessmentGradingFacadeQueries().removeUnsubmittedAssessmentGradingData(data); } catch (Exception e) { //e.printStackTrace(); log.error("Exception thrown from removeUnsubmittedAssessmentGradingData" + e.getMessage()); } } public boolean getHasGradingData(Long publishedAssessmentId) { boolean hasGradingData = false; try { hasGradingData = PersistenceService.getInstance(). getAssessmentGradingFacadeQueries().getHasGradingData(publishedAssessmentId); } catch (Exception e) { e.printStackTrace(); } return hasGradingData; } /** * CALCULATED_QUESTION * @param itemGrading * @param item * @return map of calc answers */ private Map<Integer, String> getCalculatedAnswersMap(ItemGradingData itemGrading, ItemDataIfc item) { HashMap<Integer, String> calculatedAnswersMap = new HashMap<Integer, String>(); // return value from extractCalcQAnswersArray is not used, calculatedAnswersMap is populated by this call extractCalcQAnswersArray(calculatedAnswersMap, item, itemGrading.getAssessmentGradingId(), itemGrading.getAgentId()); return calculatedAnswersMap; } /** * extractCalculations() is a utility function for Calculated Questions. It takes * one parameter, which is a block of text, and looks for any calculations * that are encoded in the text. A calculations is enclosed in [[ ]]. * <p>For example, if the passed parameter is <code>{a} + {b} = {{c}}, [[{a}+{b}]]</code>, * the resulting list would contain one entry: a string of "{a}+{b}" * <p>Formulas must contain at least one variable OR parens OR calculation symbol (*-+/) * @param text contents to be searched * @return a list of matching calculations. If no calculations are found, the * list will be empty. */ public List<String> extractCalculations(String text) { List<String> calculations = extractCalculatedQuestionKeyFromItemText(text, CALCQ_CALCULATION_PATTERN); for (Iterator<String> iterator = calculations.iterator(); iterator.hasNext();) { String calc = iterator.next(); if (!StringUtils.containsAny(calc, "{}()+-*/")) { iterator.remove(); } } return calculations; } /** * extractFormulas() is a utility function for Calculated Questions. It takes * one parameter, which is a block of text, and looks for any formula names * that are encoded in the text. A formula name is enclosed in {{ }}. The * formula itself is encoded elsewhere. * <p>For example, if the passed parameter is <code>{a} + {b} = {{c}}</code>, * the resulting list would contain one entry: a string of "c" * <p>Formulas must begin with an alpha, but subsequent character can be * alpha-numeric * @param text contents to be searched * @return a list of matching formula names. If no formulas are found, the * list will be empty. */ public List<String> extractFormulas(String text) { return extractCalculatedQuestionKeyFromItemText(text, CALCQ_FORMULA_PATTERN); } /** * extractVariables() is a utility function for Calculated Questions. It * takes one parameter, which is a block of text, and looks for any variable * names that are encoded in the text. A variable name is enclosed in { }. * The values of the variable are encoded elsewhere. * <p>For example, if the passed parameter is <code>{a} + {b} = {{c}}</code>, * the resulting list would contain two entries: strings of "a" and "b" * <p>Variables must begin with an alpha, but subsequent character can be * alpha-numeric. * <p>Note - a formula, encoded as {{ }}, will not be mistaken for a variable. * @param text content to be searched * @return a list of matching variable names. If no variables are found, the * list will be empty */ public List<String> extractVariables(String text) { return extractCalculatedQuestionKeyFromItemText(text, CALCQ_ANSWER_PATTERN); } /** * extractCalculatedQuestionKeyFromItemText() is a utility function for Calculated Questions. It * takes a block of item text, and uses a pattern to looks for keys * that are encoded in the text. * @param itemText content to be searched * @param identifierPattern pattern to use to do the search * @return a list of matching key values OR empty if none are found */ private List<String> extractCalculatedQuestionKeyFromItemText(String itemText, Pattern identifierPattern) { LinkedHashSet<String> keys = new LinkedHashSet<String>(); if (itemText != null && itemText.trim().length() > 0) { Matcher keyMatcher = identifierPattern.matcher(itemText); while (keyMatcher.find()) { String match = keyMatcher.group(1); keys.add(match); /* // first character before matching group int start = keyMatcher.start(1) - 2; // first character after matching group int end = keyMatcher.end(1) + 1; // first character after the matching group // if matching group is wrapped by {}, it's not what we are looking for (like another key or just some text) if (start < 0 || end >= itemText.length() || itemText.charAt(start) != '{' || itemText.charAt(end) != '}') { keys.add(match); }*/ } } return new ArrayList<String>(keys); } /** * CALCULATED_QUESTION * @param item the item which contains the formula * @param formulaName the name of the formula * @return the actual formula that matches this formula name OR "" (empty string) if it is not found */ private String replaceFormulaNameWithFormula(ItemDataIfc item, String formulaName) { String result = ""; @SuppressWarnings("unchecked") List<ItemTextIfc> items = item.getItemTextArray(); for (ItemTextIfc itemText : items) { if (itemText.getText().equals(formulaName)) { @SuppressWarnings("unchecked") List<AnswerIfc> answers = itemText.getAnswerArray(); for (AnswerIfc answer : answers) { if (itemText.getSequence().equals(answer.getSequence())) { result = answer.getText(); break; } } } } return result; } /** * CALCULATED_QUESTION * Takes the instructions and breaks it into segments, based on the location * of formula names. One formula would give two segments, two formulas gives * three segments, etc. * <p>Note - in this context, it would probably be easier if any variable value * substitutions have occurred before the breakup is done; otherwise, * each segment will need to have substitutions done. * @param instructions string to be broken up * @return the original string, broken up based on the formula name delimiters */ protected List<String> extractInstructionSegments(String instructions) { List<String> segments = new ArrayList<String>(); if (instructions != null && instructions.length() > 0) { String[] results = CALCQ_FORMULA_SPLIT_PATTERN.split(instructions); // only works because all variables and calculations are already replaced for (String part : results) { segments.add(part); } if (segments.size() == 1) { // add in the trailing segment segments.add(""); } /* final String FUNCTION_BEGIN = "{{"; final String FUNCTION_END = "}}"; while (instructions.indexOf(FUNCTION_BEGIN) > -1 && instructions.indexOf(FUNCTION_END) > -1) { String segment = instructions.substring(0, instructions.indexOf(FUNCTION_BEGIN)); instructions = instructions.substring(instructions.indexOf(FUNCTION_END) + FUNCTION_END.length()); segments.add(segment); } segments.add(instructions); */ } return segments; } /** * CALCULATED_QUESTION * applyPrecisionToNumberString() takes a string representation of a number and returns * a string representation of that number, rounded to the specified number of * decimal places, including trimming decimal places if needed. * Will also throw away the extra trailing zeros as well as removing a trailing decimal point. * @param numberStr * @param decimalPlaces * @return processed number string (will never be null or empty string) */ public String applyPrecisionToNumberString(String numberStr, int decimalPlaces) { // Trim off excess decimal points based on decimalPlaces value BigDecimal bd = new BigDecimal(numberStr); bd = bd.setScale(decimalPlaces, BigDecimal.ROUND_HALF_EVEN); String decimal = "."; // TODO handle localized decimal separator? //DecimalFormatSymbols dfs = new DecimalFormatSymbols(Locale); //char dec = dfs.getDecimalFormatSymbols().getDecimalSeparator(); String displayAnswer = bd.toString(); if (displayAnswer.length() > 2 && displayAnswer.contains(decimal)) { if (decimalPlaces == 0) { // Remove ".0" if decimalPlaces == 0 displayAnswer = displayAnswer.replace(decimal+"0", ""); } else { // trim away all the extra 0s from the end of the number if (displayAnswer.endsWith("0")) { displayAnswer = StringUtils.stripEnd(displayAnswer, "0"); } if (displayAnswer.endsWith(decimal)) { displayAnswer = displayAnswer.substring(0, displayAnswer.length() - 1); } } } return displayAnswer; } /** * CALCULATED_QUESTION * calculateFormulaValues() evaluates all formulas referenced in the * instructions. For each formula name it finds, it retrieves the formula * for the name, substitutes the randomized value for the variables, * evaluates the formula to a real answer, and put the answer, along with * the needed precision and decimal places in the returning Map. * @param variables a Map<String, String> of variables, The key is the * variable name, the value is the text representation, after randomization, * of a number in the variable's defined range. * @param item The question itself, which is needed to provide additional * information for called functions * @return a Map<Integer, String>. the Integer is simply the sequence. * Answers are returned in the order that the formulas are found. * The String is the result of the formula, encoded as (value)|(tolerance),(decimal places) * @throws Exception if either the formula expression fails to pass the * Samigo expression parser, which should never happen as this is validated * when the question is saved, or if a divide by zero error occurs. */ private Map<Integer, String> calculateFormulaValues(Map<String, String> variables, ItemDataIfc item) throws Exception { Map<Integer, String> values = new HashMap<Integer, String>(); String instructions = item.getInstruction(); List<String> formulaNames = this.extractFormulas(instructions); for (int i = 0; i < formulaNames.size(); i++) { String formulaName = formulaNames.get(i); String longFormula = replaceFormulaNameWithFormula(item, formulaName); // {a}+{b}|0.1,1 longFormula = defaultVarianceAndDecimal(longFormula); // sets defaults, in case tolerance or precision isn't set String formula = getAnswerExpression(longFormula); // returns just the formula String answerData = getAnswerData(longFormula); // returns just tolerance and precision int decimalPlaces = getAnswerDecimalPlaces(answerData); String substitutedFormula = replaceMappedVariablesWithNumbers(formula,variables); String formulaValue = processFormulaIntoValue(substitutedFormula, decimalPlaces); values.put(i + 1, formulaValue + answerData); // later answerData will be used for scoring } return values; } /** * CALCULATED_QUESTION * This is a busy method. It does three things: * <br>1. It removes the answer expressions ie. {{x+y}} from the question text. This value is * returned in the ArrayList texts. This format is necessary so that input boxes can be * placed in the text where the {{..}}'s appear. * <br>2. It will call methods to swap out the defined variables with randomly generated values * within the ranges defined by the user. * <br>3. It updates the HashMap answerList with the calculated answers in sequence. It will * parse and calculate what each answer needs to be. * <p>Note: If a divide by zero occurs. We change the random values and try again. It gets limited chances to * get valid values and then will return "infinity" as the answer. * @param answerList will enter the method empty and be filled with sequential answers to the question * @return ArrayList of the pieces of text to display surrounding input boxes */ public List<String> extractCalcQAnswersArray(Map<Integer, String> answerList, ItemDataIfc item, Long gradingId, String agentId) { final int MAX_ERROR_TRIES = 100; boolean hasErrors = true; Map<String, String> variableRangeMap = buildVariableRangeMap(item); List<String> instructionSegments = new ArrayList<String>(0); int attemptCount = 1; while (hasErrors && attemptCount <= MAX_ERROR_TRIES) { instructionSegments.clear(); Map<String, String> variablesWithValues = determineRandomValuesForRanges(variableRangeMap,item.getItemId(), gradingId, agentId, attemptCount); try { Map<Integer, String> evaluatedFormulas = calculateFormulaValues(variablesWithValues, item); answerList.putAll(evaluatedFormulas); // replace the variables in the text with values String instructions = item.getInstruction(); instructions = replaceMappedVariablesWithNumbers(instructions, variablesWithValues); // then replace the calculations with values (must happen AFTER the variable replacement) try { instructions = replaceCalculationsWithValues(instructions, 5); // what decimal precision should we use here? // if could not process the calculation into a result then throws IllegalStateException which will be caught below and cause the numbers to regenerate } catch (SamigoExpressionError e1) { log.warn("Samigo calculated item ("+item.getItemId()+") calculation invalid: "+e1.get()); } // only pull out the segments if the formulas worked instructionSegments = extractInstructionSegments(instructions); hasErrors = false; } catch (Exception e) { attemptCount++; } } return instructionSegments; } /** * CALCULATED_QUESTION * This returns the decimal places value in the stored answer data. * @param allAnswerText * @return */ private int getAnswerDecimalPlaces(String allAnswerText) { String answerData = getAnswerData(allAnswerText); int decimalPlaces = Integer.valueOf(answerData.substring(answerData.indexOf(",")+1, answerData.length())); return decimalPlaces; } /** * CALCULATED_QUESTION * This returns the "|2,2" (variance and decimal display) from the stored answer data. * @param allAnswerText * @return */ private String getAnswerData(String allAnswerText) { String answerData = allAnswerText.substring(allAnswerText.indexOf("|"), allAnswerText.length()); return answerData; } /** * CALCULATED_QUESTION * This is just "(x+y)/z" or if values have been added to the expression it's the * calculated value as stored in the answer data. * @param allAnswerText * @return */ private String getAnswerExpression(String allAnswerText) { String answerExpression = allAnswerText.substring(0, allAnswerText.indexOf("|")); return answerExpression; } /** * CALCULATED_QUESTION * Default acceptable variance and decimalPlaces. An answer is defined by an expression * such as {x+y|1,2} if the variance and decimal places are left off. We have to default * them to something. */ private String defaultVarianceAndDecimal(String allAnswerText) { String defaultVariance = "0.001"; String defaultDecimal = "3"; if (!allAnswerText.contains("|")) { if (!allAnswerText.contains(",")) allAnswerText = allAnswerText.concat("|"+defaultVariance+","+defaultDecimal); else allAnswerText = allAnswerText.replace(",","|"+defaultVariance+","); } if (!allAnswerText.contains(",")) allAnswerText = allAnswerText.concat(","+defaultDecimal); return allAnswerText; } /** * CALCULATED_QUESTION * Takes an answer string and checks for the value returned * is NaN or Infinity, indicating a Samigo formula parse error * Returns false if divide by zero is detected. */ public boolean isAnswerValid(String answer) { String INFINITY = "Infinity"; String NaN = "NaN"; if (answer.length() == 0) return false; if (answer.equals(INFINITY)) return false; if (answer.equals(NaN)) return false; return true; } /** * CALCULATED_QUESTION * replaceMappedVariablesWithNumbers() takes a string and substitutes any variable * names found with the value of the variable. Variables look like {a}, the name of * that variable is "a", and the value of that variable is in variablesWithValues * <p>Note - this function comprehends syntax like "5{x}". If "x" is 37, the * result would be "5*37" * @param expression - the string being substituted into * @param variables - Map key is the variable name, value is what will be * substituted into the expression. * @return a string with values substituted. If answerExpression is null, * returns a blank string (i.e ""). If variablesWithValues is null, returns * the original answerExpression */ public String replaceMappedVariablesWithNumbers(String expression, Map<String, String> variables) { if (expression == null) { expression = ""; } if (variables == null) { variables = new HashMap<String, String>(); } for (Map.Entry<String, String> entry : variables.entrySet()) { String name = "{" + entry.getKey() + "}"; String value = entry.getValue(); // not doing string replace or replaceAll because the value being // substituted can change for each occurrence of the variable. int index = expression.indexOf(name); while (index > -1) { String prefix = expression.substring(0, index); String suffix = expression.substring(index + name.length()); String replacementValue = value; // if last character of prefix is a number or the edge of parenthesis, multiply by the variable // if x = 37, 5{x} -> 5*37 // if x = 37 (5+2){x} -> (5+2)*37 (prefix is (5+2) if (prefix.length() > 0 && (Character.isDigit(prefix.charAt(prefix.length() - 1)) || prefix.charAt(prefix.length() - 1) == ')')) { replacementValue = "*" + replacementValue; } // if first character of suffix is a number or the edge of parenthesis, multiply by the variable // if x = 37, {x}5 -> 37*5 // if x = 37, {x}(5+2) -> 37*(5+2) (suffix is (5+2) if (suffix.length() > 0 && (Character.isDigit(suffix.charAt(0)) || suffix.charAt(0) == '(')) { replacementValue = replacementValue + "*"; } // perform substitution, then look for the next instance of current variable expression = prefix + replacementValue + suffix; index = expression.indexOf(name); } } return expression; } /** * CALCULATED_QUESTION * replaceMappedVariablesWithNumbers() takes a string and substitutes any variable * names found with the value of the variable. Variables look like {a}, the name of * that variable is "a", and the value of that variable is in variablesWithValues * <p>Note - this function comprehends syntax like "5{x}". If "x" is 37, the * result would be "5*37" * @param expression - the string which will be scanned for calculations * @return the input string with calculations replaced with number values. If answerExpression is null, * returns a blank string (i.e "") and if no calculations are found then original string is returned. * @throws IllegalStateException if the formula value cannot be calculated * @throws SamigoExpressionError if the formula cannot be parsed */ public String replaceCalculationsWithValues(String expression, int decimalPlaces) throws SamigoExpressionError { if (StringUtils.isEmpty(expression)) { expression = ""; } else { Matcher keyMatcher = CALCQ_CALCULATION_PATTERN.matcher(expression); ArrayList<String> toReplace = new ArrayList<String>(); while (keyMatcher.find()) { String match = keyMatcher.group(1); toReplace.add(match); // should be the formula } if (toReplace.size() > 0) { for (String formula : toReplace) { String replace = CALCULATION_OPEN+formula+CALCULATION_CLOSE; String formulaValue = processFormulaIntoValue(formula, decimalPlaces); expression = StringUtils.replace(expression, replace, formulaValue); } } } return expression; } /** * CALCULATED_QUESTION * Process a single formula into a final string representing the calculated value of the formula * * @param formula the formula to process (e.g. 1 * 2 + 3 - 4), All variable replacement must have already happened * @param decimalPlaces number of decimals to include in the final output * @return the value of the formula OR empty string if there is nothing to process * @throws IllegalStateException if the formula value cannot be calculated (typically caused by 0 divisors and the like) * @throws SamigoExpressionError if the formula cannot be parsed */ public String processFormulaIntoValue(String formula, int decimalPlaces) throws SamigoExpressionError { String value = ""; if (StringUtils.isEmpty(formula)) { value = ""; } else { if (decimalPlaces < 0) { decimalPlaces = 0; } formula = cleanFormula(formula); SamigoExpressionParser parser = new SamigoExpressionParser(); // this will turn the expression into a number in string form String numericString = parser.parse(formula, decimalPlaces+1); if (this.isAnswerValid(numericString)) { numericString = applyPrecisionToNumberString(numericString, decimalPlaces); value = numericString; } else { throw new IllegalStateException("Invalid calculation formula ("+formula+") result ("+numericString+"), result could not be calculated"); } } return value; } /** * Cleans up formula text so that whitespaces are normalized or removed * @param formula formula with variables or without * @return the cleaned formula */ public static String cleanFormula(String formula) { if (StringUtils.isEmpty(formula)) { formula = ""; } else { formula = StringUtils.trimToEmpty(formula).replaceAll("\\s+", " "); } return formula; } /** * isNegativeSqrt() looks at the incoming expression and looks specifically * to see if it executes the SQRT function. If it does, it evaluates it. If * it has an error, it assumes that the SQRT function tried to evaluate a * negative number and evaluated to NaN. * <p>Note - the incoming expression should have no variables. They should * have been replaced before this function was called * @param expression a mathematical formula, with all variables replaced by * real values, to be evaluated * @return true if the function uses the SQRT function, and the SQRT function * evaluates as an error; else false * @throws SamigoExpressionError if the evaluation of the SQRT function throws * some other parse error */ public boolean isNegativeSqrt(String expression) throws SamigoExpressionError { Pattern sqrt = Pattern.compile("sqrt\\s*\\("); boolean isNegative = false; if (expression == null) { expression = ""; } expression = expression.toLowerCase(); Matcher matcher = sqrt.matcher(expression); while (matcher.find()) { int x = matcher.end(); int p = 1; // Parentheses left to match int len = expression.length(); while (p > 0 && x < len) { if (expression.charAt(x) == ')') { --p; } else if (expression.charAt(x) == '(') { ++p; } ++x; } if (p == 0) { String sqrtExpression = expression.substring(matcher.start(), x); SamigoExpressionParser parser = new SamigoExpressionParser(); String numericAnswerString = parser.parse(sqrtExpression); if (!isAnswerValid(numericAnswerString)) { isNegative = true; break; // finding 1 invalid one is enough } } } return isNegative; } /** * CALCULATED_QUESTION * Takes a map of ranges and randomly chooses values for those ranges and stores them in a new map. */ public Map<String, String> determineRandomValuesForRanges(Map<String, String> variableRangeMap, long itemId, long gradingId, String agentId, int validAnswersAttemptCount) { Map<String, String> variableValueMap = new HashMap<String, String>(); // seed random number generator long seed = getCalcuatedQuestionSeed(itemId, gradingId, agentId, validAnswersAttemptCount); Random generator = new Random(seed); Iterator<Map.Entry<String, String>> i = variableRangeMap.entrySet().iterator(); while(i.hasNext()) { Map.Entry<String, String>entry = i.next(); String delimRange = entry.getValue().toString(); // ie. "-100|100,2" double minVal = Double.valueOf(delimRange.substring(0, delimRange.indexOf('|'))); double maxVal = Double.valueOf(delimRange.substring(delimRange.indexOf('|')+1, delimRange.indexOf(','))); int decimalPlaces = Integer.valueOf(delimRange.substring(delimRange.indexOf(',')+1, delimRange.length())); // This line does the magic of creating the random variable value within the range. Double randomValue = minVal + (maxVal - minVal) * generator.nextDouble(); // Trim off excess decimal points based on decimalPlaces value BigDecimal bd = new BigDecimal(randomValue); bd = bd.setScale(decimalPlaces,BigDecimal.ROUND_HALF_UP); randomValue = bd.doubleValue(); String displayNumber = randomValue.toString(); // Remove ".0" if decimalPlaces ==0 if (decimalPlaces == 0) { displayNumber = displayNumber.replace(".0", ""); } variableValueMap.put(entry.getKey(), displayNumber); } return variableValueMap; } /** * CALCULATED_QUESTION * Accepts an ItemDataIfc and returns a HashMap with the pairs of * variable names and variable ranges. */ private Map<String, String> buildVariableRangeMap(ItemDataIfc item) { HashMap<String, String> variableRangeMap = new HashMap<String, String>(); String instructions = item.getInstruction(); List<String> variables = this.extractVariables(instructions); // Loop through each VarName @SuppressWarnings("unchecked") List<ItemTextIfc> itemTextList = item.getItemTextArraySorted(); for (ItemTextIfc varName : itemTextList) { // only look at variables for substitution, ignore formulas if (variables.contains(varName.getText())) { @SuppressWarnings("unchecked") List<AnswerIfc> answerList = varName.getAnswerArray(); for (AnswerIfc range : answerList) { if (!(range.getLabel() == null) ) { // answer records and variable records are in the same set if (range.getSequence().equals(varName.getSequence()) && range.getText().contains("|")) { variableRangeMap.put(varName.getText(), range.getText()); } } } } } return variableRangeMap; } /** * CALCULATED_QUESTION * Make seed by combining user id, item (question) id, grading (submission) id, and attempt count (due to div by 0) */ private long getCalcuatedQuestionSeed(long itemId, long gradingId, String agentId, int validAnswersAttemptCount) { long userSeed = (long) agentId.hashCode(); return userSeed * itemId * gradingId * validAnswersAttemptCount; } /** * CALCULATED_QUESTION * Simple to check to see if this is a calculated question. It's used in storeGrades() to see if the sort is necessary. */ private boolean isCalcQuestion(List tempItemGradinglist, HashMap publishedItemHash) { if (tempItemGradinglist == null) return false; if (tempItemGradinglist.size() == 0) return false; Iterator iter = tempItemGradinglist.iterator(); ItemGradingData itemCheck = (ItemGradingData) iter.next(); Long itemId = itemCheck.getPublishedItemId(); ItemDataIfc item = (ItemDataIfc) publishedItemHash.get(itemId); if (item.getTypeId().equals(TypeIfc.CALCULATED_QUESTION)) { return true; } return false; } public ArrayList getHasGradingDataAndHasSubmission(Long publishedAssessmentId) { ArrayList al = new ArrayList(); try { al = PersistenceService.getInstance(). getAssessmentGradingFacadeQueries().getHasGradingDataAndHasSubmission(publishedAssessmentId); } catch (Exception e) { e.printStackTrace(); } return al; } public String getFileName(Long itemGradingId, String agentId, String filename) { String name = ""; try { name = PersistenceService.getInstance(). getAssessmentGradingFacadeQueries().getFilename(itemGradingId, agentId, filename); } catch (Exception e) { e.printStackTrace(); } return name; } public List getUpdatedAssessmentList(String agentId, String siteId) { List list = null; try { list = PersistenceService.getInstance(). getAssessmentGradingFacadeQueries().getUpdatedAssessmentList(agentId, siteId); } catch (Exception e) { e.printStackTrace(); } return list; } public List getSiteNeedResubmitList(String siteId) { List list = null; try { list = PersistenceService.getInstance(). getAssessmentGradingFacadeQueries().getSiteNeedResubmitList(siteId); } catch (Exception e) { e.printStackTrace(); } return list; } public void autoSubmitAssessments() { try { PersistenceService.getInstance(). getAssessmentGradingFacadeQueries().autoSubmitAssessments(); } catch (Exception e) { e.printStackTrace(); } } public ItemGradingAttachment createItemGradingAttachment( ItemGradingData itemGrading, String resourceId, String filename, String protocol) { ItemGradingAttachment attachment = null; try { attachment = PersistenceService.getInstance(). getAssessmentGradingFacadeQueries().createItemGradingtAttachment(itemGrading, resourceId, filename, protocol); } catch (Exception e) { e.printStackTrace(); } return attachment; } public void removeItemGradingAttachment(String attachmentId) { PersistenceService.getInstance().getAssessmentGradingFacadeQueries() .removeItemGradingAttachment(Long.valueOf(attachmentId)); } public void saveOrUpdateAttachments(List list) { PersistenceService.getInstance().getAssessmentGradingFacadeQueries() .saveOrUpdateAttachments(list); } public HashMap getInProgressCounts(String siteId) { return PersistenceService.getInstance().getAssessmentGradingFacadeQueries(). getInProgressCounts(siteId); } public HashMap getSubmittedCounts(String siteId) { return PersistenceService.getInstance().getAssessmentGradingFacadeQueries(). getSubmittedCounts(siteId); } public void completeItemGradingData(AssessmentGradingData assessmentGradingData) { PersistenceService.getInstance().getAssessmentGradingFacadeQueries(). completeItemGradingData(assessmentGradingData); } /** * This grades multiple choice and true false questions. Since * multiple choice/multiple select has a separate ItemGradingData for * each choice, they're graded the same way the single choice are. * BUT since we have Partial Credit stuff around we have to have a separate method here --mustansar * Choices should be given negative score values if one wants them * to lose points for the wrong choice. */ public double getAnswerScoreMCQ(ItemGradingData data, Map publishedAnswerHash) { AnswerIfc answer = (AnswerIfc) publishedAnswerHash.get(data.getPublishedAnswerId()); if (answer == null || answer.getScore() == null) { return 0d; } else if (answer.getIsCorrect().booleanValue()){ // instead of using answer score Item score needs to be used here return (answer.getItem().getScore().doubleValue()); //--mustansar } return (answer.getItem().getScore().doubleValue()*answer.getPartialCredit().doubleValue())/100d; } /** * Reoder a map of EMI scores * @param emiScoresMap * @return */ private Map<Long, Map<Long, Map<Long, EMIScore>>> reorderEMIScoreMap(Map<Long, Map<Long,Set<EMIScore>>> emiScoresMap){ Map<Long, Map<Long, Map<Long, EMIScore>>> scoresMap = new HashMap<Long, Map<Long, Map<Long, EMIScore>>>(); for(Map<Long,Set<EMIScore>> emiItemScoresMap: emiScoresMap.values()){ for(Set<EMIScore> scoreSet: emiItemScoresMap.values()){ for(EMIScore s: scoreSet){ Map<Long, Map<Long, EMIScore>> scoresItem = scoresMap.get(s.itemId); if(scoresItem == null){ scoresItem = new HashMap<Long, Map<Long, EMIScore>>(); scoresMap.put(s.itemId, scoresItem); } Map<Long, EMIScore> scoresItemText = scoresItem.get(s.itemTextId); if(scoresItemText == null){ scoresItemText = new HashMap<Long, EMIScore>(); scoresItem.put(s.itemTextId, scoresItemText); } scoresItemText.put(s.answerId, s); } } } return scoresMap; } /** * hasDistractors looks at an itemData object for a Matching question and determines * if all of the choices have correct matches or not. * @param item * @return true if any of the choices do not have a correct answer (a distractor choice), or false * if all choices have at least one correct answer */ public boolean hasDistractors(ItemDataIfc item) { boolean hasDistractor = false; Iterator<ItemTextIfc> itemIter = item.getItemTextArraySorted().iterator(); while (itemIter.hasNext()) { ItemTextIfc curItem = itemIter.next(); if (isDistractor(curItem)) { hasDistractor = true; break; } } return hasDistractor; } /** * determines if the passed parameter is a distractor * <p>For ItemTextIfc objects that hold data for matching type questions, a distractor * is a choice that has no valid matches (i.e. no correct answers). This function returns * if this ItemTextIfc object has any correct answers * @param itemText * @return true if itemtext has no correct answers (a distrator) or false if itemtext has at least * one correct answer */ public boolean isDistractor(ItemTextIfc itemText) { // look for items that do not have any correct answers boolean hasCorrectAnswer = false; List<AnswerIfc> answers = itemText.getAnswerArray(); Iterator<AnswerIfc> answerIter = answers.iterator(); while (answerIter.hasNext()) { AnswerIfc answer = answerIter.next(); if (answer.getIsCorrect() != null && answer.getIsCorrect().booleanValue()) { hasCorrectAnswer = true; break; } } return !hasCorrectAnswer; } public List getUnSubmittedAssessmentGradingDataList(Long publishedAssessmentId, String agentIdString) { return PersistenceService.getInstance().getAssessmentGradingFacadeQueries(). getUnSubmittedAssessmentGradingDataList(publishedAssessmentId, agentIdString); } } /** * A EMI score * @author jsmith * */ class EMIScore implements Comparable<EMIScore>{ long itemId = 0L; long itemTextId = 0L; long answerId = 0L; boolean correct = false; double score = 0.0; double effectiveScore = 0.0; /** * Create an EMI Score object * @param itemId * @param itemTextId * @param answerId * @param correct * @param score */ public EMIScore(Long itemId, Long itemTextId, Long answerId, boolean correct, Double score){ this.itemId = itemId == null? 0L : itemId.longValue(); this.itemTextId = itemTextId == null? 0L : itemTextId.longValue(); this.answerId = answerId == null? 0L : answerId.longValue(); this.correct = correct; this.score = score == null? 0L : score.doubleValue(); } public int compareTo(EMIScore o) { //we want the correct higher scores first if(correct == o.correct){ int c = Double.compare(o.score, score); if (c == 0){ if(itemId != o.itemId){ return (int)(itemId - o.itemId); } if(itemTextId != o.itemTextId){ return (int)(itemTextId - o.itemTextId); } if(answerId != o.answerId){ return (int)(answerId - o.answerId); } return hashCode() - o.hashCode(); }else{ return c; } }else{ return correct?-1:1; } } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (int)itemId; result = prime * result + (int)itemTextId; result = prime * result + (int)answerId; return result; } @Override public boolean equals(Object obj) { if (obj == null) return false; if (this == obj) return true; if (getClass() != obj.getClass()){ return false; } EMIScore other = (EMIScore) obj; return (itemId == other.itemId && itemTextId == other.itemTextId && answerId == other.answerId); } @Override public String toString() { return itemId + ":" + itemTextId + ":" + answerId + "(" + correct + ":" + score + ":" + effectiveScore + ")"; } }
samigo/samigo-services/src/java/org/sakaiproject/tool/assessment/services/GradingService.java
/********************************************************************************** * $URL$ * $Id$ *********************************************************************************** * * Copyright (c) 2004, 2005, 2006, 2007, 2008, 2009 The Sakai Foundation * * Licensed under the Educational Community 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.opensource.org/licenses/ECL-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.sakaiproject.tool.assessment.services; import java.math.BigDecimal; import java.text.DecimalFormat; import java.text.NumberFormat; import java.text.ParseException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Map.Entry; import java.util.Random; import java.util.Set; import java.util.StringTokenizer; import java.util.TreeSet; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.commons.math.complex.Complex; import org.apache.commons.math.complex.ComplexFormat; import org.apache.commons.math.util.MathUtils; import org.sakaiproject.event.cover.EventTrackingService; import org.sakaiproject.service.gradebook.shared.GradebookExternalAssessmentService; import org.sakaiproject.spring.SpringBeanLocator; import org.sakaiproject.tool.assessment.data.dao.grading.AssessmentGradingData; import org.sakaiproject.tool.assessment.data.dao.grading.ItemGradingAttachment; import org.sakaiproject.tool.assessment.data.dao.grading.ItemGradingData; import org.sakaiproject.tool.assessment.data.dao.grading.MediaData; import org.sakaiproject.tool.assessment.data.ifc.assessment.AnswerIfc; import org.sakaiproject.tool.assessment.data.ifc.assessment.AssessmentIfc; import org.sakaiproject.tool.assessment.data.ifc.assessment.EvaluationModelIfc; import org.sakaiproject.tool.assessment.data.ifc.assessment.ItemDataIfc; import org.sakaiproject.tool.assessment.data.ifc.assessment.ItemMetaDataIfc; import org.sakaiproject.tool.assessment.data.ifc.assessment.ItemTextIfc; import org.sakaiproject.tool.assessment.data.ifc.assessment.PublishedAssessmentIfc; import org.sakaiproject.tool.assessment.data.ifc.grading.StudentGradingSummaryIfc; import org.sakaiproject.tool.assessment.data.ifc.shared.TypeIfc; import org.sakaiproject.tool.assessment.facade.AgentFacade; import org.sakaiproject.tool.assessment.facade.GradebookFacade; import org.sakaiproject.tool.assessment.facade.TypeFacade; import org.sakaiproject.tool.assessment.facade.TypeFacadeQueriesAPI; import org.sakaiproject.tool.assessment.integration.context.IntegrationContextFactory; import org.sakaiproject.tool.assessment.integration.helper.ifc.GradebookServiceHelper; import org.sakaiproject.tool.assessment.services.assessment.PublishedAssessmentService; import org.sakaiproject.tool.assessment.util.SamigoExpressionError; import org.sakaiproject.tool.assessment.util.SamigoExpressionParser; /** * The GradingService calls the back end to get/store grading information. * It also calculates scores for autograded types. */ public class GradingService { /** * Key for a complext numeric answer e.g. 9+9i */ public static final String ANSWER_TYPE_COMPLEX = "COMPLEX"; /** * key for a real number representation e.g 1 or 10E5 */ public static final String ANSWER_TYPE_REAL = "REAL"; // CALCULATED_QUESTION final String OPEN_BRACKET = "\\{"; final String CLOSE_BRACKET = "\\}"; final String CALCULATION_OPEN = "[["; // not regex safe final String CALCULATION_CLOSE = "]]"; // not regex safe /** * regular expression for matching the contents of a variable or formula name * in Calculated Questions * NOTE: Old regex: ([\\w\\s\\.\\-\\^\\$\\!\\&\\@\\?\\*\\%\\(\\)\\+=#`~&:;|,/<>\\[\\]\\\\\\'\"]+?) * was way too complicated. */ final String CALCQ_VAR_FORM_NAME = "[a-zA-Z][^\\{\\}]*?"; // non-greedy (must start wtih alpha) final String CALCQ_VAR_FORM_NAME_EXPRESSION = "("+CALCQ_VAR_FORM_NAME+")"; // variable match - (?<!\{)\{([^\{\}]+?)\}(?!\}) - means any sequence inside braces without a braces before or after final Pattern CALCQ_ANSWER_PATTERN = Pattern.compile("(?<!\\{)" + OPEN_BRACKET + CALCQ_VAR_FORM_NAME_EXPRESSION + CLOSE_BRACKET + "(?!\\})"); final Pattern CALCQ_FORMULA_PATTERN = Pattern.compile(OPEN_BRACKET + OPEN_BRACKET + CALCQ_VAR_FORM_NAME_EXPRESSION + CLOSE_BRACKET + CLOSE_BRACKET); final Pattern CALCQ_FORMULA_SPLIT_PATTERN = Pattern.compile("(" + OPEN_BRACKET + OPEN_BRACKET + CALCQ_VAR_FORM_NAME + CLOSE_BRACKET + CLOSE_BRACKET + ")"); final Pattern CALCQ_CALCULATION_PATTERN = Pattern.compile("\\[\\[([^\\[\\]]+?)\\]\\]?"); // non-greedy private static Log log = LogFactory.getLog(GradingService.class); /** * Get all scores for a published assessment from the back end. */ public ArrayList getTotalScores(String publishedId, String which) { ArrayList results = null; try { results = new ArrayList(PersistenceService.getInstance(). getAssessmentGradingFacadeQueries().getTotalScores(publishedId, which)); } catch (Exception e) { e.printStackTrace(); } return results; } public ArrayList getTotalScores(String publishedId, String which, boolean getSubmittedOnly) { ArrayList results = null; try { results = new ArrayList(PersistenceService.getInstance(). getAssessmentGradingFacadeQueries().getTotalScores(publishedId, which, getSubmittedOnly)); } catch (Exception e) { e.printStackTrace(); } return results; } /** * Get all submissions for a published assessment from the back end. */ public List getAllSubmissions(String publishedId) { List results = null; try { results = PersistenceService.getInstance(). getAssessmentGradingFacadeQueries().getAllSubmissions(publishedId); } catch (Exception e) { e.printStackTrace(); } return results; } public List getAllAssessmentGradingData(Long publishedId) { List results = null; try { results = PersistenceService.getInstance(). getAssessmentGradingFacadeQueries().getAllAssessmentGradingData(publishedId); } catch (Exception e) { e.printStackTrace(); } return results; } public ArrayList getHighestAssessmentGradingList(Long publishedId) { ArrayList results = null; try { results = new ArrayList(PersistenceService.getInstance(). getAssessmentGradingFacadeQueries().getHighestAssessmentGradingList(publishedId)); } catch (Exception e) { e.printStackTrace(); } return results; } public List getHighestSubmittedOrGradedAssessmentGradingList(Long publishedId) { ArrayList results = null; try { results = new ArrayList(PersistenceService.getInstance(). getAssessmentGradingFacadeQueries().getHighestSubmittedOrGradedAssessmentGradingList(publishedId)); } catch (Exception e) { e.printStackTrace(); } return results; } public ArrayList getLastAssessmentGradingList(Long publishedId) { ArrayList results = null; try { results = new ArrayList(PersistenceService.getInstance(). getAssessmentGradingFacadeQueries().getLastAssessmentGradingList(publishedId)); } catch (Exception e) { e.printStackTrace(); } return results; } public List getLastSubmittedAssessmentGradingList(Long publishedId) { List results = null; try { results = PersistenceService.getInstance(). getAssessmentGradingFacadeQueries().getLastSubmittedAssessmentGradingList(publishedId); } catch (Exception e) { e.printStackTrace(); } return results; } public List getLastSubmittedOrGradedAssessmentGradingList(Long publishedId) { List results = null; try { results = PersistenceService.getInstance(). getAssessmentGradingFacadeQueries().getLastSubmittedOrGradedAssessmentGradingList(publishedId); } catch (Exception e) { e.printStackTrace(); } return results; } public void saveTotalScores(ArrayList gdataList, PublishedAssessmentIfc pub) { //log.debug("**** GradingService: saveTotalScores"); try { AssessmentGradingData gdata = null; if (gdataList.size()>0) gdata = (AssessmentGradingData) gdataList.get(0); else return; Integer scoringType = getScoringType(pub); ArrayList oldList = getAssessmentGradingsByScoringType( scoringType, gdata.getPublishedAssessmentId()); for (int i=0; i<gdataList.size(); i++){ AssessmentGradingData ag = (AssessmentGradingData)gdataList.get(i); saveOrUpdateAssessmentGrading(ag); EventTrackingService.post(EventTrackingService.newEvent("sam.total.score.update", "siteId=" + AgentFacade.getCurrentSiteId() + ", gradedBy=" + AgentFacade.getAgentString() + ", assessmentGradingId=" + ag.getAssessmentGradingId() + ", totalAutoScore=" + ag.getTotalAutoScore() + ", totalOverrideScore=" + ag.getTotalOverrideScore() + ", FinalScore=" + ag.getFinalScore() + ", comments=" + ag.getComments() , true)); } // no need to notify gradebook if this submission is not for grade // we only want to notify GB when there are changes ArrayList newList = getAssessmentGradingsByScoringType( scoringType, gdata.getPublishedAssessmentId()); ArrayList l = getListForGradebookNotification(newList, oldList); notifyGradebook(l, pub); } catch (GradebookServiceException ge) { log.error("GradebookServiceException" + ge); throw ge; } } private ArrayList getListForGradebookNotification( ArrayList newList, ArrayList oldList){ ArrayList l = new ArrayList(); HashMap h = new HashMap(); for (int i=0; i<oldList.size(); i++){ AssessmentGradingData ag = (AssessmentGradingData)oldList.get(i); h.put(ag.getAssessmentGradingId(), ag); } for (int i=0; i<newList.size(); i++){ AssessmentGradingData a = (AssessmentGradingData) newList.get(i); Object o = h.get(a.getAssessmentGradingId()); if (o == null){ // this does not exist in old list, so include it for update l.add(a); } else{ // if new is different from old, include it for update AssessmentGradingData b = (AssessmentGradingData) o; if ((a.getFinalScore()!=null && b.getFinalScore()!=null) && !a.getFinalScore().equals(b.getFinalScore())) l.add(a); } } return l; } public ArrayList getAssessmentGradingsByScoringType( Integer scoringType, Long publishedAssessmentId){ List l = null; // get the list of highest score if ((scoringType).equals(EvaluationModelIfc.HIGHEST_SCORE)){ l = getHighestSubmittedOrGradedAssessmentGradingList(publishedAssessmentId); } // get the list of last score else if ((scoringType).equals(EvaluationModelIfc.LAST_SCORE)) { l = getLastSubmittedOrGradedAssessmentGradingList(publishedAssessmentId); } else { l = getTotalScores(publishedAssessmentId.toString(), "3", false); } return new ArrayList(l); } public Integer getScoringType(PublishedAssessmentIfc pub){ Integer scoringType = null; EvaluationModelIfc e = pub.getEvaluationModel(); if ( e!=null ){ scoringType = e.getScoringType(); } return scoringType; } private boolean updateGradebook(AssessmentGradingData data, PublishedAssessmentIfc pub){ // no need to notify gradebook if this submission is not for grade boolean forGrade = (Boolean.TRUE).equals(data.getForGrade()); boolean toGradebook = false; EvaluationModelIfc e = pub.getEvaluationModel(); if ( e!=null ){ String toGradebookString = e.getToGradeBook(); toGradebook = toGradebookString.equals(EvaluationModelIfc.TO_DEFAULT_GRADEBOOK.toString()); } return (forGrade && toGradebook); } private void notifyGradebook(ArrayList l, PublishedAssessmentIfc pub){ for (int i=0; i<l.size(); i++){ notifyGradebook((AssessmentGradingData)l.get(i), pub); } } /** * Get the score information for each item from the assessment score. */ public HashMap getItemScores(Long publishedId, Long itemId, String which) { try { return (HashMap) PersistenceService.getInstance(). getAssessmentGradingFacadeQueries() .getItemScores(publishedId, itemId, which); } catch (Exception e) { e.printStackTrace(); return new HashMap(); } } public HashMap getItemScores(Long publishedId, Long itemId, String which, boolean loadItemGradingAttachment) { try { return (HashMap) PersistenceService.getInstance(). getAssessmentGradingFacadeQueries() .getItemScores(publishedId, itemId, which, loadItemGradingAttachment); } catch (Exception e) { e.printStackTrace(); return new HashMap(); } } public HashMap getItemScores(Long itemId, List scores, boolean loadItemGradingAttachment) { try { return (HashMap) PersistenceService.getInstance(). getAssessmentGradingFacadeQueries() .getItemScores(itemId, scores, loadItemGradingAttachment); } catch (Exception e) { e.printStackTrace(); return new HashMap(); } } /** * Get the last set of itemgradingdata for a student per assessment */ public HashMap getLastItemGradingData(String publishedId, String agentId) { try { return (HashMap) PersistenceService.getInstance(). getAssessmentGradingFacadeQueries() .getLastItemGradingData(Long.valueOf(publishedId), agentId); } catch (Exception e) { e.printStackTrace(); return new HashMap(); } } /** * Get the grading data for a given submission */ public HashMap getStudentGradingData(String assessmentGradingId) { try { return (HashMap) PersistenceService.getInstance(). getAssessmentGradingFacadeQueries() .getStudentGradingData(assessmentGradingId); } catch (Exception e) { e.printStackTrace(); return new HashMap(); } } /** * Get the last submission for a student per assessment */ public HashMap getSubmitData(String publishedId, String agentId, Integer scoringoption, String assessmentGradingId) { try { Long gradingId = null; if (assessmentGradingId != null) gradingId = Long.valueOf(assessmentGradingId); return (HashMap) PersistenceService.getInstance(). getAssessmentGradingFacadeQueries().getSubmitData(Long.valueOf(publishedId), agentId, scoringoption, gradingId); } catch (Exception e) { e.printStackTrace(); return new HashMap(); } } public String getTextForId(Long typeId) { TypeFacadeQueriesAPI typeFacadeQueries = PersistenceService.getInstance().getTypeFacadeQueries(); TypeFacade type = typeFacadeQueries.getTypeFacadeById(typeId); return (type.getKeyword()); } public int getSubmissionSizeOfPublishedAssessment(String publishedAssessmentId) { try{ return PersistenceService.getInstance(). getAssessmentGradingFacadeQueries() .getSubmissionSizeOfPublishedAssessment(Long.valueOf( publishedAssessmentId)); } catch(Exception e) { e.printStackTrace(); return 0; } } public Long saveMedia(byte[] media, String mimeType){ return PersistenceService.getInstance().getAssessmentGradingFacadeQueries(). saveMedia(media, mimeType); } public Long saveMedia(MediaData mediaData){ return PersistenceService.getInstance().getAssessmentGradingFacadeQueries(). saveMedia(mediaData); } public MediaData getMedia(String mediaId){ return PersistenceService.getInstance().getAssessmentGradingFacadeQueries(). getMedia(Long.valueOf(mediaId)); } public ArrayList getMediaArray(String itemGradingId){ return PersistenceService.getInstance().getAssessmentGradingFacadeQueries(). getMediaArray(Long.valueOf(itemGradingId)); } public ArrayList getMediaArray2(String itemGradingId){ return PersistenceService.getInstance().getAssessmentGradingFacadeQueries(). getMediaArray2(Long.valueOf(itemGradingId)); } public ArrayList getMediaArray(ItemGradingData i){ return PersistenceService.getInstance().getAssessmentGradingFacadeQueries(). getMediaArray(i); } public HashMap getMediaItemGradingHash(Long assessmentGradingId) { return PersistenceService.getInstance().getAssessmentGradingFacadeQueries(). getMediaItemGradingHash(assessmentGradingId); } public List<MediaData> getMediaArray(String publishedId, String publishItemId, String which){ return PersistenceService.getInstance().getAssessmentGradingFacadeQueries(). getMediaArray(Long.valueOf(publishedId), Long.valueOf(publishItemId), which); } public ItemGradingData getLastItemGradingDataByAgent(String publishedItemId, String agentId) { try { return PersistenceService.getInstance().getAssessmentGradingFacadeQueries(). getLastItemGradingDataByAgent(Long.valueOf(publishedItemId), agentId); } catch (Exception e) { e.printStackTrace(); return null; } } public ItemGradingData getItemGradingData(String assessmentGradingId, String publishedItemId) { try { return PersistenceService.getInstance().getAssessmentGradingFacadeQueries(). getItemGradingData(Long.valueOf(assessmentGradingId), Long.valueOf(publishedItemId)); } catch (Exception e) { e.printStackTrace(); return null; } } public AssessmentGradingData load(String assessmentGradingId) { return load(assessmentGradingId, true); } public AssessmentGradingData load(String assessmentGradingId, boolean loadGradingAttachment) { try{ return PersistenceService.getInstance().getAssessmentGradingFacadeQueries(). load(Long.valueOf(assessmentGradingId), loadGradingAttachment); } catch(Exception e) { log.error(e); throw new RuntimeException(e); } } public ItemGradingData getItemGrading(String itemGradingId) { try{ return PersistenceService.getInstance().getAssessmentGradingFacadeQueries(). getItemGrading(Long.valueOf(itemGradingId)); } catch(Exception e) { log.error(e); throw new Error(e); } } public AssessmentGradingData getLastAssessmentGradingByAgentId(String publishedAssessmentId, String agentIdString) { try{ return PersistenceService.getInstance().getAssessmentGradingFacadeQueries(). getLastAssessmentGradingByAgentId(Long.valueOf(publishedAssessmentId), agentIdString); } catch(Exception e) { log.error(e); throw new RuntimeException(e); } } public AssessmentGradingData getLastSavedAssessmentGradingByAgentId(String publishedAssessmentId, String agentIdString) { try{ return PersistenceService.getInstance().getAssessmentGradingFacadeQueries(). getLastSavedAssessmentGradingByAgentId(Long.valueOf(publishedAssessmentId), agentIdString); } catch(Exception e) { log.error(e); throw new RuntimeException(e); } } public AssessmentGradingData getLastSubmittedAssessmentGradingByAgentId(String publishedAssessmentId, String agentIdString, String assessmentGradingId) { AssessmentGradingData assessmentGranding = null; try { if (assessmentGradingId != null) { assessmentGranding = PersistenceService.getInstance().getAssessmentGradingFacadeQueries(). getLastSubmittedAssessmentGradingByAgentId(Long.valueOf(publishedAssessmentId), agentIdString, Long.valueOf(assessmentGradingId)); } else { assessmentGranding = PersistenceService.getInstance().getAssessmentGradingFacadeQueries(). getLastSubmittedAssessmentGradingByAgentId(Long.valueOf(publishedAssessmentId), agentIdString, null); } } catch(Exception e) { log.error(e); throw new RuntimeException(e); } return assessmentGranding; } public void saveItemGrading(ItemGradingData item) { try { PersistenceService.getInstance(). getAssessmentGradingFacadeQueries().saveItemGrading(item); } catch (Exception e) { e.printStackTrace(); } } public void saveOrUpdateAssessmentGrading(AssessmentGradingData assessment) { try { /* // Comment out the whole IF section because the only thing we do here is to // update the itemGradingSet. However, this update is redundant as it will // be updated in saveOrUpdateAssessmentGrading(assessment). if (assessment.getAssessmentGradingId()!=null && assessment.getAssessmentGradingId().longValue()>0){ //1. if assessmentGrading contain itemGrading, we want to insert/update itemGrading first Set itemGradingSet = assessment.getItemGradingSet(); Iterator iter = itemGradingSet.iterator(); while (iter.hasNext()) { ItemGradingData itemGradingData = (ItemGradingData) iter.next(); log.debug("date = " + itemGradingData.getSubmittedDate()); } // The following line seems redundant. I cannot see a reason why we need to save the itmeGradingSet // here and then again in following saveOrUpdateAssessmentGrading(assessment). Comment it out. //saveOrUpdateAll(itemGradingSet); } */ // this will update itemGradingSet and assessmentGrading. May as well, otherwise I would have // to reload assessment again PersistenceService.getInstance(). getAssessmentGradingFacadeQueries().saveOrUpdateAssessmentGrading(assessment); } catch (Exception e) { e.printStackTrace(); } } // This API only touch SAM_ASSESSMENTGRADING_T. No data gets inserted/updated in SAM_ITEMGRADING_T public void saveOrUpdateAssessmentGradingOnly(AssessmentGradingData assessment) { Set origItemGradingSet = assessment.getItemGradingSet(); HashSet h = new HashSet(origItemGradingSet); // Clear the itemGradingSet so no data gets inserted/updated in SAM_ITEMGRADING_T; origItemGradingSet.clear(); int size = assessment.getItemGradingSet().size(); log.debug("before persist to db: size = " + size); try { PersistenceService.getInstance().getAssessmentGradingFacadeQueries().saveOrUpdateAssessmentGrading(assessment); } catch (Exception e) { e.printStackTrace(); } finally { // Restore the original itemGradingSet back assessment.setItemGradingSet(h); size = assessment.getItemGradingSet().size(); log.debug("after persist to db: size = " + size); } } public List getAssessmentGradingIds(String publishedItemId){ try{ return PersistenceService.getInstance().getAssessmentGradingFacadeQueries(). getAssessmentGradingIds(Long.valueOf(publishedItemId)); } catch(Exception e) { log.error(e); throw new RuntimeException(e); } } public AssessmentGradingData getHighestAssessmentGrading(String publishedAssessmentId, String agentId){ try{ return PersistenceService.getInstance().getAssessmentGradingFacadeQueries(). getHighestAssessmentGrading(Long.valueOf(publishedAssessmentId), agentId); } catch(Exception e) { log.error(e); throw new RuntimeException(e); } } public AssessmentGradingData getHighestSubmittedAssessmentGrading(String publishedAssessmentId, String agentId, String assessmentGradingId){ AssessmentGradingData assessmentGrading = null; try { if (assessmentGradingId != null) { assessmentGrading = PersistenceService.getInstance().getAssessmentGradingFacadeQueries(). getHighestSubmittedAssessmentGrading(Long.valueOf(publishedAssessmentId), agentId, Long.valueOf(assessmentGradingId)); } else { assessmentGrading = PersistenceService.getInstance().getAssessmentGradingFacadeQueries(). getHighestSubmittedAssessmentGrading(Long.valueOf(publishedAssessmentId), agentId, null); } } catch(Exception e) { log.error(e); throw new RuntimeException(e); } return assessmentGrading; } public AssessmentGradingData getHighestSubmittedAssessmentGrading(String publishedAssessmentId, String agentId){ return getHighestSubmittedAssessmentGrading(publishedAssessmentId, agentId, null); } public Set getItemGradingSet(String assessmentGradingId){ try{ return PersistenceService.getInstance().getAssessmentGradingFacadeQueries(). getItemGradingSet(Long.valueOf(assessmentGradingId)); } catch(Exception e){ log.error(e); throw new RuntimeException(e); } } public HashMap getAssessmentGradingByItemGradingId(String publishedAssessmentId){ try{ return PersistenceService.getInstance().getAssessmentGradingFacadeQueries(). getAssessmentGradingByItemGradingId(Long.valueOf(publishedAssessmentId)); } catch(Exception e){ log.error(e); throw new RuntimeException(e); } } public void updateItemScore(ItemGradingData gdata, double scoreDifference, PublishedAssessmentIfc pub){ try { AssessmentGradingData adata = load(gdata.getAssessmentGradingId().toString()); adata.setItemGradingSet(getItemGradingSet(adata.getAssessmentGradingId().toString())); Set itemGradingSet = adata.getItemGradingSet(); Iterator iter = itemGradingSet.iterator(); double totalAutoScore = 0; double totalOverrideScore = adata.getTotalOverrideScore().doubleValue(); while (iter.hasNext()){ ItemGradingData i = (ItemGradingData)iter.next(); if (i.getItemGradingId().equals(gdata.getItemGradingId())){ i.setAutoScore(gdata.getAutoScore()); i.setComments(gdata.getComments()); i.setGradedBy(AgentFacade.getAgentString()); i.setGradedDate(new Date()); } if (i.getAutoScore()!=null) totalAutoScore += i.getAutoScore().doubleValue(); } adata.setTotalAutoScore( Double.valueOf(totalAutoScore)); if (Double.compare((totalAutoScore+totalOverrideScore),Double.valueOf("0").doubleValue())<0){ adata.setFinalScore(Double.valueOf("0")); }else{ adata.setFinalScore(Double.valueOf(totalAutoScore+totalOverrideScore)); } saveOrUpdateAssessmentGrading(adata); if (scoreDifference != 0){ notifyGradebookByScoringType(adata, pub); } } catch (GradebookServiceException ge) { ge.printStackTrace(); throw ge; } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } } /** * Assume this is a new item. */ public void storeGrades(AssessmentGradingData data, PublishedAssessmentIfc pub, HashMap publishedItemHash, HashMap publishedItemTextHash, HashMap publishedAnswerHash, HashMap invalidFINMap, ArrayList invalidSALengthList) throws GradebookServiceException, FinFormatException { log.debug("storeGrades: data.getSubmittedDate()" + data.getSubmittedDate()); storeGrades(data, false, pub, publishedItemHash, publishedItemTextHash, publishedAnswerHash, true, invalidFINMap, invalidSALengthList); } /** * Assume this is a new item. */ public void storeGrades(AssessmentGradingData data, PublishedAssessmentIfc pub, HashMap publishedItemHash, HashMap publishedItemTextHash, HashMap publishedAnswerHash, boolean persistToDB, HashMap invalidFINMap, ArrayList invalidSALengthList) throws GradebookServiceException, FinFormatException { log.debug("storeGrades (not persistToDB) : data.getSubmittedDate()" + data.getSubmittedDate()); storeGrades(data, false, pub, publishedItemHash, publishedItemTextHash, publishedAnswerHash, persistToDB, invalidFINMap, invalidSALengthList); } public void storeGrades(AssessmentGradingData data, boolean regrade, PublishedAssessmentIfc pub, HashMap publishedItemHash, HashMap publishedItemTextHash, HashMap publishedAnswerHash, boolean persistToDB) throws GradebookServiceException, FinFormatException { log.debug("storeGrades (not persistToDB) : data.getSubmittedDate()" + data.getSubmittedDate()); storeGrades(data, regrade, pub, publishedItemHash, publishedItemTextHash, publishedAnswerHash, persistToDB, null, null); } /** * This is the big, complicated mess where we take all the items in * an assessment, store the grading data, auto-grade it, and update * everything. * * If regrade is true, we just recalculate the graded score. If it's * false, we do everything from scratch. */ public void storeGrades(AssessmentGradingData data, boolean regrade, PublishedAssessmentIfc pub, HashMap publishedItemHash, HashMap publishedItemTextHash, HashMap publishedAnswerHash, boolean persistToDB, HashMap invalidFINMap, ArrayList invalidSALengthList) throws GradebookServiceException, FinFormatException { log.debug("****x1. regrade ="+regrade+" "+(new Date()).getTime()); try { String agent = data.getAgentId(); // note that this itemGradingSet is a partial set of answer submitted. it contains only // newly submitted answers, updated answers and MCMR/FIB/FIN answers ('cos we need the old ones to // calculate scores for new ones) Set<ItemGradingData> itemGradingSet = data.getItemGradingSet(); if (itemGradingSet == null) itemGradingSet = new HashSet<ItemGradingData>(); log.debug("****itemGrading size="+itemGradingSet.size()); List<ItemGradingData> tempItemGradinglist = new ArrayList<ItemGradingData>(itemGradingSet); // CALCULATED_QUESTION - if this is a calc question. Carefully sort the list of answers if (isCalcQuestion(tempItemGradinglist, publishedItemHash)) { Collections.sort(tempItemGradinglist, new Comparator<ItemGradingData>(){ public int compare(ItemGradingData o1, ItemGradingData o2) { ItemGradingData gradeData1 = o1; ItemGradingData gradeData2 = o2; // protect against blank ones in samigo initial setup. if (gradeData1 == null) return -1; if (gradeData2 == null) return 1; if (gradeData1.getPublishedAnswerId() == null) return -1; if (gradeData2.getPublishedAnswerId() == null) return 1; return gradeData1.getPublishedAnswerId().compareTo(gradeData2.getPublishedAnswerId()); } }); } Iterator<ItemGradingData> iter = tempItemGradinglist.iterator(); // fibEmiAnswersMap contains a map of HashSet of answers for a FIB or EMI item, // key =itemid, value= HashSet of answers for each item. // For FIB: This is used to keep track of answers we have already used for // mutually exclusive multiple answer type of FIB, such as // The flag of the US is {red|white|blue},{red|white|blue}, and {red|white|blue}. // so if the first blank has an answer 'red', the 'red' answer should // not be included in the answers for the other mutually exclusive blanks. // For EMI: This keeps track of how many answers were given so we don't give // extra marks for to many answers. Map fibEmiAnswersMap = new HashMap(); Map<Long, Map<Long,Set<EMIScore>>> emiScoresMap = new HashMap<Long, Map<Long,Set<EMIScore>>>(); //change algorithm based on each question (SAK-1930 & IM271559) -cwen HashMap totalItems = new HashMap(); log.debug("****x2. "+(new Date()).getTime()); double autoScore = (double) 0; Long itemId = (long)0; int calcQuestionAnswerSequence = 1; // sequence of answers for CALCULATED_QUESTION while(iter.hasNext()) { ItemGradingData itemGrading = iter.next(); // CALCULATED_QUESTION - We increment this so we that calculated // questions can know where we are in the sequence of answers. if (itemGrading.getPublishedItemId().equals(itemId)) { calcQuestionAnswerSequence++; } else { calcQuestionAnswerSequence = 1; } itemId = itemGrading.getPublishedItemId(); ItemDataIfc item = (ItemDataIfc) publishedItemHash.get(itemId); if (item == null) { //this probably shouldn't happen log.error("unable to retrive itemDataIfc for: " + publishedItemHash.get(itemId)); continue; } Long itemType = item.getTypeId(); autoScore = (double) 0; itemGrading.setAssessmentGradingId(data.getAssessmentGradingId()); //itemGrading.setSubmittedDate(new Date()); itemGrading.setAgentId(agent); itemGrading.setOverrideScore(Double.valueOf(0)); if (itemType == 5 && itemGrading.getAnswerText() != null) { String processedAnswerText = itemGrading.getAnswerText().replaceAll("\r", "").replaceAll("\n", ""); if (processedAnswerText.length() > 32000) { if (invalidSALengthList != null) { invalidSALengthList.add(item.getItemId()); } } } // note that totalItems & fibAnswersMap would be modified by the following method try { autoScore = getScoreByQuestionType(itemGrading, item, itemType, publishedItemTextHash, totalItems, fibEmiAnswersMap, emiScoresMap, publishedAnswerHash, regrade, calcQuestionAnswerSequence); } catch (FinFormatException e) { autoScore = 0d; if (invalidFINMap != null) { if (invalidFINMap.containsKey(itemId)) { ArrayList list = (ArrayList) invalidFINMap.get(itemId); list.add(itemGrading.getItemGradingId()); } else { ArrayList list = new ArrayList(); list.add(itemGrading.getItemGradingId()); invalidFINMap.put(itemId, list); } } } log.debug("**!regrade, autoScore="+autoScore); if (!(TypeIfc.MULTIPLE_CORRECT).equals(itemType) && !(TypeIfc.EXTENDED_MATCHING_ITEMS).equals(itemType)) totalItems.put(itemId, Double.valueOf(autoScore)); if (regrade && TypeIfc.AUDIO_RECORDING.equals(itemType)) itemGrading.setAttemptsRemaining(item.getTriesAllowed()); itemGrading.setAutoScore(Double.valueOf(autoScore)); } if ((invalidFINMap != null && invalidFINMap.size() > 0) || (invalidSALengthList != null && invalidSALengthList.size() > 0)) { return; } // Added persistToDB because if we don't save data to DB later, we shouldn't update the assessment // submittedDate either. The date should be sync in delivery bean and DB // This is for DeliveryBean.checkDataIntegrity() if (!regrade && persistToDB) { data.setSubmittedDate(new Date()); setIsLate(data, pub); } log.debug("****x3. "+(new Date()).getTime()); List<ItemGradingData> emiItemGradings = new ArrayList<ItemGradingData>(); // the following procedure ensure total score awarded per question is no less than 0 // this probably only applies to MCMR question type - daisyf iter = itemGradingSet.iterator(); //since the itr goes through each answer (multiple answers for a signle mc question), keep track //of its total score by itemId -> autoScore[]{user's score, total possible} Map<Long, Double[]> mcmcAllOrNothingCheck = new HashMap<Long, Double[]>(); //get item information to check if it's MCMS and Not Partial Credit Long itemType2 = -1l; String mcmsPartialCredit = ""; double itemScore = -1; while(iter.hasNext()) { ItemGradingData itemGrading = iter.next(); itemId = itemGrading.getPublishedItemId(); ItemDataIfc item = (ItemDataIfc) publishedItemHash.get(itemId); //SAM-1724 it's possible the item is not in the hash -DH if (item == null) { log.error("unable to retrive itemDataIfc for: " + publishedItemHash.get(itemId)); continue; } itemType2 = item.getTypeId(); //get item information to check if it's MCMS and Not Partial Credit mcmsPartialCredit = item.getItemMetaDataByLabel(ItemMetaDataIfc.MCMS_PARTIAL_CREDIT); itemScore = item.getScore(); //double autoScore = (double) 0; // this does not apply to EMI // just create a short-list and handle differently below if ((TypeIfc.EXTENDED_MATCHING_ITEMS).equals(itemType2)) { emiItemGradings.add(itemGrading); continue; } double eachItemScore = ((Double) totalItems.get(itemId)).doubleValue(); if((eachItemScore < 0) && !((TypeIfc.MULTIPLE_CHOICE).equals(itemType2)||(TypeIfc.TRUE_FALSE).equals(itemType2))) { itemGrading.setAutoScore( Double.valueOf(0)); } //keep track of MCMC answer's total score in order to check for all or nothing if(TypeIfc.MULTIPLE_CORRECT.equals(itemType2) && "false".equals(mcmsPartialCredit)){ Double accumulatedScore = itemGrading.getAutoScore(); if(mcmcAllOrNothingCheck.containsKey(itemId)){ Double[] accumulatedScoreArr = mcmcAllOrNothingCheck.get(itemId); accumulatedScore += accumulatedScoreArr[0]; } mcmcAllOrNothingCheck.put(itemId, new Double[]{accumulatedScore, item.getScore()}); } } log.debug("****x3.1 "+(new Date()).getTime()); // Loop 1: this procedure ensure total score awarded per EMI item // is correct // For emi's there are multiple gradings per item per question, // for the grading we only know scores after grading so we need // to reset the grading score here to the correct scores // this currently only applies to EMI question type if (emiItemGradings != null && !emiItemGradings.isEmpty()) { Map<Long, Map<Long, Map<Long, EMIScore>>> emiOrderedScoresMap = reorderEMIScoreMap(emiScoresMap); iter = emiItemGradings.iterator(); while (iter.hasNext()) { ItemGradingData itemGrading = iter.next(); //SAM-2016 check for Nullity if (itemGrading == null) { log.warn("Map contains null itemgrading!"); continue; } Map<Long, Map<Long, EMIScore>> innerMap = emiOrderedScoresMap .get(itemGrading.getPublishedItemId()); if (innerMap == null) { log.warn("Inner map is empty!"); continue; } Map<Long, EMIScore> scoreMap = innerMap .get(itemGrading.getPublishedItemTextId()); if (scoreMap == null) { log.warn("Score map is empty!"); continue; } EMIScore score = scoreMap .get(itemGrading.getPublishedAnswerId()); if (score == null) { //its possible! SAM-2016 log.warn("we can't find a score for answer: " + itemGrading.getPublishedAnswerId()); continue; } itemGrading.setAutoScore(emiOrderedScoresMap .get(itemGrading.getPublishedItemId()) .get(itemGrading.getPublishedItemTextId()) .get(itemGrading.getPublishedAnswerId()).effectiveScore); } } // if it's MCMS and Not Partial Credit and the score isn't 100% (totalAutoScoreCheck != itemScore), // that means the user didn't answer all of the correct answers only. // We need to set their score to 0 for all ItemGrading items for(Entry<Long, Double[]> entry : mcmcAllOrNothingCheck.entrySet()){ if(!(MathUtils.equalsIncludingNaN(entry.getValue()[0], entry.getValue()[1], 0.0001))){ //reset all scores to 0 since the user didn't get all correct answers iter = itemGradingSet.iterator(); while(iter.hasNext()){ ItemGradingData itemGrading = iter.next(); if(itemGrading.getPublishedItemId().equals(entry.getKey())){ itemGrading.setAutoScore(Double.valueOf(0)); } } } } log.debug("****x4. "+(new Date()).getTime()); // save#1: this itemGrading Set is a partial set of answers submitted. it contains new answers and // updated old answers and FIB answers ('cos we need the old answer to calculate the score for new // ones). we need to be cheap, we don't want to update record that hasn't been // changed. Yes, assessmentGrading's total score will be out of sync at this point, I am afraid. It // would be in sync again once the whole method is completed sucessfully. if (persistToDB) { saveOrUpdateAll(itemGradingSet); } log.debug("****x5. "+(new Date()).getTime()); // save#2: now, we need to get the full set so we can calculate the total score accumulate for the // whole assessment. Set fullItemGradingSet = getItemGradingSet(data.getAssessmentGradingId().toString()); double totalAutoScore = getTotalAutoScore(fullItemGradingSet); data.setTotalAutoScore( Double.valueOf(totalAutoScore)); //log.debug("**#1 total AutoScore"+totalAutoScore); if (Double.compare((totalAutoScore + data.getTotalOverrideScore().doubleValue()),new Double("0").doubleValue())<0){ data.setFinalScore( Double.valueOf("0")); }else{ data.setFinalScore(Double.valueOf(totalAutoScore + data.getTotalOverrideScore().doubleValue())); } log.debug("****x6. "+(new Date()).getTime()); } catch (GradebookServiceException ge) { ge.printStackTrace(); throw ge; } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } // save#3: itemGradingSet has been saved above so just need to update assessmentGrading // therefore setItemGradingSet as empty first - daisyf // however, if we do not persit to DB, we want to keep itemGradingSet with data for later use // Because if itemGradingSet is not saved to DB, we cannot go to DB to get it. We have to // get it through data. if (persistToDB) { data.setItemGradingSet(new HashSet()); saveOrUpdateAssessmentGrading(data); log.debug("****x7. "+(new Date()).getTime()); if (!regrade) { notifyGradebookByScoringType(data, pub); } } log.debug("****x8. "+(new Date()).getTime()); // I am not quite sure what the following code is doing... I modified this based on my assumption: // If this happens dring regrade, we don't want to clean these data up // We only want to clean them out in delivery if (!regrade && Boolean.TRUE.equals(data.getForGrade())) { // remove the assessmentGradingData created during gradiing (by updatding total score page) removeUnsubmittedAssessmentGradingData(data); } } private double getTotalAutoScore(Set itemGradingSet){ //log.debug("*** no. of itemGrading="+itemGradingSet.size()); double totalAutoScore =0; Iterator iter = itemGradingSet.iterator(); while (iter.hasNext()){ ItemGradingData i = (ItemGradingData)iter.next(); //log.debug(i.getItemGradingId()+"->"+i.getAutoScore()); if (i.getAutoScore()!=null) totalAutoScore += i.getAutoScore().doubleValue(); } return totalAutoScore; } private void notifyGradebookByScoringType(AssessmentGradingData data, PublishedAssessmentIfc pub){ Integer scoringType = pub.getEvaluationModel().getScoringType(); if (updateGradebook(data, pub)){ AssessmentGradingData d = data; // data is the last submission // need to decide what to tell gradebook if ((scoringType).equals(EvaluationModelIfc.HIGHEST_SCORE)) d = getHighestSubmittedAssessmentGrading(pub.getPublishedAssessmentId().toString(), data.getAgentId()); notifyGradebook(d, pub); } } private double getScoreByQuestionType(ItemGradingData itemGrading, ItemDataIfc item, Long itemType, Map publishedItemTextHash, Map totalItems, Map fibAnswersMap, Map<Long, Map<Long,Set<EMIScore>>> emiScoresMap, HashMap publishedAnswerHash, boolean regrade, int calcQuestionAnswerSequence) throws FinFormatException { //double score = (double) 0; double initScore = (double) 0; double autoScore = (double) 0; double accumelateScore = (double) 0; Long itemId = item.getItemId(); int type = itemType.intValue(); switch (type){ case 1: // MC Single Correct if(item.getPartialCreditFlag()) autoScore = getAnswerScoreMCQ(itemGrading, publishedAnswerHash); else{ autoScore = getAnswerScore(itemGrading, publishedAnswerHash); } //overridescore if (itemGrading.getOverrideScore() != null) autoScore += itemGrading.getOverrideScore().doubleValue(); totalItems.put(itemId, new Double(autoScore)); break;// MC Single Correct case 12: // MC Multiple Correct Single Selection case 3: // MC Survey case 4: // True/False autoScore = getAnswerScore(itemGrading, publishedAnswerHash); //overridescore if (itemGrading.getOverrideScore() != null) autoScore += itemGrading.getOverrideScore().doubleValue(); totalItems.put(itemId, Double.valueOf(autoScore)); break; case 2: // MC Multiple Correct ItemTextIfc itemText = (ItemTextIfc) publishedItemTextHash.get(itemGrading.getPublishedItemTextId()); List answerArray = itemText.getAnswerArray(); int correctAnswers = 0; if (answerArray != null){ for (int i =0; i<answerArray.size(); i++){ AnswerIfc a = (AnswerIfc) answerArray.get(i); if (a.getIsCorrect().booleanValue()) correctAnswers++; } } initScore = getAnswerScore(itemGrading, publishedAnswerHash); if (initScore > 0) autoScore = initScore / correctAnswers; else autoScore = (getTotalCorrectScore(itemGrading, publishedAnswerHash) / correctAnswers) * ((double) -1); //overridescore? if (itemGrading.getOverrideScore() != null) autoScore += itemGrading.getOverrideScore().doubleValue(); if (!totalItems.containsKey(itemId)){ totalItems.put(itemId, Double.valueOf(autoScore)); //log.debug("****0. first answer score = "+autoScore); } else{ accumelateScore = ((Double)totalItems.get(itemId)).doubleValue(); //log.debug("****1. before adding new score = "+accumelateScore); //log.debug("****2. this answer score = "+autoScore); accumelateScore += autoScore; //log.debug("****3. add 1+2 score = "+accumelateScore); totalItems.put(itemId, Double.valueOf(accumelateScore)); //log.debug("****4. what did we put in = "+((Double)totalItems.get(itemId)).doubleValue()); } break; case 9: // Matching initScore = getAnswerScore(itemGrading, publishedAnswerHash); if (initScore > 0) { int nonDistractors = 0; Iterator<ItemTextIfc> itemIter = item.getItemTextArraySorted().iterator(); while (itemIter.hasNext()) { ItemTextIfc curItem = itemIter.next(); if (!isDistractor(curItem)) { nonDistractors++; } } autoScore = initScore / nonDistractors; } //overridescore? if (itemGrading.getOverrideScore() != null) autoScore += itemGrading.getOverrideScore().doubleValue(); if (!totalItems.containsKey(itemId)) totalItems.put(itemId, Double.valueOf(autoScore)); else { accumelateScore = ((Double)totalItems.get(itemId)).doubleValue(); accumelateScore += autoScore; totalItems.put(itemId, Double.valueOf(accumelateScore)); } break; case 8: // FIB autoScore = getFIBScore(itemGrading, fibAnswersMap, item, publishedAnswerHash) / (double) ((ItemTextIfc) item.getItemTextSet().toArray()[0]).getAnswerSet().size(); //overridescore - cwen if (itemGrading.getOverrideScore() != null) autoScore += itemGrading.getOverrideScore().doubleValue(); if (!totalItems.containsKey(itemId)) totalItems.put(itemId, Double.valueOf(autoScore)); else { accumelateScore = ((Double)totalItems.get(itemId)).doubleValue(); accumelateScore += autoScore; totalItems.put(itemId, Double.valueOf(accumelateScore)); } break; case 15: // CALCULATED_QUESTION case 11: // FIN try { if (type == 15) { // CALCULATED_QUESTION Map<Integer, String> calculatedAnswersMap = getCalculatedAnswersMap(itemGrading, item); int numAnswers = calculatedAnswersMap.size(); autoScore = getCalcQScore(itemGrading, item, calculatedAnswersMap, calcQuestionAnswerSequence ) / (double) numAnswers; } else { autoScore = getFINScore(itemGrading, item, publishedAnswerHash) / (double) ((ItemTextIfc) item.getItemTextSet().toArray()[0]).getAnswerSet().size(); } } catch (FinFormatException e) { throw e; } //overridescore - cwen if (itemGrading.getOverrideScore() != null) autoScore += itemGrading.getOverrideScore().doubleValue(); if (!totalItems.containsKey(itemId)) totalItems.put(itemId, Double.valueOf(autoScore)); else { accumelateScore = ((Double)totalItems.get(itemId)).doubleValue(); accumelateScore += autoScore; totalItems.put(itemId, Double.valueOf(accumelateScore)); } break; case 14: // EMI autoScore = getEMIScore(itemGrading, itemId, totalItems, emiScoresMap, publishedItemTextHash, publishedAnswerHash); break; case 5: // SAQ case 6: // file upload case 7: // audio recording //overridescore - cwen if (regrade && itemGrading.getAutoScore() != null) { autoScore = itemGrading.getAutoScore(); } if (itemGrading.getOverrideScore() != null) autoScore += itemGrading.getOverrideScore().doubleValue(); if (!totalItems.containsKey(itemId)) totalItems.put(itemId, Double.valueOf(autoScore)); else { accumelateScore = ((Double)totalItems.get(itemId)).doubleValue(); accumelateScore += autoScore; totalItems.put(itemId, Double.valueOf(accumelateScore)); } break; } return autoScore; } /** * This grades multiple choice and true false questions. Since * multiple choice/multiple select has a separate ItemGradingData for * each choice, they're graded the same way the single choice are. * Choices should be given negative score values if one wants them * to lose points for the wrong choice. */ public double getAnswerScore(ItemGradingData data, Map publishedAnswerHash) { AnswerIfc answer = (AnswerIfc) publishedAnswerHash.get(data.getPublishedAnswerId()); if (answer == null || answer.getScore() == null) { return (double) 0; } ItemDataIfc item = (ItemDataIfc) answer.getItem(); Long itemType = item.getTypeId(); if (answer.getIsCorrect() == null || !answer.getIsCorrect().booleanValue()) { // return (double) 0; // Para que descuente (For discount) if ((TypeIfc.EXTENDED_MATCHING_ITEMS).equals(itemType)||(TypeIfc.MULTIPLE_CHOICE).equals(itemType)||(TypeIfc.TRUE_FALSE).equals(itemType)){ return (Math.abs(answer.getDiscount().doubleValue()) * ((double) -1)); }else{ return (double) 0; } } return answer.getScore().doubleValue(); } public void notifyGradebook(AssessmentGradingData data, PublishedAssessmentIfc pub) throws GradebookServiceException { // If the assessment is published to the gradebook, make sure to update the scores in the gradebook String toGradebook = pub.getEvaluationModel().getToGradeBook(); GradebookExternalAssessmentService g = null; boolean integrated = IntegrationContextFactory.getInstance().isIntegrated(); if (integrated) { g = (GradebookExternalAssessmentService) SpringBeanLocator.getInstance(). getBean("org.sakaiproject.service.gradebook.GradebookExternalAssessmentService"); } GradebookServiceHelper gbsHelper = IntegrationContextFactory.getInstance().getGradebookServiceHelper(); PublishedAssessmentService publishedAssessmentService = new PublishedAssessmentService(); String currentSiteId = publishedAssessmentService.getPublishedAssessmentSiteId(pub.getPublishedAssessmentId().toString()); if (gbsHelper.gradebookExists(GradebookFacade.getGradebookUId(currentSiteId), g) && toGradebook.equals(EvaluationModelIfc.TO_DEFAULT_GRADEBOOK.toString())){ if(log.isDebugEnabled()) log.debug("Attempting to update a score in the gradebook"); // add retry logic to resolve deadlock problem while sending grades to gradebook Double originalFinalScore = data.getFinalScore(); int retryCount = PersistenceService.getInstance().getPersistenceHelper().getRetryCount().intValue(); while (retryCount > 0){ try { // Send the average score if average was selected for multiple submissions Integer scoringType = pub.getEvaluationModel().getScoringType(); if (scoringType.equals(EvaluationModelIfc.AVERAGE_SCORE)) { // status = 5: there is no submission but grader update something in the score page if(data.getStatus() ==5) { data.setFinalScore(data.getFinalScore()); } else { Double averageScore = PersistenceService.getInstance().getAssessmentGradingFacadeQueries(). getAverageSubmittedAssessmentGrading(Long.valueOf(pub.getPublishedAssessmentId()), data.getAgentId()); data.setFinalScore(averageScore); } } gbsHelper.updateExternalAssessmentScore(data, g); retryCount = 0; } catch (org.sakaiproject.service.gradebook.shared.AssessmentNotFoundException ante) { log.warn("problem sending grades to gradebook: " + ante.getMessage()); if (AssessmentIfc.RETRACT_FOR_EDIT_STATUS.equals(pub.getStatus())) { retryCount = retry(retryCount, ante, pub, true); } else { // Otherwise, do the same exeption handling as others retryCount = retry(retryCount, ante, pub, false); } } catch (Exception e) { retryCount = retry(retryCount, e, pub, false); } } // change the final score back to the original score since it may set to average score. // data.getFinalScore() != originalFinalScore if(!(MathUtils.equalsIncludingNaN(data.getFinalScore(), originalFinalScore, 0.0001))) { data.setFinalScore(originalFinalScore); } } else { if(log.isDebugEnabled()) log.debug("Not updating the gradebook. toGradebook = " + toGradebook); } } private int retry(int retryCount, Exception e, PublishedAssessmentIfc pub, boolean retractForEditStatus) { log.warn("retrying...sending grades to gradebook. "); log.warn("retry...."); retryCount--; try { int deadlockInterval = PersistenceService.getInstance().getPersistenceHelper().getDeadlockInterval().intValue(); Thread.sleep(deadlockInterval); } catch(InterruptedException ex){ log.warn(ex.getMessage()); } if (retryCount==0) { if (retractForEditStatus) { // This happens in following scenario: // 1. The assessment is active and has "None" for GB setting // 2. Instructor retracts it for edit and update the to "Send to GB" // 3. Instructor updates something on the total Score page // Because the GB will not be created until the assessment gets republished, // "AssessmentNotFoundException" will be thrown here. Since, this is the expected // exception, we simply log a debug message without retrying or notifying the user. // Of course, you can argue about what if the assessment gets deleted by other cause. // But I would say the major cause would be this "retract" scenario. Also, without knowing // the change history of the assessment, I think this is the best handling. log.info("We quietly sallow the AssessmentNotFoundException excption here. Published Assessment Name: " + pub.getTitle()); } else { // after retries, still failed updating gradebook log.warn("After all retries, still failed ... Now throw error to UI"); throw new GradebookServiceException(e); } } return retryCount; } /** * This grades Fill In Blank questions. (see SAK-1685) * There will be two valid cases for scoring when there are multiple fill * in blanks in a question: * Case 1- There are different sets of answers (a set can contain one or more * item) for each blank (e.g. The {dog|coyote|wolf} howls and the {lion|cougar} * roars.) In this case each blank is tested for correctness independently. * Case 2-There is the same set of answers for each blank: e.g. The flag of the US * is {red|white|blue},{red|white|blue}, and {red|white|blue}. * These are the only two valid types of questions. When authoring, it is an * ERROR to include: * (1) a mixture of independent answer and common answer blanks * (e.g. The {dog|coyote|wolf} howls at the {red|white|blue}, {red|white|blue}, * and {red|white|blue} flag.) * (2) more than one set of blanks with a common answer ((e.g. The US flag * is {red|white|blue}, {red|white|blue}, and {red|white|blue} and the Italian * flag is {red|white|greem}, {red|white|greem}, and {red|white|greem}.) * These two invalid questions specifications should be authored as two * separate questions. Here are the definition and 12 cases I came up with (lydia, 01/2006): single answers : roses are {red} and vilets are {blue} multiple answers : {dogs|cats} have 4 legs multiple answers , mutually exclusive, all answers must be identical, can be in diff. orders : US flag has {red|blue|white} and {red |white|blue} and {blue|red|white} colors multiple answers , mutually non-exclusive : {dogs|cats} have 4 legs and {dogs|cats} can be pets. wildcard uses * to mean one of more characters -. wildcard single answer, case sensitive -. wildcard single answer, case insensitive -. single answer, no wildcard , case sensitive -. single answer, no wildcard , case insensitive -. multiple answer, mutually non-exclusive, no wildcard , case sensitive -. multiple answer, mutually non-exclusive, no wildcard , case in sensitive -. multiple answer, mutually non-exclusive, wildcard , case sensitive -. multiple answer, mutually non-exclusive, wildcard , case insensitive -. multiple answer, mutually exclusive, no wildcard , case sensitive -. multiple answer, mutually exclusive, no wildcard , case in sensitive -. multiple answer, mutually exclusive, wildcard , case sensitive -. multiple answer, mutually exclusive, wildcard , case insensitive */ public double getFIBScore(ItemGradingData data, Map fibmap, ItemDataIfc itemdata, Map publishedAnswerHash) { String studentanswer = ""; boolean matchresult = false; double totalScore = (double) 0; data.setIsCorrect(Boolean.FALSE); if (data.getPublishedAnswerId() == null) { return totalScore; } AnswerIfc answerIfc = (AnswerIfc) publishedAnswerHash.get(data.getPublishedAnswerId()); if (answerIfc == null) { return totalScore; } String answertext = answerIfc.getText(); Long itemId = itemdata.getItemId(); String casesensitive = itemdata.getItemMetaDataByLabel(ItemMetaDataIfc.CASE_SENSITIVE_FOR_FIB); String mutuallyexclusive = itemdata.getItemMetaDataByLabel(ItemMetaDataIfc.MUTUALLY_EXCLUSIVE_FOR_FIB); //Set answerSet = new HashSet(); if (answertext != null) { StringTokenizer st = new StringTokenizer(answertext, "|"); while (st.hasMoreTokens()) { String answer = st.nextToken().trim(); if ("true".equalsIgnoreCase(casesensitive)) { if (data.getAnswerText() != null){ studentanswer= data.getAnswerText().trim(); matchresult = fibmatch(answer, studentanswer, true); } } // if case sensitive else { // case insensitive , if casesensitive is false, or null, or "". if (data.getAnswerText() != null){ studentanswer= data.getAnswerText().trim(); matchresult = fibmatch(answer, studentanswer, false); } } // else , case insensitive if (matchresult){ boolean alreadyused=false; // add check for mutual exclusive if ("true".equalsIgnoreCase(mutuallyexclusive)) { // check if answers are already used. Set answer_used_sofar = (HashSet) fibmap.get(itemId); if ((answer_used_sofar!=null) && ( answer_used_sofar.contains(studentanswer.toLowerCase()))){ // already used, so it's a wrong answer for mutually exclusive questions alreadyused=true; } else { // not used, it's a good answer, now add this to the already_used list. // we only store lowercase strings in the fibmap. if (answer_used_sofar==null) { answer_used_sofar = new HashSet(); } answer_used_sofar.add(studentanswer.toLowerCase()); fibmap.put(itemId, answer_used_sofar); } } if (!alreadyused) { totalScore += ((AnswerIfc) publishedAnswerHash.get(data.getPublishedAnswerId())).getScore().doubleValue(); data.setIsCorrect(Boolean.TRUE); } // SAK-3005: quit if answer is correct, e.g. if you answered A for {a|A}, you already scored break; } } } return totalScore; } public boolean getFIBResult(ItemGradingData data, HashMap fibmap, ItemDataIfc itemdata, HashMap publishedAnswerHash) { // this method is similiar to getFIBScore(), except it returns true/false for the answer, not scores. // may be able to refactor code out to be reused, but totalscores for mutually exclusive case is a bit tricky. String studentanswer = ""; boolean matchresult = false; if (data.getPublishedAnswerId() == null) { return matchresult; } AnswerIfc answerIfc = (AnswerIfc) publishedAnswerHash.get(data.getPublishedAnswerId()); if (answerIfc == null) { return matchresult; } String answertext = answerIfc.getText(); Long itemId = itemdata.getItemId(); String casesensitive = itemdata.getItemMetaDataByLabel(ItemMetaDataIfc.CASE_SENSITIVE_FOR_FIB); String mutuallyexclusive = itemdata.getItemMetaDataByLabel(ItemMetaDataIfc.MUTUALLY_EXCLUSIVE_FOR_FIB); //Set answerSet = new HashSet(); if (answertext != null) { StringTokenizer st = new StringTokenizer(answertext, "|"); while (st.hasMoreTokens()) { String answer = st.nextToken().trim(); if ("true".equalsIgnoreCase(casesensitive)) { if (data.getAnswerText() != null){ studentanswer= data.getAnswerText().trim(); matchresult = fibmatch(answer, studentanswer, true); } } // if case sensitive else { // case insensitive , if casesensitive is false, or null, or "". if (data.getAnswerText() != null){ studentanswer= data.getAnswerText().trim(); matchresult = fibmatch(answer, studentanswer, false); } } // else , case insensitive if (matchresult){ boolean alreadyused=false; // add check for mutual exclusive if ("true".equalsIgnoreCase(mutuallyexclusive)) { // check if answers are already used. Set answer_used_sofar = (HashSet) fibmap.get(itemId); if ((answer_used_sofar!=null) && ( answer_used_sofar.contains(studentanswer.toLowerCase()))){ // already used, so it's a wrong answer for mutually exclusive questions alreadyused=true; } else { // not used, it's a good answer, now add this to the already_used list. // we only store lowercase strings in the fibmap. if (answer_used_sofar==null) { answer_used_sofar = new HashSet(); } answer_used_sofar.add(studentanswer.toLowerCase()); fibmap.put(itemId, answer_used_sofar); } } if (alreadyused) { matchresult = false; } break; } } } return matchresult; } public double getFINScore(ItemGradingData data, ItemDataIfc itemdata, Map publishedAnswerHash) throws FinFormatException { data.setIsCorrect(Boolean.FALSE); double totalScore = (double) 0; boolean matchresult = getFINResult(data, itemdata, publishedAnswerHash); if (matchresult){ totalScore += ((AnswerIfc) publishedAnswerHash.get(data.getPublishedAnswerId())).getScore().doubleValue(); data.setIsCorrect(Boolean.TRUE); } return totalScore; } public boolean getFINResult (ItemGradingData data, ItemDataIfc itemdata, Map publishedAnswerHash) throws FinFormatException { String studentanswer = ""; boolean range; boolean matchresult = false; ComplexFormat complexFormat = new ComplexFormat(); Complex answerComplex = null; Complex studentAnswerComplex = null; BigDecimal answerNum = null, answer1Num = null, answer2Num = null, studentAnswerNum = null; if (data.getPublishedAnswerId() == null) { return false; } AnswerIfc answerIfc = (AnswerIfc) publishedAnswerHash.get(data.getPublishedAnswerId()); if (answerIfc == null) { return matchresult; } String answertext = answerIfc.getText(); if (answertext != null) { StringTokenizer st = new StringTokenizer(answertext, "|"); range = false; if (st.countTokens() > 1) { range = true; } String studentAnswerText = null; if (data.getAnswerText() != null) { studentAnswerText = data.getAnswerText().trim().replace(',','.'); // in Spain, comma is used as a decimal point } if (range) { String answer1 = st.nextToken().trim(); String answer2 = st.nextToken().trim(); if (answer1 != null){ answer1 = answer1.trim().replace(',','.'); // in Spain, comma is used as a decimal point } if (answer2 != null){ answer2 = answer2.trim().replace(',','.'); // in Spain, comma is used as a decimal point } try { answer1Num = new BigDecimal(answer1); answer2Num = new BigDecimal(answer2); } catch (Exception e) { log.debug("Number is not BigDecimal: " + answer1 + " or " + answer2); } Map map = validate(studentAnswerText); studentAnswerNum = (BigDecimal) map.get(ANSWER_TYPE_REAL); matchresult = (answer1Num != null && answer2Num != null && studentAnswerNum != null && (answer1Num.compareTo(studentAnswerNum) <= 0) && (answer2Num.compareTo(studentAnswerNum) >= 0)); } else { // not range String answer = st.nextToken().trim(); if (answer != null){ answer = answer.trim().replace(',','.'); // in Spain, comma is used as a decimal point } try { answerNum = new BigDecimal(answer); } catch(NumberFormatException ex) { log.debug("Number is not BigDecimal: " + answer); } try { answerComplex = complexFormat.parse(answer); } catch(ParseException ex) { log.debug("Number is not Complex: " + answer); } if (data.getAnswerText() != null) { Map map = validate(studentAnswerText); if (answerNum != null) { studentAnswerNum = (BigDecimal) map.get(ANSWER_TYPE_REAL); matchresult = (studentAnswerNum != null && answerNum.compareTo(studentAnswerNum) == 0); } else if (answerComplex != null) { studentAnswerComplex = (Complex) map.get(ANSWER_TYPE_COMPLEX); matchresult = (studentAnswerComplex != null && answerComplex.equals(studentAnswerComplex)); } } } } return matchresult; } /** * Validate a students numeric answer * @param The answer to validate * @return a Map containing either Real or Complex answer keyed by {@link #ANSWER_TYPE_REAL} or {@link #ANSWER_TYPE_COMPLEX} */ public Map validate(String value) { HashMap map = new HashMap(); if (value == null || value.trim().equals("")) { return map; } String trimmedValue = value.trim(); boolean isComplex = true; boolean isRealNumber = true; BigDecimal studentAnswerReal = null; try { studentAnswerReal = new BigDecimal(trimmedValue); } catch (Exception e) { isRealNumber = false; } // Test for complex number only if it is not a BigDecimal Complex studentAnswerComplex = null; if (!isRealNumber) { try { DecimalFormat df = (DecimalFormat)NumberFormat.getNumberInstance(Locale.US); df.setGroupingUsed(false); // Numerical format ###.## (decimal symbol is the point) ComplexFormat complexFormat = new ComplexFormat(df); studentAnswerComplex = complexFormat.parse(trimmedValue); // This is because there is a bug parsing complex number. 9i is parsed as 9 if (studentAnswerComplex.getImaginary() == 0 && trimmedValue.contains("i")) { isComplex = false; } } catch (Exception e) { isComplex = false; } } Boolean isValid = isComplex || isRealNumber; if (!isValid) { throw new FinFormatException("Not a valid FIN Input. studentanswer=" + trimmedValue); } if (isRealNumber) { map.put(ANSWER_TYPE_REAL, studentAnswerReal); } else if (isComplex) { map.put(ANSWER_TYPE_COMPLEX, studentAnswerComplex); } return map; } /** * EMI score processing * */ private double getEMIScore(ItemGradingData itemGrading, Long itemId, Map totalItems, Map<Long, Map<Long, Set<EMIScore>>> emiScoresMap, Map publishedItemTextHash, Map publishedAnswerHash) { log.debug("getEMIScore( " + itemGrading +", " + itemId); double autoScore = 0.0; if (!totalItems.containsKey(itemId)) { totalItems.put(itemId, new HashMap()); emiScoresMap.put(itemId, new HashMap<Long, Set<EMIScore>>()); } autoScore = getAnswerScore(itemGrading, publishedAnswerHash); AnswerIfc answer = (AnswerIfc) publishedAnswerHash.get(itemGrading .getPublishedAnswerId()); if (answer == null) { //its possible we have an orphaned object ... log.warn("could not find answer: " + itemGrading .getPublishedAnswerId() + ", for item " + itemGrading.getItemGradingId()); return 0.0; } Long itemTextId = itemGrading.getPublishedItemTextId(); // update the fibEmiAnswersMap so we can keep track // of how many answers were given Map<Long, Set<EMIScore>> emiItemScoresMap = emiScoresMap.get(itemId); // place the answer scores in a sorted set. // so now we can mark the correct ones and discount the extra incorrect // ones. Set<EMIScore> scores = null; if (emiItemScoresMap.containsKey(itemTextId)) { scores = emiItemScoresMap.get(itemTextId); } else { scores = new TreeSet<EMIScore>(); emiItemScoresMap.put(itemTextId, scores); } scores.add(new EMIScore(itemId, itemTextId, itemGrading .getPublishedAnswerId(), answer.getIsCorrect(), autoScore)); ItemTextIfc itemText = (ItemTextIfc) publishedItemTextHash.get(itemTextId); int numberCorrectAnswers = itemText.getEmiCorrectOptionLabels() .length(); Integer requiredCount = itemText.getRequiredOptionsCount(); // re-calculate the scores over for the whole item autoScore = 0.0; int c = 0; for (EMIScore s : scores) { c++; s.effectiveScore = 0.0; if (c <= numberCorrectAnswers && c <= requiredCount) { // if correct and in count then add score s.effectiveScore = s.correct ? s.score : 0.0; } else if (c > numberCorrectAnswers) { // if incorrect and over count add discount s.effectiveScore = !s.correct ? s.score : 0.0; } if (autoScore + s.effectiveScore < 0.0) { // the current item tipped it to negative, // we cannot do this, so add zero s.effectiveScore = 0.0; } autoScore += s.effectiveScore; } // override score if (itemGrading.getOverrideScore() != null) autoScore += itemGrading.getOverrideScore().doubleValue(); HashMap totalItemTextScores = (HashMap) totalItems.get(itemId); totalItemTextScores.put(itemTextId, Double.valueOf(autoScore)); return autoScore; } /** * CALCULATED_QUESTION * Returns a double score value for the ItemGrading element being scored for a Calculated Question * * @param calcQuestionAnswerSequence the order of answers in the list * @return score for the item. */ public double getCalcQScore(ItemGradingData data, ItemDataIfc itemdata, Map<Integer, String> calculatedAnswersMap, int calcQuestionAnswerSequence) { double totalScore = (double) 0; if (data.getAnswerText() == null) return totalScore; // zero for blank // this variable should look something like this "42.1|2,2" String allAnswerText = calculatedAnswersMap.get(calcQuestionAnswerSequence).toString(); // NOTE: this correctAnswer will already have been trimmed to the appropriate number of decimals BigDecimal correctAnswer = new BigDecimal(getAnswerExpression(allAnswerText)); // Determine if the acceptable variance is a constant or a % of the answer String varianceString = allAnswerText.substring(allAnswerText.indexOf("|")+1, allAnswerText.indexOf(",")); BigDecimal acceptableVariance = BigDecimal.ZERO; if (varianceString.contains("%")){ double percentage = Double.valueOf(varianceString.substring(0, varianceString.indexOf("%"))); acceptableVariance = correctAnswer.multiply( new BigDecimal(percentage / 100) ); } else { acceptableVariance = new BigDecimal(varianceString); } String userAnswerString = data.getAnswerText().replaceAll(",", "").trim(); BigDecimal userAnswer; try { userAnswer = new BigDecimal(userAnswerString); } catch(NumberFormatException nfe) { return totalScore; // zero because it's not even a number! } //double userAnswer = Double.valueOf(userAnswerString); // this compares the correctAnswer against the userAnsewr BigDecimal answerDiff = (correctAnswer.subtract(userAnswer)); boolean closeEnough = (answerDiff.abs().compareTo(acceptableVariance.abs()) <= 0); if (closeEnough){ totalScore += itemdata.getScore(); } return totalScore; } public double getTotalCorrectScore(ItemGradingData data, Map publishedAnswerHash) { AnswerIfc answer = (AnswerIfc) publishedAnswerHash.get(data.getPublishedAnswerId()); if (answer == null || answer.getScore() == null) return (double) 0; return answer.getScore().doubleValue(); } private void setIsLate(AssessmentGradingData data, PublishedAssessmentIfc pub){ // If submit from timeout popup, we don't record LATE if (data.getSubmitFromTimeoutPopup()) { data.setIsLate( Boolean.valueOf(false)); } else { if (pub.getAssessmentAccessControl() != null && pub.getAssessmentAccessControl().getDueDate() != null && pub.getAssessmentAccessControl().getDueDate().before(new Date())) data.setIsLate(Boolean.TRUE); else data.setIsLate( Boolean.valueOf(false)); } if (data.getForGrade().booleanValue()) data.setStatus( Integer.valueOf(1)); data.setTotalOverrideScore(Double.valueOf(0)); } public void deleteAll(Collection c) { try { PersistenceService.getInstance(). getAssessmentGradingFacadeQueries().deleteAll(c); } catch (Exception e) { e.printStackTrace(); } } /* Note: * assessmentGrading contains set of itemGrading that are not saved in the DB yet */ public void updateAssessmentGradingScore(AssessmentGradingData adata, PublishedAssessmentIfc pub){ try { Set itemGradingSet = adata.getItemGradingSet(); Iterator iter = itemGradingSet.iterator(); double totalAutoScore = 0; double totalOverrideScore = adata.getTotalOverrideScore().doubleValue(); while (iter.hasNext()){ ItemGradingData i = (ItemGradingData)iter.next(); if (i.getAutoScore()!=null) totalAutoScore += i.getAutoScore().doubleValue(); } double oldAutoScore = adata.getTotalAutoScore().doubleValue(); double scoreDifference = totalAutoScore - oldAutoScore; adata.setTotalAutoScore(Double.valueOf(totalAutoScore)); if (Double.compare((totalAutoScore+totalOverrideScore),Double.valueOf("0").doubleValue())<0){ adata.setFinalScore(Double.valueOf("0")); }else{ adata.setFinalScore(Double.valueOf(totalAutoScore+totalOverrideScore)); } saveOrUpdateAssessmentGrading(adata); if (scoreDifference != 0){ notifyGradebookByScoringType(adata, pub); } } catch (GradebookServiceException ge) { ge.printStackTrace(); throw ge; } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } } public void saveOrUpdateAll(Collection c) { try { PersistenceService.getInstance(). getAssessmentGradingFacadeQueries().saveOrUpdateAll(c); } catch (Exception e) { e.printStackTrace(); } } public PublishedAssessmentIfc getPublishedAssessmentByAssessmentGradingId(String id){ PublishedAssessmentIfc pub = null; try { pub = PersistenceService.getInstance(). getAssessmentGradingFacadeQueries().getPublishedAssessmentByAssessmentGradingId(Long.valueOf(id)); } catch (Exception e) { e.printStackTrace(); } return pub; } public PublishedAssessmentIfc getPublishedAssessmentByPublishedItemId(String publishedItemId){ PublishedAssessmentIfc pub = null; try { pub = PersistenceService.getInstance(). getAssessmentGradingFacadeQueries().getPublishedAssessmentByPublishedItemId(Long.valueOf(publishedItemId)); } catch (Exception e) { e.printStackTrace(); } return pub; } public ArrayList getLastItemGradingDataPosition(Long assessmentGradingId, String agentId) { ArrayList results = null; try { results = PersistenceService.getInstance(). getAssessmentGradingFacadeQueries().getLastItemGradingDataPosition(assessmentGradingId, agentId); } catch (Exception e) { e.printStackTrace(); } return results; } public List getPublishedItemIds(Long assessmentGradingId) { List results = null; try { results = PersistenceService.getInstance(). getAssessmentGradingFacadeQueries().getPublishedItemIds(assessmentGradingId); } catch (Exception e) { e.printStackTrace(); } return results; } public HashSet getItemSet(Long publishedAssessmentId, Long sectionId) { HashSet results = null; try { results = PersistenceService.getInstance(). getAssessmentGradingFacadeQueries().getItemSet(publishedAssessmentId, sectionId); } catch (Exception e) { e.printStackTrace(); } return results; } public Long getTypeId(Long itemGradingId) { Long typeId = null; try { typeId = PersistenceService.getInstance(). getAssessmentGradingFacadeQueries().getTypeId(itemGradingId); } catch (Exception e) { e.printStackTrace(); } return typeId; } public boolean fibmatch(String answer, String input, boolean casesensitive) { try { StringBuilder regex_quotebuf = new StringBuilder(); String REGEX = answer.replaceAll("\\*", "|*|"); String[] oneblank = REGEX.split("\\|"); for (int j = 0; j < oneblank.length; j++) { if ("*".equals(oneblank[j])) { regex_quotebuf.append(".+"); } else { regex_quotebuf.append(Pattern.quote(oneblank[j])); } } String regex_quote = regex_quotebuf.toString(); Pattern p; if (casesensitive){ p = Pattern.compile(regex_quote ); } else { p = Pattern.compile(regex_quote,Pattern.CASE_INSENSITIVE|Pattern.UNICODE_CASE); } Matcher m = p.matcher(input); boolean result = m.matches(); return result; } catch (Exception e){ return false; } } public List getAllAssessmentGradingByAgentId(Long publishedAssessmentId, String agentIdString) { List results = null; try { results = PersistenceService.getInstance(). getAssessmentGradingFacadeQueries().getAllAssessmentGradingByAgentId(publishedAssessmentId, agentIdString); } catch (Exception e) { e.printStackTrace(); } return results; } public List<ItemGradingData> getAllItemGradingDataForItemInGrading(Long assesmentGradingId, Long publihsedItemId) { List<ItemGradingData> results = new ArrayList<ItemGradingData>(); results = PersistenceService.getInstance().getAssessmentGradingFacadeQueries().getAllItemGradingDataForItemInGrading(assesmentGradingId, publihsedItemId); return results; } public HashMap getSiteSubmissionCountHash(String siteId) { HashMap results = new HashMap(); try { results = PersistenceService.getInstance(). getAssessmentGradingFacadeQueries().getSiteSubmissionCountHash(siteId); } catch (Exception e) { e.printStackTrace(); } return results; } public HashMap getSiteInProgressCountHash(final String siteId) { HashMap results = new HashMap(); try { results = PersistenceService.getInstance(). getAssessmentGradingFacadeQueries().getSiteInProgressCountHash(siteId); } catch (Exception e) { e.printStackTrace(); } return results; } public int getActualNumberRetake(Long publishedAssessmentId, String agentIdString) { int actualNumberReatke = 0; try { actualNumberReatke = PersistenceService.getInstance(). getAssessmentGradingFacadeQueries().getActualNumberRetake(publishedAssessmentId, agentIdString); } catch (Exception e) { e.printStackTrace(); } return actualNumberReatke; } public HashMap getActualNumberRetakeHash(String agentIdString) { HashMap actualNumberReatkeHash = new HashMap(); try { actualNumberReatkeHash = PersistenceService.getInstance(). getAssessmentGradingFacadeQueries().getActualNumberRetakeHash(agentIdString); } catch (Exception e) { e.printStackTrace(); } return actualNumberReatkeHash; } public HashMap getSiteActualNumberRetakeHash(String siteIdString) { HashMap numberRetakeHash = new HashMap(); try { numberRetakeHash = PersistenceService.getInstance(). getAssessmentGradingFacadeQueries().getSiteActualNumberRetakeHash(siteIdString); } catch (Exception e) { e.printStackTrace(); } return numberRetakeHash; } public List getStudentGradingSummaryData(Long publishedAssessmentId, String agentIdString) { List results = null; try { results = PersistenceService.getInstance(). getAssessmentGradingFacadeQueries().getStudentGradingSummaryData(publishedAssessmentId, agentIdString); } catch (Exception e) { e.printStackTrace(); } return results; } public int getNumberRetake(Long publishedAssessmentId, String agentIdString) { int numberRetake = 0; try { numberRetake = PersistenceService.getInstance(). getAssessmentGradingFacadeQueries().getNumberRetake(publishedAssessmentId, agentIdString); } catch (Exception e) { e.printStackTrace(); } return numberRetake; } public HashMap getNumberRetakeHash(String agentIdString) { HashMap numberRetakeHash = new HashMap(); try { numberRetakeHash = PersistenceService.getInstance(). getAssessmentGradingFacadeQueries().getNumberRetakeHash(agentIdString); } catch (Exception e) { e.printStackTrace(); } return numberRetakeHash; } public HashMap getSiteNumberRetakeHash(String siteIdString) { HashMap siteActualNumberRetakeList = new HashMap(); try { siteActualNumberRetakeList = PersistenceService.getInstance(). getAssessmentGradingFacadeQueries().getSiteNumberRetakeHash(siteIdString); } catch (Exception e) { e.printStackTrace(); } return siteActualNumberRetakeList; } public void saveStudentGradingSummaryData(StudentGradingSummaryIfc studentGradingSummaryData) { try { PersistenceService.getInstance().getAssessmentGradingFacadeQueries().saveStudentGradingSummaryData(studentGradingSummaryData); } catch (Exception e) { e.printStackTrace(); } } public int getLateSubmissionsNumberByAgentId(Long publishedAssessmentId, String agentIdString, Date dueDate) { int numberRetake = 0; try { numberRetake = PersistenceService.getInstance(). getAssessmentGradingFacadeQueries().getLateSubmissionsNumberByAgentId(publishedAssessmentId, agentIdString, dueDate); } catch (Exception e) { e.printStackTrace(); } return numberRetake; } /** * * @param publishedAssessmentId * @param anonymous * @param audioMessage * @param fileUploadMessage * @param noSubmissionMessage * @param showPartAndTotalScoreSpreadsheetColumns * @param poolString * @param partString * @param questionString * @param textString * @param rationaleString * @param itemGradingCommentsString * @param useridMap * @return a list of responses or null if there are none */ public List getExportResponsesData(String publishedAssessmentId, boolean anonymous, String audioMessage, String fileUploadMessage, String noSubmissionMessage, boolean showPartAndTotalScoreSpreadsheetColumns, String poolString, String partString, String questionString, String textString, String rationaleString, String itemGradingCommentsString, Map useridMap) { List list = null; try { list = PersistenceService.getInstance(). getAssessmentGradingFacadeQueries().getExportResponsesData(publishedAssessmentId, anonymous,audioMessage, fileUploadMessage, noSubmissionMessage, showPartAndTotalScoreSpreadsheetColumns, poolString, partString, questionString, textString, rationaleString, itemGradingCommentsString, useridMap); } catch (Exception e) { e.printStackTrace(); } return list; } private void removeUnsubmittedAssessmentGradingData(AssessmentGradingData data){ try { PersistenceService.getInstance(). getAssessmentGradingFacadeQueries().removeUnsubmittedAssessmentGradingData(data); } catch (Exception e) { //e.printStackTrace(); log.error("Exception thrown from removeUnsubmittedAssessmentGradingData" + e.getMessage()); } } public boolean getHasGradingData(Long publishedAssessmentId) { boolean hasGradingData = false; try { hasGradingData = PersistenceService.getInstance(). getAssessmentGradingFacadeQueries().getHasGradingData(publishedAssessmentId); } catch (Exception e) { e.printStackTrace(); } return hasGradingData; } /** * CALCULATED_QUESTION * @param itemGrading * @param item * @return map of calc answers */ private Map<Integer, String> getCalculatedAnswersMap(ItemGradingData itemGrading, ItemDataIfc item) { HashMap<Integer, String> calculatedAnswersMap = new HashMap<Integer, String>(); // return value from extractCalcQAnswersArray is not used, calculatedAnswersMap is populated by this call extractCalcQAnswersArray(calculatedAnswersMap, item, itemGrading.getAssessmentGradingId(), itemGrading.getAgentId()); return calculatedAnswersMap; } /** * extractCalculations() is a utility function for Calculated Questions. It takes * one parameter, which is a block of text, and looks for any calculations * that are encoded in the text. A calculations is enclosed in [[ ]]. * <p>For example, if the passed parameter is <code>{a} + {b} = {{c}}, [[{a}+{b}]]</code>, * the resulting list would contain one entry: a string of "{a}+{b}" * <p>Formulas must contain at least one variable OR parens OR calculation symbol (*-+/) * @param text contents to be searched * @return a list of matching calculations. If no calculations are found, the * list will be empty. */ public List<String> extractCalculations(String text) { List<String> calculations = extractCalculatedQuestionKeyFromItemText(text, CALCQ_CALCULATION_PATTERN); for (Iterator<String> iterator = calculations.iterator(); iterator.hasNext();) { String calc = iterator.next(); if (!StringUtils.containsAny(calc, "{}()+-*/")) { iterator.remove(); } } return calculations; } /** * extractFormulas() is a utility function for Calculated Questions. It takes * one parameter, which is a block of text, and looks for any formula names * that are encoded in the text. A formula name is enclosed in {{ }}. The * formula itself is encoded elsewhere. * <p>For example, if the passed parameter is <code>{a} + {b} = {{c}}</code>, * the resulting list would contain one entry: a string of "c" * <p>Formulas must begin with an alpha, but subsequent character can be * alpha-numeric * @param text contents to be searched * @return a list of matching formula names. If no formulas are found, the * list will be empty. */ public List<String> extractFormulas(String text) { return extractCalculatedQuestionKeyFromItemText(text, CALCQ_FORMULA_PATTERN); } /** * extractVariables() is a utility function for Calculated Questions. It * takes one parameter, which is a block of text, and looks for any variable * names that are encoded in the text. A variable name is enclosed in { }. * The values of the variable are encoded elsewhere. * <p>For example, if the passed parameter is <code>{a} + {b} = {{c}}</code>, * the resulting list would contain two entries: strings of "a" and "b" * <p>Variables must begin with an alpha, but subsequent character can be * alpha-numeric. * <p>Note - a formula, encoded as {{ }}, will not be mistaken for a variable. * @param text content to be searched * @return a list of matching variable names. If no variables are found, the * list will be empty */ public List<String> extractVariables(String text) { return extractCalculatedQuestionKeyFromItemText(text, CALCQ_ANSWER_PATTERN); } /** * extractCalculatedQuestionKeyFromItemText() is a utility function for Calculated Questions. It * takes a block of item text, and uses a pattern to looks for keys * that are encoded in the text. * @param itemText content to be searched * @param identifierPattern pattern to use to do the search * @return a list of matching key values OR empty if none are found */ private List<String> extractCalculatedQuestionKeyFromItemText(String itemText, Pattern identifierPattern) { LinkedHashSet<String> keys = new LinkedHashSet<String>(); if (itemText != null && itemText.trim().length() > 0) { Matcher keyMatcher = identifierPattern.matcher(itemText); while (keyMatcher.find()) { String match = keyMatcher.group(1); keys.add(match); /* // first character before matching group int start = keyMatcher.start(1) - 2; // first character after matching group int end = keyMatcher.end(1) + 1; // first character after the matching group // if matching group is wrapped by {}, it's not what we are looking for (like another key or just some text) if (start < 0 || end >= itemText.length() || itemText.charAt(start) != '{' || itemText.charAt(end) != '}') { keys.add(match); }*/ } } return new ArrayList<String>(keys); } /** * CALCULATED_QUESTION * @param item the item which contains the formula * @param formulaName the name of the formula * @return the actual formula that matches this formula name OR "" (empty string) if it is not found */ private String replaceFormulaNameWithFormula(ItemDataIfc item, String formulaName) { String result = ""; @SuppressWarnings("unchecked") List<ItemTextIfc> items = item.getItemTextArray(); for (ItemTextIfc itemText : items) { if (itemText.getText().equals(formulaName)) { @SuppressWarnings("unchecked") List<AnswerIfc> answers = itemText.getAnswerArray(); for (AnswerIfc answer : answers) { if (itemText.getSequence().equals(answer.getSequence())) { result = answer.getText(); break; } } } } return result; } /** * CALCULATED_QUESTION * Takes the instructions and breaks it into segments, based on the location * of formula names. One formula would give two segments, two formulas gives * three segments, etc. * <p>Note - in this context, it would probably be easier if any variable value * substitutions have occurred before the breakup is done; otherwise, * each segment will need to have substitutions done. * @param instructions string to be broken up * @return the original string, broken up based on the formula name delimiters */ protected List<String> extractInstructionSegments(String instructions) { List<String> segments = new ArrayList<String>(); if (instructions != null && instructions.length() > 0) { String[] results = CALCQ_FORMULA_SPLIT_PATTERN.split(instructions); // only works because all variables and calculations are already replaced for (String part : results) { segments.add(part); } if (segments.size() == 1) { // add in the trailing segment segments.add(""); } /* final String FUNCTION_BEGIN = "{{"; final String FUNCTION_END = "}}"; while (instructions.indexOf(FUNCTION_BEGIN) > -1 && instructions.indexOf(FUNCTION_END) > -1) { String segment = instructions.substring(0, instructions.indexOf(FUNCTION_BEGIN)); instructions = instructions.substring(instructions.indexOf(FUNCTION_END) + FUNCTION_END.length()); segments.add(segment); } segments.add(instructions); */ } return segments; } /** * CALCULATED_QUESTION * applyPrecisionToNumberString() takes a string representation of a number and returns * a string representation of that number, rounded to the specified number of * decimal places, including trimming decimal places if needed. * Will also throw away the extra trailing zeros as well as removing a trailing decimal point. * @param numberStr * @param decimalPlaces * @return processed number string (will never be null or empty string) */ public String applyPrecisionToNumberString(String numberStr, int decimalPlaces) { // Trim off excess decimal points based on decimalPlaces value BigDecimal bd = new BigDecimal(numberStr); bd = bd.setScale(decimalPlaces, BigDecimal.ROUND_HALF_EVEN); String decimal = "."; // TODO handle localized decimal separator? //DecimalFormatSymbols dfs = new DecimalFormatSymbols(Locale); //char dec = dfs.getDecimalFormatSymbols().getDecimalSeparator(); String displayAnswer = bd.toString(); if (displayAnswer.length() > 2 && displayAnswer.contains(decimal)) { if (decimalPlaces == 0) { // Remove ".0" if decimalPlaces == 0 displayAnswer = displayAnswer.replace(decimal+"0", ""); } else { // trim away all the extra 0s from the end of the number if (displayAnswer.endsWith("0")) { displayAnswer = StringUtils.stripEnd(displayAnswer, "0"); } if (displayAnswer.endsWith(decimal)) { displayAnswer = displayAnswer.substring(0, displayAnswer.length() - 1); } } } return displayAnswer; } /** * CALCULATED_QUESTION * calculateFormulaValues() evaluates all formulas referenced in the * instructions. For each formula name it finds, it retrieves the formula * for the name, substitutes the randomized value for the variables, * evaluates the formula to a real answer, and put the answer, along with * the needed precision and decimal places in the returning Map. * @param variables a Map<String, String> of variables, The key is the * variable name, the value is the text representation, after randomization, * of a number in the variable's defined range. * @param item The question itself, which is needed to provide additional * information for called functions * @return a Map<Integer, String>. the Integer is simply the sequence. * Answers are returned in the order that the formulas are found. * The String is the result of the formula, encoded as (value)|(tolerance),(decimal places) * @throws Exception if either the formula expression fails to pass the * Samigo expression parser, which should never happen as this is validated * when the question is saved, or if a divide by zero error occurs. */ private Map<Integer, String> calculateFormulaValues(Map<String, String> variables, ItemDataIfc item) throws Exception { Map<Integer, String> values = new HashMap<Integer, String>(); String instructions = item.getInstruction(); List<String> formulaNames = this.extractFormulas(instructions); for (int i = 0; i < formulaNames.size(); i++) { String formulaName = formulaNames.get(i); String longFormula = replaceFormulaNameWithFormula(item, formulaName); // {a}+{b}|0.1,1 longFormula = defaultVarianceAndDecimal(longFormula); // sets defaults, in case tolerance or precision isn't set String formula = getAnswerExpression(longFormula); // returns just the formula String answerData = getAnswerData(longFormula); // returns just tolerance and precision int decimalPlaces = getAnswerDecimalPlaces(answerData); String substitutedFormula = replaceMappedVariablesWithNumbers(formula,variables); String formulaValue = processFormulaIntoValue(substitutedFormula, decimalPlaces); values.put(i + 1, formulaValue + answerData); // later answerData will be used for scoring } return values; } /** * CALCULATED_QUESTION * This is a busy method. It does three things: * <br>1. It removes the answer expressions ie. {{x+y}} from the question text. This value is * returned in the ArrayList texts. This format is necessary so that input boxes can be * placed in the text where the {{..}}'s appear. * <br>2. It will call methods to swap out the defined variables with randomly generated values * within the ranges defined by the user. * <br>3. It updates the HashMap answerList with the calculated answers in sequence. It will * parse and calculate what each answer needs to be. * <p>Note: If a divide by zero occurs. We change the random values and try again. It gets limited chances to * get valid values and then will return "infinity" as the answer. * @param answerList will enter the method empty and be filled with sequential answers to the question * @return ArrayList of the pieces of text to display surrounding input boxes */ public List<String> extractCalcQAnswersArray(Map<Integer, String> answerList, ItemDataIfc item, Long gradingId, String agentId) { final int MAX_ERROR_TRIES = 100; boolean hasErrors = true; Map<String, String> variableRangeMap = buildVariableRangeMap(item); List<String> instructionSegments = new ArrayList<String>(0); int attemptCount = 1; while (hasErrors && attemptCount <= MAX_ERROR_TRIES) { instructionSegments.clear(); Map<String, String> variablesWithValues = determineRandomValuesForRanges(variableRangeMap,item.getItemId(), gradingId, agentId, attemptCount); try { Map<Integer, String> evaluatedFormulas = calculateFormulaValues(variablesWithValues, item); answerList.putAll(evaluatedFormulas); // replace the variables in the text with values String instructions = item.getInstruction(); instructions = replaceMappedVariablesWithNumbers(instructions, variablesWithValues); // then replace the calculations with values (must happen AFTER the variable replacement) try { instructions = replaceCalculationsWithValues(instructions, 5); // what decimal precision should we use here? // if could not process the calculation into a result then throws IllegalStateException which will be caught below and cause the numbers to regenerate } catch (SamigoExpressionError e1) { log.warn("Samigo calculated item ("+item.getItemId()+") calculation invalid: "+e1.get()); } // only pull out the segments if the formulas worked instructionSegments = extractInstructionSegments(instructions); hasErrors = false; } catch (Exception e) { attemptCount++; } } return instructionSegments; } /** * CALCULATED_QUESTION * This returns the decimal places value in the stored answer data. * @param allAnswerText * @return */ private int getAnswerDecimalPlaces(String allAnswerText) { String answerData = getAnswerData(allAnswerText); int decimalPlaces = Integer.valueOf(answerData.substring(answerData.indexOf(",")+1, answerData.length())); return decimalPlaces; } /** * CALCULATED_QUESTION * This returns the "|2,2" (variance and decimal display) from the stored answer data. * @param allAnswerText * @return */ private String getAnswerData(String allAnswerText) { String answerData = allAnswerText.substring(allAnswerText.indexOf("|"), allAnswerText.length()); return answerData; } /** * CALCULATED_QUESTION * This is just "(x+y)/z" or if values have been added to the expression it's the * calculated value as stored in the answer data. * @param allAnswerText * @return */ private String getAnswerExpression(String allAnswerText) { String answerExpression = allAnswerText.substring(0, allAnswerText.indexOf("|")); return answerExpression; } /** * CALCULATED_QUESTION * Default acceptable variance and decimalPlaces. An answer is defined by an expression * such as {x+y|1,2} if the variance and decimal places are left off. We have to default * them to something. */ private String defaultVarianceAndDecimal(String allAnswerText) { String defaultVariance = "0.001"; String defaultDecimal = "3"; if (!allAnswerText.contains("|")) { if (!allAnswerText.contains(",")) allAnswerText = allAnswerText.concat("|"+defaultVariance+","+defaultDecimal); else allAnswerText = allAnswerText.replace(",","|"+defaultVariance+","); } if (!allAnswerText.contains(",")) allAnswerText = allAnswerText.concat(","+defaultDecimal); return allAnswerText; } /** * CALCULATED_QUESTION * Takes an answer string and checks for the value returned * is NaN or Infinity, indicating a Samigo formula parse error * Returns false if divide by zero is detected. */ public boolean isAnswerValid(String answer) { String INFINITY = "Infinity"; String NaN = "NaN"; if (answer.length() == 0) return false; if (answer.equals(INFINITY)) return false; if (answer.equals(NaN)) return false; return true; } /** * CALCULATED_QUESTION * replaceMappedVariablesWithNumbers() takes a string and substitutes any variable * names found with the value of the variable. Variables look like {a}, the name of * that variable is "a", and the value of that variable is in variablesWithValues * <p>Note - this function comprehends syntax like "5{x}". If "x" is 37, the * result would be "5*37" * @param expression - the string being substituted into * @param variables - Map key is the variable name, value is what will be * substituted into the expression. * @return a string with values substituted. If answerExpression is null, * returns a blank string (i.e ""). If variablesWithValues is null, returns * the original answerExpression */ public String replaceMappedVariablesWithNumbers(String expression, Map<String, String> variables) { if (expression == null) { expression = ""; } if (variables == null) { variables = new HashMap<String, String>(); } for (Map.Entry<String, String> entry : variables.entrySet()) { String name = "{" + entry.getKey() + "}"; String value = entry.getValue(); // not doing string replace or replaceAll because the value being // substituted can change for each occurrence of the variable. int index = expression.indexOf(name); while (index > -1) { String prefix = expression.substring(0, index); String suffix = expression.substring(index + name.length()); String replacementValue = value; // if last character of prefix is a number or the edge of parenthesis, multiply by the variable // if x = 37, 5{x} -> 5*37 // if x = 37 (5+2){x} -> (5+2)*37 (prefix is (5+2) if (prefix.length() > 0 && (Character.isDigit(prefix.charAt(prefix.length() - 1)) || prefix.charAt(prefix.length() - 1) == ')')) { replacementValue = "*" + replacementValue; } // if first character of suffix is a number or the edge of parenthesis, multiply by the variable // if x = 37, {x}5 -> 37*5 // if x = 37, {x}(5+2) -> 37*(5+2) (suffix is (5+2) if (suffix.length() > 0 && (Character.isDigit(suffix.charAt(0)) || suffix.charAt(0) == '(')) { replacementValue = replacementValue + "*"; } // perform substitution, then look for the next instance of current variable expression = prefix + replacementValue + suffix; index = expression.indexOf(name); } } return expression; } /** * CALCULATED_QUESTION * replaceMappedVariablesWithNumbers() takes a string and substitutes any variable * names found with the value of the variable. Variables look like {a}, the name of * that variable is "a", and the value of that variable is in variablesWithValues * <p>Note - this function comprehends syntax like "5{x}". If "x" is 37, the * result would be "5*37" * @param expression - the string which will be scanned for calculations * @return the input string with calculations replaced with number values. If answerExpression is null, * returns a blank string (i.e "") and if no calculations are found then original string is returned. * @throws IllegalStateException if the formula value cannot be calculated * @throws SamigoExpressionError if the formula cannot be parsed */ public String replaceCalculationsWithValues(String expression, int decimalPlaces) throws SamigoExpressionError { if (StringUtils.isEmpty(expression)) { expression = ""; } else { Matcher keyMatcher = CALCQ_CALCULATION_PATTERN.matcher(expression); ArrayList<String> toReplace = new ArrayList<String>(); while (keyMatcher.find()) { String match = keyMatcher.group(1); toReplace.add(match); // should be the formula } if (toReplace.size() > 0) { for (String formula : toReplace) { String replace = CALCULATION_OPEN+formula+CALCULATION_CLOSE; String formulaValue = processFormulaIntoValue(formula, decimalPlaces); expression = StringUtils.replace(expression, replace, formulaValue); } } } return expression; } /** * CALCULATED_QUESTION * Process a single formula into a final string representing the calculated value of the formula * * @param formula the formula to process (e.g. 1 * 2 + 3 - 4), All variable replacement must have already happened * @param decimalPlaces number of decimals to include in the final output * @return the value of the formula OR empty string if there is nothing to process * @throws IllegalStateException if the formula value cannot be calculated (typically caused by 0 divisors and the like) * @throws SamigoExpressionError if the formula cannot be parsed */ public String processFormulaIntoValue(String formula, int decimalPlaces) throws SamigoExpressionError { String value = ""; if (StringUtils.isEmpty(formula)) { value = ""; } else { if (decimalPlaces < 0) { decimalPlaces = 0; } formula = cleanFormula(formula); SamigoExpressionParser parser = new SamigoExpressionParser(); // this will turn the expression into a number in string form String numericString = parser.parse(formula, decimalPlaces+1); if (this.isAnswerValid(numericString)) { numericString = applyPrecisionToNumberString(numericString, decimalPlaces); value = numericString; } else { throw new IllegalStateException("Invalid calculation formula ("+formula+") result ("+numericString+"), result could not be calculated"); } } return value; } /** * Cleans up formula text so that whitespaces are normalized or removed * @param formula formula with variables or without * @return the cleaned formula */ public static String cleanFormula(String formula) { if (StringUtils.isEmpty(formula)) { formula = ""; } else { formula = StringUtils.trimToEmpty(formula).replaceAll("\\s+", " "); } return formula; } /** * isNegativeSqrt() looks at the incoming expression and looks specifically * to see if it executes the SQRT function. If it does, it evaluates it. If * it has an error, it assumes that the SQRT function tried to evaluate a * negative number and evaluated to NaN. * <p>Note - the incoming expression should have no variables. They should * have been replaced before this function was called * @param expression a mathematical formula, with all variables replaced by * real values, to be evaluated * @return true if the function uses the SQRT function, and the SQRT function * evaluates as an error; else false * @throws SamigoExpressionError if the evaluation of the SQRT function throws * some other parse error */ public boolean isNegativeSqrt(String expression) throws SamigoExpressionError { Pattern sqrt = Pattern.compile("sqrt\\s*\\("); boolean isNegative = false; if (expression == null) { expression = ""; } expression = expression.toLowerCase(); Matcher matcher = sqrt.matcher(expression); while (matcher.find()) { int x = matcher.end(); int p = 1; // Parentheses left to match int len = expression.length(); while (p > 0 && x < len) { if (expression.charAt(x) == ')') { --p; } else if (expression.charAt(x) == '(') { ++p; } ++x; } if (p == 0) { String sqrtExpression = expression.substring(matcher.start(), x); SamigoExpressionParser parser = new SamigoExpressionParser(); String numericAnswerString = parser.parse(sqrtExpression); if (!isAnswerValid(numericAnswerString)) { isNegative = true; break; // finding 1 invalid one is enough } } } return isNegative; } /** * CALCULATED_QUESTION * Takes a map of ranges and randomly chooses values for those ranges and stores them in a new map. */ public Map<String, String> determineRandomValuesForRanges(Map<String, String> variableRangeMap, long itemId, long gradingId, String agentId, int validAnswersAttemptCount) { Map<String, String> variableValueMap = new HashMap<String, String>(); // seed random number generator long seed = getCalcuatedQuestionSeed(itemId, gradingId, agentId, validAnswersAttemptCount); Random generator = new Random(seed); Iterator<Map.Entry<String, String>> i = variableRangeMap.entrySet().iterator(); while(i.hasNext()) { Map.Entry<String, String>entry = i.next(); String delimRange = entry.getValue().toString(); // ie. "-100|100,2" double minVal = Double.valueOf(delimRange.substring(0, delimRange.indexOf('|'))); double maxVal = Double.valueOf(delimRange.substring(delimRange.indexOf('|')+1, delimRange.indexOf(','))); int decimalPlaces = Integer.valueOf(delimRange.substring(delimRange.indexOf(',')+1, delimRange.length())); // This line does the magic of creating the random variable value within the range. Double randomValue = minVal + (maxVal - minVal) * generator.nextDouble(); // Trim off excess decimal points based on decimalPlaces value BigDecimal bd = new BigDecimal(randomValue); bd = bd.setScale(decimalPlaces,BigDecimal.ROUND_HALF_UP); randomValue = bd.doubleValue(); String displayNumber = randomValue.toString(); // Remove ".0" if decimalPlaces ==0 if (decimalPlaces == 0) { displayNumber = displayNumber.replace(".0", ""); } variableValueMap.put(entry.getKey(), displayNumber); } return variableValueMap; } /** * CALCULATED_QUESTION * Accepts an ItemDataIfc and returns a HashMap with the pairs of * variable names and variable ranges. */ private Map<String, String> buildVariableRangeMap(ItemDataIfc item) { HashMap<String, String> variableRangeMap = new HashMap<String, String>(); String instructions = item.getInstruction(); List<String> variables = this.extractVariables(instructions); // Loop through each VarName @SuppressWarnings("unchecked") List<ItemTextIfc> itemTextList = item.getItemTextArraySorted(); for (ItemTextIfc varName : itemTextList) { // only look at variables for substitution, ignore formulas if (variables.contains(varName.getText())) { @SuppressWarnings("unchecked") List<AnswerIfc> answerList = varName.getAnswerArray(); for (AnswerIfc range : answerList) { if (!(range.getLabel() == null) ) { // answer records and variable records are in the same set if (range.getSequence().equals(varName.getSequence()) && range.getText().contains("|")) { variableRangeMap.put(varName.getText(), range.getText()); } } } } } return variableRangeMap; } /** * CALCULATED_QUESTION * Make seed by combining user id, item (question) id, grading (submission) id, and attempt count (due to div by 0) */ private long getCalcuatedQuestionSeed(long itemId, long gradingId, String agentId, int validAnswersAttemptCount) { long userSeed = (long) agentId.hashCode(); return userSeed * itemId * gradingId * validAnswersAttemptCount; } /** * CALCULATED_QUESTION * Simple to check to see if this is a calculated question. It's used in storeGrades() to see if the sort is necessary. */ private boolean isCalcQuestion(List tempItemGradinglist, HashMap publishedItemHash) { if (tempItemGradinglist == null) return false; if (tempItemGradinglist.size() == 0) return false; Iterator iter = tempItemGradinglist.iterator(); ItemGradingData itemCheck = (ItemGradingData) iter.next(); Long itemId = itemCheck.getPublishedItemId(); ItemDataIfc item = (ItemDataIfc) publishedItemHash.get(itemId); if (item.getTypeId().equals(TypeIfc.CALCULATED_QUESTION)) { return true; } return false; } public ArrayList getHasGradingDataAndHasSubmission(Long publishedAssessmentId) { ArrayList al = new ArrayList(); try { al = PersistenceService.getInstance(). getAssessmentGradingFacadeQueries().getHasGradingDataAndHasSubmission(publishedAssessmentId); } catch (Exception e) { e.printStackTrace(); } return al; } public String getFileName(Long itemGradingId, String agentId, String filename) { String name = ""; try { name = PersistenceService.getInstance(). getAssessmentGradingFacadeQueries().getFilename(itemGradingId, agentId, filename); } catch (Exception e) { e.printStackTrace(); } return name; } public List getUpdatedAssessmentList(String agentId, String siteId) { List list = null; try { list = PersistenceService.getInstance(). getAssessmentGradingFacadeQueries().getUpdatedAssessmentList(agentId, siteId); } catch (Exception e) { e.printStackTrace(); } return list; } public List getSiteNeedResubmitList(String siteId) { List list = null; try { list = PersistenceService.getInstance(). getAssessmentGradingFacadeQueries().getSiteNeedResubmitList(siteId); } catch (Exception e) { e.printStackTrace(); } return list; } public void autoSubmitAssessments() { try { PersistenceService.getInstance(). getAssessmentGradingFacadeQueries().autoSubmitAssessments(); } catch (Exception e) { e.printStackTrace(); } } public ItemGradingAttachment createItemGradingAttachment( ItemGradingData itemGrading, String resourceId, String filename, String protocol) { ItemGradingAttachment attachment = null; try { attachment = PersistenceService.getInstance(). getAssessmentGradingFacadeQueries().createItemGradingtAttachment(itemGrading, resourceId, filename, protocol); } catch (Exception e) { e.printStackTrace(); } return attachment; } public void removeItemGradingAttachment(String attachmentId) { PersistenceService.getInstance().getAssessmentGradingFacadeQueries() .removeItemGradingAttachment(Long.valueOf(attachmentId)); } public void saveOrUpdateAttachments(List list) { PersistenceService.getInstance().getAssessmentGradingFacadeQueries() .saveOrUpdateAttachments(list); } public HashMap getInProgressCounts(String siteId) { return PersistenceService.getInstance().getAssessmentGradingFacadeQueries(). getInProgressCounts(siteId); } public HashMap getSubmittedCounts(String siteId) { return PersistenceService.getInstance().getAssessmentGradingFacadeQueries(). getSubmittedCounts(siteId); } public void completeItemGradingData(AssessmentGradingData assessmentGradingData) { PersistenceService.getInstance().getAssessmentGradingFacadeQueries(). completeItemGradingData(assessmentGradingData); } /** * This grades multiple choice and true false questions. Since * multiple choice/multiple select has a separate ItemGradingData for * each choice, they're graded the same way the single choice are. * BUT since we have Partial Credit stuff around we have to have a separate method here --mustansar * Choices should be given negative score values if one wants them * to lose points for the wrong choice. */ public double getAnswerScoreMCQ(ItemGradingData data, Map publishedAnswerHash) { AnswerIfc answer = (AnswerIfc) publishedAnswerHash.get(data.getPublishedAnswerId()); if (answer == null || answer.getScore() == null) { return 0d; } else if (answer.getIsCorrect().booleanValue()){ // instead of using answer score Item score needs to be used here return (answer.getItem().getScore().doubleValue()); //--mustansar } return (answer.getItem().getScore().doubleValue()*answer.getPartialCredit().doubleValue())/100d; } /** * Reoder a map of EMI scores * @param emiScoresMap * @return */ private Map<Long, Map<Long, Map<Long, EMIScore>>> reorderEMIScoreMap(Map<Long, Map<Long,Set<EMIScore>>> emiScoresMap){ Map<Long, Map<Long, Map<Long, EMIScore>>> scoresMap = new HashMap<Long, Map<Long, Map<Long, EMIScore>>>(); for(Map<Long,Set<EMIScore>> emiItemScoresMap: emiScoresMap.values()){ for(Set<EMIScore> scoreSet: emiItemScoresMap.values()){ for(EMIScore s: scoreSet){ Map<Long, Map<Long, EMIScore>> scoresItem = scoresMap.get(s.itemId); if(scoresItem == null){ scoresItem = new HashMap<Long, Map<Long, EMIScore>>(); scoresMap.put(s.itemId, scoresItem); } Map<Long, EMIScore> scoresItemText = scoresItem.get(s.itemTextId); if(scoresItemText == null){ scoresItemText = new HashMap<Long, EMIScore>(); scoresItem.put(s.itemTextId, scoresItemText); } scoresItemText.put(s.answerId, s); } } } return scoresMap; } /** * hasDistractors looks at an itemData object for a Matching question and determines * if all of the choices have correct matches or not. * @param item * @return true if any of the choices do not have a correct answer (a distractor choice), or false * if all choices have at least one correct answer */ public boolean hasDistractors(ItemDataIfc item) { boolean hasDistractor = false; Iterator<ItemTextIfc> itemIter = item.getItemTextArraySorted().iterator(); while (itemIter.hasNext()) { ItemTextIfc curItem = itemIter.next(); if (isDistractor(curItem)) { hasDistractor = true; break; } } return hasDistractor; } /** * determines if the passed parameter is a distractor * <p>For ItemTextIfc objects that hold data for matching type questions, a distractor * is a choice that has no valid matches (i.e. no correct answers). This function returns * if this ItemTextIfc object has any correct answers * @param itemText * @return true if itemtext has no correct answers (a distrator) or false if itemtext has at least * one correct answer */ public boolean isDistractor(ItemTextIfc itemText) { // look for items that do not have any correct answers boolean hasCorrectAnswer = false; List<AnswerIfc> answers = itemText.getAnswerArray(); Iterator<AnswerIfc> answerIter = answers.iterator(); while (answerIter.hasNext()) { AnswerIfc answer = answerIter.next(); if (answer.getIsCorrect() != null && answer.getIsCorrect().booleanValue()) { hasCorrectAnswer = true; break; } } return !hasCorrectAnswer; } public List getUnSubmittedAssessmentGradingDataList(Long publishedAssessmentId, String agentIdString) { return PersistenceService.getInstance().getAssessmentGradingFacadeQueries(). getUnSubmittedAssessmentGradingDataList(publishedAssessmentId, agentIdString); } } /** * A EMI score * @author jsmith * */ class EMIScore implements Comparable<EMIScore>{ long itemId = 0L; long itemTextId = 0L; long answerId = 0L; boolean correct = false; double score = 0.0; double effectiveScore = 0.0; /** * Create an EMI Score object * @param itemId * @param itemTextId * @param answerId * @param correct * @param score */ public EMIScore(Long itemId, Long itemTextId, Long answerId, boolean correct, Double score){ this.itemId = itemId == null? 0L : itemId.longValue(); this.itemTextId = itemTextId == null? 0L : itemTextId.longValue(); this.answerId = answerId == null? 0L : answerId.longValue(); this.correct = correct; this.score = score == null? 0L : score.doubleValue(); } public int compareTo(EMIScore o) { //we want the correct higher scores first if(correct == o.correct){ int c = Double.compare(o.score, score); if (c == 0){ if(itemId != o.itemId){ return (int)(itemId - o.itemId); } if(itemTextId != o.itemTextId){ return (int)(itemTextId - o.itemTextId); } if(answerId != o.answerId){ return (int)(answerId - o.answerId); } return hashCode() - o.hashCode(); }else{ return c; } }else{ return correct?-1:1; } } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (int)itemId; result = prime * result + (int)itemTextId; result = prime * result + (int)answerId; return result; } @Override public boolean equals(Object obj) { if (obj == null) return false; if (this == obj) return true; if (getClass() != obj.getClass()){ return false; } EMIScore other = (EMIScore) obj; return (itemId == other.itemId && itemTextId == other.itemTextId && answerId == other.answerId); } @Override public String toString() { return itemId + ":" + itemTextId + ":" + answerId + "(" + correct + ":" + score + ":" + effectiveScore + ")"; } }
SAM-2337 fix for no answer in calculated scoring git-svn-id: 574bb14f304dbe16c01253ed6697ea749724087f@309468 66ffb92e-73f9-0310-93c1-f5514f145a0a
samigo/samigo-services/src/java/org/sakaiproject/tool/assessment/services/GradingService.java
SAM-2337 fix for no answer in calculated scoring
<ide><path>amigo/samigo-services/src/java/org/sakaiproject/tool/assessment/services/GradingService.java <ide> <ide> if (data.getAnswerText() == null) return totalScore; // zero for blank <ide> <add> if (!calculatedAnswersMap.containsKey(calcQuestionAnswerSequence)) { <add> return totalScore; <add> } <ide> // this variable should look something like this "42.1|2,2" <ide> String allAnswerText = calculatedAnswersMap.get(calcQuestionAnswerSequence).toString(); <ide>
Java
mit
572a86313fd24be653734eeb6e045d347f0343a7
0
selig/qea
package creation; import static structure.impl.other.Quantification.EXISTS; import static structure.impl.other.Quantification.FORALL; import static structure.impl.other.Quantification.NONE; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import monitoring.intf.Monitor; import structure.impl.other.Quantification; import structure.impl.other.Transition; import structure.impl.qeas.QVar01_FVar_Det_QEA; import structure.impl.qeas.QVar01_FVar_NonDet_QEA; import structure.impl.qeas.QVar01_NoFVar_Det_QEA; import structure.impl.qeas.QVar01_NoFVar_NonDet_QEA; import structure.impl.qeas.QVar1_FVar_Det_FixedQVar_QEA; import structure.impl.qeas.QVar1_FVar_NonDet_FixedQVar_QEA; import structure.intf.Assignment; import structure.intf.Guard; import structure.intf.QEA; import exceptions.ShouldNotHappenException; /* * The general idea of this class is to allow us to build a QEA without knowing which * implementation it has. * * Usage: * create a builder * add stuff to it * call make * * This could be used along with a parser to parse some textual representation * of QEA, as we can add different kinds of transitions straightforwardly. However, I'm not sure * how guards and assignments would work in this case. */ public class QEABuilder { private static final boolean DEBUG = true; /* * To create a QEA we need - a set of transitions - a set of final stats - a * quanfication list * * We use internal representations */ private static class VarOrVal { int var = -1000; Object val; } private static class TempTransition { int start, end = -1; int event_name = -1; VarOrVal[] event_args; Guard g; Assignment a; TempEvent temp_event = null; public int[] var_args() { if (event_args == null) { return new int[] {}; } int[] vargs = new int[event_args.length]; for (int i = 0; i < event_args.length; i++) { vargs[i] = event_args[i].var; if (vargs[i] == 0) { throw new RuntimeException( "Do not yet support values in transitions"); } } return vargs; } @Override public String toString() { return start + "-" + event_name + "(" + Arrays.toString(event_args) + ")-" + end; } } private static class TempEvent { int event_name = -1; VarOrVal[] event_args = null; @Override public int hashCode() { return (event_name + Arrays.toString(event_args)).hashCode(); } @Override public boolean equals(Object o) { // if(o==this) return true; if (o instanceof TempEvent) { TempEvent other = (TempEvent) o; if (other.event_name != event_name) { return false; } if (other.event_args == null && event_args == null) { return true; } if (other.event_args == null || event_args == null) { return false; } if (other.event_args.length != event_args.length) { return false; } for (int i = 0; i < event_args.length; i++) { if (other.event_args[i] != event_args[i]) { return false; } } return true; } else { return false; } } @Override public String toString() { return event_name + "(" + Arrays.toString(event_args) + ")"; } } private static class Quant { boolean universal; int var = 1; Guard g; } Set<TempTransition> transitions = new HashSet<TempTransition>(); Set<Integer> finalstates = new HashSet<Integer>(); List<Quant> quants = new ArrayList<Quant>(); /* * It will be good to give the qea a name */ String name; public QEABuilder(String name) { this.name = name; } public QEA make() { String error = wellFormed(); if (error != null) { throw new ShouldNotHappenException(error); } // first get number of states and events int states = countStates(); int events = countEvents(); QEA qea = null; // Propositional first if (quants.size() == 0) { qea = makeProp(states, events); } // Single quantifier next if (quants.size() == 1) { qea = makeSingle(states, events); } if (qea != null) { qea.setName(name); return qea; } throw new ShouldNotHappenException( "I don't know how to make that kind of QEA yet"); } public QEA make(Class<? extends Monitor<?>> monitorClass) { String error = wellFormed(); if (error != null) { throw new ShouldNotHappenException(error); } // first get number of states and events int states = countStates(); int events = countEvents(); // Propositional first if (quants.size() == 0) { return makeProp(states, events); } // Single quantifier next if (quants.size() == 1) { return makeSingle(states, events); } throw new ShouldNotHappenException( "I don't know how to make that kind of QEA yet"); } private QEA makeProp(int states, int events) { boolean[] strongStates = computeStrongStates(); if (noFreeVariables()) { if (isEventDeterministic()) { QVar01_NoFVar_Det_QEA qea = new QVar01_NoFVar_Det_QEA(states, events, 1, NONE); for (TempTransition t : transitions) { qea.addTransition(t.start, t.event_name, t.end); } for (Integer s : finalstates) { qea.setStateAsFinal(s); } for (int i = 0; i < strongStates.length; i++) { if (strongStates[i]) { qea.setStateAsStrong(i); } } return qea; } else { QVar01_NoFVar_NonDet_QEA qea = new QVar01_NoFVar_NonDet_QEA( states, events, 1, NONE); Map<Integer, Set<Integer>>[] actual_trans = new Map[states + 1]; for (TempTransition t : transitions) { Map<Integer, Set<Integer>> this_state = actual_trans[t.start]; if (this_state == null) { actual_trans[t.start] = new HashMap<Integer, Set<Integer>>(); } this_state = actual_trans[t.start]; Set<Integer> nextstates = this_state.get(t.event_name); if (nextstates == null) { nextstates = new HashSet<Integer>(); this_state.put(t.event_name, nextstates); } nextstates.add(t.end); } for (int i = 0; i < actual_trans.length; i++) { if (actual_trans[i] != null) { for (Map.Entry<Integer, Set<Integer>> entry : actual_trans[i] .entrySet()) { int[] nextstates = new int[entry.getValue().size()]; int j = 0; for (Integer s : entry.getValue()) { nextstates[j] = s; j++; } qea.addTransitions(i, (entry.getKey()), nextstates); } } } for (Integer s : finalstates) { qea.setStateAsFinal(s); } for (int i = 0; i < strongStates.length; i++) { if (strongStates[i]) { qea.setStateAsStrong(i); } } return qea; } } else { if (isEventDeterministic()) { int fvars = countFreeVars(); QVar01_FVar_Det_QEA qea = new QVar01_FVar_Det_QEA(states, events, 1, NONE, fvars); for (TempTransition t : transitions) { Transition trans = new Transition(t.var_args(), t.g, t.end); qea.addTransition(t.start, t.event_name, trans); } for (Integer s : finalstates) { qea.setStateAsFinal(s); } for (int i = 0; i < strongStates.length; i++) { if (strongStates[i]) { qea.setStateAsStrong(i); } } return qea; } else { int frees = countFreeVars(); QVar01_FVar_NonDet_QEA qea = new QVar01_FVar_NonDet_QEA(states, events, 1, NONE, frees); Map<Integer, Set<Transition>>[] actual_trans = new Map[states + 1]; for (TempTransition t : transitions) { Map<Integer, Set<Transition>> this_state = actual_trans[t.start]; if (this_state == null) { actual_trans[t.start] = new HashMap<Integer, Set<Transition>>(); } this_state = actual_trans[t.start]; Set<Transition> nextstates = this_state.get(t.event_name); if (nextstates == null) { nextstates = new HashSet<Transition>(); this_state.put(t.event_name, nextstates); } nextstates .add(new Transition(t.var_args(), t.g, t.a, t.end)); } for (int i = 0; i < actual_trans.length; i++) { if (actual_trans[i] != null) { for (Map.Entry<Integer, Set<Transition>> entry : actual_trans[i] .entrySet()) { Transition[] nextstates = new Transition[entry .getValue().size()]; int j = 0; for (Transition s : entry.getValue()) { nextstates[j] = s; j++; } qea.addTransitions(i, (entry.getKey()), nextstates); } } } for (Integer s : finalstates) { qea.setStateAsFinal(s); } for (int i = 0; i < strongStates.length; i++) { if (strongStates[i]) { qea.setStateAsStrong(i); } } return qea; } } } private QEA makeSingle(int states, int events) { boolean[] strongStates = computeStrongStates(); Quantification q; if (quants.get(0).universal) { q = FORALL; } else { q = EXISTS; } if (noFreeVariables()) { if (isEventDeterministic()) { QVar01_NoFVar_Det_QEA qea = new QVar01_NoFVar_Det_QEA(states, events, 1, q); for (TempTransition t : transitions) { qea.addTransition(t.start, t.event_name, t.end); } for (Integer s : finalstates) { qea.setStateAsFinal(s); } for (int i = 0; i < strongStates.length; i++) { if (strongStates[i]) { qea.setStateAsStrong(i); } } return qea; } else { QVar01_NoFVar_NonDet_QEA qea = new QVar01_NoFVar_NonDet_QEA( states, events, 1, q); Map<Integer, Set<Integer>>[] actual_trans = new Map[states + 1]; for (TempTransition t : transitions) { Map<Integer, Set<Integer>> this_state = actual_trans[t.start]; if (this_state == null) { actual_trans[t.start] = new HashMap<Integer, Set<Integer>>(); } this_state = actual_trans[t.start]; Set<Integer> nextstates = this_state.get(t.event_name); if (nextstates == null) { nextstates = new HashSet<Integer>(); this_state.put(t.event_name, nextstates); } nextstates.add(t.end); } for (int i = 0; i < actual_trans.length; i++) { if (actual_trans[i] != null) { for (Map.Entry<Integer, Set<Integer>> entry : actual_trans[i] .entrySet()) { int[] nextstates = new int[entry.getValue().size()]; int j = 0; for (Integer s : entry.getValue()) { nextstates[j] = s; j++; } qea.addTransitions(i, (entry.getKey()), nextstates); } } } for (Integer s : finalstates) { qea.setStateAsFinal(s); } for (int i = 0; i < strongStates.length; i++) { if (strongStates[i]) { qea.setStateAsStrong(i); } } return qea; } } else { int frees = countFreeVars(); if (fixedQVar()) { if (isEventDeterministic()) { QVar1_FVar_Det_FixedQVar_QEA qea = new QVar1_FVar_Det_FixedQVar_QEA( states, events, 1, q, frees); for (TempTransition t : transitions) { Transition trans = new Transition(t.var_args(), t.g, t.a, t.end); qea.addTransition(t.start, t.event_name, trans); } for (Integer s : finalstates) { qea.setStateAsFinal(s); } for (int i = 0; i < strongStates.length; i++) { if (strongStates[i]) { qea.setStateAsStrong(i); } } return qea; } else { QVar1_FVar_NonDet_FixedQVar_QEA qea = new QVar1_FVar_NonDet_FixedQVar_QEA( states, events, 1, q, frees); Map<Integer, Set<Transition>>[] actual_trans = new Map[states + 1]; for (TempTransition t : transitions) { Map<Integer, Set<Transition>> this_state = actual_trans[t.start]; if (this_state == null) { actual_trans[t.start] = new HashMap<Integer, Set<Transition>>(); } this_state = actual_trans[t.start]; Set<Transition> nextstates = this_state .get(t.event_name); if (nextstates == null) { nextstates = new HashSet<Transition>(); this_state.put(t.event_name, nextstates); } nextstates.add(new Transition(t.var_args(), t.g, t.a, t.end)); } for (int i = 0; i < actual_trans.length; i++) { if (actual_trans[i] != null) { for (Map.Entry<Integer, Set<Transition>> entry : actual_trans[i] .entrySet()) { Transition[] nextstates = new Transition[entry .getValue().size()]; int j = 0; for (Transition s : entry.getValue()) { nextstates[j] = s; j++; } qea.addTransitions(i, (entry.getKey()), nextstates); } } } for (Integer s : finalstates) { qea.setStateAsFinal(s); } for (int i = 0; i < strongStates.length; i++) { if (strongStates[i]) { qea.setStateAsStrong(i); } } return qea; } } else { if (isEventDeterministic()) { QVar01_FVar_Det_QEA qea = new QVar01_FVar_Det_QEA(states, events, 1, q, frees); for (TempTransition t : transitions) { Transition trans = new Transition(t.var_args(), t.g, t.a, t.end); trans.setAssignment(t.a); trans.setGuard(t.g); qea.addTransition(t.start, t.event_name, trans); } for (Integer s : finalstates) { qea.setStateAsFinal(s); } for (int i = 0; i < strongStates.length; i++) { if (strongStates[i]) { qea.setStateAsStrong(i); } } return qea; } else { QVar01_FVar_NonDet_QEA qea = new QVar01_FVar_NonDet_QEA( states, events, 1, q, frees); Map<Integer, Set<Transition>>[] actual_trans = new Map[states + 1]; for (TempTransition t : transitions) { Map<Integer, Set<Transition>> this_state = actual_trans[t.start]; if (this_state == null) { actual_trans[t.start] = new HashMap<Integer, Set<Transition>>(); } this_state = actual_trans[t.start]; Set<Transition> nextstates = this_state .get(t.event_name); if (nextstates == null) { nextstates = new HashSet<Transition>(); this_state.put(t.event_name, nextstates); } nextstates.add(new Transition(t.var_args(), t.g, t.a, t.end)); } for (int i = 0; i < actual_trans.length; i++) { if (actual_trans[i] != null) { for (Map.Entry<Integer, Set<Transition>> entry : actual_trans[i] .entrySet()) { Transition[] nextstates = new Transition[entry .getValue().size()]; int j = 0; for (Transition s : entry.getValue()) { nextstates[j] = s; j++; } qea.addTransitions(i, (entry.getKey()), nextstates); } } } for (Integer s : finalstates) { qea.setStateAsFinal(s); } for (int i = 0; i < strongStates.length; i++) { if (strongStates[i]) { qea.setStateAsStrong(i); } } return qea; } } } } private int countStates() { int max = 0; for (TempTransition t : transitions) { if (t.start > max) { max = t.start; } if (t.end > max) { max = t.end; } } return max; } private int countEvents() { int max = 0; for (TempTransition t : transitions) { if (t.event_name > max) { max = t.event_name; } } return max; } // TODO Free variables in guards/assignments not present in transitions are // not being considered private int countFreeVars() { Set<Integer> qvars = new HashSet<Integer>(); int max = 0; for (Quant q : quants) { qvars.add(q.var); } // Set<Integer> fvars = new HashSet<Integer>(); for (TempTransition t : transitions) { if (t.event_args != null) { for (VarOrVal event_arg : t.event_args) { int var = event_arg.var; if (var != 0 && !qvars.contains(var)) { // fvars.add(var); if (var > max) { max = var; } } } } } return max; } /* * Check that all transitions have a start, end and event name And that all * quantifications have a var */ private String wellFormed() { int[] num_args = new int[1 + countEvents()]; for (int i = 0; i < num_args.length; i++) { num_args[i] = -1; } for (TempTransition trans : transitions) { if (trans.start < 1) { return "All states should be >0"; } if (trans.end < 1) { return "All states should be >0"; } if (trans.event_name < 1) { return "All event names should be >0"; } if (trans.event_args != null) { if (num_args[trans.event_name] == -1) { num_args[trans.event_name] = trans.event_args.length; } else if (num_args[trans.event_name] != trans.event_args.length) { return "All events with the same name should have the same number of parameters"; } for (VarOrVal event_arg : trans.event_args) { if (event_arg == null || (event_arg.val == null && event_arg.var == -1000)) { return "The paramters were not correctly defined in a transition"; } } } } int qstep = -1; for (Quant q : quants) { if (q.var != qstep) { return "Quantified variables should named -1,-2,..."; } qstep--; } return null; } /* * Get the quantified variables Check that all transitions that have * arguments either use a value or a quantified variable */ private boolean noFreeVariables() { Set<Integer> qvars = new HashSet<Integer>(); for (Quant q : quants) { qvars.add(q.var); } for (TempTransition t : transitions) { if (t.event_args != null) { for (int i = 0; i < t.event_args.length; i++) { if (t.event_args[i].val == null && !(qvars.contains(t.event_args[i].var))) { return false; } } } } return true; } /* * Check that for each state and event name there is a single transition */ private boolean isEventDeterministic() { Map<Integer, Set<Integer>> start_trans = new HashMap<Integer, Set<Integer>>(); for (TempTransition t : transitions) { Set<Integer> states = start_trans.get(t.start); if (states == null) { states = new HashSet<Integer>(); start_trans.put(t.start, states); } if (!states.add(t.event_name)) { return false; } } return true; } /** * Checks if the QEA of this builder meets the conditions for the FixedQVar * optimisation. This is: * <ul> * <li>There is a single quantified variable * <li>All the events contain the quantified variable as the first parameter * <li>There are no events without parameters * </ul> * * @return <code>true</code> if the QEA of this builder meets the conditions * for the FixedQVar optimisation; <code>false</code> otherwise */ private boolean fixedQVar() { // Check there is a single quantified variable if (quants.size() != 1) { return false; } int qVar = quants.get(0).var; // Iterate over all the transitions for (TempTransition t : transitions) { // Check it's not an event without parameters if (t.event_args == null || t.event_args.length == 0) { return false; } // Check the quantified variable is in the first position if (t.event_args[0].var != qVar) { return false; } // Check starting from the 2nd position there are only free vars for (int i = 1; i < t.event_args.length; i++) { if (t.event_args[i].var == qVar) { return false; } } } return true; } /* * CREATING QEA */ // add a propositional transition public void addTransition(int start, int propname, int end) { TempTransition trans = new TempTransition(); trans.start = start; trans.end = end; trans.event_name = propname; transitions.add(trans); } // add a variable only transition public void addTransition(int start, int propname, int[] vargs, int end) { TempTransition trans = new TempTransition(); trans.start = start; trans.end = end; trans.event_name = propname; VarOrVal[] args = new VarOrVal[vargs.length]; for (int i = 0; i < vargs.length; i++) { args[i] = new VarOrVal(); args[i].var = vargs[i]; } trans.event_args = args; transitions.add(trans); } // incremental transition adding TempTransition inctrans = null; List<VarOrVal> incargs = null; public void startTransition(int start) { inctrans = new TempTransition(); inctrans.start = start; incargs = new ArrayList<VarOrVal>(); } public void eventName(int eventName) { inctrans.event_name = eventName; } public void addVarArg(int var) { VarOrVal v = new VarOrVal(); v.var = var; incargs.add(v); } public void addValArg(Object val) { VarOrVal v = new VarOrVal(); v.val = val; incargs.add(v); } public void addGuard(Guard g) { assert (inctrans.g == null); inctrans.g = g; } public void addAssignment(Assignment a) { assert (inctrans.a == null); inctrans.a = a; } public void endTransition(int end) { inctrans.end = end; if (incargs.size() > 0) { VarOrVal[] args = new VarOrVal[incargs.size()]; incargs.toArray(args); inctrans.event_args = args; } transitions.add(inctrans); inctrans = null; } public void addQuantification(Quantification q, int var) { Quant quant = new Quant(); quant.universal = (q == FORALL); quant.var = var; quants.add(quant); } public void addQuantification(Quantification q, int var, Guard g) { Quant quant = new Quant(); quant.universal = (q == FORALL); quant.var = var; quant.g = g; quants.add(quant); } public void addFinalStates(int... states) { for (int state : states) { finalstates.add(state); } } /* * Must be called after all transitions that mention these events are * defined */ public void setSkipStates(int... states) { Set<TempEvent> events = getEvents(); for (int state : states) { if (usesGuards(state)) { throw new ShouldNotHappenException( "Cannot currently add skip states where guards are used" + " - you need to do this manually"); } for (TempEvent event : events) { if (!existsTransition(state, event)) { addTransition(state, event, state); } } } } private boolean usesGuards(int state) { for (TempTransition trans : transitions) { if (trans.start == state && trans.g != null) { return true; } } return false; } private void addTransition(int start, TempEvent event, int end) { TempTransition trans = new TempTransition(); trans.start = start; trans.end = end; trans.event_name = event.event_name; trans.event_args = event.event_args; trans.temp_event = event; transitions.add(trans); } private boolean existsTransition(int state, TempEvent event) { for (TempTransition trans : transitions) { if (trans.start == state && trans.temp_event.equals(event)) { return true; } } return false; } private Set<TempEvent> getEvents() { Set<TempEvent> events = new HashSet<TempEvent>(); for (TempTransition trans : transitions) { TempEvent e = new TempEvent(); e.event_name = trans.event_name; e.event_args = trans.event_args; events.add(e); trans.temp_event = e; } return events; } /* * Should only be called after all transitions are created. */ private boolean[] computeStrongStates() { int nstates = countStates(); boolean[] strong = new boolean[nstates + 1]; // state 0 is always strong strong[0] = true; // reach[1][2] is true if state 2 is reachable from state 1 boolean[][] reach = new boolean[nstates + 1][nstates + 1]; Set<TempEvent> events = getEvents(); Set<TempEvent>[] used = new Set[nstates + 1]; for (int i = 1; i < reach.length; i++) { reach[i][i] = true; used[i] = new HashSet<TempEvent>(); } for (TempTransition t : transitions) { reach[t.start][t.end] = true; used[t.start].add(t.temp_event); } for (int i = 1; i < reach.length; i++) { if (used[i].size() != events.size()) { reach[i][0] = true; } } for (int i = 1; i < nstates; i++) { for (int start = 1; start < (nstates + 1); start++) { for (int middle = 1; middle < (nstates + 1); middle++) { // for each entry in reach where start can reach middle if (reach[start][middle]) { // for every state end that middle can reach for (int end = 1; end < (nstates + 1); end++) { if (reach[middle][end]) { // set that start can reach end reach[start][end] = true; } } } } } } if (DEBUG) { System.err.println("reach:"); for (int i = 1; i < reach.length; i++) { System.err.println(i + "\t->\t" + Arrays.toString(reach[i])); } System.err.println(); } for (int i = 1; i <= nstates; i++) { boolean is_strong = true; for (int j = 0; j <= nstates; j++) { if (reach[i][j]) { is_strong &= (finalstates.contains(i) == finalstates .contains(j)); } } strong[i] = is_strong; } if (DEBUG) { System.err.println("\nStrong states: " + Arrays.toString(strong)); } return strong; } }
code/qea/src/creation/QEABuilder.java
package creation; import static structure.impl.other.Quantification.EXISTS; import static structure.impl.other.Quantification.FORALL; import static structure.impl.other.Quantification.NONE; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import monitoring.intf.Monitor; import structure.impl.other.Quantification; import structure.impl.other.Transition; import structure.impl.qeas.QVar01_FVar_Det_QEA; import structure.impl.qeas.QVar01_FVar_NonDet_QEA; import structure.impl.qeas.QVar01_NoFVar_Det_QEA; import structure.impl.qeas.QVar01_NoFVar_NonDet_QEA; import structure.impl.qeas.QVar1_FVar_Det_FixedQVar_QEA; import structure.impl.qeas.QVar1_FVar_NonDet_FixedQVar_QEA; import structure.intf.Assignment; import structure.intf.Guard; import structure.intf.QEA; import exceptions.ShouldNotHappenException; /* * The general idea of this class is to allow us to build a QEA without knowing which * implementation it has. * * Usage: * create a builder * add stuff to it * call make * * This could be used along with a parser to parse some textual representation * of QEA, as we can add different kinds of transitions straightforwardly. However, I'm not sure * how guards and assignments would work in this case. */ public class QEABuilder { private static final boolean DEBUG = true; /* * To create a QEA we need - a set of transitions - a set of final stats - a * quanfication list * * We use internal representations */ private static class VarOrVal { int var = -1000; Object val; } private static class TempTransition { int start, end = -1; int event_name = -1; VarOrVal[] event_args; Guard g; Assignment a; TempEvent temp_event = null; public int[] var_args() { if (event_args == null) { return new int[] {}; } int[] vargs = new int[event_args.length]; for (int i = 0; i < event_args.length; i++) { vargs[i] = event_args[i].var; if (vargs[i] == 0) { throw new RuntimeException( "Do not yet support values in transitions"); } } return vargs; } @Override public String toString() { return start + "-" + event_name + "(" + Arrays.toString(event_args) + ")-" + end; } } private static class TempEvent { int event_name = -1; VarOrVal[] event_args = null; @Override public int hashCode() { return (event_name + Arrays.toString(event_args)).hashCode(); } @Override public boolean equals(Object o) { // if(o==this) return true; if (o instanceof TempEvent) { TempEvent other = (TempEvent) o; if (other.event_name != event_name) { return false; } if (other.event_args == null && event_args == null) { return true; } if (other.event_args == null || event_args == null) { return false; } if (other.event_args.length != event_args.length) { return false; } for (int i = 0; i < event_args.length; i++) { if (other.event_args[i] != event_args[i]) { return false; } } return true; } else { return false; } } @Override public String toString() { return event_name + "(" + Arrays.toString(event_args) + ")"; } } private static class Quant { boolean universal; int var = 1; Guard g; } Set<TempTransition> transitions = new HashSet<TempTransition>(); Set<Integer> finalstates = new HashSet<Integer>(); List<Quant> quants = new ArrayList<Quant>(); /* * It will be good to give the qea a name */ String name; public QEABuilder(String name) { this.name = name; } public QEA make() { String error = wellFormed(); if (error != null) { throw new ShouldNotHappenException(error); } // first get number of states and events int states = countStates(); int events = countEvents(); QEA qea = null; // Propositional first if (quants.size() == 0) { qea = makeProp(states, events); } // Single quantifier next if (quants.size() == 1) { qea = makeSingle(states, events); } if (qea != null) { qea.setName(name); return qea; } throw new ShouldNotHappenException( "I don't know how to make that kind of QEA yet"); } public QEA make(Class<? extends Monitor<?>> monitorClass) { String error = wellFormed(); if (error != null) { throw new ShouldNotHappenException(error); } // first get number of states and events int states = countStates(); int events = countEvents(); // Propositional first if (quants.size() == 0) { return makeProp(states, events); } // Single quantifier next if (quants.size() == 1) { return makeSingle(states, events); } throw new ShouldNotHappenException( "I don't know how to make that kind of QEA yet"); } private QEA makeProp(int states, int events) { boolean[] strongStates = computeStrongStates(); if (noFreeVariables()) { if (isEventDeterministic()) { QVar01_NoFVar_Det_QEA qea = new QVar01_NoFVar_Det_QEA(states, events, 1, NONE); for (TempTransition t : transitions) { qea.addTransition(t.start, t.event_name, t.end); } for (Integer s : finalstates) { qea.setStateAsFinal(s); } for (int i = 0; i < strongStates.length; i++) { if (strongStates[i]) { qea.setStateAsStrong(i); } } return qea; } else { QVar01_NoFVar_NonDet_QEA qea = new QVar01_NoFVar_NonDet_QEA( states, events, 1, NONE); Map<Integer, Set<Integer>>[] actual_trans = new Map[states + 1]; for (TempTransition t : transitions) { Map<Integer, Set<Integer>> this_state = actual_trans[t.start]; if (this_state == null) { actual_trans[t.start] = new HashMap<Integer, Set<Integer>>(); } this_state = actual_trans[t.start]; Set<Integer> nextstates = this_state.get(t.event_name); if (nextstates == null) { nextstates = new HashSet<Integer>(); this_state.put(t.event_name, nextstates); } nextstates.add(t.end); } for (int i = 0; i < actual_trans.length; i++) { if (actual_trans[i] != null) { for (Map.Entry<Integer, Set<Integer>> entry : actual_trans[i] .entrySet()) { int[] nextstates = new int[entry.getValue().size()]; int j = 0; for (Integer s : entry.getValue()) { nextstates[j] = s; j++; } qea.addTransitions(i, (entry.getKey()), nextstates); } } } for (Integer s : finalstates) { qea.setStateAsFinal(s); } for (int i = 0; i < strongStates.length; i++) { if (strongStates[i]) { qea.setStateAsStrong(i); } } return qea; } } else { if (isEventDeterministic()) { int fvars = countFreeVars(); QVar01_FVar_Det_QEA qea = new QVar01_FVar_Det_QEA(states, events, 1, NONE, fvars); for (TempTransition t : transitions) { Transition trans = new Transition(t.var_args(), t.g, t.end); qea.addTransition(t.start, t.event_name, trans); } for (Integer s : finalstates) { qea.setStateAsFinal(s); } for (int i = 0; i < strongStates.length; i++) { if (strongStates[i]) { qea.setStateAsStrong(i); } } return qea; } else { int frees = countFreeVars(); QVar01_FVar_NonDet_QEA qea = new QVar01_FVar_NonDet_QEA(states, events, 1, NONE, frees); Map<Integer, Set<Transition>>[] actual_trans = new Map[states + 1]; for (TempTransition t : transitions) { Map<Integer, Set<Transition>> this_state = actual_trans[t.start]; if (this_state == null) { actual_trans[t.start] = new HashMap<Integer, Set<Transition>>(); } this_state = actual_trans[t.start]; Set<Transition> nextstates = this_state.get(t.event_name); if (nextstates == null) { nextstates = new HashSet<Transition>(); this_state.put(t.event_name, nextstates); } nextstates .add(new Transition(t.var_args(), t.g, t.a, t.end)); } for (int i = 0; i < actual_trans.length; i++) { if (actual_trans[i] != null) { for (Map.Entry<Integer, Set<Transition>> entry : actual_trans[i] .entrySet()) { Transition[] nextstates = new Transition[entry .getValue().size()]; int j = 0; for (Transition s : entry.getValue()) { nextstates[j] = s; j++; } qea.addTransitions(i, (entry.getKey()), nextstates); } } } for (Integer s : finalstates) { qea.setStateAsFinal(s); } for (int i = 0; i < strongStates.length; i++) { if (strongStates[i]) { qea.setStateAsStrong(i); } } return qea; } } } private QEA makeSingle(int states, int events) { boolean[] strongStates = computeStrongStates(); Quantification q; if (quants.get(0).universal) { q = FORALL; } else { q = EXISTS; } if (noFreeVariables()) { if (isEventDeterministic()) { QVar01_NoFVar_Det_QEA qea = new QVar01_NoFVar_Det_QEA(states, events, 1, q); for (TempTransition t : transitions) { qea.addTransition(t.start, t.event_name, t.end); } for (Integer s : finalstates) { qea.setStateAsFinal(s); } for (int i = 0; i < strongStates.length; i++) { if (strongStates[i]) { qea.setStateAsStrong(i); } } return qea; } else { QVar01_NoFVar_NonDet_QEA qea = new QVar01_NoFVar_NonDet_QEA( states, events, 1, q); Map<Integer, Set<Integer>>[] actual_trans = new Map[states + 1]; for (TempTransition t : transitions) { Map<Integer, Set<Integer>> this_state = actual_trans[t.start]; if (this_state == null) { actual_trans[t.start] = new HashMap<Integer, Set<Integer>>(); } this_state = actual_trans[t.start]; Set<Integer> nextstates = this_state.get(t.event_name); if (nextstates == null) { nextstates = new HashSet<Integer>(); this_state.put(t.event_name, nextstates); } nextstates.add(t.end); } for (int i = 0; i < actual_trans.length; i++) { if (actual_trans[i] != null) { for (Map.Entry<Integer, Set<Integer>> entry : actual_trans[i] .entrySet()) { int[] nextstates = new int[entry.getValue().size()]; int j = 0; for (Integer s : entry.getValue()) { nextstates[j] = s; j++; } qea.addTransitions(i, (entry.getKey()), nextstates); } } } for (Integer s : finalstates) { qea.setStateAsFinal(s); } for (int i = 0; i < strongStates.length; i++) { if (strongStates[i]) { qea.setStateAsStrong(i); } } return qea; } } else { int frees = countFreeVars(); if (fixedQVar()) { if (isEventDeterministic()) { QVar1_FVar_Det_FixedQVar_QEA qea = new QVar1_FVar_Det_FixedQVar_QEA( states, events, 1, q, frees); for (TempTransition t : transitions) { Transition trans = new Transition(t.var_args(), t.g, t.a, t.end); qea.addTransition(t.start, t.event_name, trans); } for (Integer s : finalstates) { qea.setStateAsFinal(s); } for (int i = 0; i < strongStates.length; i++) { if (strongStates[i]) { qea.setStateAsStrong(i); } } return qea; } else { QVar1_FVar_NonDet_FixedQVar_QEA qea = new QVar1_FVar_NonDet_FixedQVar_QEA( states, events, 1, q, frees); Map<Integer, Set<Transition>>[] actual_trans = new Map[states + 1]; for (TempTransition t : transitions) { Map<Integer, Set<Transition>> this_state = actual_trans[t.start]; if (this_state == null) { actual_trans[t.start] = new HashMap<Integer, Set<Transition>>(); } this_state = actual_trans[t.start]; Set<Transition> nextstates = this_state .get(t.event_name); if (nextstates == null) { nextstates = new HashSet<Transition>(); this_state.put(t.event_name, nextstates); } nextstates.add(new Transition(t.var_args(), t.g, t.a, t.end)); } for (int i = 0; i < actual_trans.length; i++) { if (actual_trans[i] != null) { for (Map.Entry<Integer, Set<Transition>> entry : actual_trans[i] .entrySet()) { Transition[] nextstates = new Transition[entry .getValue().size()]; int j = 0; for (Transition s : entry.getValue()) { nextstates[j] = s; j++; } qea.addTransitions(i, (entry.getKey()), nextstates); } } } for (Integer s : finalstates) { qea.setStateAsFinal(s); } for (int i = 0; i < strongStates.length; i++) { if (strongStates[i]) { qea.setStateAsStrong(i); } } return qea; } } else { if (isEventDeterministic()) { QVar01_FVar_Det_QEA qea = new QVar01_FVar_Det_QEA(states, events, 1, q, frees); for (TempTransition t : transitions) { Transition trans = new Transition(t.var_args(), t.g, t.a, t.end); trans.setAssignment(t.a); trans.setGuard(t.g); qea.addTransition(t.start, t.event_name, trans); } for (Integer s : finalstates) { qea.setStateAsFinal(s); } for (int i = 0; i < strongStates.length; i++) { if (strongStates[i]) { qea.setStateAsStrong(i); } } return qea; } else { QVar01_FVar_NonDet_QEA qea = new QVar01_FVar_NonDet_QEA( states, events, 1, q, frees); Map<Integer, Set<Transition>>[] actual_trans = new Map[states + 1]; for (TempTransition t : transitions) { Map<Integer, Set<Transition>> this_state = actual_trans[t.start]; if (this_state == null) { actual_trans[t.start] = new HashMap<Integer, Set<Transition>>(); } this_state = actual_trans[t.start]; Set<Transition> nextstates = this_state .get(t.event_name); if (nextstates == null) { nextstates = new HashSet<Transition>(); this_state.put(t.event_name, nextstates); } nextstates.add(new Transition(t.var_args(), t.g, t.a, t.end)); } for (int i = 0; i < actual_trans.length; i++) { if (actual_trans[i] != null) { for (Map.Entry<Integer, Set<Transition>> entry : actual_trans[i] .entrySet()) { Transition[] nextstates = new Transition[entry .getValue().size()]; int j = 0; for (Transition s : entry.getValue()) { nextstates[j] = s; j++; } qea.addTransitions(i, (entry.getKey()), nextstates); } } } for (Integer s : finalstates) { qea.setStateAsFinal(s); } for (int i = 0; i < strongStates.length; i++) { if (strongStates[i]) { qea.setStateAsStrong(i); } } return qea; } } } } private int countStates() { int max = 0; for (TempTransition t : transitions) { if (t.start > max) { max = t.start; } if (t.end > max) { max = t.end; } } return max; } private int countEvents() { int max = 0; for (TempTransition t : transitions) { if (t.event_name > max) { max = t.event_name; } } return max; } private int countFreeVars() { Set<Integer> qvars = new HashSet<Integer>(); int max = 0; for (Quant q : quants) { qvars.add(q.var); } // Set<Integer> fvars = new HashSet<Integer>(); for (TempTransition t : transitions) { if (t.event_args != null) { for (VarOrVal event_arg : t.event_args) { int var = event_arg.var; if (var != 0 && !qvars.contains(var)) { // fvars.add(var); if (var > max) { max = var; } } } } } return max; } /* * Check that all transitions have a start, end and event name And that all * quantifications have a var */ private String wellFormed() { int[] num_args = new int[1 + countEvents()]; for (int i = 0; i < num_args.length; i++) { num_args[i] = -1; } for (TempTransition trans : transitions) { if (trans.start < 1) { return "All states should be >0"; } if (trans.end < 1) { return "All states should be >0"; } if (trans.event_name < 1) { return "All event names should be >0"; } if (trans.event_args != null) { if (num_args[trans.event_name] == -1) { num_args[trans.event_name] = trans.event_args.length; } else if (num_args[trans.event_name] != trans.event_args.length) { return "All events with the same name should have the same number of parameters"; } for (VarOrVal event_arg : trans.event_args) { if (event_arg == null || (event_arg.val == null && event_arg.var == -1000)) { return "The paramters were not correctly defined in a transition"; } } } } int qstep = -1; for (Quant q : quants) { if (q.var != qstep) { return "Quantified variables should named -1,-2,..."; } qstep--; } return null; } /* * Get the quantified variables Check that all transitions that have * arguments either use a value or a quantified variable */ private boolean noFreeVariables() { Set<Integer> qvars = new HashSet<Integer>(); for (Quant q : quants) { qvars.add(q.var); } for (TempTransition t : transitions) { if (t.event_args != null) { for (int i = 0; i < t.event_args.length; i++) { if (t.event_args[i].val == null && !(qvars.contains(t.event_args[i].var))) { return false; } } } } return true; } /* * Check that for each state and event name there is a single transition */ private boolean isEventDeterministic() { Map<Integer, Set<Integer>> start_trans = new HashMap<Integer, Set<Integer>>(); for (TempTransition t : transitions) { Set<Integer> states = start_trans.get(t.start); if (states == null) { states = new HashSet<Integer>(); start_trans.put(t.start, states); } if (!states.add(t.event_name)) { return false; } } return true; } /** * Checks if the QEA of this builder meets the conditions for the FixedQVar * optimisation. This is: * <ul> * <li>There is a single quantified variable * <li>All the events contain the quantified variable as the first parameter * <li>There are no events without parameters * </ul> * * @return <code>true</code> if the QEA of this builder meets the conditions * for the FixedQVar optimisation; <code>false</code> otherwise */ private boolean fixedQVar() { // Check there is a single quantified variable if (quants.size() != 1) { return false; } int qVar = quants.get(0).var; // Iterate over all the transitions for (TempTransition t : transitions) { // Check it's not an event without parameters if (t.event_args == null || t.event_args.length == 0) { return false; } // Check the quantified variable is in the first position if (t.event_args[0].var != qVar) { return false; } // Check starting from the 2nd position there are only free vars for (int i = 1; i < t.event_args.length; i++) { if (t.event_args[i].var == qVar) { return false; } } } return true; } /* * CREATING QEA */ // add a propositional transition public void addTransition(int start, int propname, int end) { TempTransition trans = new TempTransition(); trans.start = start; trans.end = end; trans.event_name = propname; transitions.add(trans); } // add a variable only transition public void addTransition(int start, int propname, int[] vargs, int end) { TempTransition trans = new TempTransition(); trans.start = start; trans.end = end; trans.event_name = propname; VarOrVal[] args = new VarOrVal[vargs.length]; for (int i = 0; i < vargs.length; i++) { args[i] = new VarOrVal(); args[i].var = vargs[i]; } trans.event_args = args; transitions.add(trans); } // incremental transition adding TempTransition inctrans = null; List<VarOrVal> incargs = null; public void startTransition(int start) { inctrans = new TempTransition(); inctrans.start = start; incargs = new ArrayList<VarOrVal>(); } public void eventName(int eventName) { inctrans.event_name = eventName; } public void addVarArg(int var) { VarOrVal v = new VarOrVal(); v.var = var; incargs.add(v); } public void addValArg(Object val) { VarOrVal v = new VarOrVal(); v.val = val; incargs.add(v); } public void addGuard(Guard g) { assert (inctrans.g == null); inctrans.g = g; } public void addAssignment(Assignment a) { assert (inctrans.a == null); inctrans.a = a; } public void endTransition(int end) { inctrans.end = end; if (incargs.size() > 0) { VarOrVal[] args = new VarOrVal[incargs.size()]; incargs.toArray(args); inctrans.event_args = args; } transitions.add(inctrans); inctrans = null; } public void addQuantification(Quantification q, int var) { Quant quant = new Quant(); quant.universal = (q == FORALL); quant.var = var; quants.add(quant); } public void addQuantification(Quantification q, int var, Guard g) { Quant quant = new Quant(); quant.universal = (q == FORALL); quant.var = var; quant.g = g; quants.add(quant); } public void addFinalStates(int... states) { for (int state : states) { finalstates.add(state); } } /* * Must be called after all transitions that mention these events are * defined */ public void setSkipStates(int... states) { Set<TempEvent> events = getEvents(); for (int state : states) { if (usesGuards(state)) { throw new ShouldNotHappenException( "Cannot currently add skip states where guards are used" + " - you need to do this manually"); } for (TempEvent event : events) { if (!existsTransition(state, event)) { addTransition(state, event, state); } } } } private boolean usesGuards(int state) { for (TempTransition trans : transitions) { if (trans.start == state && trans.g != null) { return true; } } return false; } private void addTransition(int start, TempEvent event, int end) { TempTransition trans = new TempTransition(); trans.start = start; trans.end = end; trans.event_name = event.event_name; trans.event_args = event.event_args; trans.temp_event = event; transitions.add(trans); } private boolean existsTransition(int state, TempEvent event) { for (TempTransition trans : transitions) { if (trans.start == state && trans.temp_event.equals(event)) { return true; } } return false; } private Set<TempEvent> getEvents() { Set<TempEvent> events = new HashSet<TempEvent>(); for (TempTransition trans : transitions) { TempEvent e = new TempEvent(); e.event_name = trans.event_name; e.event_args = trans.event_args; events.add(e); trans.temp_event = e; } return events; } /* * Should only be called after all transitions are created. */ private boolean[] computeStrongStates() { int nstates = countStates(); boolean[] strong = new boolean[nstates + 1]; // state 0 is always strong strong[0] = true; // reach[1][2] is true if state 2 is reachable from state 1 boolean[][] reach = new boolean[nstates + 1][nstates + 1]; Set<TempEvent> events = getEvents(); Set<TempEvent>[] used = new Set[nstates + 1]; for (int i = 1; i < reach.length; i++) { reach[i][i] = true; used[i] = new HashSet<TempEvent>(); } for (TempTransition t : transitions) { reach[t.start][t.end] = true; used[t.start].add(t.temp_event); } for (int i = 1; i < reach.length; i++) { if (used[i].size() != events.size()) { reach[i][0] = true; } } for (int i = 1; i < nstates; i++) { for (int start = 1; start < (nstates + 1); start++) { for (int middle = 1; middle < (nstates + 1); middle++) { // for each entry in reach where start can reach middle if (reach[start][middle]) { // for every state end that middle can reach for (int end = 1; end < (nstates + 1); end++) { if (reach[middle][end]) { // set that start can reach end reach[start][end] = true; } } } } } } if (DEBUG) { System.err.println("reach:"); for (int i = 1; i < reach.length; i++) { System.err.println(i + "\t->\t" + Arrays.toString(reach[i])); } System.err.println(); } for (int i = 1; i <= nstates; i++) { boolean is_strong = true; for (int j = 0; j <= nstates; j++) { if (reach[i][j]) { is_strong &= (finalstates.contains(i) == finalstates .contains(j)); } } strong[i] = is_strong; } if (DEBUG) { System.err.println("\nStrong states: " + Arrays.toString(strong)); } return strong; } }
*Comment added
code/qea/src/creation/QEABuilder.java
*Comment added
<ide><path>ode/qea/src/creation/QEABuilder.java <ide> return max; <ide> } <ide> <add> // TODO Free variables in guards/assignments not present in transitions are <add> // not being considered <ide> private int countFreeVars() { <ide> Set<Integer> qvars = new HashSet<Integer>(); <ide> int max = 0;
Java
apache-2.0
a648205bff464f9f59c0af726d20e9c81401c494
0
tateshitah/jspwiki,tateshitah/jspwiki,tateshitah/jspwiki,tateshitah/jspwiki
/* * (C) Janne Jalkanen 2005 * */ package com.ecyrd.jspwiki.dav.items; import java.io.InputStream; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import org.apache.commons.lang.time.DateFormatUtils; import org.jdom.Element; import org.jdom.Namespace; import com.ecyrd.jspwiki.dav.DavPath; import com.ecyrd.jspwiki.dav.DavProvider; /** * @author jalkanen * * @since */ public class DirectoryItem extends DavItem { public DirectoryItem( DavProvider provider, DavPath path ) { super( provider, path ); } public String getContentType() { return "text/plain; charset=UTF-8"; } public long getLength() { return -1; } public Collection getPropertySet() { ArrayList ts = new ArrayList(); Namespace davns = Namespace.getNamespace( "DAV:" ); ts.add( new Element("resourcetype",davns).addContent(new Element("collection",davns)) ); Element txt = new Element("displayname",davns); txt.setText( m_path.getName() ); ts.add( txt ); ts.add( new Element("getcontentlength",davns).setText("0") ); ts.add( new Element("getlastmodified", davns).setText(DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.format(new Date()))); return ts; } public String getHref() { return m_provider.getURL( m_path ); } public void addDavItem( DavItem di ) { m_items.add( di ); } public void addDavItems( Collection c ) { m_items.addAll( c ); } /* (non-Javadoc) * @see com.ecyrd.jspwiki.dav.items.DavItem#getInputStream() */ public InputStream getInputStream() { // TODO Auto-generated method stub return null; } }
src/com/ecyrd/jspwiki/dav/items/DirectoryItem.java
/* * (C) Janne Jalkanen 2005 * */ package com.ecyrd.jspwiki.dav.items; import java.io.InputStream; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import org.apache.commons.lang.time.DateFormatUtils; import org.jdom.Element; import org.jdom.Namespace; import com.ecyrd.jspwiki.dav.DavPath; import com.ecyrd.jspwiki.dav.DavProvider; /** * @author jalkanen * * @since */ public class DirectoryItem extends DavItem { public DirectoryItem( DavProvider provider, DavPath path ) { super( provider, path ); } public String getContentType() { return "text/plain; charset=UTF-8"; } public long getLength() { return -1; } public Collection getPropertySet() { ArrayList ts = new ArrayList(); Namespace davns = Namespace.getNamespace( "DAV:" ); ts.add( new Element("resourcetype",davns).addContent(new Element("collection",davns)) ); Element txt = new Element("displayname",davns); txt.setText( m_path.getName() ); ts.add( txt ); ts.add( new Element("getcontentlength",davns).setText("0") ); ts.add( new Element("getlastmodified", davns).setText(DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.format(new Date()))); return ts; } public String getHref() { String davurl = m_path.getName(); //FIXME: Fixed, should determine from elsewhere if( !davurl.endsWith("/") ) davurl+="/"; return m_provider.getURL( davurl ); } public void addDavItem( DavItem di ) { m_items.add( di ); } public void addDavItems( Collection c ) { m_items.addAll( c ); } /* (non-Javadoc) * @see com.ecyrd.jspwiki.dav.items.DavItem#getInputStream() */ public InputStream getInputStream() { // TODO Auto-generated method stub return null; } }
Added two-layer pages. git-svn-id: 6c0206e3b9edd104850923da33ebd73b435d374d@624350 13f79535-47bb-0310-9956-ffa450edef68
src/com/ecyrd/jspwiki/dav/items/DirectoryItem.java
Added two-layer pages.
<ide><path>rc/com/ecyrd/jspwiki/dav/items/DirectoryItem.java <ide> <ide> public String getHref() <ide> { <del> String davurl = m_path.getName(); //FIXME: Fixed, should determine from elsewhere <del> <del> if( !davurl.endsWith("/") ) davurl+="/"; <del> <del> return m_provider.getURL( davurl ); <add> return m_provider.getURL( m_path ); <ide> } <ide> <ide> public void addDavItem( DavItem di )
Java
mit
209116ec5c36c5eea1d0485f70922ce649b87948
0
solinor/paymenthighway-java-lib
package io.paymenthighway.model.response; import com.fasterxml.jackson.annotation.JsonProperty; public class MobilePayStatusResponse extends Response { @JsonProperty("status") private String status; @JsonProperty("transaction_id") private String transactionId; @JsonProperty("valid_until") private String validUntil; public String getStatus() { return status; } public String getTransactionId() { return transactionId; } public String getValidUntil() { return validUntil; } }
src/main/java/io/paymenthighway/model/response/MobilePayStatusResponse.java
package io.paymenthighway.model.response; import com.fasterxml.jackson.annotation.JsonProperty; public class MobilePayStatusResponse extends Response { @JsonProperty("status") private String status; @JsonProperty("transaction-id") private String transactionId; @JsonProperty("valid-until") private String validUntil; public String getStatus() { return status; } public String getTransactionId() { return transactionId; } public String getValidUntil() { return validUntil; } }
Use snake_case for json keys.
src/main/java/io/paymenthighway/model/response/MobilePayStatusResponse.java
Use snake_case for json keys.
<ide><path>rc/main/java/io/paymenthighway/model/response/MobilePayStatusResponse.java <ide> <ide> public class MobilePayStatusResponse extends Response { <ide> @JsonProperty("status") private String status; <del> @JsonProperty("transaction-id") private String transactionId; <del> @JsonProperty("valid-until") private String validUntil; <add> @JsonProperty("transaction_id") private String transactionId; <add> @JsonProperty("valid_until") private String validUntil; <ide> <ide> public String getStatus() { <ide> return status;
Java
apache-2.0
0ec66973f88dc76081ee02bcf79f4a7e2dc02cc4
0
hbs/oss,hbs/oss,hbs/oss
/* * Copyright 2012-2013 Mathias Herberts * * 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.geoxp.oss; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.math.BigInteger; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketAddress; import java.security.InvalidKeyException; import java.security.Key; import java.security.KeyFactory; import java.security.KeyPair; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.SecureRandom; import java.security.Security; import java.security.Signature; import java.security.SignatureException; import java.security.interfaces.DSAPrivateKey; import java.security.interfaces.DSAPublicKey; import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; import java.security.spec.DSAPublicKeySpec; import java.security.spec.InvalidKeySpecException; import java.security.spec.KeySpec; import java.security.spec.RSAPublicKeySpec; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.List; import org.bouncycastle.bcpg.ArmoredOutputStream; import org.bouncycastle.crypto.AsymmetricBlockCipher; import org.bouncycastle.crypto.InvalidCipherTextException; import org.bouncycastle.crypto.encodings.PKCS1Encoding; import org.bouncycastle.crypto.engines.AESWrapEngine; import org.bouncycastle.crypto.engines.RSABlindedEngine; import org.bouncycastle.crypto.paddings.PKCS7Padding; import org.bouncycastle.crypto.params.KeyParameter; import org.bouncycastle.crypto.params.RSAKeyParameters; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.openpgp.PGPCompressedDataGenerator; import org.bouncycastle.openpgp.PGPEncryptedDataGenerator; import org.bouncycastle.openpgp.PGPException; import org.bouncycastle.openpgp.PGPKeyRing; import org.bouncycastle.openpgp.PGPLiteralData; import org.bouncycastle.openpgp.PGPLiteralDataGenerator; import org.bouncycastle.openpgp.PGPObjectFactory; import org.bouncycastle.openpgp.PGPPublicKey; import org.bouncycastle.openpgp.PGPUtil; import org.bouncycastle.openpgp.operator.bc.BcPGPDataEncryptorBuilder; import org.bouncycastle.openpgp.operator.bc.BcPublicKeyKeyEncryptionMethodGenerator; import org.bouncycastle.util.encoders.Hex; import com.etsy.net.JUDS; import com.etsy.net.UnixDomainSocketClient; /** * Helper class containing various methods used to * ease up cryptographic operations */ public class CryptoHelper { /** * Default algorithm to use when generating signatures */ public static final String DEFAULT_SIGNATURE_ALGORITHM = "SHA256WithRSA"; private static final String SSH_DSS_PREFIX = "ssh-dss"; private static final String SSH_RSA_PREFIX = "ssh-rsa"; /** * SecureRandom used by the class */ private static SecureRandom sr = null; static { // // Add BouncyCastleProvider // Security.addProvider(new BouncyCastleProvider()); // // Create PRNG, will be null if provider/algorithm not found // try { sr = SecureRandom.getInstance("SHA1PRNG","SUN"); } catch (NoSuchProviderException nspe) { } catch (NoSuchAlgorithmException nsae) { } if (null == sr) { sr = new SecureRandom(); } } public static SecureRandom getSecureRandom() { return CryptoHelper.sr; } /** * Pad data using PKCS7. * * @param alignment Alignement on which to pad, e.g. 8 * @param data Data to pad * @return The padded data */ public static byte[] padPKCS7(int alignment, byte[] data, int offset, int len) { // // Allocate the target byte array. Its size is a multiple of 'alignment'. // If data to pad is a multiple of 'alignment', the target array will be // 'alignment' bytes longer than the data to pad. // byte[] target = new byte[len + (alignment - len % alignment)]; // // Copy the data to pad into the target array // System.arraycopy (data, offset, target, 0, len); // // Add padding bytes // PKCS7Padding padding = new PKCS7Padding(); padding.addPadding(target, len); return target; } public static byte[] padPKCS7(int alignment, byte[] data) { return padPKCS7(alignment, data, 0, data.length); } /** * Remove PKCS7 padding from padded data * @param padded The padded data to 'unpad' * @return The original unpadded data * @throws InvalidCipherTextException if data is not correctly padded */ public static byte[] unpadPKCS7(byte[] padded) throws InvalidCipherTextException { PKCS7Padding padding = new PKCS7Padding(); // // Determine length of padding // int pad = padding.padCount(padded); // // Allocate array for unpadded data // byte[] unpadded = new byte[padded.length - pad]; // // Copy data without the padding // System.arraycopy(padded, 0, unpadded, 0, padded.length - pad); return unpadded; } /** * Protect some data using AES Key Wrapping * * @param key AES wrapping key * @param data Data to wrap * @param offset Where does the data start in 'data' * @param len How long is the data * @param nonce Should a random prefix be added to the data prior to wrapping * @return The wrapped data */ public static byte[] wrapAES(byte[] key, byte[] data, int offset, int len, boolean nonce) { // // Initialize AES Wrap Engine for wrapping // AESWrapEngine aes = new AESWrapEngine(); KeyParameter keyparam = new KeyParameter(key); aes.init(true, keyparam); if (nonce) { byte[] nonced = new byte[len + OSS.NONCE_BYTES]; byte[] noncebytes = new byte[OSS.NONCE_BYTES]; getSecureRandom().nextBytes(noncebytes); System.arraycopy(noncebytes, 0, nonced, 0, OSS.NONCE_BYTES); System.arraycopy(data, offset, nonced, OSS.NONCE_BYTES, len); data = nonced; offset = 0; len = data.length; } // // Pad the data on an 8 bytes boundary // byte[] padded = padPKCS7(8, data, offset, len); // // Wrap data and return it // return aes.wrap(padded, 0, padded.length); } public static byte[] wrapAES(byte[] key, byte[] data) { return wrapAES(key, data, 0, data.length, false); } public static byte[] wrapBlob(byte[] key, byte[] blob) { return wrapAES(key, blob, 0, blob.length, true); } /** * Unwrap data protected by AES Key Wrapping * * @param key Key used to wrap the data * @param data Wrapped data * @return The unwrapped data or null if an error occurred */ public static byte[] unwrapAES(byte[] key, byte[] data, boolean hasnonce) { // // Initialize the AES Wrap Engine for unwrapping // AESWrapEngine aes = new AESWrapEngine(); KeyParameter keyparam = new KeyParameter(key); aes.init(false, keyparam); // // Unwrap then unpad data // try { byte[] unpadded = unpadPKCS7(aes.unwrap(data, 0, data.length)); // // Remove nonce if data has one // if (hasnonce) { return Arrays.copyOfRange(unpadded, OSS.NONCE_BYTES, unpadded.length); } else { return unpadded; } } catch (InvalidCipherTextException icte) { return null; } } public static byte[] unwrapAES(byte[] key, byte[] data) { return unwrapAES(key, data, false); } public static byte[] unwrapBlob(byte[] key, byte[] blob) { return unwrapAES(key, blob, true); } /** * Encrypt data using RSA. * CAUTION: this can take a while on large data * * @param key RSA key to use for encryption * @param data Cleartext data * @return The ciphertext data or null if an error occured */ public static byte[] encryptRSA(Key key, byte[] data) { // // Get an RSA Cipher instance // //Cipher rsa = null; try { /* The following commented code can be used the BouncyCastle * JCE provider signature is intact, which is not the * case when BC has been repackaged using jarjar rsa = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC"); rsa.init (Cipher.ENCRYPT_MODE, key, CryptoHelper.sr); return rsa.doFinal(data); */ AsymmetricBlockCipher c = new PKCS1Encoding(new RSABlindedEngine()); if (key instanceof RSAPublicKey) { c.init(true, new RSAKeyParameters(true, ((RSAPublicKey) key).getModulus(), ((RSAPublicKey) key).getPublicExponent())); } else if (key instanceof RSAPrivateKey) { c.init(true, new RSAKeyParameters(true, ((RSAPrivateKey) key).getModulus(), ((RSAPrivateKey) key).getPrivateExponent())); } else { return null; } int insize = c.getInputBlockSize(); int offset = 0; ByteArrayOutputStream baos = new ByteArrayOutputStream(); while(offset < data.length) { int len = Math.min(insize, data.length - offset); baos.write(c.processBlock(data, offset, len)); offset += len; } return baos.toByteArray(); /* } catch (NoSuchProviderException nspe) { return null; } catch (NoSuchPaddingException nspe) { return null; } catch (NoSuchAlgorithmException nsae) { return null; } catch (InvalidKeyException ike) { return null; } catch (BadPaddingException bpe) { return null; } catch (IllegalBlockSizeException ibse) { return null; } */ } catch (InvalidCipherTextException icte) { return null; } catch (IOException ioe) { return null; } } /** * Decrypt data previously encrypted with RSA * @param key RSA key to use for decryption * @param data Ciphertext data * @return The cleartext data or null if an error occurred */ public static byte[] decryptRSA(Key key, byte[] data) { // // Get an RSA Cipher instance // //Cipher rsa = null; try { /* The following commented code can be used the BouncyCastle * JCE provider signature is intact, which is not the * case when BC has been repackaged using jarjar rsa = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC"); rsa.init (Cipher.DECRYPT_MODE, key, CryptoHelper.sr); return rsa.doFinal(data); */ AsymmetricBlockCipher c = new PKCS1Encoding(new RSABlindedEngine()); if (key instanceof RSAPublicKey) { c.init(false, new RSAKeyParameters(true, ((RSAPublicKey) key).getModulus(), ((RSAPublicKey) key).getPublicExponent())); } else if (key instanceof RSAPrivateKey) { c.init(false, new RSAKeyParameters(true, ((RSAPrivateKey) key).getModulus(), ((RSAPrivateKey) key).getPrivateExponent())); } else { return null; } int insize = c.getInputBlockSize(); int offset = 0; ByteArrayOutputStream baos = new ByteArrayOutputStream(); while(offset < data.length) { int len = Math.min(insize, data.length - offset); baos.write(c.processBlock(data, offset, len)); offset += len; } return baos.toByteArray(); /* } catch (NoSuchProviderException nspe) { return null; } catch (NoSuchPaddingException nspe) { return null; } catch (NoSuchAlgorithmException nsae) { return null; } catch (InvalidKeyException ike) { return null; } catch (BadPaddingException bpe) { return null; } catch (IllegalBlockSizeException ibse) { return null; } */ } catch (InvalidCipherTextException icte) { return null; } catch (IOException ioe) { return null; } } /** * Sign data using the given algorithm * * @param algorithm Name of algorithm to use for signing * @param key Private key to use for signing (must be compatible with chosen algorithm) * @param data Data to sign * @return The signature of data or null if an error occurred */ public static byte[] sign(String algorithm, PrivateKey key, byte[] data) { try { Signature signature = Signature.getInstance(algorithm, "BC"); signature.initSign(key, CryptoHelper.sr); signature.update(data); return signature.sign(); } catch (SignatureException se) { return null; } catch (InvalidKeyException ike) { return null; } catch (NoSuchAlgorithmException nsae) { return null; } catch (NoSuchProviderException nspe) { return null; } } /** * Verify a signature * * @param algorithm Algorithm used to generate the signature * @param key Public key to use for verifying the signature * @param data Data whose signature must be verified * @param sig The signature to verify * @return true or false depending on successful verification */ public static boolean verify(String algorithm, PublicKey key, byte[] data, byte[] sig) { try { Signature signature = Signature.getInstance(algorithm, "BC"); signature.initVerify(key); signature.update(data); return signature.verify(sig); } catch (SignatureException se) { return false; } catch (InvalidKeyException ike) { return false; } catch (NoSuchAlgorithmException nsae) { return false; } catch (NoSuchProviderException nspe) { return false; } } /** * Convert an SSH Key Blob to a Public Key * * @param blob SSH Key Blob * @return The extracted public key or null if an error occurred */ public static PublicKey sshKeyBlobToPublicKey(byte[] blob) { // // RFC 4253 describes keys as either // // ssh-dss p q g y // ssh-rsa e n // // // Extract SSH key type // byte[] keyType = decodeNetworkString(blob,0); int offset = 4 + keyType.length; String keyTypeStr = new String(keyType); try { if (SSH_DSS_PREFIX.equals(keyTypeStr)) { // // Extract DSA key parameters p q g and y // byte[] p = decodeNetworkString(blob, offset); offset += 4; offset += p.length; byte[] q = decodeNetworkString(blob, offset); offset += 4; offset += q.length; byte[] g = decodeNetworkString(blob, offset); offset += 4; offset += g.length; byte[] y = decodeNetworkString(blob, offset); offset += 4; offset += y.length; KeySpec key = new DSAPublicKeySpec(new BigInteger(y), new BigInteger(p), new BigInteger(q), new BigInteger(g)); return KeyFactory.getInstance("DSA").generatePublic(key); } else if (SSH_RSA_PREFIX.equals(keyTypeStr)) { // // Extract RSA key parameters e and n // byte[] e = decodeNetworkString(blob, offset); offset += 4; offset += e.length; byte[] n = decodeNetworkString(blob, offset); offset += 4; offset += n.length; KeySpec key = new RSAPublicKeySpec(new BigInteger(n), new BigInteger(e)); return KeyFactory.getInstance("RSA").generatePublic(key); } else { return null; } } catch (NoSuchAlgorithmException nsae) { nsae.printStackTrace(); return null; } catch (InvalidKeySpecException ikse) { ikse.printStackTrace(); return null; } } /** * Compute the MD5 fingerprint of an SSH key blob * * @param blob Public Key Blob to compute the fingerprint on * @return The computed signature or null if an error occurred */ public static byte[] sshKeyBlobFingerprint(byte[] blob) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(blob); return md5.digest(); } catch (NoSuchAlgorithmException nsae) { return null; } } /** * Encode a key pair as an SSH Key Blob * * @param kp Public/private key pair to encode * @return The encoded public key or null if provided key is not RSA or DSA */ public static byte[] sshKeyBlobFromKeyPair(KeyPair kp) { if (kp.getPrivate() instanceof RSAPrivateKey) { // // Extract key parameters // BigInteger n = ((RSAPublicKey) kp.getPublic()).getModulus(); BigInteger e = ((RSAPublicKey) kp.getPublic()).getPublicExponent(); BigInteger d = ((RSAPrivateKey) kp.getPrivate()).getPrivateExponent(); // Not available and not used by ssh-agent anyway ... BigInteger iqmp = BigInteger.ZERO; BigInteger p = BigInteger.ZERO; BigInteger q = BigInteger.ZERO; byte[] tns = null; try { tns = encodeNetworkString(SSH_RSA_PREFIX.getBytes("UTF-8")); } catch (UnsupportedEncodingException uee) {} byte[] nns = encodeNetworkString(n.toByteArray()); byte[] ens = encodeNetworkString(e.toByteArray()); byte[] dns = encodeNetworkString(d.toByteArray()); byte[] iqmpns = encodeNetworkString(iqmp.toByteArray()); byte[] pns = encodeNetworkString(p.toByteArray()); byte[] qns = encodeNetworkString(q.toByteArray()); // // Allocate array for blob // byte[] blob = new byte[tns.length + nns.length + ens.length + dns.length + iqmpns.length + pns.length + qns.length]; // // Copy network strings to blob // System.arraycopy(tns, 0, blob, 0, tns.length); System.arraycopy(nns, 0, blob, tns.length, nns.length); System.arraycopy(ens, 0, blob, tns.length + nns.length, ens.length); System.arraycopy(dns, 0, blob, tns.length + nns.length + ens.length, dns.length); System.arraycopy(iqmpns, 0, blob, tns.length + nns.length + ens.length + dns.length, iqmpns.length); System.arraycopy(pns, 0, blob, tns.length + nns.length + ens.length + dns.length + iqmpns.length, pns.length); System.arraycopy(qns, 0, blob, tns.length + nns.length + ens.length + dns.length + iqmpns.length + pns.length, qns.length); return blob; } else if (kp.getPrivate() instanceof DSAPrivateKey) { // // Extract key parameters // BigInteger p = ((DSAPublicKey) kp.getPublic()).getParams().getP(); BigInteger q = ((DSAPublicKey) kp.getPublic()).getParams().getQ(); BigInteger g = ((DSAPublicKey) kp.getPublic()).getParams().getG(); BigInteger y = ((DSAPublicKey) kp.getPublic()).getY(); BigInteger x = ((DSAPrivateKey) kp.getPrivate()).getX(); // // Encode parameters as network strings // byte[] tns = null; try { tns = encodeNetworkString(SSH_DSS_PREFIX.getBytes("UTF-8")); } catch (UnsupportedEncodingException uee) {} byte[] pns = encodeNetworkString(p.toByteArray()); byte[] qns = encodeNetworkString(q.toByteArray()); byte[] gns = encodeNetworkString(g.toByteArray()); byte[] yns = encodeNetworkString(y.toByteArray()); byte[] xns = encodeNetworkString(x.toByteArray()); // // Allocate array for blob // byte[] blob = new byte[tns.length + pns.length + qns.length + gns.length + yns.length + xns.length]; // // Copy network strings to blob // System.arraycopy(tns, 0, blob, 0, tns.length); System.arraycopy(pns, 0, blob, tns.length, pns.length); System.arraycopy(qns, 0, blob, tns.length + pns.length, qns.length); System.arraycopy(gns, 0, blob, tns.length + pns.length + qns.length, gns.length); System.arraycopy(yns, 0, blob, tns.length + pns.length + qns.length + gns.length, yns.length); System.arraycopy(xns, 0, blob, tns.length + pns.length + qns.length + gns.length + yns.length, xns.length); return blob; } else { return null; } } /** * Encode a public key as an SSH Key Blob * * @param key Public key to encode * @return The encoded public key or null if provided key is not RSA or DSA */ public static byte[] sshKeyBlobFromPublicKey(PublicKey key) { if (key instanceof RSAPublicKey) { // // Extract public exponent and modulus // BigInteger e = ((RSAPublicKey) key).getPublicExponent(); BigInteger n = ((RSAPublicKey) key).getModulus(); // // Encode parameters as Network Strings // byte[] tns = null; try { tns = encodeNetworkString(SSH_RSA_PREFIX.getBytes("UTF-8")); } catch (UnsupportedEncodingException uee) {} byte[] ens = encodeNetworkString(e.toByteArray()); byte[] nns = encodeNetworkString(n.toByteArray()); // // Allocate array for blob // byte[] blob = new byte[tns.length + nns.length + ens.length]; // // Copy network strings to blob // System.arraycopy(tns, 0, blob, 0, tns.length); System.arraycopy(ens, 0, blob, tns.length, ens.length); System.arraycopy(nns, 0, blob, tns.length + ens.length, nns.length); return blob; } else if (key instanceof DSAPublicKey) { // // Extract key parameters // BigInteger p = ((DSAPublicKey) key).getParams().getP(); BigInteger q = ((DSAPublicKey) key).getParams().getQ(); BigInteger g = ((DSAPublicKey) key).getParams().getG(); BigInteger y = ((DSAPublicKey) key).getY(); // // Encode parameters as network strings // byte[] tns = null; try { tns = encodeNetworkString(SSH_DSS_PREFIX.getBytes("UTF-8")); } catch (UnsupportedEncodingException uee) {} byte[] pns = encodeNetworkString(p.toByteArray()); byte[] qns = encodeNetworkString(q.toByteArray()); byte[] gns = encodeNetworkString(g.toByteArray()); byte[] yns = encodeNetworkString(y.toByteArray()); // // Allocate array for blob // byte[] blob = new byte[tns.length + pns.length + qns.length + gns.length + yns.length]; // // Copy network strings to blob // System.arraycopy(tns, 0, blob, 0, tns.length); System.arraycopy(pns, 0, blob, tns.length, pns.length); System.arraycopy(qns, 0, blob, tns.length + pns.length, qns.length); System.arraycopy(gns, 0, blob, tns.length + pns.length + qns.length, gns.length); System.arraycopy(yns, 0, blob, tns.length + pns.length + qns.length + gns.length, yns.length); return blob; } else { return null; } } /** * Generate an SSH signature blob * * @param data Data to sign * @param key Private key to use for signing * @return The generated signature blob or null if the provided key is not supported */ public static byte[] sshSignatureBlobSign(byte[] data, PrivateKey key) { try { if (key instanceof RSAPrivateKey) { // // Create Signature object // Signature signature = java.security.Signature.getInstance("SHA1withRSA"); signature.initSign(key); signature.update(data); byte[] sig = signature.sign(); // // Build the SSH sigBlob // byte[] tns = null; try { encodeNetworkString(SSH_RSA_PREFIX.getBytes("UTF-8")); } catch (UnsupportedEncodingException uee) {} byte[] sns = encodeNetworkString(sig); byte[] blob = new byte[tns.length + sns.length]; System.arraycopy(tns, 0, blob, 0, tns.length); System.arraycopy(sns, 0, blob, tns.length, sns.length); return blob; } else if (key instanceof DSAPrivateKey) { // // Create Signature object // Signature signature = java.security.Signature.getInstance("SHA1withDSA"); signature.initSign(key); signature.update(data); byte[] asn1sig = signature.sign(); // // Convert ASN.1 signature to SSH signature blob // Inspired by OpenSSH code // int frst = asn1sig[3] - (byte) 0x14; int scnd = asn1sig[1] - (byte) 0x2c - frst; byte[] sshsig = new byte[asn1sig.length - frst - scnd - 6]; System.arraycopy(asn1sig, 4 + frst, sshsig, 0, 20); System.arraycopy(asn1sig, 6 + asn1sig[3] + scnd, sshsig, 20, 20); byte[] tns = null; try { tns = encodeNetworkString(SSH_DSS_PREFIX.getBytes("UTF-8")); } catch (UnsupportedEncodingException uee) {} byte[] sns = encodeNetworkString(sshsig); byte[] blob = new byte[tns.length + sns.length]; System.arraycopy(tns, 0, blob, 0, tns.length); System.arraycopy(sns, 0, blob, tns.length, sns.length); return blob; } else { return null; } } catch (NoSuchAlgorithmException nsae) { return null; } catch (InvalidKeyException ike) { return null; } catch (SignatureException se) { return null; } } /** * Verify the signature included in an SSH signature blob * * @param data The data whose signature must be verified * @param off Offset in the data array * @param len Length of data to sign * @param sigBlob The SSH signature blob containing the signature * @param pubkey The public key to use to verify the signature * @return true if the signature was verified successfully, false in all other cases (including if an error occurs). */ public static boolean sshSignatureBlobVerify(byte[] data, int off, int len, byte[] sigBlob, PublicKey pubkey) { Signature signature = null; int offset = 0; byte[] sigType = decodeNetworkString(sigBlob, 0); offset += 4; offset += sigType.length; String sigTypeStr = new String(sigType); try { if (pubkey instanceof RSAPublicKey && SSH_RSA_PREFIX.equals(sigTypeStr)) { // // Create Signature object // signature = java.security.Signature.getInstance("SHA1withRSA"); signature.initVerify(pubkey); signature.update(data, off, len); byte[] sig = decodeNetworkString(sigBlob, offset); return signature.verify(sig); } else if (pubkey instanceof DSAPublicKey && SSH_DSS_PREFIX.equals(sigTypeStr)) { // // Create Signature object // signature = java.security.Signature.getInstance("SHA1withDSA"); signature.initVerify(pubkey); signature.update(data, off, len); // // Convert SSH signature blob to ASN.1 signature // byte[] rs = decodeNetworkString(sigBlob, offset); // ASN.1 int frst = ((rs[0] & 0x80) != 0 ? 1 : 0); int scnd = ((rs[20] & 0x80) != 0 ? 1 : 0); int length = rs.length + 6 + frst + scnd; byte[] asn1sig = new byte[length]; asn1sig[0] = (byte) 0x30; asn1sig[1] = (byte) 0x2c; asn1sig[1] += frst; asn1sig[1] += scnd; asn1sig[2] = (byte) 0x02; asn1sig[3] = (byte) 0x14; asn1sig[3] += frst; System.arraycopy(rs, 0, asn1sig, 4 + frst, 20); asn1sig[4 + asn1sig[3]] = (byte) 0x02; asn1sig[5 + asn1sig[3]] = (byte) 0x14; asn1sig[5 + asn1sig[3]] += scnd; System.arraycopy(rs, 20, asn1sig, 6 + asn1sig[3] + scnd, 20); // // Verify signature // return signature.verify(asn1sig); } else { return false; } } catch (NoSuchAlgorithmException nsae) { return false; } catch (SignatureException se) { return false; } catch (InvalidKeyException ike) { return false; } } public static boolean sshSignatureBlobVerify(byte[] data, byte[] sigBlob, PublicKey pubkey) { return sshSignatureBlobVerify(data, 0, data.length, sigBlob, pubkey); } /** * Extract an encoded Network String * A Network String has its length on 4 bytes (MSB first). * * @param data Data to parse * @param offset Offset at which the network string starts. * @return */ public static byte[] decodeNetworkString(byte[] data, int offset) { int len = unpackInt(data, offset); // // Safety net, don't allow to allocate more than // what's left in the array // if (len > data.length - offset - 4) { return null; } byte[] string = new byte[len]; System.arraycopy(data, offset + 4, string, 0, len); return string; } /** * Encode data as a Network String * A Network String has its length on 4 bytes (MSB first). * * @param data Data to encode * @return the encoded data */ public static byte[] encodeNetworkString(byte[] data) { byte[] ns = new byte[4 + data.length]; // // Pack data length // packInt(data.length, ns, 0); System.arraycopy(data, 0, ns, 4, data.length); return ns; } /** * Pack an integer value in a byte array, MSB first * * @param value Value to pack * @param data Byte array where to pack * @param offset Offset where to start */ private static void packInt(int value, byte[] data, int offset) { data[0] = (byte) ((value >> 24) & 0x000000ff); data[1] = (byte) ((value >> 16) & 0x000000ff); data[2] = (byte) ((value >> 8) & 0x000000ff); data[3] = (byte) (value & 0x000000ff); } /** * Unpack an int stored as MSB first in a byte array * @param data Array from which to extract the int * @param offset Offset in the array where the int is stored * @return */ private static int unpackInt(byte[] data, int offset) { int value = 0; value |= (data[offset] << 24) & 0xff000000; value |= (data[offset + 1] << 16) &0x00ff0000; value |= (data[offset + 2] << 8) &0x0000ff00; value |= data[offset + 3] &0x000000ff; return value; } public static class SSHAgentClient { // // Request / Response codes from OpenSSH implementation // Some are not supported (yet) by this implementation // //private static final int AGENTC_REQUEST_RSA_IDENTITIES = 1; //private static final int AGENT_RSA_IDENTITIES_ANSWER = 2; private static final int AGENT_FAILURE = 5; private static final int AGENT_SUCCESS = 6; //private static final int AGENTC_REMOVE_RSA_IDENTITY = 8; //private static final int AGENTC_REMOVE_ALL_RSA_IDENTITIES = 9; private static final int AGENTC_REQUEST_IDENTITIES = 11; private static final int AGENT_IDENTITIES_ANSWER = 12; private static final int AGENTC_SIGN_REQUEST = 13; private static final int AGENT_SIGN_RESPONSE = 14; private static final int AGENTC_ADD_IDENTITY = 17; //private static final int AGENTC_REMOVE_IDENTITY = 18; //private static final int AGENTC_REMOVE_ALL_IDENTITIES = 19; private static boolean hasJUDS = false; static { try { Class c = Class.forName("com.etsy.net.UnixDomainSocket"); hasJUDS = true; } catch (Throwable t) { hasJUDS = false; } finally { if (!hasJUDS) { System.err.println("No JUDS support, please use -Djuds.in=... -Djuds.out=... or -Djuds.addr=... -Djuds.port=..."); } } } private UnixDomainSocketClient socket = null; private Socket sock = null; private InputStream in = null; private OutputStream out = null; private ByteArrayOutputStream buffer = null; /** * Callback interface to handle agent response */ private static interface AgentCallback { public Object onSuccess(byte[] packet); public Object onFailure(byte[] packet); } public static class SSHKey { public byte[] blob; public String comment; public String fingerprint; public String toString() { StringBuilder sb = new StringBuilder(); sb.append(fingerprint); sb.append(" "); sb.append(comment); return sb.toString(); } } /** * Create an instance of SSHAgentClient using the Unix Socket defined in * the environment variable SSH_AUTH_SOCK as set by ssh-agent * * @throws IOException in case of errors */ public SSHAgentClient() throws IOException { this(System.getenv("SSH_AUTH_SOCK")); } /** * Create an instance of SSHAgentClient using the provided Unix Socket * * @param path Path to the Unix domain socket to use. * @throws IOException In case of errors */ public SSHAgentClient(String path) throws IOException { if (null != System.getProperty("juds.in") && null != System.getProperty("juds.out")) { in = new FileInputStream(System.getProperty("juds.in")); out = new FileOutputStream(System.getProperty("juds.out")); } else if (null != System.getProperty("juds.addr") && null != System.getProperty("juds.port")) { sock = new Socket(); SocketAddress endpoint = new InetSocketAddress(System.getProperty("juds.addr"), Integer.valueOf(System.getProperty("juds.port"))); sock.connect(endpoint); in = sock.getInputStream(); out = sock.getOutputStream(); } else if (hasJUDS) { // // Connect to the local socket of the SSH agent // socket = new UnixDomainSocketClient(path, JUDS.SOCK_STREAM); in = socket.getInputStream(); out = socket.getOutputStream(); } else { throw new RuntimeException("No JUDS Support, use -Djuds.in=... -Djuds.out=... or -Djuds.addr=... -Djuds.port=..."); } // // Create an input buffer for data exchange with the socket // buffer = new ByteArrayOutputStream(); } public void close() { if (null != sock) { try { sock.close(); } catch (IOException ioe) { } } else if (null != socket) { socket.close(); } else { try { in.close(); } catch (IOException ioe) { } try { out.close(); } catch (IOException ioe) { } } } /** * Send a request to the SSH Agent * * @param type Type of request to send * @param data Data packet of the request * @throws IOException in case of errors */ private void sendRequest(int type, byte[] data) throws IOException { // // Allocate request packet. // It needs to hold the request data, the data length // and the request type. // byte[] packet = new byte[data.length + 4 + 1]; // // Pack data length + 1 (request type) // packInt(data.length + 1, packet, 0); // // Store request type // packet[4] = (byte) type; // // Copy request data // System.arraycopy(data, 0, packet, 5, data.length); // // Write request packet onto the socket // out.write(packet); out.flush(); } /** * Listen to agent response and call the appropriate method * of the provided callback. * * @param callback * @return * @throws IOException */ private Object awaitResponse(AgentCallback callback) throws IOException { int packetLen = -1; byte[] buf = new byte[128]; while(true) { int len = in.read(buf); // // Add data to buffer // if (len > 0) { buffer.write(buf, 0, len); } // // If buffer contains less than 4 bytes, continue reading data // if (buffer.size() <= 4) { continue; } // // If packet len has not yet been extracted, read it. // if (packetLen < 0) { packetLen = unpackInt(buffer.toByteArray(), 0); } // // If buffer does not the full packet yet, continue reading // if (buffer.size() < 4 + packetLen) { continue; } // // Buffer contains the packet data, // convert input buffer to byte array // byte[] inbuf = buffer.toByteArray(); // // Extract packet data // byte[] packet = new byte[packetLen]; System.arraycopy(inbuf, 4, packet, 0, packetLen); // // Put extraneous data at the beginning of 'buffer' // buffer.reset(); buffer.write(inbuf, 4 + packetLen, inbuf.length - packetLen - 4); // // Extract response type // int respType = packet[0]; if (AGENT_FAILURE == respType) { return callback.onFailure(packet); } else if (AGENT_SUCCESS == respType) { return callback.onSuccess(new byte[0]); } else { return callback.onSuccess(packet); } } } /** * Add an identity to the agent * * @param keyblob SSH key blob * @param comment A comment to describe the identity * @return true if the identity has been succesfully loaded */ public (Boolean) addIdentity(byte[] keyblob, String comment) throws IOException { ByteArrayOutputStream request = new ByteArrayOutputStream(); request.write(keyblob); request.write(encodeNetworkString(comment.getBytes())); sendRequest(AGENTC_ADD_IDENTITY, request.toByteArray()); return (Boolean) awaitResponse(new AgentCallback() { @Override public Object onFailure(byte[] packet) { return Boolean.FALSE; } @Override public Object onSuccess(byte[] packet) { return Boolean.TRUE; } }); } /** * Request the agent to sign 'data' using the provided key blob * * @param keyblob SSH Key Blob * @param data Data to sign * @return An SSH signature blob */ public byte[] sign(byte[] keyblob, byte[] data) throws IOException { // // Create request packet // ByteArrayOutputStream request = new ByteArrayOutputStream(); request.write(encodeNetworkString(keyblob)); request.write(encodeNetworkString(data)); request.write(new byte[4]); sendRequest(AGENTC_SIGN_REQUEST, request.toByteArray()); return (byte[]) awaitResponse(new AgentCallback() { @Override public Object onFailure(byte[] packet) { return null; } @Override public Object onSuccess(byte[] packet) { if (AGENT_SIGN_RESPONSE != packet[0]) { return null; } byte[] signature = decodeNetworkString(packet, 1); return signature; } }); } public List<SSHKey> requestIdentities() throws IOException { sendRequest(AGENTC_REQUEST_IDENTITIES, new byte[0]); Object result = awaitResponse(new AgentCallback() { @Override public Object onFailure(byte[] packet) { return null; } @Override public Object onSuccess(byte[] packet) { if (AGENT_IDENTITIES_ANSWER != packet[0]) { return null; } List<SSHKey> keys = new ArrayList<SSHKey>(); int offset = 1; int numKeys = unpackInt(packet, offset); offset += 4; for (int i = 0; i < numKeys; i++) { SSHKey key = new SSHKey(); // // Extract key blob // key.blob = decodeNetworkString(packet, offset); offset += 4 + key.blob.length; // // Extract comment // byte[] comment = decodeNetworkString(packet, offset); key.comment = new String(comment); offset += 4 + comment.length; // // Compute key fingerprint // try { key.fingerprint = new String(Hex.encode(sshKeyBlobFingerprint(key.blob)), "UTF-8"); } catch (UnsupportedEncodingException uee) { } keys.add(key); } return keys; } }); return (List<SSHKey>) result; } } // // Shamir Secret Sharing Scheme // The following code is inspired by a java version of Tontine // /** * Abstract class representing a number */ private static abstract class SSSSNumber extends Number { public abstract SSSSNumber add(SSSSNumber b); public abstract SSSSNumber sub(SSSSNumber b); public abstract SSSSNumber mul(SSSSNumber b); public abstract SSSSNumber div(SSSSNumber b); public abstract SSSSNumber neg(); public abstract SSSSNumber zero(); public abstract SSSSNumber one(); public abstract SSSSNumber clone(); } /** * Subclass of SSSSNumber for integer type */ private static final class SSSSInt extends SSSSNumber { private int value; public SSSSInt(int v) { value = v; } public SSSSNumber add(SSSSNumber b) { if (b instanceof SSSSInt) { SSSSInt bInt = (SSSSInt) b; return new SSSSInt(value + bInt.value); } else { throw new RuntimeException("Type mismatch"); } } public SSSSNumber sub(SSSSNumber b) { if (b instanceof SSSSInt) { SSSSInt bInt = (SSSSInt) b; return new SSSSInt(value - bInt.value); } else { throw new RuntimeException("Type mismatch"); } } public SSSSNumber mul(SSSSNumber b) { if (b instanceof SSSSInt) { SSSSInt bInt = (SSSSInt) b; return new SSSSInt(value * bInt.value); } else { throw new RuntimeException("Type mismatch"); } } public SSSSNumber div(SSSSNumber b) { if (b instanceof SSSSInt) { SSSSInt bInt = (SSSSInt) b; return new SSSSInt(value / bInt.value); } else { throw new RuntimeException("Type mismatch"); } } public SSSSNumber neg() { return new SSSSInt(-value); } public SSSSNumber zero() { return new SSSSInt(0); } public SSSSNumber one() { return new SSSSInt(1); } public int intValue() { return (int) value; } public long longValue() { return (long) value; } public float floatValue() { return (float) value; } public double doubleValue() { return (double) value; } public boolean equals(Object o) { if (o instanceof SSSSInt) { return (value == ((SSSSInt) o).value); } else { return false; } } public String toString() { return Integer.toString(value); } public SSSSInt clone() { return new SSSSInt(this.intValue()); } } /** * Subclass of SSSSNumber for double types */ private static final class SSSSDouble extends SSSSNumber { private double value; public SSSSDouble(double v) { this.value = v; } public SSSSNumber add(SSSSNumber b) { if (b instanceof SSSSDouble) { SSSSDouble bDouble = (SSSSDouble) b; return new SSSSDouble(value + bDouble.value); } else { throw new RuntimeException("Type mismatch"); } } public SSSSNumber sub(SSSSNumber b) { if (b instanceof SSSSDouble) { SSSSDouble bDouble = (SSSSDouble) b; return new SSSSDouble(value - bDouble.value); } else { throw new RuntimeException("Type mismatch"); } } public SSSSNumber mul(SSSSNumber b) { if (b instanceof SSSSDouble) { SSSSDouble bDouble = (SSSSDouble) b; return new SSSSDouble(value * bDouble.value); } else { throw new RuntimeException("Type mismatch"); } } public SSSSNumber div(SSSSNumber b) { if (b instanceof SSSSDouble) { SSSSDouble bDouble = (SSSSDouble) b; return new SSSSDouble(value / bDouble.value); } else { throw new RuntimeException("Type mismatch"); } } public SSSSNumber neg() { return new SSSSDouble(-value); } public SSSSNumber zero() { return new SSSSDouble(0); } public SSSSNumber one() { return new SSSSDouble(1); } public int intValue() { return (int) value; } public long longValue() { return (long) value; } public float floatValue() { return (float) value; } public double doubleValue() { return (double) value; } public boolean equals(Object o) { if (o instanceof SSSSDouble) { return (value == ((SSSSDouble) o).value); } else { return false; } } public String toString() { return Double.toString(value); } public SSSSDouble clone() { return new SSSSDouble(this.doubleValue()); } } /** * Subclass of SSSSNumber for polynomials */ private static final class SSSSPolynomial extends SSSSNumber { /** * Polynomial coefficients */ SSSSNumber[] coefficients; public SSSSPolynomial(SSSSNumber[] c) { this.coefficients = new SSSSNumber[c.length]; for (int i = 0; i < c.length; i++) { if (null == c[i]) { throw new RuntimeException("Null coefficient for degree " + i); } this.coefficients[i] = c[i].clone(); } } /** * Compute the value of polynomial at x * @param x * @return */ public SSSSNumber f(SSSSNumber x) { SSSSNumber result = coefficients[coefficients.length - 1]; for (int i = coefficients.length - 1; i > 0; i--) { result = result.mul(x); result = result.add(coefficients[i - 1]); } return result; } public SSSSNumber add(SSSSNumber b) { SSSSNumber[] result; if (b instanceof SSSSPolynomial) { SSSSPolynomial bPoly = (SSSSPolynomial) b; int degMin = Math.min(coefficients.length, bPoly.coefficients.length); int degMax = Math.max(coefficients.length, bPoly.coefficients.length); boolean bBigger = (bPoly.coefficients.length > coefficients.length); result = new SSSSNumber[degMax]; for (int i = 0; i < degMin; i++) { result[i] = coefficients[i].add(bPoly.coefficients[i]); } for (int i = degMin; i < degMax; i++) { if (bBigger) { result[i] = bPoly.coefficients[i]; } else { result[i] = coefficients[i]; } } } else { result = copy(); result[0].add(b); } return new SSSSPolynomial(result); } public SSSSNumber sub(SSSSNumber b) { SSSSNumber[] result; if (b instanceof SSSSPolynomial) { SSSSPolynomial bPoly = (SSSSPolynomial) b; int degMin = Math.min(coefficients.length, bPoly.coefficients.length); int degMax = Math.max(coefficients.length, bPoly.coefficients.length); boolean bBigger = (bPoly.coefficients.length > coefficients.length); result = new SSSSNumber[degMax]; for (int i = 0; i < degMin; i++) { result[i] = coefficients[i].sub(bPoly.coefficients[i]); } for (int i = degMin; i < degMax; i++) { if (bBigger) { result[i] = bPoly.coefficients[i].neg(); } else { result[i] = coefficients[i]; } } } else { result = copy(); result[0].add(b); } return new SSSSPolynomial(result); } public SSSSNumber mul(SSSSNumber b) { SSSSNumber[] result; if (b instanceof SSSSPolynomial) { SSSSPolynomial bPoly = (SSSSPolynomial) b; result = new SSSSNumber[coefficients.length + bPoly.coefficients.length - 1]; for (int i = 0; i < coefficients.length; i++) { for (int j = 0; j < bPoly.coefficients.length; j++) { SSSSNumber co = coefficients[i].mul(bPoly.coefficients[j]); if (result[i + j] == null) { result[i + j] = co; } else { result[i + j] = result[i + j].add(co); } } } } else { result = copy(); for (int i = 0; i < result.length; i++) { result[i] = result[i].mul(b); } } return new SSSSPolynomial(result); } public SSSSNumber div(SSSSNumber b) { return null; } public SSSSNumber neg() { SSSSNumber[] result = copy(); for (int i = 0; i < result.length; i++) { result[i] = result[i].neg(); } return new SSSSPolynomial(result); } public SSSSNumber zero() { return coefficients[0].zero(); } public SSSSNumber one() { return coefficients[0].one(); } public int getDegree() { if (coefficients.length > 0) { return coefficients.length - 1; } else { return 0; } } public SSSSNumber getCoefficient(int index) { return coefficients[index]; } public int intValue() { return coefficients[0].intValue(); } public long longValue() { return coefficients[0].longValue(); } public float floatValue() { return coefficients[0].floatValue(); } public double doubleValue() { return coefficients[0].doubleValue(); } private SSSSNumber[] copy() { SSSSNumber[] result = new SSSSNumber[coefficients.length]; System.arraycopy(coefficients, 0, result, 0, coefficients.length); return result; } private int degree(SSSSNumber[] coeff) { if (null == coeff) { return 0; } for (int i = coeff.length - 1; i >= 0; i--) { if (!coeff[i].equals(coeff[i].zero())) { return i; } } return 0; } public String toString() { StringBuilder result = new StringBuilder(); for (int i = getDegree(); i >= 0; i--) { result.append(getCoefficient(i)); result.append("*x^"); result.append(i); result.append(' '); } return result.toString(); } public SSSSPolynomial clone() { return new SSSSPolynomial(this.coefficients); } } /** * A point has two coordinates (x,y) of type {@link SSSSNumber}. */ private static final class SSSSXY extends SSSSNumber { SSSSNumber x; SSSSNumber y; /** * Create a new point. * * @param x The x coordinate of this point. * @param y The y coordinate of this point. */ public SSSSXY(SSSSNumber x, SSSSNumber y) { this.x = x; this.y = y; } public SSSSNumber add(SSSSNumber b) { if (b instanceof SSSSXY) { SSSSXY bXY = (SSSSXY) b; return new SSSSXY(getX().add(bXY.getX()), getY().add(bXY.getY())); } else { throw new UnsupportedOperationException("Need to add an instance of SSSSXY."); } } public SSSSNumber sub(SSSSNumber b) { if (b instanceof SSSSXY) { SSSSXY bXY = (SSSSXY) b; return new SSSSXY(getX().sub(bXY.getX()), getY().sub(bXY.getY())); } else { throw new UnsupportedOperationException("Need to add an instance of SSSSXY."); } } /** * Multiplication of two XY is defined as a new XY whose coordinates * are the product of each member's matching coordinates */ public SSSSNumber mul(SSSSNumber b) { if (b instanceof SSSSXY) { SSSSXY bXY = (SSSSXY) b; return new SSSSXY(getX().mul(bXY.getX()), getY().mul(bXY.getY())); } else { return new SSSSXY(getX().mul(b), getY().mul(b)); } } /** * Division of two XY is defined as a new XY whose coordinates are * the results of the division of each dividend's coordinate by the matching coordinate of the * divisor */ public SSSSNumber div(SSSSNumber b) { if (b instanceof SSSSXY) { SSSSXY bXY = (SSSSXY) b; return new SSSSXY(getX().div(bXY.getX()), getY().div(bXY.getY())); } else { return new SSSSXY(getX().div(b), getY().div(b)); } } public SSSSNumber neg() { return new SSSSXY(getX().neg(), getY().neg()); } public SSSSNumber zero() { return new SSSSXY(getX().zero(), getY().zero()); } public SSSSNumber one() { return new SSSSXY(getX().one(), getY().one()); } public SSSSNumber getX() { return this.x; } public SSSSNumber getY() { return this.y; } public int intValue() { throw new UnsupportedOperationException(); } public long longValue() { throw new UnsupportedOperationException(); } public float floatValue() { throw new UnsupportedOperationException(); } public double doubleValue() { throw new UnsupportedOperationException(); } public SSSSXY clone() { return new SSSSXY(this.x, this.y); } } /** * This exception is throw when two points with the same x coordinate are encountered in * an {@link SSSSPolynomialInterpolator}. */ private static class SSSSDuplicateAbscissaException extends Exception { public SSSSDuplicateAbscissaException() { super("Abscissa collision detected during interpolation"); } } /** * Interface of polynomial interpolator */ private static interface SSSSPolynomialInterpolator { /** * Find a polynomial that interpolates the given points. * * @param points Set of points to interpolate * @return The polynomial passing through the given points. * @throws SSSSDuplicateAbscissaException If any two points share the same x coordinate. */ public SSSSPolynomial interpolate(SSSSXY[] points) throws SSSSDuplicateAbscissaException; } /** * Polynomial interpolator using Lagrange polynomials * * @see http://en.wikipedia.org/wiki/Lagrange_polynomial */ private static class SSSSLagrangePolynomialInterpolator implements SSSSPolynomialInterpolator { public SSSSPolynomial interpolate(SSSSXY[] points) throws SSSSDuplicateAbscissaException { SSSSNumber result = null; // // Check x coordinates // checkPointSeparation(points); // // Build the interpolating polynomial as a linear combination // of Lagrange basis polynomials // for (int j = 0; j < points.length; j++) { if (result != null) { result = result.add(Lj(points, j)); } else { result = Lj(points, j); } } return (SSSSPolynomial) result; } /** * Checks that a set of points does not contain points with identical x coordinates. * * @param points Set of points to check. * @throws SSSSDuplicateAbscissaException if identical x coordinates exist */ private void checkPointSeparation(SSSSXY[] points) throws SSSSDuplicateAbscissaException { for (int i = 0; i < points.length - 1; i++) { for (int j = i + 1; j < points.length; j++) { if (points[i].getX().equals(points[j].getX())) { throw new SSSSDuplicateAbscissaException(); } } } } /** * Return the j'th Lagrange basis polynomial * * @param points Set of points to interpolate * @param j Index of polynomial to return * @return */ private SSSSNumber Lj(SSSSXY[] points, int j) { SSSSNumber one = points[0].getX().one(); SSSSNumber[] resultP = new SSSSNumber[1]; resultP[0] = points[j].getY(); SSSSNumber[] product = new SSSSNumber[2]; SSSSNumber result = new SSSSPolynomial(resultP); for (int i = 0; i < points.length; i++) { if (i == j) { continue; } SSSSNumber numerator; SSSSNumber denominator; numerator = one; denominator = points[j].getX().sub(points[i].getX()); product[1] = numerator.div(denominator); numerator = points[i].getX(); denominator = points[i].getX().sub(points[j].getX()); product[0] = numerator.div(denominator); SSSSPolynomial poly = new SSSSPolynomial(product); result = result.mul(poly); } return result; } } /** * This class represents polynomials over GF(256) * * GF(p^n) is a finite (or Galois) field, p being prime. * * @see http://mathworld.wolfram.com/FiniteField.html * * The advantage of GF(256) is that it contains 256 elements * so each byte value can be considered a polynomial over GF(256) * and arithmetic rules can be implemented that represent polynomial * arithmetic in GF(256). * * Each byte is mapped to a polynomial using the following rule: * * Bit n of a byte is the polynomial coefficient of x^n. * * So 0x0D = 0b00001101 = x^3 + x^2 + 1 * * The modulo polynomial used to generate this field is * * x^8 + x^4 + x^3 + x^2 + 1 * * 0x011D = 0b0000000100011101 */ public static final class SSSSGF256Polynomial extends SSSSNumber { /** * Value representing the polynomial */ private short value; /** * Generator used to generate the exp/log tables * * For QR/Code generator is 0x02 and Prime polynomial 0x11d * For Rijndael generator is 0x03 and Prime polynomial 0x11b */ private static final int GF256_GENERATOR = 0x02; /** * Prime polynomial used to generate the exp/log tables */ private static final int GF256_PRIME_POLYNOMIAL = 0x11d; public static final short[] GF256_exptable; public static final short[] GF256_logtable; static { // // Generate GF256 exp/log tables // @see http://en.wikiversity.org/wiki/Reed%E2%80%93Solomon_codes_for_coders // @see http://www.samiam.org/galois.html // GF256_exptable = new short[256]; GF256_logtable = new short[256]; GF256_logtable[0] = (1 - 256) & 0xff; GF256_exptable[0] = 1; for (int i = 1; i < 256; i++) { int exp = GF256_exptable[i - 1] * GF256_GENERATOR; if (exp >= 256) { exp ^= GF256_PRIME_POLYNOMIAL; } exp &= 0xff; GF256_exptable[i] = (short) exp; // Generator^255 = Generator^0 so we use the power modulo 255 // @see http://math.stackexchange.com/questions/76045/reed-solomon-polynomial-generator GF256_logtable[GF256_exptable[i]] = (short) (((short) i) % 255); } } /** * @param v The integer representing the polynomial in this * field. A bit i = 2<sup>n</sup> is set iff * x<sup>n</sup> is a term in the polynomial. */ public SSSSGF256Polynomial(int v) { value = (short) v; } /** * Implement addition on GF256, polynomial coefficients are * XORed * * @param b The SSSSGF256Polynomial to add * @throws RuntimeException in case of type mismatch */ public SSSSNumber add(SSSSNumber b) { if (b instanceof SSSSGF256Polynomial) { SSSSGF256Polynomial bPoly = (SSSSGF256Polynomial) b; return new SSSSGF256Polynomial(bPoly.value ^ value); } else { throw new RuntimeException("Type mismatch"); } } /** * Polynomial subtraction is really an addition since in * GF(2^n), a + b = a - b * * @param b SSSSGF256Polynomial to subtract * @throws RuntimeException in case of type mismatch */ public SSSSNumber sub(SSSSNumber b) { return add(b); } /** * Multiplication in GF256. * * @param b The second term. It must also be a GF256. * @throws RuntimeException If the second term is not of type * GF256. */ public SSSSNumber mul(SSSSNumber b) { if (b instanceof SSSSGF256Polynomial) { SSSSGF256Polynomial bPoly = (SSSSGF256Polynomial) b; // // Handle the special case of 0 // 0 * x = x * 0 = 0 // if ((bPoly.value == 0) || (value == 0)) { return zero(); } // // In the general case, multiplication is done using logarithms // @see http://www.logic.at/wiki/index.php/GF(256) // // log(a * b) = log(a) + log(b) // // Modulo is 255 because there are only 255 values in the log table int newPower = (log() + bPoly.log()) % 255; return new SSSSGF256Polynomial(GF256_exptable[newPower]); } else { throw new RuntimeException("Type mismatch."); } } /** * Division in GF256. * * @param b The second term. It must also be a GF256. * @throws RuntimeException If the second term is not of type * GF256 or if we divide by 0. */ public SSSSNumber div(SSSSNumber b) { if (b instanceof SSSSGF256Polynomial) { SSSSGF256Polynomial bPoly = (SSSSGF256Polynomial) b; // // Cannot divide by 0 // if (bPoly.value == 0) { throw new RuntimeException("Division by zero."); } // // 0 / x = 0 // if (value == 0) { return zero(); } // // Use the log rule: // @see http://www.logic.at/wiki/index.php/GF(256) // // log(a/b) = log(a) - log(b) // int newPower = (log() - bPoly.log()) % 255; if (newPower < 0) { newPower += 255; } return (SSSSNumber) new SSSSGF256Polynomial(GF256_exptable[newPower]); } else { throw new RuntimeException("Type mismatch"); } } /** * a + a = 0, so a = -a. * * @return The arithmetic inverse of the current value. */ public SSSSNumber neg() { return new SSSSGF256Polynomial(-value); } /** * @return The arithmetic identity. */ public SSSSNumber zero() { return new SSSSGF256Polynomial(0); } /** * @return The multiplicative identity. */ public SSSSNumber one() { return new SSSSGF256Polynomial(1); } public int intValue() { return (int) value; } public long longValue() { return (long) value; } public float floatValue() { return (float) value; } public double doubleValue() { return (double) value; } /** * @return The value n such that x<sup>n</n> is equivalent to * the current polynomial in this field. */ private int log() { if (0 == value) { throw new RuntimeException("Cannot take log of 0"); } return GF256_logtable[value]; } public String toString() { return Short.toString(value); } public int hashCode() { return value; } public boolean equals(Object o) { if (o instanceof SSSSGF256Polynomial) { SSSSGF256Polynomial oPoly = (SSSSGF256Polynomial) o; if (oPoly.value == value) { return true; } } return false; } @Override public SSSSGF256Polynomial clone() { return new SSSSGF256Polynomial(this.intValue()); } } /** * Implements a Shamir Secret Sharing Scheme. * * An input stream of bytes (the secret) is split by an encoder * in a number (n) of keys (byte streams) so that k of those keys * can be combined by a decoder to recreate the secret. */ public static final class SSSS { /** * Polynomial interpolator */ private SSSSPolynomialInterpolator interpolator; /** * Pseudo Random Number Generator */ private SecureRandom prng; /** * Create an encoder/decoder using the default * PRNG and the Lagrange polynomial interpolator. */ public SSSS() { interpolator = new SSSSLagrangePolynomialInterpolator(); prng = CryptoHelper.sr; } /** * Create an encoder using the Lagrange polynomial interpolator * and the specified SecureRandom implementation. * * @param rand The SecureRandom instance to use. */ public SSSS(SecureRandom rand) { interpolator = new SSSSLagrangePolynomialInterpolator(); prng = rand; } /** * Create an encoder using the specified SecureRandom implementation * and the specified SSSSPolynomialInterpolator. * * @param rand The SecureRandom instance to use. * @param pi The SSSSPolynomialInterpolator instance to use */ public SSSS(SecureRandom rand, SSSSPolynomialInterpolator pi) { interpolator = pi; prng = rand; } /** * Given k keys, recreate the secret. * If the keys are the wrong ones, the produced data will be random. * To further detect that situation, the secret should contain a * control mechanism to validate the decoded data. * * The decode method operates on streams so input and output can * be of any size. * * @param result The OutputStream to which the reconstructed secret will be written * @param keys Key InputStreams * @throws IOException in case of I/O errors * @throws SSSSDuplicateAbscissaException If the keys cover identical points, probably because they're the wrong ones */ public void decode(OutputStream result, InputStream[] keys) throws IOException, SSSSDuplicateAbscissaException { SSSSXY[] pGroup; do { pGroup = readPoints(keys); if (pGroup != null) { result.write(decodeByte(pGroup)); } } while (pGroup != null); } private int decodeByte(SSSSXY[] points) throws IOException, SSSSDuplicateAbscissaException { SSSSPolynomial fit = interpolator.interpolate(points); // // Decoded byte is P(0) where P is the polynomial which interpolates all points. // SSSSGF256Polynomial result = (SSSSGF256Polynomial) fit.f(new SSSSGF256Polynomial(0)); return result.intValue(); } /** * Read one point from each key * * @param keys Key InputStreams * @return An array of SSSSXY instances or null if EOF is reached on one key * @throws IOException */ private SSSSXY[] readPoints(InputStream[] keys) throws IOException { SSSSXY[] result = new SSSSXY[keys.length]; int xVal, yVal; // // Read one valid x/y pair per key // for (int i = 0; i < result.length; i++) { // // Read one x/y pair, skipping pairs whose x coordinate is 0 // do { xVal = keys[i].read(); if (xVal < 0) { return null; } yVal = keys[i].read(); if (yVal < 0) { return null; } } while (xVal == 0); // // X and Y coordinates are GF256 polynomials // result[i] = new SSSSXY(new SSSSGF256Polynomial(xVal), new SSSSGF256Polynomial(yVal)); } return result; } /** * Given a secret, write out the keys representing that secret. * * @param input The InputStream containing the secret * @param keys OutputStreams for each of the keys. * * @throws IOException If there's an I/O error reading or writing */ public void encode(InputStream input, OutputStream[] keys, int keysNeeded) throws IOException { // // If n < 2 or n > 255 or k < 2 we cannot split, ditto if k > n // if (keys.length < 2 || keys.length > 255 || keysNeeded < 2 || keysNeeded > keys.length) { throw new RuntimeException("Need to have at least 2 keys and at most 255 and more keys than number of needed keys."); } int v; do { // // Read input byte // v = input.read(); if (v >= 0) { encodeByte(v, keys, keysNeeded); } } while (v >= 0); } /** * Encode a byte * * @param byteVal Byte value to encode * @param keys OutputStreams for the keys * @param keysNeeded Number of keys needed to reconstruct the secret * @throws IOException if an I/O error occurs */ private void encodeByte(int byteVal, OutputStream[] keys, int keysNeeded) throws IOException { // // Array of boolean to keep track of x values already chosen // boolean[] picked = new boolean[256]; // // Select a random polynomial whose value at 0 is the byte value to encode // The degree of the polynomial is the number of keys needed to reconstruct the secret minus one // (Because N points determine uniquely a polynomial of degree N-1, i.e. two points a line, three a parabola...) // SSSSPolynomial rPoly = selectRandomPolynomial(keysNeeded - 1, new SSSSGF256Polynomial(byteVal)); // // Pick a distinct x value per key. // If 0 is chosen as x value, generate a random byte as the associated y coordinate // and pick another x value. // 0 cannot be chosen as P(0) is the encoded value, but we cannot ignore 0 otherwise the // keys would fail a randomness test (since they would not contain enough 0s) // for (int i = 0; i < keys.length; i++) { int xPick; do { // // Pick a random x value // xPick = getRandomByte(); // // If we picked 0, write it out with a random y value to // pass randomness tests // if (xPick == 0) { keys[i].write(xPick); keys[i].write(getRandomByte()); } // Do so while we picked 0 or an already picked x value } while ((xPick == 0) || (picked[xPick] == true)); // Marked the current x value as picked picked[xPick] = true; // Generate x/y SSSSGF256Polynomial xVal = new SSSSGF256Polynomial(xPick); SSSSGF256Polynomial yVal = (SSSSGF256Polynomial) rPoly.f(xVal); // Write x/y pair keys[i].write(xVal.intValue()); keys[i].write(yVal.intValue()); } } /** * Select a random polynomial with coefficients in GF256 whose degree and * value at the origin are fixed. * * @param degree Degree of the polynomial to generate * @param c0 Value of P(0) * @return */ private SSSSPolynomial selectRandomPolynomial(int degree, SSSSGF256Polynomial c0) { SSSSNumber[] coeff = new SSSSNumber[degree + 1]; coeff[0] = c0; for (int i = 1; i < degree; i++) { coeff[i] = new SSSSGF256Polynomial(getRandomByte()); } int cDegree; // // Make sure coefficient for 'degree' is non 0 // do { cDegree = getRandomByte(); } while (cDegree == 0); coeff[degree] = new SSSSGF256Polynomial(cDegree); return new SSSSPolynomial(coeff); } /** * Generate a single byte using the provided PRNG * * @return A random byte */ private int getRandomByte() { byte[] v = new byte[1]; prng.nextBytes(v); return (int) (v[0] & 0xff); } } /** * Split 'data' in N parts, K of which are needed to recover 'data'. * * K should be > N/2 so there are no two independent sets of secrets * in the wild which could be used to recover the initial data. * * @param data * @param n * @param k * @return */ public static List<byte[]> SSSSSplit(byte[] data, int n, int k) { // // If n < 2 or k < 2 we cannot split, ditto if k > n // if (n < 2 || n > 255 || k < 2 || k > n) { return null; } List<byte[]> secrets = new ArrayList<byte[]>(); SSSS ss = new SSSS(); ByteArrayInputStream bais = new ByteArrayInputStream(data); ByteArrayOutputStream[] baos = new ByteArrayOutputStream[n]; for (int i = 0; i < n; i++) { baos[i] = new ByteArrayOutputStream(); } try { ss.encode (bais, baos, k); } catch (IOException ioe) { return null; } // // Retrieve secrets from ByteArrayOutputStream instances // for (int i = 0; i < n; i++) { secrets.add(baos[i].toByteArray()); } return secrets; } /** * Recover data from a list of secrets which is a sublist of a list generated by 'split' * * @param secrets * @return */ public static byte[] SSSSRecover(Collection<byte[]> secrets) { SSSS ss = new SSSS(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ByteArrayInputStream[] bais = new ByteArrayInputStream[secrets.size()]; int i = 0; for (byte[] secret: secrets) { bais[i] = new ByteArrayInputStream(secret); i++; } try { ss.decode(baos, bais); } catch (SSSSDuplicateAbscissaException dpe) { return null; } catch (IOException ioe) { return null; } return baos.toByteArray(); } // // PGP Related code // public static List<PGPPublicKey> PGPPublicKeysFromKeyRing(String keyring) throws IOException { PGPObjectFactory factory = new PGPObjectFactory(PGPUtil.getDecoderStream(new ByteArrayInputStream(keyring.getBytes("UTF-8")))); List<PGPPublicKey> pubkeys = new ArrayList<PGPPublicKey>(); do { Object o = factory.nextObject(); if (null == o) { break; } if (o instanceof PGPKeyRing) { PGPKeyRing ring = (PGPKeyRing) o; Iterator<PGPPublicKey> iter = ring.getPublicKeys(); while(iter.hasNext()) { PGPPublicKey key = iter.next(); pubkeys.add(key); } } } while (true); return pubkeys; } public static byte[] encryptPGP(byte[] data, PGPPublicKey key, boolean armored, String name, int compressionAlgorithm, int encAlgorithm) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); OutputStream out = armored ? new ArmoredOutputStream(baos) : baos; BcPGPDataEncryptorBuilder dataEncryptor = new BcPGPDataEncryptorBuilder(encAlgorithm); dataEncryptor.setWithIntegrityPacket(true); dataEncryptor.setSecureRandom(CryptoHelper.getSecureRandom()); PGPEncryptedDataGenerator encryptedDataGenerator = new PGPEncryptedDataGenerator(dataEncryptor); encryptedDataGenerator.addMethod(new BcPublicKeyKeyEncryptionMethodGenerator(key)); try { OutputStream encout = encryptedDataGenerator.open(out, 1024); PGPCompressedDataGenerator pgpcdg = new PGPCompressedDataGenerator(compressionAlgorithm); OutputStream compout = pgpcdg.open(encout); PGPLiteralDataGenerator pgpldg = new PGPLiteralDataGenerator(false); OutputStream ldout = pgpldg.open(compout, PGPLiteralData.BINARY, name, data.length, PGPLiteralData.NOW); ldout.write(data); ldout.close(); compout.close(); encout.close(); out.close(); baos.close(); return baos.toByteArray(); } catch (PGPException pgpe) { throw new IOException(pgpe); } } }
src/main/java/com/geoxp/oss/CryptoHelper.java
/* * Copyright 2012-2013 Mathias Herberts * * 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.geoxp.oss; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.math.BigInteger; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketAddress; import java.security.InvalidKeyException; import java.security.Key; import java.security.KeyFactory; import java.security.KeyPair; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.SecureRandom; import java.security.Security; import java.security.Signature; import java.security.SignatureException; import java.security.interfaces.DSAPrivateKey; import java.security.interfaces.DSAPublicKey; import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; import java.security.spec.DSAPublicKeySpec; import java.security.spec.InvalidKeySpecException; import java.security.spec.KeySpec; import java.security.spec.RSAPublicKeySpec; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.List; import org.bouncycastle.bcpg.ArmoredOutputStream; import org.bouncycastle.crypto.AsymmetricBlockCipher; import org.bouncycastle.crypto.InvalidCipherTextException; import org.bouncycastle.crypto.encodings.PKCS1Encoding; import org.bouncycastle.crypto.engines.AESWrapEngine; import org.bouncycastle.crypto.engines.RSABlindedEngine; import org.bouncycastle.crypto.paddings.PKCS7Padding; import org.bouncycastle.crypto.params.KeyParameter; import org.bouncycastle.crypto.params.RSAKeyParameters; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.openpgp.PGPCompressedDataGenerator; import org.bouncycastle.openpgp.PGPEncryptedDataGenerator; import org.bouncycastle.openpgp.PGPException; import org.bouncycastle.openpgp.PGPKeyRing; import org.bouncycastle.openpgp.PGPLiteralData; import org.bouncycastle.openpgp.PGPLiteralDataGenerator; import org.bouncycastle.openpgp.PGPObjectFactory; import org.bouncycastle.openpgp.PGPPublicKey; import org.bouncycastle.openpgp.PGPUtil; import org.bouncycastle.openpgp.operator.bc.BcPGPDataEncryptorBuilder; import org.bouncycastle.openpgp.operator.bc.BcPublicKeyKeyEncryptionMethodGenerator; import org.bouncycastle.util.encoders.Hex; import com.etsy.net.JUDS; import com.etsy.net.UnixDomainSocketClient; /** * Helper class containing various methods used to * ease up cryptographic operations */ public class CryptoHelper { /** * Default algorithm to use when generating signatures */ public static final String DEFAULT_SIGNATURE_ALGORITHM = "SHA256WithRSA"; private static final String SSH_DSS_PREFIX = "ssh-dss"; private static final String SSH_RSA_PREFIX = "ssh-rsa"; /** * SecureRandom used by the class */ private static SecureRandom sr = null; static { // // Add BouncyCastleProvider // Security.addProvider(new BouncyCastleProvider()); // // Create PRNG, will be null if provider/algorithm not found // try { sr = SecureRandom.getInstance("SHA1PRNG","SUN"); } catch (NoSuchProviderException nspe) { } catch (NoSuchAlgorithmException nsae) { } if (null == sr) { sr = new SecureRandom(); } } public static SecureRandom getSecureRandom() { return CryptoHelper.sr; } /** * Pad data using PKCS7. * * @param alignment Alignement on which to pad, e.g. 8 * @param data Data to pad * @return The padded data */ public static byte[] padPKCS7(int alignment, byte[] data, int offset, int len) { // // Allocate the target byte array. Its size is a multiple of 'alignment'. // If data to pad is a multiple of 'alignment', the target array will be // 'alignment' bytes longer than the data to pad. // byte[] target = new byte[len + (alignment - len % alignment)]; // // Copy the data to pad into the target array // System.arraycopy (data, offset, target, 0, len); // // Add padding bytes // PKCS7Padding padding = new PKCS7Padding(); padding.addPadding(target, len); return target; } public static byte[] padPKCS7(int alignment, byte[] data) { return padPKCS7(alignment, data, 0, data.length); } /** * Remove PKCS7 padding from padded data * @param padded The padded data to 'unpad' * @return The original unpadded data * @throws InvalidCipherTextException if data is not correctly padded */ public static byte[] unpadPKCS7(byte[] padded) throws InvalidCipherTextException { PKCS7Padding padding = new PKCS7Padding(); // // Determine length of padding // int pad = padding.padCount(padded); // // Allocate array for unpadded data // byte[] unpadded = new byte[padded.length - pad]; // // Copy data without the padding // System.arraycopy(padded, 0, unpadded, 0, padded.length - pad); return unpadded; } /** * Protect some data using AES Key Wrapping * * @param key AES wrapping key * @param data Data to wrap * @param offset Where does the data start in 'data' * @param len How long is the data * @param nonce Should a random prefix be added to the data prior to wrapping * @return The wrapped data */ public static byte[] wrapAES(byte[] key, byte[] data, int offset, int len, boolean nonce) { // // Initialize AES Wrap Engine for wrapping // AESWrapEngine aes = new AESWrapEngine(); KeyParameter keyparam = new KeyParameter(key); aes.init(true, keyparam); if (nonce) { byte[] nonced = new byte[len + OSS.NONCE_BYTES]; byte[] noncebytes = new byte[OSS.NONCE_BYTES]; getSecureRandom().nextBytes(noncebytes); System.arraycopy(noncebytes, 0, nonced, 0, OSS.NONCE_BYTES); System.arraycopy(data, offset, nonced, OSS.NONCE_BYTES, len); data = nonced; offset = 0; len = data.length; } // // Pad the data on an 8 bytes boundary // byte[] padded = padPKCS7(8, data, offset, len); // // Wrap data and return it // return aes.wrap(padded, 0, padded.length); } public static byte[] wrapAES(byte[] key, byte[] data) { return wrapAES(key, data, 0, data.length, false); } public static byte[] wrapBlob(byte[] key, byte[] blob) { return wrapAES(key, blob, 0, blob.length, true); } /** * Unwrap data protected by AES Key Wrapping * * @param key Key used to wrap the data * @param data Wrapped data * @return The unwrapped data or null if an error occurred */ public static byte[] unwrapAES(byte[] key, byte[] data, boolean hasnonce) { // // Initialize the AES Wrap Engine for unwrapping // AESWrapEngine aes = new AESWrapEngine(); KeyParameter keyparam = new KeyParameter(key); aes.init(false, keyparam); // // Unwrap then unpad data // try { byte[] unpadded = unpadPKCS7(aes.unwrap(data, 0, data.length)); // // Remove nonce if data has one // if (hasnonce) { return Arrays.copyOfRange(unpadded, OSS.NONCE_BYTES, unpadded.length); } else { return unpadded; } } catch (InvalidCipherTextException icte) { return null; } } public static byte[] unwrapAES(byte[] key, byte[] data) { return unwrapAES(key, data, false); } public static byte[] unwrapBlob(byte[] key, byte[] blob) { return unwrapAES(key, blob, true); } /** * Encrypt data using RSA. * CAUTION: this can take a while on large data * * @param key RSA key to use for encryption * @param data Cleartext data * @return The ciphertext data or null if an error occured */ public static byte[] encryptRSA(Key key, byte[] data) { // // Get an RSA Cipher instance // //Cipher rsa = null; try { /* The following commented code can be used the BouncyCastle * JCE provider signature is intact, which is not the * case when BC has been repackaged using jarjar rsa = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC"); rsa.init (Cipher.ENCRYPT_MODE, key, CryptoHelper.sr); return rsa.doFinal(data); */ AsymmetricBlockCipher c = new PKCS1Encoding(new RSABlindedEngine()); if (key instanceof RSAPublicKey) { c.init(true, new RSAKeyParameters(true, ((RSAPublicKey) key).getModulus(), ((RSAPublicKey) key).getPublicExponent())); } else if (key instanceof RSAPrivateKey) { c.init(true, new RSAKeyParameters(true, ((RSAPrivateKey) key).getModulus(), ((RSAPrivateKey) key).getPrivateExponent())); } else { return null; } int insize = c.getInputBlockSize(); int offset = 0; ByteArrayOutputStream baos = new ByteArrayOutputStream(); while(offset < data.length) { int len = Math.min(insize, data.length - offset); baos.write(c.processBlock(data, offset, len)); offset += len; } return baos.toByteArray(); /* } catch (NoSuchProviderException nspe) { return null; } catch (NoSuchPaddingException nspe) { return null; } catch (NoSuchAlgorithmException nsae) { return null; } catch (InvalidKeyException ike) { return null; } catch (BadPaddingException bpe) { return null; } catch (IllegalBlockSizeException ibse) { return null; } */ } catch (InvalidCipherTextException icte) { return null; } catch (IOException ioe) { return null; } } /** * Decrypt data previously encrypted with RSA * @param key RSA key to use for decryption * @param data Ciphertext data * @return The cleartext data or null if an error occurred */ public static byte[] decryptRSA(Key key, byte[] data) { // // Get an RSA Cipher instance // //Cipher rsa = null; try { /* The following commented code can be used the BouncyCastle * JCE provider signature is intact, which is not the * case when BC has been repackaged using jarjar rsa = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC"); rsa.init (Cipher.DECRYPT_MODE, key, CryptoHelper.sr); return rsa.doFinal(data); */ AsymmetricBlockCipher c = new PKCS1Encoding(new RSABlindedEngine()); if (key instanceof RSAPublicKey) { c.init(false, new RSAKeyParameters(true, ((RSAPublicKey) key).getModulus(), ((RSAPublicKey) key).getPublicExponent())); } else if (key instanceof RSAPrivateKey) { c.init(false, new RSAKeyParameters(true, ((RSAPrivateKey) key).getModulus(), ((RSAPrivateKey) key).getPrivateExponent())); } else { return null; } int insize = c.getInputBlockSize(); int offset = 0; ByteArrayOutputStream baos = new ByteArrayOutputStream(); while(offset < data.length) { int len = Math.min(insize, data.length - offset); baos.write(c.processBlock(data, offset, len)); offset += len; } return baos.toByteArray(); /* } catch (NoSuchProviderException nspe) { return null; } catch (NoSuchPaddingException nspe) { return null; } catch (NoSuchAlgorithmException nsae) { return null; } catch (InvalidKeyException ike) { return null; } catch (BadPaddingException bpe) { return null; } catch (IllegalBlockSizeException ibse) { return null; } */ } catch (InvalidCipherTextException icte) { return null; } catch (IOException ioe) { return null; } } /** * Sign data using the given algorithm * * @param algorithm Name of algorithm to use for signing * @param key Private key to use for signing (must be compatible with chosen algorithm) * @param data Data to sign * @return The signature of data or null if an error occurred */ public static byte[] sign(String algorithm, PrivateKey key, byte[] data) { try { Signature signature = Signature.getInstance(algorithm, "BC"); signature.initSign(key, CryptoHelper.sr); signature.update(data); return signature.sign(); } catch (SignatureException se) { return null; } catch (InvalidKeyException ike) { return null; } catch (NoSuchAlgorithmException nsae) { return null; } catch (NoSuchProviderException nspe) { return null; } } /** * Verify a signature * * @param algorithm Algorithm used to generate the signature * @param key Public key to use for verifying the signature * @param data Data whose signature must be verified * @param sig The signature to verify * @return true or false depending on successful verification */ public static boolean verify(String algorithm, PublicKey key, byte[] data, byte[] sig) { try { Signature signature = Signature.getInstance(algorithm, "BC"); signature.initVerify(key); signature.update(data); return signature.verify(sig); } catch (SignatureException se) { return false; } catch (InvalidKeyException ike) { return false; } catch (NoSuchAlgorithmException nsae) { return false; } catch (NoSuchProviderException nspe) { return false; } } /** * Convert an SSH Key Blob to a Public Key * * @param blob SSH Key Blob * @return The extracted public key or null if an error occurred */ public static PublicKey sshKeyBlobToPublicKey(byte[] blob) { // // RFC 4253 describes keys as either // // ssh-dss p q g y // ssh-rsa e n // // // Extract SSH key type // byte[] keyType = decodeNetworkString(blob,0); int offset = 4 + keyType.length; String keyTypeStr = new String(keyType); try { if (SSH_DSS_PREFIX.equals(keyTypeStr)) { // // Extract DSA key parameters p q g and y // byte[] p = decodeNetworkString(blob, offset); offset += 4; offset += p.length; byte[] q = decodeNetworkString(blob, offset); offset += 4; offset += q.length; byte[] g = decodeNetworkString(blob, offset); offset += 4; offset += g.length; byte[] y = decodeNetworkString(blob, offset); offset += 4; offset += y.length; KeySpec key = new DSAPublicKeySpec(new BigInteger(y), new BigInteger(p), new BigInteger(q), new BigInteger(g)); return KeyFactory.getInstance("DSA").generatePublic(key); } else if (SSH_RSA_PREFIX.equals(keyTypeStr)) { // // Extract RSA key parameters e and n // byte[] e = decodeNetworkString(blob, offset); offset += 4; offset += e.length; byte[] n = decodeNetworkString(blob, offset); offset += 4; offset += n.length; KeySpec key = new RSAPublicKeySpec(new BigInteger(n), new BigInteger(e)); return KeyFactory.getInstance("RSA").generatePublic(key); } else { return null; } } catch (NoSuchAlgorithmException nsae) { nsae.printStackTrace(); return null; } catch (InvalidKeySpecException ikse) { ikse.printStackTrace(); return null; } } /** * Compute the MD5 fingerprint of an SSH key blob * * @param blob Public Key Blob to compute the fingerprint on * @return The computed signature or null if an error occurred */ public static byte[] sshKeyBlobFingerprint(byte[] blob) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(blob); return md5.digest(); } catch (NoSuchAlgorithmException nsae) { return null; } } /** * Encode a key pair as an SSH Key Blob * * @param kp Public/private key pair to encode * @return The encoded public key or null if provided key is not RSA or DSA */ public static byte[] sshKeyBlobFromKeyPair(KeyPair kp) { if (kp.getPrivate() instanceof RSAPrivateKey) { // // Extract key parameters // BigInteger n = ((RSAPublicKey) kp.getPublic()).getModulus(); BigInteger e = ((RSAPublicKey) kp.getPublic()).getPublicExponent(); BigInteger d = ((RSAPrivateKey) kp.getPrivate()).getPrivateExponent(); // Not available and not used by ssh-agent anyway ... BigInteger iqmp = BigInteger.ZERO; BigInteger p = BigInteger.ZERO; BigInteger q = BigInteger.ZERO; byte[] tns = null; try { tns = encodeNetworkString(SSH_RSA_PREFIX.getBytes("UTF-8")); } catch (UnsupportedEncodingException uee) {} byte[] nns = encodeNetworkString(n.toByteArray()); byte[] ens = encodeNetworkString(e.toByteArray()); byte[] dns = encodeNetworkString(d.toByteArray()); byte[] iqmpns = encodeNetworkString(iqmp.toByteArray()); byte[] pns = encodeNetworkString(p.toByteArray()); byte[] qns = encodeNetworkString(q.toByteArray()); // // Allocate array for blob // byte[] blob = new byte[tns.length + nns.length + ens.length + dns.length + iqmpns.length + pns.length + qns.length]; // // Copy network strings to blob // System.arraycopy(tns, 0, blob, 0, tns.length); System.arraycopy(nns, 0, blob, tns.length, nns.length); System.arraycopy(ens, 0, blob, tns.length + nns.length, ens.length); System.arraycopy(dns, 0, blob, tns.length + nns.length + ens.length, dns.length); System.arraycopy(iqmpns, 0, blob, tns.length + nns.length + ens.length + dns.length, iqmpns.length); System.arraycopy(pns, 0, blob, tns.length + nns.length + ens.length + dns.length + iqmpns.length, pns.length); System.arraycopy(qns, 0, blob, tns.length + nns.length + ens.length + dns.length + iqmpns.length + pns.length, qns.length); return blob; } else if (kp.getPrivate() instanceof DSAPrivateKey) { // // Extract key parameters // BigInteger p = ((DSAPublicKey) kp.getPublic()).getParams().getP(); BigInteger q = ((DSAPublicKey) kp.getPublic()).getParams().getQ(); BigInteger g = ((DSAPublicKey) kp.getPublic()).getParams().getG(); BigInteger y = ((DSAPublicKey) kp.getPublic()).getY(); BigInteger x = ((DSAPrivateKey) kp.getPrivate()).getX(); // // Encode parameters as network strings // byte[] tns = null; try { tns = encodeNetworkString(SSH_DSS_PREFIX.getBytes("UTF-8")); } catch (UnsupportedEncodingException uee) {} byte[] pns = encodeNetworkString(p.toByteArray()); byte[] qns = encodeNetworkString(q.toByteArray()); byte[] gns = encodeNetworkString(g.toByteArray()); byte[] yns = encodeNetworkString(y.toByteArray()); byte[] xns = encodeNetworkString(x.toByteArray()); // // Allocate array for blob // byte[] blob = new byte[tns.length + pns.length + qns.length + gns.length + yns.length + xns.length]; // // Copy network strings to blob // System.arraycopy(tns, 0, blob, 0, tns.length); System.arraycopy(pns, 0, blob, tns.length, pns.length); System.arraycopy(qns, 0, blob, tns.length + pns.length, qns.length); System.arraycopy(gns, 0, blob, tns.length + pns.length + qns.length, gns.length); System.arraycopy(yns, 0, blob, tns.length + pns.length + qns.length + gns.length, yns.length); System.arraycopy(xns, 0, blob, tns.length + pns.length + qns.length + gns.length + yns.length, xns.length); return blob; } else { return null; } } /** * Encode a public key as an SSH Key Blob * * @param key Public key to encode * @return The encoded public key or null if provided key is not RSA or DSA */ public static byte[] sshKeyBlobFromPublicKey(PublicKey key) { if (key instanceof RSAPublicKey) { // // Extract public exponent and modulus // BigInteger e = ((RSAPublicKey) key).getPublicExponent(); BigInteger n = ((RSAPublicKey) key).getModulus(); // // Encode parameters as Network Strings // byte[] tns = null; try { tns = encodeNetworkString(SSH_RSA_PREFIX.getBytes("UTF-8")); } catch (UnsupportedEncodingException uee) {} byte[] ens = encodeNetworkString(e.toByteArray()); byte[] nns = encodeNetworkString(n.toByteArray()); // // Allocate array for blob // byte[] blob = new byte[tns.length + nns.length + ens.length]; // // Copy network strings to blob // System.arraycopy(tns, 0, blob, 0, tns.length); System.arraycopy(ens, 0, blob, tns.length, ens.length); System.arraycopy(nns, 0, blob, tns.length + ens.length, nns.length); return blob; } else if (key instanceof DSAPublicKey) { // // Extract key parameters // BigInteger p = ((DSAPublicKey) key).getParams().getP(); BigInteger q = ((DSAPublicKey) key).getParams().getQ(); BigInteger g = ((DSAPublicKey) key).getParams().getG(); BigInteger y = ((DSAPublicKey) key).getY(); // // Encode parameters as network strings // byte[] tns = null; try { tns = encodeNetworkString(SSH_DSS_PREFIX.getBytes("UTF-8")); } catch (UnsupportedEncodingException uee) {} byte[] pns = encodeNetworkString(p.toByteArray()); byte[] qns = encodeNetworkString(q.toByteArray()); byte[] gns = encodeNetworkString(g.toByteArray()); byte[] yns = encodeNetworkString(y.toByteArray()); // // Allocate array for blob // byte[] blob = new byte[tns.length + pns.length + qns.length + gns.length + yns.length]; // // Copy network strings to blob // System.arraycopy(tns, 0, blob, 0, tns.length); System.arraycopy(pns, 0, blob, tns.length, pns.length); System.arraycopy(qns, 0, blob, tns.length + pns.length, qns.length); System.arraycopy(gns, 0, blob, tns.length + pns.length + qns.length, gns.length); System.arraycopy(yns, 0, blob, tns.length + pns.length + qns.length + gns.length, yns.length); return blob; } else { return null; } } /** * Generate an SSH signature blob * * @param data Data to sign * @param key Private key to use for signing * @return The generated signature blob or null if the provided key is not supported */ public static byte[] sshSignatureBlobSign(byte[] data, PrivateKey key) { try { if (key instanceof RSAPrivateKey) { // // Create Signature object // Signature signature = java.security.Signature.getInstance("SHA1withRSA"); signature.initSign(key); signature.update(data); byte[] sig = signature.sign(); // // Build the SSH sigBlob // byte[] tns = null; try { encodeNetworkString(SSH_RSA_PREFIX.getBytes("UTF-8")); } catch (UnsupportedEncodingException uee) {} byte[] sns = encodeNetworkString(sig); byte[] blob = new byte[tns.length + sns.length]; System.arraycopy(tns, 0, blob, 0, tns.length); System.arraycopy(sns, 0, blob, tns.length, sns.length); return blob; } else if (key instanceof DSAPrivateKey) { // // Create Signature object // Signature signature = java.security.Signature.getInstance("SHA1withDSA"); signature.initSign(key); signature.update(data); byte[] asn1sig = signature.sign(); // // Convert ASN.1 signature to SSH signature blob // Inspired by OpenSSH code // int frst = asn1sig[3] - (byte) 0x14; int scnd = asn1sig[1] - (byte) 0x2c - frst; byte[] sshsig = new byte[asn1sig.length - frst - scnd - 6]; System.arraycopy(asn1sig, 4 + frst, sshsig, 0, 20); System.arraycopy(asn1sig, 6 + asn1sig[3] + scnd, sshsig, 20, 20); byte[] tns = null; try { tns = encodeNetworkString(SSH_DSS_PREFIX.getBytes("UTF-8")); } catch (UnsupportedEncodingException uee) {} byte[] sns = encodeNetworkString(sshsig); byte[] blob = new byte[tns.length + sns.length]; System.arraycopy(tns, 0, blob, 0, tns.length); System.arraycopy(sns, 0, blob, tns.length, sns.length); return blob; } else { return null; } } catch (NoSuchAlgorithmException nsae) { return null; } catch (InvalidKeyException ike) { return null; } catch (SignatureException se) { return null; } } /** * Verify the signature included in an SSH signature blob * * @param data The data whose signature must be verified * @param off Offset in the data array * @param len Length of data to sign * @param sigBlob The SSH signature blob containing the signature * @param pubkey The public key to use to verify the signature * @return true if the signature was verified successfully, false in all other cases (including if an error occurs). */ public static boolean sshSignatureBlobVerify(byte[] data, int off, int len, byte[] sigBlob, PublicKey pubkey) { Signature signature = null; int offset = 0; byte[] sigType = decodeNetworkString(sigBlob, 0); offset += 4; offset += sigType.length; String sigTypeStr = new String(sigType); try { if (pubkey instanceof RSAPublicKey && SSH_RSA_PREFIX.equals(sigTypeStr)) { // // Create Signature object // signature = java.security.Signature.getInstance("SHA1withRSA"); signature.initVerify(pubkey); signature.update(data, off, len); byte[] sig = decodeNetworkString(sigBlob, offset); return signature.verify(sig); } else if (pubkey instanceof DSAPublicKey && SSH_DSS_PREFIX.equals(sigTypeStr)) { // // Create Signature object // signature = java.security.Signature.getInstance("SHA1withDSA"); signature.initVerify(pubkey); signature.update(data, off, len); // // Convert SSH signature blob to ASN.1 signature // byte[] rs = decodeNetworkString(sigBlob, offset); // ASN.1 int frst = ((rs[0] & 0x80) != 0 ? 1 : 0); int scnd = ((rs[20] & 0x80) != 0 ? 1 : 0); int length = rs.length + 6 + frst + scnd; byte[] asn1sig = new byte[length]; asn1sig[0] = (byte) 0x30; asn1sig[1] = (byte) 0x2c; asn1sig[1] += frst; asn1sig[1] += scnd; asn1sig[2] = (byte) 0x02; asn1sig[3] = (byte) 0x14; asn1sig[3] += frst; System.arraycopy(rs, 0, asn1sig, 4 + frst, 20); asn1sig[4 + asn1sig[3]] = (byte) 0x02; asn1sig[5 + asn1sig[3]] = (byte) 0x14; asn1sig[5 + asn1sig[3]] += scnd; System.arraycopy(rs, 20, asn1sig, 6 + asn1sig[3] + scnd, 20); // // Verify signature // return signature.verify(asn1sig); } else { return false; } } catch (NoSuchAlgorithmException nsae) { return false; } catch (SignatureException se) { return false; } catch (InvalidKeyException ike) { return false; } } public static boolean sshSignatureBlobVerify(byte[] data, byte[] sigBlob, PublicKey pubkey) { return sshSignatureBlobVerify(data, 0, data.length, sigBlob, pubkey); } /** * Extract an encoded Network String * A Network String has its length on 4 bytes (MSB first). * * @param data Data to parse * @param offset Offset at which the network string starts. * @return */ public static byte[] decodeNetworkString(byte[] data, int offset) { int len = unpackInt(data, offset); // // Safety net, don't allow to allocate more than // what's left in the array // if (len > data.length - offset - 4) { return null; } byte[] string = new byte[len]; System.arraycopy(data, offset + 4, string, 0, len); return string; } /** * Encode data as a Network String * A Network String has its length on 4 bytes (MSB first). * * @param data Data to encode * @return the encoded data */ public static byte[] encodeNetworkString(byte[] data) { byte[] ns = new byte[4 + data.length]; // // Pack data length // packInt(data.length, ns, 0); System.arraycopy(data, 0, ns, 4, data.length); return ns; } /** * Pack an integer value in a byte array, MSB first * * @param value Value to pack * @param data Byte array where to pack * @param offset Offset where to start */ private static void packInt(int value, byte[] data, int offset) { data[0] = (byte) ((value >> 24) & 0x000000ff); data[1] = (byte) ((value >> 16) & 0x000000ff); data[2] = (byte) ((value >> 8) & 0x000000ff); data[3] = (byte) (value & 0x000000ff); } /** * Unpack an int stored as MSB first in a byte array * @param data Array from which to extract the int * @param offset Offset in the array where the int is stored * @return */ private static int unpackInt(byte[] data, int offset) { int value = 0; value |= (data[offset] << 24) & 0xff000000; value |= (data[offset + 1] << 16) &0x00ff0000; value |= (data[offset + 2] << 8) &0x0000ff00; value |= data[offset + 3] &0x000000ff; return value; } public static class SSHAgentClient { // // Request / Response codes from OpenSSH implementation // Some are not supported (yet) by this implementation // //private static final int AGENTC_REQUEST_RSA_IDENTITIES = 1; //private static final int AGENT_RSA_IDENTITIES_ANSWER = 2; private static final int AGENT_FAILURE = 5; private static final int AGENT_SUCCESS = 6; //private static final int AGENTC_REMOVE_RSA_IDENTITY = 8; //private static final int AGENTC_REMOVE_ALL_RSA_IDENTITIES = 9; private static final int AGENTC_REQUEST_IDENTITIES = 11; private static final int AGENT_IDENTITIES_ANSWER = 12; private static final int AGENTC_SIGN_REQUEST = 13; private static final int AGENT_SIGN_RESPONSE = 14; private static final int AGENTC_ADD_IDENTITY = 17; //private static final int AGENTC_REMOVE_IDENTITY = 18; //private static final int AGENTC_REMOVE_ALL_IDENTITIES = 19; private static boolean hasJUDS = false; static { try { Class c = Class.forName("com.etsy.net.UnixDomainSocket"); hasJUDS = true; } catch (Throwable t) { hasJUDS = false; } finally { if (!hasJUDS) { System.err.println("No JUDS support, please use -Djuds.in=... -Djuds.out=... or -Djuds.addr=... -Djuds.port=..."); } } } private UnixDomainSocketClient socket = null; private Socket sock = null; private InputStream in = null; private OutputStream out = null; private ByteArrayOutputStream buffer = null; /** * Callback interface to handle agent response */ private static interface AgentCallback { public Object onSuccess(byte[] packet); public Object onFailure(byte[] packet); } public static class SSHKey { public byte[] blob; public String comment; public String fingerprint; public String toString() { StringBuilder sb = new StringBuilder(); sb.append(fingerprint); sb.append(" "); sb.append(comment); return sb.toString(); } } /** * Create an instance of SSHAgentClient using the Unix Socket defined in * the environment variable SSH_AUTH_SOCK as set by ssh-agent * * @throws IOException in case of errors */ public SSHAgentClient() throws IOException { this(System.getenv("SSH_AUTH_SOCK")); } /** * Create an instance of SSHAgentClient using the provided Unix Socket * * @param path Path to the Unix domain socket to use. * @throws IOException In case of errors */ public SSHAgentClient(String path) throws IOException { if (null != System.getProperty("juds.in") && null != System.getProperty("juds.out")) { in = new FileInputStream(System.getProperty("juds.in")); out = new FileOutputStream(System.getProperty("juds.out")); } else if (null != System.getProperty("juds.addr") && null != System.getProperty("juds.port")) { sock = new Socket(); SocketAddress endpoint = new InetSocketAddress(System.getProperty("juds.addr"), Integer.valueOf(System.getProperty("juds.port"))); sock.connect(endpoint); in = sock.getInputStream(); out = sock.getOutputStream(); } else if (hasJUDS) { // // Connect to the local socket of the SSH agent // socket = new UnixDomainSocketClient(path, JUDS.SOCK_STREAM); in = socket.getInputStream(); out = socket.getOutputStream(); } else { throw new RuntimeException("No JUDS Support, use -Djuds.in=... -Djuds.out=... or -Djuds.addr=... -Djuds.port=..."); } // // Create an input buffer for data exchange with the socket // buffer = new ByteArrayOutputStream(); } public void close() { if (null != sock) { try { sock.close(); } catch (IOException ioe) { } } else if (null != socket) { socket.close(); } else { try { in.close(); } catch (IOException ioe) { } try { out.close(); } catch (IOException ioe) { } } } /** * Send a request to the SSH Agent * * @param type Type of request to send * @param data Data packet of the request * @throws IOException in case of errors */ private void sendRequest(int type, byte[] data) throws IOException { // // Allocate request packet. // It needs to hold the request data, the data length // and the request type. // byte[] packet = new byte[data.length + 4 + 1]; // // Pack data length + 1 (request type) // packInt(data.length + 1, packet, 0); // // Store request type // packet[4] = (byte) type; // // Copy request data // System.arraycopy(data, 0, packet, 5, data.length); // // Write request packet onto the socket // out.write(packet); out.flush(); } /** * Listen to agent response and call the appropriate method * of the provided callback. * * @param callback * @return * @throws IOException */ private Object awaitResponse(AgentCallback callback) throws IOException { int packetLen = -1; byte[] buf = new byte[128]; while(true) { int len = in.read(buf); // // Add data to buffer // if (len > 0) { buffer.write(buf, 0, len); } // // If buffer contains less than 4 bytes, continue reading data // if (buffer.size() <= 4) { continue; } // // If packet len has not yet been extracted, read it. // if (packetLen < 0) { packetLen = unpackInt(buffer.toByteArray(), 0); } // // If buffer does not the full packet yet, continue reading // if (buffer.size() < 4 + packetLen) { continue; } // // Buffer contains the packet data, // convert input buffer to byte array // byte[] inbuf = buffer.toByteArray(); // // Extract packet data // byte[] packet = new byte[packetLen]; System.arraycopy(inbuf, 4, packet, 0, packetLen); // // Put extraneous data at the beginning of 'buffer' // buffer.reset(); buffer.write(inbuf, 4 + packetLen, inbuf.length - packetLen - 4); // // Extract response type // int respType = packet[0]; if (AGENT_FAILURE == respType) { return callback.onFailure(packet); } else if (AGENT_SUCCESS == respType) { return callback.onSuccess(new byte[0]); } else { return callback.onSuccess(packet); } } } /** * Add an identity to the agent * */ public Boolean addIdentity(byte[] keyblob, String comment) throws IOException { ByteArrayOutputStream request = new ByteArrayOutputStream(); request.write(keyblob); request.write(encodeNetworkString(comment.getBytes())); sendRequest(AGENTC_ADD_IDENTITY, request.toByteArray()); return (Boolean) awaitResponse(new AgentCallback() { @Override public Object onFailure(byte[] packet) { return Boolean.FALSE; } @Override public Object onSuccess(byte[] packet) { return Boolean.TRUE; } }); } /** * Request the agent to sign 'data' using the provided key blob * * @param keyblob SSH Key Blob * @param data Data to sign * @return An SSH signature blob */ public byte[] sign(byte[] keyblob, byte[] data) throws IOException { // // Create request packet // ByteArrayOutputStream request = new ByteArrayOutputStream(); request.write(encodeNetworkString(keyblob)); request.write(encodeNetworkString(data)); request.write(new byte[4]); sendRequest(AGENTC_SIGN_REQUEST, request.toByteArray()); return (byte[]) awaitResponse(new AgentCallback() { @Override public Object onFailure(byte[] packet) { return null; } @Override public Object onSuccess(byte[] packet) { if (AGENT_SIGN_RESPONSE != packet[0]) { return null; } byte[] signature = decodeNetworkString(packet, 1); return signature; } }); } public List<SSHKey> requestIdentities() throws IOException { sendRequest(AGENTC_REQUEST_IDENTITIES, new byte[0]); Object result = awaitResponse(new AgentCallback() { @Override public Object onFailure(byte[] packet) { return null; } @Override public Object onSuccess(byte[] packet) { if (AGENT_IDENTITIES_ANSWER != packet[0]) { return null; } List<SSHKey> keys = new ArrayList<SSHKey>(); int offset = 1; int numKeys = unpackInt(packet, offset); offset += 4; for (int i = 0; i < numKeys; i++) { SSHKey key = new SSHKey(); // // Extract key blob // key.blob = decodeNetworkString(packet, offset); offset += 4 + key.blob.length; // // Extract comment // byte[] comment = decodeNetworkString(packet, offset); key.comment = new String(comment); offset += 4 + comment.length; // // Compute key fingerprint // try { key.fingerprint = new String(Hex.encode(sshKeyBlobFingerprint(key.blob)), "UTF-8"); } catch (UnsupportedEncodingException uee) { } keys.add(key); } return keys; } }); return (List<SSHKey>) result; } } // // Shamir Secret Sharing Scheme // The following code is inspired by a java version of Tontine // /** * Abstract class representing a number */ private static abstract class SSSSNumber extends Number { public abstract SSSSNumber add(SSSSNumber b); public abstract SSSSNumber sub(SSSSNumber b); public abstract SSSSNumber mul(SSSSNumber b); public abstract SSSSNumber div(SSSSNumber b); public abstract SSSSNumber neg(); public abstract SSSSNumber zero(); public abstract SSSSNumber one(); public abstract SSSSNumber clone(); } /** * Subclass of SSSSNumber for integer type */ private static final class SSSSInt extends SSSSNumber { private int value; public SSSSInt(int v) { value = v; } public SSSSNumber add(SSSSNumber b) { if (b instanceof SSSSInt) { SSSSInt bInt = (SSSSInt) b; return new SSSSInt(value + bInt.value); } else { throw new RuntimeException("Type mismatch"); } } public SSSSNumber sub(SSSSNumber b) { if (b instanceof SSSSInt) { SSSSInt bInt = (SSSSInt) b; return new SSSSInt(value - bInt.value); } else { throw new RuntimeException("Type mismatch"); } } public SSSSNumber mul(SSSSNumber b) { if (b instanceof SSSSInt) { SSSSInt bInt = (SSSSInt) b; return new SSSSInt(value * bInt.value); } else { throw new RuntimeException("Type mismatch"); } } public SSSSNumber div(SSSSNumber b) { if (b instanceof SSSSInt) { SSSSInt bInt = (SSSSInt) b; return new SSSSInt(value / bInt.value); } else { throw new RuntimeException("Type mismatch"); } } public SSSSNumber neg() { return new SSSSInt(-value); } public SSSSNumber zero() { return new SSSSInt(0); } public SSSSNumber one() { return new SSSSInt(1); } public int intValue() { return (int) value; } public long longValue() { return (long) value; } public float floatValue() { return (float) value; } public double doubleValue() { return (double) value; } public boolean equals(Object o) { if (o instanceof SSSSInt) { return (value == ((SSSSInt) o).value); } else { return false; } } public String toString() { return Integer.toString(value); } public SSSSInt clone() { return new SSSSInt(this.intValue()); } } /** * Subclass of SSSSNumber for double types */ private static final class SSSSDouble extends SSSSNumber { private double value; public SSSSDouble(double v) { this.value = v; } public SSSSNumber add(SSSSNumber b) { if (b instanceof SSSSDouble) { SSSSDouble bDouble = (SSSSDouble) b; return new SSSSDouble(value + bDouble.value); } else { throw new RuntimeException("Type mismatch"); } } public SSSSNumber sub(SSSSNumber b) { if (b instanceof SSSSDouble) { SSSSDouble bDouble = (SSSSDouble) b; return new SSSSDouble(value - bDouble.value); } else { throw new RuntimeException("Type mismatch"); } } public SSSSNumber mul(SSSSNumber b) { if (b instanceof SSSSDouble) { SSSSDouble bDouble = (SSSSDouble) b; return new SSSSDouble(value * bDouble.value); } else { throw new RuntimeException("Type mismatch"); } } public SSSSNumber div(SSSSNumber b) { if (b instanceof SSSSDouble) { SSSSDouble bDouble = (SSSSDouble) b; return new SSSSDouble(value / bDouble.value); } else { throw new RuntimeException("Type mismatch"); } } public SSSSNumber neg() { return new SSSSDouble(-value); } public SSSSNumber zero() { return new SSSSDouble(0); } public SSSSNumber one() { return new SSSSDouble(1); } public int intValue() { return (int) value; } public long longValue() { return (long) value; } public float floatValue() { return (float) value; } public double doubleValue() { return (double) value; } public boolean equals(Object o) { if (o instanceof SSSSDouble) { return (value == ((SSSSDouble) o).value); } else { return false; } } public String toString() { return Double.toString(value); } public SSSSDouble clone() { return new SSSSDouble(this.doubleValue()); } } /** * Subclass of SSSSNumber for polynomials */ private static final class SSSSPolynomial extends SSSSNumber { /** * Polynomial coefficients */ SSSSNumber[] coefficients; public SSSSPolynomial(SSSSNumber[] c) { this.coefficients = new SSSSNumber[c.length]; for (int i = 0; i < c.length; i++) { if (null == c[i]) { throw new RuntimeException("Null coefficient for degree " + i); } this.coefficients[i] = c[i].clone(); } } /** * Compute the value of polynomial at x * @param x * @return */ public SSSSNumber f(SSSSNumber x) { SSSSNumber result = coefficients[coefficients.length - 1]; for (int i = coefficients.length - 1; i > 0; i--) { result = result.mul(x); result = result.add(coefficients[i - 1]); } return result; } public SSSSNumber add(SSSSNumber b) { SSSSNumber[] result; if (b instanceof SSSSPolynomial) { SSSSPolynomial bPoly = (SSSSPolynomial) b; int degMin = Math.min(coefficients.length, bPoly.coefficients.length); int degMax = Math.max(coefficients.length, bPoly.coefficients.length); boolean bBigger = (bPoly.coefficients.length > coefficients.length); result = new SSSSNumber[degMax]; for (int i = 0; i < degMin; i++) { result[i] = coefficients[i].add(bPoly.coefficients[i]); } for (int i = degMin; i < degMax; i++) { if (bBigger) { result[i] = bPoly.coefficients[i]; } else { result[i] = coefficients[i]; } } } else { result = copy(); result[0].add(b); } return new SSSSPolynomial(result); } public SSSSNumber sub(SSSSNumber b) { SSSSNumber[] result; if (b instanceof SSSSPolynomial) { SSSSPolynomial bPoly = (SSSSPolynomial) b; int degMin = Math.min(coefficients.length, bPoly.coefficients.length); int degMax = Math.max(coefficients.length, bPoly.coefficients.length); boolean bBigger = (bPoly.coefficients.length > coefficients.length); result = new SSSSNumber[degMax]; for (int i = 0; i < degMin; i++) { result[i] = coefficients[i].sub(bPoly.coefficients[i]); } for (int i = degMin; i < degMax; i++) { if (bBigger) { result[i] = bPoly.coefficients[i].neg(); } else { result[i] = coefficients[i]; } } } else { result = copy(); result[0].add(b); } return new SSSSPolynomial(result); } public SSSSNumber mul(SSSSNumber b) { SSSSNumber[] result; if (b instanceof SSSSPolynomial) { SSSSPolynomial bPoly = (SSSSPolynomial) b; result = new SSSSNumber[coefficients.length + bPoly.coefficients.length - 1]; for (int i = 0; i < coefficients.length; i++) { for (int j = 0; j < bPoly.coefficients.length; j++) { SSSSNumber co = coefficients[i].mul(bPoly.coefficients[j]); if (result[i + j] == null) { result[i + j] = co; } else { result[i + j] = result[i + j].add(co); } } } } else { result = copy(); for (int i = 0; i < result.length; i++) { result[i] = result[i].mul(b); } } return new SSSSPolynomial(result); } public SSSSNumber div(SSSSNumber b) { return null; } public SSSSNumber neg() { SSSSNumber[] result = copy(); for (int i = 0; i < result.length; i++) { result[i] = result[i].neg(); } return new SSSSPolynomial(result); } public SSSSNumber zero() { return coefficients[0].zero(); } public SSSSNumber one() { return coefficients[0].one(); } public int getDegree() { if (coefficients.length > 0) { return coefficients.length - 1; } else { return 0; } } public SSSSNumber getCoefficient(int index) { return coefficients[index]; } public int intValue() { return coefficients[0].intValue(); } public long longValue() { return coefficients[0].longValue(); } public float floatValue() { return coefficients[0].floatValue(); } public double doubleValue() { return coefficients[0].doubleValue(); } private SSSSNumber[] copy() { SSSSNumber[] result = new SSSSNumber[coefficients.length]; System.arraycopy(coefficients, 0, result, 0, coefficients.length); return result; } private int degree(SSSSNumber[] coeff) { if (null == coeff) { return 0; } for (int i = coeff.length - 1; i >= 0; i--) { if (!coeff[i].equals(coeff[i].zero())) { return i; } } return 0; } public String toString() { StringBuilder result = new StringBuilder(); for (int i = getDegree(); i >= 0; i--) { result.append(getCoefficient(i)); result.append("*x^"); result.append(i); result.append(' '); } return result.toString(); } public SSSSPolynomial clone() { return new SSSSPolynomial(this.coefficients); } } /** * A point has two coordinates (x,y) of type {@link SSSSNumber}. */ private static final class SSSSXY extends SSSSNumber { SSSSNumber x; SSSSNumber y; /** * Create a new point. * * @param x The x coordinate of this point. * @param y The y coordinate of this point. */ public SSSSXY(SSSSNumber x, SSSSNumber y) { this.x = x; this.y = y; } public SSSSNumber add(SSSSNumber b) { if (b instanceof SSSSXY) { SSSSXY bXY = (SSSSXY) b; return new SSSSXY(getX().add(bXY.getX()), getY().add(bXY.getY())); } else { throw new UnsupportedOperationException("Need to add an instance of SSSSXY."); } } public SSSSNumber sub(SSSSNumber b) { if (b instanceof SSSSXY) { SSSSXY bXY = (SSSSXY) b; return new SSSSXY(getX().sub(bXY.getX()), getY().sub(bXY.getY())); } else { throw new UnsupportedOperationException("Need to add an instance of SSSSXY."); } } /** * Multiplication of two XY is defined as a new XY whose coordinates * are the product of each member's matching coordinates */ public SSSSNumber mul(SSSSNumber b) { if (b instanceof SSSSXY) { SSSSXY bXY = (SSSSXY) b; return new SSSSXY(getX().mul(bXY.getX()), getY().mul(bXY.getY())); } else { return new SSSSXY(getX().mul(b), getY().mul(b)); } } /** * Division of two XY is defined as a new XY whose coordinates are * the results of the division of each dividend's coordinate by the matching coordinate of the * divisor */ public SSSSNumber div(SSSSNumber b) { if (b instanceof SSSSXY) { SSSSXY bXY = (SSSSXY) b; return new SSSSXY(getX().div(bXY.getX()), getY().div(bXY.getY())); } else { return new SSSSXY(getX().div(b), getY().div(b)); } } public SSSSNumber neg() { return new SSSSXY(getX().neg(), getY().neg()); } public SSSSNumber zero() { return new SSSSXY(getX().zero(), getY().zero()); } public SSSSNumber one() { return new SSSSXY(getX().one(), getY().one()); } public SSSSNumber getX() { return this.x; } public SSSSNumber getY() { return this.y; } public int intValue() { throw new UnsupportedOperationException(); } public long longValue() { throw new UnsupportedOperationException(); } public float floatValue() { throw new UnsupportedOperationException(); } public double doubleValue() { throw new UnsupportedOperationException(); } public SSSSXY clone() { return new SSSSXY(this.x, this.y); } } /** * This exception is throw when two points with the same x coordinate are encountered in * an {@link SSSSPolynomialInterpolator}. */ private static class SSSSDuplicateAbscissaException extends Exception { public SSSSDuplicateAbscissaException() { super("Abscissa collision detected during interpolation"); } } /** * Interface of polynomial interpolator */ private static interface SSSSPolynomialInterpolator { /** * Find a polynomial that interpolates the given points. * * @param points Set of points to interpolate * @return The polynomial passing through the given points. * @throws SSSSDuplicateAbscissaException If any two points share the same x coordinate. */ public SSSSPolynomial interpolate(SSSSXY[] points) throws SSSSDuplicateAbscissaException; } /** * Polynomial interpolator using Lagrange polynomials * * @see http://en.wikipedia.org/wiki/Lagrange_polynomial */ private static class SSSSLagrangePolynomialInterpolator implements SSSSPolynomialInterpolator { public SSSSPolynomial interpolate(SSSSXY[] points) throws SSSSDuplicateAbscissaException { SSSSNumber result = null; // // Check x coordinates // checkPointSeparation(points); // // Build the interpolating polynomial as a linear combination // of Lagrange basis polynomials // for (int j = 0; j < points.length; j++) { if (result != null) { result = result.add(Lj(points, j)); } else { result = Lj(points, j); } } return (SSSSPolynomial) result; } /** * Checks that a set of points does not contain points with identical x coordinates. * * @param points Set of points to check. * @throws SSSSDuplicateAbscissaException if identical x coordinates exist */ private void checkPointSeparation(SSSSXY[] points) throws SSSSDuplicateAbscissaException { for (int i = 0; i < points.length - 1; i++) { for (int j = i + 1; j < points.length; j++) { if (points[i].getX().equals(points[j].getX())) { throw new SSSSDuplicateAbscissaException(); } } } } /** * Return the j'th Lagrange basis polynomial * * @param points Set of points to interpolate * @param j Index of polynomial to return * @return */ private SSSSNumber Lj(SSSSXY[] points, int j) { SSSSNumber one = points[0].getX().one(); SSSSNumber[] resultP = new SSSSNumber[1]; resultP[0] = points[j].getY(); SSSSNumber[] product = new SSSSNumber[2]; SSSSNumber result = new SSSSPolynomial(resultP); for (int i = 0; i < points.length; i++) { if (i == j) { continue; } SSSSNumber numerator; SSSSNumber denominator; numerator = one; denominator = points[j].getX().sub(points[i].getX()); product[1] = numerator.div(denominator); numerator = points[i].getX(); denominator = points[i].getX().sub(points[j].getX()); product[0] = numerator.div(denominator); SSSSPolynomial poly = new SSSSPolynomial(product); result = result.mul(poly); } return result; } } /** * This class represents polynomials over GF(256) * * GF(p^n) is a finite (or Galois) field, p being prime. * * @see http://mathworld.wolfram.com/FiniteField.html * * The advantage of GF(256) is that it contains 256 elements * so each byte value can be considered a polynomial over GF(256) * and arithmetic rules can be implemented that represent polynomial * arithmetic in GF(256). * * Each byte is mapped to a polynomial using the following rule: * * Bit n of a byte is the polynomial coefficient of x^n. * * So 0x0D = 0b00001101 = x^3 + x^2 + 1 * * The modulo polynomial used to generate this field is * * x^8 + x^4 + x^3 + x^2 + 1 * * 0x011D = 0b0000000100011101 */ public static final class SSSSGF256Polynomial extends SSSSNumber { /** * Value representing the polynomial */ private short value; /** * Generator used to generate the exp/log tables * * For QR/Code generator is 0x02 and Prime polynomial 0x11d * For Rijndael generator is 0x03 and Prime polynomial 0x11b */ private static final int GF256_GENERATOR = 0x02; /** * Prime polynomial used to generate the exp/log tables */ private static final int GF256_PRIME_POLYNOMIAL = 0x11d; public static final short[] GF256_exptable; public static final short[] GF256_logtable; static { // // Generate GF256 exp/log tables // @see http://en.wikiversity.org/wiki/Reed%E2%80%93Solomon_codes_for_coders // @see http://www.samiam.org/galois.html // GF256_exptable = new short[256]; GF256_logtable = new short[256]; GF256_logtable[0] = (1 - 256) & 0xff; GF256_exptable[0] = 1; for (int i = 1; i < 256; i++) { int exp = GF256_exptable[i - 1] * GF256_GENERATOR; if (exp >= 256) { exp ^= GF256_PRIME_POLYNOMIAL; } exp &= 0xff; GF256_exptable[i] = (short) exp; // Generator^255 = Generator^0 so we use the power modulo 255 // @see http://math.stackexchange.com/questions/76045/reed-solomon-polynomial-generator GF256_logtable[GF256_exptable[i]] = (short) (((short) i) % 255); } } /** * @param v The integer representing the polynomial in this * field. A bit i = 2<sup>n</sup> is set iff * x<sup>n</sup> is a term in the polynomial. */ public SSSSGF256Polynomial(int v) { value = (short) v; } /** * Implement addition on GF256, polynomial coefficients are * XORed * * @param b The SSSSGF256Polynomial to add * @throws RuntimeException in case of type mismatch */ public SSSSNumber add(SSSSNumber b) { if (b instanceof SSSSGF256Polynomial) { SSSSGF256Polynomial bPoly = (SSSSGF256Polynomial) b; return new SSSSGF256Polynomial(bPoly.value ^ value); } else { throw new RuntimeException("Type mismatch"); } } /** * Polynomial subtraction is really an addition since in * GF(2^n), a + b = a - b * * @param b SSSSGF256Polynomial to subtract * @throws RuntimeException in case of type mismatch */ public SSSSNumber sub(SSSSNumber b) { return add(b); } /** * Multiplication in GF256. * * @param b The second term. It must also be a GF256. * @throws RuntimeException If the second term is not of type * GF256. */ public SSSSNumber mul(SSSSNumber b) { if (b instanceof SSSSGF256Polynomial) { SSSSGF256Polynomial bPoly = (SSSSGF256Polynomial) b; // // Handle the special case of 0 // 0 * x = x * 0 = 0 // if ((bPoly.value == 0) || (value == 0)) { return zero(); } // // In the general case, multiplication is done using logarithms // @see http://www.logic.at/wiki/index.php/GF(256) // // log(a * b) = log(a) + log(b) // // Modulo is 255 because there are only 255 values in the log table int newPower = (log() + bPoly.log()) % 255; return new SSSSGF256Polynomial(GF256_exptable[newPower]); } else { throw new RuntimeException("Type mismatch."); } } /** * Division in GF256. * * @param b The second term. It must also be a GF256. * @throws RuntimeException If the second term is not of type * GF256 or if we divide by 0. */ public SSSSNumber div(SSSSNumber b) { if (b instanceof SSSSGF256Polynomial) { SSSSGF256Polynomial bPoly = (SSSSGF256Polynomial) b; // // Cannot divide by 0 // if (bPoly.value == 0) { throw new RuntimeException("Division by zero."); } // // 0 / x = 0 // if (value == 0) { return zero(); } // // Use the log rule: // @see http://www.logic.at/wiki/index.php/GF(256) // // log(a/b) = log(a) - log(b) // int newPower = (log() - bPoly.log()) % 255; if (newPower < 0) { newPower += 255; } return (SSSSNumber) new SSSSGF256Polynomial(GF256_exptable[newPower]); } else { throw new RuntimeException("Type mismatch"); } } /** * a + a = 0, so a = -a. * * @return The arithmetic inverse of the current value. */ public SSSSNumber neg() { return new SSSSGF256Polynomial(-value); } /** * @return The arithmetic identity. */ public SSSSNumber zero() { return new SSSSGF256Polynomial(0); } /** * @return The multiplicative identity. */ public SSSSNumber one() { return new SSSSGF256Polynomial(1); } public int intValue() { return (int) value; } public long longValue() { return (long) value; } public float floatValue() { return (float) value; } public double doubleValue() { return (double) value; } /** * @return The value n such that x<sup>n</n> is equivalent to * the current polynomial in this field. */ private int log() { if (0 == value) { throw new RuntimeException("Cannot take log of 0"); } return GF256_logtable[value]; } public String toString() { return Short.toString(value); } public int hashCode() { return value; } public boolean equals(Object o) { if (o instanceof SSSSGF256Polynomial) { SSSSGF256Polynomial oPoly = (SSSSGF256Polynomial) o; if (oPoly.value == value) { return true; } } return false; } @Override public SSSSGF256Polynomial clone() { return new SSSSGF256Polynomial(this.intValue()); } } /** * Implements a Shamir Secret Sharing Scheme. * * An input stream of bytes (the secret) is split by an encoder * in a number (n) of keys (byte streams) so that k of those keys * can be combined by a decoder to recreate the secret. */ public static final class SSSS { /** * Polynomial interpolator */ private SSSSPolynomialInterpolator interpolator; /** * Pseudo Random Number Generator */ private SecureRandom prng; /** * Create an encoder/decoder using the default * PRNG and the Lagrange polynomial interpolator. */ public SSSS() { interpolator = new SSSSLagrangePolynomialInterpolator(); prng = CryptoHelper.sr; } /** * Create an encoder using the Lagrange polynomial interpolator * and the specified SecureRandom implementation. * * @param rand The SecureRandom instance to use. */ public SSSS(SecureRandom rand) { interpolator = new SSSSLagrangePolynomialInterpolator(); prng = rand; } /** * Create an encoder using the specified SecureRandom implementation * and the specified SSSSPolynomialInterpolator. * * @param rand The SecureRandom instance to use. * @param pi The SSSSPolynomialInterpolator instance to use */ public SSSS(SecureRandom rand, SSSSPolynomialInterpolator pi) { interpolator = pi; prng = rand; } /** * Given k keys, recreate the secret. * If the keys are the wrong ones, the produced data will be random. * To further detect that situation, the secret should contain a * control mechanism to validate the decoded data. * * The decode method operates on streams so input and output can * be of any size. * * @param result The OutputStream to which the reconstructed secret will be written * @param keys Key InputStreams * @throws IOException in case of I/O errors * @throws SSSSDuplicateAbscissaException If the keys cover identical points, probably because they're the wrong ones */ public void decode(OutputStream result, InputStream[] keys) throws IOException, SSSSDuplicateAbscissaException { SSSSXY[] pGroup; do { pGroup = readPoints(keys); if (pGroup != null) { result.write(decodeByte(pGroup)); } } while (pGroup != null); } private int decodeByte(SSSSXY[] points) throws IOException, SSSSDuplicateAbscissaException { SSSSPolynomial fit = interpolator.interpolate(points); // // Decoded byte is P(0) where P is the polynomial which interpolates all points. // SSSSGF256Polynomial result = (SSSSGF256Polynomial) fit.f(new SSSSGF256Polynomial(0)); return result.intValue(); } /** * Read one point from each key * * @param keys Key InputStreams * @return An array of SSSSXY instances or null if EOF is reached on one key * @throws IOException */ private SSSSXY[] readPoints(InputStream[] keys) throws IOException { SSSSXY[] result = new SSSSXY[keys.length]; int xVal, yVal; // // Read one valid x/y pair per key // for (int i = 0; i < result.length; i++) { // // Read one x/y pair, skipping pairs whose x coordinate is 0 // do { xVal = keys[i].read(); if (xVal < 0) { return null; } yVal = keys[i].read(); if (yVal < 0) { return null; } } while (xVal == 0); // // X and Y coordinates are GF256 polynomials // result[i] = new SSSSXY(new SSSSGF256Polynomial(xVal), new SSSSGF256Polynomial(yVal)); } return result; } /** * Given a secret, write out the keys representing that secret. * * @param input The InputStream containing the secret * @param keys OutputStreams for each of the keys. * * @throws IOException If there's an I/O error reading or writing */ public void encode(InputStream input, OutputStream[] keys, int keysNeeded) throws IOException { // // If n < 2 or n > 255 or k < 2 we cannot split, ditto if k > n // if (keys.length < 2 || keys.length > 255 || keysNeeded < 2 || keysNeeded > keys.length) { throw new RuntimeException("Need to have at least 2 keys and at most 255 and more keys than number of needed keys."); } int v; do { // // Read input byte // v = input.read(); if (v >= 0) { encodeByte(v, keys, keysNeeded); } } while (v >= 0); } /** * Encode a byte * * @param byteVal Byte value to encode * @param keys OutputStreams for the keys * @param keysNeeded Number of keys needed to reconstruct the secret * @throws IOException if an I/O error occurs */ private void encodeByte(int byteVal, OutputStream[] keys, int keysNeeded) throws IOException { // // Array of boolean to keep track of x values already chosen // boolean[] picked = new boolean[256]; // // Select a random polynomial whose value at 0 is the byte value to encode // The degree of the polynomial is the number of keys needed to reconstruct the secret minus one // (Because N points determine uniquely a polynomial of degree N-1, i.e. two points a line, three a parabola...) // SSSSPolynomial rPoly = selectRandomPolynomial(keysNeeded - 1, new SSSSGF256Polynomial(byteVal)); // // Pick a distinct x value per key. // If 0 is chosen as x value, generate a random byte as the associated y coordinate // and pick another x value. // 0 cannot be chosen as P(0) is the encoded value, but we cannot ignore 0 otherwise the // keys would fail a randomness test (since they would not contain enough 0s) // for (int i = 0; i < keys.length; i++) { int xPick; do { // // Pick a random x value // xPick = getRandomByte(); // // If we picked 0, write it out with a random y value to // pass randomness tests // if (xPick == 0) { keys[i].write(xPick); keys[i].write(getRandomByte()); } // Do so while we picked 0 or an already picked x value } while ((xPick == 0) || (picked[xPick] == true)); // Marked the current x value as picked picked[xPick] = true; // Generate x/y SSSSGF256Polynomial xVal = new SSSSGF256Polynomial(xPick); SSSSGF256Polynomial yVal = (SSSSGF256Polynomial) rPoly.f(xVal); // Write x/y pair keys[i].write(xVal.intValue()); keys[i].write(yVal.intValue()); } } /** * Select a random polynomial with coefficients in GF256 whose degree and * value at the origin are fixed. * * @param degree Degree of the polynomial to generate * @param c0 Value of P(0) * @return */ private SSSSPolynomial selectRandomPolynomial(int degree, SSSSGF256Polynomial c0) { SSSSNumber[] coeff = new SSSSNumber[degree + 1]; coeff[0] = c0; for (int i = 1; i < degree; i++) { coeff[i] = new SSSSGF256Polynomial(getRandomByte()); } int cDegree; // // Make sure coefficient for 'degree' is non 0 // do { cDegree = getRandomByte(); } while (cDegree == 0); coeff[degree] = new SSSSGF256Polynomial(cDegree); return new SSSSPolynomial(coeff); } /** * Generate a single byte using the provided PRNG * * @return A random byte */ private int getRandomByte() { byte[] v = new byte[1]; prng.nextBytes(v); return (int) (v[0] & 0xff); } } /** * Split 'data' in N parts, K of which are needed to recover 'data'. * * K should be > N/2 so there are no two independent sets of secrets * in the wild which could be used to recover the initial data. * * @param data * @param n * @param k * @return */ public static List<byte[]> SSSSSplit(byte[] data, int n, int k) { // // If n < 2 or k < 2 we cannot split, ditto if k > n // if (n < 2 || n > 255 || k < 2 || k > n) { return null; } List<byte[]> secrets = new ArrayList<byte[]>(); SSSS ss = new SSSS(); ByteArrayInputStream bais = new ByteArrayInputStream(data); ByteArrayOutputStream[] baos = new ByteArrayOutputStream[n]; for (int i = 0; i < n; i++) { baos[i] = new ByteArrayOutputStream(); } try { ss.encode (bais, baos, k); } catch (IOException ioe) { return null; } // // Retrieve secrets from ByteArrayOutputStream instances // for (int i = 0; i < n; i++) { secrets.add(baos[i].toByteArray()); } return secrets; } /** * Recover data from a list of secrets which is a sublist of a list generated by 'split' * * @param secrets * @return */ public static byte[] SSSSRecover(Collection<byte[]> secrets) { SSSS ss = new SSSS(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ByteArrayInputStream[] bais = new ByteArrayInputStream[secrets.size()]; int i = 0; for (byte[] secret: secrets) { bais[i] = new ByteArrayInputStream(secret); i++; } try { ss.decode(baos, bais); } catch (SSSSDuplicateAbscissaException dpe) { return null; } catch (IOException ioe) { return null; } return baos.toByteArray(); } // // PGP Related code // public static List<PGPPublicKey> PGPPublicKeysFromKeyRing(String keyring) throws IOException { PGPObjectFactory factory = new PGPObjectFactory(PGPUtil.getDecoderStream(new ByteArrayInputStream(keyring.getBytes("UTF-8")))); List<PGPPublicKey> pubkeys = new ArrayList<PGPPublicKey>(); do { Object o = factory.nextObject(); if (null == o) { break; } if (o instanceof PGPKeyRing) { PGPKeyRing ring = (PGPKeyRing) o; Iterator<PGPPublicKey> iter = ring.getPublicKeys(); while(iter.hasNext()) { PGPPublicKey key = iter.next(); pubkeys.add(key); } } } while (true); return pubkeys; } public static byte[] encryptPGP(byte[] data, PGPPublicKey key, boolean armored, String name, int compressionAlgorithm, int encAlgorithm) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); OutputStream out = armored ? new ArmoredOutputStream(baos) : baos; BcPGPDataEncryptorBuilder dataEncryptor = new BcPGPDataEncryptorBuilder(encAlgorithm); dataEncryptor.setWithIntegrityPacket(true); dataEncryptor.setSecureRandom(CryptoHelper.getSecureRandom()); PGPEncryptedDataGenerator encryptedDataGenerator = new PGPEncryptedDataGenerator(dataEncryptor); encryptedDataGenerator.addMethod(new BcPublicKeyKeyEncryptionMethodGenerator(key)); try { OutputStream encout = encryptedDataGenerator.open(out, 1024); PGPCompressedDataGenerator pgpcdg = new PGPCompressedDataGenerator(compressionAlgorithm); OutputStream compout = pgpcdg.open(encout); PGPLiteralDataGenerator pgpldg = new PGPLiteralDataGenerator(false); OutputStream ldout = pgpldg.open(compout, PGPLiteralData.BINARY, name, data.length, PGPLiteralData.NOW); ldout.write(data); ldout.close(); compout.close(); encout.close(); out.close(); baos.close(); return baos.toByteArray(); } catch (PGPException pgpe) { throw new IOException(pgpe); } } }
Add javadoc to addIdentity method
src/main/java/com/geoxp/oss/CryptoHelper.java
Add javadoc to addIdentity method
<ide><path>rc/main/java/com/geoxp/oss/CryptoHelper.java <ide> /** <ide> * Add an identity to the agent <ide> * <del> */ <del> public Boolean addIdentity(byte[] keyblob, String comment) throws IOException { <add> * @param keyblob SSH key blob <add> * @param comment A comment to describe the identity <add> * @return true if the identity has been succesfully loaded <add> */ <add> public (Boolean) addIdentity(byte[] keyblob, String comment) throws IOException { <ide> ByteArrayOutputStream request = new ByteArrayOutputStream(); <ide> <ide> request.write(keyblob);
Java
agpl-3.0
8cf240a95675dad94cfa48350892c14edfe7d6f6
0
RestComm/jss7,RestComm/jss7
/* * UssdsimulatorView.java */ package org.mobicents.protocols.ss7.ussdsimulator; import java.util.logging.Level; import java.util.logging.Logger; import org.jdesktop.application.Action; import org.jdesktop.application.ResourceMap; import org.jdesktop.application.SingleFrameApplication; import org.jdesktop.application.FrameView; import org.jdesktop.application.TaskMonitor; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Properties; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import javax.swing.Timer; import javax.swing.Icon; import javax.swing.JDialog; import javax.swing.JFrame; import org.mobicents.protocols.ss7.map.MAPStackImpl; import org.mobicents.protocols.ss7.map.api.MAPApplicationContext; import org.mobicents.protocols.ss7.map.api.MAPDialog; import org.mobicents.protocols.ss7.map.api.MAPDialogListener; import org.mobicents.protocols.ss7.map.api.MAPException; import org.mobicents.protocols.ss7.map.api.MAPProvider; import org.mobicents.protocols.ss7.map.api.MAPServiceListener; import org.mobicents.protocols.ss7.map.api.MAPStack; import org.mobicents.protocols.ss7.map.api.dialog.AddressNature; import org.mobicents.protocols.ss7.map.api.dialog.AddressString; import org.mobicents.protocols.ss7.map.api.dialog.MAPAcceptInfo; import org.mobicents.protocols.ss7.map.api.dialog.MAPCloseInfo; import org.mobicents.protocols.ss7.map.api.dialog.MAPOpenInfo; import org.mobicents.protocols.ss7.map.api.dialog.MAPProviderAbortInfo; import org.mobicents.protocols.ss7.map.api.dialog.MAPRefuseInfo; import org.mobicents.protocols.ss7.map.api.dialog.MAPUserAbortInfo; import org.mobicents.protocols.ss7.map.api.dialog.NumberingPlan; import org.mobicents.protocols.ss7.map.api.service.supplementary.ProcessUnstructuredSSIndication; import org.mobicents.protocols.ss7.map.api.service.supplementary.USSDString; import org.mobicents.protocols.ss7.map.api.service.supplementary.UnstructuredSSIndication; import org.mobicents.protocols.ss7.sccp.impl.sctp.SccpSCTPProviderImpl; import org.mobicents.protocols.ss7.sccp.parameter.GlobalTitle; import org.mobicents.protocols.ss7.sccp.parameter.SccpAddress; import org.mobicents.protocols.ss7.stream.tcp.StartFailedException; import org.mobicents.protocols.ss7.ussdsimulator.mtp.USSDSimultorMtpProvider; /** * The application's main frame. */ public class UssdsimulatorView extends FrameView implements MAPDialogListener,MAPServiceListener{ public UssdsimulatorView(SingleFrameApplication app) { super(app); initComponents(); // status bar initialization - message timeout, idle icon and busy animation, etc ResourceMap resourceMap = getResourceMap(); int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout"); messageTimer = new Timer(messageTimeout, new ActionListener() { public void actionPerformed(ActionEvent e) { // statusMessageLabel.setText(""); } }); messageTimer.setRepeats(false); int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate"); for (int i = 0; i < busyIcons.length; i++) { busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]"); } busyIconTimer = new Timer(busyAnimationRate, new ActionListener() { public void actionPerformed(ActionEvent e) { busyIconIndex = (busyIconIndex + 1) % busyIcons.length; // statusAnimationLabel.setIcon(busyIcons[busyIconIndex]); } }); idleIcon = resourceMap.getIcon("StatusBar.idleIcon"); // statusAnimationLabel.setIcon(idleIcon); // progressBar.setVisible(false); // connecting action tasks to status bar via TaskMonitor TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext()); taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() { public void propertyChange(java.beans.PropertyChangeEvent evt) { String propertyName = evt.getPropertyName(); if ("started".equals(propertyName)) { if (!busyIconTimer.isRunning()) { // statusAnimationLabel.setIcon(busyIcons[0]); busyIconIndex = 0; busyIconTimer.start(); } // progressBar.setVisible(true); // progressBar.setIndeterminate(true); } else if ("done".equals(propertyName)) { busyIconTimer.stop(); // statusAnimationLabel.setIcon(idleIcon); // progressBar.setVisible(false); // progressBar.setValue(0); } else if ("message".equals(propertyName)) { String text = (String)(evt.getNewValue()); // statusMessageLabel.setText((text == null) ? "" : text); messageTimer.restart(); } else if ("progress".equals(propertyName)) { int value = (Integer)(evt.getNewValue()); //progressBar.setVisible(true); //progressBar.setIndeterminate(false); //progressBar.setValue(value); } } }); //stupid net beans, can do that from GUI _field_peer_ip.setText("127.0.0.1"); enableKeyPad(false); } @Action public void showAboutBox() { if (aboutBox == null) { JFrame mainFrame = UssdsimulatorApp.getApplication().getMainFrame(); aboutBox = new UssdsimulatorAboutBox(mainFrame); aboutBox.setLocationRelativeTo(mainFrame); } UssdsimulatorApp.getApplication().show(aboutBox); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { mainPanel = new javax.swing.JPanel(); cell_keypad_master_panel = new javax.swing.JPanel(); cell_keypad_call_buttons_panel = new javax.swing.JPanel(); _keypad_button_call = new javax.swing.JButton(); _keypad_button_break = new javax.swing.JButton(); _keypad_button_1 = new javax.swing.JButton(); _keypad_button_2 = new javax.swing.JButton(); _keypad_button_3 = new javax.swing.JButton(); _keypad_button_4 = new javax.swing.JButton(); _keypad_button_5 = new javax.swing.JButton(); _keypad_button_6 = new javax.swing.JButton(); _keypad_button_7 = new javax.swing.JButton(); _keypad_button_8 = new javax.swing.JButton(); _keypad_button_9 = new javax.swing.JButton(); _keypad_button_star = new javax.swing.JButton(); _keypad_button_0 = new javax.swing.JButton(); _keypad_button_hash = new javax.swing.JButton(); _field_result_display = new java.awt.TextArea(); _field_punch_display = new java.awt.TextArea(); jSeparator1 = new javax.swing.JSeparator(); jSeparator2 = new javax.swing.JSeparator(); _label_peer_IP = new javax.swing.JLabel(); _label_peer_port = new javax.swing.JLabel(); _field_peer_port = new javax.swing.JTextField(); _button_open_server = new javax.swing.JButton(); _button_close_server = new javax.swing.JButton(); _field_peer_ip = new javax.swing.JTextField(); menuBar = new javax.swing.JMenuBar(); javax.swing.JMenu fileMenu = new javax.swing.JMenu(); javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem(); javax.swing.JMenu helpMenu = new javax.swing.JMenu(); javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem(); mainPanel.setName("mainPanel"); // NOI18N org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(org.mobicents.protocols.ss7.ussdsimulator.UssdsimulatorApp.class).getContext().getResourceMap(UssdsimulatorView.class); cell_keypad_master_panel.setBorder(javax.swing.BorderFactory.createMatteBorder(1, 1, 1, 1, resourceMap.getColor("cell_keypad_master_panel.border.matteColor"))); // NOI18N cell_keypad_master_panel.setName("cell_keypad_master_panel"); // NOI18N cell_keypad_call_buttons_panel.setName("cell_keypad_call_buttons_panel"); // NOI18N _keypad_button_call.setText(resourceMap.getString("_keypad_button_call.text")); // NOI18N _keypad_button_call.setName("_keypad_button_call"); // NOI18N _keypad_button_call.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { _keypad_button_callActionPerformed(evt); } }); _keypad_button_break.setText(resourceMap.getString("_keypad_button_break.text")); // NOI18N _keypad_button_break.setName("_keypad_button_break"); // NOI18N _keypad_button_break.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { _keypad_button_breakActionPerformed(evt); } }); org.jdesktop.layout.GroupLayout cell_keypad_call_buttons_panelLayout = new org.jdesktop.layout.GroupLayout(cell_keypad_call_buttons_panel); cell_keypad_call_buttons_panel.setLayout(cell_keypad_call_buttons_panelLayout); cell_keypad_call_buttons_panelLayout.setHorizontalGroup( cell_keypad_call_buttons_panelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(cell_keypad_call_buttons_panelLayout.createSequentialGroup() .addContainerGap() .add(_keypad_button_call) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 13, Short.MAX_VALUE) .add(_keypad_button_break) .addContainerGap()) ); cell_keypad_call_buttons_panelLayout.setVerticalGroup( cell_keypad_call_buttons_panelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(org.jdesktop.layout.GroupLayout.TRAILING, cell_keypad_call_buttons_panelLayout.createSequentialGroup() .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .add(cell_keypad_call_buttons_panelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(_keypad_button_call) .add(_keypad_button_break)) .addContainerGap()) ); _keypad_button_1.setText(resourceMap.getString("_keypad_button_1.text")); // NOI18N _keypad_button_1.setName("_keypad_button_1"); // NOI18N _keypad_button_1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { _keypad_button_1ActionPerformed(evt); } }); _keypad_button_2.setText(resourceMap.getString("_keypad_button_2.text")); // NOI18N _keypad_button_2.setName("_keypad_button_2"); // NOI18N _keypad_button_2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { _keypad_button_2ActionPerformed(evt); } }); _keypad_button_3.setText(resourceMap.getString("_keypad_button_3.text")); // NOI18N _keypad_button_3.setName("_keypad_button_3"); // NOI18N _keypad_button_3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { _keypad_button_3ActionPerformed(evt); } }); _keypad_button_4.setText(resourceMap.getString("_keypad_button_4.text")); // NOI18N _keypad_button_4.setName("_keypad_button_4"); // NOI18N _keypad_button_4.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { _keypad_button_4ActionPerformed(evt); } }); _keypad_button_5.setText(resourceMap.getString("_keypad_button_5.text")); // NOI18N _keypad_button_5.setName("_keypad_button_5"); // NOI18N _keypad_button_5.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { _keypad_button_5ActionPerformed(evt); } }); _keypad_button_6.setText(resourceMap.getString("_keypad_button_6.text")); // NOI18N _keypad_button_6.setName("_keypad_button_6"); // NOI18N _keypad_button_6.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { _keypad_button_6ActionPerformed(evt); } }); _keypad_button_7.setText(resourceMap.getString("_keypad_button_7.text")); // NOI18N _keypad_button_7.setName("_keypad_button_7"); // NOI18N _keypad_button_7.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { _keypad_button_7ActionPerformed(evt); } }); _keypad_button_8.setText(resourceMap.getString("_keypad_button_8.text")); // NOI18N _keypad_button_8.setName("_keypad_button_8"); // NOI18N _keypad_button_8.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { _keypad_button_8ActionPerformed(evt); } }); _keypad_button_9.setText(resourceMap.getString("_keypad_button_9.text")); // NOI18N _keypad_button_9.setName("_keypad_button_9"); // NOI18N _keypad_button_9.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { _keypad_button_9ActionPerformed(evt); } }); _keypad_button_star.setText(resourceMap.getString("_keypad_button_star.text")); // NOI18N _keypad_button_star.setName("_keypad_button_star"); // NOI18N _keypad_button_star.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { _keypad_button_starActionPerformed(evt); } }); _keypad_button_0.setText(resourceMap.getString("_keypad_button_0.text")); // NOI18N _keypad_button_0.setName("_keypad_button_0"); // NOI18N _keypad_button_0.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { _keypad_button_0ActionPerformed(evt); } }); _keypad_button_hash.setText(resourceMap.getString("_keypad_button_hash.text")); // NOI18N _keypad_button_hash.setName("_keypad_button_hash"); // NOI18N _keypad_button_hash.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { _keypad_button_hashActionPerformed(evt); } }); org.jdesktop.layout.GroupLayout cell_keypad_master_panelLayout = new org.jdesktop.layout.GroupLayout(cell_keypad_master_panel); cell_keypad_master_panel.setLayout(cell_keypad_master_panelLayout); cell_keypad_master_panelLayout.setHorizontalGroup( cell_keypad_master_panelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(cell_keypad_master_panelLayout.createSequentialGroup() .addContainerGap() .add(cell_keypad_master_panelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false) .add(cell_keypad_master_panelLayout.createSequentialGroup() .add(_keypad_button_4) .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED) .add(_keypad_button_5) .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED) .add(_keypad_button_6, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .add(cell_keypad_master_panelLayout.createSequentialGroup() .add(_keypad_button_7) .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED) .add(_keypad_button_8) .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED) .add(_keypad_button_9, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .add(cell_keypad_master_panelLayout.createSequentialGroup() .add(_keypad_button_star) .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED) .add(_keypad_button_0) .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED) .add(_keypad_button_hash)) .add(cell_keypad_call_buttons_panel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .add(cell_keypad_master_panelLayout.createSequentialGroup() .add(_keypad_button_1) .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED) .add(_keypad_button_2) .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED) .add(_keypad_button_3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); cell_keypad_master_panelLayout.setVerticalGroup( cell_keypad_master_panelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(cell_keypad_master_panelLayout.createSequentialGroup() .addContainerGap() .add(cell_keypad_call_buttons_panel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(cell_keypad_master_panelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(_keypad_button_1) .add(_keypad_button_2) .add(_keypad_button_3)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(cell_keypad_master_panelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(_keypad_button_4) .add(_keypad_button_5) .add(_keypad_button_6)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(cell_keypad_master_panelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(_keypad_button_7) .add(_keypad_button_8) .add(_keypad_button_9)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(cell_keypad_master_panelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(_keypad_button_star) .add(_keypad_button_0) .add(_keypad_button_hash)) .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); _field_result_display.setEditable(false); _field_result_display.setName("_field_result_display"); // NOI18N _field_punch_display.setName("_field_punch_display"); // NOI18N jSeparator1.setName("jSeparator1"); // NOI18N jSeparator2.setName("jSeparator2"); // NOI18N _label_peer_IP.setText(resourceMap.getString("_label_peer_IP.text")); // NOI18N _label_peer_IP.setName("_label_peer_IP"); // NOI18N _label_peer_port.setText(resourceMap.getString("_label_peer_port.text")); // NOI18N _label_peer_port.setName("_label_peer_port"); // NOI18N _field_peer_port.setText(resourceMap.getString("_field_peer_port.text")); // NOI18N _field_peer_port.setName("_field_peer_port"); // NOI18N _button_open_server.setText(resourceMap.getString("_button_open_server.text")); // NOI18N _button_open_server.setName("_button_open_server"); // NOI18N _button_open_server.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { _button_open_serverActionPerformed(evt); } }); _button_close_server.setText(resourceMap.getString("_button_close_server.text")); // NOI18N _button_close_server.setEnabled(false); _button_close_server.setName("_button_close_server"); // NOI18N _button_close_server.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { _button_close_serverActionPerformed(evt); } }); _field_peer_ip.setText(resourceMap.getString("_field_peer_ip.text")); // NOI18N _field_peer_ip.setName("_field_peer_ip"); // NOI18N org.jdesktop.layout.GroupLayout mainPanelLayout = new org.jdesktop.layout.GroupLayout(mainPanel); mainPanel.setLayout(mainPanelLayout); mainPanelLayout.setHorizontalGroup( mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(mainPanelLayout.createSequentialGroup() .addContainerGap() .add(mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(mainPanelLayout.createSequentialGroup() .add(_field_result_display, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 415, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jSeparator1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(_field_punch_display, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 160, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(cell_keypad_master_panel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))) .add(mainPanelLayout.createSequentialGroup() .add(mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING, false) .add(org.jdesktop.layout.GroupLayout.LEADING, mainPanelLayout.createSequentialGroup() .add(_label_peer_port) .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED) .add(_field_peer_port)) .add(org.jdesktop.layout.GroupLayout.LEADING, mainPanelLayout.createSequentialGroup() .add(_label_peer_IP) .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED) .add(_field_peer_ip, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 122, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false) .add(_button_close_server, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .add(_button_open_server, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 125, Short.MAX_VALUE))) .add(jSeparator2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 602, Short.MAX_VALUE)) .add(103, 103, 103)) ); mainPanelLayout.setVerticalGroup( mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(mainPanelLayout.createSequentialGroup() .addContainerGap() .add(mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(mainPanelLayout.createSequentialGroup() .add(cell_keypad_master_panel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(mainPanelLayout.createSequentialGroup() .add(80, 80, 80) .add(jSeparator1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 10, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .add(mainPanelLayout.createSequentialGroup() .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(_field_punch_display, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 175, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))) .add(_field_result_display, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 370, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jSeparator2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 10, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(7, 7, 7) .add(mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING) .add(mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(_label_peer_IP) .add(_field_peer_ip, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .add(_button_open_server)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(_label_peer_port) .add(_field_peer_port, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .add(_button_close_server)) .addContainerGap(17, Short.MAX_VALUE)) ); menuBar.setName("menuBar"); // NOI18N fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N fileMenu.setName("fileMenu"); // NOI18N javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(org.mobicents.protocols.ss7.ussdsimulator.UssdsimulatorApp.class).getContext().getActionMap(UssdsimulatorView.class, this); exitMenuItem.setAction(actionMap.get("quit")); // NOI18N exitMenuItem.setName("exitMenuItem"); // NOI18N fileMenu.add(exitMenuItem); menuBar.add(fileMenu); helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N helpMenu.setName("helpMenu"); // NOI18N aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N aboutMenuItem.setName("aboutMenuItem"); // NOI18N helpMenu.add(aboutMenuItem); menuBar.add(helpMenu); setComponent(mainPanel); setMenuBar(menuBar); }// </editor-fold>//GEN-END:initComponents private void _button_open_serverActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event__button_open_serverActionPerformed this._button_close_server.setEnabled(true); this._button_open_server.setEnabled(false); this.initSS7Future = this._EXECUTOR.schedule(new Runnable() { public void run() { try { initSS7(); } catch (Exception ex) { Logger.getLogger(UssdsimulatorView.class.getName()).log(Level.SEVERE, null, ex); resetServer(); _field_punch_display.setText("Failed to initiate connection."); onlyKeyPadContent = false; } if(!mtpLayer.isLinkUp()) { resetServer(); _field_punch_display.setText("Failed to initiate connection."); onlyKeyPadContent = false; }else { _field_punch_display.setText("Connected to RA."); onlyKeyPadContent = false; //init some fake addressses //create some fake addresses. peer1Address = sccpProvider.getSccpParameterFactory().getSccpAddress(); GlobalTitle gt = sccpProvider.getSccpParameterFactory().getGlobalTitle100(); //dont set more, until statics are defined! gt.setDigits("5557779"); peer1Address.setGlobalTitle(gt); peer1Address.setGlobalTitleIndicator(4);//for GT 100 peer2Address = sccpProvider.getSccpParameterFactory().getSccpAddress(); gt = sccpProvider.getSccpParameterFactory().getGlobalTitle100(); //dont set more, until statics are defined! gt.setDigits("5888879"); peer2Address.setGlobalTitle(gt); peer2Address.setGlobalTitleIndicator(4);//for GT 100 //map/ussd part mapUssdAppContext = MAPApplicationContext.networkUnstructuredSsContextV2; //fake data again //FIXME: Amit add proper comments. orgiReference = mapStack.getMAPProvider().getMapServiceFactory() .createAddressString(AddressNature.international_number, NumberingPlan.ISDN, "31628968300"); destReference = mapStack.getMAPProvider().getMapServiceFactory() .createAddressString(AddressNature.international_number, NumberingPlan.land_mobile, "204208300008002"); //we are done, lets enable keypad enableKeyPad(true); } } },0,TimeUnit.MICROSECONDS); }//GEN-LAST:event__button_open_serverActionPerformed private void _button_close_serverActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event__button_close_serverActionPerformed this.resetServer(); }//GEN-LAST:event__button_close_serverActionPerformed private void _keypad_button_callActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event__keypad_button_callActionPerformed //here we make map call to peer :) MAPProvider mapProvider = this.mapStack.getMAPProvider(); //here, if no dialog exists its initial call :) String punchedText = this._field_punch_display.getText(); if (punchedText == null || punchedText.equals("")) { return; } USSDString ussdString = mapProvider.getMapServiceFactory().createUSSDString(punchedText); if (this.clientDialog == null) { try { this.clientDialog = mapProvider.createNewDialog(this.mapUssdAppContext, this.peer1Address, orgiReference, this.peer2Address, destReference); } catch (MAPException ex) { Logger.getLogger(UssdsimulatorView.class.getName()).log(Level.SEVERE, null, ex); this._field_punch_display.setText("Failed to create MAP dialog: " + ex); this.onlyKeyPadContent = false; return; } } try { AddressString msisdn = this.mapStack.getMAPProvider().getMapServiceFactory() .createAddressString(AddressNature.international_number, NumberingPlan.ISDN, "31628838002"); clientDialog.addProcessUnstructuredSSRequest((byte) 0x0F, ussdString,msisdn); clientDialog.send(); this._field_punch_display.setText(""); this._keypad_button_break.setEnabled(true); this._field_result_display.append("\n"); this._field_result_display.append(punchedText); } catch (MAPException ex) { Logger.getLogger(UssdsimulatorView.class.getName()).log(Level.SEVERE, null, ex); this._field_punch_display.setText("Failed to pass USSD request: " + ex); this.onlyKeyPadContent = false; return; } }//GEN-LAST:event__keypad_button_callActionPerformed private void _keypad_button_breakActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event__keypad_button_breakActionPerformed //this is set once call should end if(this.clientDialog!=null) { try { this.clientDialog.close(true); } catch (MAPException ex) { Logger.getLogger(UssdsimulatorView.class.getName()).log(Level.SEVERE, null, ex); this._field_punch_display.setText("Failed to close MAP Dialog: " + ex); this.onlyKeyPadContent = false; } this._keypad_button_break.setEnabled(false); } }//GEN-LAST:event__keypad_button_breakActionPerformed private void _keypad_button_1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event__keypad_button_1ActionPerformed this.keypadDigitPressed(evt); }//GEN-LAST:event__keypad_button_1ActionPerformed private void _keypad_button_2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event__keypad_button_2ActionPerformed this.keypadDigitPressed(evt); }//GEN-LAST:event__keypad_button_2ActionPerformed private void _keypad_button_3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event__keypad_button_3ActionPerformed this.keypadDigitPressed(evt); }//GEN-LAST:event__keypad_button_3ActionPerformed private void _keypad_button_4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event__keypad_button_4ActionPerformed this.keypadDigitPressed(evt); }//GEN-LAST:event__keypad_button_4ActionPerformed private void _keypad_button_5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event__keypad_button_5ActionPerformed this.keypadDigitPressed(evt); }//GEN-LAST:event__keypad_button_5ActionPerformed private void _keypad_button_6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event__keypad_button_6ActionPerformed this.keypadDigitPressed(evt); }//GEN-LAST:event__keypad_button_6ActionPerformed private void _keypad_button_7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event__keypad_button_7ActionPerformed this.keypadDigitPressed(evt); }//GEN-LAST:event__keypad_button_7ActionPerformed private void _keypad_button_8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event__keypad_button_8ActionPerformed this.keypadDigitPressed(evt); }//GEN-LAST:event__keypad_button_8ActionPerformed private void _keypad_button_9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event__keypad_button_9ActionPerformed this.keypadDigitPressed(evt); }//GEN-LAST:event__keypad_button_9ActionPerformed private void _keypad_button_starActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event__keypad_button_starActionPerformed this.keypadDigitPressed(evt); }//GEN-LAST:event__keypad_button_starActionPerformed private void _keypad_button_0ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event__keypad_button_0ActionPerformed this.keypadDigitPressed(evt); }//GEN-LAST:event__keypad_button_0ActionPerformed private void _keypad_button_hashActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event__keypad_button_hashActionPerformed this.keypadDigitPressed(evt); }//GEN-LAST:event__keypad_button_hashActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton _button_close_server; private javax.swing.JButton _button_open_server; private javax.swing.JTextField _field_peer_ip; private javax.swing.JTextField _field_peer_port; private java.awt.TextArea _field_punch_display; private java.awt.TextArea _field_result_display; private javax.swing.JButton _keypad_button_0; private javax.swing.JButton _keypad_button_1; private javax.swing.JButton _keypad_button_2; private javax.swing.JButton _keypad_button_3; private javax.swing.JButton _keypad_button_4; private javax.swing.JButton _keypad_button_5; private javax.swing.JButton _keypad_button_6; private javax.swing.JButton _keypad_button_7; private javax.swing.JButton _keypad_button_8; private javax.swing.JButton _keypad_button_9; private javax.swing.JButton _keypad_button_break; private javax.swing.JButton _keypad_button_call; private javax.swing.JButton _keypad_button_hash; private javax.swing.JButton _keypad_button_star; private javax.swing.JLabel _label_peer_IP; private javax.swing.JLabel _label_peer_port; private javax.swing.JPanel cell_keypad_call_buttons_panel; private javax.swing.JPanel cell_keypad_master_panel; private javax.swing.JSeparator jSeparator1; private javax.swing.JSeparator jSeparator2; private javax.swing.JPanel mainPanel; private javax.swing.JMenuBar menuBar; // End of variables declaration//GEN-END:variables private final Timer messageTimer; private final Timer busyIconTimer; private final Icon idleIcon; private final Icon[] busyIcons = new Icon[15]; private int busyIconIndex = 0; private JDialog aboutBox; private void enableKeyPad(boolean b) { this._keypad_button_1.setEnabled(b); this._keypad_button_2.setEnabled(b); this._keypad_button_3.setEnabled(b); this._keypad_button_4.setEnabled(b); this._keypad_button_5.setEnabled(b); this._keypad_button_6.setEnabled(b); this._keypad_button_7.setEnabled(b); this._keypad_button_8.setEnabled(b); this._keypad_button_9.setEnabled(b); this._keypad_button_0.setEnabled(b); this._keypad_button_star.setEnabled(b); this._keypad_button_hash.setEnabled(b); this._keypad_button_call.setEnabled(b); this._keypad_button_break.setEnabled(false); } private void keypadDigitPressed(ActionEvent evt) { if(!this.onlyKeyPadContent) { //clear this._field_punch_display.setText(""); this.onlyKeyPadContent = true; } this._field_punch_display.append(evt.getActionCommand()); } ///////////////// // async stuff // ///////////////// private ScheduledExecutorService _EXECUTOR = Executors.newScheduledThreadPool(2); private Future initSS7Future; ///////////////// // State stuff // ///////////////// private boolean onlyKeyPadContent = false; private SccpAddress peer1Address,peer2Address; private MAPApplicationContext mapUssdAppContext; private AddressString orgiReference,destReference; private MAPDialog clientDialog; ////////////// // SS7 part // ////////////// private Properties stackProperties; // private TCAPStack tcapStack; // private TCAPProvider tcapProvider; //this sucks... private SccpSCTPProviderImpl sccpProvider; private MAPStack mapStack; //this we have to create private USSDSimultorMtpProvider mtpLayer; //method to init stacks private void initSS7() throws Exception { this.stackProperties = new Properties(); //fake values; this.stackProperties.put("sccp.opc", "13150"); this.stackProperties.put("sccp.dpc", "31510"); this.stackProperties.put("sccp.sls", "0"); this.stackProperties.put("sccp.ssf", "3"); mtpLayer = new USSDSimultorMtpProvider(_field_peer_ip, _field_peer_port); mtpLayer.start(); long startTime = System.currentTimeMillis(); while(!mtpLayer.isLinkUp()) { Thread.currentThread().sleep(5000); if(startTime+20000<System.currentTimeMillis()) { break; } } if(!this.mtpLayer.isLinkUp()) { throw new StartFailedException(); } this.sccpProvider = new SccpSCTPProviderImpl(this.mtpLayer, stackProperties); this.mapStack = new MAPStackImpl(sccpProvider); this.mapStack.getMAPProvider().addMAPDialogListener(this); this.mapStack.getMAPProvider().addMAPServiceListener(this); //indicate linkup, since we mockup now, its done by hand. //this method is called by M3UserConnector! this.sccpProvider.linkUp(); } //FIXME: add proper dialog kill private void terminateSS7() { if(this.mtpLayer!=null) { this.mtpLayer.stop(); //this.mtpLayer = null; } } private void resetServer() { if(this.initSS7Future!=null) { this.initSS7Future.cancel(false); this.initSS7Future = null; } terminateSS7(); _button_close_server.setEnabled(false); _button_open_server.setEnabled(true); this.enableKeyPad(false); } public void onMAPAcceptInfo(MAPAcceptInfo arg0) { //throw new UnsupportedOperationException("Not supported yet."); } public void onMAPOpenInfo(MAPOpenInfo arg0) { //throw new UnsupportedOperationException("Not supported yet."); } public void onMAPCloseInfo(MAPCloseInfo close) { this._field_punch_display.setText("Dialog Closed"); this.onlyKeyPadContent = false; this.clientDialog = null; this._keypad_button_break.setEnabled(false); } public void onMAPProviderAbortInfo(MAPProviderAbortInfo arg0) { this._field_punch_display.setText("Dialog Aborted: "+arg0); this.onlyKeyPadContent = false; this.clientDialog = null; this._keypad_button_break.setEnabled(false); } public void onMAPRefuseInfo(MAPRefuseInfo arg0) { this._field_punch_display.setText("Dialog Refused: "+arg0); this.onlyKeyPadContent = false; this.clientDialog = null; this._keypad_button_break.setEnabled(false); } public void onMAPUserAbortInfo(MAPUserAbortInfo arg0) { this._field_punch_display.setText("Dialog UAborted: "+arg0); this.onlyKeyPadContent = false; this.clientDialog = null; this._keypad_button_break.setEnabled(false); } public void onProcessUnstructuredSSIndication(ProcessUnstructuredSSIndication arg0) { //we dont server requests. throw new UnsupportedOperationException("Not supported yet."); } public void onUnstructuredSSIndication(UnstructuredSSIndication ussdInditaion) { //here RA responds. USSDString string =ussdInditaion.getUSSDString(); this._field_result_display.setText(string.getString()); } }
tools/ussd-simulator/src/main/java/org/mobicents/protocols/ss7/ussdsimulator/UssdsimulatorView.java
/* * UssdsimulatorView.java */ package org.mobicents.protocols.ss7.ussdsimulator; import java.util.logging.Level; import java.util.logging.Logger; import org.jdesktop.application.Action; import org.jdesktop.application.ResourceMap; import org.jdesktop.application.SingleFrameApplication; import org.jdesktop.application.FrameView; import org.jdesktop.application.TaskMonitor; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Properties; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import javax.swing.Timer; import javax.swing.Icon; import javax.swing.JDialog; import javax.swing.JFrame; import org.mobicents.protocols.ss7.map.MAPStackImpl; import org.mobicents.protocols.ss7.map.api.MAPApplicationContext; import org.mobicents.protocols.ss7.map.api.MAPDialog; import org.mobicents.protocols.ss7.map.api.MAPDialogListener; import org.mobicents.protocols.ss7.map.api.MAPException; import org.mobicents.protocols.ss7.map.api.MAPProvider; import org.mobicents.protocols.ss7.map.api.MAPServiceListener; import org.mobicents.protocols.ss7.map.api.MAPStack; import org.mobicents.protocols.ss7.map.api.dialog.AddressNature; import org.mobicents.protocols.ss7.map.api.dialog.AddressString; import org.mobicents.protocols.ss7.map.api.dialog.MAPAcceptInfo; import org.mobicents.protocols.ss7.map.api.dialog.MAPCloseInfo; import org.mobicents.protocols.ss7.map.api.dialog.MAPOpenInfo; import org.mobicents.protocols.ss7.map.api.dialog.MAPProviderAbortInfo; import org.mobicents.protocols.ss7.map.api.dialog.MAPRefuseInfo; import org.mobicents.protocols.ss7.map.api.dialog.MAPUserAbortInfo; import org.mobicents.protocols.ss7.map.api.dialog.NumberingPlan; import org.mobicents.protocols.ss7.map.api.service.supplementary.ProcessUnstructuredSSIndication; import org.mobicents.protocols.ss7.map.api.service.supplementary.USSDString; import org.mobicents.protocols.ss7.map.api.service.supplementary.UnstructuredSSIndication; import org.mobicents.protocols.ss7.sccp.impl.sctp.SccpSCTPProviderImpl; import org.mobicents.protocols.ss7.sccp.parameter.GlobalTitle; import org.mobicents.protocols.ss7.sccp.parameter.SccpAddress; import org.mobicents.protocols.ss7.stream.tcp.StartFailedException; import org.mobicents.protocols.ss7.ussdsimulator.mtp.USSDSimultorMtpProvider; /** * The application's main frame. */ public class UssdsimulatorView extends FrameView implements MAPDialogListener,MAPServiceListener{ public UssdsimulatorView(SingleFrameApplication app) { super(app); initComponents(); // status bar initialization - message timeout, idle icon and busy animation, etc ResourceMap resourceMap = getResourceMap(); int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout"); messageTimer = new Timer(messageTimeout, new ActionListener() { public void actionPerformed(ActionEvent e) { // statusMessageLabel.setText(""); } }); messageTimer.setRepeats(false); int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate"); for (int i = 0; i < busyIcons.length; i++) { busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]"); } busyIconTimer = new Timer(busyAnimationRate, new ActionListener() { public void actionPerformed(ActionEvent e) { busyIconIndex = (busyIconIndex + 1) % busyIcons.length; // statusAnimationLabel.setIcon(busyIcons[busyIconIndex]); } }); idleIcon = resourceMap.getIcon("StatusBar.idleIcon"); // statusAnimationLabel.setIcon(idleIcon); // progressBar.setVisible(false); // connecting action tasks to status bar via TaskMonitor TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext()); taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() { public void propertyChange(java.beans.PropertyChangeEvent evt) { String propertyName = evt.getPropertyName(); if ("started".equals(propertyName)) { if (!busyIconTimer.isRunning()) { // statusAnimationLabel.setIcon(busyIcons[0]); busyIconIndex = 0; busyIconTimer.start(); } // progressBar.setVisible(true); // progressBar.setIndeterminate(true); } else if ("done".equals(propertyName)) { busyIconTimer.stop(); // statusAnimationLabel.setIcon(idleIcon); // progressBar.setVisible(false); // progressBar.setValue(0); } else if ("message".equals(propertyName)) { String text = (String)(evt.getNewValue()); // statusMessageLabel.setText((text == null) ? "" : text); messageTimer.restart(); } else if ("progress".equals(propertyName)) { int value = (Integer)(evt.getNewValue()); //progressBar.setVisible(true); //progressBar.setIndeterminate(false); //progressBar.setValue(value); } } }); //stupid net beans, can do that from GUI _field_peer_ip.setText("127.0.0.1"); enableKeyPad(false); } @Action public void showAboutBox() { if (aboutBox == null) { JFrame mainFrame = UssdsimulatorApp.getApplication().getMainFrame(); aboutBox = new UssdsimulatorAboutBox(mainFrame); aboutBox.setLocationRelativeTo(mainFrame); } UssdsimulatorApp.getApplication().show(aboutBox); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { mainPanel = new javax.swing.JPanel(); cell_keypad_master_panel = new javax.swing.JPanel(); cell_keypad_call_buttons_panel = new javax.swing.JPanel(); _keypad_button_call = new javax.swing.JButton(); _keypad_button_break = new javax.swing.JButton(); _keypad_button_1 = new javax.swing.JButton(); _keypad_button_2 = new javax.swing.JButton(); _keypad_button_3 = new javax.swing.JButton(); _keypad_button_4 = new javax.swing.JButton(); _keypad_button_5 = new javax.swing.JButton(); _keypad_button_6 = new javax.swing.JButton(); _keypad_button_7 = new javax.swing.JButton(); _keypad_button_8 = new javax.swing.JButton(); _keypad_button_9 = new javax.swing.JButton(); _keypad_button_star = new javax.swing.JButton(); _keypad_button_0 = new javax.swing.JButton(); _keypad_button_hash = new javax.swing.JButton(); _field_result_display = new java.awt.TextArea(); _field_punch_display = new java.awt.TextArea(); jSeparator1 = new javax.swing.JSeparator(); jSeparator2 = new javax.swing.JSeparator(); _label_peer_IP = new javax.swing.JLabel(); _label_peer_port = new javax.swing.JLabel(); _field_peer_port = new javax.swing.JTextField(); _button_open_server = new javax.swing.JButton(); _button_close_server = new javax.swing.JButton(); _field_peer_ip = new javax.swing.JTextField(); menuBar = new javax.swing.JMenuBar(); javax.swing.JMenu fileMenu = new javax.swing.JMenu(); javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem(); javax.swing.JMenu helpMenu = new javax.swing.JMenu(); javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem(); mainPanel.setName("mainPanel"); // NOI18N org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(org.mobicents.protocols.ss7.ussdsimulator.UssdsimulatorApp.class).getContext().getResourceMap(UssdsimulatorView.class); cell_keypad_master_panel.setBorder(javax.swing.BorderFactory.createMatteBorder(1, 1, 1, 1, resourceMap.getColor("cell_keypad_master_panel.border.matteColor"))); // NOI18N cell_keypad_master_panel.setName("cell_keypad_master_panel"); // NOI18N cell_keypad_call_buttons_panel.setName("cell_keypad_call_buttons_panel"); // NOI18N _keypad_button_call.setText(resourceMap.getString("_keypad_button_call.text")); // NOI18N _keypad_button_call.setName("_keypad_button_call"); // NOI18N _keypad_button_call.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { _keypad_button_callActionPerformed(evt); } }); _keypad_button_break.setText(resourceMap.getString("_keypad_button_break.text")); // NOI18N _keypad_button_break.setName("_keypad_button_break"); // NOI18N _keypad_button_break.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { _keypad_button_breakActionPerformed(evt); } }); org.jdesktop.layout.GroupLayout cell_keypad_call_buttons_panelLayout = new org.jdesktop.layout.GroupLayout(cell_keypad_call_buttons_panel); cell_keypad_call_buttons_panel.setLayout(cell_keypad_call_buttons_panelLayout); cell_keypad_call_buttons_panelLayout.setHorizontalGroup( cell_keypad_call_buttons_panelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(cell_keypad_call_buttons_panelLayout.createSequentialGroup() .addContainerGap() .add(_keypad_button_call) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 13, Short.MAX_VALUE) .add(_keypad_button_break) .addContainerGap()) ); cell_keypad_call_buttons_panelLayout.setVerticalGroup( cell_keypad_call_buttons_panelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(org.jdesktop.layout.GroupLayout.TRAILING, cell_keypad_call_buttons_panelLayout.createSequentialGroup() .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .add(cell_keypad_call_buttons_panelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(_keypad_button_call) .add(_keypad_button_break)) .addContainerGap()) ); _keypad_button_1.setText(resourceMap.getString("_keypad_button_1.text")); // NOI18N _keypad_button_1.setName("_keypad_button_1"); // NOI18N _keypad_button_1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { _keypad_button_1ActionPerformed(evt); } }); _keypad_button_2.setText(resourceMap.getString("_keypad_button_2.text")); // NOI18N _keypad_button_2.setName("_keypad_button_2"); // NOI18N _keypad_button_2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { _keypad_button_2ActionPerformed(evt); } }); _keypad_button_3.setText(resourceMap.getString("_keypad_button_3.text")); // NOI18N _keypad_button_3.setName("_keypad_button_3"); // NOI18N _keypad_button_3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { _keypad_button_3ActionPerformed(evt); } }); _keypad_button_4.setText(resourceMap.getString("_keypad_button_4.text")); // NOI18N _keypad_button_4.setName("_keypad_button_4"); // NOI18N _keypad_button_4.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { _keypad_button_4ActionPerformed(evt); } }); _keypad_button_5.setText(resourceMap.getString("_keypad_button_5.text")); // NOI18N _keypad_button_5.setName("_keypad_button_5"); // NOI18N _keypad_button_5.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { _keypad_button_5ActionPerformed(evt); } }); _keypad_button_6.setText(resourceMap.getString("_keypad_button_6.text")); // NOI18N _keypad_button_6.setName("_keypad_button_6"); // NOI18N _keypad_button_6.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { _keypad_button_6ActionPerformed(evt); } }); _keypad_button_7.setText(resourceMap.getString("_keypad_button_7.text")); // NOI18N _keypad_button_7.setName("_keypad_button_7"); // NOI18N _keypad_button_7.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { _keypad_button_7ActionPerformed(evt); } }); _keypad_button_8.setText(resourceMap.getString("_keypad_button_8.text")); // NOI18N _keypad_button_8.setName("_keypad_button_8"); // NOI18N _keypad_button_8.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { _keypad_button_8ActionPerformed(evt); } }); _keypad_button_9.setText(resourceMap.getString("_keypad_button_9.text")); // NOI18N _keypad_button_9.setName("_keypad_button_9"); // NOI18N _keypad_button_9.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { _keypad_button_9ActionPerformed(evt); } }); _keypad_button_star.setText(resourceMap.getString("_keypad_button_star.text")); // NOI18N _keypad_button_star.setName("_keypad_button_star"); // NOI18N _keypad_button_star.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { _keypad_button_starActionPerformed(evt); } }); _keypad_button_0.setText(resourceMap.getString("_keypad_button_0.text")); // NOI18N _keypad_button_0.setName("_keypad_button_0"); // NOI18N _keypad_button_0.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { _keypad_button_0ActionPerformed(evt); } }); _keypad_button_hash.setText(resourceMap.getString("_keypad_button_hash.text")); // NOI18N _keypad_button_hash.setName("_keypad_button_hash"); // NOI18N _keypad_button_hash.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { _keypad_button_hashActionPerformed(evt); } }); org.jdesktop.layout.GroupLayout cell_keypad_master_panelLayout = new org.jdesktop.layout.GroupLayout(cell_keypad_master_panel); cell_keypad_master_panel.setLayout(cell_keypad_master_panelLayout); cell_keypad_master_panelLayout.setHorizontalGroup( cell_keypad_master_panelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(cell_keypad_master_panelLayout.createSequentialGroup() .addContainerGap() .add(cell_keypad_master_panelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false) .add(cell_keypad_master_panelLayout.createSequentialGroup() .add(_keypad_button_4) .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED) .add(_keypad_button_5) .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED) .add(_keypad_button_6, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .add(cell_keypad_master_panelLayout.createSequentialGroup() .add(_keypad_button_7) .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED) .add(_keypad_button_8) .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED) .add(_keypad_button_9, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .add(cell_keypad_master_panelLayout.createSequentialGroup() .add(_keypad_button_star) .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED) .add(_keypad_button_0) .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED) .add(_keypad_button_hash)) .add(cell_keypad_call_buttons_panel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .add(cell_keypad_master_panelLayout.createSequentialGroup() .add(_keypad_button_1) .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED) .add(_keypad_button_2) .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED) .add(_keypad_button_3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); cell_keypad_master_panelLayout.setVerticalGroup( cell_keypad_master_panelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(cell_keypad_master_panelLayout.createSequentialGroup() .addContainerGap() .add(cell_keypad_call_buttons_panel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(cell_keypad_master_panelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(_keypad_button_1) .add(_keypad_button_2) .add(_keypad_button_3)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(cell_keypad_master_panelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(_keypad_button_4) .add(_keypad_button_5) .add(_keypad_button_6)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(cell_keypad_master_panelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(_keypad_button_7) .add(_keypad_button_8) .add(_keypad_button_9)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(cell_keypad_master_panelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(_keypad_button_star) .add(_keypad_button_0) .add(_keypad_button_hash)) .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); _field_result_display.setEditable(false); _field_result_display.setName("_field_result_display"); // NOI18N _field_punch_display.setName("_field_punch_display"); // NOI18N jSeparator1.setName("jSeparator1"); // NOI18N jSeparator2.setName("jSeparator2"); // NOI18N _label_peer_IP.setText(resourceMap.getString("_label_peer_IP.text")); // NOI18N _label_peer_IP.setName("_label_peer_IP"); // NOI18N _label_peer_port.setText(resourceMap.getString("_label_peer_port.text")); // NOI18N _label_peer_port.setName("_label_peer_port"); // NOI18N _field_peer_port.setText(resourceMap.getString("_field_peer_port.text")); // NOI18N _field_peer_port.setName("_field_peer_port"); // NOI18N _button_open_server.setText(resourceMap.getString("_button_open_server.text")); // NOI18N _button_open_server.setName("_button_open_server"); // NOI18N _button_open_server.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { _button_open_serverActionPerformed(evt); } }); _button_close_server.setText(resourceMap.getString("_button_close_server.text")); // NOI18N _button_close_server.setEnabled(false); _button_close_server.setName("_button_close_server"); // NOI18N _button_close_server.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { _button_close_serverActionPerformed(evt); } }); _field_peer_ip.setText(resourceMap.getString("_field_peer_ip.text")); // NOI18N _field_peer_ip.setName("_field_peer_ip"); // NOI18N org.jdesktop.layout.GroupLayout mainPanelLayout = new org.jdesktop.layout.GroupLayout(mainPanel); mainPanel.setLayout(mainPanelLayout); mainPanelLayout.setHorizontalGroup( mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(mainPanelLayout.createSequentialGroup() .addContainerGap() .add(mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(mainPanelLayout.createSequentialGroup() .add(_field_result_display, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 415, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jSeparator1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(_field_punch_display, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 160, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(cell_keypad_master_panel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))) .add(mainPanelLayout.createSequentialGroup() .add(mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING, false) .add(org.jdesktop.layout.GroupLayout.LEADING, mainPanelLayout.createSequentialGroup() .add(_label_peer_port) .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED) .add(_field_peer_port)) .add(org.jdesktop.layout.GroupLayout.LEADING, mainPanelLayout.createSequentialGroup() .add(_label_peer_IP) .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED) .add(_field_peer_ip, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 122, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false) .add(_button_close_server, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .add(_button_open_server, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 125, Short.MAX_VALUE))) .add(jSeparator2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 602, Short.MAX_VALUE)) .add(103, 103, 103)) ); mainPanelLayout.setVerticalGroup( mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(mainPanelLayout.createSequentialGroup() .addContainerGap() .add(mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(mainPanelLayout.createSequentialGroup() .add(cell_keypad_master_panel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(mainPanelLayout.createSequentialGroup() .add(80, 80, 80) .add(jSeparator1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 10, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .add(mainPanelLayout.createSequentialGroup() .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(_field_punch_display, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 175, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))) .add(_field_result_display, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 370, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jSeparator2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 10, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(7, 7, 7) .add(mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING) .add(mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(_label_peer_IP) .add(_field_peer_ip, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .add(_button_open_server)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(_label_peer_port) .add(_field_peer_port, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .add(_button_close_server)) .addContainerGap(17, Short.MAX_VALUE)) ); menuBar.setName("menuBar"); // NOI18N fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N fileMenu.setName("fileMenu"); // NOI18N javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(org.mobicents.protocols.ss7.ussdsimulator.UssdsimulatorApp.class).getContext().getActionMap(UssdsimulatorView.class, this); exitMenuItem.setAction(actionMap.get("quit")); // NOI18N exitMenuItem.setName("exitMenuItem"); // NOI18N fileMenu.add(exitMenuItem); menuBar.add(fileMenu); helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N helpMenu.setName("helpMenu"); // NOI18N aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N aboutMenuItem.setName("aboutMenuItem"); // NOI18N helpMenu.add(aboutMenuItem); menuBar.add(helpMenu); setComponent(mainPanel); setMenuBar(menuBar); }// </editor-fold>//GEN-END:initComponents private void _button_open_serverActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event__button_open_serverActionPerformed this._button_close_server.setEnabled(true); this._button_open_server.setEnabled(false); this.initSS7Future = this._EXECUTOR.schedule(new Runnable() { public void run() { try { initSS7(); } catch (Exception ex) { Logger.getLogger(UssdsimulatorView.class.getName()).log(Level.SEVERE, null, ex); resetServer(); _field_punch_display.setText("Failed to initiate connection."); onlyKeyPadContent = false; } if(!mtpLayer.isLinkUp()) { resetServer(); _field_punch_display.setText("Failed to initiate connection."); onlyKeyPadContent = false; }else { _field_punch_display.setText("Connected to RA."); onlyKeyPadContent = false; //init some fake addressses //create some fake addresses. peer1Address = sccpProvider.getSccpParameterFactory().getSccpAddress(); GlobalTitle gt = sccpProvider.getSccpParameterFactory().getGlobalTitle100(); //dont set more, until statics are defined! gt.setDigits("5557779"); peer1Address.setGlobalTitle(gt); peer2Address = sccpProvider.getSccpParameterFactory().getSccpAddress(); gt = sccpProvider.getSccpParameterFactory().getGlobalTitle100(); //dont set more, until statics are defined! gt.setDigits("5888879"); peer2Address.setGlobalTitle(gt); //map/ussd part mapUssdAppContext = MAPApplicationContext.networkUnstructuredSsContextV2; //fake data again //FIXME: Amit add proper comments. orgiReference = mapStack.getMAPProvider().getMapServiceFactory() .createAddressString(AddressNature.international_number, NumberingPlan.ISDN, "31628968300"); destReference = mapStack.getMAPProvider().getMapServiceFactory() .createAddressString(AddressNature.international_number, NumberingPlan.land_mobile, "204208300008002"); //we are done, lets enable keypad enableKeyPad(true); } } },0,TimeUnit.MICROSECONDS); }//GEN-LAST:event__button_open_serverActionPerformed private void _button_close_serverActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event__button_close_serverActionPerformed this.resetServer(); }//GEN-LAST:event__button_close_serverActionPerformed private void _keypad_button_callActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event__keypad_button_callActionPerformed //here we make map call to peer :) MAPProvider mapProvider = this.mapStack.getMAPProvider(); //here, if no dialog exists its initial call :) String punchedText = this._field_punch_display.getText(); if (punchedText == null || punchedText.equals("")) { return; } USSDString ussdString = mapProvider.getMapServiceFactory().createUSSDString(punchedText); if (this.clientDialog == null) { try { this.clientDialog = mapProvider.createNewDialog(this.mapUssdAppContext, this.peer1Address, orgiReference, this.peer2Address, destReference); } catch (MAPException ex) { Logger.getLogger(UssdsimulatorView.class.getName()).log(Level.SEVERE, null, ex); this._field_punch_display.setText("Failed to create MAP dialog: " + ex); this.onlyKeyPadContent = false; return; } } try { clientDialog.addProcessUnstructuredSSRequest((byte) 0x0F, ussdString); clientDialog.send(); this._field_punch_display.setText(""); this._keypad_button_break.setEnabled(true); this._field_result_display.append("\n"); this._field_result_display.append(punchedText); } catch (MAPException ex) { Logger.getLogger(UssdsimulatorView.class.getName()).log(Level.SEVERE, null, ex); this._field_punch_display.setText("Failed to pass USSD request: " + ex); this.onlyKeyPadContent = false; return; } }//GEN-LAST:event__keypad_button_callActionPerformed private void _keypad_button_breakActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event__keypad_button_breakActionPerformed //this is set once call should end if(this.clientDialog!=null) { try { this.clientDialog.close(true); } catch (MAPException ex) { Logger.getLogger(UssdsimulatorView.class.getName()).log(Level.SEVERE, null, ex); this._field_punch_display.setText("Failed to close MAP Dialog: " + ex); this.onlyKeyPadContent = false; } this._keypad_button_break.setEnabled(false); } }//GEN-LAST:event__keypad_button_breakActionPerformed private void _keypad_button_1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event__keypad_button_1ActionPerformed this.keypadDigitPressed(evt); }//GEN-LAST:event__keypad_button_1ActionPerformed private void _keypad_button_2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event__keypad_button_2ActionPerformed this.keypadDigitPressed(evt); }//GEN-LAST:event__keypad_button_2ActionPerformed private void _keypad_button_3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event__keypad_button_3ActionPerformed this.keypadDigitPressed(evt); }//GEN-LAST:event__keypad_button_3ActionPerformed private void _keypad_button_4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event__keypad_button_4ActionPerformed this.keypadDigitPressed(evt); }//GEN-LAST:event__keypad_button_4ActionPerformed private void _keypad_button_5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event__keypad_button_5ActionPerformed this.keypadDigitPressed(evt); }//GEN-LAST:event__keypad_button_5ActionPerformed private void _keypad_button_6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event__keypad_button_6ActionPerformed this.keypadDigitPressed(evt); }//GEN-LAST:event__keypad_button_6ActionPerformed private void _keypad_button_7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event__keypad_button_7ActionPerformed this.keypadDigitPressed(evt); }//GEN-LAST:event__keypad_button_7ActionPerformed private void _keypad_button_8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event__keypad_button_8ActionPerformed this.keypadDigitPressed(evt); }//GEN-LAST:event__keypad_button_8ActionPerformed private void _keypad_button_9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event__keypad_button_9ActionPerformed this.keypadDigitPressed(evt); }//GEN-LAST:event__keypad_button_9ActionPerformed private void _keypad_button_starActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event__keypad_button_starActionPerformed this.keypadDigitPressed(evt); }//GEN-LAST:event__keypad_button_starActionPerformed private void _keypad_button_0ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event__keypad_button_0ActionPerformed this.keypadDigitPressed(evt); }//GEN-LAST:event__keypad_button_0ActionPerformed private void _keypad_button_hashActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event__keypad_button_hashActionPerformed this.keypadDigitPressed(evt); }//GEN-LAST:event__keypad_button_hashActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton _button_close_server; private javax.swing.JButton _button_open_server; private javax.swing.JTextField _field_peer_ip; private javax.swing.JTextField _field_peer_port; private java.awt.TextArea _field_punch_display; private java.awt.TextArea _field_result_display; private javax.swing.JButton _keypad_button_0; private javax.swing.JButton _keypad_button_1; private javax.swing.JButton _keypad_button_2; private javax.swing.JButton _keypad_button_3; private javax.swing.JButton _keypad_button_4; private javax.swing.JButton _keypad_button_5; private javax.swing.JButton _keypad_button_6; private javax.swing.JButton _keypad_button_7; private javax.swing.JButton _keypad_button_8; private javax.swing.JButton _keypad_button_9; private javax.swing.JButton _keypad_button_break; private javax.swing.JButton _keypad_button_call; private javax.swing.JButton _keypad_button_hash; private javax.swing.JButton _keypad_button_star; private javax.swing.JLabel _label_peer_IP; private javax.swing.JLabel _label_peer_port; private javax.swing.JPanel cell_keypad_call_buttons_panel; private javax.swing.JPanel cell_keypad_master_panel; private javax.swing.JSeparator jSeparator1; private javax.swing.JSeparator jSeparator2; private javax.swing.JPanel mainPanel; private javax.swing.JMenuBar menuBar; // End of variables declaration//GEN-END:variables private final Timer messageTimer; private final Timer busyIconTimer; private final Icon idleIcon; private final Icon[] busyIcons = new Icon[15]; private int busyIconIndex = 0; private JDialog aboutBox; private void enableKeyPad(boolean b) { this._keypad_button_1.setEnabled(b); this._keypad_button_2.setEnabled(b); this._keypad_button_3.setEnabled(b); this._keypad_button_4.setEnabled(b); this._keypad_button_5.setEnabled(b); this._keypad_button_6.setEnabled(b); this._keypad_button_7.setEnabled(b); this._keypad_button_8.setEnabled(b); this._keypad_button_9.setEnabled(b); this._keypad_button_0.setEnabled(b); this._keypad_button_star.setEnabled(b); this._keypad_button_hash.setEnabled(b); this._keypad_button_call.setEnabled(b); this._keypad_button_break.setEnabled(false); } private void keypadDigitPressed(ActionEvent evt) { if(!this.onlyKeyPadContent) { //clear this._field_punch_display.setText(""); this.onlyKeyPadContent = true; } this._field_punch_display.append(evt.getActionCommand()); } ///////////////// // async stuff // ///////////////// private ScheduledExecutorService _EXECUTOR = Executors.newScheduledThreadPool(2); private Future initSS7Future; ///////////////// // State stuff // ///////////////// private boolean onlyKeyPadContent = false; private SccpAddress peer1Address,peer2Address; private MAPApplicationContext mapUssdAppContext; private AddressString orgiReference,destReference; private MAPDialog clientDialog; ////////////// // SS7 part // ////////////// private Properties stackProperties; // private TCAPStack tcapStack; // private TCAPProvider tcapProvider; //this sucks... private SccpSCTPProviderImpl sccpProvider; private MAPStack mapStack; //this we have to create private USSDSimultorMtpProvider mtpLayer; //method to init stacks private void initSS7() throws Exception { this.stackProperties = new Properties(); //fake values; this.stackProperties.put("sccp.opc", "13150"); this.stackProperties.put("sccp.dpc", "31510"); this.stackProperties.put("sccp.sls", "0"); this.stackProperties.put("sccp.ssf", "3"); mtpLayer = new USSDSimultorMtpProvider(_field_peer_ip, _field_peer_port); mtpLayer.start(); long startTime = System.currentTimeMillis(); while(!mtpLayer.isLinkUp()) { Thread.currentThread().sleep(5000); if(startTime+20000<System.currentTimeMillis()) { break; } } if(!this.mtpLayer.isLinkUp()) { throw new StartFailedException(); } this.sccpProvider = new SccpSCTPProviderImpl(this.mtpLayer, stackProperties); this.mapStack = new MAPStackImpl(sccpProvider); this.mapStack.getMAPProvider().addMAPDialogListener(this); this.mapStack.getMAPProvider().addMAPServiceListener(this); //indicate linkup, since we mockup now, its done by hand. //this method is called by M3UserConnector! this.sccpProvider.linkUp(); } //FIXME: add proper dialog kill private void terminateSS7() { if(this.mtpLayer!=null) { this.mtpLayer.stop(); //this.mtpLayer = null; } } private void resetServer() { if(this.initSS7Future!=null) { this.initSS7Future.cancel(false); this.initSS7Future = null; } terminateSS7(); _button_close_server.setEnabled(false); _button_open_server.setEnabled(true); this.enableKeyPad(false); } public void onMAPAcceptInfo(MAPAcceptInfo arg0) { //throw new UnsupportedOperationException("Not supported yet."); } public void onMAPOpenInfo(MAPOpenInfo arg0) { //throw new UnsupportedOperationException("Not supported yet."); } public void onMAPCloseInfo(MAPCloseInfo close) { this._field_punch_display.setText("Dialog Closed"); this.onlyKeyPadContent = false; this.clientDialog = null; this._keypad_button_break.setEnabled(false); } public void onMAPProviderAbortInfo(MAPProviderAbortInfo arg0) { this._field_punch_display.setText("Dialog Aborted: "+arg0); this.onlyKeyPadContent = false; this.clientDialog = null; this._keypad_button_break.setEnabled(false); } public void onMAPRefuseInfo(MAPRefuseInfo arg0) { this._field_punch_display.setText("Dialog Refused: "+arg0); this.onlyKeyPadContent = false; this.clientDialog = null; this._keypad_button_break.setEnabled(false); } public void onMAPUserAbortInfo(MAPUserAbortInfo arg0) { this._field_punch_display.setText("Dialog UAborted: "+arg0); this.onlyKeyPadContent = false; this.clientDialog = null; this._keypad_button_break.setEnabled(false); } public void onProcessUnstructuredSSIndication(ProcessUnstructuredSSIndication arg0) { //we dont server requests. throw new UnsupportedOperationException("Not supported yet."); } public void onUnstructuredSSIndication(UnstructuredSSIndication ussdInditaion) { //here RA responds. USSDString string =ussdInditaion.getUSSDString(); this._field_result_display.setText(string.getString()); } }
git-svn-id: https://mobicents.googlecode.com/svn/trunk/protocols/ss7@11929 bf0df8d0-2c1f-0410-b170-bd30377b63dc
tools/ussd-simulator/src/main/java/org/mobicents/protocols/ss7/ussdsimulator/UssdsimulatorView.java
<ide><path>ools/ussd-simulator/src/main/java/org/mobicents/protocols/ss7/ussdsimulator/UssdsimulatorView.java <ide> //dont set more, until statics are defined! <ide> gt.setDigits("5557779"); <ide> peer1Address.setGlobalTitle(gt); <add> peer1Address.setGlobalTitleIndicator(4);//for GT 100 <ide> <ide> peer2Address = sccpProvider.getSccpParameterFactory().getSccpAddress(); <ide> gt = sccpProvider.getSccpParameterFactory().getGlobalTitle100(); <ide> //dont set more, until statics are defined! <ide> gt.setDigits("5888879"); <ide> peer2Address.setGlobalTitle(gt); <add> peer2Address.setGlobalTitleIndicator(4);//for GT 100 <ide> <ide> //map/ussd part <ide> mapUssdAppContext = MAPApplicationContext.networkUnstructuredSsContextV2; <ide> } <ide> } <ide> try { <del> clientDialog.addProcessUnstructuredSSRequest((byte) 0x0F, ussdString); <add> AddressString msisdn = this.mapStack.getMAPProvider().getMapServiceFactory() <add> .createAddressString(AddressNature.international_number, <add> NumberingPlan.ISDN, "31628838002"); <add> clientDialog.addProcessUnstructuredSSRequest((byte) 0x0F, ussdString,msisdn); <ide> clientDialog.send(); <ide> this._field_punch_display.setText(""); <ide> this._keypad_button_break.setEnabled(true);
Java
apache-2.0
b81316a6c33b4d8631eb21514516211ba3493680
0
MatthewTamlin/Avatar
package com.matthewtamlin.java_compiler_utilities.element_supplier; /** * Exception which indicates that a unique element for some criteria could not be found when searching a source file. */ public class UniqueElementNotFoundException extends RuntimeException { public UniqueElementNotFoundException() { super(); } public UniqueElementNotFoundException(final String message) { super(message); } public UniqueElementNotFoundException(final String message, final Throwable cause) { super(message, cause); } public UniqueElementNotFoundException(final Throwable cause) { super(cause); } }
library/src/main/java/com/matthewtamlin/java_compiler_utilities/element_supplier/UniqueElementNotFoundException.java
package com.matthewtamlin.java_compiler_utilities.element_supplier; /** * An exception to indicate that a unique element for some criteria could not be found when searching a source file. */ public class UniqueElementNotFoundException extends RuntimeException { public UniqueElementNotFoundException() { super(); } public UniqueElementNotFoundException(final String message) { super(message); } public UniqueElementNotFoundException(final String message, final Throwable cause) { super(message, cause); } public UniqueElementNotFoundException(final Throwable cause) { super(cause); } }
Changed Javadoc
library/src/main/java/com/matthewtamlin/java_compiler_utilities/element_supplier/UniqueElementNotFoundException.java
Changed Javadoc
<ide><path>ibrary/src/main/java/com/matthewtamlin/java_compiler_utilities/element_supplier/UniqueElementNotFoundException.java <ide> package com.matthewtamlin.java_compiler_utilities.element_supplier; <ide> <ide> /** <del> * An exception to indicate that a unique element for some criteria could not be found when searching a source file. <add> * Exception which indicates that a unique element for some criteria could not be found when searching a source file. <ide> */ <ide> public class UniqueElementNotFoundException extends RuntimeException { <ide> public UniqueElementNotFoundException() {
Java
epl-1.0
5ffdafda691ace48078fbdfe8829a98f1c51d5ca
0
vitruv-tools/Vitruv
package tools.vitruv.framework.vsum.ui; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.IExtension; import org.eclipse.core.runtime.IExtensionPoint; import org.eclipse.core.runtime.IExtensionRegistry; import org.eclipse.core.runtime.Platform; import org.eclipse.jface.wizard.WizardPage; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Text; import org.eclipse.swt.widgets.Tree; import org.eclipse.swt.widgets.TreeItem; import java.util.List; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; public class DomainSelectionPage extends WizardPage { private static final String PAGENAME = "Vitruvius Project"; private static final String DESCRIPTION = "Create a new Vitruvius Project."; private HashMap<IProject, HashSet<IExtension>> map; private Composite container; protected DomainSelectionPage() { super(PAGENAME); setTitle(PAGENAME); setDescription(DESCRIPTION); map = new HashMap<>(); } @Override public void createControl(Composite parent) { container = new Composite(parent, SWT.NONE); GridLayout layout = new GridLayout(); container.setLayout(layout); layout.numColumns = 1; Label label1 = new Label(container, SWT.NONE); label1.setText("Select the Project and a required domain."); IProject projects[] = getProjects(); final Tree tree = new Tree(container, SWT.CHECK | SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL); GridData treeGridData = new GridData(GridData.FILL_BOTH); tree.setLayoutData(treeGridData); IExtensionRegistry reg = Platform.getExtensionRegistry(); IExtensionPoint ep = reg.getExtensionPoint("tools.vitruv.framework.vsum.domain"); IExtension[] extensions = null; if (ep != null) { extensions = ep.getExtensions(); } for (IProject project : projects) { TreeItem t = new TreeItem(tree, SWT.CHECK); t.setText(project.getName()); t.setData(project); map.put(project, new HashSet<>()); if (extensions != null) { for (int i = 0; i < extensions.length; i++) { TreeItem childItem = new TreeItem(t, SWT.CHECK); childItem.setText(extensions[i].getLabel()); childItem.setData(extensions[i]); } } } tree.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { if (event.detail == SWT.CHECK) { TreeItem item = (TreeItem) event.item; TreeItem parent = item.getParentItem(); if (item.getChecked()) { // check a project automatically, when one of it's domains is checked if (null != parent) { parent.setChecked(true); map.get(parent.getData()).add((IExtension) item.getData()); } } else { // all domains get deselected, when project is deselected. if (null == parent) { for (TreeItem child : item.getItems()) { child.setChecked(false); map.get(item.getData()).remove(child.getData()); } } else { map.get(parent.getData()).remove(item.getData()); } } // only finish if something is checked. boolean finished = false; for (TreeItem treeItem : tree.getItems()) { finished = finished || treeItem.getChecked(); } setPageComplete(finished); } } }); setControl(container); setPageComplete(false); } /** * Returns a HashMap of Projects, where every project is mapped to all of it's selected domains, respectively. * @return a HashMap that maps all project to their checked domains, respectively */ public HashMap<IProject, HashSet<IExtension>> getCheckedDomains() { return map; } private IProject[] getProjects() { return ResourcesPlugin.getWorkspace().getRoot().getProjects(); } }
bundles/framework/tools.vitruv.framework.vsum.ui/src/tools/vitruv/framework/vsum/ui/DomainSelectionPage.java
package tools.vitruv.framework.vsum.ui; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.IExtension; import org.eclipse.core.runtime.IExtensionPoint; import org.eclipse.core.runtime.IExtensionRegistry; import org.eclipse.core.runtime.Platform; import org.eclipse.jface.wizard.WizardPage; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Text; import org.eclipse.swt.widgets.Tree; import org.eclipse.swt.widgets.TreeItem; import java.util.HashMap; import java.util.HashSet; public class DomainSelectionPage extends WizardPage { private static final String PAGENAME = "Vitruvius Project"; private static final String DESCRIPTION = "Create a new Vitruvius Project."; private HashMap<IProject, HashSet<IExtension>> map; private Composite container; protected DomainSelectionPage() { super(PAGENAME); setTitle(PAGENAME); setDescription(DESCRIPTION); map = new HashMap<>(); } @Override public void createControl(Composite parent) { container = new Composite(parent, SWT.NONE); GridLayout layout = new GridLayout(); container.setLayout(layout); layout.numColumns = 1; Label label1 = new Label(container, SWT.NONE); label1.setText("Select the Project and a required domain."); IProject projects[] = getProjects(); final Tree tree = new Tree(container, SWT.CHECK | SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL); tree.setItemCount(projects.length); GridData treeGridData = new GridData(GridData.FILL_BOTH); tree.setLayoutData(treeGridData); IExtensionRegistry reg = Platform.getExtensionRegistry(); IExtensionPoint ep = reg.getExtensionPoint("tools.vitruv.framework.vsum.domain"); IExtension[] extensions = null; if (ep != null) { extensions = ep.getExtensions(); } for (IProject project : projects) { TreeItem t = new TreeItem(tree, SWT.CHECK); t.setText(project.getName()); t.setData(project); map.put(project, new HashSet<>()); if (extensions != null) { for (int i = 0; i < extensions.length; i++) { TreeItem childItem = new TreeItem(t, SWT.CHECK); childItem.setText(extensions[i].getLabel()); childItem.setData(extensions[i]); } } } tree.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { if (event.detail == SWT.CHECK) { TreeItem item = (TreeItem) event.item; TreeItem parent = item.getParentItem(); if (item.getChecked()) { // check a project automatically, when one of it's domains is checked if (null != parent) { parent.setChecked(true); map.get(parent.getData()).add((IExtension) item.getData()); } } else { // all domains get deselected, when project is deselected. if (null == parent) { for (TreeItem child : item.getItems()) { child.setChecked(false); map.get(item.getData()).remove(child.getData()); } } else { map.get(parent.getData()).remove(item.getData()); } } // only finish if something is checked. boolean finished = false; for (TreeItem treeItem : tree.getItems()) { finished = finished || treeItem.getChecked(); } setPageComplete(finished); } } }); setControl(container); setPageComplete(false); } /** * Returns a HashMap of Projects, where every project is mapped to all of it's selected domains, respectively. * @return a HashMap that maps all project to their checked domains, respectively */ public HashMap<IProject, HashSet<IExtension>> getCheckedDomains() { return map; } private IProject[] getProjects() { return ResourcesPlugin.getWorkspace().getRoot().getProjects(); } }
Finally fix the ’too many items’ problem of the tree.
bundles/framework/tools.vitruv.framework.vsum.ui/src/tools/vitruv/framework/vsum/ui/DomainSelectionPage.java
Finally fix the ’too many items’ problem of the tree.
<ide><path>undles/framework/tools.vitruv.framework.vsum.ui/src/tools/vitruv/framework/vsum/ui/DomainSelectionPage.java <ide> import org.eclipse.swt.widgets.Tree; <ide> import org.eclipse.swt.widgets.TreeItem; <ide> <add>import java.util.List; <add>import java.util.Arrays; <ide> import java.util.HashMap; <ide> import java.util.HashSet; <ide> <ide> IProject projects[] = getProjects(); <ide> <ide> final Tree tree = new Tree(container, SWT.CHECK | SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL); <del> tree.setItemCount(projects.length); <ide> <ide> GridData treeGridData = new GridData(GridData.FILL_BOTH); <ide> tree.setLayoutData(treeGridData);
Java
apache-2.0
ded2b94bfb057673dde6b642edfe25145f9a8048
0
TanayParikh/foam2,foam-framework/foam2,foam-framework/foam2,foam-framework/foam2,TanayParikh/foam2,foam-framework/foam2,jacksonic/vjlofvhjfgm,TanayParikh/foam2,TanayParikh/foam2,jacksonic/vjlofvhjfgm,foam-framework/foam2,jacksonic/vjlofvhjfgm
/** * @license * Copyright 2017 The FOAM Authors. All Rights Reserved. * http://www.apache.org/licenses/LICENSE-2.0 */ package foam.nanos.boot; import foam.core.*; import foam.dao.*; import foam.nanos.*; public class Boot { protected DAO serviceDAO_; protected X root_ = new ProxyX(); public Boot() { serviceDAO_ = new MapDAO(); ((MapDAO) serviceDAO_).setOf(NSpec.getOwnClassInfo()); ((MapDAO) serviceDAO_).setX(root_); loadTestData(); ((AbstractDAO) serviceDAO_).select(new AbstractSink() { public void put(FObject obj, Detachable sub) { NSpec sp = (NSpec) obj; System.out.println("NSpec: " + sp.getName()); try { // NanoService ns = sp.createService(); // ((ContextAwareSupport) ns).setX(root_); // ns.start(); root_.putFactory(sp.getName(), new SingletonFactory(new NSpecFactory(sp))); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } }); } protected void loadTestData() { NSpec s = new NSpec(); s.setName("http"); s.setServiceClass("foam.nanos.http.NanoHttpServer"); serviceDAO_.put(s); } public static void main (String[] args) throws Exception { new Boot(); } }
java_src/foam/nanos/boot/Boot.java
/** * @license * Copyright 2017 The FOAM Authors. All Rights Reserved. * http://www.apache.org/licenses/LICENSE-2.0 */ package foam.nanos.boot; import foam.core.*; import foam.dao.*; import foam.nanos.*; public class Boot { protected DAO serviceDAO_; protected X root_ = new ProxyX(); public Boot() { serviceDAO_ = new MapDAO(); ((MapDAO) serviceDAO_).setOf(NSpec.getOwnClassInfo()); ((MapDAO) serviceDAO_).setX(root_); loadTestData(); ((AbstractDAO) serviceDAO_).select(new AbstractSink() { public void put(FObject obj, Detachable sub) { NSpec sp = (NSpec) obj; System.out.println("NSpec: " + sp.getName()); try { NanoService ns = sp.createService(); ((ContextAwareSupport) ns).setX(root_); ns.start(); root_.put(sp.getName(), ns); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } }); } protected void loadTestData() { NSpec s = new NSpec(); s.setName("http"); s.setServiceClass("foam.nanos.http.NanoHttpServer"); serviceDAO_.put(s); } public static void main (String[] args) throws Exception { new Boot(); } }
Changes to boot service
java_src/foam/nanos/boot/Boot.java
Changes to boot service
<ide><path>ava_src/foam/nanos/boot/Boot.java <ide> import foam.nanos.*; <ide> <ide> public class Boot { <del> <ide> protected DAO serviceDAO_; <ide> protected X root_ = new ProxyX(); <ide> <ide> System.out.println("NSpec: " + sp.getName()); <ide> <ide> try { <del> NanoService ns = sp.createService(); <add> // NanoService ns = sp.createService(); <ide> <del> ((ContextAwareSupport) ns).setX(root_); <del> ns.start(); <del> root_.put(sp.getName(), ns); <add> // ((ContextAwareSupport) ns).setX(root_); <add> // ns.start(); <add> <add> root_.putFactory(sp.getName(), new SingletonFactory(new NSpecFactory(sp))); <ide> } catch (ClassNotFoundException e) { <ide> e.printStackTrace(); <ide> } catch (InstantiationException e) {
Java
mit
error: pathspec 'src/main/java/hk/ust/isom3320/assignment/Statistics.java' did not match any file(s) known to git
2a63ece6649135b13a354282a756553a51763e43
1
chpoon92/display-statistics-java
package hk.ust.isom3320.assignment.Statistics import java.util.Scanner; import java.io.File; public class assignment{ public static void main(String[] args) throws Exception{ System.out.print("Please input the path of the file: "); Scanner filePathInput = new Scanner(System.in); String filePath = filePathInput.next(); File file = new File(filePath); filePathInput.close(); Scanner fileInput = new Scanner(file); String row = new String(fileInput.nextLine()); int numberOfColumn = 1; for (int i = 0; i < row.length() - 1; i++) { if (row.charAt(i) == ',') ++numberOfColumn; } int numberOfRow = 1; while (fileInput.hasNextLine()) { ++numberOfRow; fileInput.nextLine(); } fileInput.close(); fileInput = new Scanner(file); fileInput.useDelimiter("[,\n]"); String[][] matrix = new String[numberOfRow][numberOfColumn]; for (int i = 0; i < numberOfRow; i++) for (int j = 0; j < numberOfColumn; j++) matrix[i][j] = new String(fileInput.next()); fileInput.close(); for (int i = 0; i < numberOfRow; i++) for (int j = 0; j < numberOfColumn; j++) if (matrix[i][j].length()>15) matrix[i][j]=matrix[i][j].substring(0, 15); for (int i = 0; i < numberOfRow; i++) { for (int j = 0; j < numberOfColumn; j++) System.out.printf("%-20s", matrix[i][j]); System.out.println(); } System.out.println(); System.out.printf("%-20s", "Store"); for (int i = 1; i < numberOfColumn; i++) System.out.printf("%-20s", matrix[0][i]); System.out.println(); System.out.printf("%-20s", "Total"); double locationMax=-1; double locationMin=-1; for (int i = 1; i < numberOfColumn; i++) { double total = 0; for (int j = 1; j < numberOfRow; j++) total += Double.parseDouble(matrix[j][i]); if (total > locationMax) locationMax = total; if ((total < locationMin) || (locationMin == -1)) locationMin = total; System.out.printf("%-20.2f", total); } System.out.println(); System.out.printf("%-20s", "Average"); for (int i = 1; i < numberOfColumn; i++) { double total = 0; for (int j = 1; j < numberOfRow; j++) total += Double.parseDouble(matrix[j][i]); double average = total / (numberOfRow - 1); System.out.printf("%-20.2f", average); } System.out.println("\n"); System.out.printf("%-20s", "Item"); for (int i = 1; i < numberOfRow; i++) System.out.printf("%-20s", matrix[i][0]); System.out.println(); System.out.printf("%-20s", "Total"); double itemMax=-1; double itemMin=-1; for (int i = 1; i < numberOfRow; i++) { double total = 0; for (int j = 1; j < numberOfColumn; j++) total += Double.parseDouble(matrix[i][j]); if (total > itemMax) itemMax = total; if ((total < itemMin) || (itemMin == -1)) itemMin = total; System.out.printf("%-20.2f", total); } System.out.println(); System.out.printf("%-20s", "Average"); for (int i = 1; i < numberOfRow; i++) { double total = 0; for (int j = 1; j < numberOfColumn; j++) total += Double.parseDouble(matrix[i][j]); double average = total / ( numberOfColumn - 1); System.out.printf("%-20.2f", average); } System.out.println(); System.out.printf("%s", "Best selling store(s):"); for (int i = 1; i < numberOfColumn; i++) { double total = 0; for (int j = 1; j < numberOfRow; j++) total += Double.parseDouble(matrix[j][i]); if (locationMax == total) System.out.printf("%-15s", matrix[0][i]); } System.out.println(); System.out.printf("%s", "Least selling store(s):"); for (int i = 1; i < numberOfColumn; i++) { double total = 0; for (int j = 1; j < numberOfRow; j++) total += Double.parseDouble(matrix[j][i]); if(locationMin == total) System.out.printf("%-15s", matrix[0][i]); } System.out.println(); System.out.printf("%s", "Best selling item(s):"); for (int i = 1; i < numberOfRow; i++) { double total = 0; for(int j = 1; j < numberOfColumn; j++) total += Double.parseDouble(matrix[i][j]); if(itemMax == total) System.out.printf("%-15s", matrix[i][0]); } System.out.println(); System.out.printf("%s", "Least selling item(s):"); for (int i = 1; i < numberOfRow; i++) { double total = 0; for(int j = 1; j < numberOfColumn; j++) total += Double.parseDouble(matrix[i][j]); if(itemMin == total) System.out.printf("%-15s", matrix[i][0]); } } }
src/main/java/hk/ust/isom3320/assignment/Statistics.java
Add finalized source codes
src/main/java/hk/ust/isom3320/assignment/Statistics.java
Add finalized source codes
<ide><path>rc/main/java/hk/ust/isom3320/assignment/Statistics.java <add>package hk.ust.isom3320.assignment.Statistics <add> <add>import java.util.Scanner; <add>import java.io.File; <add> <add>public class assignment{ <add> public static void main(String[] args) throws Exception{ <add> System.out.print("Please input the path of the file: "); <add> Scanner filePathInput = new Scanner(System.in); <add> String filePath = filePathInput.next(); <add> File file = new File(filePath); <add> filePathInput.close(); <add> Scanner fileInput = new Scanner(file); <add> String row = new String(fileInput.nextLine()); <add> int numberOfColumn = 1; <add> for (int i = 0; i < row.length() - 1; i++) { <add> if (row.charAt(i) == ',') <add> ++numberOfColumn; <add> } <add> int numberOfRow = 1; <add> while (fileInput.hasNextLine()) { <add> ++numberOfRow; <add> fileInput.nextLine(); <add> } <add> fileInput.close(); <add> fileInput = new Scanner(file); <add> fileInput.useDelimiter("[,\n]"); <add> String[][] matrix = new String[numberOfRow][numberOfColumn]; <add> for (int i = 0; i < numberOfRow; i++) <add> for (int j = 0; j < numberOfColumn; j++) <add> matrix[i][j] = new String(fileInput.next()); <add> fileInput.close(); <add> for (int i = 0; i < numberOfRow; i++) <add> for (int j = 0; j < numberOfColumn; j++) <add> if (matrix[i][j].length()>15) <add> matrix[i][j]=matrix[i][j].substring(0, 15); <add> for (int i = 0; i < numberOfRow; i++) { <add> for (int j = 0; j < numberOfColumn; j++) <add> System.out.printf("%-20s", matrix[i][j]); <add> System.out.println(); <add> } <add> System.out.println(); <add> System.out.printf("%-20s", "Store"); <add> for (int i = 1; i < numberOfColumn; i++) <add> System.out.printf("%-20s", matrix[0][i]); <add> System.out.println(); <add> System.out.printf("%-20s", "Total"); <add> double locationMax=-1; <add> double locationMin=-1; <add> for (int i = 1; i < numberOfColumn; i++) { <add> double total = 0; <add> for (int j = 1; j < numberOfRow; j++) <add> total += Double.parseDouble(matrix[j][i]); <add> if (total > locationMax) <add> locationMax = total; <add> if ((total < locationMin) || (locationMin == -1)) <add> locationMin = total; <add> System.out.printf("%-20.2f", total); <add> } <add> System.out.println(); <add> System.out.printf("%-20s", "Average"); <add> for (int i = 1; i < numberOfColumn; i++) { <add> double total = 0; <add> for (int j = 1; j < numberOfRow; j++) <add> total += Double.parseDouble(matrix[j][i]); <add> double average = total / (numberOfRow - 1); <add> System.out.printf("%-20.2f", average); <add> } <add> System.out.println("\n"); <add> System.out.printf("%-20s", "Item"); <add> for (int i = 1; i < numberOfRow; i++) <add> System.out.printf("%-20s", matrix[i][0]); <add> System.out.println(); <add> System.out.printf("%-20s", "Total"); <add> double itemMax=-1; <add> double itemMin=-1; <add> for (int i = 1; i < numberOfRow; i++) { <add> double total = 0; <add> for (int j = 1; j < numberOfColumn; j++) <add> total += Double.parseDouble(matrix[i][j]); <add> if (total > itemMax) <add> itemMax = total; <add> if ((total < itemMin) || (itemMin == -1)) <add> itemMin = total; <add> System.out.printf("%-20.2f", total); <add> } <add> System.out.println(); <add> System.out.printf("%-20s", "Average"); <add> for (int i = 1; i < numberOfRow; i++) { <add> double total = 0; <add> for (int j = 1; j < numberOfColumn; j++) <add> total += Double.parseDouble(matrix[i][j]); <add> double average = total / ( numberOfColumn - 1); <add> System.out.printf("%-20.2f", average); <add> } <add> System.out.println(); <add> System.out.printf("%s", "Best selling store(s):"); <add> for (int i = 1; i < numberOfColumn; i++) { <add> double total = 0; <add> for (int j = 1; j < numberOfRow; j++) <add> total += Double.parseDouble(matrix[j][i]); <add> if (locationMax == total) <add> System.out.printf("%-15s", matrix[0][i]); <add> } <add> System.out.println(); <add> System.out.printf("%s", "Least selling store(s):"); <add> for (int i = 1; i < numberOfColumn; i++) { <add> double total = 0; <add> for (int j = 1; j < numberOfRow; j++) <add> total += Double.parseDouble(matrix[j][i]); <add> if(locationMin == total) <add> System.out.printf("%-15s", matrix[0][i]); <add> } <add> System.out.println(); <add> System.out.printf("%s", "Best selling item(s):"); <add> for (int i = 1; i < numberOfRow; i++) { <add> double total = 0; <add> for(int j = 1; j < numberOfColumn; j++) <add> total += Double.parseDouble(matrix[i][j]); <add> if(itemMax == total) <add> System.out.printf("%-15s", matrix[i][0]); <add> } <add> System.out.println(); <add> System.out.printf("%s", "Least selling item(s):"); <add> for (int i = 1; i < numberOfRow; i++) { <add> double total = 0; <add> for(int j = 1; j < numberOfColumn; j++) <add> total += Double.parseDouble(matrix[i][j]); <add> if(itemMin == total) <add> System.out.printf("%-15s", matrix[i][0]); <add> } <add> } <add>}
Java
apache-2.0
46d9b4cf085692cd4fe72dd12ccb7c7f635ba2c6
0
HubSpot/hbase,HubSpot/hbase,HubSpot/hbase,HubSpot/hbase,HubSpot/hbase,HubSpot/hbase,HubSpot/hbase,HubSpot/hbase,HubSpot/hbase,HubSpot/hbase
/** * * 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.hadoop.hbase.regionserver; import static org.junit.Assert.fail; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.CountDownLatch; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hbase.HBaseTestingUtility; import org.apache.hadoop.hbase.HConstants; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.client.ColumnFamilyDescriptorBuilder; import org.apache.hadoop.hbase.client.Increment; import org.apache.hadoop.hbase.client.Mutation; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.client.RegionInfo; import org.apache.hadoop.hbase.client.RegionInfoBuilder; import org.apache.hadoop.hbase.client.TableDescriptor; import org.apache.hadoop.hbase.client.TableDescriptorBuilder; import org.apache.hadoop.hbase.regionserver.wal.AbstractFSWAL; import org.apache.hadoop.hbase.testclassification.RegionServerTests; import org.apache.hadoop.hbase.testclassification.SmallTests; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.hbase.util.FSUtils; import org.apache.hadoop.hbase.wal.WAL; import org.apache.hadoop.hbase.wal.WALEdit; import org.apache.hadoop.hbase.wal.WALFactory; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.rules.TestName; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameter; import org.junit.runners.Parameterized.Parameters; /** * Test for HBASE-17471. * <p> * MVCCPreAssign is added by HBASE-16698, but pre-assign mvcc is only used in put/delete path. Other * write paths like increment/append still assign mvcc in ringbuffer's consumer thread. If put and * increment are used parallel. Then seqid in WAL may not increase monotonically Disorder in wals * will lead to data loss. * <p> * This case use two thread to put and increment at the same time in a single region. Then check the * seqid in WAL. If seqid is wal is not monotonically increasing, this case will fail */ @RunWith(Parameterized.class) @Category({ RegionServerTests.class, SmallTests.class }) public class TestWALMonotonicallyIncreasingSeqId { private final Log LOG = LogFactory.getLog(getClass()); private final static HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility(); private static Path testDir = TEST_UTIL.getDataTestDir("TestWALMonotonicallyIncreasingSeqId"); private WALFactory wals; private FileSystem fileSystem; private Configuration walConf; private HRegion region; @Parameter public String walProvider; @Rule public TestName name = new TestName(); @Parameters(name = "{index}: wal={0}") public static List<Object[]> data() { return Arrays.asList(new Object[] { "asyncfs" }, new Object[] { "filesystem" }); } private TableDescriptor getTableDesc(TableName tableName, byte[]... families) { TableDescriptorBuilder builder = TableDescriptorBuilder.newBuilder(tableName); Arrays.stream(families).map( f -> ColumnFamilyDescriptorBuilder.newBuilder(f).setMaxVersions(Integer.MAX_VALUE).build()) .forEachOrdered(builder::addColumnFamily); return builder.build(); } private HRegion initHRegion(TableDescriptor htd, byte[] startKey, byte[] stopKey, int replicaId) throws IOException { Configuration conf = TEST_UTIL.getConfiguration(); conf.set("hbase.wal.provider", walProvider); conf.setBoolean("hbase.hregion.mvcc.preassign", false); Path tableDir = FSUtils.getTableDir(testDir, htd.getTableName()); RegionInfo info = RegionInfoBuilder.newBuilder(htd.getTableName()).setStartKey(startKey) .setEndKey(stopKey).setReplicaId(replicaId).setRegionId(0).build(); fileSystem = tableDir.getFileSystem(conf); final Configuration walConf = new Configuration(conf); FSUtils.setRootDir(walConf, tableDir); this.walConf = walConf; wals = new WALFactory(walConf, null, "log_" + replicaId); ChunkCreator.initialize(MemStoreLABImpl.CHUNK_SIZE_DEFAULT, false, 0, 0, 0, null); HRegion region = HRegion.createHRegion(info, TEST_UTIL.getDefaultRootDirPath(), conf, htd, wals.getWAL(info.getEncodedNameAsBytes(), info.getTable().getNamespace())); return region; } CountDownLatch latch = new CountDownLatch(1); public class PutThread extends Thread { HRegion region; public PutThread(HRegion region) { this.region = region; } @Override public void run() { try { for (int i = 0; i < 100; i++) { byte[] row = Bytes.toBytes("putRow" + i); Put put = new Put(row); put.addColumn("cf".getBytes(), Bytes.toBytes(0), Bytes.toBytes("")); latch.await(); region.batchMutate(new Mutation[] { put }); Thread.sleep(10); } } catch (Throwable t) { LOG.warn("Error happend when Increment: ", t); } } } public class IncThread extends Thread { HRegion region; public IncThread(HRegion region) { this.region = region; } @Override public void run() { try { for (int i = 0; i < 100; i++) { byte[] row = Bytes.toBytes("incrementRow" + i); Increment inc = new Increment(row); inc.addColumn("cf".getBytes(), Bytes.toBytes(0), 1); // inc.setDurability(Durability.ASYNC_WAL); region.increment(inc); latch.countDown(); Thread.sleep(10); } } catch (Throwable t) { LOG.warn("Error happend when Put: ", t); } } } @Before public void setUp() throws IOException { byte[][] families = new byte[][] { Bytes.toBytes("cf") }; TableDescriptor htd = getTableDesc( TableName.valueOf(name.getMethodName().replaceAll("[^0-9A-Za-z_]", "_")), families); region = initHRegion(htd, HConstants.EMPTY_START_ROW, HConstants.EMPTY_END_ROW, 0); } @After public void tearDown() throws IOException { if (region != null) { region.close(); } } @AfterClass public static void tearDownAfterClass() throws IOException { TEST_UTIL.cleanupTestDir(); } private WAL.Reader createReader(Path logPath, Path oldWalsDir) throws IOException { try { return wals.createReader(fileSystem, logPath); } catch (IOException e) { return wals.createReader(fileSystem, new Path(oldWalsDir, logPath.getName())); } } @Test public void testWALMonotonicallyIncreasingSeqId() throws Exception { List<Thread> putThreads = new ArrayList<>(); for (int i = 0; i < 1; i++) { putThreads.add(new PutThread(region)); } IncThread incThread = new IncThread(region); for (int i = 0; i < 1; i++) { putThreads.get(i).start(); } incThread.start(); incThread.join(); Path logPath = ((AbstractFSWAL<?>) region.getWAL()).getCurrentFileName(); region.getWAL().rollWriter(); Thread.sleep(10); Path hbaseDir = new Path(walConf.get(HConstants.HBASE_DIR)); Path oldWalsDir = new Path(hbaseDir, HConstants.HREGION_OLDLOGDIR_NAME); try (WAL.Reader reader = createReader(logPath, oldWalsDir)) { long currentMaxSeqid = 0; for (WAL.Entry e; (e = reader.next()) != null;) { if (!WALEdit.isMetaEditFamily(e.getEdit().getCells().get(0))) { long currentSeqid = e.getKey().getSequenceId(); if (currentSeqid > currentMaxSeqid) { currentMaxSeqid = currentSeqid; } else { fail("Current max Seqid is " + currentMaxSeqid + ", but the next seqid in wal is smaller:" + currentSeqid); } } } } } }
hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/TestWALMonotonicallyIncreasingSeqId.java
/** * * 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.hadoop.hbase.regionserver; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hbase.*; import org.apache.hadoop.hbase.client.*; import org.apache.hadoop.hbase.regionserver.wal.FSHLog; import org.apache.hadoop.hbase.wal.WALEdit; import org.apache.hadoop.hbase.testclassification.RegionServerTests; import org.apache.hadoop.hbase.testclassification.SmallTests; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.hbase.util.FSUtils; import org.apache.hadoop.hbase.wal.WAL; import org.apache.hadoop.hbase.wal.WALFactory; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.rules.TestName; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CountDownLatch; /** * Test for HBASE-17471 * MVCCPreAssign is added by HBASE-16698, but pre-assign mvcc is only used in put/delete * path. Other write paths like increment/append still assign mvcc in ringbuffer's consumer * thread. If put and increment are used parallel. Then seqid in WAL may not increase monotonically * Disorder in wals will lead to data loss. * This case use two thread to put and increment at the same time in a single region. * Then check the seqid in WAL. If seqid is wal is not monotonically increasing, this case will fail * */ @Category({RegionServerTests.class, SmallTests.class}) public class TestWALMonotonicallyIncreasingSeqId { final Log LOG = LogFactory.getLog(getClass()); private final static HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility(); private static Path testDir = TEST_UTIL.getDataTestDir("TestWALMonotonicallyIncreasingSeqId"); private WALFactory wals; private FileSystem fileSystem; private Configuration walConf; public static final String KEY_SEED = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; private static final int KEY_SEED_LEN = KEY_SEED.length(); private static final char[] KEY_SEED_CHARS = KEY_SEED.toCharArray(); @Rule public TestName name = new TestName(); private HTableDescriptor getTableDesc(TableName tableName, byte[]... families) { HTableDescriptor htd = new HTableDescriptor(tableName); for (byte[] family : families) { HColumnDescriptor hcd = new HColumnDescriptor(family); // Set default to be three versions. hcd.setMaxVersions(Integer.MAX_VALUE); htd.addFamily(hcd); } return htd; } private Region initHRegion(HTableDescriptor htd, byte[] startKey, byte[] stopKey, int replicaId) throws IOException { Configuration conf = TEST_UTIL.getConfiguration(); conf.setBoolean("hbase.hregion.mvcc.preassign", false); Path tableDir = FSUtils.getTableDir(testDir, htd.getTableName()); HRegionInfo info = new HRegionInfo(htd.getTableName(), startKey, stopKey, false, 0, replicaId); fileSystem = tableDir.getFileSystem(conf); HRegionFileSystem fs = new HRegionFileSystem(conf, fileSystem, tableDir, info); final Configuration walConf = new Configuration(conf); FSUtils.setRootDir(walConf, tableDir); this.walConf = walConf; wals = new WALFactory(walConf, null, "log_" + replicaId); ChunkCreator.initialize(MemStoreLABImpl.CHUNK_SIZE_DEFAULT, false, 0, 0, 0, null); HRegion region = HRegion.createHRegion(info, TEST_UTIL.getDefaultRootDirPath(), conf, htd, wals.getWAL(info.getEncodedNameAsBytes(), info.getTable().getNamespace())); return region; } CountDownLatch latch = new CountDownLatch(1); public class PutThread extends Thread { HRegion region; public PutThread(HRegion region) { this.region = region; } @Override public void run() { try { for(int i = 0; i < 100; i++) { byte[] row = Bytes.toBytes("putRow" + i); Put put = new Put(row); put.addColumn("cf".getBytes(), Bytes.toBytes(0), Bytes.toBytes("")); //put.setDurability(Durability.ASYNC_WAL); latch.await(); region.batchMutate(new Mutation[]{put}); Thread.sleep(10); } } catch (Throwable t) { LOG.warn("Error happend when Increment: ", t); } } } public class IncThread extends Thread { HRegion region; public IncThread(HRegion region) { this.region = region; } @Override public void run() { try { for(int i = 0; i < 100; i++) { byte[] row = Bytes.toBytes("incrementRow" + i); Increment inc = new Increment(row); inc.addColumn("cf".getBytes(), Bytes.toBytes(0), 1); //inc.setDurability(Durability.ASYNC_WAL); region.increment(inc); latch.countDown(); Thread.sleep(10); } } catch (Throwable t) { LOG.warn("Error happend when Put: ", t); } } } @Test public void TestWALMonotonicallyIncreasingSeqId() throws Exception { byte[][] families = new byte[][] {Bytes.toBytes("cf")}; byte[] qf = Bytes.toBytes("cq"); HTableDescriptor htd = getTableDesc(TableName.valueOf(name.getMethodName()), families); HRegion region = (HRegion)initHRegion(htd, HConstants.EMPTY_START_ROW, HConstants.EMPTY_END_ROW, 0); List<Thread> putThreads = new ArrayList<>(); for(int i = 0; i < 1; i++) { putThreads.add(new PutThread(region)); } IncThread incThread = new IncThread(region); for(int i = 0; i < 1; i++) { putThreads.get(i).start(); } incThread.start(); incThread.join(); Path logPath = ((FSHLog) region.getWAL()).getCurrentFileName(); region.getWAL().rollWriter(); Thread.sleep(10); Path hbaseDir = new Path(walConf.get(HConstants.HBASE_DIR)); Path oldWalsDir = new Path(hbaseDir, HConstants.HREGION_OLDLOGDIR_NAME); WAL.Reader reader = null; try { reader = wals.createReader(fileSystem, logPath); } catch (Throwable t) { reader = wals.createReader(fileSystem, new Path(oldWalsDir, logPath.getName())); } WAL.Entry e; try { long currentMaxSeqid = 0; while ((e = reader.next()) != null) { if (!WALEdit.isMetaEditFamily(e.getEdit().getCells().get(0))) { long currentSeqid = e.getKey().getSequenceId(); if(currentSeqid > currentMaxSeqid) { currentMaxSeqid = currentSeqid; } else { Assert.fail("Current max Seqid is " + currentMaxSeqid + ", but the next seqid in wal is smaller:" + currentSeqid); } } } } finally { if(reader != null) { reader.close(); } if(region != null) { region.close(); } } } }
HBASE-19493 Make TestWALMonotonicallyIncreasingSeqId also work with AsyncFSWAL
hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/TestWALMonotonicallyIncreasingSeqId.java
HBASE-19493 Make TestWALMonotonicallyIncreasingSeqId also work with AsyncFSWAL
<ide><path>base-server/src/test/java/org/apache/hadoop/hbase/regionserver/TestWALMonotonicallyIncreasingSeqId.java <ide> */ <ide> package org.apache.hadoop.hbase.regionserver; <ide> <add>import static org.junit.Assert.fail; <add> <add>import java.io.IOException; <add>import java.util.ArrayList; <add>import java.util.Arrays; <add>import java.util.List; <add>import java.util.concurrent.CountDownLatch; <add> <ide> import org.apache.commons.logging.Log; <ide> import org.apache.commons.logging.LogFactory; <ide> import org.apache.hadoop.conf.Configuration; <ide> import org.apache.hadoop.fs.FileSystem; <ide> import org.apache.hadoop.fs.Path; <del>import org.apache.hadoop.hbase.*; <del>import org.apache.hadoop.hbase.client.*; <del>import org.apache.hadoop.hbase.regionserver.wal.FSHLog; <del>import org.apache.hadoop.hbase.wal.WALEdit; <add>import org.apache.hadoop.hbase.HBaseTestingUtility; <add>import org.apache.hadoop.hbase.HConstants; <add>import org.apache.hadoop.hbase.TableName; <add>import org.apache.hadoop.hbase.client.ColumnFamilyDescriptorBuilder; <add>import org.apache.hadoop.hbase.client.Increment; <add>import org.apache.hadoop.hbase.client.Mutation; <add>import org.apache.hadoop.hbase.client.Put; <add>import org.apache.hadoop.hbase.client.RegionInfo; <add>import org.apache.hadoop.hbase.client.RegionInfoBuilder; <add>import org.apache.hadoop.hbase.client.TableDescriptor; <add>import org.apache.hadoop.hbase.client.TableDescriptorBuilder; <add>import org.apache.hadoop.hbase.regionserver.wal.AbstractFSWAL; <ide> import org.apache.hadoop.hbase.testclassification.RegionServerTests; <ide> import org.apache.hadoop.hbase.testclassification.SmallTests; <ide> import org.apache.hadoop.hbase.util.Bytes; <ide> import org.apache.hadoop.hbase.util.FSUtils; <ide> import org.apache.hadoop.hbase.wal.WAL; <add>import org.apache.hadoop.hbase.wal.WALEdit; <ide> import org.apache.hadoop.hbase.wal.WALFactory; <del>import org.junit.Assert; <add>import org.junit.After; <add>import org.junit.AfterClass; <add>import org.junit.Before; <ide> import org.junit.Rule; <ide> import org.junit.Test; <ide> import org.junit.experimental.categories.Category; <ide> import org.junit.rules.TestName; <del> <del>import java.io.IOException; <del>import java.util.ArrayList; <del>import java.util.List; <del>import java.util.concurrent.CountDownLatch; <add>import org.junit.runner.RunWith; <add>import org.junit.runners.Parameterized; <add>import org.junit.runners.Parameterized.Parameter; <add>import org.junit.runners.Parameterized.Parameters; <ide> <ide> /** <del> * Test for HBASE-17471 <del> * MVCCPreAssign is added by HBASE-16698, but pre-assign mvcc is only used in put/delete <del> * path. Other write paths like increment/append still assign mvcc in ringbuffer's consumer <del> * thread. If put and increment are used parallel. Then seqid in WAL may not increase monotonically <del> * Disorder in wals will lead to data loss. <del> * This case use two thread to put and increment at the same time in a single region. <del> * Then check the seqid in WAL. If seqid is wal is not monotonically increasing, this case will fail <del> * <add> * Test for HBASE-17471. <add> * <p> <add> * MVCCPreAssign is added by HBASE-16698, but pre-assign mvcc is only used in put/delete path. Other <add> * write paths like increment/append still assign mvcc in ringbuffer's consumer thread. If put and <add> * increment are used parallel. Then seqid in WAL may not increase monotonically Disorder in wals <add> * will lead to data loss. <add> * <p> <add> * This case use two thread to put and increment at the same time in a single region. Then check the <add> * seqid in WAL. If seqid is wal is not monotonically increasing, this case will fail <ide> */ <del>@Category({RegionServerTests.class, SmallTests.class}) <add>@RunWith(Parameterized.class) <add>@Category({ RegionServerTests.class, SmallTests.class }) <ide> public class TestWALMonotonicallyIncreasingSeqId { <del> final Log LOG = LogFactory.getLog(getClass()); <add> private final Log LOG = LogFactory.getLog(getClass()); <ide> private final static HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility(); <ide> private static Path testDir = TEST_UTIL.getDataTestDir("TestWALMonotonicallyIncreasingSeqId"); <ide> private WALFactory wals; <ide> private FileSystem fileSystem; <ide> private Configuration walConf; <del> <del> public static final String KEY_SEED = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; <del> <del> private static final int KEY_SEED_LEN = KEY_SEED.length(); <del> <del> private static final char[] KEY_SEED_CHARS = KEY_SEED.toCharArray(); <add> private HRegion region; <add> <add> @Parameter <add> public String walProvider; <ide> <ide> @Rule <ide> public TestName name = new TestName(); <ide> <del> private HTableDescriptor getTableDesc(TableName tableName, byte[]... families) { <del> HTableDescriptor htd = new HTableDescriptor(tableName); <del> for (byte[] family : families) { <del> HColumnDescriptor hcd = new HColumnDescriptor(family); <del> // Set default to be three versions. <del> hcd.setMaxVersions(Integer.MAX_VALUE); <del> htd.addFamily(hcd); <del> } <del> return htd; <del> } <del> <del> private Region initHRegion(HTableDescriptor htd, byte[] startKey, byte[] stopKey, int replicaId) <add> @Parameters(name = "{index}: wal={0}") <add> public static List<Object[]> data() { <add> return Arrays.asList(new Object[] { "asyncfs" }, new Object[] { "filesystem" }); <add> } <add> <add> private TableDescriptor getTableDesc(TableName tableName, byte[]... families) { <add> TableDescriptorBuilder builder = TableDescriptorBuilder.newBuilder(tableName); <add> Arrays.stream(families).map( <add> f -> ColumnFamilyDescriptorBuilder.newBuilder(f).setMaxVersions(Integer.MAX_VALUE).build()) <add> .forEachOrdered(builder::addColumnFamily); <add> return builder.build(); <add> } <add> <add> private HRegion initHRegion(TableDescriptor htd, byte[] startKey, byte[] stopKey, int replicaId) <ide> throws IOException { <ide> Configuration conf = TEST_UTIL.getConfiguration(); <add> conf.set("hbase.wal.provider", walProvider); <ide> conf.setBoolean("hbase.hregion.mvcc.preassign", false); <ide> Path tableDir = FSUtils.getTableDir(testDir, htd.getTableName()); <ide> <del> HRegionInfo info = new HRegionInfo(htd.getTableName(), startKey, stopKey, false, 0, replicaId); <del> fileSystem = tableDir.getFileSystem(conf); <del> HRegionFileSystem fs = new HRegionFileSystem(conf, fileSystem, tableDir, info); <add> RegionInfo info = RegionInfoBuilder.newBuilder(htd.getTableName()).setStartKey(startKey) <add> .setEndKey(stopKey).setReplicaId(replicaId).setRegionId(0).build(); <add> fileSystem = tableDir.getFileSystem(conf); <ide> final Configuration walConf = new Configuration(conf); <ide> FSUtils.setRootDir(walConf, tableDir); <ide> this.walConf = walConf; <ide> wals = new WALFactory(walConf, null, "log_" + replicaId); <ide> ChunkCreator.initialize(MemStoreLABImpl.CHUNK_SIZE_DEFAULT, false, 0, 0, 0, null); <ide> HRegion region = HRegion.createHRegion(info, TEST_UTIL.getDefaultRootDirPath(), conf, htd, <del> wals.getWAL(info.getEncodedNameAsBytes(), info.getTable().getNamespace())); <add> wals.getWAL(info.getEncodedNameAsBytes(), info.getTable().getNamespace())); <ide> return region; <ide> } <ide> <ide> CountDownLatch latch = new CountDownLatch(1); <add> <ide> public class PutThread extends Thread { <ide> HRegion region; <add> <ide> public PutThread(HRegion region) { <ide> this.region = region; <ide> } <ide> @Override <ide> public void run() { <ide> try { <del> for(int i = 0; i < 100; i++) { <add> for (int i = 0; i < 100; i++) { <ide> byte[] row = Bytes.toBytes("putRow" + i); <ide> Put put = new Put(row); <ide> put.addColumn("cf".getBytes(), Bytes.toBytes(0), Bytes.toBytes("")); <del> //put.setDurability(Durability.ASYNC_WAL); <ide> latch.await(); <del> region.batchMutate(new Mutation[]{put}); <add> region.batchMutate(new Mutation[] { put }); <ide> Thread.sleep(10); <ide> } <del> <ide> <ide> } catch (Throwable t) { <ide> LOG.warn("Error happend when Increment: ", t); <ide> } <del> <ide> } <ide> } <ide> <ide> public class IncThread extends Thread { <ide> HRegion region; <add> <ide> public IncThread(HRegion region) { <ide> this.region = region; <ide> } <add> <ide> @Override <ide> public void run() { <ide> try { <del> for(int i = 0; i < 100; i++) { <add> for (int i = 0; i < 100; i++) { <ide> byte[] row = Bytes.toBytes("incrementRow" + i); <ide> Increment inc = new Increment(row); <ide> inc.addColumn("cf".getBytes(), Bytes.toBytes(0), 1); <del> //inc.setDurability(Durability.ASYNC_WAL); <add> // inc.setDurability(Durability.ASYNC_WAL); <ide> region.increment(inc); <ide> latch.countDown(); <ide> Thread.sleep(10); <ide> } <ide> <del> <ide> } catch (Throwable t) { <ide> LOG.warn("Error happend when Put: ", t); <ide> } <del> <add> } <add> } <add> <add> @Before <add> public void setUp() throws IOException { <add> byte[][] families = new byte[][] { Bytes.toBytes("cf") }; <add> TableDescriptor htd = getTableDesc( <add> TableName.valueOf(name.getMethodName().replaceAll("[^0-9A-Za-z_]", "_")), families); <add> region = initHRegion(htd, HConstants.EMPTY_START_ROW, HConstants.EMPTY_END_ROW, 0); <add> } <add> <add> @After <add> public void tearDown() throws IOException { <add> if (region != null) { <add> region.close(); <add> } <add> } <add> <add> @AfterClass <add> public static void tearDownAfterClass() throws IOException { <add> TEST_UTIL.cleanupTestDir(); <add> } <add> <add> private WAL.Reader createReader(Path logPath, Path oldWalsDir) throws IOException { <add> try { <add> return wals.createReader(fileSystem, logPath); <add> } catch (IOException e) { <add> return wals.createReader(fileSystem, new Path(oldWalsDir, logPath.getName())); <ide> } <ide> } <ide> <ide> @Test <del> public void TestWALMonotonicallyIncreasingSeqId() throws Exception { <del> byte[][] families = new byte[][] {Bytes.toBytes("cf")}; <del> byte[] qf = Bytes.toBytes("cq"); <del> HTableDescriptor htd = getTableDesc(TableName.valueOf(name.getMethodName()), families); <del> HRegion region = (HRegion)initHRegion(htd, HConstants.EMPTY_START_ROW, HConstants.EMPTY_END_ROW, 0); <add> public void testWALMonotonicallyIncreasingSeqId() throws Exception { <ide> List<Thread> putThreads = new ArrayList<>(); <del> for(int i = 0; i < 1; i++) { <add> for (int i = 0; i < 1; i++) { <ide> putThreads.add(new PutThread(region)); <ide> } <ide> IncThread incThread = new IncThread(region); <del> for(int i = 0; i < 1; i++) { <add> for (int i = 0; i < 1; i++) { <ide> putThreads.get(i).start(); <ide> } <ide> incThread.start(); <ide> incThread.join(); <ide> <del> Path logPath = ((FSHLog) region.getWAL()).getCurrentFileName(); <add> Path logPath = ((AbstractFSWAL<?>) region.getWAL()).getCurrentFileName(); <ide> region.getWAL().rollWriter(); <ide> Thread.sleep(10); <ide> Path hbaseDir = new Path(walConf.get(HConstants.HBASE_DIR)); <ide> Path oldWalsDir = new Path(hbaseDir, HConstants.HREGION_OLDLOGDIR_NAME); <del> WAL.Reader reader = null; <del> try { <del> reader = wals.createReader(fileSystem, logPath); <del> } catch (Throwable t) { <del> reader = wals.createReader(fileSystem, new Path(oldWalsDir, logPath.getName())); <del> <del> } <del> WAL.Entry e; <del> try { <add> try (WAL.Reader reader = createReader(logPath, oldWalsDir)) { <ide> long currentMaxSeqid = 0; <del> while ((e = reader.next()) != null) { <add> for (WAL.Entry e; (e = reader.next()) != null;) { <ide> if (!WALEdit.isMetaEditFamily(e.getEdit().getCells().get(0))) { <ide> long currentSeqid = e.getKey().getSequenceId(); <del> if(currentSeqid > currentMaxSeqid) { <add> if (currentSeqid > currentMaxSeqid) { <ide> currentMaxSeqid = currentSeqid; <ide> } else { <del> Assert.fail("Current max Seqid is " + currentMaxSeqid <del> + ", but the next seqid in wal is smaller:" + currentSeqid); <add> fail("Current max Seqid is " + currentMaxSeqid + <add> ", but the next seqid in wal is smaller:" + currentSeqid); <ide> } <ide> } <ide> } <del> } finally { <del> if(reader != null) { <del> reader.close(); <del> } <del> if(region != null) { <del> region.close(); <del> } <del> } <del> } <del> <del> <add> } <add> } <ide> }
Java
epl-1.0
0d008e16c78447616ce700ef5e79c17c2a7a18c5
0
bpsm/edn-java
package bpsm.edn.parser; import static bpsm.edn.model.Symbol.newSymbol; import static bpsm.edn.model.Tag.newTag; import static bpsm.edn.model.TaggedValue.newTaggedValue; import static org.junit.Assert.assertEquals; import java.io.IOException; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import org.junit.Test; public class TestParser { @Test public void parseEdnSample() throws IOException { Parser parser = parser(IOUtil .stringFromResource("bpsm/edn/edn-sample.txt")); @SuppressWarnings("unchecked") List<Object> expected = Arrays.asList( map(TestScanner.key("keyword"), TestScanner.sym("symbol"), 1, 2.0d, new BigInteger("3"), new BigDecimal("4.0")), Arrays.asList(1, 1, 2, 3, 5, 8), new HashSet<Object>(Arrays.asList('\n', '\t')), Arrays.asList(Arrays.asList(Arrays.asList(true, false, null)))); List<Object> results = new ArrayList<Object>(); for (int i = 0; i < 4; i++) { results.add(parser.nextValue()); } assertEquals(expected, results); } @Test public void parseTaggedValueWithUnkownTag() { assertEquals(newTaggedValue(newTag(newSymbol("foo", "bar")), 1), parse("#foo/bar 1")); } @Test public void parseTaggedInstant() { assertEquals(1347235200000L, ((Date)parse("#inst \"2012-09-10\"")).getTime()); } @Test public void parseTaggedUUID() { assertEquals(UUID.fromString("f81d4fae-7dec-11d0-a765-00a0c91e6bf6"), parse("#uuid \"f81d4fae-7dec-11d0-a765-00a0c91e6bf6\"")); } private static final String INVALID_UUID = "#uuid \"f81d4fae-XXXX-11d0-a765-00a0c91e6bf6\""; @Test(expected=NumberFormatException.class) public void invalidUUIDCausesException() { parse(INVALID_UUID); } @Test public void discardedTaggedValuesDoNotCallTransformer() { // The given UUID is invalid, as demonstrated in the test above. // were the transformer for #uuid to be called despite the #_, // it would throw an exception and cause this test to fail. assertEquals(123L, parse("#_ " + INVALID_UUID + " 123")); } @Test(expected=UnsupportedOperationException.class) public void parserShouldReturnUnmodifiableListByDefault() { ((List<?>)parse("(1)")).remove(0); } @Test(expected=UnsupportedOperationException.class) public void parserShouldReturnUnmodifiableVectorByDefault() { ((List<?>)parse("[1]")).remove(0); } @Test(expected=UnsupportedOperationException.class) public void parserShouldReturnUnmodifiableSetByDefault() { ((Set<?>)parse("#{1}")).remove(1); } @Test(expected=UnsupportedOperationException.class) public void parserShouldReturnUnmodifiableMapByDefault() { ((Map<?,?>)parse("{1,-1}")).remove(1); } //@Test public void performanceOfInstantParsing() { StringBuilder b = new StringBuilder(); for (int h = -12; h <= 12; h++) { b.append("#inst ") .append('"') .append("2012-11-25T10:11:12.343") .append(String.format("%+03d", h)) .append(":00") .append('"') .append(' '); } for (int i = 0; i < 9; i++) { b.append(b.toString()); } String txt = "[" + b.toString() + "]"; long ns = System.nanoTime(); List<?> result = (List<?>) parse(txt); ns = System.nanoTime() - ns; long ms = ns / 1000000; System.out.printf("%d insts took %d ms (%1.2f ms/inst)\n", result.size(), ms, (1.0*ms)/result.size()); } static Object parse(String input) { try { return parser(input).nextValue(); } catch (IOException e) { throw new RuntimeException(e); } } static Parser parser(String input) { try { return Parser.newParser(ParserConfiguration.defaultConfiguration(), input); } catch (IOException e) { throw new RuntimeException(e); } } private Map<Object, Object> map(Object... kvs) { Map<Object, Object> m = new HashMap<Object, Object>(); for (int i = 0; i < kvs.length; i += 2) { m.put(kvs[i], kvs[i + 1]); } return m; } }
src/test/java/bpsm/edn/parser/TestParser.java
package bpsm.edn.parser; import static bpsm.edn.model.Symbol.newSymbol; import static bpsm.edn.model.Tag.newTag; import static bpsm.edn.model.TaggedValue.newTaggedValue; import static org.junit.Assert.assertEquals; import java.io.IOException; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import org.junit.Test; public class TestParser { @Test public void parseEdnSample() throws IOException { Parser parser = parser(IOUtil .stringFromResource("bpsm/edn/edn-sample.txt")); @SuppressWarnings("unchecked") List<Object> expected = Arrays.asList( map(TestScanner.key("keyword"), TestScanner.sym("symbol"), 1, 2.0d, new BigInteger("3"), new BigDecimal("4.0")), Arrays.asList(1, 1, 2, 3, 5, 8), new HashSet<Object>(Arrays.asList('\n', '\t')), Arrays.asList(Arrays.asList(Arrays.asList(true, false, null)))); List<Object> results = new ArrayList<Object>(); for (int i = 0; i < 4; i++) { results.add(parser.nextValue()); } assertEquals(expected, results); } @Test public void parseTaggedValueWithUnkownTag() { assertEquals(newTaggedValue(newTag(newSymbol("foo", "bar")), 1), parse("#foo/bar 1")); } @Test public void parseTaggedInstant() { assertEquals(1347235200000L, ((Date)parse("#inst \"2012-09-10\"")).getTime()); } @Test public void parseTaggedUUID() { assertEquals(UUID.fromString("f81d4fae-7dec-11d0-a765-00a0c91e6bf6"), parse("#uuid \"f81d4fae-7dec-11d0-a765-00a0c91e6bf6\"")); } @Test(expected=NumberFormatException.class) public void invalidUUIDCausesException() { parse("#uuid \"f81d4fae-XXXX-11d0-a765-00a0c91e6bf6\""); } @Test public void discardedTaggedValuesDoNotCallTransformer() { // The given UUID is invalid, as demonstrated in the test above. // were the transformer for #uuid to be called despite the #_, // it would throw an exception and cause this test to fail. assertEquals(123, parse("#_ #uuid \"f81d4fae-XXXX-11d0-a765-00a0c91e6bf6\" 123")); } @Test(expected=UnsupportedOperationException.class) public void parserShouldReturnUnmodifiableListByDefault() { ((List<?>)parse("(1)")).remove(0); } @Test(expected=UnsupportedOperationException.class) public void parserShouldReturnUnmodifiableVectorByDefault() { ((List<?>)parse("[1]")).remove(0); } @Test(expected=UnsupportedOperationException.class) public void parserShouldReturnUnmodifiableSetByDefault() { ((Set<?>)parse("#{1}")).remove(1); } @Test(expected=UnsupportedOperationException.class) public void parserShouldReturnUnmodifiableMapByDefault() { ((Map<?,?>)parse("{1,-1}")).remove(1); } //@Test public void performanceOfInstantParsing() { StringBuilder b = new StringBuilder(); for (int h = -12; h <= 12; h++) { b.append("#inst ") .append('"') .append("2012-11-25T10:11:12.343") .append(String.format("%+03d", h)) .append(":00") .append('"') .append(' '); } for (int i = 0; i < 9; i++) { b.append(b.toString()); } String txt = "[" + b.toString() + "]"; long ns = System.nanoTime(); List<?> result = (List<?>) parse(txt); ns = System.nanoTime() - ns; long ms = ns / 1000000; System.out.printf("%d insts took %d ms (%1.2f ms/inst)\n", result.size(), ms, (1.0*ms)/result.size()); } static Object parse(String input) { try { return parser(input).nextValue(); } catch (IOException e) { throw new RuntimeException(e); } } static Parser parser(String input) { try { return Parser.newParser(ParserConfiguration.defaultConfiguration(), input); } catch (IOException e) { throw new RuntimeException(e); } } private Map<Object, Object> map(Object... kvs) { Map<Object, Object> m = new HashMap<Object, Object>(); for (int i = 0; i < kvs.length; i += 2) { m.put(kvs[i], kvs[i + 1]); } return m; } }
TestParser: extract constant
src/test/java/bpsm/edn/parser/TestParser.java
TestParser: extract constant
<ide><path>rc/test/java/bpsm/edn/parser/TestParser.java <ide> parse("#uuid \"f81d4fae-7dec-11d0-a765-00a0c91e6bf6\"")); <ide> } <ide> <add> private static final String INVALID_UUID = "#uuid \"f81d4fae-XXXX-11d0-a765-00a0c91e6bf6\""; <add> <ide> @Test(expected=NumberFormatException.class) <ide> public void invalidUUIDCausesException() { <del> parse("#uuid \"f81d4fae-XXXX-11d0-a765-00a0c91e6bf6\""); <add> parse(INVALID_UUID); <ide> } <ide> <ide> @Test <ide> // were the transformer for #uuid to be called despite the #_, <ide> // it would throw an exception and cause this test to fail. <ide> <del> assertEquals(123, parse("#_ #uuid \"f81d4fae-XXXX-11d0-a765-00a0c91e6bf6\" 123")); <add> assertEquals(123L, parse("#_ " + INVALID_UUID + " 123")); <ide> } <ide> <ide> @Test(expected=UnsupportedOperationException.class)
Java
mit
error: pathspec '20120227-junit3_to_junit4/src/test/java/com/dfremont/blog/JUnit4WrongTest.java' did not match any file(s) known to git
4bdfdeafb37fa772125c8287c4740396cdf46304
1
DamienFremont/blog,DamienFremont/blog,DamienFremont/blog,DamienFremont/blog,DamienFremont/blog,DamienFremont/blog,DamienFremont/blog
package com.dfremont.blog; import org.junit.Test; public class JUnit4WrongTest { @Test public void testDivideValue() { // Arrange ClassToTest classToTest = new ClassToTest(); int param1 = 10; int param2 = 2; // Act int result = classToTest.divide(param1, param2); // Assert // assertEquals(5, result); } @Test public void testDivideValueWith0() { // Arrange ClassToTest classToTest = new ClassToTest(); int param1 = 10; int param2 = 0; // Act try { classToTest.divide(param1, param2); // fail("Expected error!"); } catch (ArithmeticException e) { // Assert // assertEquals("Wrong Exc msg!", "Division by zero prohibited!", // e.getMessage()); } } }
20120227-junit3_to_junit4/src/test/java/com/dfremont/blog/JUnit4WrongTest.java
wrong test example
20120227-junit3_to_junit4/src/test/java/com/dfremont/blog/JUnit4WrongTest.java
wrong test example
<ide><path>0120227-junit3_to_junit4/src/test/java/com/dfremont/blog/JUnit4WrongTest.java <add>package com.dfremont.blog; <add> <add>import org.junit.Test; <add> <add>public class JUnit4WrongTest { <add> @Test <add> public void testDivideValue() { <add> // Arrange <add> ClassToTest classToTest = new ClassToTest(); <add> int param1 = 10; <add> int param2 = 2; <add> // Act <add> int result = classToTest.divide(param1, param2); <add> // Assert <add> // assertEquals(5, result); <add> } <add> <add> @Test <add> public void testDivideValueWith0() { <add> // Arrange <add> ClassToTest classToTest = new ClassToTest(); <add> int param1 = 10; <add> int param2 = 0; <add> // Act <add> try { <add> classToTest.divide(param1, param2); <add> // fail("Expected error!"); <add> } catch (ArithmeticException e) { <add> // Assert <add> // assertEquals("Wrong Exc msg!", "Division by zero prohibited!", <add> // e.getMessage()); <add> } <add> } <add>}
JavaScript
mit
fa43e4c177964583f61518e05dfcb7df927c3f28
0
jordanfarrer/Knockout-Utilities
ko.bindingHandlers.numericValue = { init: function (element, valueAccessor, allBindingsAccessor) { var updateEvents = []; //keyup and change only works if precision is set to 0. if (allBindingsAccessor().valueUpdate === 'afterkeydown' && allBindingsAccessor().precision === 0) { updateEvents.push('keyup'); updateEvents.push('change'); } else { updateEvents.push('blur'); } for (var x = 0; x < updateEvents.length; x++) { ko.utils.registerEventHandler(element, updateEvents[x], function () { var value = parseFloat(element.value) || 0; var precision = ko.utils.unwrapObservable(allBindingsAccessor().precision); if (typeof precision === "undefined") { precision = ko.bindingHandlers.numericText.defaultPrecision; } var formattedValue = value.toFixed(precision); if ($.isFunction(valueAccessor())) { var observable = valueAccessor(); observable(formattedValue); ko.bindingHandlers.value.update(element, function () { return formattedValue; }); } }); } }, update: function (element, valueAccessor, allBindingsAccessor) { var value = ko.utils.unwrapObservable(valueAccessor()); var formattedValue = 0; if (typeof value === 'number') { var precision = ko.utils.unwrapObservable(allBindingsAccessor().precision); if (typeof precision === "undefined") { precision = ko.bindingHandlers.numericText.defaultPrecision; } formattedValue = value.toFixed(precision); } ko.bindingHandlers.value.update(element, function () { return formattedValue; }); }, defaultPrecision: 2 };
ko-numericValue.js
ko.bindingHandlers.numericValue = { init: function (element, valueAccessor, allBindingsAccessor) { var updateEvents = []; //keyup and change only works if precision is set to 0. if (allBindingsAccessor().valueUpdate === 'afterkeydown' && allBindingsAccessor().precision === 0) { updateEvents.push('keyup'); updateEvents.push('change'); } else { updateEvents.push('blur'); } for (var x = 0; x < updateEvents.length; x++) { ko.utils.registerEventHandler(element, updateEvents[x], function () { var value = parseFloat(element.value) || 0; var precision = ko.utils.unwrapObservable(allBindingsAccessor().precision); if (typeof precision === "undefined") { precision = ko.bindingHandlers.numericText.defaultPrecision; } var formattedValue = value.toFixed(precision); if ($.isFunction(valueAccessor())) { var observable = valueAccessor(); observable(formattedValue); ko.bindingHandlers.value.update(element, function () { return formattedValue; }); } }); } }, update: function (element, valueAccessor, allBindingsAccessor) { var value = ko.utils.unwrapObservable(valueAccessor()); var formattedValue = 0; if (typeof value === 'number') { var precision = ko.utils.unwrapObservable(allBindingsAccessor().precision); if (typeof precision === "undefined") { precision = ko.bindingHandlers.numericText.defaultPrecision; } formattedValue = value.toFixed(precision); } ko.bindingHandlers.value.update(element, function () { return formattedValue; }); }, defaultPrecision: 2 };
Whitespace Change - for testing
ko-numericValue.js
Whitespace Change - for testing
Java
bsd-2-clause
b72bda1c7568f383715dc078d1affb752317fa9a
0
Sethtroll/runelite,runelite/runelite,runelite/runelite,abelbriggs1/runelite,l2-/runelite,Sethtroll/runelite,abelbriggs1/runelite,abelbriggs1/runelite,runelite/runelite,l2-/runelite
/* * Copyright (c) 2017, Adam <[email protected]> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package net.runelite.client.game; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import com.google.common.eventbus.Subscribe; import java.awt.Color; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import javax.inject.Inject; import javax.inject.Singleton; import lombok.Value; import lombok.extern.slf4j.Slf4j; import net.runelite.api.Client; import static net.runelite.api.Constants.CLIENT_DEFAULT_ZOOM; import net.runelite.api.GameState; import net.runelite.api.ItemComposition; import net.runelite.api.SpritePixels; import net.runelite.api.events.GameStateChanged; import net.runelite.client.callback.ClientThread; import net.runelite.http.api.item.ItemClient; import net.runelite.http.api.item.ItemPrice; import net.runelite.http.api.item.SearchResult; @Singleton @Slf4j public class ItemManager { @Value private static class ImageKey { private final int itemId; private final int itemQuantity; private final boolean stackable; } @Value private static class OutlineKey { private final int itemId; private final int itemQuantity; private final Color outlineColor; } private final Client client; private final ScheduledExecutorService scheduledExecutorService; private final ClientThread clientThread; private final ItemClient itemClient = new ItemClient(); private final LoadingCache<String, SearchResult> itemSearches; private final ConcurrentMap<Integer, ItemPrice> itemPrices = new ConcurrentHashMap<>(); private final LoadingCache<ImageKey, AsyncBufferedImage> itemImages; private final LoadingCache<Integer, ItemComposition> itemCompositions; private final LoadingCache<OutlineKey, BufferedImage> itemOutlines; @Inject public ItemManager(Client client, ScheduledExecutorService executor, ClientThread clientThread) { this.client = client; this.scheduledExecutorService = executor; this.clientThread = clientThread; scheduledExecutorService.scheduleWithFixedDelay(this::loadPrices, 0, 30, TimeUnit.MINUTES); itemSearches = CacheBuilder.newBuilder() .maximumSize(512L) .expireAfterAccess(1, TimeUnit.HOURS) .build(new CacheLoader<String, SearchResult>() { @Override public SearchResult load(String key) throws Exception { return itemClient.search(key); } }); itemImages = CacheBuilder.newBuilder() .maximumSize(128L) .expireAfterAccess(1, TimeUnit.HOURS) .build(new CacheLoader<ImageKey, AsyncBufferedImage>() { @Override public AsyncBufferedImage load(ImageKey key) throws Exception { return loadImage(key.itemId, key.itemQuantity, key.stackable); } }); itemCompositions = CacheBuilder.newBuilder() .maximumSize(1024L) .expireAfterAccess(1, TimeUnit.HOURS) .build(new CacheLoader<Integer, ItemComposition>() { @Override public ItemComposition load(Integer key) throws Exception { return client.getItemDefinition(key); } }); itemOutlines = CacheBuilder.newBuilder() .maximumSize(128L) .expireAfterAccess(1, TimeUnit.HOURS) .build(new CacheLoader<OutlineKey, BufferedImage>() { @Override public BufferedImage load(OutlineKey key) throws Exception { return loadItemOutline(key.itemId, key.itemQuantity, key.outlineColor); } }); } private void loadPrices() { try { ItemPrice[] prices = itemClient.getPrices(); if (prices != null) { itemPrices.clear(); for (ItemPrice price : prices) { itemPrices.put(price.getItem().getId(), price); } } log.debug("Loaded {} prices", itemPrices.size()); } catch (IOException e) { log.warn("error loading prices!", e); } } @Subscribe public void onGameStateChanged(final GameStateChanged event) { if (event.getGameState() == GameState.HOPPING || event.getGameState() == GameState.LOGIN_SCREEN) { itemCompositions.invalidateAll(); } } /** * Look up an item's price * * @param itemId item id * @return item price */ public ItemPrice getItemPrice(int itemId) { itemId = ItemMapping.mapFirst(itemId); return itemPrices.get(itemId); } /** * Look up an item's composition * * @param itemName item name * @return item search result * @throws java.util.concurrent.ExecutionException exception when item * is not found */ public SearchResult searchForItem(String itemName) throws ExecutionException { return itemSearches.get(itemName); } /** * Look up an item's composition * * @param itemId item id * @return item composition */ public ItemComposition getItemComposition(int itemId) { assert client.isClientThread() : "getItemComposition must be called on client thread"; return itemCompositions.getUnchecked(itemId); } /** * Loads item sprite from game, makes transparent, and generates image * * @param itemId * @return */ private AsyncBufferedImage loadImage(int itemId, int quantity, boolean stackable) { AsyncBufferedImage img = new AsyncBufferedImage(36, 32, BufferedImage.TYPE_INT_ARGB); clientThread.invoke(() -> { if (client.getGameState().ordinal() < GameState.LOGIN_SCREEN.ordinal()) { return false; } SpritePixels sprite = client.createItemSprite(itemId, quantity, 1, SpritePixels.DEFAULT_SHADOW_COLOR, stackable ? 1 : 0, false, CLIENT_DEFAULT_ZOOM); if (sprite == null) { return false; } sprite.toBufferedImage(img); img.changed(); return true; }); return img; } /** * Get item sprite image as BufferedImage. * <p> * This method may return immediately with a blank image if not called on the game thread. * The image will be filled in later. If this is used for a UI label/button, it should be added * using AsyncBufferedImage::addTo to ensure it is painted properly * * @param itemId * @return */ public AsyncBufferedImage getImage(int itemId) { return getImage(itemId, 1, false); } /** * Get item sprite image as BufferedImage. * <p> * This method may return immediately with a blank image if not called on the game thread. * The image will be filled in later. If this is used for a UI label/button, it should be added * using AsyncBufferedImage::addTo to ensure it is painted properly * * @param itemId * @param quantity * @return */ public AsyncBufferedImage getImage(int itemId, int quantity, boolean stackable) { try { return itemImages.get(new ImageKey(itemId, quantity, stackable)); } catch (ExecutionException ex) { return null; } } /** * Create item sprite and applies an outline. * * @param itemId item id * @param itemQuantity item quantity * @param outlineColor outline color * @return image */ private BufferedImage loadItemOutline(final int itemId, final int itemQuantity, final Color outlineColor) { final SpritePixels itemSprite = client.createItemSprite(itemId, itemQuantity, 1, 0, 0, true, 710); return itemSprite.toBufferedOutline(outlineColor); } /** * Get item outline with a specific color. * * @param itemId item id * @param itemQuantity item quantity * @param outlineColor outline color * @return image */ public BufferedImage getItemOutline(final int itemId, final int itemQuantity, final Color outlineColor) { try { return itemOutlines.get(new OutlineKey(itemId, itemQuantity, outlineColor)); } catch (ExecutionException e) { return null; } } }
runelite-client/src/main/java/net/runelite/client/game/ItemManager.java
/* * Copyright (c) 2017, Adam <[email protected]> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package net.runelite.client.game; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import com.google.common.eventbus.Subscribe; import java.awt.Color; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import javax.inject.Inject; import javax.inject.Singleton; import lombok.Value; import lombok.extern.slf4j.Slf4j; import net.runelite.api.Client; import static net.runelite.api.Constants.CLIENT_DEFAULT_ZOOM; import net.runelite.api.GameState; import net.runelite.api.ItemComposition; import net.runelite.api.SpritePixels; import net.runelite.api.events.GameStateChanged; import net.runelite.client.callback.ClientThread; import net.runelite.http.api.item.ItemClient; import net.runelite.http.api.item.ItemPrice; import net.runelite.http.api.item.SearchResult; @Singleton @Slf4j public class ItemManager { @Value private static class ImageKey { private final int itemId; private final int itemQuantity; private final boolean stackable; } @Value private static class OutlineKey { private final int itemId; private final int itemQuantity; private final Color outlineColor; } private final Client client; private final ScheduledExecutorService scheduledExecutorService; private final ClientThread clientThread; private final ItemClient itemClient = new ItemClient(); private final LoadingCache<String, SearchResult> itemSearches; private final ConcurrentMap<Integer, ItemPrice> itemPrices = new ConcurrentHashMap<>(); private final LoadingCache<ImageKey, AsyncBufferedImage> itemImages; private final LoadingCache<Integer, ItemComposition> itemCompositions; private final LoadingCache<OutlineKey, BufferedImage> itemOutlines; @Inject public ItemManager(Client client, ScheduledExecutorService executor, ClientThread clientThread) { this.client = client; this.scheduledExecutorService = executor; this.clientThread = clientThread; scheduledExecutorService.scheduleWithFixedDelay(this::loadPrices, 0, 30, TimeUnit.MINUTES); itemSearches = CacheBuilder.newBuilder() .maximumSize(512L) .expireAfterAccess(1, TimeUnit.HOURS) .build(new CacheLoader<String, SearchResult>() { @Override public SearchResult load(String key) throws Exception { return itemClient.search(key); } }); itemImages = CacheBuilder.newBuilder() .maximumSize(128L) .expireAfterAccess(1, TimeUnit.HOURS) .build(new CacheLoader<ImageKey, AsyncBufferedImage>() { @Override public AsyncBufferedImage load(ImageKey key) throws Exception { return loadImage(key.itemId, key.itemQuantity, key.stackable); } }); itemCompositions = CacheBuilder.newBuilder() .maximumSize(1024L) .expireAfterAccess(1, TimeUnit.HOURS) .build(new CacheLoader<Integer, ItemComposition>() { @Override public ItemComposition load(Integer key) throws Exception { return client.getItemDefinition(key); } }); itemOutlines = CacheBuilder.newBuilder() .maximumSize(128L) .expireAfterAccess(1, TimeUnit.HOURS) .build(new CacheLoader<OutlineKey, BufferedImage>() { @Override public BufferedImage load(OutlineKey key) throws Exception { return loadItemOutline(key.itemId, key.itemQuantity, key.outlineColor); } }); } private void loadPrices() { try { ItemPrice[] prices = itemClient.getPrices(); if (prices != null) { itemPrices.clear(); for (ItemPrice price : prices) { itemPrices.put(price.getItem().getId(), price); } } log.debug("Loaded {} prices", itemPrices.size()); } catch (IOException e) { log.warn("error loading prices!", e); } } @Subscribe public void onGameStateChanged(final GameStateChanged event) { if (event.getGameState() == GameState.HOPPING || event.getGameState() == GameState.LOGIN_SCREEN) { itemCompositions.invalidateAll(); } } /** * Look up an item's price * * @param itemId item id * @return item price */ public ItemPrice getItemPrice(int itemId) { itemId = ItemMapping.mapFirst(itemId); return itemPrices.get(itemId); } /** * Look up an item's composition * * @param itemName item name * @return item search result * @throws java.util.concurrent.ExecutionException exception when item * is not found */ public SearchResult searchForItem(String itemName) throws ExecutionException { return itemSearches.get(itemName); } /** * Look up an item's composition * * @param itemId item id * @return item composition */ public ItemComposition getItemComposition(int itemId) { return itemCompositions.getUnchecked(itemId); } /** * Loads item sprite from game, makes transparent, and generates image * * @param itemId * @return */ private AsyncBufferedImage loadImage(int itemId, int quantity, boolean stackable) { AsyncBufferedImage img = new AsyncBufferedImage(36, 32, BufferedImage.TYPE_INT_ARGB); clientThread.invoke(() -> { if (client.getGameState().ordinal() < GameState.LOGIN_SCREEN.ordinal()) { return false; } SpritePixels sprite = client.createItemSprite(itemId, quantity, 1, SpritePixels.DEFAULT_SHADOW_COLOR, stackable ? 1 : 0, false, CLIENT_DEFAULT_ZOOM); if (sprite == null) { return false; } sprite.toBufferedImage(img); img.changed(); return true; }); return img; } /** * Get item sprite image as BufferedImage. * <p> * This method may return immediately with a blank image if not called on the game thread. * The image will be filled in later. If this is used for a UI label/button, it should be added * using AsyncBufferedImage::addTo to ensure it is painted properly * * @param itemId * @return */ public AsyncBufferedImage getImage(int itemId) { return getImage(itemId, 1, false); } /** * Get item sprite image as BufferedImage. * <p> * This method may return immediately with a blank image if not called on the game thread. * The image will be filled in later. If this is used for a UI label/button, it should be added * using AsyncBufferedImage::addTo to ensure it is painted properly * * @param itemId * @param quantity * @return */ public AsyncBufferedImage getImage(int itemId, int quantity, boolean stackable) { try { return itemImages.get(new ImageKey(itemId, quantity, stackable)); } catch (ExecutionException ex) { return null; } } /** * Create item sprite and applies an outline. * * @param itemId item id * @param itemQuantity item quantity * @param outlineColor outline color * @return image */ private BufferedImage loadItemOutline(final int itemId, final int itemQuantity, final Color outlineColor) { final SpritePixels itemSprite = client.createItemSprite(itemId, itemQuantity, 1, 0, 0, true, 710); return itemSprite.toBufferedOutline(outlineColor); } /** * Get item outline with a specific color. * * @param itemId item id * @param itemQuantity item quantity * @param outlineColor outline color * @return image */ public BufferedImage getItemOutline(final int itemId, final int itemQuantity, final Color outlineColor) { try { return itemOutlines.get(new OutlineKey(itemId, itemQuantity, outlineColor)); } catch (ExecutionException e) { return null; } } }
item manager: assert item composition access is done from client thread
runelite-client/src/main/java/net/runelite/client/game/ItemManager.java
item manager: assert item composition access is done from client thread
<ide><path>unelite-client/src/main/java/net/runelite/client/game/ItemManager.java <ide> */ <ide> public ItemComposition getItemComposition(int itemId) <ide> { <add> assert client.isClientThread() : "getItemComposition must be called on client thread"; <ide> return itemCompositions.getUnchecked(itemId); <ide> } <ide>
Java
lgpl-2.1
026fbb3ca92761cf868b8b80319f0c55727974fb
0
rhusar/wildfly,tadamski/wildfly,jstourac/wildfly,golovnin/wildfly,wildfly/wildfly,rhusar/wildfly,rhusar/wildfly,xasx/wildfly,iweiss/wildfly,tadamski/wildfly,tomazzupan/wildfly,pferraro/wildfly,jstourac/wildfly,pferraro/wildfly,iweiss/wildfly,xasx/wildfly,xasx/wildfly,99sono/wildfly,golovnin/wildfly,wildfly/wildfly,jstourac/wildfly,golovnin/wildfly,rhusar/wildfly,iweiss/wildfly,pferraro/wildfly,99sono/wildfly,jstourac/wildfly,wildfly/wildfly,iweiss/wildfly,99sono/wildfly,wildfly/wildfly,pferraro/wildfly,tadamski/wildfly,tomazzupan/wildfly,tomazzupan/wildfly
/* * JBoss, Home of Professional Open Source. * Copyright 2014, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.security.common; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.CORE_SERVICE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RESULT; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.VAULT; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.VAULT_OPTIONS; import java.io.File; import java.util.Iterator; import java.util.Set; import org.jboss.as.arquillian.api.ServerSetupTask; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.client.OperationBuilder; import org.jboss.as.controller.operations.common.Util; import org.jboss.as.security.vault.VaultSession; import org.jboss.dmr.ModelNode; import org.jboss.logging.Logger; /** * Basic Vault ServerSetupTask which add new vault and store attribute for block "someVaultBlock" and attribute name * "someAttributeName" with attribute value "secretValue" * * @author olukas * */ public class BasicVaultServerSetupTask implements ServerSetupTask { private static Logger LOGGER = Logger.getLogger(BasicVaultServerSetupTask.class); private ModelNode originalVault; private VaultSession nonInteractiveSession; public static final String ATTRIBUTE_NAME = "someAttributeName"; public static final String VAULT_BLOCK = "someVaultBlock"; public static final String VAULT_ATTRIBUTE = "secretValue"; public static final String VAULTED_PROPERTY = "${VAULT::" + VAULT_BLOCK + "::" + ATTRIBUTE_NAME + "::1}"; public static final String VAULT_PASSWORD = "VaultPassword"; public static final String VAULT_ALIAS = "VaultAlias"; static final String KEY_STORE_FILE = "myVault.keystore"; static final String RESOURCE_LOCATION = ""; static final PathAddress VAULT_PATH = PathAddress.pathAddress().append(CORE_SERVICE, VAULT); private VaultHandler vaultHandler; private String externalVaultPassword = null; @Override public void setup(ManagementClient managementClient, String containerId) throws Exception { // clean directory and keystore VaultHandler.cleanFilesystem(RESOURCE_LOCATION, false, KEY_STORE_FILE); // create vault keystore vaultHandler = new VaultHandler(KEY_STORE_FILE, VAULT_PASSWORD, null, RESOURCE_LOCATION, 128, VAULT_ALIAS, "87654321", 20); ModelNode op = new ModelNode(); // save original vault setting LOGGER.info("Saving original vault setting"); op = Util.getReadAttributeOperation(VAULT_PATH, VAULT_OPTIONS); originalVault = (managementClient.getControllerClient().execute(new OperationBuilder(op).build())).get(RESULT); // remove original vault if (originalVault.get("KEYSTORE_URL") != null && originalVault.hasDefined("KEYSTORE_URL")) { op = Util.createRemoveOperation(VAULT_PATH); CoreUtils.applyUpdate(op, managementClient.getControllerClient()); } // create new vault LOGGER.info("Creating new vault"); String keystoreURL = vaultHandler.getKeyStore(); String encryptionDirectory = new File(RESOURCE_LOCATION).getAbsolutePath(); String salt = "87654321"; int iterationCount = 20; nonInteractiveSession = new VaultSession(keystoreURL, VAULT_PASSWORD, encryptionDirectory, salt, iterationCount); nonInteractiveSession.startVaultSession(VAULT_ALIAS); // create security attributes LOGGER.info("Inserting attribute " + VAULT_ATTRIBUTE + " to vault"); nonInteractiveSession.addSecuredAttribute(VAULT_BLOCK, ATTRIBUTE_NAME, VAULT_ATTRIBUTE.toCharArray()); // create new vault setting in standalone op = Util.createAddOperation(VAULT_PATH); ModelNode vaultOption = op.get(VAULT_OPTIONS); vaultOption.get("KEYSTORE_URL").set(keystoreURL); if (externalVaultPassword != null) { vaultOption.get("KEYSTORE_PASSWORD").set(externalVaultPassword); } else { vaultOption.get("KEYSTORE_PASSWORD").set(nonInteractiveSession.getKeystoreMaskedPassword()); } vaultOption.get("KEYSTORE_ALIAS").set(VAULT_ALIAS); vaultOption.get("SALT").set(salt); vaultOption.get("ITERATION_COUNT").set(Integer.toString(iterationCount)); vaultOption.get("ENC_FILE_DIR").set(encryptionDirectory); CoreUtils.applyUpdate(op, managementClient.getControllerClient()); LOGGER.debug("Vault created in server configuration"); } @Override public void tearDown(ManagementClient managementClient, String containerId) throws Exception { ModelNode op; op = Util.createRemoveOperation(VAULT_PATH); CoreUtils.applyUpdate(op, managementClient.getControllerClient()); // set original vault if (originalVault.get("KEYSTORE_URL") != null && originalVault.hasDefined("KEYSTORE_URL")) { Set<String> originalVaultParam = originalVault.keys(); Iterator<String> it = originalVaultParam.iterator(); op = Util.createAddOperation(VAULT_PATH); ModelNode vaultOption = op.get(VAULT_OPTIONS); while (it.hasNext()) { String param = (String) it.next(); vaultOption.get(param).set(originalVault.get(param)); } CoreUtils.applyUpdate(op, managementClient.getControllerClient()); } // remove vault files vaultHandler.cleanUp(); } protected void setExternalVaultPassword(String externalVaultPassword) { this.externalVaultPassword = externalVaultPassword; } }
testsuite/shared/src/main/java/org/jboss/as/test/integration/security/common/BasicVaultServerSetupTask.java
/* * JBoss, Home of Professional Open Source. * Copyright 2014, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.security.common; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.CORE_SERVICE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RESULT; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.VAULT; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.VAULT_OPTIONS; import java.io.File; import java.util.Iterator; import java.util.Set; import org.jboss.as.arquillian.api.ServerSetupTask; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.client.OperationBuilder; import org.jboss.as.controller.operations.common.Util; import org.jboss.as.security.vault.VaultSession; import org.jboss.dmr.ModelNode; import org.jboss.logging.Logger; /** * Basic Vault ServerSetupTask which add new vault and store attribute for block "someVaultBlock" and attribute name * "someAttributeName" with attribute value "secretValue" * * @author olukas * */ public class BasicVaultServerSetupTask implements ServerSetupTask { private static Logger LOGGER = Logger.getLogger(BasicVaultServerSetupTask.class); private ModelNode originalVault; private VaultSession nonInteractiveSession; public static final String ATTRIBUTE_NAME = "someAttributeName"; public static final String VAULT_BLOCK = "someVaultBlock"; public static final String VAULT_ATTRIBUTE = "secretValue"; public static final String VAULTED_PROPERTY = "${VAULT::" + VAULT_BLOCK + "::" + ATTRIBUTE_NAME + "::1}"; public static final String VAULT_PASSWORD = "VaultPassword"; public static final String VAULT_ALIAS = "VaultAlias"; static final String KEY_STORE_FILE = "myVault.keystore"; static final String RESOURCE_LOCATION = ""; static final PathAddress VAULT_PATH = PathAddress.pathAddress().append(CORE_SERVICE, VAULT); private VaultHandler vaultHandler; private String externalVaultPassword = null; @Override public void setup(ManagementClient managementClient, String containerId) throws Exception { // clean directory and keystore VaultHandler.cleanFilesystem(RESOURCE_LOCATION, false, KEY_STORE_FILE); // create vault keystore vaultHandler = new VaultHandler(KEY_STORE_FILE, VAULT_PASSWORD, null, RESOURCE_LOCATION, 128, VAULT_ALIAS, "87654321", 20); ModelNode op = new ModelNode(); // save original vault setting LOGGER.info("Saving original vault setting"); op = Util.getReadAttributeOperation(VAULT_PATH, VAULT_OPTIONS); originalVault = (managementClient.getControllerClient().execute(new OperationBuilder(op).build())).get(RESULT); // remove original vault if (originalVault.get("KEYSTORE_URL") != null && originalVault.hasDefined("KEYSTORE_URL")) { op = Util.createRemoveOperation(VAULT_PATH); CoreUtils.applyUpdate(op, managementClient.getControllerClient()); } // create new vault LOGGER.info("Creating new vault"); String keystoreURL = vaultHandler.getKeyStore(); String encryptionDirectory = new File(RESOURCE_LOCATION).getAbsolutePath(); String salt = "87654321"; int iterationCount = 20; nonInteractiveSession = new VaultSession(keystoreURL, VAULT_PASSWORD, encryptionDirectory, salt, iterationCount); nonInteractiveSession.startVaultSession(VAULT_ALIAS); // create security attributes LOGGER.info("Inserting attribute " + VAULT_ATTRIBUTE + " to vault"); nonInteractiveSession.addSecuredAttribute(VAULT_BLOCK, ATTRIBUTE_NAME, VAULT_ATTRIBUTE.toCharArray()); // create new vault setting in standalone op = Util.createAddOperation(VAULT_PATH); ModelNode vaultOption = op.get(VAULT_OPTIONS); vaultOption.get("KEYSTORE_URL").set(keystoreURL); if (externalVaultPassword != null) { vaultOption.get("KEYSTORE_PASSWORD").set(externalVaultPassword); } else { vaultOption.get("KEYSTORE_PASSWORD").set(nonInteractiveSession.getKeystoreMaskedPassword()); } vaultOption.get("KEYSTORE_ALIAS").set(VAULT_ALIAS); vaultOption.get("SALT").set(salt); vaultOption.get("ITERATION_COUNT").set(Integer.toString(iterationCount)); vaultOption.get("ENC_FILE_DIR").set(encryptionDirectory); CoreUtils.applyUpdate(op, managementClient.getControllerClient()); LOGGER.debug("Vault created in server configuration"); } @Override public void tearDown(ManagementClient managementClient, String containerId) throws Exception { ModelNode op; op = Util.createRemoveOperation(VAULT_PATH); CoreUtils.applyUpdate(op, managementClient.getControllerClient()); // set original vault if (originalVault.get("KEYSTORE_URL") != null && originalVault.hasDefined("KEYSTORE_URL")) { Set<String> originalVaultParam = originalVault.keys(); Iterator<String> it = originalVaultParam.iterator(); op = Util.createAddOperation(VAULT_PATH); ModelNode vaultOption = op.get(VAULT_OPTIONS); while (it.hasNext()) { String param = (String) it.next(); vaultOption.get(param).set(originalVault.get(param)); } CoreUtils.applyUpdate(op, managementClient.getControllerClient()); } // remove vault files vaultHandler.cleanUp(); } }
[BZ1124086] Fix for BasicVaultServerSetupTask
testsuite/shared/src/main/java/org/jboss/as/test/integration/security/common/BasicVaultServerSetupTask.java
[BZ1124086] Fix for BasicVaultServerSetupTask
<ide><path>estsuite/shared/src/main/java/org/jboss/as/test/integration/security/common/BasicVaultServerSetupTask.java <ide> // remove vault files <ide> vaultHandler.cleanUp(); <ide> } <add> <add> protected void setExternalVaultPassword(String externalVaultPassword) { <add> this.externalVaultPassword = externalVaultPassword; <add> } <ide> }
JavaScript
mit
5754dfa79b5abd38491369cf812a19e3a4912775
0
nahuelio/boneyard,3dimention/boneyard,3dimention/spinal
/** * @module com.spinal.util * @author Patricio Ferreira <[email protected]> **/ define(['core/spinal'], function(Spinal) { /** * Define a Generic Schema definition structure to validate and parse model data * @namespace com.spinal.util * @class com.spinal.util.Schema * @extends com.spinal.core.SpinalClass **/ var Schema = Spinal.namespace('com.spinal.util.Schema', Spinal.SpinalClass.inherit({ /** * Initialize * @public * @chainable * @method initialize * @return {com.spinal.mvc.Model} **/ initialize: function() { return Schema.__super__.initialize.apply(this, arguments); }, /** * Schema Set checks schema data types before taking the properties * @public * @method parse * @param key {Object} Key String or Object (hashmap) to be set as properties. * @param value {Object} Value to be set for the key property specified in p * @return Object **/ parse: function(key, value, options) { var attrs = {}; if(_.isObject(key)) { attrs = key; options = value; } if(_.isString(key)) attrs[key] = value; _.each(attrs, _.bind(function(v, k) { var m = ('_' + attrs[k]); attrs[v] = (attrs[k] && this[m]) ? this[m](v) : v; }, this)); return attrs; }, /** * Boolean data type parser * @private * @method _boolean * @param value {Object} value to be transform * @return Boolean **/ _boolean: function(value) { return (value === 'true') ? true : (value === 'false') ? false : value; }, /** * Integer data type parser * @private * @method _int * @param value {Object} value to be transform * @return Number **/ _int: function(value) { return parseInt(value, 10); }, /** * Float data type parser * @private * @method _float * @param value {Object} value to be transform * @return Number **/ _float: function(value) { return parseFloat(value); }, /** * String data type parser * @private * @method _string * @param value {Object} value to be transform * @return String **/ _string: function(value) { return value.toString(); } }, { /** * @static * @property NAME * @type String **/ NAME: 'Schema' })); return Schema; });
src/com/spinal/util/schema.js
/** * @module com.spinal.util * @author Patricio Ferreira <[email protected]> **/ define(['core/spinal'], function(Spinal) { // TODO: Review the implementation of this /** * Define a generic model structure based on Backbone.Model * @namespace com.spinal.mvc * @class com.spinal.mvc.Model * @extends Spinal.Backbone.Model **/ var Model = Spinal.namespace('com.spinal.util.Model', Spinal.Backbone.Model.inherit({ /** * Model Schema * @public * @property schema * @type Object **/ schema: null, /** * Initialize * @public * @chainable * @method initialize * @return {com.spinal.mvc.Model} **/ initialize: function(opts) { opts || (opts = {}); this.schema = (opts.schema) ? opts.schema : {}; Model.__super__.initialize.apply(this, arguments); return this; }, /** * Model Set checks schema data types before taking the properties * @public * @method set * @param key {Object} Key String or Object (hashmap) to be set as properties. * @param val {Object} Value to be set for the key property specified in p * @return Object **/ set: function(key, val, options) { var attrs; if(typeof key === 'object') { attrs = key; options = val; } else { (attrs = {})[key] = val; } _.each(attrs, _.bind(function(v, k) { try { switch (this.schema[k]) { case 'boolean': attrs[k] = v === 'true' ? true : v === 'false' ? false : v; break; case 'int': attrs[k] = parseInt(v, 10); break; case 'float': attrs[k] = parseFloat(v); break; case 'string': attrs[k] = v.toString(); break; default: attrs[k] = v; break; } } catch (ex) { // Throw a custom exception ??? } }, this)); return Model.__super__.set.apply(this, [attrs, options]); }, /** * String representation of an instance of this class * @public * @method toString * @return String **/ toString: function() { return '[object Model]'; } }, { /** * @static * @property NAME * @type String **/ NAME: 'Model' })); return Model; });
Added Schema class to the util package.
src/com/spinal/util/schema.js
Added Schema class to the util package.
<ide><path>rc/com/spinal/util/schema.js <ide> **/ <ide> define(['core/spinal'], function(Spinal) { <ide> <del> // TODO: Review the implementation of this <ide> /** <del> * Define a generic model structure based on Backbone.Model <del> * @namespace com.spinal.mvc <del> * @class com.spinal.mvc.Model <del> * @extends Spinal.Backbone.Model <add> * Define a Generic Schema definition structure to validate and parse model data <add> * @namespace com.spinal.util <add> * @class com.spinal.util.Schema <add> * @extends com.spinal.core.SpinalClass <ide> **/ <del> var Model = Spinal.namespace('com.spinal.util.Model', Spinal.Backbone.Model.inherit({ <del> <del> /** <del> * Model Schema <del> * @public <del> * @property schema <del> * @type Object <del> **/ <del> schema: null, <add> var Schema = Spinal.namespace('com.spinal.util.Schema', Spinal.SpinalClass.inherit({ <ide> <ide> /** <ide> * Initialize <ide> * @method initialize <ide> * @return {com.spinal.mvc.Model} <ide> **/ <del> initialize: function(opts) { <del> opts || (opts = {}); <del> this.schema = (opts.schema) ? opts.schema : {}; <del> Model.__super__.initialize.apply(this, arguments); <del> return this; <add> initialize: function() { <add> return Schema.__super__.initialize.apply(this, arguments); <ide> }, <ide> <ide> /** <del> * Model Set checks schema data types before taking the properties <add> * Schema Set checks schema data types before taking the properties <ide> * @public <del> * @method set <add> * @method parse <ide> * @param key {Object} Key String or Object (hashmap) to be set as properties. <del> * @param val {Object} Value to be set for the key property specified in p <add> * @param value {Object} Value to be set for the key property specified in p <ide> * @return Object <ide> **/ <del> set: function(key, val, options) { <del> var attrs; <del> if(typeof key === 'object') { <del> attrs = key; options = val; <del> } else { <del> (attrs = {})[key] = val; <del> } <add> parse: function(key, value, options) { <add> var attrs = {}; <add> if(_.isObject(key)) { attrs = key; options = value; } <add> if(_.isString(key)) attrs[key] = value; <ide> _.each(attrs, _.bind(function(v, k) { <del> try { <del> switch (this.schema[k]) { <del> case 'boolean': <del> attrs[k] = v === 'true' ? true : v === 'false' ? false : v; <del> break; <del> case 'int': <del> attrs[k] = parseInt(v, 10); <del> break; <del> case 'float': <del> attrs[k] = parseFloat(v); <del> break; <del> case 'string': <del> attrs[k] = v.toString(); <del> break; <del> default: <del> attrs[k] = v; <del> break; <del> } <del> } catch (ex) { <del> // Throw a custom exception ??? <del> } <add> var m = ('_' + attrs[k]); <add> attrs[v] = (attrs[k] && this[m]) ? this[m](v) : v; <ide> }, this)); <del> return Model.__super__.set.apply(this, [attrs, options]); <add> return attrs; <ide> }, <ide> <ide> /** <del> * String representation of an instance of this class <del> * @public <del> * @method toString <add> * Boolean data type parser <add> * @private <add> * @method _boolean <add> * @param value {Object} value to be transform <add> * @return Boolean <add> **/ <add> _boolean: function(value) { <add> return (value === 'true') ? true : (value === 'false') ? false : value; <add> }, <add> <add> /** <add> * Integer data type parser <add> * @private <add> * @method _int <add> * @param value {Object} value to be transform <add> * @return Number <add> **/ <add> _int: function(value) { <add> return parseInt(value, 10); <add> }, <add> <add> /** <add> * Float data type parser <add> * @private <add> * @method _float <add> * @param value {Object} value to be transform <add> * @return Number <add> **/ <add> _float: function(value) { <add> return parseFloat(value); <add> }, <add> <add> /** <add> * String data type parser <add> * @private <add> * @method _string <add> * @param value {Object} value to be transform <ide> * @return String <ide> **/ <del> toString: function() { <del> return '[object Model]'; <add> _string: function(value) { <add> return value.toString(); <ide> } <ide> <ide> }, { <ide> * @property NAME <ide> * @type String <ide> **/ <del> NAME: 'Model' <add> NAME: 'Schema' <ide> <ide> })); <ide> <del> return Model; <add> return Schema; <ide> <ide> });
Java
apache-2.0
e74a80de930c36e4af8729c4577f95195bdc8b84
0
naver/ngrinder,naver/ngrinder,naver/ngrinder,naver/ngrinder,naver/ngrinder
/* * Copyright (c) 2012-present NAVER Corp. * * This file is part of The nGrinder software distribution. Refer to * the file LICENSE which is part of The nGrinder distribution for * licensing details. The nGrinder distribution is available on the * Internet at https://naver.github.io/ngrinder * * 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.grinder.scriptengine.groovy; import net.grinder.common.GrinderProperties; import net.grinder.engine.common.EngineException; import net.grinder.engine.common.ScriptLocation; import net.grinder.scriptengine.DCRContext; import net.grinder.scriptengine.Instrumenter; import net.grinder.scriptengine.ScriptEngineService; import net.grinder.util.FileExtensionMatcher; import java.util.List; import static java.util.Collections.emptyList; /** * Groovy script engine service. * * @author Mavlarn * @since 3.0 */ public class GroovyScriptEngineService implements ScriptEngineService { private final FileExtensionMatcher m_groovyFileMatcher = new FileExtensionMatcher(".groovy"); @SuppressWarnings("unused") private final boolean m_forceDCRInstrumentation; /** * Constructor. * * @param properties Properties. * @param dcrContext DCR context. * @param scriptLocation Script location. */ public GroovyScriptEngineService(GrinderProperties properties, DCRContext dcrContext, ScriptLocation scriptLocation) { // This property name is poor, since it really means "If DCR // instrumentation is available, avoid the traditional Jython // instrumenter". I'm not renaming it, since I expect it only to last // a few releases, until DCR becomes the default. m_forceDCRInstrumentation = properties.getBoolean("grinder.dcrinstrumentation", false) // Hack: force DCR instrumentation for non-Jython scripts. || m_groovyFileMatcher.accept(scriptLocation.getFile()); } /** * Constructor used when DCR is unavailable. */ public GroovyScriptEngineService() { m_forceDCRInstrumentation = false; } /** * {@inheritDoc} */ @Override public List<Instrumenter> createInstrumenters() { return emptyList(); } /** * {@inheritDoc} */ @Override public ScriptEngine createScriptEngine(ScriptLocation script) throws EngineException { if (m_groovyFileMatcher.accept(script.getFile())) { return new GroovyScriptEngine(script); } return null; } }
ngrinder-groovy/src/main/java/net/grinder/scriptengine/groovy/GroovyScriptEngineService.java
/* * Copyright (c) 2012-present NAVER Corp. * * This file is part of The nGrinder software distribution. Refer to * the file LICENSE which is part of The nGrinder distribution for * licensing details. The nGrinder distribution is available on the * Internet at https://naver.github.io/ngrinder * * 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.grinder.scriptengine.groovy; import net.grinder.common.GrinderProperties; import net.grinder.engine.common.EngineException; import net.grinder.engine.common.ScriptLocation; import net.grinder.engine.process.JavaDCRInstrumenterEx; import net.grinder.scriptengine.DCRContext; import net.grinder.scriptengine.Instrumenter; import net.grinder.scriptengine.ScriptEngineService; import net.grinder.util.FileExtensionMatcher; import java.util.ArrayList; import java.util.List; /** * Groovy script engine service. * * @author Mavlarn * @since 3.0 */ public class GroovyScriptEngineService implements ScriptEngineService { private final FileExtensionMatcher m_groovyFileMatcher = new FileExtensionMatcher(".groovy"); @SuppressWarnings("unused") private final boolean m_forceDCRInstrumentation; private final DCRContext m_dcrContext; /** * Constructor. * * @param properties Properties. * @param dcrContext DCR context. * @param scriptLocation Script location. */ public GroovyScriptEngineService(GrinderProperties properties, // DCRContext dcrContext, ScriptLocation scriptLocation) { // This property name is poor, since it really means "If DCR // instrumentation is available, avoid the traditional Jython // instrumenter". I'm not renaming it, since I expect it only to last // a few releases, until DCR becomes the default. m_forceDCRInstrumentation = properties.getBoolean("grinder.dcrinstrumentation", false) // Hack: force DCR instrumentation for non-Jython scripts. || m_groovyFileMatcher.accept(scriptLocation.getFile()); m_dcrContext = dcrContext; } /** * Constructor used when DCR is unavailable. */ public GroovyScriptEngineService() { m_dcrContext = null; m_forceDCRInstrumentation = false; } /** * {@inheritDoc} */ @Override public List<Instrumenter> createInstrumenters() { final List<Instrumenter> instrumenters = new ArrayList<>(); /* * if (!m_forceDCRInstrumentation) { * System.out.println("m_forceDCRInstrumentation is false."); // must using Instrumentation * } */ if (m_dcrContext != null) { instrumenters.add(new JavaDCRInstrumenterEx(m_dcrContext)); } return instrumenters; } /** * {@inheritDoc} */ @Override public ScriptEngine createScriptEngine(ScriptLocation script) throws EngineException { if (m_groovyFileMatcher.accept(script.getFile())) { return new GroovyScriptEngine(script); } return null; } }
Make groovy engine service always delegate instrumentation
ngrinder-groovy/src/main/java/net/grinder/scriptengine/groovy/GroovyScriptEngineService.java
Make groovy engine service always delegate instrumentation
<ide><path>grinder-groovy/src/main/java/net/grinder/scriptengine/groovy/GroovyScriptEngineService.java <ide> import net.grinder.common.GrinderProperties; <ide> import net.grinder.engine.common.EngineException; <ide> import net.grinder.engine.common.ScriptLocation; <del>import net.grinder.engine.process.JavaDCRInstrumenterEx; <ide> import net.grinder.scriptengine.DCRContext; <ide> import net.grinder.scriptengine.Instrumenter; <ide> import net.grinder.scriptengine.ScriptEngineService; <ide> import net.grinder.util.FileExtensionMatcher; <ide> <del>import java.util.ArrayList; <ide> import java.util.List; <add> <add>import static java.util.Collections.emptyList; <ide> <ide> /** <ide> * Groovy script engine service. <ide> <ide> @SuppressWarnings("unused") <ide> private final boolean m_forceDCRInstrumentation; <del> private final DCRContext m_dcrContext; <ide> <ide> /** <ide> * Constructor. <ide> * <del> * @param properties Properties. <del> * @param dcrContext DCR context. <del> * @param scriptLocation Script location. <add> * @param properties Properties. <add> * @param dcrContext DCR context. <add> * @param scriptLocation Script location. <ide> */ <del> public GroovyScriptEngineService(GrinderProperties properties, // <del> DCRContext dcrContext, ScriptLocation scriptLocation) { <del> <add> public GroovyScriptEngineService(GrinderProperties properties, DCRContext dcrContext, ScriptLocation scriptLocation) { <ide> // This property name is poor, since it really means "If DCR <ide> // instrumentation is available, avoid the traditional Jython <ide> // instrumenter". I'm not renaming it, since I expect it only to last <ide> // a few releases, until DCR becomes the default. <ide> m_forceDCRInstrumentation = properties.getBoolean("grinder.dcrinstrumentation", false) <del> // Hack: force DCR instrumentation for non-Jython scripts. <del> || m_groovyFileMatcher.accept(scriptLocation.getFile()); <del> <del> m_dcrContext = dcrContext; <add> // Hack: force DCR instrumentation for non-Jython scripts. <add> || m_groovyFileMatcher.accept(scriptLocation.getFile()); <ide> } <ide> <ide> /** <ide> * Constructor used when DCR is unavailable. <ide> */ <ide> public GroovyScriptEngineService() { <del> m_dcrContext = null; <ide> m_forceDCRInstrumentation = false; <ide> } <ide> <ide> */ <ide> @Override <ide> public List<Instrumenter> createInstrumenters() { <del> <del> final List<Instrumenter> instrumenters = new ArrayList<>(); <del> <del> /* <del> * if (!m_forceDCRInstrumentation) { <del> * System.out.println("m_forceDCRInstrumentation is false."); // must using Instrumentation <del> * } <del> */ <del> if (m_dcrContext != null) { <del> instrumenters.add(new JavaDCRInstrumenterEx(m_dcrContext)); <del> } <del> <del> return instrumenters; <add> return emptyList(); <ide> } <ide> <ide> /**
Java
apache-2.0
33866f58847ed25d1583776f2b0f8242d63e7232
0
ysc/superword,ysc/superword,ysc/superword
/* * APDPlat - Application Product Development Platform * Copyright (c) 2013, 杨尚川, [email protected] * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.apdplat.superword.tools; import org.apdplat.superword.model.Word; import org.apdplat.superword.tools.WordLinker.Dictionary; import org.apdplat.word.WordSegmenter; import org.apdplat.word.segmentation.SegmentationAlgorithm; import java.io.IOException; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; /** * 辅助阅读: * 以电影功夫熊猫使用的单词分析为例 * 你英语四级过了吗? 功夫熊猫看了吗? * 去除停用词后,功夫熊猫使用了789个英语单词,你会说很简单吧,别急,这些单词中仍然有148个单词不在四级词汇表中,花两分钟时间看看你是否认识这些单词. * Created by ysc on 11/15/15. */ public class AidReading { private static final Set<Word> STOP_WORDS = WordSources.get("/word_stop.txt"); public static void main(String[] args) throws IOException { WordLinker.serverRedirect = null; String result = analyse(WordSources.get("/word_CET4.txt"), Dictionary.ICIBA, 6, "/it/movie/kungfupanda.txt"); //String result = analyse(WordSources.get("/word_CET4.txt"), Dictionary.ICIBA, 6, "/it/movie/kungfupanda.txt", "/it/movie/kungfupanda2.txt"); /* String url = "http://spark.apache.org/docs/latest/streaming-programming-guide.html"; String text = Jsoup.parse(new URL(url), 60000).text(); System.out.println(text); String result = analyse(WordSources.get("/word_CET4.txt"), Dictionary.ICIBA, 6, false, null, Arrays.asList(text)); */ System.out.println(result); } public static String analyse(Set<Word> words, Dictionary dictionary, int column, String... resources) { return analyse(words, dictionary, column, false, null, resources); } public static String analyse(Set<Word> words, Dictionary dictionary, int column, boolean searchOriginalText, String book, String... resources) { List<String> text = new ArrayList<>(); for(String resource : resources) { text.addAll(FileUtils.readResource(resource)); } return analyse(words, dictionary, column, searchOriginalText, book, text); } public static String analyse(Set<Word> words, Dictionary dictionary, int column, boolean searchOriginalText, String book, List<String> text) { Set<String> wordSet = new HashSet<>(); words.forEach(word -> wordSet.add(word.getWord().toLowerCase())); StringBuilder result = new StringBuilder(); Map<String, AtomicInteger> map = new ConcurrentHashMap<>(); text.forEach(line -> { StringBuilder buffer = new StringBuilder(); line = line.replaceAll("[^a-zA-Z0-9]*[a-zA-Z0-9]+'[a-zA-Z0-9]+[^a-zA-Z0-9]*", " ") .replaceAll("[^a-zA-Z0-9]*[a-zA-Z0-9]+`[a-zA-Z0-9]+[^a-zA-Z0-9]*", " "); for (org.apdplat.word.segmentation.Word term : WordSegmenter.segWithStopWords(line, SegmentationAlgorithm.PureEnglish)) { String word = term.getText(); if (word.contains("'")) { continue; } buffer.setLength(0); for (char c : word.toCharArray()) { if (Character.isAlphabetic(c)) { buffer.append(Character.toLowerCase(c)); } } String baseForm = IrregularVerbs.getBaseForm(buffer.toString()); buffer.setLength(0); buffer.append(baseForm); String singular = IrregularPlurals.getSingular(buffer.toString()); buffer.setLength(0); buffer.append(singular); if (buffer.length() < 2 || buffer.length() > 14) { continue; } if (STOP_WORDS.contains(new Word(buffer.toString().toLowerCase(), ""))) { continue; } map.putIfAbsent(buffer.toString(), new AtomicInteger()); map.get(buffer.toString()).incrementAndGet(); } }); List<String> list = new ArrayList<>(); Map<String, AtomicInteger> map2 = new ConcurrentHashMap<>(); map.entrySet().stream().sorted((a, b) -> b.getValue().get() - a.getValue().get()).forEach(entry -> { AtomicInteger v = entry.getValue(); String w = entry.getKey().toLowerCase(); if(w.length() < 3){ return; } if (wordSet.contains(w)) { map2.put(w, v); return; } if (w.endsWith("ly") && wordSet.contains(w.substring(0, w.length() - 2))) { map2.put(w+"_"+w.substring(0, w.length() - 2), v); return; } if (w.endsWith("s") && wordSet.contains(w.substring(0, w.length() - 1))) { map2.put(w+"_"+w.substring(0, w.length() - 1), v); return; } if (w.endsWith("es") && wordSet.contains(w.substring(0, w.length() - 2))) { map2.put(w+"_"+w.substring(0, w.length() - 2), v); return; } if (w.endsWith("ies") && wordSet.contains(w.substring(0, w.length() - 3)+"y")) { map2.put(w+"_"+w.substring(0, w.length() - 3)+"y", v); return; } if (w.endsWith("ed") && wordSet.contains(w.substring(0, w.length() - 1))) { map2.put(w+"_"+w.substring(0, w.length() - 1), v); return; } if (w.endsWith("ed") && wordSet.contains(w.substring(0, w.length() - 2))) { map2.put(w+"_"+w.substring(0, w.length() - 2), v); return; } if (w.endsWith("ed") && w.length()>5 && wordSet.contains(w.substring(0, w.length() - 3)) && (w.charAt(w.length()-3)==w.charAt(w.length()-4))) { map2.put(w+"_"+w.substring(0, w.length() - 3), v); return; } if (w.endsWith("ied") && wordSet.contains(w.substring(0, w.length() - 3)+"y")) { map2.put(w+"_"+w.substring(0, w.length() - 3)+"y", v); return; } if (w.endsWith("ing") && wordSet.contains(w.substring(0, w.length() - 3))) { map2.put(w+"_"+w.substring(0, w.length() - 3), v); return; } if (w.endsWith("ing") && wordSet.contains(w.substring(0, w.length() - 3)+"e")) { map2.put(w+"_"+w.substring(0, w.length() - 3)+"e", v); return; } if (w.endsWith("ing") && w.length()>6 && wordSet.contains(w.substring(0, w.length() - 4)) && (w.charAt(w.length()-4)==w.charAt(w.length()-5))) { map2.put(w+"_"+w.substring(0, w.length() - 4), v); return; } if (w.endsWith("er") && wordSet.contains(w.substring(0, w.length() - 1))) { map2.put(w+"_"+w.substring(0, w.length() - 1), v); return; } if (w.endsWith("er") && wordSet.contains(w.substring(0, w.length() - 2))) { map2.put(w+"_"+w.substring(0, w.length() - 2), v); return; } if (w.endsWith("er") && w.length()>5 && wordSet.contains(w.substring(0, w.length() - 3)) && (w.charAt(w.length()-3)==w.charAt(w.length()-4))) { map2.put(w+"_"+w.substring(0, w.length() - 3), v); return; } if (w.endsWith("est") && wordSet.contains(w.substring(0, w.length() - 2))) { map2.put(w+"_"+w.substring(0, w.length() - 2), v); return; } if (w.endsWith("est") && wordSet.contains(w.substring(0, w.length() - 3))) { map2.put(w+"_"+w.substring(0, w.length() - 3), v); return; } if (w.endsWith("est") && w.length()>6 && wordSet.contains(w.substring(0, w.length() - 4)) && (w.charAt(w.length()-4)==w.charAt(w.length()-5))) { map2.put(w+"_"+w.substring(0, w.length() - 4), v); return; } if (w.endsWith("ier") && wordSet.contains(w.substring(0, w.length() - 3)+"y")) { map2.put(w+"_"+w.substring(0, w.length() - 3)+"y", v); return; } if (w.endsWith("iest") && wordSet.contains(w.substring(0, w.length() - 4)+"y")) { map2.put(w+"_"+w.substring(0, w.length() - 4)+"y", v); return; } if (w.endsWith("ves") && wordSet.contains(w.substring(0, w.length() - 3)+"f")) { map2.put(w+"_"+w.substring(0, w.length() - 3)+"f", v); return; } String originalText = ""; if(searchOriginalText){ originalText = "\t<a target=\"_blank\" href=\"aid-reading-detail.jsp?book="+book+"&word="+entry.getKey()+"&dict=ICIBA&pageSize="+entry.getValue()+"\">[" + entry.getValue() + "]</a>"; }else{ originalText = "\t[" + entry.getValue() + "]"; } list.add(WordLinker.toLink(entry.getKey(), dictionary) + originalText); }); result.append("<h3>words don't occur in specified set: ("+list.size()+") </h3>\n"); result.append(HtmlFormatter.toHtmlTableFragment(list, column)); list.clear(); map2.entrySet().stream().sorted((a, b) -> b.getValue().get() - a.getValue().get()).forEach(entry -> { String originalText = ""; if (searchOriginalText) { originalText = "\t<a target=\"_blank\" href=\"aid-reading-detail.jsp?book=" + book + "&word=" + entry.getKey() + "&dict=ICIBA&pageSize=" + entry.getValue() + "\">[" + entry.getValue() + "]</a>"; } else { originalText = "\t[" + entry.getValue() + "]"; } StringBuilder link = new StringBuilder(); for (String word : entry.getKey().split("_")) { link.append(WordLinker.toLink(word, dictionary)).append(" | "); } link.setLength(link.length()-3); list.add(link.toString() + originalText); }); result.append("<h3>words occur in specified set: (" + list.size() + ") </h3>\n"); result.append(HtmlFormatter.toHtmlTableFragment(list, column)); return result.toString(); } }
src/main/java/org/apdplat/superword/tools/AidReading.java
/* * APDPlat - Application Product Development Platform * Copyright (c) 2013, 杨尚川, [email protected] * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.apdplat.superword.tools; import org.apdplat.superword.model.Word; import org.apdplat.superword.tools.WordLinker.Dictionary; import org.apdplat.word.WordSegmenter; import org.apdplat.word.segmentation.SegmentationAlgorithm; import java.io.IOException; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; /** * 辅助阅读: * 以电影功夫熊猫使用的单词分析为例 * 你英语四级过了吗? 功夫熊猫看了吗? * 去除停用词后,功夫熊猫使用了794个英语单词,你会说很简单吧,别急,这些单词中仍然有148个单词不在四级词汇表中,花两分钟时间看看你是否认识这些单词. * Created by ysc on 11/15/15. */ public class AidReading { private static final Set<Word> STOP_WORDS = WordSources.get("/word_stop.txt"); public static void main(String[] args) throws IOException { WordLinker.serverRedirect = null; String result = analyse(WordSources.get("/word_CET4.txt"), Dictionary.ICIBA, 6, "/it/movie/kungfupanda.txt"); //String result = analyse(WordSources.get("/word_CET4.txt"), Dictionary.ICIBA, 6, "/it/movie/kungfupanda.txt", "/it/movie/kungfupanda2.txt"); /* String url = "http://spark.apache.org/docs/latest/streaming-programming-guide.html"; String text = Jsoup.parse(new URL(url), 60000).text(); System.out.println(text); String result = analyse(WordSources.get("/word_CET4.txt"), Dictionary.ICIBA, 6, false, null, Arrays.asList(text)); */ System.out.println(result); } public static String analyse(Set<Word> words, Dictionary dictionary, int column, String... resources) { return analyse(words, dictionary, column, false, null, resources); } public static String analyse(Set<Word> words, Dictionary dictionary, int column, boolean searchOriginalText, String book, String... resources) { List<String> text = new ArrayList<>(); for(String resource : resources) { text.addAll(FileUtils.readResource(resource)); } return analyse(words, dictionary, column, searchOriginalText, book, text); } public static String analyse(Set<Word> words, Dictionary dictionary, int column, boolean searchOriginalText, String book, List<String> text) { Set<String> wordSet = new HashSet<>(); words.forEach(word -> wordSet.add(word.getWord().toLowerCase())); StringBuilder result = new StringBuilder(); Map<String, AtomicInteger> map = new ConcurrentHashMap<>(); text.forEach(line -> { StringBuilder buffer = new StringBuilder(); line = line.replaceAll("[^a-zA-Z0-9]*[a-zA-Z0-9]+'[a-zA-Z0-9]+[^a-zA-Z0-9]*", " ") .replaceAll("[^a-zA-Z0-9]*[a-zA-Z0-9]+`[a-zA-Z0-9]+[^a-zA-Z0-9]*", " "); for (org.apdplat.word.segmentation.Word term : WordSegmenter.segWithStopWords(line, SegmentationAlgorithm.PureEnglish)) { String word = term.getText(); if (word.contains("'")) { continue; } buffer.setLength(0); for (char c : word.toCharArray()) { if (Character.isAlphabetic(c)) { buffer.append(Character.toLowerCase(c)); } } String baseForm = IrregularVerbs.getBaseForm(buffer.toString()); buffer.setLength(0); buffer.append(baseForm); String singular = IrregularPlurals.getSingular(buffer.toString()); buffer.setLength(0); buffer.append(singular); if (buffer.length() < 2 || buffer.length() > 14) { continue; } if (STOP_WORDS.contains(new Word(buffer.toString().toLowerCase(), ""))) { continue; } map.putIfAbsent(buffer.toString(), new AtomicInteger()); map.get(buffer.toString()).incrementAndGet(); } }); List<String> list = new ArrayList<>(); map.entrySet().stream().sorted((a, b) -> b.getValue().get() - a.getValue().get()).forEach(entry -> { String w = entry.getKey().toLowerCase(); if(w.length() < 3){ return; } if (wordSet.contains(w)) { return; } if (w.endsWith("ly") && wordSet.contains(w.substring(0, w.length() - 2))) { return; } if (w.endsWith("s") && wordSet.contains(w.substring(0, w.length() - 1))) { return; } if (w.endsWith("es") && wordSet.contains(w.substring(0, w.length() - 2))) { return; } if (w.endsWith("ies") && wordSet.contains(w.substring(0, w.length() - 3)+"y")) { return; } if (w.endsWith("ed") && wordSet.contains(w.substring(0, w.length() - 1))) { return; } if (w.endsWith("ed") && wordSet.contains(w.substring(0, w.length() - 2))) { return; } if (w.endsWith("ed") && w.length()>5 && wordSet.contains(w.substring(0, w.length() - 3)) && (w.charAt(w.length()-3)==w.charAt(w.length()-4))) { return; } if (w.endsWith("ied") && wordSet.contains(w.substring(0, w.length() - 3)+"y")) { return; } if (w.endsWith("ing") && wordSet.contains(w.substring(0, w.length() - 3))) { return; } if (w.endsWith("ing") && wordSet.contains(w.substring(0, w.length() - 3)+"e")) { return; } if (w.endsWith("ing") && w.length()>6 && wordSet.contains(w.substring(0, w.length() - 4)) && (w.charAt(w.length()-4)==w.charAt(w.length()-5))) { return; } if (w.endsWith("er") && wordSet.contains(w.substring(0, w.length() - 1))) { return; } if (w.endsWith("er") && wordSet.contains(w.substring(0, w.length() - 2))) { return; } if (w.endsWith("er") && w.length()>5 && wordSet.contains(w.substring(0, w.length() - 3)) && (w.charAt(w.length()-3)==w.charAt(w.length()-4))) { return; } if (w.endsWith("est") && wordSet.contains(w.substring(0, w.length() - 2))) { return; } if (w.endsWith("est") && wordSet.contains(w.substring(0, w.length() - 3))) { return; } if (w.endsWith("est") && w.length()>6 && wordSet.contains(w.substring(0, w.length() - 4)) && (w.charAt(w.length()-4)==w.charAt(w.length()-5))) { return; } if (w.endsWith("ier") && wordSet.contains(w.substring(0, w.length() - 3)+"y")) { return; } if (w.endsWith("iest") && wordSet.contains(w.substring(0, w.length() - 4)+"y")) { return; } if (w.endsWith("ves") && wordSet.contains(w.substring(0, w.length() - 3)+"f")) { return; } String originalText = ""; if(searchOriginalText){ originalText = "\t<a target=\"_blank\" href=\"aid-reading-detail.jsp?book="+book+"&word="+entry.getKey()+"&dict=ICIBA&pageSize="+entry.getValue()+"\">[" + entry.getValue() + "]</a>"; }else{ originalText = "\t[" + entry.getValue() + "]"; } list.add(WordLinker.toLink(entry.getKey(), dictionary) + originalText); }); result.append("<h3>words don't occur in specified set: ("+list.size()+") </h3>\n"); result.append(HtmlFormatter.toHtmlTableFragment(list, column)); list.clear(); map.entrySet().stream().sorted((a, b) -> b.getValue().get() - a.getValue().get()).forEach(entry -> { String originalText = ""; if(searchOriginalText){ originalText = "\t<a target=\"_blank\" href=\"aid-reading-detail.jsp?book="+book+"&word="+entry.getKey()+"&dict=ICIBA&pageSize="+entry.getValue()+"\">[" + entry.getValue() + "]</a>"; }else{ originalText = "\t[" + entry.getValue() + "]"; } list.add(WordLinker.toLink(entry.getKey(), dictionary) + originalText); }); result.append("<h3>words: (" + list.size() + ") </h3>\n"); result.append(HtmlFormatter.toHtmlTableFragment(list, column)); return result.toString(); } }
分级词汇包含原则
src/main/java/org/apdplat/superword/tools/AidReading.java
分级词汇包含原则
<ide><path>rc/main/java/org/apdplat/superword/tools/AidReading.java <ide> * 辅助阅读: <ide> * 以电影功夫熊猫使用的单词分析为例 <ide> * 你英语四级过了吗? 功夫熊猫看了吗? <del> * 去除停用词后,功夫熊猫使用了794个英语单词,你会说很简单吧,别急,这些单词中仍然有148个单词不在四级词汇表中,花两分钟时间看看你是否认识这些单词. <add> * 去除停用词后,功夫熊猫使用了789个英语单词,你会说很简单吧,别急,这些单词中仍然有148个单词不在四级词汇表中,花两分钟时间看看你是否认识这些单词. <ide> * Created by ysc on 11/15/15. <ide> */ <ide> public class AidReading { <ide> <ide> List<String> list = new ArrayList<>(); <ide> <add> Map<String, AtomicInteger> map2 = new ConcurrentHashMap<>(); <add> <ide> map.entrySet().stream().sorted((a, b) -> b.getValue().get() - a.getValue().get()).forEach(entry -> { <add> AtomicInteger v = entry.getValue(); <ide> String w = entry.getKey().toLowerCase(); <ide> if(w.length() < 3){ <ide> return; <ide> } <ide> if (wordSet.contains(w)) { <add> map2.put(w, v); <ide> return; <ide> } <ide> if (w.endsWith("ly") && wordSet.contains(w.substring(0, w.length() - 2))) { <add> map2.put(w+"_"+w.substring(0, w.length() - 2), v); <ide> return; <ide> } <ide> if (w.endsWith("s") && wordSet.contains(w.substring(0, w.length() - 1))) { <add> map2.put(w+"_"+w.substring(0, w.length() - 1), v); <ide> return; <ide> } <ide> if (w.endsWith("es") && wordSet.contains(w.substring(0, w.length() - 2))) { <add> map2.put(w+"_"+w.substring(0, w.length() - 2), v); <ide> return; <ide> } <ide> if (w.endsWith("ies") && wordSet.contains(w.substring(0, w.length() - 3)+"y")) { <add> map2.put(w+"_"+w.substring(0, w.length() - 3)+"y", v); <ide> return; <ide> } <ide> if (w.endsWith("ed") && wordSet.contains(w.substring(0, w.length() - 1))) { <add> map2.put(w+"_"+w.substring(0, w.length() - 1), v); <ide> return; <ide> } <ide> if (w.endsWith("ed") && wordSet.contains(w.substring(0, w.length() - 2))) { <add> map2.put(w+"_"+w.substring(0, w.length() - 2), v); <ide> return; <ide> } <ide> if (w.endsWith("ed") && w.length()>5 && wordSet.contains(w.substring(0, w.length() - 3)) && (w.charAt(w.length()-3)==w.charAt(w.length()-4))) { <add> map2.put(w+"_"+w.substring(0, w.length() - 3), v); <ide> return; <ide> } <ide> if (w.endsWith("ied") && wordSet.contains(w.substring(0, w.length() - 3)+"y")) { <add> map2.put(w+"_"+w.substring(0, w.length() - 3)+"y", v); <ide> return; <ide> } <ide> if (w.endsWith("ing") && wordSet.contains(w.substring(0, w.length() - 3))) { <add> map2.put(w+"_"+w.substring(0, w.length() - 3), v); <ide> return; <ide> } <ide> if (w.endsWith("ing") && wordSet.contains(w.substring(0, w.length() - 3)+"e")) { <add> map2.put(w+"_"+w.substring(0, w.length() - 3)+"e", v); <ide> return; <ide> } <ide> if (w.endsWith("ing") && w.length()>6 && wordSet.contains(w.substring(0, w.length() - 4)) && (w.charAt(w.length()-4)==w.charAt(w.length()-5))) { <add> map2.put(w+"_"+w.substring(0, w.length() - 4), v); <ide> return; <ide> } <ide> if (w.endsWith("er") && wordSet.contains(w.substring(0, w.length() - 1))) { <add> map2.put(w+"_"+w.substring(0, w.length() - 1), v); <ide> return; <ide> } <ide> if (w.endsWith("er") && wordSet.contains(w.substring(0, w.length() - 2))) { <add> map2.put(w+"_"+w.substring(0, w.length() - 2), v); <ide> return; <ide> } <ide> if (w.endsWith("er") && w.length()>5 && wordSet.contains(w.substring(0, w.length() - 3)) && (w.charAt(w.length()-3)==w.charAt(w.length()-4))) { <add> map2.put(w+"_"+w.substring(0, w.length() - 3), v); <ide> return; <ide> } <ide> if (w.endsWith("est") && wordSet.contains(w.substring(0, w.length() - 2))) { <add> map2.put(w+"_"+w.substring(0, w.length() - 2), v); <ide> return; <ide> } <ide> if (w.endsWith("est") && wordSet.contains(w.substring(0, w.length() - 3))) { <add> map2.put(w+"_"+w.substring(0, w.length() - 3), v); <ide> return; <ide> } <ide> if (w.endsWith("est") && w.length()>6 && wordSet.contains(w.substring(0, w.length() - 4)) && (w.charAt(w.length()-4)==w.charAt(w.length()-5))) { <add> map2.put(w+"_"+w.substring(0, w.length() - 4), v); <ide> return; <ide> } <ide> if (w.endsWith("ier") && wordSet.contains(w.substring(0, w.length() - 3)+"y")) { <add> map2.put(w+"_"+w.substring(0, w.length() - 3)+"y", v); <ide> return; <ide> } <ide> if (w.endsWith("iest") && wordSet.contains(w.substring(0, w.length() - 4)+"y")) { <add> map2.put(w+"_"+w.substring(0, w.length() - 4)+"y", v); <ide> return; <ide> } <ide> if (w.endsWith("ves") && wordSet.contains(w.substring(0, w.length() - 3)+"f")) { <add> map2.put(w+"_"+w.substring(0, w.length() - 3)+"f", v); <ide> return; <ide> } <ide> String originalText = ""; <ide> <ide> list.clear(); <ide> <del> map.entrySet().stream().sorted((a, b) -> b.getValue().get() - a.getValue().get()).forEach(entry -> { <add> map2.entrySet().stream().sorted((a, b) -> b.getValue().get() - a.getValue().get()).forEach(entry -> { <ide> String originalText = ""; <del> if(searchOriginalText){ <del> originalText = "\t<a target=\"_blank\" href=\"aid-reading-detail.jsp?book="+book+"&word="+entry.getKey()+"&dict=ICIBA&pageSize="+entry.getValue()+"\">[" + entry.getValue() + "]</a>"; <del> }else{ <add> if (searchOriginalText) { <add> originalText = "\t<a target=\"_blank\" href=\"aid-reading-detail.jsp?book=" + book + "&word=" + entry.getKey() + "&dict=ICIBA&pageSize=" + entry.getValue() + "\">[" + entry.getValue() + "]</a>"; <add> } else { <ide> originalText = "\t[" + entry.getValue() + "]"; <ide> } <del> list.add(WordLinker.toLink(entry.getKey(), dictionary) + originalText); <add> StringBuilder link = new StringBuilder(); <add> for (String word : entry.getKey().split("_")) { <add> link.append(WordLinker.toLink(word, dictionary)).append(" | "); <add> } <add> link.setLength(link.length()-3); <add> list.add(link.toString() + originalText); <ide> }); <del> result.append("<h3>words: (" + list.size() + ") </h3>\n"); <add> result.append("<h3>words occur in specified set: (" + list.size() + ") </h3>\n"); <ide> result.append(HtmlFormatter.toHtmlTableFragment(list, column)); <ide> return result.toString(); <ide> }
Java
agpl-3.0
error: pathspec 'cadc-util/src/main/java/ca/nrc/cadc/util/CoordUtil.java' did not match any file(s) known to git
7424cd5fd2ecbb1ab6ef8de59a3f5922550fb9a0
1
opencadc/core,opencadc/core
// Created on 8-Feb-2006 package ca.nrc.cadc.util; import java.text.NumberFormat; import java.util.StringTokenizer; /** * Simple astronomical coordinate conversion utility. * * @version $Version$ * @author pdowler */ public class CoordUtil { // the unicode degree symbol public static String DEGREE_SYMBOL = new Character((char) 0x00b0).toString(); private static String raSeparators = "'\"hmsHMS:"; private static String decSeparators = "'\"dmsDMS:" + DEGREE_SYMBOL; private static NumberFormat raFormat = NumberFormat.getInstance(); private static NumberFormat decFormat = NumberFormat.getInstance(); static { raFormat.setMaximumFractionDigits(1); raFormat.setMinimumFractionDigits(1); raFormat.setMaximumIntegerDigits(2); raFormat.setMinimumIntegerDigits(2); decFormat.setMaximumFractionDigits(1); decFormat.setMinimumFractionDigits(1); decFormat.setMaximumIntegerDigits(2); decFormat.setMinimumIntegerDigits(2); } /* * Convert the ra,dec values in degrees to sexigessimal format. This is a * convenience method that calls degreesToRA() and degreesToDEC(). * * @return String[2] with ra and dec */ public static String[] degreesToSexigessimal(double ra, double dec) { return new String[] { degreesToRA(ra), degreesToDEC(dec) }; } public static String degreesToRA(double val) { // raneg reduction to [0.0,360.0) while ( val < 0.0) val += 360.0; while (val >= 360.0) val -= 360.0; //if (val < 0.0 || val >= 360.0) // throw new IllegalArgumentException("value "+val+" out of bounds: [0.0, 360.0)"); // 24 hours/360 degrees = 15 deg/hour int h = (int) (val / 15.0); val -= h * 15.0; // 15 deg/hour == 0.25 deg/min == 4 min/deg int m = (int) (val * 4.0); val -= m / 4.0; // 4 min/deg == 240 sec/deg val *= 240.0; String d = Double.toString(val); String s = null; String hh = Integer.toString(h); String mm = Integer.toString(m); if (h < 10) hh = "0" + h; if(m < 10) mm = "0" + m; s = hh + ":" + mm + ":"; return s + raFormat.format(val); } public static String degreesToDEC(double val) { if (val < -90.0 || val > 90.0) throw new IllegalArgumentException("value "+val+" out of bounds: [-90.0, 90.0]"); String sign = "+"; if (val < 0.0) { sign = "-"; val *= -1.0; } int deg = (int) (val); val -= deg; // 60 min/deg int m = (int) (val * 60.0); val -= m / 60.0; // 60 sec/min == 3600 sec/deg val *= 3600.0; String d = Double.toString(val); String degs = Integer.toString(deg); if(deg < 10) degs = "0" + degs; String min = Integer.toString(m); if(m < 10) min = "0" + m; String s = sign + degs + ":" + min + ":"; return s + decFormat.format(val); } public static double[] sexigessimalToDegrees(String ra, String dec) throws NumberFormatException { return new double[] { raToDegrees(ra), decToDegrees(dec) }; } /** * Convert a string to a right ascension value in degrees. The argument is split * into components using a variety of separators (space, colon, some chars). * Valid formats include 15h30m45.6s = 15:30:45.6 = 15 30 45.6 ~ 232.69 (degrees). * If there is only one component after splitting, it is assumed to be the degrees * component (ie. 15 != 15:0:0) unless followed by the character 'h' (ie. 15h = 15:0:0). * * TODO - This is obscure and can be simplified! * TODO - 2007.01.05 * * @param ra * @return right ascension in degrees * @throws NumberFormatException if arg cannot be parsed * @throws IllegalArgumentException if the resulting value is not in [0,360] */ public static double raToDegrees(final String ra) throws NumberFormatException { StringTokenizer st = new StringTokenizer(ra, raSeparators, true); double h = Double.NaN; double m = 0.0; double s = 0.0; if ( st.hasMoreTokens() ) h = Double.parseDouble(st.nextToken()); if ( st.hasMoreTokens() ) { String str = st.nextToken(); // consume separator if (str.equals("h") || str.equals(":")) h *= 15.0; } if ( st.hasMoreTokens() ) m = Double.parseDouble(st.nextToken()); if ( st.hasMoreTokens() ) st.nextToken(); // consume separator if ( st.hasMoreTokens() ) s = Double.parseDouble(st.nextToken()); if ( Double.isNaN(h) ) throw new IllegalArgumentException("empty string (RA)"); double ret = h + m/4.0 + s/240.0; while ( ret < 0.0) ret += 360.0; while (ret > 360.0) ret -= 360.0; //if (0.0 <= ret && ret < 360.0) return ret; //throw new IllegalArgumentException("RA must be in [0,360]: " + ret); } /** * Obtain the radian value of the given RA string. * @param ra * @return double radian * @throws NumberFormatException */ public static double raToRadians(final String ra) throws NumberFormatException { return (raToDegrees(ra) * Math.PI) / 180.0; } /** * Obtain the String RA of the given Radians. * @param raRadians * @return String HH mm ss.s */ public static String radiansToRA(final double raRadians) { return degreesToRA((raRadians * 180) / Math.PI); } /** * Convert a string to a declination value in degrees. The argument is split * into components using a variety of separators (space, colon, some chars). * Valid formats include 15d30m45.6s = 15:30:45.6 = 15 30 45.6 ~ 15.51267 (degrees). * If there is only one component after splitting, it is assumed to be the degrees * component (thus, 15 == 15:0:0). Only the degrees component should have a negative * sign. * * @param dec * @return declination in degrees * @throws NumberFormatException if arg cannot be parsed * @throws IllegalArgumentException if the resulting value is not in [-90,90] */ public static double decToDegrees(String dec) throws IllegalArgumentException, NumberFormatException { StringTokenizer st = new StringTokenizer(dec, decSeparators); double d = Double.NaN; double m = 0; double s = 0; if ( st.hasMoreTokens() ) d = Double.parseDouble(st.nextToken()); if ( st.hasMoreTokens() ) m = Double.parseDouble(st.nextToken()); if ( st.hasMoreTokens() ) s = Double.parseDouble(st.nextToken()); if ( Double.isNaN(d) ) throw new IllegalArgumentException("empty string (DEC)"); double ret = d + m/60.0 + s/3600.0; if (dec.startsWith("-")) ret = d - m/60.0 - s/3600.0; if (-90.0 <= ret && ret <= 90.0) return ret; throw new IllegalArgumentException("DEC must be in [-90,90]: " + ret); } /** * Obtain the radian value of the String declination. * * @param dec * @return double as radians. * @throws IllegalArgumentException * @throws NumberFormatException */ public static double decToRadians(final String dec) throws IllegalArgumentException, NumberFormatException { return (decToDegrees(dec) * Math.PI) / 180.0; } /** * Obtain the String declination of the given radians. * * @param decRadians * @return String declination DD mm ss.s */ public static String radiansToDec(final double decRadians) { return degreesToDEC((decRadians * 180) / Math.PI); } /* public static void main(String[] args) { double[] ra = { 0.0, 10.0, 350.0, 360.0, 370.0, -10.0, -350.0, -370.0 }; double[] dec = {-90.0, -85, -0.1, 0.0, 0.1, 85.0, 90.0 }; double[] edec = { -100.0, 100.0 }; for (int i=0; i<ra.length; i++) { String s = degreesToRA(ra[i]); System.out.println(ra[i] + " -> " + s); double d = raToDegrees(s); System.out.println(s + " -> " + d); assert d == ra[i]; } for (int i=0; i<dec.length; i++) { String s = degreesToDEC(dec[i]); System.out.println(dec[i] + " -> " + s); double d = decToDegrees(s); System.out.println(s + " -> " + d); assert d == dec[i]; } for (int i=0; i<edec.length; i++) { try { String s = degreesToDEC(edec[i]); System.out.println(dec[i] + " -> " + s + " [FAIL]"); double d = decToDegrees(s); System.out.println(s + " -> " + d + " [FAIL]"); assert d == dec[i]; } catch(IllegalArgumentException ok) { System.out.println("caught expected: " + ok); } } } */ }
cadc-util/src/main/java/ca/nrc/cadc/util/CoordUtil.java
s1970: moved CoordUtil from javaUtil to cadc-util.
cadc-util/src/main/java/ca/nrc/cadc/util/CoordUtil.java
s1970: moved CoordUtil from javaUtil to cadc-util.
<ide><path>adc-util/src/main/java/ca/nrc/cadc/util/CoordUtil.java <add>// Created on 8-Feb-2006 <add> <add>package ca.nrc.cadc.util; <add> <add>import java.text.NumberFormat; <add>import java.util.StringTokenizer; <add> <add>/** <add> * Simple astronomical coordinate conversion utility. <add> * <add> * @version $Version$ <add> * @author pdowler <add> */ <add>public class CoordUtil <add>{ <add> // the unicode degree symbol <add> public static String DEGREE_SYMBOL = new Character((char) 0x00b0).toString(); <add> <add> private static String raSeparators = "'\"hmsHMS:"; <add> private static String decSeparators = "'\"dmsDMS:" + DEGREE_SYMBOL; <add> <add> private static NumberFormat raFormat = NumberFormat.getInstance(); <add> private static NumberFormat decFormat = NumberFormat.getInstance(); <add> static { <add> raFormat.setMaximumFractionDigits(1); <add> raFormat.setMinimumFractionDigits(1); <add> raFormat.setMaximumIntegerDigits(2); <add> raFormat.setMinimumIntegerDigits(2); <add> <add> decFormat.setMaximumFractionDigits(1); <add> decFormat.setMinimumFractionDigits(1); <add> decFormat.setMaximumIntegerDigits(2); <add> decFormat.setMinimumIntegerDigits(2); <add> } <add> <add> /* <add> * Convert the ra,dec values in degrees to sexigessimal format. This is a <add> * convenience method that calls degreesToRA() and degreesToDEC(). <add> * <add> * @return String[2] with ra and dec <add> */ <add> public static String[] degreesToSexigessimal(double ra, double dec) <add> { <add> return new String[] { degreesToRA(ra), degreesToDEC(dec) }; <add> } <add> public static String degreesToRA(double val) <add> { <add> // raneg reduction to [0.0,360.0) <add> while ( val < 0.0) <add> val += 360.0; <add> while (val >= 360.0) <add> val -= 360.0; <add> <add> //if (val < 0.0 || val >= 360.0) <add> // throw new IllegalArgumentException("value "+val+" out of bounds: [0.0, 360.0)"); <add> <add> // 24 hours/360 degrees = 15 deg/hour <add> int h = (int) (val / 15.0); <add> val -= h * 15.0; <add> // 15 deg/hour == 0.25 deg/min == 4 min/deg <add> int m = (int) (val * 4.0); <add> val -= m / 4.0; <add> // 4 min/deg == 240 sec/deg <add> val *= 240.0; <add> String d = Double.toString(val); <add> String s = null; <add> String hh = Integer.toString(h); <add> String mm = Integer.toString(m); <add> if (h < 10) <add> hh = "0" + h; <add> if(m < 10) <add> mm = "0" + m; <add> <add> s = hh + ":" + mm + ":"; <add> return s + raFormat.format(val); <add> } <add> public static String degreesToDEC(double val) <add> { <add> if (val < -90.0 || val > 90.0) <add> throw new IllegalArgumentException("value "+val+" out of bounds: [-90.0, 90.0]"); <add> String sign = "+"; <add> if (val < 0.0) <add> { <add> sign = "-"; <add> val *= -1.0; <add> } <add> int deg = (int) (val); <add> val -= deg; <add> // 60 min/deg <add> int m = (int) (val * 60.0); <add> val -= m / 60.0; <add> // 60 sec/min == 3600 sec/deg <add> val *= 3600.0; <add> String d = Double.toString(val); <add> <add> String degs = Integer.toString(deg); <add> if(deg < 10) <add> degs = "0" + degs; <add> String min = Integer.toString(m); <add> if(m < 10) <add> min = "0" + m; <add> <add> String s = sign + degs + ":" + min + ":"; <add> <add> return s + decFormat.format(val); <add> } <add> <add> <add> <add> public static double[] sexigessimalToDegrees(String ra, String dec) <add> throws NumberFormatException <add> { <add> return new double[] { raToDegrees(ra), decToDegrees(dec) }; <add> } <add> <add> /** <add> * Convert a string to a right ascension value in degrees. The argument is split <add> * into components using a variety of separators (space, colon, some chars). <add> * Valid formats include 15h30m45.6s = 15:30:45.6 = 15 30 45.6 ~ 232.69 (degrees). <add> * If there is only one component after splitting, it is assumed to be the degrees <add> * component (ie. 15 != 15:0:0) unless followed by the character 'h' (ie. 15h = 15:0:0). <add> * <add> * TODO - This is obscure and can be simplified! <add> * TODO - 2007.01.05 <add> * <add> * @param ra <add> * @return right ascension in degrees <add> * @throws NumberFormatException if arg cannot be parsed <add> * @throws IllegalArgumentException if the resulting value is not in [0,360] <add> */ <add> public static double raToDegrees(final String ra) <add> throws NumberFormatException <add> { <add> StringTokenizer st = new StringTokenizer(ra, raSeparators, true); <add> double h = Double.NaN; <add> double m = 0.0; <add> double s = 0.0; <add> <add> if ( st.hasMoreTokens() ) <add> h = Double.parseDouble(st.nextToken()); <add> if ( st.hasMoreTokens() ) <add> { <add> String str = st.nextToken(); // consume separator <add> if (str.equals("h") || str.equals(":")) <add> h *= 15.0; <add> } <add> if ( st.hasMoreTokens() ) <add> m = Double.parseDouble(st.nextToken()); <add> if ( st.hasMoreTokens() ) <add> st.nextToken(); // consume separator <add> if ( st.hasMoreTokens() ) <add> s = Double.parseDouble(st.nextToken()); <add> <add> if ( Double.isNaN(h) ) <add> throw new IllegalArgumentException("empty string (RA)"); <add> <add> double ret = h + m/4.0 + s/240.0; <add> while ( ret < 0.0) <add> ret += 360.0; <add> while (ret > 360.0) <add> ret -= 360.0; <add> //if (0.0 <= ret && ret < 360.0) <add> return ret; <add> //throw new IllegalArgumentException("RA must be in [0,360]: " + ret); <add> } <add> <add> /** <add> * Obtain the radian value of the given RA string. <add> * @param ra <add> * @return double radian <add> * @throws NumberFormatException <add> */ <add> public static double raToRadians(final String ra) <add> throws NumberFormatException <add> { <add> return (raToDegrees(ra) * Math.PI) / 180.0; <add> } <add> <add> /** <add> * Obtain the String RA of the given Radians. <add> * @param raRadians <add> * @return String HH mm ss.s <add> */ <add> public static String radiansToRA(final double raRadians) <add> { <add> return degreesToRA((raRadians * 180) / Math.PI); <add> } <add> <add> /** <add> * Convert a string to a declination value in degrees. The argument is split <add> * into components using a variety of separators (space, colon, some chars). <add> * Valid formats include 15d30m45.6s = 15:30:45.6 = 15 30 45.6 ~ 15.51267 (degrees). <add> * If there is only one component after splitting, it is assumed to be the degrees <add> * component (thus, 15 == 15:0:0). Only the degrees component should have a negative <add> * sign. <add> * <add> * @param dec <add> * @return declination in degrees <add> * @throws NumberFormatException if arg cannot be parsed <add> * @throws IllegalArgumentException if the resulting value is not in [-90,90] <add> */ <add> public static double decToDegrees(String dec) <add> throws IllegalArgumentException, NumberFormatException <add> { <add> StringTokenizer st = new StringTokenizer(dec, decSeparators); <add> double d = Double.NaN; <add> double m = 0; <add> double s = 0; <add> if ( st.hasMoreTokens() ) <add> d = Double.parseDouble(st.nextToken()); <add> if ( st.hasMoreTokens() ) <add> m = Double.parseDouble(st.nextToken()); <add> if ( st.hasMoreTokens() ) <add> s = Double.parseDouble(st.nextToken()); <add> <add> if ( Double.isNaN(d) ) <add> throw new IllegalArgumentException("empty string (DEC)"); <add> <add> double ret = d + m/60.0 + s/3600.0; <add> if (dec.startsWith("-")) <add> ret = d - m/60.0 - s/3600.0; <add> <add> if (-90.0 <= ret && ret <= 90.0) <add> return ret; <add> throw new IllegalArgumentException("DEC must be in [-90,90]: " + ret); <add> } <add> <add> /** <add> * Obtain the radian value of the String declination. <add> * <add> * @param dec <add> * @return double as radians. <add> * @throws IllegalArgumentException <add> * @throws NumberFormatException <add> */ <add> public static double decToRadians(final String dec) <add> throws IllegalArgumentException, NumberFormatException <add> { <add> return (decToDegrees(dec) * Math.PI) / 180.0; <add> } <add> <add> /** <add> * Obtain the String declination of the given radians. <add> * <add> * @param decRadians <add> * @return String declination DD mm ss.s <add> */ <add> public static String radiansToDec(final double decRadians) <add> { <add> return degreesToDEC((decRadians * 180) / Math.PI); <add> } <add> <add> /* <add> public static void main(String[] args) <add> { <add> double[] ra = { 0.0, 10.0, 350.0, 360.0, 370.0, -10.0, -350.0, -370.0 }; <add> double[] dec = {-90.0, -85, -0.1, 0.0, 0.1, 85.0, 90.0 }; <add> double[] edec = { -100.0, 100.0 }; <add> <add> for (int i=0; i<ra.length; i++) <add> { <add> String s = degreesToRA(ra[i]); <add> System.out.println(ra[i] + " -> " + s); <add> double d = raToDegrees(s); <add> System.out.println(s + " -> " + d); <add> assert d == ra[i]; <add> } <add> for (int i=0; i<dec.length; i++) <add> { <add> String s = degreesToDEC(dec[i]); <add> System.out.println(dec[i] + " -> " + s); <add> double d = decToDegrees(s); <add> System.out.println(s + " -> " + d); <add> assert d == dec[i]; <add> } <add> for (int i=0; i<edec.length; i++) <add> { <add> try <add> { <add> String s = degreesToDEC(edec[i]); <add> System.out.println(dec[i] + " -> " + s + " [FAIL]"); <add> double d = decToDegrees(s); <add> System.out.println(s + " -> " + d + " [FAIL]"); <add> assert d == dec[i]; <add> } <add> catch(IllegalArgumentException ok) { System.out.println("caught expected: " + ok); } <add> } <add> } <add> */ <add>}
Java
mit
0ae9d370483cd827cb0d347a649b63ffa032b280
0
grepx/archivorg
package gregpearce.archivorg.ui; import android.os.Bundle; import android.support.design.widget.NavigationView; import android.support.design.widget.TabLayout; import android.support.v4.view.GravityCompat; import android.support.v4.view.ViewPager; import android.support.v4.widget.DrawerLayout; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import com.lapism.searchview.SearchView; import javax.inject.Inject; import butterknife.BindView; import butterknife.ButterKnife; import gregpearce.archivorg.R; import gregpearce.archivorg.ui.feed.FeedPresenter; public class MainActivity extends BaseActivity { @Inject FeedPresenter feedPresenter; @BindView(R.id.drawer_layout) DrawerLayout drawerLayout; @BindView(R.id.toolbar) Toolbar toolbar; @BindView(R.id.view_pager) ViewPager viewPager; @BindView(R.id.tab_layout) TabLayout tabLayout; @BindView(R.id.search_view) SearchView searchView; @BindView(R.id.navigation_view) NavigationView navigationView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); getComponent().inject(this); ButterKnife.bind(this); setupToolbar(); setupTabs(); setupSearchView(); } private void setupToolbar() { toolbar.setNavigationContentDescription(getResources().getString(R.string.app_name)); toolbar.setNavigationIcon(R.drawable.ic_menu_white_24dp); setSupportActionBar(toolbar); } private void setupTabs() { MainPagerAdapter sectionsPagerAdapter = new MainPagerAdapter(getSupportFragmentManager()); viewPager.setAdapter(sectionsPagerAdapter); tabLayout.setupWithViewPager(viewPager); } protected void setupSearchView() { searchView.setVersion(SearchView.VERSION_MENU_ITEM); searchView.setVersionMargins(SearchView.VERSION_MARGINS_MENU_ITEM); searchView.setTheme(SearchView.THEME_LIGHT, true); searchView.setHint(R.string.search); searchView.setTextSize(16); searchView.setHint("Search Archive.org"); searchView.setDivider(false); searchView.setVoice(true); searchView.setVoiceText("Set permission on Android 6+ !"); searchView.setAnimationDuration(SearchView.ANIMATION_DURATION); // shadow = modal behavior, possibly revert back to this in the future searchView.setShadow(false); // searchView.setShadowColor(ContextCompat.getColor(this, R.color.search_shadow_layout)); searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { feedPresenter.search(query); return true; } @Override public boolean onQueryTextChange(String newText) { return false; } }); searchView.setOnOpenCloseListener(new SearchView.OnOpenCloseListener() { @Override public void onClose() { feedPresenter.search(""); } @Override public void onOpen() { } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_search: searchView.open(true); return true; case android.R.id.home: drawerLayout.openDrawer(GravityCompat.START); return true; default: return super.onOptionsItemSelected(item); } } }
app/src/main/java/gregpearce/archivorg/ui/MainActivity.java
package gregpearce.archivorg.ui; import android.os.Bundle; import android.support.design.widget.NavigationView; import android.support.design.widget.TabLayout; import android.support.v4.view.GravityCompat; import android.support.v4.view.ViewPager; import android.support.v4.widget.DrawerLayout; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import com.lapism.searchview.SearchView; import butterknife.BindView; import butterknife.ButterKnife; import gregpearce.archivorg.R; public class MainActivity extends BaseActivity { @BindView(R.id.drawer_layout) DrawerLayout drawerLayout; @BindView(R.id.toolbar) Toolbar toolbar; @BindView(R.id.view_pager) ViewPager viewPager; @BindView(R.id.tab_layout) TabLayout tabLayout; @BindView(R.id.search_view) SearchView searchView; @BindView(R.id.navigation_view) NavigationView navigationView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); setupToolbar(); setupTabs(); setupSearchView(); } private void setupToolbar() { toolbar.setNavigationContentDescription(getResources().getString(R.string.app_name)); toolbar.setNavigationIcon(R.drawable.ic_menu_white_24dp); setSupportActionBar(toolbar); } private void setupTabs() { MainPagerAdapter sectionsPagerAdapter = new MainPagerAdapter(getSupportFragmentManager()); viewPager.setAdapter(sectionsPagerAdapter); tabLayout.setupWithViewPager(viewPager); } protected void setupSearchView() { searchView.setVersion(SearchView.VERSION_MENU_ITEM); searchView.setVersionMargins(SearchView.VERSION_MARGINS_MENU_ITEM); searchView.setTheme(SearchView.THEME_LIGHT, true); searchView.setHint(R.string.search); searchView.setTextSize(16); searchView.setHint("Search Archive.org"); searchView.setDivider(false); searchView.setVoice(true); searchView.setVoiceText("Set permission on Android 6+ !"); searchView.setAnimationDuration(SearchView.ANIMATION_DURATION); // shadow = modal behavior, possibly revert back to this in the future searchView.setShadow(false); // searchView.setShadowColor(ContextCompat.getColor(this, R.color.search_shadow_layout)); searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { return true; } @Override public boolean onQueryTextChange(String newText) { return false; } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_search: searchView.open(true); return true; case android.R.id.home: drawerLayout.openDrawer(GravityCompat.START); return true; default: return super.onOptionsItemSelected(item); } } }
Hook up search box to feed presenter
app/src/main/java/gregpearce/archivorg/ui/MainActivity.java
Hook up search box to feed presenter
<ide><path>pp/src/main/java/gregpearce/archivorg/ui/MainActivity.java <ide> <ide> import com.lapism.searchview.SearchView; <ide> <add>import javax.inject.Inject; <add> <ide> import butterknife.BindView; <ide> import butterknife.ButterKnife; <ide> import gregpearce.archivorg.R; <add>import gregpearce.archivorg.ui.feed.FeedPresenter; <ide> <ide> public class MainActivity extends BaseActivity { <add> @Inject FeedPresenter feedPresenter; <ide> <ide> @BindView(R.id.drawer_layout) DrawerLayout drawerLayout; <ide> @BindView(R.id.toolbar) Toolbar toolbar; <ide> super.onCreate(savedInstanceState); <ide> <ide> setContentView(R.layout.activity_main); <add> getComponent().inject(this); <ide> ButterKnife.bind(this); <ide> <ide> setupToolbar(); <ide> searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { <ide> @Override <ide> public boolean onQueryTextSubmit(String query) { <add> feedPresenter.search(query); <ide> return true; <ide> } <ide> <ide> @Override <ide> public boolean onQueryTextChange(String newText) { <ide> return false; <add> } <add> }); <add> searchView.setOnOpenCloseListener(new SearchView.OnOpenCloseListener() { <add> @Override public void onClose() { <add> feedPresenter.search(""); <add> } <add> <add> @Override public void onOpen() { <ide> } <ide> }); <ide> }
JavaScript
mit
b1b0cca13a007be04e45de4fd7bc717119143f76
0
c9/c9.automate
define(function(require, exports, module) { main.consumes = ["Plugin"]; main.provides = ["automate"]; return main; function main(options, imports, register) { var Plugin = imports.Plugin; var async = require("async"); /***** Initialization *****/ var plugin = new Plugin("Ajax.org", main.consumes); // var emit = plugin.getEmitter(); var namespaces = {}; /***** Methods *****/ function addCommand(ns, name, implementation) { if (!namespaces[ns]) namespaces[ns] = { commands: {}, alias: {} }; namespaces[ns].commands[name] = implementation; } function removeCommand(ns, name) { if (!namespaces[ns]) namespaces[ns] = { commands: {}, alias: {} }; delete namespaces[ns].commands[name]; } function addCommandAlias(ns, name) { if (!namespaces[ns]) namespaces[ns] = { commands: {}, alias: {} }; for (var i = 1; i < arguments.length; i++) { namespaces[ns].alias[arguments[i]] = name; } } function getCommand(ns, name) { if (!namespaces[ns]) throw new Error("Unknown namespace: " + ns); var cmd = namespaces[ns].commands; return cmd[name] || cmd[namespaces[ns].alias[name]]; } function createSession(ns) { var session = new Plugin("Ajax.org", main.consumes); var emit = session.getEmitter(); var tasks = []; var output = ""; var lastProcess; var executing = false; var aborting = false; function task(task, options, validate) { if (executing) throw new Error("Adding tasks while executing"); if (typeof options == "function" || options === undefined) { if (!validate) validate = options; options = {}; } Object.defineProperty(task, "$options", { enumerable: false, configurable: false, writable: false, value: options }); tasks.push(task); } function execute(tasks, callback, options) { if (tasks.$options) options = tasks.$options; // Loop over all tasks or sub-tasks when called recursively async.eachSeries(tasks, function(task, next) { options = task.$options || options || {}; if (options.ignore) return next(); // The task consists of multiple tasks if (Array.isArray(task)) return execute(task, next, options); // Loop over all competing tasks async.eachSeries(Object.keys(task), function(type, next) { var s = type.split(":"); if (s.length > 1) s = { ns: s[0], type: s[1] }; if (type == "install") { return execute(task[type], function(err){ next(err || 1); }, options); } var command = getCommand(s.ns || ns, s.type || type); command.isAvailable(function(available){ if (!available) return next(); var items = Array.isArray(task[type]) ? task[type] : [task[type]]; // Loop over each of the tasks for this command async.eachSeries(items, function(item, next){ if (aborting) return next(new Error("Aborted")); emit("each", { session: session, task: task, options: options, type: type, item: item }); var onData = function(chunk, process){ if (aborting) return process && process.end(); output += chunk; lastProcess = process; emit("data", { data: chunk, process: process }); }; var onFinish = function(err){ if (err && err.code == "EDISCONNECT") { command.execute(item, options, onData, onFinish); return; } next(err); }; command.execute(item, options, onData, onFinish); }, function(err){ next(err || 1); }); }); }, function(err){ // Success if (err === 1) return next(); // Failure if (err) return next(err); // No command avialable err = new Error("None of the available commands are available: " + JSON.stringify(task, 4, " ")); err.code = "ENOTAVAILABLE"; return next(err); }); }, function(err){ callback(err); }); } function run(callback) { if (executing) return; emit("run"); aborting = false; executing = true; execute(tasks, function(err){ executing = false; lastProcess = null; callback && callback.apply(this, arguments); session.unload(); emit("stop", err); }); } function abort(callback){ aborting = true; if (!executing) { lastProcess = null; emit("stop", new Error("Aborted")); } callback && callback(); } // Make session a baseclass to allow others to extend session.baseclass(); /** * **/ session.freezePublicAPI({ /** * */ get tasks(){ return tasks; }, /** * */ get executing(){ return executing; }, /** * */ get output(){ return output; }, /** * */ get process(){ return lastProcess || null; }, /** * */ task: task, /** * */ run: run, /** * */ abort: abort }); return session; } /***** Lifecycle *****/ plugin.on("load", function() { }); plugin.on("unload", function() { }); /***** Register and define API *****/ /** * **/ plugin.freezePublicAPI({ /** * */ createSession: createSession, /** * */ addCommand: addCommand, /** * */ removeCommand: removeCommand, /** * */ addCommandAlias: addCommandAlias }); register(null, { automate: plugin }); } });
automate.js
define(function(require, exports, module) { main.consumes = ["Plugin"]; main.provides = ["automate"]; return main; function main(options, imports, register) { var Plugin = imports.Plugin; var async = require("async"); /***** Initialization *****/ var plugin = new Plugin("Ajax.org", main.consumes); // var emit = plugin.getEmitter(); var namespaces = {}; /***** Methods *****/ function addCommand(ns, name, implementation) { if (!namespaces[ns]) namespaces[ns] = { commands: {}, alias: {} }; namespaces[ns].commands[name] = implementation; } function removeCommand(ns, name) { if (!namespaces[ns]) namespaces[ns] = { commands: {}, alias: {} }; delete namespaces[ns].commands[name]; } function addCommandAlias(ns, name) { if (!namespaces[ns]) namespaces[ns] = { commands: {}, alias: {} }; for (var i = 1; i < arguments.length; i++) { namespaces[ns].alias[arguments[i]] = name; } } function getCommand(ns, name) { if (!namespaces[ns]) throw new Error("Unknown namespace: " + ns); var cmd = namespaces[ns].commands; return cmd[name] || cmd[namespaces[ns].alias[name]]; } function createSession(ns) { var session = new Plugin("Ajax.org", main.consumes); var emit = session.getEmitter(); var tasks = []; var output = ""; var lastProcess; var executing = false; var aborting = false; function task(task, options, validate) { if (executing) throw new Error("Adding tasks while executing"); if (typeof options == "function" || options === undefined) { if (!validate) validate = options; options = {}; } Object.defineProperty(task, "$options", { enumerable: false, configurable: false, writable: false, value: options }); tasks.push(task); } function execute(tasks, callback, options) { if (tasks.$options) options = tasks.$options; // Loop over all tasks or sub-tasks when called recursively async.eachSeries(tasks, function(task, next) { options = task.$options || options || {}; if (options.ignore) return next(); // The task consists of multiple tasks if (Array.isArray(task)) return execute(task, next, options); // Loop over all competing tasks async.eachSeries(Object.keys(task), function(type, next) { var s = type.split(":"); if (s.length > 1) s = { ns: s[0], type: s[1] }; if (type == "install") { return execute(task[type], function(err){ next(err || 1); }, options); } var command = getCommand(s.ns || ns, s.type || type); command.isAvailable(function(available){ if (!available) return next(); var items = Array.isArray(task[type]) ? task[type] : [task[type]]; // Loop over each of the tasks for this command async.eachSeries(items, function(item, next){ if (aborting) return next(new Error("Aborted")); emit("each", { session: session, task: task, options: options, type: type, item: item }); command.execute(item, options, function(chunk, process){ if (aborting) return process && process.end(); output += chunk; lastProcess = process; emit("data", { data: chunk, process: process }); }, function(err){ next(err); }); }, function(err){ next(err || 1); }); }); }, function(err){ // Success if (err === 1) return next(); // Failure if (err) return next(err); // No command avialable err = new Error("None of the available commands are available: " + JSON.stringify(task, 4, " ")); err.code = "ENOTAVAILABLE"; return next(err); }); }, function(err){ callback(err); }); } function run(callback) { if (executing) return; emit("run"); aborting = false; executing = true; execute(tasks, function(err){ executing = false; lastProcess = null; callback && callback.apply(this, arguments); session.unload(); emit("stop", err); }); } function abort(callback){ aborting = true; if (!executing) { lastProcess = null; emit("stop", new Error("Aborted")); } callback && callback(); } // Make session a baseclass to allow others to extend session.baseclass(); /** * **/ session.freezePublicAPI({ /** * */ get tasks(){ return tasks; }, /** * */ get executing(){ return executing; }, /** * */ get output(){ return output; }, /** * */ get process(){ return lastProcess || null; }, /** * */ task: task, /** * */ run: run, /** * */ abort: abort }); return session; } /***** Lifecycle *****/ plugin.on("load", function() { }); plugin.on("unload", function() { }); /***** Register and define API *****/ /** * **/ plugin.freezePublicAPI({ /** * */ createSession: createSession, /** * */ addCommand: addCommand, /** * */ removeCommand: removeCommand, /** * */ addCommandAlias: addCommandAlias }); register(null, { automate: plugin }); } });
Survive a disconnect
automate.js
Survive a disconnect
<ide><path>utomate.js <ide> item: item <ide> }); <ide> <del> command.execute(item, options, function(chunk, process){ <add> var onData = function(chunk, process){ <ide> if (aborting) return process && process.end(); <ide> <ide> output += chunk; <ide> lastProcess = process; <ide> emit("data", { data: chunk, process: process }); <del> }, function(err){ <add> }; <add> <add> var onFinish = function(err){ <add> if (err && err.code == "EDISCONNECT") { <add> command.execute(item, options, onData, onFinish); <add> return; <add> } <add> <ide> next(err); <del> }); <add> }; <add> <add> command.execute(item, options, onData, onFinish); <ide> }, function(err){ <ide> next(err || 1); <ide> });
Java
agpl-3.0
f2cbe7e961d95c6b20bc688f7d03f9d0d142b93f
0
EhsanTang/ApiManager,EhsanTang/ApiManager,EhsanTang/ApiManager
package cn.crap.controller.front; import java.util.HashMap; import java.util.List; import java.util.Map; import cn.crap.adapter.ArticleAdapter; import cn.crap.adapter.CommentAdapter; import cn.crap.dto.ArticleDto; import cn.crap.dto.CrumbDto; import cn.crap.enumer.ArticleStatus; import cn.crap.enumer.MyError; import cn.crap.model.mybatis.*; import cn.crap.service.custom.CustomArticleService; import cn.crap.service.custom.CustomCommentService; import cn.crap.service.custom.CustomModuleService; import cn.crap.service.mybatis.ArticleService; import cn.crap.utils.MyCrumbDtoList; import cn.crap.utils.MyHashMap; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import cn.crap.enumer.ArticleType; import cn.crap.framework.JsonResult; import cn.crap.framework.MyException; import cn.crap.framework.base.BaseController; import cn.crap.model.mybatis.Project; import cn.crap.utils.Page; import cn.crap.utils.Tools; /** * front article page * @author Ehsan */ @Controller("frontArticleController") public class ArticleController extends BaseController { @Autowired private CustomModuleService customModuleService; @Autowired private CustomArticleService customArticleService; @Autowired private ArticleService articleService; @Autowired private CustomCommentService customCommentService; @RequestMapping("/front/article/diclist.do") @ResponseBody public JsonResult list(@RequestParam String moduleId, String name, @RequestParam(defaultValue = "1") Integer currentPage, String password, String visitCode) throws MyException { String type = ArticleType.DICTIONARY.name(); Module module = moduleCache.get(moduleId); Project project = projectCache.get(module.getProjectId()); // private project need login, public project need check password checkFrontPermission(password, visitCode, project); Page page = new Page(currentPage); List<Article> articles = customArticleService.queryArticle(moduleId, name, type, null, null, page); page.setAllRow(customArticleService.countByModuleId(moduleId, name, type, null, null)); Map<String, Object> others = Tools.getMap("crumbs", Tools.getCrumbs(type + "-" + module.getName(), "void")); return new JsonResult().success().data(ArticleAdapter.getDto(articles, module)).page(page).others(others); } @RequestMapping("/front/article/list.do") @ResponseBody public JsonResult list( Integer currentPage, String moduleId, @RequestParam String type, String category, String password, String visitCode, Byte status) throws MyException { Page page = new Page(currentPage); if (status == null || !status.equals(ArticleStatus.RECOMMEND.getStatus())){ Module module = moduleCache.get(moduleId); Project project = projectCache.get(module.getProjectId()); // 如果是私有项目,必须登录才能访问,公开项目需要查看是否需要密码 checkFrontPermission(password, visitCode, project); List<String> categories = customModuleService.queryCategoryByModuleId(module.getId()); List<Article> articles = customArticleService.queryArticle(moduleId, null, type, category, status, page); page.setAllRow(customArticleService.countByModuleId(moduleId, null, type, category, status)); List<ArticleDto> articleDtos = ArticleAdapter.getDto(articles, module); Map<String, Object> others = MyHashMap.getMap("type", ArticleType.valueOf(type).getName()) .put("category", category) .put("categorys", categories) .put("crumbs", Tools.getCrumbs("模块:" + project.getName(), "#/" + project.getId() + "/module/list", "文章:" + module.getName(), "void")) .getMap(); return new JsonResult().success().data(articleDtos).page(page).others(others); } // 推荐的文章 List<String> categories = customArticleService.queryTop10RecommendCategory(); List<Article> articles = customArticleService.queryArticle(null, null, type, category, status, page); List<ArticleDto> articleDtos = ArticleAdapter.getDto(articles, null); page.setAllRow(customArticleService.countByModuleId(null, null, type, category, status)); Map<String, Object> others = MyHashMap.getMap("type", ArticleType.valueOf(type).getName()) .put("category", category) .put("categorys", categories) .put("crumbs", Tools.getCrumbs( "推荐文章列表", "void")) .getMap(); return new JsonResult().success().data(articleDtos).page(page).others(others); } @RequestMapping("/front/article/detail.do") @ResponseBody public JsonResult articleDetail(@RequestParam String id, String password, String visitCode, Integer currentPage) throws MyException { Map<String, Object> returnMap = new HashMap<>(); ArticleWithBLOBs article = null; article = articleService.getById(id); if (article == null) { article = customArticleService.selectByKey(id); } if (article == null) { throw new MyException(MyError.E000020); } id = article.getId(); Module module = moduleCache.get(article.getModuleId()); Project project = projectCache.get(module.getProjectId()); // 如果是私有项目,必须登录才能访问,公开项目需要查看是否需要密码 checkFrontPermission(password, visitCode, project); if (article.getType().equals(ArticleType.DICTIONARY.name())) { return new JsonResult().success().data(article).others(returnMap); } // 初始化前端js评论对象 Comment comment = new Comment(); comment.setArticleId(id); returnMap.put("comment", comment); // 评论 Page page = new Page(10, currentPage); List<Comment> comments = customCommentService.selectByArticelId(id, null, page); page.setAllRow(customCommentService.countByArticleId(id)); returnMap.put("comments", CommentAdapter.getDto(comments)); returnMap.put("commentCode", settingCache.get(S_COMMENTCODE).getValue()); // 更新点击量 customArticleService.updateClickById(id); List<CrumbDto> crumbDtos = MyCrumbDtoList.getList("模块:" + project.getName(), "#/" + project.getId() + "/module/list") .add("文章:" + module.getName(), "#/" + project.getId() + "/article/list/" + module.getId() + "/ARTICLE/NULL/NULL/NULL") .add(article.getName(), "void") .getList(); returnMap.put("crumbs", crumbDtos); return new JsonResult(1, article, page, returnMap); } }
api/src/main/java/cn/crap/controller/front/ArticleController.java
package cn.crap.controller.front; import java.util.HashMap; import java.util.List; import java.util.Map; import cn.crap.adapter.ArticleAdapter; import cn.crap.adapter.CommentAdapter; import cn.crap.dto.ArticleDto; import cn.crap.dto.CrumbDto; import cn.crap.enumer.ArticleStatus; import cn.crap.enumer.MyError; import cn.crap.model.mybatis.*; import cn.crap.service.custom.CustomArticleService; import cn.crap.service.custom.CustomCommentService; import cn.crap.service.custom.CustomModuleService; import cn.crap.service.mybatis.ArticleService; import cn.crap.utils.MyCrumbDtoList; import cn.crap.utils.MyHashMap; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import cn.crap.enumer.ArticleType; import cn.crap.framework.JsonResult; import cn.crap.framework.MyException; import cn.crap.framework.base.BaseController; import cn.crap.model.mybatis.Project; import cn.crap.utils.Page; import cn.crap.utils.Tools; /** * front article page * @author Ehsan */ @Controller("frontArticleController") public class ArticleController extends BaseController { @Autowired private CustomModuleService customModuleService; @Autowired private CustomArticleService customArticleService; @Autowired private ArticleService articleService; @Autowired private CustomCommentService customCommentService; @RequestMapping("/front/article/diclist.do") @ResponseBody public JsonResult list(@RequestParam String moduleId, String name, @RequestParam(defaultValue = "1") Integer currentPage, String password, String visitCode) throws MyException { String type = ArticleType.DICTIONARY.name(); Module module = moduleCache.get(moduleId); Project project = projectCache.get(module.getProjectId()); // private project need login, public project need check password checkFrontPermission(password, visitCode, project); Page page = new Page(currentPage); List<Article> articles = customArticleService.queryArticle(moduleId, name, type, null, null, page); page.setAllRow(customArticleService.countByModuleId(moduleId, name, type, null, null)); Map<String, Object> others = Tools.getMap("crumbs", Tools.getCrumbs(type + "-" + module.getName(), "void")); return new JsonResult().success().data(ArticleAdapter.getDto(articles, module)).page(page).others(others); } @RequestMapping("/front/article/list.do") @ResponseBody public JsonResult list( Integer currentPage, String moduleId, @RequestParam String type, String category, String password, String visitCode, Byte status) throws MyException { Page page = new Page(currentPage); if (status == null || !status.equals(ArticleStatus.RECOMMEND.getStatus())){ Module module = moduleCache.get(moduleId); Project project = projectCache.get(module.getProjectId()); // 如果是私有项目,必须登录才能访问,公开项目需要查看是否需要密码 checkFrontPermission(password, visitCode, project); List<String> categories = customModuleService.queryCategoryByModuleId(module.getId()); List<Article> articles = customArticleService.queryArticle(moduleId, null, type, category, status, page); page.setAllRow(customArticleService.countByModuleId(moduleId, null, type, category, status)); List<ArticleDto> articleDtos = ArticleAdapter.getDto(articles, module); Map<String, Object> others = MyHashMap.getMap("type", ArticleType.valueOf(type).getName()) .put("category", category) .put("categorys", categories) .put("crumbs", Tools.getCrumbs("模块:" + project.getName(), "#/" + project.getId() + "/module/list", "文章:" + module.getName(), "void")) .getMap(); return new JsonResult().success().data(articleDtos).page(page).others(others); } // 推荐的文章 List<String> categories = customArticleService.queryTop10RecommendCategory(); List<Article> articles = customArticleService.queryArticle(null, null, type, category, status, page); List<ArticleDto> articleDtos = ArticleAdapter.getDto(articles, null); Map<String, Object> others = MyHashMap.getMap("type", ArticleType.valueOf(type).getName()) .put("category", category) .put("categorys", categories) .put("crumbs", Tools.getCrumbs( "推荐文章列表", "void")) .getMap(); return new JsonResult().success().data(articleDtos).page(page).others(others); } @RequestMapping("/front/article/detail.do") @ResponseBody public JsonResult articleDetail(@RequestParam String id, String password, String visitCode, Integer currentPage) throws MyException { Map<String, Object> returnMap = new HashMap<>(); ArticleWithBLOBs article = null; article = articleService.getById(id); if (article == null) { article = customArticleService.selectByKey(id); } if (article == null) { throw new MyException(MyError.E000020); } id = article.getId(); Module module = moduleCache.get(article.getModuleId()); Project project = projectCache.get(module.getProjectId()); // 如果是私有项目,必须登录才能访问,公开项目需要查看是否需要密码 checkFrontPermission(password, visitCode, project); if (article.getType().equals(ArticleType.DICTIONARY.name())) { return new JsonResult().success().data(article).others(returnMap); } // 初始化前端js评论对象 Comment comment = new Comment(); comment.setArticleId(id); returnMap.put("comment", comment); // 评论 Page page = new Page(10, currentPage); List<Comment> comments = customCommentService.selectByArticelId(id, null, page); page.setAllRow(customCommentService.countByArticleId(id)); returnMap.put("comments", CommentAdapter.getDto(comments)); returnMap.put("commentCode", settingCache.get(S_COMMENTCODE).getValue()); // 更新点击量 customArticleService.updateClickById(id); List<CrumbDto> crumbDtos = MyCrumbDtoList.getList("模块:" + project.getName(), "#/" + project.getId() + "/module/list") .add("文章:" + module.getName(), "#/" + project.getId() + "/article/list/" + module.getId() + "/ARTICLE/NULL/NULL/NULL") .add(article.getName(), "void") .getList(); returnMap.put("crumbs", crumbDtos); return new JsonResult(1, article, page, returnMap); } }
修改bug
api/src/main/java/cn/crap/controller/front/ArticleController.java
修改bug
<ide><path>pi/src/main/java/cn/crap/controller/front/ArticleController.java <ide> List<Article> articles = customArticleService.queryArticle(null, null, type, category, status, page); <ide> List<ArticleDto> articleDtos = ArticleAdapter.getDto(articles, null); <ide> <add> page.setAllRow(customArticleService.countByModuleId(null, null, type, category, status)); <ide> Map<String, Object> others = MyHashMap.getMap("type", ArticleType.valueOf(type).getName()) <ide> .put("category", category) <ide> .put("categorys", categories)
JavaScript
apache-2.0
3a83129d9415f56148d02827b65a49af05eb75d1
0
researchstudio-sat/webofneeds,researchstudio-sat/webofneeds,researchstudio-sat/webofneeds,researchstudio-sat/webofneeds,researchstudio-sat/webofneeds,researchstudio-sat/webofneeds,researchstudio-sat/webofneeds
/** * Created by ksinger on 20.08.2015. */ ; import angular from 'angular'; import { attach } from '../utils'; import { actionCreators } from '../actions/actions'; import * as srefUtils from '../sref-utils'; function genLogoutConf() { //let template = `<a class="wl__button clickable" ng-click="self.hideLogin()"> // <span class="wl__button__caption">{{self.email}}</span> // <img src="generated/icon-sprite.svg#ico16_arrow_up" class="wl__button__carret"> // <img src="generated/icon-sprite.svg#ico36_person" class="wl__button__icon"> // </a> // <a class="wl__button" ui-sref="{{ self.absSRef('about') }}">About</a> // <button class="won-button--filled lighterblue" ng-click="::self.logout()">Sign out</button>`; let template = `<a class="menu-root-btn clickable" ng-click="self.hideLogin()"> <span class="mrb__caption">{{self.email}}</span> <img src="generated/icon-sprite.svg#ico16_arrow_up" class="mrb__carret"> <img src="generated/icon-sprite.svg#ico36_person" class="mrb__icon"> </a> <!--<ul class="menu-entries">--> <!--<a ui-sref="{{ self.absSRef('about') }}">About</a>--> <!--</ul>--> <div style="width: 100%;" class="wl__button"> <a class="wl__button" style="margin-left: auto; margin-right: auto; color: #f04646;"> About </a> </div> <button class="won-button--filled lighterblue" ng-click="::self.logout()">Sign out</button>`; const serviceDependencies = ['$ngRedux', '$scope', /*'$routeParams' /*injections as strings here*/]; class Controller { constructor(/* arguments <- serviceDependencies */){ attach(this, serviceDependencies, arguments); Object.assign(this, srefUtils); this.email = ""; this.password = ""; const logout = (state) => ({ loggedIn: state.getIn(['user','loggedIn']), email: state.getIn(['user','email']) }); const disconnect = this.$ngRedux.connect(logout, actionCreators)(this); this.$scope.$on('$destroy',disconnect); } } Controller.$inject = serviceDependencies; return { restrict: 'E', controller: Controller, controllerAs: 'self', bindToController: true, //scope-bindings -> ctrl scope: {open: '='}, template: template } } export default angular.module('won.owner.components.logout', []) .directive('wonLogout', genLogoutConf) .name;
webofneeds/won-owner-webapp/src/main/webapp/app/components/logout.js
/** * Created by ksinger on 20.08.2015. */ ; import angular from 'angular'; import { attach } from '../utils'; import { actionCreators } from '../actions/actions'; import * as srefUtils from '../sref-utils'; function genLogoutConf() { //let template = `<a class="wl__button clickable" ng-click="self.hideLogin()"> // <span class="wl__button__caption">{{self.email}}</span> // <img src="generated/icon-sprite.svg#ico16_arrow_up" class="wl__button__carret"> // <img src="generated/icon-sprite.svg#ico36_person" class="wl__button__icon"> // </a> // <a class="wl__button" ui-sref="{{ self.absSRef('about') }}">About</a> // <button class="won-button--filled lighterblue" ng-click="::self.logout()">Sign out</button>`; let template = `<a class="menu-root-btn clickable" ng-click="self.hideLogin()"> <span class="mrb__caption">{{self.email}}</span> <img src="generated/icon-sprite.svg#ico16_arrow_up" class="mrb__carret"> <img src="generated/icon-sprite.svg#ico36_person" class="mrb__icon"> </a> <ul class="menu-entries"> <a ui-sref="{{ self.absSRef('about') }}">About</a> </ul> <button class="won-button--filled lighterblue" ng-click="::self.logout()">Sign out</button>`; const serviceDependencies = ['$ngRedux', '$scope', /*'$routeParams' /*injections as strings here*/]; class Controller { constructor(/* arguments <- serviceDependencies */){ attach(this, serviceDependencies, arguments); Object.assign(this, srefUtils); this.email = ""; this.password = ""; const logout = (state) => ({ loggedIn: state.getIn(['user','loggedIn']), email: state.getIn(['user','email']) }); const disconnect = this.$ngRedux.connect(logout, actionCreators)(this); this.$scope.$on('$destroy',disconnect); } } Controller.$inject = serviceDependencies; return { restrict: 'E', controller: Controller, controllerAs: 'self', bindToController: true, //scope-bindings -> ctrl scope: {open: '='}, template: template } } export default angular.module('won.owner.components.logout', []) .directive('wonLogout', genLogoutConf) .name;
Tinkering with link to about in logout-menu.
webofneeds/won-owner-webapp/src/main/webapp/app/components/logout.js
Tinkering with link to about in logout-menu.
<ide><path>ebofneeds/won-owner-webapp/src/main/webapp/app/components/logout.js <ide> <img src="generated/icon-sprite.svg#ico16_arrow_up" class="mrb__carret"> <ide> <img src="generated/icon-sprite.svg#ico36_person" class="mrb__icon"> <ide> </a> <del> <ul class="menu-entries"> <del> <a ui-sref="{{ self.absSRef('about') }}">About</a> <del> </ul> <add> <!--<ul class="menu-entries">--> <add> <!--<a ui-sref="{{ self.absSRef('about') }}">About</a>--> <add> <!--</ul>--> <add> <div style="width: 100%;" class="wl__button"> <add> <a class="wl__button" <add> style="margin-left: auto; margin-right: auto; color: #f04646;"> <add> About <add> </a> <add> </div> <ide> <button class="won-button--filled lighterblue" ng-click="::self.logout()">Sign out</button>`; <ide> <ide> const serviceDependencies = ['$ngRedux', '$scope', /*'$routeParams' /*injections as strings here*/];
Java
bsd-3-clause
ee1040ddb88fe037b8e37486ec93ec674e423641
0
jesperpedersen/pgjdbc-ng,brettwooldridge/pgjdbc-ng,gregb/pgjdbc-ng,gregb/pgjdbc-ng,jesperpedersen/pgjdbc-ng,frode-carlsen/pgjdbc-ng
package com.impossibl.postgres.jdbc; import static com.impossibl.postgres.jdbc.ErrorUtils.makeSQLException; import static com.impossibl.postgres.jdbc.ErrorUtils.makeSQLWarningChain; import static com.impossibl.postgres.jdbc.Exceptions.INVALID_COMMAND_FOR_GENERATED_KEYS; import static com.impossibl.postgres.jdbc.Exceptions.NOT_IMPLEMENTED; import static com.impossibl.postgres.jdbc.Exceptions.NOT_SUPPORTED; import static com.impossibl.postgres.jdbc.Exceptions.UNWRAP_ERROR; import static com.impossibl.postgres.jdbc.SQLTextUtils.appendReturningClause; import static com.impossibl.postgres.jdbc.SQLTextUtils.getBeginText; import static com.impossibl.postgres.jdbc.SQLTextUtils.getCommitText; import static com.impossibl.postgres.jdbc.SQLTextUtils.getGetSessionIsolationLevelText; import static com.impossibl.postgres.jdbc.SQLTextUtils.getGetSessionReadabilityText; import static com.impossibl.postgres.jdbc.SQLTextUtils.getIsolationLevel; import static com.impossibl.postgres.jdbc.SQLTextUtils.getReleaseSavepointText; import static com.impossibl.postgres.jdbc.SQLTextUtils.getRollbackText; import static com.impossibl.postgres.jdbc.SQLTextUtils.getRollbackToText; import static com.impossibl.postgres.jdbc.SQLTextUtils.getSetSavepointText; import static com.impossibl.postgres.jdbc.SQLTextUtils.getSetSessionIsolationLevelText; import static com.impossibl.postgres.jdbc.SQLTextUtils.getSetSessionReadabilityText; import static com.impossibl.postgres.jdbc.SQLTextUtils.isTrue; import static com.impossibl.postgres.protocol.TransactionStatus.Idle; import static java.sql.ResultSet.CLOSE_CURSORS_AT_COMMIT; import static java.sql.ResultSet.CONCUR_READ_ONLY; import static java.sql.ResultSet.TYPE_FORWARD_ONLY; import static java.sql.Statement.RETURN_GENERATED_KEYS; import static java.util.Arrays.asList; import static java.util.Collections.unmodifiableMap; import java.io.IOException; import java.lang.ref.WeakReference; import java.net.SocketAddress; import java.sql.Array; import java.sql.Blob; import java.sql.CallableStatement; import java.sql.Clob; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.NClob; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLClientInfoException; import java.sql.SQLException; import java.sql.SQLWarning; import java.sql.SQLXML; import java.sql.Savepoint; import java.sql.Struct; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.concurrent.Executor; import com.impossibl.postgres.protocol.Command; import com.impossibl.postgres.protocol.PrepareCommand; import com.impossibl.postgres.system.BasicContext; import com.impossibl.postgres.system.NoticeException; import com.impossibl.postgres.types.ArrayType; import com.impossibl.postgres.types.Type; class PGConnection extends BasicContext implements Connection { long statementId = 0l; long portalId = 0l; int savepointId; private int holdability; boolean autoCommit = true; boolean readOnly = false; int networkTimeout; SQLWarning warningChain; List<WeakReference<PGStatement>> activeStatements; PGConnection(SocketAddress address, Properties settings, Map<String, Class<?>> targetTypeMap) throws IOException { super(address, settings, targetTypeMap); activeStatements = new ArrayList<>(); } protected void finalize() throws SQLException { close(); } /** * Ensure the connection is not closed * * @throws SQLException * If the connection is closed */ void checkClosed() throws SQLException { if(isClosed()) throw new SQLException("connection closed"); } /** * Ensures the connection is currently in manual-commit mode * * @throws SQLException * If the connection is not in manual-commit mode */ void checkManualCommit() throws SQLException { if(autoCommit != false) throw new SQLException("must not be in auto-commit mode"); } /** * Ensures the connection is currently in auto-commit mode * * @throws SQLException * IF the connection is not in auto-commit mode */ void checkAutoCommit() throws SQLException { if(autoCommit != false) throw new SQLException("must be in auto-commit mode"); } /** * Ensures that a transaction is active when in manual commit mode * * @throws SQLException */ void checkTransaction() throws SQLException { if(!autoCommit && protocol.getTransactionStatus() == Idle) { try { execQuery(getBeginText()); } catch(IOException e) { throw new SQLException(e); } catch(NoticeException e) { throw makeSQLException(e.getNotice()); } } } /** * Generates and returns the next unique statement name for this connection * * @return New unique statement name */ String getNextStatementName() { return String.format("%016X", ++statementId); } /** * Generates and returns the next unique portal name for this connection * * @return New unique portal name */ String getNextPortalName() { return String.format("%016X", ++portalId); } /** * Called by statements to notify the connection of their closure * * @param statement */ void handleStatementClosure(PGStatement statement) { Iterator<WeakReference<PGStatement>> stmtRefIter = activeStatements.iterator(); while(stmtRefIter.hasNext()) { PGStatement stmt = stmtRefIter.next().get(); if(stmt == null || stmt == statement) { stmtRefIter.remove(); } } } /** * Closes all active statements for this connection * * @throws SQLException */ void closeStatements() throws SQLException { for(WeakReference<PGStatement> stmtRef : activeStatements) { PGStatement statement = stmtRef.get(); if(statement != null) statement.internalClose(); } } /** * Executes the given command and throws a SQLException if an error was * encountered and returns a chain of SQLWarnings if any were generated. * * @param cmd * Command to execute * @return Chain of SQLWarning objects if any were encountered * @throws SQLException * If an error was encountered */ SQLWarning execute(Command cmd) throws SQLException { checkTransaction(); try { protocol.execute(cmd); if(cmd.getError() != null) { throw makeSQLException(cmd.getError()); } return makeSQLWarningChain(cmd.getWarnings()); } catch(IOException e) { throw new SQLException(e); } } /** * Executes the given SQL text ignoring all result values * * @param sql * SQL text to execute * @throws SQLException * If an error was encountered during execution */ void execute(String sql) throws SQLException { checkTransaction(); try { execQuery(sql); } catch(IOException e) { throw new SQLException(e); } catch(NoticeException e) { throw makeSQLException(e.getNotice()); } } /** * Executes the given SQL text returning the first column of the first row * * @param sql * SQL text to execute * @return String String value of the 1st column of the 1st row or empty * string if no results are available * @throws SQLException * If an error was encountered during execution */ String executeForString(String sql) throws SQLException { checkTransaction(); try { return execQueryForString(sql); } catch(IOException e) { throw new SQLException(e); } catch(NoticeException e) { throw makeSQLException(e.getNotice()); } } /** * Executes the given SQL text returning the first column of the first row * * @param sql * SQL text to execute * @return String String value of the 1st column of the 1st row or empty * string if no results are available * @throws SQLException * If an error was encountered during execution */ <T> T executeForResult(String sql, Class<T> returnType, Object... params) throws SQLException { checkTransaction(); try { List<Object[]> res = execQuery(sql, Object[].class, params); if(res.isEmpty()) return null; Object[] resRow = res.get(0); if(resRow.length == 0) return null; return returnType.cast(resRow[0]); } catch(IOException e) { throw new SQLException(e); } catch(NoticeException e) { throw makeSQLException(e.getNotice()); } } /** * Closes all statemens and shuts down the protocol * * @throws SQLException If an error occurs closing any of the statements */ void internalClose() throws SQLException { closeStatements(); shutdown(); } @Override public boolean isValid(int timeout) throws SQLException { //Not valid if connection is closed if(isClosed()) return false; return executeForString("SELECT '1'::char").equals("1"); } @Override public Map<String, Class<?>> getTypeMap() throws SQLException { checkClosed(); return targetTypeMap; } @Override public void setTypeMap(Map<String, Class<?>> typeMap) throws SQLException { checkClosed(); targetTypeMap = unmodifiableMap(typeMap); } @Override public int getHoldability() throws SQLException { checkClosed(); return holdability; } @Override public void setHoldability(int holdability) throws SQLException { checkClosed(); if( holdability != ResultSet.CLOSE_CURSORS_AT_COMMIT && holdability != ResultSet.HOLD_CURSORS_OVER_COMMIT) { throw new SQLException("illegal argument"); } this.holdability = holdability; } @Override public DatabaseMetaData getMetaData() throws SQLException { checkClosed(); return new PGDatabaseMetaData(this); } @Override public boolean getAutoCommit() throws SQLException { checkClosed(); return autoCommit; } @Override public void setAutoCommit(boolean autoCommit) throws SQLException { checkClosed(); // Do nothing if no change in state if(this.autoCommit == autoCommit) return; // Commit any in-flight transaction (cannot call commit as it will start a // new transaction since we would still be in manual commit mode) if(!this.autoCommit && protocol.getTransactionStatus() != Idle) { execute(getCommitText()); } this.autoCommit = autoCommit; } @Override public boolean isReadOnly() throws SQLException { checkClosed(); String readability = executeForString(getGetSessionReadabilityText()); return isTrue(readability); } @Override public void setReadOnly(boolean readOnly) throws SQLException { checkClosed(); if(protocol.getTransactionStatus() != Idle) { throw new SQLException("cannot set read only during a transaction"); } execute(getSetSessionReadabilityText(readOnly)); } @Override public int getTransactionIsolation() throws SQLException { checkClosed(); String isolLevel = executeForString(getGetSessionIsolationLevelText()); return getIsolationLevel(isolLevel); } @Override public void setTransactionIsolation(int level) throws SQLException { checkClosed(); if( level != Connection.TRANSACTION_NONE && level != Connection.TRANSACTION_READ_UNCOMMITTED && level != Connection.TRANSACTION_READ_COMMITTED && level != Connection.TRANSACTION_REPEATABLE_READ && level != Connection.TRANSACTION_SERIALIZABLE) { throw new SQLException("illegal argument"); } execute(getSetSessionIsolationLevelText(level)); } @Override public void commit() throws SQLException { checkClosed(); checkManualCommit(); // Commit the current transaction if(protocol.getTransactionStatus() != Idle) { execute(getCommitText()); } } @Override public void rollback() throws SQLException { checkClosed(); checkManualCommit(); // Roll back the current transaction if(protocol.getTransactionStatus() != Idle) { execute(getRollbackText()); } } @Override public Savepoint setSavepoint() throws SQLException { checkClosed(); checkManualCommit(); // Allocate new save-point name & wrapper PGSavepoint savepoint = new PGSavepoint(++savepointId); // Mark save-point (will auto start txn if needed) execute(getSetSavepointText(savepoint)); return savepoint; } @Override public Savepoint setSavepoint(String name) throws SQLException { checkClosed(); checkManualCommit(); // Allocate new save-point wrapper PGSavepoint savepoint = new PGSavepoint(name); // Mark save-point (will auto start txn if needed) execute(getSetSavepointText(savepoint)); return savepoint; } @Override public void rollback(Savepoint savepointParam) throws SQLException { checkClosed(); checkManualCommit(); PGSavepoint savepoint = (PGSavepoint) savepointParam; if(!savepoint.isValid()) { throw new SQLException("invalid savepoint"); } // Use up the savepoint savepoint.invalidate(); // Rollback to save-point (if in transaction) if(protocol.getTransactionStatus() != Idle) { execute(getRollbackToText(savepoint)); } } @Override public void releaseSavepoint(Savepoint savepointParam) throws SQLException { checkClosed(); checkManualCommit(); PGSavepoint savepoint = (PGSavepoint) savepointParam; if(!savepoint.isValid()) { throw new SQLException("invalid savepoint"); } // Use up the save-point savepoint.invalidate(); // Release the save-point (if in a transaction) if(protocol.getTransactionStatus() != Idle) { execute(getReleaseSavepointText((PGSavepoint) savepoint)); } } @Override public String getCatalog() throws SQLException { checkClosed(); return null; } @Override public void setCatalog(String catalog) throws SQLException { checkClosed(); } @Override public String getSchema() throws SQLException { checkClosed(); return null; } @Override public void setSchema(String schema) throws SQLException { checkClosed(); } @Override public String nativeSQL(String sql) throws SQLException { checkClosed(); SQLText sqlText = new SQLText(sql); SQLTextEscapes.processEscapes(sqlText, this); return sqlText.toString(); } @Override public PGStatement createStatement() throws SQLException { return createStatement(TYPE_FORWARD_ONLY, CONCUR_READ_ONLY, CLOSE_CURSORS_AT_COMMIT); } @Override public PGStatement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException { return createStatement(resultSetType, resultSetConcurrency, CLOSE_CURSORS_AT_COMMIT); } @Override public PGStatement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { checkClosed(); PGSimpleStatement statement = new PGSimpleStatement(this, resultSetType, resultSetConcurrency, resultSetHoldability); activeStatements.add(new WeakReference<PGStatement>(statement)); return statement; } @Override public PGPreparedStatement prepareStatement(String sql) throws SQLException { return prepareStatement(sql, TYPE_FORWARD_ONLY, CONCUR_READ_ONLY, CLOSE_CURSORS_AT_COMMIT); } @Override public PGPreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { return prepareStatement(sql, resultSetType, resultSetConcurrency, CLOSE_CURSORS_AT_COMMIT); } @Override public PGPreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { checkClosed(); SQLText sqlText = new SQLText(sql); return prepareStatement(sqlText, resultSetType, resultSetConcurrency, resultSetHoldability); } public PGPreparedStatement prepareStatement(SQLText sqlText, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { SQLTextEscapes.processEscapes(sqlText, this); String statementName = getNextStatementName(); PrepareCommand prepare = protocol.createPrepare(statementName, sqlText.toString(), Collections.<Type> emptyList()); warningChain = execute(prepare); PGPreparedStatement statement = new PGPreparedStatement(this, resultSetType, resultSetConcurrency, resultSetHoldability, statementName, prepare.getDescribedParameterTypes(), prepare.getDescribedResultFields()); activeStatements.add(new WeakReference<PGStatement>(statement)); return statement; } @Override public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException { checkClosed(); SQLText sqlText = new SQLText(sql); if(autoGeneratedKeys != RETURN_GENERATED_KEYS) { return prepareStatement(sql); } if(appendReturningClause(sqlText) == false) { throw INVALID_COMMAND_FOR_GENERATED_KEYS; } PGPreparedStatement statement = prepareStatement(sqlText, TYPE_FORWARD_ONLY, CONCUR_READ_ONLY, CLOSE_CURSORS_AT_COMMIT); statement.setWantsGeneratedKeys(true); return statement; } @Override public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException { checkClosed(); throw NOT_SUPPORTED; } @Override public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException { checkClosed(); SQLText sqlText = new SQLText(sql); if(appendReturningClause(sqlText, asList(columnNames)) == false) { throw INVALID_COMMAND_FOR_GENERATED_KEYS; } PGPreparedStatement statement = prepareStatement(sqlText, TYPE_FORWARD_ONLY, CONCUR_READ_ONLY, CLOSE_CURSORS_AT_COMMIT); statement.setWantsGeneratedKeys(true); return statement; } @Override public CallableStatement prepareCall(String sql) throws SQLException { checkClosed(); throw NOT_IMPLEMENTED; } @Override public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { checkClosed(); throw NOT_IMPLEMENTED; } @Override public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { checkClosed(); throw NOT_IMPLEMENTED; } @Override public Blob createBlob() throws SQLException { checkClosed(); int loOid = LargeObject.creat(this, 0); return new PGBlob(this, loOid); } @Override public SQLXML createSQLXML() throws SQLException { checkClosed(); throw NOT_IMPLEMENTED; } @Override public Array createArrayOf(String typeName, Object[] elements) throws SQLException { checkClosed(); Type type = getRegistry().loadType("_" + typeName); if(type == null) { throw new SQLException("Array type not found"); } return new PGArray(this, (ArrayType)type, elements); } @Override public Struct createStruct(String typeName, Object[] attributes) throws SQLException { checkClosed(); throw NOT_IMPLEMENTED; } @Override public void setClientInfo(String name, String value) throws SQLClientInfoException { // TODO: implement throw new UnsupportedOperationException(); } @Override public void setClientInfo(Properties properties) throws SQLClientInfoException { // TODO: implement throw new UnsupportedOperationException(); } @Override public String getClientInfo(String name) throws SQLException { checkClosed(); throw NOT_IMPLEMENTED; } @Override public Properties getClientInfo() throws SQLException { checkClosed(); throw NOT_IMPLEMENTED; } @Override public Clob createClob() throws SQLException { checkClosed(); throw NOT_IMPLEMENTED; } @Override public NClob createNClob() throws SQLException { checkClosed(); throw NOT_IMPLEMENTED; } @Override public boolean isClosed() throws SQLException { return protocol == null; } @Override public void close() throws SQLException { // Ignore multiple closes if(isClosed()) return; internalClose(); } @Override public void abort(Executor executor) throws SQLException { throw NOT_IMPLEMENTED; } @Override public SQLWarning getWarnings() throws SQLException { checkClosed(); return warningChain; } @Override public void clearWarnings() throws SQLException { checkClosed(); warningChain = null; } @Override public int getNetworkTimeout() throws SQLException { checkClosed(); return networkTimeout; } @Override public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException { checkClosed(); networkTimeout = milliseconds; } @Override public <T> T unwrap(Class<T> iface) throws SQLException { if(!iface.isAssignableFrom(getClass())) { throw UNWRAP_ERROR; } return iface.cast(this); } @Override public boolean isWrapperFor(Class<?> iface) throws SQLException { return iface.isAssignableFrom(getClass()); } }
src/main/java/com/impossibl/postgres/jdbc/PGConnection.java
package com.impossibl.postgres.jdbc; import static com.impossibl.postgres.jdbc.ErrorUtils.makeSQLException; import static com.impossibl.postgres.jdbc.ErrorUtils.makeSQLWarningChain; import static com.impossibl.postgres.jdbc.Exceptions.INVALID_COMMAND_FOR_GENERATED_KEYS; import static com.impossibl.postgres.jdbc.Exceptions.NOT_IMPLEMENTED; import static com.impossibl.postgres.jdbc.Exceptions.NOT_SUPPORTED; import static com.impossibl.postgres.jdbc.Exceptions.UNWRAP_ERROR; import static com.impossibl.postgres.jdbc.SQLTextUtils.appendReturningClause; import static com.impossibl.postgres.jdbc.SQLTextUtils.getBeginText; import static com.impossibl.postgres.jdbc.SQLTextUtils.getCommitText; import static com.impossibl.postgres.jdbc.SQLTextUtils.getGetSessionIsolationLevelText; import static com.impossibl.postgres.jdbc.SQLTextUtils.getGetSessionReadabilityText; import static com.impossibl.postgres.jdbc.SQLTextUtils.getIsolationLevel; import static com.impossibl.postgres.jdbc.SQLTextUtils.getReleaseSavepointText; import static com.impossibl.postgres.jdbc.SQLTextUtils.getRollbackText; import static com.impossibl.postgres.jdbc.SQLTextUtils.getRollbackToText; import static com.impossibl.postgres.jdbc.SQLTextUtils.getSetSavepointText; import static com.impossibl.postgres.jdbc.SQLTextUtils.getSetSessionIsolationLevelText; import static com.impossibl.postgres.jdbc.SQLTextUtils.getSetSessionReadabilityText; import static com.impossibl.postgres.jdbc.SQLTextUtils.isTrue; import static com.impossibl.postgres.protocol.TransactionStatus.Idle; import static java.sql.ResultSet.CLOSE_CURSORS_AT_COMMIT; import static java.sql.ResultSet.CONCUR_READ_ONLY; import static java.sql.ResultSet.TYPE_FORWARD_ONLY; import static java.sql.Statement.RETURN_GENERATED_KEYS; import static java.util.Arrays.asList; import static java.util.Collections.unmodifiableMap; import java.io.IOException; import java.lang.ref.WeakReference; import java.net.SocketAddress; import java.sql.Array; import java.sql.Blob; import java.sql.CallableStatement; import java.sql.Clob; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.NClob; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLClientInfoException; import java.sql.SQLException; import java.sql.SQLWarning; import java.sql.SQLXML; import java.sql.Savepoint; import java.sql.Struct; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.concurrent.Executor; import com.impossibl.postgres.protocol.Command; import com.impossibl.postgres.protocol.PrepareCommand; import com.impossibl.postgres.system.BasicContext; import com.impossibl.postgres.system.NoticeException; import com.impossibl.postgres.types.Type; class PGConnection extends BasicContext implements Connection { long statementId = 0l; long portalId = 0l; int savepointId; private int holdability; boolean autoCommit = true; boolean readOnly = false; int networkTimeout; SQLWarning warningChain; List<WeakReference<PGStatement>> activeStatements; PGConnection(SocketAddress address, Properties settings, Map<String, Class<?>> targetTypeMap) throws IOException { super(address, settings, targetTypeMap); activeStatements = new ArrayList<>(); } protected void finalize() throws SQLException { close(); } /** * Ensure the connection is not closed * * @throws SQLException * If the connection is closed */ void checkClosed() throws SQLException { if(isClosed()) throw new SQLException("connection closed"); } /** * Ensures the connection is currently in manual-commit mode * * @throws SQLException * If the connection is not in manual-commit mode */ void checkManualCommit() throws SQLException { if(autoCommit != false) throw new SQLException("must not be in auto-commit mode"); } /** * Ensures the connection is currently in auto-commit mode * * @throws SQLException * IF the connection is not in auto-commit mode */ void checkAutoCommit() throws SQLException { if(autoCommit != false) throw new SQLException("must be in auto-commit mode"); } /** * Ensures that a transaction is active when in manual commit mode * * @throws SQLException */ void checkTransaction() throws SQLException { if(!autoCommit && protocol.getTransactionStatus() == Idle) { try { execQuery(getBeginText()); } catch(IOException e) { throw new SQLException(e); } catch(NoticeException e) { throw makeSQLException(e.getNotice()); } } } /** * Generates and returns the next unique statement name for this connection * * @return New unique statement name */ String getNextStatementName() { return String.format("%016X", ++statementId); } /** * Generates and returns the next unique portal name for this connection * * @return New unique portal name */ String getNextPortalName() { return String.format("%016X", ++portalId); } /** * Called by statements to notify the connection of their closure * * @param statement */ void handleStatementClosure(PGStatement statement) { Iterator<WeakReference<PGStatement>> stmtRefIter = activeStatements.iterator(); while(stmtRefIter.hasNext()) { PGStatement stmt = stmtRefIter.next().get(); if(stmt == null || stmt == statement) { stmtRefIter.remove(); } } } /** * Closes all active statements for this connection * * @throws SQLException */ void closeStatements() throws SQLException { for(WeakReference<PGStatement> stmtRef : activeStatements) { PGStatement statement = stmtRef.get(); if(statement != null) statement.internalClose(); } } /** * Executes the given command and throws a SQLException if an error was * encountered and returns a chain of SQLWarnings if any were generated. * * @param cmd * Command to execute * @return Chain of SQLWarning objects if any were encountered * @throws SQLException * If an error was encountered */ SQLWarning execute(Command cmd) throws SQLException { checkTransaction(); try { protocol.execute(cmd); if(cmd.getError() != null) { throw makeSQLException(cmd.getError()); } return makeSQLWarningChain(cmd.getWarnings()); } catch(IOException e) { throw new SQLException(e); } } /** * Executes the given SQL text ignoring all result values * * @param sql * SQL text to execute * @throws SQLException * If an error was encountered during execution */ void execute(String sql) throws SQLException { checkTransaction(); try { execQuery(sql); } catch(IOException e) { throw new SQLException(e); } catch(NoticeException e) { throw makeSQLException(e.getNotice()); } } /** * Executes the given SQL text returning the first column of the first row * * @param sql * SQL text to execute * @return String String value of the 1st column of the 1st row or empty * string if no results are available * @throws SQLException * If an error was encountered during execution */ String executeForString(String sql) throws SQLException { checkTransaction(); try { return execQueryForString(sql); } catch(IOException e) { throw new SQLException(e); } catch(NoticeException e) { throw makeSQLException(e.getNotice()); } } /** * Executes the given SQL text returning the first column of the first row * * @param sql * SQL text to execute * @return String String value of the 1st column of the 1st row or empty * string if no results are available * @throws SQLException * If an error was encountered during execution */ <T> T executeForResult(String sql, Class<T> returnType, Object... params) throws SQLException { checkTransaction(); try { List<Object[]> res = execQuery(sql, Object[].class, params); if(res.isEmpty()) return null; Object[] resRow = res.get(0); if(resRow.length == 0) return null; return returnType.cast(resRow[0]); } catch(IOException e) { throw new SQLException(e); } catch(NoticeException e) { throw makeSQLException(e.getNotice()); } } /** * Closes all statemens and shuts down the protocol * * @throws SQLException If an error occurs closing any of the statements */ void internalClose() throws SQLException { closeStatements(); shutdown(); } @Override public boolean isValid(int timeout) throws SQLException { //Not valid if connection is closed if(isClosed()) return false; return executeForString("SELECT '1'::char").equals("1"); } @Override public Map<String, Class<?>> getTypeMap() throws SQLException { checkClosed(); return targetTypeMap; } @Override public void setTypeMap(Map<String, Class<?>> typeMap) throws SQLException { checkClosed(); targetTypeMap = unmodifiableMap(typeMap); } @Override public int getHoldability() throws SQLException { checkClosed(); return holdability; } @Override public void setHoldability(int holdability) throws SQLException { checkClosed(); if( holdability != ResultSet.CLOSE_CURSORS_AT_COMMIT && holdability != ResultSet.HOLD_CURSORS_OVER_COMMIT) { throw new SQLException("illegal argument"); } this.holdability = holdability; } @Override public DatabaseMetaData getMetaData() throws SQLException { checkClosed(); return new PGDatabaseMetaData(this); } @Override public boolean getAutoCommit() throws SQLException { checkClosed(); return autoCommit; } @Override public void setAutoCommit(boolean autoCommit) throws SQLException { checkClosed(); // Do nothing if no change in state if(this.autoCommit == autoCommit) return; // Commit any in-flight transaction (cannot call commit as it will start a // new transaction since we would still be in manual commit mode) if(!this.autoCommit && protocol.getTransactionStatus() != Idle) { execute(getCommitText()); } this.autoCommit = autoCommit; } @Override public boolean isReadOnly() throws SQLException { checkClosed(); String readability = executeForString(getGetSessionReadabilityText()); return isTrue(readability); } @Override public void setReadOnly(boolean readOnly) throws SQLException { checkClosed(); if(protocol.getTransactionStatus() != Idle) { throw new SQLException("cannot set read only during a transaction"); } execute(getSetSessionReadabilityText(readOnly)); } @Override public int getTransactionIsolation() throws SQLException { checkClosed(); String isolLevel = executeForString(getGetSessionIsolationLevelText()); return getIsolationLevel(isolLevel); } @Override public void setTransactionIsolation(int level) throws SQLException { checkClosed(); if( level != Connection.TRANSACTION_NONE && level != Connection.TRANSACTION_READ_UNCOMMITTED && level != Connection.TRANSACTION_READ_COMMITTED && level != Connection.TRANSACTION_REPEATABLE_READ && level != Connection.TRANSACTION_SERIALIZABLE) { throw new SQLException("illegal argument"); } execute(getSetSessionIsolationLevelText(level)); } @Override public void commit() throws SQLException { checkClosed(); checkManualCommit(); // Commit the current transaction if(protocol.getTransactionStatus() != Idle) { execute(getCommitText()); } } @Override public void rollback() throws SQLException { checkClosed(); checkManualCommit(); // Roll back the current transaction if(protocol.getTransactionStatus() != Idle) { execute(getRollbackText()); } } @Override public Savepoint setSavepoint() throws SQLException { checkClosed(); checkManualCommit(); // Allocate new save-point name & wrapper PGSavepoint savepoint = new PGSavepoint(++savepointId); // Mark save-point (will auto start txn if needed) execute(getSetSavepointText(savepoint)); return savepoint; } @Override public Savepoint setSavepoint(String name) throws SQLException { checkClosed(); checkManualCommit(); // Allocate new save-point wrapper PGSavepoint savepoint = new PGSavepoint(name); // Mark save-point (will auto start txn if needed) execute(getSetSavepointText(savepoint)); return savepoint; } @Override public void rollback(Savepoint savepointParam) throws SQLException { checkClosed(); checkManualCommit(); PGSavepoint savepoint = (PGSavepoint) savepointParam; if(!savepoint.isValid()) { throw new SQLException("invalid savepoint"); } // Use up the savepoint savepoint.invalidate(); // Rollback to save-point (if in transaction) if(protocol.getTransactionStatus() != Idle) { execute(getRollbackToText(savepoint)); } } @Override public void releaseSavepoint(Savepoint savepointParam) throws SQLException { checkClosed(); checkManualCommit(); PGSavepoint savepoint = (PGSavepoint) savepointParam; if(!savepoint.isValid()) { throw new SQLException("invalid savepoint"); } // Use up the save-point savepoint.invalidate(); // Release the save-point (if in a transaction) if(protocol.getTransactionStatus() != Idle) { execute(getReleaseSavepointText((PGSavepoint) savepoint)); } } @Override public String getCatalog() throws SQLException { checkClosed(); return null; } @Override public void setCatalog(String catalog) throws SQLException { checkClosed(); } @Override public String getSchema() throws SQLException { checkClosed(); return null; } @Override public void setSchema(String schema) throws SQLException { checkClosed(); } @Override public String nativeSQL(String sql) throws SQLException { checkClosed(); SQLText sqlText = new SQLText(sql); SQLTextEscapes.processEscapes(sqlText, this); return sqlText.toString(); } @Override public PGStatement createStatement() throws SQLException { return createStatement(TYPE_FORWARD_ONLY, CONCUR_READ_ONLY, CLOSE_CURSORS_AT_COMMIT); } @Override public PGStatement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException { return createStatement(resultSetType, resultSetConcurrency, CLOSE_CURSORS_AT_COMMIT); } @Override public PGStatement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { checkClosed(); PGSimpleStatement statement = new PGSimpleStatement(this, resultSetType, resultSetConcurrency, resultSetHoldability); activeStatements.add(new WeakReference<PGStatement>(statement)); return statement; } @Override public PGPreparedStatement prepareStatement(String sql) throws SQLException { return prepareStatement(sql, TYPE_FORWARD_ONLY, CONCUR_READ_ONLY, CLOSE_CURSORS_AT_COMMIT); } @Override public PGPreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { return prepareStatement(sql, resultSetType, resultSetConcurrency, CLOSE_CURSORS_AT_COMMIT); } @Override public PGPreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { checkClosed(); SQLText sqlText = new SQLText(sql); return prepareStatement(sqlText, resultSetType, resultSetConcurrency, resultSetHoldability); } public PGPreparedStatement prepareStatement(SQLText sqlText, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { SQLTextEscapes.processEscapes(sqlText, this); String statementName = getNextStatementName(); PrepareCommand prepare = protocol.createPrepare(statementName, sqlText.toString(), Collections.<Type> emptyList()); warningChain = execute(prepare); PGPreparedStatement statement = new PGPreparedStatement(this, resultSetType, resultSetConcurrency, resultSetHoldability, statementName, prepare.getDescribedParameterTypes(), prepare.getDescribedResultFields()); activeStatements.add(new WeakReference<PGStatement>(statement)); return statement; } @Override public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException { checkClosed(); SQLText sqlText = new SQLText(sql); if(autoGeneratedKeys != RETURN_GENERATED_KEYS) { return prepareStatement(sql); } if(appendReturningClause(sqlText) == false) { throw INVALID_COMMAND_FOR_GENERATED_KEYS; } PGPreparedStatement statement = prepareStatement(sqlText, TYPE_FORWARD_ONLY, CONCUR_READ_ONLY, CLOSE_CURSORS_AT_COMMIT); statement.setWantsGeneratedKeys(true); return statement; } @Override public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException { checkClosed(); throw NOT_SUPPORTED; } @Override public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException { checkClosed(); SQLText sqlText = new SQLText(sql); if(appendReturningClause(sqlText, asList(columnNames)) == false) { throw INVALID_COMMAND_FOR_GENERATED_KEYS; } PGPreparedStatement statement = prepareStatement(sqlText, TYPE_FORWARD_ONLY, CONCUR_READ_ONLY, CLOSE_CURSORS_AT_COMMIT); statement.setWantsGeneratedKeys(true); return statement; } @Override public CallableStatement prepareCall(String sql) throws SQLException { checkClosed(); throw NOT_IMPLEMENTED; } @Override public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { checkClosed(); throw NOT_IMPLEMENTED; } @Override public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { checkClosed(); throw NOT_IMPLEMENTED; } @Override public Clob createClob() throws SQLException { checkClosed(); throw NOT_IMPLEMENTED; } @Override public Blob createBlob() throws SQLException { checkClosed(); int loOid = LargeObject.creat(this, 0); return new PGBlob(this, loOid); } @Override public NClob createNClob() throws SQLException { checkClosed(); throw NOT_IMPLEMENTED; } @Override public SQLXML createSQLXML() throws SQLException { checkClosed(); throw NOT_IMPLEMENTED; } @Override public void setClientInfo(String name, String value) throws SQLClientInfoException { // TODO: implement throw new UnsupportedOperationException(); } @Override public void setClientInfo(Properties properties) throws SQLClientInfoException { // TODO: implement throw new UnsupportedOperationException(); } @Override public String getClientInfo(String name) throws SQLException { checkClosed(); throw NOT_IMPLEMENTED; } @Override public Properties getClientInfo() throws SQLException { checkClosed(); throw NOT_IMPLEMENTED; } @Override public Array createArrayOf(String typeName, Object[] elements) throws SQLException { checkClosed(); throw NOT_IMPLEMENTED; } @Override public Struct createStruct(String typeName, Object[] attributes) throws SQLException { checkClosed(); throw NOT_IMPLEMENTED; } @Override public boolean isClosed() throws SQLException { return protocol == null; } @Override public void close() throws SQLException { // Ignore multiple closes if(isClosed()) return; internalClose(); } @Override public void abort(Executor executor) throws SQLException { throw NOT_IMPLEMENTED; } @Override public SQLWarning getWarnings() throws SQLException { checkClosed(); return warningChain; } @Override public void clearWarnings() throws SQLException { checkClosed(); warningChain = null; } @Override public int getNetworkTimeout() throws SQLException { checkClosed(); return networkTimeout; } @Override public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException { checkClosed(); networkTimeout = milliseconds; } @Override public <T> T unwrap(Class<T> iface) throws SQLException { if(!iface.isAssignableFrom(getClass())) { throw UNWRAP_ERROR; } return iface.cast(this); } @Override public boolean isWrapperFor(Class<?> iface) throws SQLException { return iface.isAssignableFrom(getClass()); } }
Implement array factory in Connection class
src/main/java/com/impossibl/postgres/jdbc/PGConnection.java
Implement array factory in Connection class
<ide><path>rc/main/java/com/impossibl/postgres/jdbc/PGConnection.java <ide> import com.impossibl.postgres.protocol.PrepareCommand; <ide> import com.impossibl.postgres.system.BasicContext; <ide> import com.impossibl.postgres.system.NoticeException; <add>import com.impossibl.postgres.types.ArrayType; <ide> import com.impossibl.postgres.types.Type; <ide> <ide> <ide> } <ide> <ide> @Override <del> public Clob createClob() throws SQLException { <del> checkClosed(); <del> throw NOT_IMPLEMENTED; <del> } <del> <del> @Override <ide> public Blob createBlob() throws SQLException { <ide> checkClosed(); <ide> <ide> } <ide> <ide> @Override <del> public NClob createNClob() throws SQLException { <del> checkClosed(); <del> throw NOT_IMPLEMENTED; <del> } <del> <del> @Override <ide> public SQLXML createSQLXML() throws SQLException { <add> checkClosed(); <add> throw NOT_IMPLEMENTED; <add> } <add> <add> @Override <add> public Array createArrayOf(String typeName, Object[] elements) throws SQLException { <add> checkClosed(); <add> <add> Type type = getRegistry().loadType("_" + typeName); <add> if(type == null) { <add> throw new SQLException("Array type not found"); <add> } <add> <add> return new PGArray(this, (ArrayType)type, elements); <add> } <add> <add> @Override <add> public Struct createStruct(String typeName, Object[] attributes) throws SQLException { <ide> checkClosed(); <ide> throw NOT_IMPLEMENTED; <ide> } <ide> } <ide> <ide> @Override <del> public Array createArrayOf(String typeName, Object[] elements) throws SQLException { <del> checkClosed(); <del> throw NOT_IMPLEMENTED; <del> } <del> <del> @Override <del> public Struct createStruct(String typeName, Object[] attributes) throws SQLException { <add> public Clob createClob() throws SQLException { <add> checkClosed(); <add> throw NOT_IMPLEMENTED; <add> } <add> <add> @Override <add> public NClob createNClob() throws SQLException { <ide> checkClosed(); <ide> throw NOT_IMPLEMENTED; <ide> }
Java
bsd-2-clause
58c90333205ae939800d1af7fe186989e20466cf
0
imagej/imagej-ops,gab1one/imagej-ops,kephale/imagej-ops,stelfrich/imagej-ops
/* * #%L * ImageJ OPS: a framework for reusable algorithms. * %% * Copyright (C) 2014 Board of Regents of the University of * Wisconsin-Madison and University of Konstanz. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * #L% */ package imagej.ops.threshold; import imagej.ops.AbstractFunction; import imagej.ops.Op; import imagej.ops.threshold.LocalThresholdMethod.Pair; import net.imglib2.Cursor; import net.imglib2.RandomAccessibleInterval; import net.imglib2.algorithm.region.localneighborhood.Neighborhood; import net.imglib2.algorithm.region.localneighborhood.Shape; import net.imglib2.outofbounds.OutOfBoundsFactory; import net.imglib2.type.logic.BitType; import net.imglib2.type.numeric.RealType; import net.imglib2.view.Views; import org.scijava.plugin.Parameter; import org.scijava.plugin.Plugin; /** * @author Martin Horn */ @Plugin(type = Op.class, name = Threshold.NAME) public class LocalThreshold<T extends RealType<T>> extends AbstractFunction<RandomAccessibleInterval<T>, RandomAccessibleInterval<BitType>> implements Threshold { @Parameter private LocalThresholdMethod<T> method; @Parameter private Shape shape; @Parameter(required = false) private OutOfBoundsFactory<T, RandomAccessibleInterval<T>> outOfBounds; @Override public RandomAccessibleInterval<BitType> compute(RandomAccessibleInterval<T> input, RandomAccessibleInterval<BitType> output) { // TODO: provide threaded implementation and specialized ones for // rectangular neighborhoods (using integral images) RandomAccessibleInterval<T> extInput = Views.interval(Views.extend(input, outOfBounds), input); Iterable<Neighborhood<T>> neighborhoods = shape.neighborhoodsSafe(extInput); final Cursor<T> inCursor = Views.flatIterable(input).cursor(); final Cursor<BitType> outCursor = Views.flatIterable(output).cursor(); Pair<T> pair = new Pair<T>(); for (final Neighborhood<T> neighborhood : neighborhoods) { pair.neighborhood = neighborhood; pair.pixel = inCursor.next(); method.compute(pair, outCursor.next()); } return output; } }
src/main/java/imagej/ops/threshold/LocalThreshold.java
/* * #%L * ImageJ OPS: a framework for reusable algorithms. * %% * Copyright (C) 2014 Board of Regents of the University of * Wisconsin-Madison and University of Konstanz. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * #L% */ package imagej.ops.threshold; import imagej.ops.AbstractFunction; import imagej.ops.Op; import imagej.ops.threshold.LocalThresholdMethod.Pair; import net.imglib2.Cursor; import net.imglib2.RandomAccessibleInterval; import net.imglib2.algorithm.region.localneighborhood.Neighborhood; import net.imglib2.algorithm.region.localneighborhood.Shape; import net.imglib2.type.logic.BitType; import net.imglib2.type.numeric.RealType; import net.imglib2.view.Views; import org.scijava.plugin.Parameter; import org.scijava.plugin.Plugin; /** * @author Martin Horn */ @Plugin(type = Op.class, name = Threshold.NAME) public class LocalThreshold<T extends RealType<T>> extends AbstractFunction<RandomAccessibleInterval<T>, RandomAccessibleInterval<BitType>> implements Threshold { @Parameter private LocalThresholdMethod<T> method; @Parameter private Shape shape; @Override public RandomAccessibleInterval<BitType> compute(RandomAccessibleInterval<T> input, RandomAccessibleInterval<BitType> output) { // TODO: provide threaded implementation and specialized ones for // rectangular neighborhoods (using integral images) Iterable<Neighborhood<T>> neighborhoods = shape.neighborhoodsSafe(input); final Cursor<T> inCursor = Views.flatIterable(input).cursor(); final Cursor<BitType> outCursor = Views.flatIterable(output).cursor(); Pair<T> pair = new Pair<T>(); for (final Neighborhood<T> neighborhood : neighborhoods) { pair.neighborhood = neighborhood; pair.pixel = inCursor.next(); method.compute(pair, outCursor.next()); } return output; } }
OutOfBoundFactory for LocalThreshold
src/main/java/imagej/ops/threshold/LocalThreshold.java
OutOfBoundFactory for LocalThreshold
<ide><path>rc/main/java/imagej/ops/threshold/LocalThreshold.java <ide> import net.imglib2.RandomAccessibleInterval; <ide> import net.imglib2.algorithm.region.localneighborhood.Neighborhood; <ide> import net.imglib2.algorithm.region.localneighborhood.Shape; <add>import net.imglib2.outofbounds.OutOfBoundsFactory; <ide> import net.imglib2.type.logic.BitType; <ide> import net.imglib2.type.numeric.RealType; <ide> import net.imglib2.view.Views; <ide> @Parameter <ide> private Shape shape; <ide> <add> @Parameter(required = false) <add> private OutOfBoundsFactory<T, RandomAccessibleInterval<T>> outOfBounds; <add> <ide> @Override <ide> public RandomAccessibleInterval<BitType> <ide> compute(RandomAccessibleInterval<T> input, <ide> { <ide> // TODO: provide threaded implementation and specialized ones for <ide> // rectangular neighborhoods (using integral images) <del> <del> Iterable<Neighborhood<T>> neighborhoods = shape.neighborhoodsSafe(input); <add> RandomAccessibleInterval<T> extInput = <add> Views.interval(Views.extend(input, outOfBounds), input); <add> Iterable<Neighborhood<T>> neighborhoods = shape.neighborhoodsSafe(extInput); <ide> final Cursor<T> inCursor = Views.flatIterable(input).cursor(); <ide> final Cursor<BitType> outCursor = Views.flatIterable(output).cursor(); <ide> Pair<T> pair = new Pair<T>();
Java
apache-2.0
1c68c3bc831bc62b588b3e05fa08008c573bc8ce
0
leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc
/* * Copyright 2016-2018 shardingsphere.io. * <p> * 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. * </p> */ package io.shardingsphere.shardingjdbc.jdbc.adapter; import com.google.common.base.Preconditions; import com.google.common.collect.HashMultimap; import com.google.common.collect.Multimap; import io.shardingsphere.core.constant.ConnectionMode; import io.shardingsphere.core.constant.transaction.TransactionOperationType; import io.shardingsphere.core.constant.transaction.TransactionType; import io.shardingsphere.core.event.transaction.base.SagaTransactionEvent; import io.shardingsphere.core.event.transaction.xa.XATransactionEvent; import io.shardingsphere.core.hint.HintManagerHolder; import io.shardingsphere.core.routing.router.masterslave.MasterVisitedManager; import io.shardingsphere.shardingjdbc.jdbc.adapter.executor.ForceExecuteCallback; import io.shardingsphere.shardingjdbc.jdbc.adapter.executor.ForceExecuteTemplate; import io.shardingsphere.shardingjdbc.jdbc.unsupported.AbstractUnsupportedOperationConnection; import io.shardingsphere.shardingjdbc.transaction.TransactionTypeHolder; import io.shardingsphere.spi.root.RootInvokeHook; import io.shardingsphere.spi.root.SPIRootInvokeHook; import io.shardingsphere.spi.transaction.ShardingTransactionHandlerRegistry; import javax.sql.DataSource; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.SQLWarning; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Map.Entry; /** * Adapter for {@code Connection}. * * @author zhangliang * @author panjuan */ public abstract class AbstractConnectionAdapter extends AbstractUnsupportedOperationConnection { private final Multimap<String, Connection> cachedConnections = HashMultimap.create(); private boolean autoCommit = true; private boolean readOnly = true; private boolean closed; private int transactionIsolation = TRANSACTION_READ_UNCOMMITTED; private final ForceExecuteTemplate<Connection> forceExecuteTemplate = new ForceExecuteTemplate<>(); private final ForceExecuteTemplate<Entry<String, Connection>> forceExecuteTemplateForClose = new ForceExecuteTemplate<>(); private final RootInvokeHook rootInvokeHook = new SPIRootInvokeHook(); private final TransactionType transactionType = TransactionType.LOCAL; private final ShardingTransactionHandlerRegistry transactionRegistry = ShardingTransactionHandlerRegistry.getInstance(); protected AbstractConnectionAdapter() { rootInvokeHook.start(); } /** * Get database connection. * * @param dataSourceName data source name * @return database connection * @throws SQLException SQL exception */ public final Connection getConnection(final String dataSourceName) throws SQLException { return getConnections(ConnectionMode.MEMORY_STRICTLY, dataSourceName, 1).get(0); } /** * Get database connections. * * @param connectionMode connection mode * @param dataSourceName data source name * @param connectionSize size of connection list to be get * @return database connections * @throws SQLException SQL exception */ public final List<Connection> getConnections(final ConnectionMode connectionMode, final String dataSourceName, final int connectionSize) throws SQLException { DataSource dataSource = getDataSourceMap().get(dataSourceName); Preconditions.checkState(null != dataSource, "Missing the data source name: '%s'", dataSourceName); Collection<Connection> connections; synchronized (cachedConnections) { connections = cachedConnections.get(dataSourceName); } List<Connection> result; if (connections.size() >= connectionSize) { result = new ArrayList<>(connections).subList(0, connectionSize); } else if (!connections.isEmpty()) { result = new ArrayList<>(connectionSize); result.addAll(connections); List<Connection> newConnections = createConnections(connectionMode, dataSource, connectionSize - connections.size()); result.addAll(newConnections); synchronized (cachedConnections) { cachedConnections.putAll(dataSourceName, newConnections); } } else { result = new ArrayList<>(createConnections(connectionMode, dataSource, connectionSize)); synchronized (cachedConnections) { cachedConnections.putAll(dataSourceName, result); } } return result; } @SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter") private List<Connection> createConnections(final ConnectionMode connectionMode, final DataSource dataSource, final int connectionSize) throws SQLException { if (1 == connectionSize) { return Collections.singletonList(createConnection(dataSource)); } if (ConnectionMode.CONNECTION_STRICTLY == connectionMode) { return createConnections(dataSource, connectionSize); } synchronized (dataSource) { return createConnections(dataSource, connectionSize); } } private List<Connection> createConnections(final DataSource dataSource, final int connectionSize) throws SQLException { List<Connection> result = new ArrayList<>(connectionSize); for (int i = 0; i < connectionSize; i++) { result.add(createConnection(dataSource)); } return result; } private Connection createConnection(final DataSource dataSource) throws SQLException { Connection result = dataSource.getConnection(); replayMethodsInvocation(result); return result; } protected abstract Map<String, DataSource> getDataSourceMap(); protected final void removeCache(final Connection connection) { cachedConnections.values().remove(connection); } @Override public final boolean getAutoCommit() { return autoCommit; } @Override public final void setAutoCommit(final boolean autoCommit) throws SQLException { this.autoCommit = autoCommit; if (TransactionType.LOCAL == transactionType) { recordMethodInvocation(Connection.class, "setAutoCommit", new Class[]{boolean.class}, new Object[]{autoCommit}); forceExecuteTemplate.execute(cachedConnections.values(), new ForceExecuteCallback<Connection>() { @Override public void execute(final Connection connection) throws SQLException { connection.setAutoCommit(autoCommit); } }); } else if (TransactionType.XA == transactionType) { transactionRegistry.getHandler(TransactionType.XA).doInTransaction(new XATransactionEvent(TransactionOperationType.BEGIN)); } else if (TransactionType.BASE == transactionType) { transactionRegistry.getHandler(TransactionType.BASE).doInTransaction(new SagaTransactionEvent(TransactionOperationType.BEGIN, this)); } } @Override public final void commit() throws SQLException { if (TransactionType.LOCAL == transactionType) { forceExecuteTemplate.execute(cachedConnections.values(), new ForceExecuteCallback<Connection>() { @Override public void execute(final Connection connection) throws SQLException { connection.commit(); } }); } else if (TransactionType.XA == transactionType) { transactionRegistry.getHandler(TransactionType.XA).doInTransaction(new XATransactionEvent(TransactionOperationType.COMMIT)); } else if (TransactionType.BASE == transactionType) { transactionRegistry.getHandler(TransactionType.BASE).doInTransaction(new SagaTransactionEvent(TransactionOperationType.COMMIT)); } } @Override public final void rollback() throws SQLException { if (TransactionType.LOCAL == transactionType) { forceExecuteTemplate.execute(cachedConnections.values(), new ForceExecuteCallback<Connection>() { @Override public void execute(final Connection connection) throws SQLException { connection.rollback(); } }); } else if (TransactionType.XA == transactionType) { transactionRegistry.getHandler(TransactionType.XA).doInTransaction(new XATransactionEvent(TransactionOperationType.ROLLBACK)); } else if (TransactionType.BASE == transactionType) { transactionRegistry.getHandler(TransactionType.BASE).doInTransaction(new SagaTransactionEvent(TransactionOperationType.ROLLBACK)); } } @Override public final void close() throws SQLException { if (closed) { return; } closed = true; HintManagerHolder.clear(); MasterVisitedManager.clear(); TransactionTypeHolder.clear(); int connectionSize = cachedConnections.size(); try { forceExecuteTemplateForClose.execute(cachedConnections.entries(), new ForceExecuteCallback<Map.Entry<String, Connection>>() { @Override public void execute(final Entry<String, Connection> cachedConnections) throws SQLException { cachedConnections.getValue().close(); } }); } finally { rootInvokeHook.finish(connectionSize); } } @Override public final boolean isClosed() { return closed; } @Override public final boolean isReadOnly() { return readOnly; } @Override public final void setReadOnly(final boolean readOnly) throws SQLException { this.readOnly = readOnly; recordMethodInvocation(Connection.class, "setReadOnly", new Class[]{boolean.class}, new Object[]{readOnly}); forceExecuteTemplate.execute(cachedConnections.values(), new ForceExecuteCallback<Connection>() { @Override public void execute(final Connection connection) throws SQLException { connection.setReadOnly(readOnly); } }); } @Override public final int getTransactionIsolation() throws SQLException { if (cachedConnections.values().isEmpty()) { return transactionIsolation; } return cachedConnections.values().iterator().next().getTransactionIsolation(); } @Override public final void setTransactionIsolation(final int level) throws SQLException { transactionIsolation = level; recordMethodInvocation(Connection.class, "setTransactionIsolation", new Class[]{int.class}, new Object[]{level}); forceExecuteTemplate.execute(cachedConnections.values(), new ForceExecuteCallback<Connection>() { @Override public void execute(final Connection connection) throws SQLException { connection.setTransactionIsolation(level); } }); } // ------- Consist with MySQL driver implementation ------- @Override public final SQLWarning getWarnings() { return null; } @Override public void clearWarnings() { } @Override public final int getHoldability() { return ResultSet.CLOSE_CURSORS_AT_COMMIT; } @Override public final void setHoldability(final int holdability) { } }
sharding-jdbc/sharding-jdbc-core/src/main/java/io/shardingsphere/shardingjdbc/jdbc/adapter/AbstractConnectionAdapter.java
/* * Copyright 2016-2018 shardingsphere.io. * <p> * 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. * </p> */ package io.shardingsphere.shardingjdbc.jdbc.adapter; import com.google.common.base.Preconditions; import com.google.common.collect.HashMultimap; import com.google.common.collect.Multimap; import io.shardingsphere.core.constant.ConnectionMode; import io.shardingsphere.core.constant.transaction.TransactionOperationType; import io.shardingsphere.core.constant.transaction.TransactionType; import io.shardingsphere.core.event.transaction.base.SagaTransactionEvent; import io.shardingsphere.core.event.transaction.xa.XATransactionEvent; import io.shardingsphere.core.hint.HintManagerHolder; import io.shardingsphere.core.routing.router.masterslave.MasterVisitedManager; import io.shardingsphere.shardingjdbc.jdbc.adapter.executor.ForceExecuteCallback; import io.shardingsphere.shardingjdbc.jdbc.adapter.executor.ForceExecuteTemplate; import io.shardingsphere.shardingjdbc.jdbc.unsupported.AbstractUnsupportedOperationConnection; import io.shardingsphere.shardingjdbc.transaction.TransactionTypeHolder; import io.shardingsphere.spi.root.RootInvokeHook; import io.shardingsphere.spi.root.SPIRootInvokeHook; import io.shardingsphere.spi.transaction.ShardingTransactionHandlerRegistry; import javax.sql.DataSource; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.SQLWarning; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Map.Entry; /** * Adapter for {@code Connection}. * * @author zhangliang * @author panjuan */ public abstract class AbstractConnectionAdapter extends AbstractUnsupportedOperationConnection { private final Multimap<String, Connection> cachedConnections = HashMultimap.create(); private boolean autoCommit = true; private boolean readOnly = true; private boolean closed; private int transactionIsolation = TRANSACTION_READ_UNCOMMITTED; private final ForceExecuteTemplate<Connection> forceExecuteTemplate = new ForceExecuteTemplate<>(); private final ForceExecuteTemplate<Entry<String, Connection>> forceExecuteTemplateForClose = new ForceExecuteTemplate<>(); private final RootInvokeHook rootInvokeHook = new SPIRootInvokeHook(); private final ShardingTransactionHandlerRegistry transactionRegistry = ShardingTransactionHandlerRegistry.getInstance(); protected AbstractConnectionAdapter() { rootInvokeHook.start(); } /** * Get database connection. * * @param dataSourceName data source name * @return database connection * @throws SQLException SQL exception */ public final Connection getConnection(final String dataSourceName) throws SQLException { return getConnections(ConnectionMode.MEMORY_STRICTLY, dataSourceName, 1).get(0); } /** * Get database connections. * * @param connectionMode connection mode * @param dataSourceName data source name * @param connectionSize size of connection list to be get * @return database connections * @throws SQLException SQL exception */ public final List<Connection> getConnections(final ConnectionMode connectionMode, final String dataSourceName, final int connectionSize) throws SQLException { DataSource dataSource = getDataSourceMap().get(dataSourceName); Preconditions.checkState(null != dataSource, "Missing the data source name: '%s'", dataSourceName); Collection<Connection> connections; synchronized (cachedConnections) { connections = cachedConnections.get(dataSourceName); } List<Connection> result; if (connections.size() >= connectionSize) { result = new ArrayList<>(connections).subList(0, connectionSize); } else if (!connections.isEmpty()) { result = new ArrayList<>(connectionSize); result.addAll(connections); List<Connection> newConnections = createConnections(connectionMode, dataSource, connectionSize - connections.size()); result.addAll(newConnections); synchronized (cachedConnections) { cachedConnections.putAll(dataSourceName, newConnections); } } else { result = new ArrayList<>(createConnections(connectionMode, dataSource, connectionSize)); synchronized (cachedConnections) { cachedConnections.putAll(dataSourceName, result); } } return result; } @SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter") private List<Connection> createConnections(final ConnectionMode connectionMode, final DataSource dataSource, final int connectionSize) throws SQLException { if (1 == connectionSize) { return Collections.singletonList(createConnection(dataSource)); } if (ConnectionMode.CONNECTION_STRICTLY == connectionMode) { return createConnections(dataSource, connectionSize); } synchronized (dataSource) { return createConnections(dataSource, connectionSize); } } private List<Connection> createConnections(final DataSource dataSource, final int connectionSize) throws SQLException { List<Connection> result = new ArrayList<>(connectionSize); for (int i = 0; i < connectionSize; i++) { result.add(createConnection(dataSource)); } return result; } private Connection createConnection(final DataSource dataSource) throws SQLException { Connection result = dataSource.getConnection(); replayMethodsInvocation(result); return result; } protected abstract Map<String, DataSource> getDataSourceMap(); protected final void removeCache(final Connection connection) { cachedConnections.values().remove(connection); } @Override public final boolean getAutoCommit() { return autoCommit; } @Override public void setAutoCommit(final boolean autoCommit) throws SQLException { this.autoCommit = autoCommit; if (TransactionType.LOCAL == TransactionTypeHolder.get()) { recordMethodInvocation(Connection.class, "setAutoCommit", new Class[]{boolean.class}, new Object[]{autoCommit}); forceExecuteTemplate.execute(cachedConnections.values(), new ForceExecuteCallback<Connection>() { @Override public void execute(final Connection connection) throws SQLException { connection.setAutoCommit(autoCommit); } }); } else if (TransactionType.XA == TransactionTypeHolder.get()) { transactionRegistry.getHandler(TransactionType.XA).doInTransaction(new XATransactionEvent(TransactionOperationType.BEGIN)); } else if (TransactionType.BASE == TransactionTypeHolder.get()) { transactionRegistry.getHandler(TransactionType.BASE).doInTransaction(new SagaTransactionEvent(TransactionOperationType.BEGIN, this)); } } @Override public void commit() throws SQLException { if (TransactionType.LOCAL == TransactionTypeHolder.get()) { forceExecuteTemplate.execute(cachedConnections.values(), new ForceExecuteCallback<Connection>() { @Override public void execute(final Connection connection) throws SQLException { connection.commit(); } }); } else if (TransactionType.XA == TransactionTypeHolder.get()) { transactionRegistry.getHandler(TransactionType.XA).doInTransaction(new XATransactionEvent(TransactionOperationType.COMMIT)); } else if (TransactionType.BASE == TransactionTypeHolder.get()) { transactionRegistry.getHandler(TransactionType.BASE).doInTransaction(new SagaTransactionEvent(TransactionOperationType.COMMIT)); } } @Override public void rollback() throws SQLException { if (TransactionType.LOCAL == TransactionTypeHolder.get()) { forceExecuteTemplate.execute(cachedConnections.values(), new ForceExecuteCallback<Connection>() { @Override public void execute(final Connection connection) throws SQLException { connection.rollback(); } }); } else if (TransactionType.XA == TransactionTypeHolder.get()) { transactionRegistry.getHandler(TransactionType.XA).doInTransaction(new XATransactionEvent(TransactionOperationType.ROLLBACK)); } else if (TransactionType.BASE == TransactionTypeHolder.get()) { transactionRegistry.getHandler(TransactionType.BASE).doInTransaction(new SagaTransactionEvent(TransactionOperationType.ROLLBACK)); } } @Override public final void close() throws SQLException { if (closed) { return; } closed = true; HintManagerHolder.clear(); MasterVisitedManager.clear(); TransactionTypeHolder.clear(); int connectionSize = cachedConnections.size(); try { forceExecuteTemplateForClose.execute(cachedConnections.entries(), new ForceExecuteCallback<Map.Entry<String, Connection>>() { @Override public void execute(final Entry<String, Connection> cachedConnections) throws SQLException { cachedConnections.getValue().close(); } }); } finally { rootInvokeHook.finish(connectionSize); } } @Override public final boolean isClosed() { return closed; } @Override public final boolean isReadOnly() { return readOnly; } @Override public final void setReadOnly(final boolean readOnly) throws SQLException { this.readOnly = readOnly; recordMethodInvocation(Connection.class, "setReadOnly", new Class[]{boolean.class}, new Object[]{readOnly}); forceExecuteTemplate.execute(cachedConnections.values(), new ForceExecuteCallback<Connection>() { @Override public void execute(final Connection connection) throws SQLException { connection.setReadOnly(readOnly); } }); } @Override public final int getTransactionIsolation() throws SQLException { if (cachedConnections.values().isEmpty()) { return transactionIsolation; } return cachedConnections.values().iterator().next().getTransactionIsolation(); } @Override public final void setTransactionIsolation(final int level) throws SQLException { transactionIsolation = level; recordMethodInvocation(Connection.class, "setTransactionIsolation", new Class[]{int.class}, new Object[]{level}); forceExecuteTemplate.execute(cachedConnections.values(), new ForceExecuteCallback<Connection>() { @Override public void execute(final Connection connection) throws SQLException { connection.setTransactionIsolation(level); } }); } // ------- Consist with MySQL driver implementation ------- @Override public final SQLWarning getWarnings() { return null; } @Override public void clearWarnings() { } @Override public final int getHoldability() { return ResultSet.CLOSE_CURSORS_AT_COMMIT; } @Override public final void setHoldability(final int holdability) { } }
#1363 Make TransactionType bind with current connection.
sharding-jdbc/sharding-jdbc-core/src/main/java/io/shardingsphere/shardingjdbc/jdbc/adapter/AbstractConnectionAdapter.java
#1363 Make TransactionType bind with current connection.
<ide><path>harding-jdbc/sharding-jdbc-core/src/main/java/io/shardingsphere/shardingjdbc/jdbc/adapter/AbstractConnectionAdapter.java <ide> <ide> private final RootInvokeHook rootInvokeHook = new SPIRootInvokeHook(); <ide> <add> private final TransactionType transactionType = TransactionType.LOCAL; <add> <ide> private final ShardingTransactionHandlerRegistry transactionRegistry = ShardingTransactionHandlerRegistry.getInstance(); <ide> <ide> protected AbstractConnectionAdapter() { <ide> } <ide> <ide> @Override <del> public void setAutoCommit(final boolean autoCommit) throws SQLException { <add> public final void setAutoCommit(final boolean autoCommit) throws SQLException { <ide> this.autoCommit = autoCommit; <del> if (TransactionType.LOCAL == TransactionTypeHolder.get()) { <add> if (TransactionType.LOCAL == transactionType) { <ide> recordMethodInvocation(Connection.class, "setAutoCommit", new Class[]{boolean.class}, new Object[]{autoCommit}); <ide> forceExecuteTemplate.execute(cachedConnections.values(), new ForceExecuteCallback<Connection>() { <ide> <ide> connection.setAutoCommit(autoCommit); <ide> } <ide> }); <del> } else if (TransactionType.XA == TransactionTypeHolder.get()) { <add> } else if (TransactionType.XA == transactionType) { <ide> transactionRegistry.getHandler(TransactionType.XA).doInTransaction(new XATransactionEvent(TransactionOperationType.BEGIN)); <del> } else if (TransactionType.BASE == TransactionTypeHolder.get()) { <add> } else if (TransactionType.BASE == transactionType) { <ide> transactionRegistry.getHandler(TransactionType.BASE).doInTransaction(new SagaTransactionEvent(TransactionOperationType.BEGIN, this)); <ide> } <ide> } <ide> <ide> @Override <del> public void commit() throws SQLException { <del> if (TransactionType.LOCAL == TransactionTypeHolder.get()) { <add> public final void commit() throws SQLException { <add> if (TransactionType.LOCAL == transactionType) { <ide> forceExecuteTemplate.execute(cachedConnections.values(), new ForceExecuteCallback<Connection>() { <ide> <ide> @Override <ide> connection.commit(); <ide> } <ide> }); <del> } else if (TransactionType.XA == TransactionTypeHolder.get()) { <add> } else if (TransactionType.XA == transactionType) { <ide> transactionRegistry.getHandler(TransactionType.XA).doInTransaction(new XATransactionEvent(TransactionOperationType.COMMIT)); <del> } else if (TransactionType.BASE == TransactionTypeHolder.get()) { <add> } else if (TransactionType.BASE == transactionType) { <ide> transactionRegistry.getHandler(TransactionType.BASE).doInTransaction(new SagaTransactionEvent(TransactionOperationType.COMMIT)); <ide> } <ide> } <ide> <ide> @Override <del> public void rollback() throws SQLException { <del> if (TransactionType.LOCAL == TransactionTypeHolder.get()) { <add> public final void rollback() throws SQLException { <add> if (TransactionType.LOCAL == transactionType) { <ide> forceExecuteTemplate.execute(cachedConnections.values(), new ForceExecuteCallback<Connection>() { <ide> <ide> @Override <ide> connection.rollback(); <ide> } <ide> }); <del> } else if (TransactionType.XA == TransactionTypeHolder.get()) { <add> } else if (TransactionType.XA == transactionType) { <ide> transactionRegistry.getHandler(TransactionType.XA).doInTransaction(new XATransactionEvent(TransactionOperationType.ROLLBACK)); <del> } else if (TransactionType.BASE == TransactionTypeHolder.get()) { <add> } else if (TransactionType.BASE == transactionType) { <ide> transactionRegistry.getHandler(TransactionType.BASE).doInTransaction(new SagaTransactionEvent(TransactionOperationType.ROLLBACK)); <ide> } <ide> }
Java
apache-2.0
c09af9d0c9efc0923378900b8731f2b98cdbf97b
0
kurtharriger/spring-osgi
/* * Copyright 2006-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.osgi.iandt; import java.io.File; import java.io.FilePermission; import java.lang.reflect.ReflectPermission; import java.security.Permission; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.PropertyPermission; import java.util.jar.Manifest; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.BundleEvent; import org.osgi.framework.BundlePermission; import org.osgi.framework.Constants; import org.osgi.framework.PackagePermission; import org.osgi.framework.ServicePermission; import org.osgi.framework.ServiceReference; import org.osgi.framework.SynchronousBundleListener; import org.osgi.service.permissionadmin.PermissionAdmin; import org.osgi.service.permissionadmin.PermissionInfo; import org.springframework.core.io.Resource; import org.springframework.osgi.test.AbstractConfigurableBundleCreatorTests; import org.springframework.osgi.test.provisioning.ArtifactLocator; import org.springframework.osgi.util.OsgiStringUtils; import org.springframework.util.ObjectUtils; import org.springframework.util.StringUtils; /** * Base test class used for improving performance of integration tests by * creating bundles only with the classes within a package as opposed to all * resources available in the target folder. * * <p/> Additionally, the class checks for the presence Clover if a certain * property is set and uses a special setup to use the instrumented jars instead * of the naked ones. * * @author Costin Leau * */ public abstract class BaseIntegrationTest extends AbstractConfigurableBundleCreatorTests { private class CloverClassifiedArtifactLocator implements ArtifactLocator { private final ArtifactLocator delegate; public CloverClassifiedArtifactLocator(ArtifactLocator delegate) { this.delegate = delegate; } public Resource locateArtifact(String group, String id, String version, String type) { return parse(id + "-" + version, delegate.locateArtifact(group, id, version, type)); } public Resource locateArtifact(String group, String id, String version) { return parse(id + "-" + version, delegate.locateArtifact(group, id, version)); } private Resource parse(String id, Resource resource) { if (id.indexOf(SPRING_DM_PREFIX) > -1) { try { String relativePath = ""; // check if it's a relative file if (StringUtils.cleanPath(resource.getURI().toString()).indexOf("/target/") > -1) { relativePath = "clover" + File.separator; } relativePath = relativePath + id + "-clover.jar"; Resource res = resource.createRelative(relativePath); BaseIntegrationTest.this.logger.info("Using clover instrumented jar " + res.getDescription()); return res; } catch (Exception ex) { throw (RuntimeException) new IllegalStateException( "Trying to find Clover instrumented class but none is available; disable clover or build the instrumented artifacts").initCause(ex); } } return resource; } } private class PermissionManager implements SynchronousBundleListener { private final PermissionAdmin pa; /** * Constructs a new <code>PermissionManager</code> instance. * * @param bc */ private PermissionManager(BundleContext bc) { ServiceReference ref = bc.getServiceReference(PermissionAdmin.class.getName()); if (ref != null) { logger.trace("Found permission admin " + ref); pa = (PermissionAdmin) bc.getService(ref); bc.addBundleListener(this); logger.trace("Default permissions are " + ObjectUtils.nullSafeToString(pa.getDefaultPermissions())); logger.warn("Security turned ON"); } else { logger.warn("Security turned OFF"); pa = null; } } public void bundleChanged(BundleEvent event) { if (event.getType() == BundleEvent.INSTALLED) { Bundle bnd = event.getBundle(); String location = bnd.getLocation(); if (location.indexOf("iandt") > -1 || location.indexOf("integration-tests") > -1) { logger.trace("Discovered I&T test..."); List perms = getIAndTPermissions(); // define permission info PermissionInfo[] pi = getPIFromPermissions(perms); logger.info("About to set permissions " + perms + " for I&T bundle " + OsgiStringUtils.nullSafeNameAndSymName(bnd) + "@" + location); pa.setPermissions(location, pi); } else if (location.indexOf("onTheFly") > -1) { logger.trace("Discovered on the fly test..."); List perms = getTestPermissions(); // define permission info PermissionInfo[] pi = getPIFromPermissions(perms); logger.info("About to set permissions " + perms + " for OnTheFly bundle " + OsgiStringUtils.nullSafeNameAndSymName(bnd) + "@" + location); pa.setPermissions(location, pi); } } } private PermissionInfo[] getPIFromPermissions(List perms) { PermissionInfo[] pi = new PermissionInfo[perms.size()]; int index = 0; for (Iterator iterator = perms.iterator(); iterator.hasNext();) { Permission perm = (Permission) iterator.next(); pi[index++] = new PermissionInfo(perm.getClass().getName(), perm.getName(), perm.getActions()); } return pi; } } private static final String CLOVER_PROPERTY = "org.springframework.osgi.integration.testing.clover"; private static final String CLOVER_PKG = "com_cenqua_clover"; private static final String SPRING_DM_PREFIX = "spring-osgi"; protected String[] getBundleContentPattern() { String pkg = getClass().getPackage().getName().replace('.', '/').concat("/"); String[] patterns = new String[] { BaseIntegrationTest.class.getName().replace('.', '/').concat("*.class"), pkg + "**/*" }; return patterns; } protected void preProcessBundleContext(BundleContext context) throws Exception { super.preProcessBundleContext(context); PermissionManager pm = new PermissionManager(context); if (isCloverEnabled()) { logger.warn("Test coverage instrumentation (Clover) enabled"); } } private boolean isCloverEnabled() { return Boolean.getBoolean(CLOVER_PROPERTY); } protected ArtifactLocator getLocator() { ArtifactLocator defaultLocator = super.getLocator(); // redirect to the clover artifacts if (isCloverEnabled()) { return new CloverClassifiedArtifactLocator(defaultLocator); } return defaultLocator; } protected List getBootDelegationPackages() { List bootPkgs = super.getBootDelegationPackages(); if (isCloverEnabled()) { bootPkgs.add(CLOVER_PKG); } return bootPkgs; } protected Manifest getManifest() { String permissionPackage = "org.osgi.service.permissionadmin"; Manifest mf = super.getManifest(); // make permission admin packages optional String impPackage = mf.getMainAttributes().getValue(Constants.IMPORT_PACKAGE); int startIndex = impPackage.indexOf(permissionPackage); String newImpPackage = impPackage; if (startIndex >= 0) { newImpPackage = impPackage.substring(0, startIndex) + permissionPackage + ";resolution:=optional" + impPackage.substring(startIndex + permissionPackage.length()); } mf.getMainAttributes().putValue(Constants.IMPORT_PACKAGE, newImpPackage); return mf; } /** * Returns the list of permissions for the running test. * * @return */ protected List getTestPermissions() { List perms = new ArrayList(); perms.add(new PackagePermission("*", PackagePermission.EXPORT)); perms.add(new PackagePermission("*", PackagePermission.IMPORT)); perms.add(new BundlePermission("*", BundlePermission.HOST)); perms.add(new BundlePermission("*", BundlePermission.PROVIDE)); perms.add(new BundlePermission("*", BundlePermission.REQUIRE)); perms.add(new ServicePermission("*", ServicePermission.REGISTER)); perms.add(new ServicePermission("*", ServicePermission.GET)); perms.add(new PropertyPermission("org.springframework.osgi.*", "read")); perms.add(new PropertyPermission("org.springframework.osgi.iandt.*", "write")); // required by Spring perms.add(new RuntimePermission("*", "accessDeclaredMembers")); perms.add(new ReflectPermission("*", "suppressAccessChecks")); // logging permission perms.add(new FilePermission("-", "read,write,delete")); return perms; } protected List getIAndTPermissions() { List perms = new ArrayList(); // export package perms.add(new PackagePermission("*", PackagePermission.EXPORT)); perms.add(new PackagePermission("*", PackagePermission.IMPORT)); perms.add(new BundlePermission("*", BundlePermission.FRAGMENT)); perms.add(new BundlePermission("*", BundlePermission.PROVIDE)); perms.add(new ServicePermission("*", ServicePermission.REGISTER)); perms.add(new ServicePermission("*", ServicePermission.GET)); perms.add(new PropertyPermission("*", "read,write")); // logging permission perms.add(new FilePermission("-", "read,write,delete")); // required by Spring perms.add(new RuntimePermission("*", "accessDeclaredMembers")); perms.add(new ReflectPermission("*", "suppressAccessChecks")); return perms; } }
integration-tests/tests/src/test/java/org/springframework/osgi/iandt/BaseIntegrationTest.java
/* * Copyright 2006-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.osgi.iandt; import java.io.File; import java.io.FilePermission; import java.lang.reflect.ReflectPermission; import java.security.Permission; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.PropertyPermission; import java.util.jar.Manifest; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.BundleEvent; import org.osgi.framework.BundlePermission; import org.osgi.framework.Constants; import org.osgi.framework.PackagePermission; import org.osgi.framework.ServicePermission; import org.osgi.framework.ServiceReference; import org.osgi.framework.SynchronousBundleListener; import org.osgi.service.permissionadmin.PermissionAdmin; import org.osgi.service.permissionadmin.PermissionInfo; import org.springframework.core.io.Resource; import org.springframework.osgi.test.AbstractConfigurableBundleCreatorTests; import org.springframework.osgi.test.provisioning.ArtifactLocator; import org.springframework.osgi.util.OsgiStringUtils; import org.springframework.util.ObjectUtils; import org.springframework.util.StringUtils; /** * Base test class used for improving performance of integration tests by * creating bundles only with the classes within a package as opposed to all * resources available in the target folder. * * <p/> Additionally, the class checks for the presence Clover if a certain * property is set and uses a special setup to use the instrumented jars instead * of the naked ones. * * @author Costin Leau * */ public abstract class BaseIntegrationTest extends AbstractConfigurableBundleCreatorTests { private class CloverClassifiedArtifactLocator implements ArtifactLocator { private final ArtifactLocator delegate; public CloverClassifiedArtifactLocator(ArtifactLocator delegate) { this.delegate = delegate; } public Resource locateArtifact(String group, String id, String version, String type) { return parse(id + "-" + version, delegate.locateArtifact(group, id, version, type)); } public Resource locateArtifact(String group, String id, String version) { return parse(id + "-" + version, delegate.locateArtifact(group, id, version)); } private Resource parse(String id, Resource resource) { if (id.indexOf(SPRING_DM_PREFIX) > -1) { try { String relativePath = ""; // check if it's a relative file if (StringUtils.cleanPath(resource.getURI().toString()).indexOf("/target/") > -1) { relativePath = "clover" + File.separator; } relativePath = relativePath + id + "-clover.jar"; Resource res = resource.createRelative(relativePath); BaseIntegrationTest.this.logger.info("Using clover instrumented jar " + res.getDescription()); return res; } catch (Exception ex) { throw (RuntimeException) new IllegalStateException( "Trying to find Clover instrumented class but none is available; disable clover or build the instrumented artifacts").initCause(ex); } } return resource; } } private class PermissionManager implements SynchronousBundleListener { private final PermissionAdmin pa; /** * Constructs a new <code>PermissionManager</code> instance. * * @param bc */ private PermissionManager(BundleContext bc) { ServiceReference ref = bc.getServiceReference(PermissionAdmin.class.getName()); if (ref != null) { logger.trace("Found permission admin " + ref); pa = (PermissionAdmin) bc.getService(ref); bc.addBundleListener(this); logger.trace("Default permissions are " + ObjectUtils.nullSafeToString(pa.getDefaultPermissions())); logger.warn("Security turned ON"); } else { logger.warn("Security turned OFF"); pa = null; } } public void bundleChanged(BundleEvent event) { if (event.getType() == BundleEvent.INSTALLED) { Bundle bnd = event.getBundle(); String location = bnd.getLocation(); if (location.indexOf("iandt") > -1 || location.indexOf("integration-tests") > -1) { logger.trace("Discovered I&T test..."); List perms = getIAndTPermissions(); // define permission info PermissionInfo[] pi = getPIFromPermissions(perms); logger.info("About to set permissions " + perms + " for I&T bundle " + OsgiStringUtils.nullSafeNameAndSymName(bnd) + "@" + location); pa.setPermissions(location, pi); } else if (location.indexOf("onTheFly") > -1) { logger.trace("Discovered on the fly test..."); List perms = getTestPermissions(); // define permission info PermissionInfo[] pi = getPIFromPermissions(perms); logger.info("About to set permissions " + perms + " for OnTheFly bundle " + OsgiStringUtils.nullSafeNameAndSymName(bnd) + "@" + location); pa.setPermissions(location, pi); } } } private PermissionInfo[] getPIFromPermissions(List perms) { PermissionInfo[] pi = new PermissionInfo[perms.size()]; int index = 0; for (Iterator iterator = perms.iterator(); iterator.hasNext();) { Permission perm = (Permission) iterator.next(); pi[index++] = new PermissionInfo(perm.getClass().getName(), perm.getName(), perm.getActions()); } return pi; } } private static final String CLOVER_PROPERTY = "org.springframework.osgi.integration.testing.clover"; private static final String CLOVER_PKG = "com_cenqua_clover"; private static final String SPRING_DM_PREFIX = "spring-osgi"; protected String[] getBundleContentPattern() { String pkg = getClass().getPackage().getName().replace('.', '/').concat("/"); String[] patterns = new String[] { BaseIntegrationTest.class.getName().replace('.', '/').concat("*.class"), pkg + "**/*" }; return patterns; } protected void preProcessBundleContext(BundleContext context) throws Exception { super.preProcessBundleContext(context); PermissionManager pm = new PermissionManager(context); if (isCloverEnabled()) { logger.warn("Test coverage instrumentation (Clover) enabled"); } } private boolean isCloverEnabled() { return Boolean.getBoolean(CLOVER_PROPERTY); } protected ArtifactLocator getLocator() { ArtifactLocator defaultLocator = super.getLocator(); // redirect to the clover artifacts if (isCloverEnabled()) { return new CloverClassifiedArtifactLocator(defaultLocator); } return defaultLocator; } protected List getBootDelegationPackages() { List bootPkgs = super.getBootDelegationPackages(); if (isCloverEnabled()) { bootPkgs.add(CLOVER_PKG); } return bootPkgs; } protected Manifest getManifest() { String permissionPackage = "org.osgi.service.permissionadmin"; Manifest mf = super.getManifest(); // make permission admin packages optional String impPackage = mf.getMainAttributes().getValue(Constants.IMPORT_PACKAGE); int startIndex = impPackage.indexOf(permissionPackage); String newImpPackage = impPackage; if (startIndex >= 0) { newImpPackage = impPackage.substring(0, startIndex) + permissionPackage + ";resolution:=optional" + impPackage.substring(startIndex + permissionPackage.length()); } mf.getMainAttributes().putValue(Constants.IMPORT_PACKAGE, newImpPackage); return mf; } /** * Returns the list of permissions for the running test. * * @return */ protected List getTestPermissions() { List perms = new ArrayList(); perms.add(new PackagePermission("*", PackagePermission.EXPORT)); perms.add(new PackagePermission("*", PackagePermission.IMPORT)); perms.add(new BundlePermission("*", BundlePermission.HOST)); perms.add(new BundlePermission("*", BundlePermission.PROVIDE)); perms.add(new BundlePermission("*", BundlePermission.REQUIRE)); perms.add(new ServicePermission("*", ServicePermission.REGISTER)); perms.add(new ServicePermission("*", ServicePermission.GET)); perms.add(new PropertyPermission("org.springframework.osgi.*", "read")); perms.add(new PropertyPermission("org.springframework.osgi.iandt.*", "write")); // required by Spring perms.add(new RuntimePermission("*", "accessDeclaredMembers")); perms.add(new ReflectPermission("*", "suppressAccessChecks")); // logging permission perms.add(new FilePermission("-", "WRITE")); return perms; } protected List getIAndTPermissions() { List perms = new ArrayList(); // export package perms.add(new PackagePermission("*", PackagePermission.EXPORT)); perms.add(new PackagePermission("*", PackagePermission.IMPORT)); perms.add(new BundlePermission("*", BundlePermission.FRAGMENT)); perms.add(new BundlePermission("*", BundlePermission.PROVIDE)); perms.add(new ServicePermission("*", ServicePermission.REGISTER)); perms.add(new ServicePermission("*", ServicePermission.GET)); perms.add(new PropertyPermission("*", "read,write")); // logging permission perms.add(new FilePermission("-", "WRITE")); // required by Spring perms.add(new RuntimePermission("*", "accessDeclaredMembers")); perms.add(new ReflectPermission("*", "suppressAccessChecks")); return perms; } }
+ add more file permission (to cope with logs rollover)
integration-tests/tests/src/test/java/org/springframework/osgi/iandt/BaseIntegrationTest.java
+ add more file permission (to cope with logs rollover)
<ide><path>ntegration-tests/tests/src/test/java/org/springframework/osgi/iandt/BaseIntegrationTest.java <ide> perms.add(new RuntimePermission("*", "accessDeclaredMembers")); <ide> perms.add(new ReflectPermission("*", "suppressAccessChecks")); <ide> // logging permission <del> perms.add(new FilePermission("-", "WRITE")); <add> perms.add(new FilePermission("-", "read,write,delete")); <ide> return perms; <ide> } <ide> <ide> perms.add(new ServicePermission("*", ServicePermission.GET)); <ide> perms.add(new PropertyPermission("*", "read,write")); <ide> // logging permission <del> perms.add(new FilePermission("-", "WRITE")); <add> perms.add(new FilePermission("-", "read,write,delete")); <ide> <ide> // required by Spring <ide> perms.add(new RuntimePermission("*", "accessDeclaredMembers"));
Java
apache-2.0
48d5d1d4d33cd1d95354062764858e1a1b4e5d38
0
robertdale/tinkerpop,pluradj/incubator-tinkerpop,krlohnes/tinkerpop,apache/incubator-tinkerpop,pluradj/incubator-tinkerpop,apache/tinkerpop,krlohnes/tinkerpop,apache/incubator-tinkerpop,pluradj/incubator-tinkerpop,apache/tinkerpop,robertdale/tinkerpop,krlohnes/tinkerpop,apache/tinkerpop,apache/incubator-tinkerpop,krlohnes/tinkerpop,apache/tinkerpop,krlohnes/tinkerpop,robertdale/tinkerpop,apache/tinkerpop,apache/tinkerpop,apache/tinkerpop,robertdale/tinkerpop,robertdale/tinkerpop
/* * 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.tinkerpop.gremlin.structure.util.star; import java.util.HashMap; import java.util.Map; import org.apache.tinkerpop.gremlin.process.computer.GraphFilter; import org.apache.tinkerpop.gremlin.structure.Direction; import org.apache.tinkerpop.gremlin.structure.io.gryo.kryoshim.shaded.ShadedSerializerAdapter; /** * A wrapper for {@link StarGraphSerializer} that makes it compatible with TinkerPop's * shaded Kryo. * * @author Marko A. Rodriguez (http://markorodriguez.com) * @author Stephen Mallette (http://stephen.genoprime.com) */ public final class StarGraphGryoSerializer extends ShadedSerializerAdapter<StarGraph> { private static final Map<Direction, StarGraphGryoSerializer> CACHE = new HashMap<>(); static { CACHE.put(Direction.BOTH, new StarGraphGryoSerializer(Direction.BOTH)); CACHE.put(Direction.IN, new StarGraphGryoSerializer(Direction.IN)); CACHE.put(Direction.OUT, new StarGraphGryoSerializer(Direction.OUT)); CACHE.put(null, new StarGraphGryoSerializer(null)); } private StarGraphGryoSerializer(final Direction edgeDirectionToSerialize, final GraphFilter graphFilter) { super(new StarGraphSerializer(edgeDirectionToSerialize, graphFilter)); } private StarGraphGryoSerializer(final Direction edgeDirectionToSerialize) { this(edgeDirectionToSerialize, new GraphFilter()); } /** * Gets a serializer from the cache. Use {@code null} for the direction when requiring a serializer that * doesn't serialize the edges of a vertex. */ public static StarGraphGryoSerializer with(final Direction direction) { return CACHE.get(direction); } public static StarGraphGryoSerializer withGraphFilter(final GraphFilter graphFilter) { final StarGraphGryoSerializer serializer = new StarGraphGryoSerializer(Direction.BOTH, graphFilter.clone()); return serializer; } }
gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/util/star/StarGraphGryoSerializer.java
/* * 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.tinkerpop.gremlin.structure.util.star; import java.util.EnumMap; import java.util.HashMap; import java.util.Map; import org.apache.tinkerpop.gremlin.process.computer.GraphFilter; import org.apache.tinkerpop.gremlin.structure.Direction; import org.apache.tinkerpop.gremlin.structure.io.gryo.kryoshim.shaded.ShadedSerializerAdapter; /** * A wrapper for {@link StarGraphSerializer} that makes it compatible with TinkerPop's * shaded Kryo. * * @author Marko A. Rodriguez (http://markorodriguez.com) * @author Stephen Mallette (http://stephen.genoprime.com) */ public final class StarGraphGryoSerializer extends ShadedSerializerAdapter<StarGraph> { private static final Map<Direction, StarGraphGryoSerializer> CACHE = new EnumMap<>(Direction.class); static { CACHE.put(Direction.BOTH, new StarGraphGryoSerializer(Direction.BOTH)); CACHE.put(Direction.IN, new StarGraphGryoSerializer(Direction.IN)); CACHE.put(Direction.OUT, new StarGraphGryoSerializer(Direction.OUT)); CACHE.put(null, new StarGraphGryoSerializer(null)); } private StarGraphGryoSerializer(final Direction edgeDirectionToSerialize, final GraphFilter graphFilter) { super(new StarGraphSerializer(edgeDirectionToSerialize, graphFilter)); } private StarGraphGryoSerializer(final Direction edgeDirectionToSerialize) { this(edgeDirectionToSerialize, new GraphFilter()); } /** * Gets a serializer from the cache. Use {@code null} for the direction when requiring a serializer that * doesn't serialize the edges of a vertex. */ public static StarGraphGryoSerializer with(final Direction direction) { return CACHE.get(direction); } public static StarGraphGryoSerializer withGraphFilter(final GraphFilter graphFilter) { final StarGraphGryoSerializer serializer = new StarGraphGryoSerializer(Direction.BOTH, graphFilter.clone()); return serializer; } }
reverts class StarGraphGryoSerializer
gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/util/star/StarGraphGryoSerializer.java
reverts class StarGraphGryoSerializer
<ide><path>remlin-core/src/main/java/org/apache/tinkerpop/gremlin/structure/util/star/StarGraphGryoSerializer.java <ide> */ <ide> package org.apache.tinkerpop.gremlin.structure.util.star; <ide> <del>import java.util.EnumMap; <ide> import java.util.HashMap; <ide> import java.util.Map; <ide> <ide> */ <ide> public final class StarGraphGryoSerializer extends ShadedSerializerAdapter<StarGraph> { <ide> <del> private static final Map<Direction, StarGraphGryoSerializer> CACHE = new EnumMap<>(Direction.class); <add> private static final Map<Direction, StarGraphGryoSerializer> CACHE = new HashMap<>(); <ide> <ide> static { <ide> CACHE.put(Direction.BOTH, new StarGraphGryoSerializer(Direction.BOTH));
Java
apache-2.0
8ef4f77fb12e7d0478831a692cf69d318d01824f
0
dnltsk/intellij-mapfile-plugin
package org.dnltsk.mapfileplugin.highlighter; import com.intellij.openapi.editor.colors.TextAttributesKey; import com.intellij.openapi.fileTypes.SyntaxHighlighter; import com.intellij.openapi.options.colors.AttributesDescriptor; import com.intellij.openapi.options.colors.ColorDescriptor; import com.intellij.openapi.options.colors.ColorSettingsPage; import org.dnltsk.mapfileplugin.MapfileIcons; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.util.Map; public class MapfileColorSettingsPage implements ColorSettingsPage { private static final AttributesDescriptor[] DESCRIPTORS = new AttributesDescriptor[]{ new AttributesDescriptor("Keywords", MapfileSyntaxHighlighter.KEYWORD_HIGHLIGHTER), new AttributesDescriptor("Enum Values", MapfileSyntaxHighlighter.ENUM_HIGHLIGHTER), new AttributesDescriptor("Numbers", MapfileSyntaxHighlighter.NUMBERS_HIGHLIGHTER), new AttributesDescriptor("Strings", MapfileSyntaxHighlighter.STRING_HIGHLIGHTER), new AttributesDescriptor("Comments", MapfileSyntaxHighlighter.COMMENT_HIGHLIGHTER), new AttributesDescriptor("Bad Characters", MapfileSyntaxHighlighter.BAD_CHARACTER_HIGHLIGHTER), }; @Nullable @Override public Icon getIcon() { return MapfileIcons.FILE; } @NotNull @Override public SyntaxHighlighter getHighlighter() { return new MapfileSyntaxHighlighter(); } @NotNull @Override public String getDemoText() { return "#\n" + "# preview adopted from\n" + "# http://mapserver.org/introduction.html\n" + "#\n" + "MAP\n" + " NAME \"sample\"\n" + " STATUS ON\n" + " SIZE 600 400\n" + " SYMBOLSET \"../etc/symbols.txt\"\n" + " EXTENT -180 -90 180 90\n" + " UNITS DD\n" + " SHAPEPATH \"../data\"\n" + " IMAGECOLOR 255 255 255\n" + " FONTSET \"../etc/fonts.txt\"\n" + "\n" + " #\n" + " # Start of web interface definition\n" + " #\n" + " WEB\n" + " IMAGEPATH \"/ms4w/tmp/ms_tmp/\"\n" + " IMAGEURL \"/ms_tmp/\"\n" + " END # WEB\n" + "\n" + " #\n" + " # Start of layer definitions\n" + " #\n" + " LAYER\n" + " NAME \"global-raster\"\n" + " TYPE RASTER\n" + " STATUS DEFAULT\n" + " DATA \"bluemarble.gif\"\n" + " END # LAYER\n" + "END # MAP"; } @Nullable @Override public Map<String, TextAttributesKey> getAdditionalHighlightingTagToDescriptorMap() { return null; } @NotNull @Override public AttributesDescriptor[] getAttributeDescriptors() { return DESCRIPTORS; } @NotNull @Override public ColorDescriptor[] getColorDescriptors() { return ColorDescriptor.EMPTY_ARRAY; } @NotNull @Override public String getDisplayName() { return "Mapfile"; } }
src/org/dnltsk/mapfileplugin/highlighter/MapfileColorSettingsPage.java
package org.dnltsk.mapfileplugin.highlighter; import com.intellij.openapi.editor.colors.TextAttributesKey; import com.intellij.openapi.fileTypes.SyntaxHighlighter; import com.intellij.openapi.options.colors.AttributesDescriptor; import com.intellij.openapi.options.colors.ColorDescriptor; import com.intellij.openapi.options.colors.ColorSettingsPage; import org.dnltsk.mapfileplugin.MapfileIcons; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.util.Map; public class MapfileColorSettingsPage implements ColorSettingsPage { private static final AttributesDescriptor[] DESCRIPTORS = new AttributesDescriptor[]{ new AttributesDescriptor("Keywords", MapfileSyntaxHighlighter.KEYWORD_HIGHLIGHTER), new AttributesDescriptor("Enum Values", MapfileSyntaxHighlighter.ENUM_HIGHLIGHTER), new AttributesDescriptor("Nunmbers", MapfileSyntaxHighlighter.NUMBERS_HIGHLIGHTER), new AttributesDescriptor("Strings", MapfileSyntaxHighlighter.STRING_HIGHLIGHTER), new AttributesDescriptor("Comments", MapfileSyntaxHighlighter.COMMENT_HIGHLIGHTER), new AttributesDescriptor("Bad Characters", MapfileSyntaxHighlighter.BAD_CHARACTER_HIGHLIGHTER), }; @Nullable @Override public Icon getIcon() { return MapfileIcons.FILE; } @NotNull @Override public SyntaxHighlighter getHighlighter() { return new MapfileSyntaxHighlighter(); } @NotNull @Override public String getDemoText() { return "MAP\n" + " NAME \"sample\"\n" + " STATUS ON\n" + " SIZE 600 400\n" + " SYMBOLSET \"../etc/symbols.txt\"\n" + " EXTENT -180 -90 180 90\n" + " UNITS DD\n" + " SHAPEPATH \"../data\"\n" + " IMAGECOLOR 255 255 255\n" + " FONTSET \"../etc/fonts.txt\"\n" + "\n" + " #\n" + " # Start of web interface definition\n" + " #\n" + " WEB\n" + " IMAGEPATH \"/ms4w/tmp/ms_tmp/\"\n" + " IMAGEURL \"/ms_tmp/\"\n" + " END # WEB\n" + "\n" + " #\n" + " # Start of layer definitions\n" + " #\n" + " LAYER\n" + " NAME \"global-raster\"\n" + " TYPE RASTER\n" + " STATUS DEFAULT\n" + " DATA \"bluemarble.gif\"\n" + " END # LAYER\n" + "END # MAP"; } @Nullable @Override public Map<String, TextAttributesKey> getAdditionalHighlightingTagToDescriptorMap() { return null; } @NotNull @Override public AttributesDescriptor[] getAttributeDescriptors() { return DESCRIPTORS; } @NotNull @Override public ColorDescriptor[] getColorDescriptors() { return ColorDescriptor.EMPTY_ARRAY; } @NotNull @Override public String getDisplayName() { return "Mapfile"; } }
comment + typo
src/org/dnltsk/mapfileplugin/highlighter/MapfileColorSettingsPage.java
comment + typo
<ide><path>rc/org/dnltsk/mapfileplugin/highlighter/MapfileColorSettingsPage.java <ide> private static final AttributesDescriptor[] DESCRIPTORS = new AttributesDescriptor[]{ <ide> new AttributesDescriptor("Keywords", MapfileSyntaxHighlighter.KEYWORD_HIGHLIGHTER), <ide> new AttributesDescriptor("Enum Values", MapfileSyntaxHighlighter.ENUM_HIGHLIGHTER), <del> new AttributesDescriptor("Nunmbers", MapfileSyntaxHighlighter.NUMBERS_HIGHLIGHTER), <add> new AttributesDescriptor("Numbers", MapfileSyntaxHighlighter.NUMBERS_HIGHLIGHTER), <ide> new AttributesDescriptor("Strings", MapfileSyntaxHighlighter.STRING_HIGHLIGHTER), <ide> new AttributesDescriptor("Comments", MapfileSyntaxHighlighter.COMMENT_HIGHLIGHTER), <ide> new AttributesDescriptor("Bad Characters", MapfileSyntaxHighlighter.BAD_CHARACTER_HIGHLIGHTER), <ide> @NotNull <ide> @Override <ide> public String getDemoText() { <del> return "MAP\n" + <add> return "#\n" + <add> "# preview adopted from\n" + <add> "# http://mapserver.org/introduction.html\n" + <add> "#\n" + <add> "MAP\n" + <ide> " NAME \"sample\"\n" + <ide> " STATUS ON\n" + <ide> " SIZE 600 400\n" +
Java
apache-2.0
0fe9f1450b3ff81c8d0f1e3ff1a0b7f22b44c56a
0
EShkuratova/java_pft,EShkuratova/java_pft
package ru.stqa.pft.addressbook; import org.openqa.selenium.By; import org.openqa.selenium.NoAlertPresentException; import org.openqa.selenium.firefox.FirefoxDriver; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.util.concurrent.TimeUnit; public class CreateGroupTests { FirefoxDriver wd; @BeforeMethod public void setUp(){ wd = new FirefoxDriver(); wd.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS); login(); } @Test public void testGroupCreation() { wd.findElement(By.linkText("groups")).click(); wd.findElement(By.xpath("//div[@id='content']/form/input[4]")).click(); wd.findElement(By.name("group_name")).click(); wd.findElement(By.name("group_name")).clear(); wd.findElement(By.name("group_name")).sendKeys("test1"); wd.findElement(By.name("group_header")).click(); wd.findElement(By.name("group_header")).clear(); wd.findElement(By.name("group_header")).sendKeys("test2"); wd.findElement(By.name("group_footer")).click(); wd.findElement(By.name("group_footer")).clear(); wd.findElement(By.name("group_footer")).sendKeys("test3"); wd.findElement(By.name("submit")).click(); wd.findElement(By.linkText("group page")).click(); wd.quit(); } private void login(){ wd.get("http://localhost/addressbook/"); wd.findElement(By.name("pass")).click(); wd.findElement(By.name("pass")).clear(); wd.findElement(By.name("pass")).sendKeys("secret"); wd.findElement(By.name("user")).click(); wd.findElement(By.name("user")).clear(); wd.findElement(By.name("user")).sendKeys("admin"); wd.findElement(By.xpath("//form[@id='LoginForm']/input[3]")).click(); } @AfterMethod public void tearDown(){ wd.quit(); } public static boolean isAlertPresent(FirefoxDriver wd) { try { wd.switchTo().alert(); return true; } catch (NoAlertPresentException e) { return false; } } }
addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/CreateGroupTests.java
package ru.stqa.pft.addressbook; import org.openqa.selenium.By; import org.openqa.selenium.NoAlertPresentException; import org.openqa.selenium.firefox.FirefoxDriver; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.util.concurrent.TimeUnit; public class CreateGroupTests { FirefoxDriver wd; @BeforeMethod public void setUp(){ wd = new FirefoxDriver(); wd.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS); } @Test public void createGroup() { wd.get("http://localhost/addressbook/"); wd.findElement(By.name("pass")).click(); wd.findElement(By.name("pass")).clear(); wd.findElement(By.name("pass")).sendKeys("secret"); wd.findElement(By.name("user")).click(); wd.findElement(By.name("user")).clear(); wd.findElement(By.name("user")).sendKeys("admin"); wd.findElement(By.xpath("//form[@id='LoginForm']/input[3]")).click(); wd.findElement(By.linkText("groups")).click(); wd.findElement(By.xpath("//div[@id='content']/form/input[4]")).click(); wd.findElement(By.name("group_name")).click(); wd.findElement(By.name("group_name")).clear(); wd.findElement(By.name("group_name")).sendKeys("test1"); wd.findElement(By.name("group_header")).click(); wd.findElement(By.name("group_header")).clear(); wd.findElement(By.name("group_header")).sendKeys("test2"); wd.findElement(By.name("group_footer")).click(); wd.findElement(By.name("group_footer")).clear(); wd.findElement(By.name("group_footer")).sendKeys("test3"); wd.findElement(By.name("submit")).click(); wd.findElement(By.linkText("group page")).click(); wd.quit(); } public static boolean isAlertPresent(FirefoxDriver wd) { try { wd.switchTo().alert(); return true; } catch (NoAlertPresentException e) { return false; } } }
Авторизация в приложении выненсена в отдельный метод и вызывается под аннотацией @BeforMethod
addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/CreateGroupTests.java
Авторизация в приложении выненсена в отдельный метод и вызывается под аннотацией @BeforMethod
<ide><path>ddressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/CreateGroupTests.java <ide> import org.openqa.selenium.By; <ide> import org.openqa.selenium.NoAlertPresentException; <ide> import org.openqa.selenium.firefox.FirefoxDriver; <add>import org.testng.annotations.AfterMethod; <ide> import org.testng.annotations.BeforeMethod; <ide> import org.testng.annotations.Test; <ide> <ide> public void setUp(){ <ide> wd = new FirefoxDriver(); <ide> wd.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS); <add> login(); <ide> <ide> } <ide> <ide> @Test <del> public void createGroup() { <add> public void testGroupCreation() { <ide> <ide> <del> wd.get("http://localhost/addressbook/"); <del> wd.findElement(By.name("pass")).click(); <del> wd.findElement(By.name("pass")).clear(); <del> wd.findElement(By.name("pass")).sendKeys("secret"); <del> wd.findElement(By.name("user")).click(); <del> wd.findElement(By.name("user")).clear(); <del> wd.findElement(By.name("user")).sendKeys("admin"); <del> wd.findElement(By.xpath("//form[@id='LoginForm']/input[3]")).click(); <add> <ide> wd.findElement(By.linkText("groups")).click(); <ide> wd.findElement(By.xpath("//div[@id='content']/form/input[4]")).click(); <ide> wd.findElement(By.name("group_name")).click(); <ide> wd.findElement(By.linkText("group page")).click(); <ide> wd.quit(); <ide> } <del> <add> <add> private void login(){ <add> <add> wd.get("http://localhost/addressbook/"); <add> wd.findElement(By.name("pass")).click(); <add> wd.findElement(By.name("pass")).clear(); <add> wd.findElement(By.name("pass")).sendKeys("secret"); <add> wd.findElement(By.name("user")).click(); <add> wd.findElement(By.name("user")).clear(); <add> wd.findElement(By.name("user")).sendKeys("admin"); <add> wd.findElement(By.xpath("//form[@id='LoginForm']/input[3]")).click(); <add> <add> } <add> <add> @AfterMethod <add> <add> public void tearDown(){ <add> wd.quit(); <add> } <ide> public static boolean isAlertPresent(FirefoxDriver wd) { <ide> try { <ide> wd.switchTo().alert();
Java
apache-2.0
efd1f1b29ff51d28a1a1c702cef6a7ce2554ee2a
0
strapdata/elassandra,vroyer/elassandra,strapdata/elassandra,vroyer/elassandra,vroyer/elassandra,strapdata/elassandra,strapdata/elassandra,strapdata/elassandra
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch 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.elasticsearch.search.aggregations.pipeline.moving.avg; import org.elasticsearch.action.bulk.BulkRequestBuilder; import org.elasticsearch.action.index.IndexRequestBuilder; import org.elasticsearch.action.search.SearchPhaseExecutionException; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.support.WriteRequest; import org.elasticsearch.common.collect.EvictingQueue; import org.elasticsearch.search.aggregations.bucket.histogram.Histogram; import org.elasticsearch.search.aggregations.bucket.histogram.Histogram.Bucket; import org.elasticsearch.search.aggregations.metrics.avg.Avg; import org.elasticsearch.search.aggregations.pipeline.BucketHelpers; import org.elasticsearch.search.aggregations.pipeline.PipelineAggregationHelperTests; import org.elasticsearch.search.aggregations.pipeline.SimpleValue; import org.elasticsearch.search.aggregations.pipeline.derivative.Derivative; import org.elasticsearch.search.aggregations.pipeline.movavg.models.EwmaModel; import org.elasticsearch.search.aggregations.pipeline.movavg.models.HoltLinearModel; import org.elasticsearch.search.aggregations.pipeline.movavg.models.HoltWintersModel; import org.elasticsearch.search.aggregations.pipeline.movavg.models.LinearModel; import org.elasticsearch.search.aggregations.pipeline.movavg.models.MovAvgModelBuilder; import org.elasticsearch.search.aggregations.pipeline.movavg.models.SimpleModel; import org.elasticsearch.search.aggregations.support.ValuesSource; import org.elasticsearch.search.aggregations.support.ValuesSourceAggregationBuilder; import org.elasticsearch.test.ESIntegTestCase; import org.hamcrest.Matchers; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; import static org.elasticsearch.search.aggregations.AggregationBuilders.avg; import static org.elasticsearch.search.aggregations.AggregationBuilders.histogram; import static org.elasticsearch.search.aggregations.AggregationBuilders.max; import static org.elasticsearch.search.aggregations.AggregationBuilders.min; import static org.elasticsearch.search.aggregations.AggregationBuilders.range; import static org.elasticsearch.search.aggregations.pipeline.PipelineAggregatorBuilders.derivative; import static org.elasticsearch.search.aggregations.pipeline.PipelineAggregatorBuilders.movingAvg; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSearchResponse; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.hamcrest.core.IsNull.notNullValue; import static org.hamcrest.core.IsNull.nullValue; @ESIntegTestCase.SuiteScopeTestCase public class MovAvgIT extends ESIntegTestCase { private static final String INTERVAL_FIELD = "l_value"; private static final String VALUE_FIELD = "v_value"; private static final String VALUE_FIELD2 = "v_value2"; static int interval; static int numBuckets; static int windowSize; static double alpha; static double beta; static double gamma; static int period; static HoltWintersModel.SeasonalityType seasonalityType; static BucketHelpers.GapPolicy gapPolicy; static ValuesSourceAggregationBuilder<? extends ValuesSource, ? extends ValuesSourceAggregationBuilder<?, ?>> metric; static List<PipelineAggregationHelperTests.MockBucket> mockHisto; static Map<String, ArrayList<Double>> testValues; enum MovAvgType { SIMPLE ("simple"), LINEAR("linear"), EWMA("ewma"), HOLT("holt"), HOLT_WINTERS("holt_winters"), HOLT_BIG_MINIMIZE("holt"); private final String name; MovAvgType(String s) { name = s; } @Override public String toString(){ return name; } } enum MetricTarget { VALUE ("value"), COUNT("count"), METRIC("metric"); private final String name; MetricTarget(String s) { name = s; } @Override public String toString(){ return name; } } @Override public void setupSuiteScopeCluster() throws Exception { createIndex("idx"); createIndex("idx_unmapped"); List<IndexRequestBuilder> builders = new ArrayList<>(); interval = 5; numBuckets = randomIntBetween(6, 80); period = randomIntBetween(1, 5); windowSize = randomIntBetween(period * 2, 10); // start must be 2*period to play nice with HW alpha = randomDouble(); beta = randomDouble(); gamma = randomDouble(); seasonalityType = randomBoolean() ? HoltWintersModel.SeasonalityType.ADDITIVE : HoltWintersModel.SeasonalityType.MULTIPLICATIVE; gapPolicy = randomBoolean() ? BucketHelpers.GapPolicy.SKIP : BucketHelpers.GapPolicy.INSERT_ZEROS; metric = randomMetric("the_metric", VALUE_FIELD); mockHisto = PipelineAggregationHelperTests.generateHistogram(interval, numBuckets, randomDouble(), randomDouble()); testValues = new HashMap<>(8); for (MovAvgType type : MovAvgType.values()) { for (MetricTarget target : MetricTarget.values()) { if (type.equals(MovAvgType.HOLT_BIG_MINIMIZE)) { setupExpected(type, target, numBuckets); } else { setupExpected(type, target, windowSize); } } } for (PipelineAggregationHelperTests.MockBucket mockBucket : mockHisto) { for (double value : mockBucket.docValues) { builders.add(client().prepareIndex("idx", "type").setSource(jsonBuilder().startObject() .field(INTERVAL_FIELD, mockBucket.key) .field(VALUE_FIELD, value).endObject())); } } for (int i = -10; i < 10; i++) { builders.add(client().prepareIndex("neg_idx", "type").setSource( jsonBuilder().startObject().field(INTERVAL_FIELD, i).field(VALUE_FIELD, 10).endObject())); } for (int i = 0; i < 12; i++) { builders.add(client().prepareIndex("double_predict", "type").setSource( jsonBuilder().startObject().field(INTERVAL_FIELD, i).field(VALUE_FIELD, 10).endObject())); } indexRandom(true, builders); ensureSearchable(); } /** * Calculates the moving averages for a specific (model, target) tuple based on the previously generated mock histogram. * Computed values are stored in the testValues map. * * @param type The moving average model to use * @param target The document field "target", e.g. _count or a field value */ private void setupExpected(MovAvgType type, MetricTarget target, int windowSize) { ArrayList<Double> values = new ArrayList<>(numBuckets); EvictingQueue<Double> window = new EvictingQueue<>(windowSize); for (PipelineAggregationHelperTests.MockBucket mockBucket : mockHisto) { double metricValue; double[] docValues = mockBucket.docValues; // Gaps only apply to metric values, not doc _counts if (mockBucket.count == 0 && target.equals(MetricTarget.VALUE)) { // If there was a gap in doc counts and we are ignoring, just skip this bucket if (gapPolicy.equals(BucketHelpers.GapPolicy.SKIP)) { values.add(null); continue; } else if (gapPolicy.equals(BucketHelpers.GapPolicy.INSERT_ZEROS)) { // otherwise insert a zero instead of the true value metricValue = 0.0; } else { metricValue = PipelineAggregationHelperTests.calculateMetric(docValues, metric); } } else { // If this isn't a gap, or is a _count, just insert the value metricValue = target.equals(MetricTarget.VALUE) ? PipelineAggregationHelperTests.calculateMetric(docValues, metric) : mockBucket.count; } if (window.size() > 0) { switch (type) { case SIMPLE: values.add(simple(window)); break; case LINEAR: values.add(linear(window)); break; case EWMA: values.add(ewma(window)); break; case HOLT: values.add(holt(window)); break; case HOLT_BIG_MINIMIZE: values.add(holt(window)); break; case HOLT_WINTERS: // HW needs at least 2 periods of data to start if (window.size() >= period * 2) { values.add(holtWinters(window)); } else { values.add(null); } break; } } else { values.add(null); } window.offer(metricValue); } testValues.put(type.name() + "_" + target.name(), values); } /** * Simple, unweighted moving average * * @param window Window of values to compute movavg for */ private double simple(Collection<Double> window) { double movAvg = 0; for (double value : window) { movAvg += value; } movAvg /= window.size(); return movAvg; } /** * Linearly weighted moving avg * * @param window Window of values to compute movavg for */ private double linear(Collection<Double> window) { double avg = 0; long totalWeight = 1; long current = 1; for (double value : window) { avg += value * current; totalWeight += current; current += 1; } return avg / totalWeight; } /** * Exponentially weighted (EWMA, Single exponential) moving avg * * @param window Window of values to compute movavg for */ private double ewma(Collection<Double> window) { double avg = 0; boolean first = true; for (double value : window) { if (first) { avg = value; first = false; } else { avg = (value * alpha) + (avg * (1 - alpha)); } } return avg; } /** * Holt-Linear (Double exponential) moving avg * @param window Window of values to compute movavg for */ private double holt(Collection<Double> window) { double s = 0; double last_s = 0; // Trend value double b = 0; double last_b = 0; int counter = 0; double last; for (double value : window) { last = value; if (counter == 0) { s = value; b = value - last; } else { s = alpha * value + (1.0d - alpha) * (last_s + last_b); b = beta * (s - last_s) + (1 - beta) * last_b; } counter += 1; last_s = s; last_b = b; } return s + (0 * b) ; } /** * Holt winters (triple exponential) moving avg * @param window Window of values to compute movavg for */ private double holtWinters(Collection<Double> window) { // Smoothed value double s = 0; double last_s = 0; // Trend value double b = 0; double last_b = 0; // Seasonal value double[] seasonal = new double[window.size()]; double padding = seasonalityType.equals(HoltWintersModel.SeasonalityType.MULTIPLICATIVE) ? 0.0000000001 : 0; int counter = 0; double[] vs = new double[window.size()]; for (double v : window) { vs[counter] = v + padding; counter += 1; } // Initial level value is average of first season // Calculate the slopes between first and second season for each period for (int i = 0; i < period; i++) { s += vs[i]; b += (vs[i + period] - vs[i]) / period; } s /= period; b /= period; last_s = s; // Calculate first seasonal if (Double.compare(s, 0.0) == 0 || Double.compare(s, -0.0) == 0) { Arrays.fill(seasonal, 0.0); } else { for (int i = 0; i < period; i++) { seasonal[i] = vs[i] / s; } } for (int i = period; i < vs.length; i++) { if (seasonalityType.equals(HoltWintersModel.SeasonalityType.MULTIPLICATIVE)) { s = alpha * (vs[i] / seasonal[i - period]) + (1.0d - alpha) * (last_s + last_b); } else { s = alpha * (vs[i] - seasonal[i - period]) + (1.0d - alpha) * (last_s + last_b); } b = beta * (s - last_s) + (1 - beta) * last_b; if (seasonalityType.equals(HoltWintersModel.SeasonalityType.MULTIPLICATIVE)) { seasonal[i] = gamma * (vs[i] / (last_s + last_b )) + (1 - gamma) * seasonal[i - period]; } else { seasonal[i] = gamma * (vs[i] - (last_s - last_b )) + (1 - gamma) * seasonal[i - period]; } last_s = s; last_b = b; } int idx = window.size() - period + (0 % period); // TODO perhaps pad out seasonal to a power of 2 and use a mask instead of modulo? if (seasonalityType.equals(HoltWintersModel.SeasonalityType.MULTIPLICATIVE)) { return (s + (1 * b)) * seasonal[idx]; } else { return s + (1 * b) + seasonal[idx]; } } /** * test simple moving average on single value field */ public void testSimpleSingleValuedField() { SearchResponse response = client() .prepareSearch("idx").setTypes("type") .addAggregation( histogram("histo").field(INTERVAL_FIELD).interval(interval) .extendedBounds(0L, (long) (interval * (numBuckets - 1))) .subAggregation(metric) .subAggregation(movingAvg("movavg_counts","_count") .window(windowSize) .modelBuilder(new SimpleModel.SimpleModelBuilder()) .gapPolicy(gapPolicy)) .subAggregation(movingAvg("movavg_values","the_metric") .window(windowSize) .modelBuilder(new SimpleModel.SimpleModelBuilder()) .gapPolicy(gapPolicy)) ).execute().actionGet(); assertSearchResponse(response); Histogram histo = response.getAggregations().get("histo"); assertThat(histo, notNullValue()); assertThat(histo.getName(), equalTo("histo")); List<? extends Bucket> buckets = histo.getBuckets(); assertThat("Size of buckets array is not correct.", buckets.size(), equalTo(mockHisto.size())); List<Double> expectedCounts = testValues.get(MovAvgType.SIMPLE.name() + "_" + MetricTarget.COUNT.name()); List<Double> expectedValues = testValues.get(MovAvgType.SIMPLE.name() + "_" + MetricTarget.VALUE.name()); Iterator<? extends Histogram.Bucket> actualIter = buckets.iterator(); Iterator<PipelineAggregationHelperTests.MockBucket> expectedBucketIter = mockHisto.iterator(); Iterator<Double> expectedCountsIter = expectedCounts.iterator(); Iterator<Double> expectedValuesIter = expectedValues.iterator(); while (actualIter.hasNext()) { assertValidIterators(expectedBucketIter, expectedCountsIter, expectedValuesIter); Histogram.Bucket actual = actualIter.next(); PipelineAggregationHelperTests.MockBucket expected = expectedBucketIter.next(); Double expectedCount = expectedCountsIter.next(); Double expectedValue = expectedValuesIter.next(); assertThat("keys do not match", ((Number) actual.getKey()).longValue(), equalTo(expected.key)); assertThat("doc counts do not match", actual.getDocCount(), equalTo((long)expected.count)); assertBucketContents(actual, expectedCount, expectedValue); } } public void testLinearSingleValuedField() { SearchResponse response = client() .prepareSearch("idx").setTypes("type") .addAggregation( histogram("histo").field(INTERVAL_FIELD).interval(interval) .extendedBounds(0L, (long) (interval * (numBuckets - 1))) .subAggregation(metric) .subAggregation(movingAvg("movavg_counts", "_count") .window(windowSize) .modelBuilder(new LinearModel.LinearModelBuilder()) .gapPolicy(gapPolicy)) .subAggregation(movingAvg("movavg_values", "the_metric") .window(windowSize) .modelBuilder(new LinearModel.LinearModelBuilder()) .gapPolicy(gapPolicy)) ).execute().actionGet(); assertSearchResponse(response); Histogram histo = response.getAggregations().get("histo"); assertThat(histo, notNullValue()); assertThat(histo.getName(), equalTo("histo")); List<? extends Bucket> buckets = histo.getBuckets(); assertThat("Size of buckets array is not correct.", buckets.size(), equalTo(mockHisto.size())); List<Double> expectedCounts = testValues.get(MovAvgType.LINEAR.name() + "_" + MetricTarget.COUNT.name()); List<Double> expectedValues = testValues.get(MovAvgType.LINEAR.name() + "_" + MetricTarget.VALUE.name()); Iterator<? extends Histogram.Bucket> actualIter = buckets.iterator(); Iterator<PipelineAggregationHelperTests.MockBucket> expectedBucketIter = mockHisto.iterator(); Iterator<Double> expectedCountsIter = expectedCounts.iterator(); Iterator<Double> expectedValuesIter = expectedValues.iterator(); while (actualIter.hasNext()) { assertValidIterators(expectedBucketIter, expectedCountsIter, expectedValuesIter); Histogram.Bucket actual = actualIter.next(); PipelineAggregationHelperTests.MockBucket expected = expectedBucketIter.next(); Double expectedCount = expectedCountsIter.next(); Double expectedValue = expectedValuesIter.next(); assertThat("keys do not match", ((Number) actual.getKey()).longValue(), equalTo(expected.key)); assertThat("doc counts do not match", actual.getDocCount(), equalTo((long)expected.count)); assertBucketContents(actual, expectedCount, expectedValue); } } public void testEwmaSingleValuedField() { SearchResponse response = client() .prepareSearch("idx").setTypes("type") .addAggregation( histogram("histo").field(INTERVAL_FIELD).interval(interval) .extendedBounds(0L, (long) (interval * (numBuckets - 1))) .subAggregation(metric) .subAggregation(movingAvg("movavg_counts", "_count") .window(windowSize) .modelBuilder(new EwmaModel.EWMAModelBuilder().alpha(alpha)) .gapPolicy(gapPolicy)) .subAggregation(movingAvg("movavg_values", "the_metric") .window(windowSize) .modelBuilder(new EwmaModel.EWMAModelBuilder().alpha(alpha)) .gapPolicy(gapPolicy)) ).execute().actionGet(); assertSearchResponse(response); Histogram histo = response.getAggregations().get("histo"); assertThat(histo, notNullValue()); assertThat(histo.getName(), equalTo("histo")); List<? extends Bucket> buckets = histo.getBuckets(); assertThat("Size of buckets array is not correct.", buckets.size(), equalTo(mockHisto.size())); List<Double> expectedCounts = testValues.get(MovAvgType.EWMA.name() + "_" + MetricTarget.COUNT.name()); List<Double> expectedValues = testValues.get(MovAvgType.EWMA.name() + "_" + MetricTarget.VALUE.name()); Iterator<? extends Histogram.Bucket> actualIter = buckets.iterator(); Iterator<PipelineAggregationHelperTests.MockBucket> expectedBucketIter = mockHisto.iterator(); Iterator<Double> expectedCountsIter = expectedCounts.iterator(); Iterator<Double> expectedValuesIter = expectedValues.iterator(); while (actualIter.hasNext()) { assertValidIterators(expectedBucketIter, expectedCountsIter, expectedValuesIter); Histogram.Bucket actual = actualIter.next(); PipelineAggregationHelperTests.MockBucket expected = expectedBucketIter.next(); Double expectedCount = expectedCountsIter.next(); Double expectedValue = expectedValuesIter.next(); assertThat("keys do not match", ((Number) actual.getKey()).longValue(), equalTo(expected.key)); assertThat("doc counts do not match", actual.getDocCount(), equalTo((long)expected.count)); assertBucketContents(actual, expectedCount, expectedValue); } } public void testHoltSingleValuedField() { SearchResponse response = client() .prepareSearch("idx").setTypes("type") .addAggregation( histogram("histo").field(INTERVAL_FIELD).interval(interval) .extendedBounds(0L, (long) (interval * (numBuckets - 1))) .subAggregation(metric) .subAggregation(movingAvg("movavg_counts", "_count") .window(windowSize) .modelBuilder(new HoltLinearModel.HoltLinearModelBuilder().alpha(alpha).beta(beta)) .gapPolicy(gapPolicy)) .subAggregation(movingAvg("movavg_values", "the_metric") .window(windowSize) .modelBuilder(new HoltLinearModel.HoltLinearModelBuilder().alpha(alpha).beta(beta)) .gapPolicy(gapPolicy)) ).execute().actionGet(); assertSearchResponse(response); Histogram histo = response.getAggregations().get("histo"); assertThat(histo, notNullValue()); assertThat(histo.getName(), equalTo("histo")); List<? extends Bucket> buckets = histo.getBuckets(); assertThat("Size of buckets array is not correct.", buckets.size(), equalTo(mockHisto.size())); List<Double> expectedCounts = testValues.get(MovAvgType.HOLT.name() + "_" + MetricTarget.COUNT.name()); List<Double> expectedValues = testValues.get(MovAvgType.HOLT.name() + "_" + MetricTarget.VALUE.name()); Iterator<? extends Histogram.Bucket> actualIter = buckets.iterator(); Iterator<PipelineAggregationHelperTests.MockBucket> expectedBucketIter = mockHisto.iterator(); Iterator<Double> expectedCountsIter = expectedCounts.iterator(); Iterator<Double> expectedValuesIter = expectedValues.iterator(); while (actualIter.hasNext()) { assertValidIterators(expectedBucketIter, expectedCountsIter, expectedValuesIter); Histogram.Bucket actual = actualIter.next(); PipelineAggregationHelperTests.MockBucket expected = expectedBucketIter.next(); Double expectedCount = expectedCountsIter.next(); Double expectedValue = expectedValuesIter.next(); assertThat("keys do not match", ((Number) actual.getKey()).longValue(), equalTo(expected.key)); assertThat("doc counts do not match", actual.getDocCount(), equalTo((long)expected.count)); assertBucketContents(actual, expectedCount, expectedValue); } } @AwaitsFix(bugUrl = "https://github.com/elastic/elasticsearch/issues/35632") public void testHoltWintersValuedField() { SearchResponse response = client() .prepareSearch("idx").setTypes("type") .addAggregation( histogram("histo").field(INTERVAL_FIELD).interval(interval) .extendedBounds(0L, (long) (interval * (numBuckets - 1))) .subAggregation(metric) .subAggregation(movingAvg("movavg_counts", "_count") .window(windowSize) .modelBuilder(new HoltWintersModel.HoltWintersModelBuilder() .alpha(alpha).beta(beta).gamma(gamma).period(period).seasonalityType(seasonalityType)) .gapPolicy(gapPolicy) .minimize(false)) .subAggregation(movingAvg("movavg_values", "the_metric") .window(windowSize) .modelBuilder(new HoltWintersModel.HoltWintersModelBuilder() .alpha(alpha).beta(beta).gamma(gamma).period(period).seasonalityType(seasonalityType)) .gapPolicy(gapPolicy) .minimize(false)) ).execute().actionGet(); assertSearchResponse(response); Histogram histo = response.getAggregations().get("histo"); assertThat(histo, notNullValue()); assertThat(histo.getName(), equalTo("histo")); List<? extends Bucket> buckets = histo.getBuckets(); assertThat("Size of buckets array is not correct.", buckets.size(), equalTo(mockHisto.size())); List<Double> expectedCounts = testValues.get(MovAvgType.HOLT_WINTERS.name() + "_" + MetricTarget.COUNT.name()); List<Double> expectedValues = testValues.get(MovAvgType.HOLT_WINTERS.name() + "_" + MetricTarget.VALUE.name()); Iterator<? extends Histogram.Bucket> actualIter = buckets.iterator(); Iterator<PipelineAggregationHelperTests.MockBucket> expectedBucketIter = mockHisto.iterator(); Iterator<Double> expectedCountsIter = expectedCounts.iterator(); Iterator<Double> expectedValuesIter = expectedValues.iterator(); while (actualIter.hasNext()) { assertValidIterators(expectedBucketIter, expectedCountsIter, expectedValuesIter); Histogram.Bucket actual = actualIter.next(); PipelineAggregationHelperTests.MockBucket expected = expectedBucketIter.next(); Double expectedCount = expectedCountsIter.next(); Double expectedValue = expectedValuesIter.next(); assertThat("keys do not match", ((Number) actual.getKey()).longValue(), equalTo(expected.key)); assertThat("doc counts do not match", actual.getDocCount(), equalTo((long)expected.count)); assertBucketContents(actual, expectedCount, expectedValue); } } public void testPredictNegativeKeysAtStart() { SearchResponse response = client() .prepareSearch("neg_idx") .setTypes("type") .addAggregation( histogram("histo") .field(INTERVAL_FIELD) .interval(1) .subAggregation(avg("avg").field(VALUE_FIELD)) .subAggregation( movingAvg("movavg_values", "avg").window(windowSize).modelBuilder(new SimpleModel.SimpleModelBuilder()) .gapPolicy(gapPolicy).predict(5))).execute().actionGet(); assertSearchResponse(response); Histogram histo = response.getAggregations().get("histo"); assertThat(histo, notNullValue()); assertThat(histo.getName(), equalTo("histo")); List<? extends Bucket> buckets = histo.getBuckets(); assertThat("Size of buckets array is not correct.", buckets.size(), equalTo(25)); SimpleValue current = buckets.get(0).getAggregations().get("movavg_values"); assertThat(current, nullValue()); for (int i = 1; i < 20; i++) { Bucket bucket = buckets.get(i); assertThat(bucket, notNullValue()); assertThat(bucket.getKey(), equalTo(i - 10d)); assertThat(bucket.getDocCount(), equalTo(1L)); Avg avgAgg = bucket.getAggregations().get("avg"); assertThat(avgAgg, notNullValue()); assertThat(avgAgg.value(), equalTo(10d)); SimpleValue movAvgAgg = bucket.getAggregations().get("movavg_values"); assertThat(movAvgAgg, notNullValue()); assertThat(movAvgAgg.value(), equalTo(10d)); } for (int i = 20; i < 25; i++) { Bucket bucket = buckets.get(i); assertThat(bucket, notNullValue()); assertThat(bucket.getKey(), equalTo(i - 10d)); assertThat(bucket.getDocCount(), equalTo(0L)); Avg avgAgg = bucket.getAggregations().get("avg"); assertThat(avgAgg, nullValue()); SimpleValue movAvgAgg = bucket.getAggregations().get("movavg_values"); assertThat(movAvgAgg, notNullValue()); assertThat(movAvgAgg.value(), equalTo(10d)); } } public void testSizeZeroWindow() { try { client() .prepareSearch("idx").setTypes("type") .addAggregation( histogram("histo").field(INTERVAL_FIELD).interval(interval) .extendedBounds(0L, (long) (interval * (numBuckets - 1))) .subAggregation(randomMetric("the_metric", VALUE_FIELD)) .subAggregation(movingAvg("movavg_counts", "the_metric") .window(0) .modelBuilder(new SimpleModel.SimpleModelBuilder()) .gapPolicy(gapPolicy)) ).execute().actionGet(); fail("MovingAvg should not accept a window that is zero"); } catch (IllegalArgumentException e) { assertThat(e.getMessage(), is("[window] must be a positive integer: [movavg_counts]")); } } public void testBadParent() { try { client() .prepareSearch("idx").setTypes("type") .addAggregation( range("histo").field(INTERVAL_FIELD).addRange(0, 10) .subAggregation(randomMetric("the_metric", VALUE_FIELD)) .subAggregation(movingAvg("movavg_counts", "the_metric") .window(windowSize) .modelBuilder(new SimpleModel.SimpleModelBuilder()) .gapPolicy(gapPolicy)) ).execute().actionGet(); fail("MovingAvg should not accept non-histogram as parent"); } catch (SearchPhaseExecutionException exception) { // All good } } public void testNegativeWindow() { try { client() .prepareSearch("idx").setTypes("type") .addAggregation( histogram("histo").field(INTERVAL_FIELD).interval(interval) .extendedBounds(0L, (long) (interval * (numBuckets - 1))) .subAggregation(randomMetric("the_metric", VALUE_FIELD)) .subAggregation(movingAvg("movavg_counts", "_count") .window(-10) .modelBuilder(new SimpleModel.SimpleModelBuilder()) .gapPolicy(gapPolicy)) ).execute().actionGet(); fail("MovingAvg should not accept a window that is negative"); } catch (IllegalArgumentException e) { assertThat(e.getMessage(), is("[window] must be a positive integer: [movavg_counts]")); } } public void testNoBucketsInHistogram() { SearchResponse response = client() .prepareSearch("idx").setTypes("type") .addAggregation( histogram("histo").field("test").interval(interval) .subAggregation(randomMetric("the_metric", VALUE_FIELD)) .subAggregation(movingAvg("movavg_counts", "the_metric") .window(windowSize) .modelBuilder(new SimpleModel.SimpleModelBuilder()) .gapPolicy(gapPolicy)) ).execute().actionGet(); assertSearchResponse(response); Histogram histo = response.getAggregations().get("histo"); assertThat(histo, notNullValue()); assertThat(histo.getName(), equalTo("histo")); List<? extends Bucket> buckets = histo.getBuckets(); assertThat(buckets.size(), equalTo(0)); } public void testNoBucketsInHistogramWithPredict() { int numPredictions = randomIntBetween(1,10); SearchResponse response = client() .prepareSearch("idx").setTypes("type") .addAggregation( histogram("histo").field("test").interval(interval) .subAggregation(randomMetric("the_metric", VALUE_FIELD)) .subAggregation(movingAvg("movavg_counts", "the_metric") .window(windowSize) .modelBuilder(new SimpleModel.SimpleModelBuilder()) .gapPolicy(gapPolicy) .predict(numPredictions)) ).execute().actionGet(); assertSearchResponse(response); Histogram histo = response.getAggregations().get("histo"); assertThat(histo, notNullValue()); assertThat(histo.getName(), equalTo("histo")); List<? extends Bucket> buckets = histo.getBuckets(); assertThat(buckets.size(), equalTo(0)); } public void testZeroPrediction() { try { client() .prepareSearch("idx").setTypes("type") .addAggregation( histogram("histo").field(INTERVAL_FIELD).interval(interval) .extendedBounds(0L, (long) (interval * (numBuckets - 1))) .subAggregation(randomMetric("the_metric", VALUE_FIELD)) .subAggregation(movingAvg("movavg_counts", "the_metric") .window(windowSize) .modelBuilder(randomModelBuilder()) .gapPolicy(gapPolicy) .predict(0)) ).execute().actionGet(); fail("MovingAvg should not accept a prediction size that is zero"); } catch (IllegalArgumentException exception) { // All Good } } public void testNegativePrediction() { try { client() .prepareSearch("idx").setTypes("type") .addAggregation( histogram("histo").field(INTERVAL_FIELD).interval(interval) .extendedBounds(0L, (long) (interval * (numBuckets - 1))) .subAggregation(randomMetric("the_metric", VALUE_FIELD)) .subAggregation(movingAvg("movavg_counts", "the_metric") .window(windowSize) .modelBuilder(randomModelBuilder()) .gapPolicy(gapPolicy) .predict(-10)) ).execute().actionGet(); fail("MovingAvg should not accept a prediction size that is negative"); } catch (IllegalArgumentException exception) { // All Good } } public void testHoltWintersNotEnoughData() { try { SearchResponse response = client() .prepareSearch("idx").setTypes("type") .addAggregation( histogram("histo").field(INTERVAL_FIELD).interval(interval) .extendedBounds(0L, (long) (interval * (numBuckets - 1))) .subAggregation(metric) .subAggregation(movingAvg("movavg_counts", "_count") .window(10) .modelBuilder(new HoltWintersModel.HoltWintersModelBuilder() .alpha(alpha).beta(beta).gamma(gamma).period(20).seasonalityType(seasonalityType)) .gapPolicy(gapPolicy)) .subAggregation(movingAvg("movavg_values", "the_metric") .window(windowSize) .modelBuilder(new HoltWintersModel.HoltWintersModelBuilder() .alpha(alpha).beta(beta).gamma(gamma).period(20).seasonalityType(seasonalityType)) .gapPolicy(gapPolicy)) ).execute().actionGet(); } catch (SearchPhaseExecutionException e) { // All good } } public void testTwoMovAvgsWithPredictions() { SearchResponse response = client() .prepareSearch("double_predict") .setTypes("type") .addAggregation( histogram("histo") .field(INTERVAL_FIELD) .interval(1) .subAggregation(avg("avg").field(VALUE_FIELD)) .subAggregation(derivative("deriv", "avg").gapPolicy(gapPolicy)) .subAggregation( movingAvg("avg_movavg", "avg").window(windowSize).modelBuilder(new SimpleModel.SimpleModelBuilder()) .gapPolicy(gapPolicy).predict(12)) .subAggregation( movingAvg("deriv_movavg", "deriv").window(windowSize).modelBuilder(new SimpleModel.SimpleModelBuilder()) .gapPolicy(gapPolicy).predict(12)) ).execute().actionGet(); assertSearchResponse(response); Histogram histo = response.getAggregations().get("histo"); assertThat(histo, notNullValue()); assertThat(histo.getName(), equalTo("histo")); List<? extends Bucket> buckets = histo.getBuckets(); assertThat("Size of buckets array is not correct.", buckets.size(), equalTo(24)); Bucket bucket = buckets.get(0); assertThat(bucket, notNullValue()); assertThat(bucket.getKey(), equalTo(0d)); assertThat(bucket.getDocCount(), equalTo(1L)); Avg avgAgg = bucket.getAggregations().get("avg"); assertThat(avgAgg, notNullValue()); assertThat(avgAgg.value(), equalTo(10d)); SimpleValue movAvgAgg = bucket.getAggregations().get("avg_movavg"); assertThat(movAvgAgg, nullValue()); Derivative deriv = bucket.getAggregations().get("deriv"); assertThat(deriv, nullValue()); SimpleValue derivMovAvg = bucket.getAggregations().get("deriv_movavg"); assertThat(derivMovAvg, nullValue()); // Second bucket bucket = buckets.get(1); assertThat(bucket, notNullValue()); assertThat(bucket.getKey(), equalTo(1d)); assertThat(bucket.getDocCount(), equalTo(1L)); avgAgg = bucket.getAggregations().get("avg"); assertThat(avgAgg, notNullValue()); assertThat(avgAgg.value(), equalTo(10d)); deriv = bucket.getAggregations().get("deriv"); assertThat(deriv, notNullValue()); assertThat(deriv.value(), equalTo(0d)); movAvgAgg = bucket.getAggregations().get("avg_movavg"); assertThat(movAvgAgg, notNullValue()); assertThat(movAvgAgg.value(), equalTo(10d)); derivMovAvg = bucket.getAggregations().get("deriv_movavg"); assertThat(derivMovAvg, Matchers.nullValue()); // still null because of movavg delay for (int i = 2; i < 12; i++) { bucket = buckets.get(i); assertThat(bucket, notNullValue()); assertThat(bucket.getKey(), equalTo((double) i)); assertThat(bucket.getDocCount(), equalTo(1L)); avgAgg = bucket.getAggregations().get("avg"); assertThat(avgAgg, notNullValue()); assertThat(avgAgg.value(), equalTo(10d)); deriv = bucket.getAggregations().get("deriv"); assertThat(deriv, notNullValue()); assertThat(deriv.value(), equalTo(0d)); movAvgAgg = bucket.getAggregations().get("avg_movavg"); assertThat(movAvgAgg, notNullValue()); assertThat(movAvgAgg.value(), equalTo(10d)); derivMovAvg = bucket.getAggregations().get("deriv_movavg"); assertThat(derivMovAvg, notNullValue()); assertThat(derivMovAvg.value(), equalTo(0d)); } // Predictions for (int i = 12; i < 24; i++) { bucket = buckets.get(i); assertThat(bucket, notNullValue()); assertThat(bucket.getKey(), equalTo((double) i)); assertThat(bucket.getDocCount(), equalTo(0L)); avgAgg = bucket.getAggregations().get("avg"); assertThat(avgAgg, nullValue()); deriv = bucket.getAggregations().get("deriv"); assertThat(deriv, nullValue()); movAvgAgg = bucket.getAggregations().get("avg_movavg"); assertThat(movAvgAgg, notNullValue()); assertThat(movAvgAgg.value(), equalTo(10d)); derivMovAvg = bucket.getAggregations().get("deriv_movavg"); assertThat(derivMovAvg, notNullValue()); assertThat(derivMovAvg.value(), equalTo(0d)); } } public void testBadModelParams() { try { SearchResponse response = client() .prepareSearch("idx").setTypes("type") .addAggregation( histogram("histo").field(INTERVAL_FIELD).interval(interval) .extendedBounds(0L, (long) (interval * (numBuckets - 1))) .subAggregation(metric) .subAggregation(movingAvg("movavg_counts", "_count") .window(10) .modelBuilder(randomModelBuilder(100)) .gapPolicy(gapPolicy)) ).execute().actionGet(); } catch (SearchPhaseExecutionException e) { // All good } } public void testHoltWintersMinimization() { SearchResponse response = client() .prepareSearch("idx").setTypes("type") .addAggregation( histogram("histo").field(INTERVAL_FIELD).interval(interval) .extendedBounds(0L, (long) (interval * (numBuckets - 1))) .subAggregation(metric) .subAggregation(movingAvg("movavg_counts", "_count") .window(windowSize) .modelBuilder(new HoltWintersModel.HoltWintersModelBuilder() .period(period).seasonalityType(seasonalityType)) .gapPolicy(gapPolicy) .minimize(true)) .subAggregation(movingAvg("movavg_values", "the_metric") .window(windowSize) .modelBuilder(new HoltWintersModel.HoltWintersModelBuilder() .period(period).seasonalityType(seasonalityType)) .gapPolicy(gapPolicy) .minimize(true)) ).execute().actionGet(); assertSearchResponse(response); Histogram histo = response.getAggregations().get("histo"); assertThat(histo, notNullValue()); assertThat(histo.getName(), equalTo("histo")); List<? extends Bucket> buckets = histo.getBuckets(); assertThat("Size of buckets array is not correct.", buckets.size(), equalTo(mockHisto.size())); List<Double> expectedCounts = testValues.get(MovAvgType.HOLT_WINTERS.name() + "_" + MetricTarget.COUNT.name()); List<Double> expectedValues = testValues.get(MovAvgType.HOLT_WINTERS.name() + "_" + MetricTarget.VALUE.name()); Iterator<? extends Histogram.Bucket> actualIter = buckets.iterator(); Iterator<PipelineAggregationHelperTests.MockBucket> expectedBucketIter = mockHisto.iterator(); Iterator<Double> expectedCountsIter = expectedCounts.iterator(); Iterator<Double> expectedValueIter = expectedValues.iterator(); // The minimizer is stochastic, so just make sure all the values coming back aren't null while (actualIter.hasNext()) { Histogram.Bucket actual = actualIter.next(); PipelineAggregationHelperTests.MockBucket expected = expectedBucketIter.next(); Double expectedCount = expectedCountsIter.next(); Double expectedValue = expectedValueIter.next(); assertThat("keys do not match", ((Number) actual.getKey()).longValue(), equalTo(expected.key)); assertThat("doc counts do not match", actual.getDocCount(), equalTo((long)expected.count)); SimpleValue countMovAvg = actual.getAggregations().get("movavg_counts"); SimpleValue valuesMovAvg = actual.getAggregations().get("movavg_values"); if (expectedCount == null) { //this bucket wasn't supposed to have a value (empty, skipped, etc), so //movavg should be null too assertThat(countMovAvg, nullValue()); } else { // Note that we don't compare against the mock values, since those are assuming // a non-minimized set of coefficients. Just check for not-nullness assertThat(countMovAvg, notNullValue()); } if (expectedValue == null) { //this bucket wasn't supposed to have a value (empty, skipped, etc), so //movavg should be null too assertThat(valuesMovAvg, nullValue()); } else { // Note that we don't compare against the mock values, since those are assuming // a non-minimized set of coefficients. Just check for not-nullness assertThat(valuesMovAvg, notNullValue()); } } } /** * If the minimizer is turned on, but there isn't enough data to minimize with, it will simply use * the default settings. Which means our mock histo will match the generated result (which it won't * if the minimizer is actually working, since the coefficients will be different and thus generate different * data) * * We can simulate this by setting the window size == size of histo */ public void testMinimizeNotEnoughData() { SearchResponse response = client() .prepareSearch("idx").setTypes("type") .addAggregation( histogram("histo").field(INTERVAL_FIELD).interval(interval) .extendedBounds(0L, (long) (interval * (numBuckets - 1))) .subAggregation(metric) .subAggregation(movingAvg("movavg_counts", "_count") .window(numBuckets) .modelBuilder(new HoltLinearModel.HoltLinearModelBuilder().alpha(alpha).beta(beta)) .gapPolicy(gapPolicy) .minimize(true)) .subAggregation(movingAvg("movavg_values", "the_metric") .window(numBuckets) .modelBuilder(new HoltLinearModel.HoltLinearModelBuilder().alpha(alpha).beta(beta)) .gapPolicy(gapPolicy) .minimize(true)) ).execute().actionGet(); assertSearchResponse(response); Histogram histo = response.getAggregations().get("histo"); assertThat(histo, notNullValue()); assertThat(histo.getName(), equalTo("histo")); List<? extends Bucket> buckets = histo.getBuckets(); assertThat("Size of buckets array is not correct.", buckets.size(), equalTo(mockHisto.size())); List<Double> expectedCounts = testValues.get(MovAvgType.HOLT_BIG_MINIMIZE.name() + "_" + MetricTarget.COUNT.name()); List<Double> expectedValues = testValues.get(MovAvgType.HOLT_BIG_MINIMIZE.name() + "_" + MetricTarget.VALUE.name()); Iterator<? extends Histogram.Bucket> actualIter = buckets.iterator(); Iterator<PipelineAggregationHelperTests.MockBucket> expectedBucketIter = mockHisto.iterator(); Iterator<Double> expectedCountsIter = expectedCounts.iterator(); Iterator<Double> expectedValuesIter = expectedValues.iterator(); while (actualIter.hasNext()) { assertValidIterators(expectedBucketIter, expectedCountsIter, expectedValuesIter); Histogram.Bucket actual = actualIter.next(); PipelineAggregationHelperTests.MockBucket expected = expectedBucketIter.next(); Double expectedCount = expectedCountsIter.next(); Double expectedValue = expectedValuesIter.next(); assertThat("keys do not match", ((Number) actual.getKey()).longValue(), equalTo(expected.key)); assertThat("doc counts do not match", actual.getDocCount(), equalTo((long)expected.count)); assertBucketContents(actual, expectedCount, expectedValue); } } /** * Only some models can be minimized, should throw exception for: simple, linear */ public void testCheckIfNonTunableCanBeMinimized() { try { client() .prepareSearch("idx").setTypes("type") .addAggregation( histogram("histo").field(INTERVAL_FIELD).interval(interval) .extendedBounds(0L, (long) (interval * (numBuckets - 1))) .subAggregation(metric) .subAggregation(movingAvg("movavg_counts", "_count") .window(numBuckets) .modelBuilder(new SimpleModel.SimpleModelBuilder()) .gapPolicy(gapPolicy) .minimize(true)) ).execute().actionGet(); fail("Simple Model cannot be minimized, but an exception was not thrown"); } catch (SearchPhaseExecutionException e) { // All good } try { client() .prepareSearch("idx").setTypes("type") .addAggregation( histogram("histo").field(INTERVAL_FIELD).interval(interval) .extendedBounds(0L, (long) (interval * (numBuckets - 1))) .subAggregation(metric) .subAggregation(movingAvg("movavg_counts", "_count") .window(numBuckets) .modelBuilder(new LinearModel.LinearModelBuilder()) .gapPolicy(gapPolicy) .minimize(true)) ).execute().actionGet(); fail("Linear Model cannot be minimized, but an exception was not thrown"); } catch (SearchPhaseExecutionException e) { // all good } } /** * These models are all minimizable, so they should not throw exceptions */ public void testCheckIfTunableCanBeMinimized() { MovAvgModelBuilder[] builders = new MovAvgModelBuilder[]{ new EwmaModel.EWMAModelBuilder(), new HoltLinearModel.HoltLinearModelBuilder(), new HoltWintersModel.HoltWintersModelBuilder() }; for (MovAvgModelBuilder builder : builders) { try { client() .prepareSearch("idx").setTypes("type") .addAggregation( histogram("histo").field(INTERVAL_FIELD).interval(interval) .extendedBounds(0L, (long) (interval * (numBuckets - 1))) .subAggregation(metric) .subAggregation(movingAvg("movavg_counts", "_count") .window(numBuckets) .modelBuilder(builder) .gapPolicy(gapPolicy) .minimize(true)) ).execute().actionGet(); } catch (SearchPhaseExecutionException e) { fail("Model [" + builder.toString() + "] can be minimized, but an exception was thrown"); } } } public void testPredictWithNonEmptyBuckets() throws Exception { createIndex("predict_non_empty"); BulkRequestBuilder bulkBuilder = client().prepareBulk().setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE); for (int i = 0; i < 10; i++) { bulkBuilder.add(client().prepareIndex("predict_non_empty", "type").setSource( jsonBuilder().startObject().field(INTERVAL_FIELD, i) .field(VALUE_FIELD, 10) .field(VALUE_FIELD2, 10) .endObject())); } for (int i = 10; i < 20; i++) { // Extra so there is a bucket that only has second field bulkBuilder.add(client().prepareIndex("predict_non_empty", "type").setSource( jsonBuilder().startObject().field(INTERVAL_FIELD, i).field(VALUE_FIELD2, 10).endObject())); } bulkBuilder.execute().actionGet(); ensureSearchable(); SearchResponse response = client() .prepareSearch("predict_non_empty") .setTypes("type") .addAggregation( histogram("histo") .field(INTERVAL_FIELD) .interval(1) .subAggregation(max("max").field(VALUE_FIELD)) .subAggregation(max("max2").field(VALUE_FIELD2)) .subAggregation( movingAvg("movavg_values", "max") .window(windowSize) .modelBuilder(new SimpleModel.SimpleModelBuilder()) .gapPolicy(BucketHelpers.GapPolicy.SKIP).predict(5))).execute().actionGet(); assertSearchResponse(response); Histogram histo = response.getAggregations().get("histo"); assertThat(histo, notNullValue()); assertThat(histo.getName(), equalTo("histo")); List<? extends Bucket> buckets = histo.getBuckets(); assertThat("Size of buckets array is not correct.", buckets.size(), equalTo(20)); SimpleValue current = buckets.get(0).getAggregations().get("movavg_values"); assertThat(current, nullValue()); for (int i = 1; i < 20; i++) { Bucket bucket = buckets.get(i); assertThat(bucket, notNullValue()); assertThat(bucket.getKey(), equalTo((double)i)); assertThat(bucket.getDocCount(), equalTo(1L)); SimpleValue movAvgAgg = bucket.getAggregations().get("movavg_values"); if (i < 15) { assertThat(movAvgAgg, notNullValue()); assertThat(movAvgAgg.value(), equalTo(10d)); } else { assertThat(movAvgAgg, nullValue()); } } } private void assertValidIterators(Iterator expectedBucketIter, Iterator expectedCountsIter, Iterator expectedValuesIter) { if (!expectedBucketIter.hasNext()) { fail("`expectedBucketIter` iterator ended before `actual` iterator, size mismatch"); } if (!expectedCountsIter.hasNext()) { fail("`expectedCountsIter` iterator ended before `actual` iterator, size mismatch"); } if (!expectedValuesIter.hasNext()) { fail("`expectedValuesIter` iterator ended before `actual` iterator, size mismatch"); } } private void assertBucketContents(Histogram.Bucket actual, Double expectedCount, Double expectedValue) { // This is a gap bucket SimpleValue countMovAvg = actual.getAggregations().get("movavg_counts"); if (expectedCount == null) { assertThat("[_count] movavg is not null", countMovAvg, nullValue()); } else if (Double.isNaN(expectedCount)) { assertThat("[_count] movavg should be NaN, but is ["+countMovAvg.value()+"] instead", countMovAvg.value(), equalTo(Double.NaN)); } else { assertThat("[_count] movavg is null", countMovAvg, notNullValue()); assertEquals("[_count] movavg does not match expected [" + countMovAvg.value() + " vs " + expectedCount + "]", countMovAvg.value(), expectedCount, 0.1 * Math.abs(countMovAvg.value())); } // This is a gap bucket SimpleValue valuesMovAvg = actual.getAggregations().get("movavg_values"); if (expectedValue == null) { assertThat("[value] movavg is not null", valuesMovAvg, Matchers.nullValue()); } else if (Double.isNaN(expectedValue)) { assertThat("[value] movavg should be NaN, but is ["+valuesMovAvg.value()+"] instead", valuesMovAvg.value(), equalTo(Double.NaN)); } else { assertThat("[value] movavg is null", valuesMovAvg, notNullValue()); assertEquals("[value] movavg does not match expected [" + valuesMovAvg.value() + " vs " + expectedValue + "]", valuesMovAvg.value(), expectedValue, 0.1 * Math.abs(valuesMovAvg.value())); } } private MovAvgModelBuilder randomModelBuilder() { return randomModelBuilder(0); } private MovAvgModelBuilder randomModelBuilder(double padding) { int rand = randomIntBetween(0,3); // HoltWinters is excluded from random generation, because it's "cold start" behavior makes // randomized testing too tricky. Should probably add dedicated, randomized tests just for HoltWinters, // which can compensate for the idiosyncrasies switch (rand) { case 0: return new SimpleModel.SimpleModelBuilder(); case 1: return new LinearModel.LinearModelBuilder(); case 2: return new EwmaModel.EWMAModelBuilder().alpha(alpha + padding); case 3: return new HoltLinearModel.HoltLinearModelBuilder().alpha(alpha + padding).beta(beta + padding); default: return new SimpleModel.SimpleModelBuilder(); } } private ValuesSourceAggregationBuilder<? extends ValuesSource, ? extends ValuesSourceAggregationBuilder<?, ?>> randomMetric(String name, String field) { int rand = randomIntBetween(0,3); switch (rand) { case 0: return min(name).field(field); case 2: return max(name).field(field); case 3: return avg(name).field(field); default: return avg(name).field(field); } } }
server/src/test/java/org/elasticsearch/search/aggregations/pipeline/moving/avg/MovAvgIT.java
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch 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.elasticsearch.search.aggregations.pipeline.moving.avg; import org.elasticsearch.action.bulk.BulkRequestBuilder; import org.elasticsearch.action.index.IndexRequestBuilder; import org.elasticsearch.action.search.SearchPhaseExecutionException; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.support.WriteRequest; import org.elasticsearch.common.collect.EvictingQueue; import org.elasticsearch.search.aggregations.bucket.histogram.Histogram; import org.elasticsearch.search.aggregations.bucket.histogram.Histogram.Bucket; import org.elasticsearch.search.aggregations.metrics.avg.Avg; import org.elasticsearch.search.aggregations.pipeline.BucketHelpers; import org.elasticsearch.search.aggregations.pipeline.PipelineAggregationHelperTests; import org.elasticsearch.search.aggregations.pipeline.SimpleValue; import org.elasticsearch.search.aggregations.pipeline.derivative.Derivative; import org.elasticsearch.search.aggregations.pipeline.movavg.models.EwmaModel; import org.elasticsearch.search.aggregations.pipeline.movavg.models.HoltLinearModel; import org.elasticsearch.search.aggregations.pipeline.movavg.models.HoltWintersModel; import org.elasticsearch.search.aggregations.pipeline.movavg.models.LinearModel; import org.elasticsearch.search.aggregations.pipeline.movavg.models.MovAvgModelBuilder; import org.elasticsearch.search.aggregations.pipeline.movavg.models.SimpleModel; import org.elasticsearch.search.aggregations.support.ValuesSource; import org.elasticsearch.search.aggregations.support.ValuesSourceAggregationBuilder; import org.elasticsearch.test.ESIntegTestCase; import org.hamcrest.Matchers; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; import static org.elasticsearch.search.aggregations.AggregationBuilders.avg; import static org.elasticsearch.search.aggregations.AggregationBuilders.histogram; import static org.elasticsearch.search.aggregations.AggregationBuilders.max; import static org.elasticsearch.search.aggregations.AggregationBuilders.min; import static org.elasticsearch.search.aggregations.AggregationBuilders.range; import static org.elasticsearch.search.aggregations.pipeline.PipelineAggregatorBuilders.derivative; import static org.elasticsearch.search.aggregations.pipeline.PipelineAggregatorBuilders.movingAvg; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSearchResponse; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.hamcrest.core.IsNull.notNullValue; import static org.hamcrest.core.IsNull.nullValue; @ESIntegTestCase.SuiteScopeTestCase public class MovAvgIT extends ESIntegTestCase { private static final String INTERVAL_FIELD = "l_value"; private static final String VALUE_FIELD = "v_value"; private static final String VALUE_FIELD2 = "v_value2"; static int interval; static int numBuckets; static int windowSize; static double alpha; static double beta; static double gamma; static int period; static HoltWintersModel.SeasonalityType seasonalityType; static BucketHelpers.GapPolicy gapPolicy; static ValuesSourceAggregationBuilder<? extends ValuesSource, ? extends ValuesSourceAggregationBuilder<?, ?>> metric; static List<PipelineAggregationHelperTests.MockBucket> mockHisto; static Map<String, ArrayList<Double>> testValues; enum MovAvgType { SIMPLE ("simple"), LINEAR("linear"), EWMA("ewma"), HOLT("holt"), HOLT_WINTERS("holt_winters"), HOLT_BIG_MINIMIZE("holt"); private final String name; MovAvgType(String s) { name = s; } @Override public String toString(){ return name; } } enum MetricTarget { VALUE ("value"), COUNT("count"), METRIC("metric"); private final String name; MetricTarget(String s) { name = s; } @Override public String toString(){ return name; } } @Override public void setupSuiteScopeCluster() throws Exception { createIndex("idx"); createIndex("idx_unmapped"); List<IndexRequestBuilder> builders = new ArrayList<>(); interval = 5; numBuckets = randomIntBetween(6, 80); period = randomIntBetween(1, 5); windowSize = randomIntBetween(period * 2, 10); // start must be 2*period to play nice with HW alpha = randomDouble(); beta = randomDouble(); gamma = randomDouble(); seasonalityType = randomBoolean() ? HoltWintersModel.SeasonalityType.ADDITIVE : HoltWintersModel.SeasonalityType.MULTIPLICATIVE; gapPolicy = randomBoolean() ? BucketHelpers.GapPolicy.SKIP : BucketHelpers.GapPolicy.INSERT_ZEROS; metric = randomMetric("the_metric", VALUE_FIELD); mockHisto = PipelineAggregationHelperTests.generateHistogram(interval, numBuckets, randomDouble(), randomDouble()); testValues = new HashMap<>(8); for (MovAvgType type : MovAvgType.values()) { for (MetricTarget target : MetricTarget.values()) { if (type.equals(MovAvgType.HOLT_BIG_MINIMIZE)) { setupExpected(type, target, numBuckets); } else { setupExpected(type, target, windowSize); } } } for (PipelineAggregationHelperTests.MockBucket mockBucket : mockHisto) { for (double value : mockBucket.docValues) { builders.add(client().prepareIndex("idx", "type").setSource(jsonBuilder().startObject() .field(INTERVAL_FIELD, mockBucket.key) .field(VALUE_FIELD, value).endObject())); } } for (int i = -10; i < 10; i++) { builders.add(client().prepareIndex("neg_idx", "type").setSource( jsonBuilder().startObject().field(INTERVAL_FIELD, i).field(VALUE_FIELD, 10).endObject())); } for (int i = 0; i < 12; i++) { builders.add(client().prepareIndex("double_predict", "type").setSource( jsonBuilder().startObject().field(INTERVAL_FIELD, i).field(VALUE_FIELD, 10).endObject())); } indexRandom(true, builders); ensureSearchable(); } /** * Calculates the moving averages for a specific (model, target) tuple based on the previously generated mock histogram. * Computed values are stored in the testValues map. * * @param type The moving average model to use * @param target The document field "target", e.g. _count or a field value */ private void setupExpected(MovAvgType type, MetricTarget target, int windowSize) { ArrayList<Double> values = new ArrayList<>(numBuckets); EvictingQueue<Double> window = new EvictingQueue<>(windowSize); for (PipelineAggregationHelperTests.MockBucket mockBucket : mockHisto) { double metricValue; double[] docValues = mockBucket.docValues; // Gaps only apply to metric values, not doc _counts if (mockBucket.count == 0 && target.equals(MetricTarget.VALUE)) { // If there was a gap in doc counts and we are ignoring, just skip this bucket if (gapPolicy.equals(BucketHelpers.GapPolicy.SKIP)) { values.add(null); continue; } else if (gapPolicy.equals(BucketHelpers.GapPolicy.INSERT_ZEROS)) { // otherwise insert a zero instead of the true value metricValue = 0.0; } else { metricValue = PipelineAggregationHelperTests.calculateMetric(docValues, metric); } } else { // If this isn't a gap, or is a _count, just insert the value metricValue = target.equals(MetricTarget.VALUE) ? PipelineAggregationHelperTests.calculateMetric(docValues, metric) : mockBucket.count; } if (window.size() > 0) { switch (type) { case SIMPLE: values.add(simple(window)); break; case LINEAR: values.add(linear(window)); break; case EWMA: values.add(ewma(window)); break; case HOLT: values.add(holt(window)); break; case HOLT_BIG_MINIMIZE: values.add(holt(window)); break; case HOLT_WINTERS: // HW needs at least 2 periods of data to start if (window.size() >= period * 2) { values.add(holtWinters(window)); } else { values.add(null); } break; } } else { values.add(null); } window.offer(metricValue); } testValues.put(type.name() + "_" + target.name(), values); } /** * Simple, unweighted moving average * * @param window Window of values to compute movavg for */ private double simple(Collection<Double> window) { double movAvg = 0; for (double value : window) { movAvg += value; } movAvg /= window.size(); return movAvg; } /** * Linearly weighted moving avg * * @param window Window of values to compute movavg for */ private double linear(Collection<Double> window) { double avg = 0; long totalWeight = 1; long current = 1; for (double value : window) { avg += value * current; totalWeight += current; current += 1; } return avg / totalWeight; } /** * Exponentially weighted (EWMA, Single exponential) moving avg * * @param window Window of values to compute movavg for */ private double ewma(Collection<Double> window) { double avg = 0; boolean first = true; for (double value : window) { if (first) { avg = value; first = false; } else { avg = (value * alpha) + (avg * (1 - alpha)); } } return avg; } /** * Holt-Linear (Double exponential) moving avg * @param window Window of values to compute movavg for */ private double holt(Collection<Double> window) { double s = 0; double last_s = 0; // Trend value double b = 0; double last_b = 0; int counter = 0; double last; for (double value : window) { last = value; if (counter == 0) { s = value; b = value - last; } else { s = alpha * value + (1.0d - alpha) * (last_s + last_b); b = beta * (s - last_s) + (1 - beta) * last_b; } counter += 1; last_s = s; last_b = b; } return s + (0 * b) ; } /** * Holt winters (triple exponential) moving avg * @param window Window of values to compute movavg for */ private double holtWinters(Collection<Double> window) { // Smoothed value double s = 0; double last_s = 0; // Trend value double b = 0; double last_b = 0; // Seasonal value double[] seasonal = new double[window.size()]; double padding = seasonalityType.equals(HoltWintersModel.SeasonalityType.MULTIPLICATIVE) ? 0.0000000001 : 0; int counter = 0; double[] vs = new double[window.size()]; for (double v : window) { vs[counter] = v + padding; counter += 1; } // Initial level value is average of first season // Calculate the slopes between first and second season for each period for (int i = 0; i < period; i++) { s += vs[i]; b += (vs[i + period] - vs[i]) / period; } s /= period; b /= period; last_s = s; // Calculate first seasonal if (Double.compare(s, 0.0) == 0 || Double.compare(s, -0.0) == 0) { Arrays.fill(seasonal, 0.0); } else { for (int i = 0; i < period; i++) { seasonal[i] = vs[i] / s; } } for (int i = period; i < vs.length; i++) { if (seasonalityType.equals(HoltWintersModel.SeasonalityType.MULTIPLICATIVE)) { s = alpha * (vs[i] / seasonal[i - period]) + (1.0d - alpha) * (last_s + last_b); } else { s = alpha * (vs[i] - seasonal[i - period]) + (1.0d - alpha) * (last_s + last_b); } b = beta * (s - last_s) + (1 - beta) * last_b; if (seasonalityType.equals(HoltWintersModel.SeasonalityType.MULTIPLICATIVE)) { seasonal[i] = gamma * (vs[i] / (last_s + last_b )) + (1 - gamma) * seasonal[i - period]; } else { seasonal[i] = gamma * (vs[i] - (last_s - last_b )) + (1 - gamma) * seasonal[i - period]; } last_s = s; last_b = b; } int idx = window.size() - period + (0 % period); // TODO perhaps pad out seasonal to a power of 2 and use a mask instead of modulo? if (seasonalityType.equals(HoltWintersModel.SeasonalityType.MULTIPLICATIVE)) { return (s + (1 * b)) * seasonal[idx]; } else { return s + (1 * b) + seasonal[idx]; } } /** * test simple moving average on single value field */ public void testSimpleSingleValuedField() { SearchResponse response = client() .prepareSearch("idx").setTypes("type") .addAggregation( histogram("histo").field(INTERVAL_FIELD).interval(interval) .extendedBounds(0L, (long) (interval * (numBuckets - 1))) .subAggregation(metric) .subAggregation(movingAvg("movavg_counts","_count") .window(windowSize) .modelBuilder(new SimpleModel.SimpleModelBuilder()) .gapPolicy(gapPolicy)) .subAggregation(movingAvg("movavg_values","the_metric") .window(windowSize) .modelBuilder(new SimpleModel.SimpleModelBuilder()) .gapPolicy(gapPolicy)) ).execute().actionGet(); assertSearchResponse(response); Histogram histo = response.getAggregations().get("histo"); assertThat(histo, notNullValue()); assertThat(histo.getName(), equalTo("histo")); List<? extends Bucket> buckets = histo.getBuckets(); assertThat("Size of buckets array is not correct.", buckets.size(), equalTo(mockHisto.size())); List<Double> expectedCounts = testValues.get(MovAvgType.SIMPLE.name() + "_" + MetricTarget.COUNT.name()); List<Double> expectedValues = testValues.get(MovAvgType.SIMPLE.name() + "_" + MetricTarget.VALUE.name()); Iterator<? extends Histogram.Bucket> actualIter = buckets.iterator(); Iterator<PipelineAggregationHelperTests.MockBucket> expectedBucketIter = mockHisto.iterator(); Iterator<Double> expectedCountsIter = expectedCounts.iterator(); Iterator<Double> expectedValuesIter = expectedValues.iterator(); while (actualIter.hasNext()) { assertValidIterators(expectedBucketIter, expectedCountsIter, expectedValuesIter); Histogram.Bucket actual = actualIter.next(); PipelineAggregationHelperTests.MockBucket expected = expectedBucketIter.next(); Double expectedCount = expectedCountsIter.next(); Double expectedValue = expectedValuesIter.next(); assertThat("keys do not match", ((Number) actual.getKey()).longValue(), equalTo(expected.key)); assertThat("doc counts do not match", actual.getDocCount(), equalTo((long)expected.count)); assertBucketContents(actual, expectedCount, expectedValue); } } public void testLinearSingleValuedField() { SearchResponse response = client() .prepareSearch("idx").setTypes("type") .addAggregation( histogram("histo").field(INTERVAL_FIELD).interval(interval) .extendedBounds(0L, (long) (interval * (numBuckets - 1))) .subAggregation(metric) .subAggregation(movingAvg("movavg_counts", "_count") .window(windowSize) .modelBuilder(new LinearModel.LinearModelBuilder()) .gapPolicy(gapPolicy)) .subAggregation(movingAvg("movavg_values", "the_metric") .window(windowSize) .modelBuilder(new LinearModel.LinearModelBuilder()) .gapPolicy(gapPolicy)) ).execute().actionGet(); assertSearchResponse(response); Histogram histo = response.getAggregations().get("histo"); assertThat(histo, notNullValue()); assertThat(histo.getName(), equalTo("histo")); List<? extends Bucket> buckets = histo.getBuckets(); assertThat("Size of buckets array is not correct.", buckets.size(), equalTo(mockHisto.size())); List<Double> expectedCounts = testValues.get(MovAvgType.LINEAR.name() + "_" + MetricTarget.COUNT.name()); List<Double> expectedValues = testValues.get(MovAvgType.LINEAR.name() + "_" + MetricTarget.VALUE.name()); Iterator<? extends Histogram.Bucket> actualIter = buckets.iterator(); Iterator<PipelineAggregationHelperTests.MockBucket> expectedBucketIter = mockHisto.iterator(); Iterator<Double> expectedCountsIter = expectedCounts.iterator(); Iterator<Double> expectedValuesIter = expectedValues.iterator(); while (actualIter.hasNext()) { assertValidIterators(expectedBucketIter, expectedCountsIter, expectedValuesIter); Histogram.Bucket actual = actualIter.next(); PipelineAggregationHelperTests.MockBucket expected = expectedBucketIter.next(); Double expectedCount = expectedCountsIter.next(); Double expectedValue = expectedValuesIter.next(); assertThat("keys do not match", ((Number) actual.getKey()).longValue(), equalTo(expected.key)); assertThat("doc counts do not match", actual.getDocCount(), equalTo((long)expected.count)); assertBucketContents(actual, expectedCount, expectedValue); } } public void testEwmaSingleValuedField() { SearchResponse response = client() .prepareSearch("idx").setTypes("type") .addAggregation( histogram("histo").field(INTERVAL_FIELD).interval(interval) .extendedBounds(0L, (long) (interval * (numBuckets - 1))) .subAggregation(metric) .subAggregation(movingAvg("movavg_counts", "_count") .window(windowSize) .modelBuilder(new EwmaModel.EWMAModelBuilder().alpha(alpha)) .gapPolicy(gapPolicy)) .subAggregation(movingAvg("movavg_values", "the_metric") .window(windowSize) .modelBuilder(new EwmaModel.EWMAModelBuilder().alpha(alpha)) .gapPolicy(gapPolicy)) ).execute().actionGet(); assertSearchResponse(response); Histogram histo = response.getAggregations().get("histo"); assertThat(histo, notNullValue()); assertThat(histo.getName(), equalTo("histo")); List<? extends Bucket> buckets = histo.getBuckets(); assertThat("Size of buckets array is not correct.", buckets.size(), equalTo(mockHisto.size())); List<Double> expectedCounts = testValues.get(MovAvgType.EWMA.name() + "_" + MetricTarget.COUNT.name()); List<Double> expectedValues = testValues.get(MovAvgType.EWMA.name() + "_" + MetricTarget.VALUE.name()); Iterator<? extends Histogram.Bucket> actualIter = buckets.iterator(); Iterator<PipelineAggregationHelperTests.MockBucket> expectedBucketIter = mockHisto.iterator(); Iterator<Double> expectedCountsIter = expectedCounts.iterator(); Iterator<Double> expectedValuesIter = expectedValues.iterator(); while (actualIter.hasNext()) { assertValidIterators(expectedBucketIter, expectedCountsIter, expectedValuesIter); Histogram.Bucket actual = actualIter.next(); PipelineAggregationHelperTests.MockBucket expected = expectedBucketIter.next(); Double expectedCount = expectedCountsIter.next(); Double expectedValue = expectedValuesIter.next(); assertThat("keys do not match", ((Number) actual.getKey()).longValue(), equalTo(expected.key)); assertThat("doc counts do not match", actual.getDocCount(), equalTo((long)expected.count)); assertBucketContents(actual, expectedCount, expectedValue); } } public void testHoltSingleValuedField() { SearchResponse response = client() .prepareSearch("idx").setTypes("type") .addAggregation( histogram("histo").field(INTERVAL_FIELD).interval(interval) .extendedBounds(0L, (long) (interval * (numBuckets - 1))) .subAggregation(metric) .subAggregation(movingAvg("movavg_counts", "_count") .window(windowSize) .modelBuilder(new HoltLinearModel.HoltLinearModelBuilder().alpha(alpha).beta(beta)) .gapPolicy(gapPolicy)) .subAggregation(movingAvg("movavg_values", "the_metric") .window(windowSize) .modelBuilder(new HoltLinearModel.HoltLinearModelBuilder().alpha(alpha).beta(beta)) .gapPolicy(gapPolicy)) ).execute().actionGet(); assertSearchResponse(response); Histogram histo = response.getAggregations().get("histo"); assertThat(histo, notNullValue()); assertThat(histo.getName(), equalTo("histo")); List<? extends Bucket> buckets = histo.getBuckets(); assertThat("Size of buckets array is not correct.", buckets.size(), equalTo(mockHisto.size())); List<Double> expectedCounts = testValues.get(MovAvgType.HOLT.name() + "_" + MetricTarget.COUNT.name()); List<Double> expectedValues = testValues.get(MovAvgType.HOLT.name() + "_" + MetricTarget.VALUE.name()); Iterator<? extends Histogram.Bucket> actualIter = buckets.iterator(); Iterator<PipelineAggregationHelperTests.MockBucket> expectedBucketIter = mockHisto.iterator(); Iterator<Double> expectedCountsIter = expectedCounts.iterator(); Iterator<Double> expectedValuesIter = expectedValues.iterator(); while (actualIter.hasNext()) { assertValidIterators(expectedBucketIter, expectedCountsIter, expectedValuesIter); Histogram.Bucket actual = actualIter.next(); PipelineAggregationHelperTests.MockBucket expected = expectedBucketIter.next(); Double expectedCount = expectedCountsIter.next(); Double expectedValue = expectedValuesIter.next(); assertThat("keys do not match", ((Number) actual.getKey()).longValue(), equalTo(expected.key)); assertThat("doc counts do not match", actual.getDocCount(), equalTo((long)expected.count)); assertBucketContents(actual, expectedCount, expectedValue); } } public void testHoltWintersValuedField() { SearchResponse response = client() .prepareSearch("idx").setTypes("type") .addAggregation( histogram("histo").field(INTERVAL_FIELD).interval(interval) .extendedBounds(0L, (long) (interval * (numBuckets - 1))) .subAggregation(metric) .subAggregation(movingAvg("movavg_counts", "_count") .window(windowSize) .modelBuilder(new HoltWintersModel.HoltWintersModelBuilder() .alpha(alpha).beta(beta).gamma(gamma).period(period).seasonalityType(seasonalityType)) .gapPolicy(gapPolicy) .minimize(false)) .subAggregation(movingAvg("movavg_values", "the_metric") .window(windowSize) .modelBuilder(new HoltWintersModel.HoltWintersModelBuilder() .alpha(alpha).beta(beta).gamma(gamma).period(period).seasonalityType(seasonalityType)) .gapPolicy(gapPolicy) .minimize(false)) ).execute().actionGet(); assertSearchResponse(response); Histogram histo = response.getAggregations().get("histo"); assertThat(histo, notNullValue()); assertThat(histo.getName(), equalTo("histo")); List<? extends Bucket> buckets = histo.getBuckets(); assertThat("Size of buckets array is not correct.", buckets.size(), equalTo(mockHisto.size())); List<Double> expectedCounts = testValues.get(MovAvgType.HOLT_WINTERS.name() + "_" + MetricTarget.COUNT.name()); List<Double> expectedValues = testValues.get(MovAvgType.HOLT_WINTERS.name() + "_" + MetricTarget.VALUE.name()); Iterator<? extends Histogram.Bucket> actualIter = buckets.iterator(); Iterator<PipelineAggregationHelperTests.MockBucket> expectedBucketIter = mockHisto.iterator(); Iterator<Double> expectedCountsIter = expectedCounts.iterator(); Iterator<Double> expectedValuesIter = expectedValues.iterator(); while (actualIter.hasNext()) { assertValidIterators(expectedBucketIter, expectedCountsIter, expectedValuesIter); Histogram.Bucket actual = actualIter.next(); PipelineAggregationHelperTests.MockBucket expected = expectedBucketIter.next(); Double expectedCount = expectedCountsIter.next(); Double expectedValue = expectedValuesIter.next(); assertThat("keys do not match", ((Number) actual.getKey()).longValue(), equalTo(expected.key)); assertThat("doc counts do not match", actual.getDocCount(), equalTo((long)expected.count)); assertBucketContents(actual, expectedCount, expectedValue); } } public void testPredictNegativeKeysAtStart() { SearchResponse response = client() .prepareSearch("neg_idx") .setTypes("type") .addAggregation( histogram("histo") .field(INTERVAL_FIELD) .interval(1) .subAggregation(avg("avg").field(VALUE_FIELD)) .subAggregation( movingAvg("movavg_values", "avg").window(windowSize).modelBuilder(new SimpleModel.SimpleModelBuilder()) .gapPolicy(gapPolicy).predict(5))).execute().actionGet(); assertSearchResponse(response); Histogram histo = response.getAggregations().get("histo"); assertThat(histo, notNullValue()); assertThat(histo.getName(), equalTo("histo")); List<? extends Bucket> buckets = histo.getBuckets(); assertThat("Size of buckets array is not correct.", buckets.size(), equalTo(25)); SimpleValue current = buckets.get(0).getAggregations().get("movavg_values"); assertThat(current, nullValue()); for (int i = 1; i < 20; i++) { Bucket bucket = buckets.get(i); assertThat(bucket, notNullValue()); assertThat(bucket.getKey(), equalTo(i - 10d)); assertThat(bucket.getDocCount(), equalTo(1L)); Avg avgAgg = bucket.getAggregations().get("avg"); assertThat(avgAgg, notNullValue()); assertThat(avgAgg.value(), equalTo(10d)); SimpleValue movAvgAgg = bucket.getAggregations().get("movavg_values"); assertThat(movAvgAgg, notNullValue()); assertThat(movAvgAgg.value(), equalTo(10d)); } for (int i = 20; i < 25; i++) { Bucket bucket = buckets.get(i); assertThat(bucket, notNullValue()); assertThat(bucket.getKey(), equalTo(i - 10d)); assertThat(bucket.getDocCount(), equalTo(0L)); Avg avgAgg = bucket.getAggregations().get("avg"); assertThat(avgAgg, nullValue()); SimpleValue movAvgAgg = bucket.getAggregations().get("movavg_values"); assertThat(movAvgAgg, notNullValue()); assertThat(movAvgAgg.value(), equalTo(10d)); } } public void testSizeZeroWindow() { try { client() .prepareSearch("idx").setTypes("type") .addAggregation( histogram("histo").field(INTERVAL_FIELD).interval(interval) .extendedBounds(0L, (long) (interval * (numBuckets - 1))) .subAggregation(randomMetric("the_metric", VALUE_FIELD)) .subAggregation(movingAvg("movavg_counts", "the_metric") .window(0) .modelBuilder(new SimpleModel.SimpleModelBuilder()) .gapPolicy(gapPolicy)) ).execute().actionGet(); fail("MovingAvg should not accept a window that is zero"); } catch (IllegalArgumentException e) { assertThat(e.getMessage(), is("[window] must be a positive integer: [movavg_counts]")); } } public void testBadParent() { try { client() .prepareSearch("idx").setTypes("type") .addAggregation( range("histo").field(INTERVAL_FIELD).addRange(0, 10) .subAggregation(randomMetric("the_metric", VALUE_FIELD)) .subAggregation(movingAvg("movavg_counts", "the_metric") .window(windowSize) .modelBuilder(new SimpleModel.SimpleModelBuilder()) .gapPolicy(gapPolicy)) ).execute().actionGet(); fail("MovingAvg should not accept non-histogram as parent"); } catch (SearchPhaseExecutionException exception) { // All good } } public void testNegativeWindow() { try { client() .prepareSearch("idx").setTypes("type") .addAggregation( histogram("histo").field(INTERVAL_FIELD).interval(interval) .extendedBounds(0L, (long) (interval * (numBuckets - 1))) .subAggregation(randomMetric("the_metric", VALUE_FIELD)) .subAggregation(movingAvg("movavg_counts", "_count") .window(-10) .modelBuilder(new SimpleModel.SimpleModelBuilder()) .gapPolicy(gapPolicy)) ).execute().actionGet(); fail("MovingAvg should not accept a window that is negative"); } catch (IllegalArgumentException e) { assertThat(e.getMessage(), is("[window] must be a positive integer: [movavg_counts]")); } } public void testNoBucketsInHistogram() { SearchResponse response = client() .prepareSearch("idx").setTypes("type") .addAggregation( histogram("histo").field("test").interval(interval) .subAggregation(randomMetric("the_metric", VALUE_FIELD)) .subAggregation(movingAvg("movavg_counts", "the_metric") .window(windowSize) .modelBuilder(new SimpleModel.SimpleModelBuilder()) .gapPolicy(gapPolicy)) ).execute().actionGet(); assertSearchResponse(response); Histogram histo = response.getAggregations().get("histo"); assertThat(histo, notNullValue()); assertThat(histo.getName(), equalTo("histo")); List<? extends Bucket> buckets = histo.getBuckets(); assertThat(buckets.size(), equalTo(0)); } public void testNoBucketsInHistogramWithPredict() { int numPredictions = randomIntBetween(1,10); SearchResponse response = client() .prepareSearch("idx").setTypes("type") .addAggregation( histogram("histo").field("test").interval(interval) .subAggregation(randomMetric("the_metric", VALUE_FIELD)) .subAggregation(movingAvg("movavg_counts", "the_metric") .window(windowSize) .modelBuilder(new SimpleModel.SimpleModelBuilder()) .gapPolicy(gapPolicy) .predict(numPredictions)) ).execute().actionGet(); assertSearchResponse(response); Histogram histo = response.getAggregations().get("histo"); assertThat(histo, notNullValue()); assertThat(histo.getName(), equalTo("histo")); List<? extends Bucket> buckets = histo.getBuckets(); assertThat(buckets.size(), equalTo(0)); } public void testZeroPrediction() { try { client() .prepareSearch("idx").setTypes("type") .addAggregation( histogram("histo").field(INTERVAL_FIELD).interval(interval) .extendedBounds(0L, (long) (interval * (numBuckets - 1))) .subAggregation(randomMetric("the_metric", VALUE_FIELD)) .subAggregation(movingAvg("movavg_counts", "the_metric") .window(windowSize) .modelBuilder(randomModelBuilder()) .gapPolicy(gapPolicy) .predict(0)) ).execute().actionGet(); fail("MovingAvg should not accept a prediction size that is zero"); } catch (IllegalArgumentException exception) { // All Good } } public void testNegativePrediction() { try { client() .prepareSearch("idx").setTypes("type") .addAggregation( histogram("histo").field(INTERVAL_FIELD).interval(interval) .extendedBounds(0L, (long) (interval * (numBuckets - 1))) .subAggregation(randomMetric("the_metric", VALUE_FIELD)) .subAggregation(movingAvg("movavg_counts", "the_metric") .window(windowSize) .modelBuilder(randomModelBuilder()) .gapPolicy(gapPolicy) .predict(-10)) ).execute().actionGet(); fail("MovingAvg should not accept a prediction size that is negative"); } catch (IllegalArgumentException exception) { // All Good } } public void testHoltWintersNotEnoughData() { try { SearchResponse response = client() .prepareSearch("idx").setTypes("type") .addAggregation( histogram("histo").field(INTERVAL_FIELD).interval(interval) .extendedBounds(0L, (long) (interval * (numBuckets - 1))) .subAggregation(metric) .subAggregation(movingAvg("movavg_counts", "_count") .window(10) .modelBuilder(new HoltWintersModel.HoltWintersModelBuilder() .alpha(alpha).beta(beta).gamma(gamma).period(20).seasonalityType(seasonalityType)) .gapPolicy(gapPolicy)) .subAggregation(movingAvg("movavg_values", "the_metric") .window(windowSize) .modelBuilder(new HoltWintersModel.HoltWintersModelBuilder() .alpha(alpha).beta(beta).gamma(gamma).period(20).seasonalityType(seasonalityType)) .gapPolicy(gapPolicy)) ).execute().actionGet(); } catch (SearchPhaseExecutionException e) { // All good } } public void testTwoMovAvgsWithPredictions() { SearchResponse response = client() .prepareSearch("double_predict") .setTypes("type") .addAggregation( histogram("histo") .field(INTERVAL_FIELD) .interval(1) .subAggregation(avg("avg").field(VALUE_FIELD)) .subAggregation(derivative("deriv", "avg").gapPolicy(gapPolicy)) .subAggregation( movingAvg("avg_movavg", "avg").window(windowSize).modelBuilder(new SimpleModel.SimpleModelBuilder()) .gapPolicy(gapPolicy).predict(12)) .subAggregation( movingAvg("deriv_movavg", "deriv").window(windowSize).modelBuilder(new SimpleModel.SimpleModelBuilder()) .gapPolicy(gapPolicy).predict(12)) ).execute().actionGet(); assertSearchResponse(response); Histogram histo = response.getAggregations().get("histo"); assertThat(histo, notNullValue()); assertThat(histo.getName(), equalTo("histo")); List<? extends Bucket> buckets = histo.getBuckets(); assertThat("Size of buckets array is not correct.", buckets.size(), equalTo(24)); Bucket bucket = buckets.get(0); assertThat(bucket, notNullValue()); assertThat(bucket.getKey(), equalTo(0d)); assertThat(bucket.getDocCount(), equalTo(1L)); Avg avgAgg = bucket.getAggregations().get("avg"); assertThat(avgAgg, notNullValue()); assertThat(avgAgg.value(), equalTo(10d)); SimpleValue movAvgAgg = bucket.getAggregations().get("avg_movavg"); assertThat(movAvgAgg, nullValue()); Derivative deriv = bucket.getAggregations().get("deriv"); assertThat(deriv, nullValue()); SimpleValue derivMovAvg = bucket.getAggregations().get("deriv_movavg"); assertThat(derivMovAvg, nullValue()); // Second bucket bucket = buckets.get(1); assertThat(bucket, notNullValue()); assertThat(bucket.getKey(), equalTo(1d)); assertThat(bucket.getDocCount(), equalTo(1L)); avgAgg = bucket.getAggregations().get("avg"); assertThat(avgAgg, notNullValue()); assertThat(avgAgg.value(), equalTo(10d)); deriv = bucket.getAggregations().get("deriv"); assertThat(deriv, notNullValue()); assertThat(deriv.value(), equalTo(0d)); movAvgAgg = bucket.getAggregations().get("avg_movavg"); assertThat(movAvgAgg, notNullValue()); assertThat(movAvgAgg.value(), equalTo(10d)); derivMovAvg = bucket.getAggregations().get("deriv_movavg"); assertThat(derivMovAvg, Matchers.nullValue()); // still null because of movavg delay for (int i = 2; i < 12; i++) { bucket = buckets.get(i); assertThat(bucket, notNullValue()); assertThat(bucket.getKey(), equalTo((double) i)); assertThat(bucket.getDocCount(), equalTo(1L)); avgAgg = bucket.getAggregations().get("avg"); assertThat(avgAgg, notNullValue()); assertThat(avgAgg.value(), equalTo(10d)); deriv = bucket.getAggregations().get("deriv"); assertThat(deriv, notNullValue()); assertThat(deriv.value(), equalTo(0d)); movAvgAgg = bucket.getAggregations().get("avg_movavg"); assertThat(movAvgAgg, notNullValue()); assertThat(movAvgAgg.value(), equalTo(10d)); derivMovAvg = bucket.getAggregations().get("deriv_movavg"); assertThat(derivMovAvg, notNullValue()); assertThat(derivMovAvg.value(), equalTo(0d)); } // Predictions for (int i = 12; i < 24; i++) { bucket = buckets.get(i); assertThat(bucket, notNullValue()); assertThat(bucket.getKey(), equalTo((double) i)); assertThat(bucket.getDocCount(), equalTo(0L)); avgAgg = bucket.getAggregations().get("avg"); assertThat(avgAgg, nullValue()); deriv = bucket.getAggregations().get("deriv"); assertThat(deriv, nullValue()); movAvgAgg = bucket.getAggregations().get("avg_movavg"); assertThat(movAvgAgg, notNullValue()); assertThat(movAvgAgg.value(), equalTo(10d)); derivMovAvg = bucket.getAggregations().get("deriv_movavg"); assertThat(derivMovAvg, notNullValue()); assertThat(derivMovAvg.value(), equalTo(0d)); } } public void testBadModelParams() { try { SearchResponse response = client() .prepareSearch("idx").setTypes("type") .addAggregation( histogram("histo").field(INTERVAL_FIELD).interval(interval) .extendedBounds(0L, (long) (interval * (numBuckets - 1))) .subAggregation(metric) .subAggregation(movingAvg("movavg_counts", "_count") .window(10) .modelBuilder(randomModelBuilder(100)) .gapPolicy(gapPolicy)) ).execute().actionGet(); } catch (SearchPhaseExecutionException e) { // All good } } public void testHoltWintersMinimization() { SearchResponse response = client() .prepareSearch("idx").setTypes("type") .addAggregation( histogram("histo").field(INTERVAL_FIELD).interval(interval) .extendedBounds(0L, (long) (interval * (numBuckets - 1))) .subAggregation(metric) .subAggregation(movingAvg("movavg_counts", "_count") .window(windowSize) .modelBuilder(new HoltWintersModel.HoltWintersModelBuilder() .period(period).seasonalityType(seasonalityType)) .gapPolicy(gapPolicy) .minimize(true)) .subAggregation(movingAvg("movavg_values", "the_metric") .window(windowSize) .modelBuilder(new HoltWintersModel.HoltWintersModelBuilder() .period(period).seasonalityType(seasonalityType)) .gapPolicy(gapPolicy) .minimize(true)) ).execute().actionGet(); assertSearchResponse(response); Histogram histo = response.getAggregations().get("histo"); assertThat(histo, notNullValue()); assertThat(histo.getName(), equalTo("histo")); List<? extends Bucket> buckets = histo.getBuckets(); assertThat("Size of buckets array is not correct.", buckets.size(), equalTo(mockHisto.size())); List<Double> expectedCounts = testValues.get(MovAvgType.HOLT_WINTERS.name() + "_" + MetricTarget.COUNT.name()); List<Double> expectedValues = testValues.get(MovAvgType.HOLT_WINTERS.name() + "_" + MetricTarget.VALUE.name()); Iterator<? extends Histogram.Bucket> actualIter = buckets.iterator(); Iterator<PipelineAggregationHelperTests.MockBucket> expectedBucketIter = mockHisto.iterator(); Iterator<Double> expectedCountsIter = expectedCounts.iterator(); Iterator<Double> expectedValueIter = expectedValues.iterator(); // The minimizer is stochastic, so just make sure all the values coming back aren't null while (actualIter.hasNext()) { Histogram.Bucket actual = actualIter.next(); PipelineAggregationHelperTests.MockBucket expected = expectedBucketIter.next(); Double expectedCount = expectedCountsIter.next(); Double expectedValue = expectedValueIter.next(); assertThat("keys do not match", ((Number) actual.getKey()).longValue(), equalTo(expected.key)); assertThat("doc counts do not match", actual.getDocCount(), equalTo((long)expected.count)); SimpleValue countMovAvg = actual.getAggregations().get("movavg_counts"); SimpleValue valuesMovAvg = actual.getAggregations().get("movavg_values"); if (expectedCount == null) { //this bucket wasn't supposed to have a value (empty, skipped, etc), so //movavg should be null too assertThat(countMovAvg, nullValue()); } else { // Note that we don't compare against the mock values, since those are assuming // a non-minimized set of coefficients. Just check for not-nullness assertThat(countMovAvg, notNullValue()); } if (expectedValue == null) { //this bucket wasn't supposed to have a value (empty, skipped, etc), so //movavg should be null too assertThat(valuesMovAvg, nullValue()); } else { // Note that we don't compare against the mock values, since those are assuming // a non-minimized set of coefficients. Just check for not-nullness assertThat(valuesMovAvg, notNullValue()); } } } /** * If the minimizer is turned on, but there isn't enough data to minimize with, it will simply use * the default settings. Which means our mock histo will match the generated result (which it won't * if the minimizer is actually working, since the coefficients will be different and thus generate different * data) * * We can simulate this by setting the window size == size of histo */ public void testMinimizeNotEnoughData() { SearchResponse response = client() .prepareSearch("idx").setTypes("type") .addAggregation( histogram("histo").field(INTERVAL_FIELD).interval(interval) .extendedBounds(0L, (long) (interval * (numBuckets - 1))) .subAggregation(metric) .subAggregation(movingAvg("movavg_counts", "_count") .window(numBuckets) .modelBuilder(new HoltLinearModel.HoltLinearModelBuilder().alpha(alpha).beta(beta)) .gapPolicy(gapPolicy) .minimize(true)) .subAggregation(movingAvg("movavg_values", "the_metric") .window(numBuckets) .modelBuilder(new HoltLinearModel.HoltLinearModelBuilder().alpha(alpha).beta(beta)) .gapPolicy(gapPolicy) .minimize(true)) ).execute().actionGet(); assertSearchResponse(response); Histogram histo = response.getAggregations().get("histo"); assertThat(histo, notNullValue()); assertThat(histo.getName(), equalTo("histo")); List<? extends Bucket> buckets = histo.getBuckets(); assertThat("Size of buckets array is not correct.", buckets.size(), equalTo(mockHisto.size())); List<Double> expectedCounts = testValues.get(MovAvgType.HOLT_BIG_MINIMIZE.name() + "_" + MetricTarget.COUNT.name()); List<Double> expectedValues = testValues.get(MovAvgType.HOLT_BIG_MINIMIZE.name() + "_" + MetricTarget.VALUE.name()); Iterator<? extends Histogram.Bucket> actualIter = buckets.iterator(); Iterator<PipelineAggregationHelperTests.MockBucket> expectedBucketIter = mockHisto.iterator(); Iterator<Double> expectedCountsIter = expectedCounts.iterator(); Iterator<Double> expectedValuesIter = expectedValues.iterator(); while (actualIter.hasNext()) { assertValidIterators(expectedBucketIter, expectedCountsIter, expectedValuesIter); Histogram.Bucket actual = actualIter.next(); PipelineAggregationHelperTests.MockBucket expected = expectedBucketIter.next(); Double expectedCount = expectedCountsIter.next(); Double expectedValue = expectedValuesIter.next(); assertThat("keys do not match", ((Number) actual.getKey()).longValue(), equalTo(expected.key)); assertThat("doc counts do not match", actual.getDocCount(), equalTo((long)expected.count)); assertBucketContents(actual, expectedCount, expectedValue); } } /** * Only some models can be minimized, should throw exception for: simple, linear */ public void testCheckIfNonTunableCanBeMinimized() { try { client() .prepareSearch("idx").setTypes("type") .addAggregation( histogram("histo").field(INTERVAL_FIELD).interval(interval) .extendedBounds(0L, (long) (interval * (numBuckets - 1))) .subAggregation(metric) .subAggregation(movingAvg("movavg_counts", "_count") .window(numBuckets) .modelBuilder(new SimpleModel.SimpleModelBuilder()) .gapPolicy(gapPolicy) .minimize(true)) ).execute().actionGet(); fail("Simple Model cannot be minimized, but an exception was not thrown"); } catch (SearchPhaseExecutionException e) { // All good } try { client() .prepareSearch("idx").setTypes("type") .addAggregation( histogram("histo").field(INTERVAL_FIELD).interval(interval) .extendedBounds(0L, (long) (interval * (numBuckets - 1))) .subAggregation(metric) .subAggregation(movingAvg("movavg_counts", "_count") .window(numBuckets) .modelBuilder(new LinearModel.LinearModelBuilder()) .gapPolicy(gapPolicy) .minimize(true)) ).execute().actionGet(); fail("Linear Model cannot be minimized, but an exception was not thrown"); } catch (SearchPhaseExecutionException e) { // all good } } /** * These models are all minimizable, so they should not throw exceptions */ public void testCheckIfTunableCanBeMinimized() { MovAvgModelBuilder[] builders = new MovAvgModelBuilder[]{ new EwmaModel.EWMAModelBuilder(), new HoltLinearModel.HoltLinearModelBuilder(), new HoltWintersModel.HoltWintersModelBuilder() }; for (MovAvgModelBuilder builder : builders) { try { client() .prepareSearch("idx").setTypes("type") .addAggregation( histogram("histo").field(INTERVAL_FIELD).interval(interval) .extendedBounds(0L, (long) (interval * (numBuckets - 1))) .subAggregation(metric) .subAggregation(movingAvg("movavg_counts", "_count") .window(numBuckets) .modelBuilder(builder) .gapPolicy(gapPolicy) .minimize(true)) ).execute().actionGet(); } catch (SearchPhaseExecutionException e) { fail("Model [" + builder.toString() + "] can be minimized, but an exception was thrown"); } } } public void testPredictWithNonEmptyBuckets() throws Exception { createIndex("predict_non_empty"); BulkRequestBuilder bulkBuilder = client().prepareBulk().setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE); for (int i = 0; i < 10; i++) { bulkBuilder.add(client().prepareIndex("predict_non_empty", "type").setSource( jsonBuilder().startObject().field(INTERVAL_FIELD, i) .field(VALUE_FIELD, 10) .field(VALUE_FIELD2, 10) .endObject())); } for (int i = 10; i < 20; i++) { // Extra so there is a bucket that only has second field bulkBuilder.add(client().prepareIndex("predict_non_empty", "type").setSource( jsonBuilder().startObject().field(INTERVAL_FIELD, i).field(VALUE_FIELD2, 10).endObject())); } bulkBuilder.execute().actionGet(); ensureSearchable(); SearchResponse response = client() .prepareSearch("predict_non_empty") .setTypes("type") .addAggregation( histogram("histo") .field(INTERVAL_FIELD) .interval(1) .subAggregation(max("max").field(VALUE_FIELD)) .subAggregation(max("max2").field(VALUE_FIELD2)) .subAggregation( movingAvg("movavg_values", "max") .window(windowSize) .modelBuilder(new SimpleModel.SimpleModelBuilder()) .gapPolicy(BucketHelpers.GapPolicy.SKIP).predict(5))).execute().actionGet(); assertSearchResponse(response); Histogram histo = response.getAggregations().get("histo"); assertThat(histo, notNullValue()); assertThat(histo.getName(), equalTo("histo")); List<? extends Bucket> buckets = histo.getBuckets(); assertThat("Size of buckets array is not correct.", buckets.size(), equalTo(20)); SimpleValue current = buckets.get(0).getAggregations().get("movavg_values"); assertThat(current, nullValue()); for (int i = 1; i < 20; i++) { Bucket bucket = buckets.get(i); assertThat(bucket, notNullValue()); assertThat(bucket.getKey(), equalTo((double)i)); assertThat(bucket.getDocCount(), equalTo(1L)); SimpleValue movAvgAgg = bucket.getAggregations().get("movavg_values"); if (i < 15) { assertThat(movAvgAgg, notNullValue()); assertThat(movAvgAgg.value(), equalTo(10d)); } else { assertThat(movAvgAgg, nullValue()); } } } private void assertValidIterators(Iterator expectedBucketIter, Iterator expectedCountsIter, Iterator expectedValuesIter) { if (!expectedBucketIter.hasNext()) { fail("`expectedBucketIter` iterator ended before `actual` iterator, size mismatch"); } if (!expectedCountsIter.hasNext()) { fail("`expectedCountsIter` iterator ended before `actual` iterator, size mismatch"); } if (!expectedValuesIter.hasNext()) { fail("`expectedValuesIter` iterator ended before `actual` iterator, size mismatch"); } } private void assertBucketContents(Histogram.Bucket actual, Double expectedCount, Double expectedValue) { // This is a gap bucket SimpleValue countMovAvg = actual.getAggregations().get("movavg_counts"); if (expectedCount == null) { assertThat("[_count] movavg is not null", countMovAvg, nullValue()); } else if (Double.isNaN(expectedCount)) { assertThat("[_count] movavg should be NaN, but is ["+countMovAvg.value()+"] instead", countMovAvg.value(), equalTo(Double.NaN)); } else { assertThat("[_count] movavg is null", countMovAvg, notNullValue()); assertEquals("[_count] movavg does not match expected [" + countMovAvg.value() + " vs " + expectedCount + "]", countMovAvg.value(), expectedCount, 0.1 * Math.abs(countMovAvg.value())); } // This is a gap bucket SimpleValue valuesMovAvg = actual.getAggregations().get("movavg_values"); if (expectedValue == null) { assertThat("[value] movavg is not null", valuesMovAvg, Matchers.nullValue()); } else if (Double.isNaN(expectedValue)) { assertThat("[value] movavg should be NaN, but is ["+valuesMovAvg.value()+"] instead", valuesMovAvg.value(), equalTo(Double.NaN)); } else { assertThat("[value] movavg is null", valuesMovAvg, notNullValue()); assertEquals("[value] movavg does not match expected [" + valuesMovAvg.value() + " vs " + expectedValue + "]", valuesMovAvg.value(), expectedValue, 0.1 * Math.abs(valuesMovAvg.value())); } } private MovAvgModelBuilder randomModelBuilder() { return randomModelBuilder(0); } private MovAvgModelBuilder randomModelBuilder(double padding) { int rand = randomIntBetween(0,3); // HoltWinters is excluded from random generation, because it's "cold start" behavior makes // randomized testing too tricky. Should probably add dedicated, randomized tests just for HoltWinters, // which can compensate for the idiosyncrasies switch (rand) { case 0: return new SimpleModel.SimpleModelBuilder(); case 1: return new LinearModel.LinearModelBuilder(); case 2: return new EwmaModel.EWMAModelBuilder().alpha(alpha + padding); case 3: return new HoltLinearModel.HoltLinearModelBuilder().alpha(alpha + padding).beta(beta + padding); default: return new SimpleModel.SimpleModelBuilder(); } } private ValuesSourceAggregationBuilder<? extends ValuesSource, ? extends ValuesSourceAggregationBuilder<?, ?>> randomMetric(String name, String field) { int rand = randomIntBetween(0,3); switch (rand) { case 0: return min(name).field(field); case 2: return max(name).field(field); case 3: return avg(name).field(field); default: return avg(name).field(field); } } }
[CI] Mute MovAvgIT.testHoltWintersValuedField Relates to #35632
server/src/test/java/org/elasticsearch/search/aggregations/pipeline/moving/avg/MovAvgIT.java
[CI] Mute MovAvgIT.testHoltWintersValuedField
<ide><path>erver/src/test/java/org/elasticsearch/search/aggregations/pipeline/moving/avg/MovAvgIT.java <ide> } <ide> } <ide> <add> @AwaitsFix(bugUrl = "https://github.com/elastic/elasticsearch/issues/35632") <ide> public void testHoltWintersValuedField() { <ide> SearchResponse response = client() <ide> .prepareSearch("idx").setTypes("type")
Java
apache-2.0
e53db1a478b30783eb2d5a463bcfdd16b39ed947
0
ESamir/elasticsearch,SergVro/elasticsearch,tcucchietti/elasticsearch,xingguang2013/elasticsearch,btiernay/elasticsearch,overcome/elasticsearch,iantruslove/elasticsearch,jbertouch/elasticsearch,wittyameta/elasticsearch,jw0201/elastic,ESamir/elasticsearch,Clairebi/ElasticsearchClone,karthikjaps/elasticsearch,andrejserafim/elasticsearch,hafkensite/elasticsearch,alexkuk/elasticsearch,lightslife/elasticsearch,wbowling/elasticsearch,cnfire/elasticsearch-1,dantuffery/elasticsearch,rmuir/elasticsearch,queirozfcom/elasticsearch,kubum/elasticsearch,onegambler/elasticsearch,kevinkluge/elasticsearch,ImpressTV/elasticsearch,StefanGor/elasticsearch,strapdata/elassandra,jbertouch/elasticsearch,gfyoung/elasticsearch,a2lin/elasticsearch,gingerwizard/elasticsearch,mm0/elasticsearch,dylan8902/elasticsearch,Siddartha07/elasticsearch,VukDukic/elasticsearch,AndreKR/elasticsearch,HarishAtGitHub/elasticsearch,markllama/elasticsearch,tahaemin/elasticsearch,NBSW/elasticsearch,Clairebi/ElasticsearchClone,umeshdangat/elasticsearch,hechunwen/elasticsearch,nrkkalyan/elasticsearch,wayeast/elasticsearch,tahaemin/elasticsearch,Stacey-Gammon/elasticsearch,loconsolutions/elasticsearch,dongjoon-hyun/elasticsearch,ThalaivaStars/OrgRepo1,GlenRSmith/elasticsearch,markllama/elasticsearch,wayeast/elasticsearch,easonC/elasticsearch,ZTE-PaaS/elasticsearch,zhiqinghuang/elasticsearch,mmaracic/elasticsearch,NBSW/elasticsearch,ThalaivaStars/OrgRepo1,markharwood/elasticsearch,gingerwizard/elasticsearch,nezirus/elasticsearch,zhaocloud/elasticsearch,Widen/elasticsearch,ajhalani/elasticsearch,rlugojr/elasticsearch,slavau/elasticsearch,areek/elasticsearch,awislowski/elasticsearch,nomoa/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,zeroctu/elasticsearch,phani546/elasticsearch,nazarewk/elasticsearch,trangvh/elasticsearch,lydonchandra/elasticsearch,geidies/elasticsearch,weipinghe/elasticsearch,kalburgimanjunath/elasticsearch,lks21c/elasticsearch,pozhidaevak/elasticsearch,aglne/elasticsearch,lzo/elasticsearch-1,Widen/elasticsearch,a2lin/elasticsearch,sjohnr/elasticsearch,mgalushka/elasticsearch,slavau/elasticsearch,IanvsPoplicola/elasticsearch,s1monw/elasticsearch,mkis-/elasticsearch,Kakakakakku/elasticsearch,Fsero/elasticsearch,kalburgimanjunath/elasticsearch,EasonYi/elasticsearch,ImpressTV/elasticsearch,sc0ttkclark/elasticsearch,snikch/elasticsearch,ulkas/elasticsearch,pablocastro/elasticsearch,iacdingping/elasticsearch,markwalkom/elasticsearch,truemped/elasticsearch,wenpos/elasticsearch,iacdingping/elasticsearch,ckclark/elasticsearch,ThalaivaStars/OrgRepo1,chirilo/elasticsearch,Shekharrajak/elasticsearch,vietlq/elasticsearch,zhaocloud/elasticsearch,qwerty4030/elasticsearch,lydonchandra/elasticsearch,apepper/elasticsearch,alexkuk/elasticsearch,zkidkid/elasticsearch,winstonewert/elasticsearch,ulkas/elasticsearch,boliza/elasticsearch,kenshin233/elasticsearch,mm0/elasticsearch,tebriel/elasticsearch,janmejay/elasticsearch,ivansun1010/elasticsearch,JervyShi/elasticsearch,scottsom/elasticsearch,AleksKochev/elasticsearch,kcompher/elasticsearch,hydro2k/elasticsearch,khiraiwa/elasticsearch,pranavraman/elasticsearch,weipinghe/elasticsearch,abhijitiitr/es,liweinan0423/elasticsearch,hydro2k/elasticsearch,huanzhong/elasticsearch,a2lin/elasticsearch,tsohil/elasticsearch,tsohil/elasticsearch,Shepard1212/elasticsearch,awislowski/elasticsearch,markllama/elasticsearch,lydonchandra/elasticsearch,heng4fun/elasticsearch,knight1128/elasticsearch,vroyer/elassandra,likaiwalkman/elasticsearch,koxa29/elasticsearch,episerver/elasticsearch,boliza/elasticsearch,truemped/elasticsearch,luiseduardohdbackup/elasticsearch,nrkkalyan/elasticsearch,episerver/elasticsearch,HonzaKral/elasticsearch,JackyMai/elasticsearch,milodky/elasticsearch,dpursehouse/elasticsearch,luiseduardohdbackup/elasticsearch,C-Bish/elasticsearch,ydsakyclguozi/elasticsearch,Asimov4/elasticsearch,masaruh/elasticsearch,hechunwen/elasticsearch,yanjunh/elasticsearch,markharwood/elasticsearch,nilabhsagar/elasticsearch,libosu/elasticsearch,masterweb121/elasticsearch,alexbrasetvik/elasticsearch,overcome/elasticsearch,sarwarbhuiyan/elasticsearch,synhershko/elasticsearch,wbowling/elasticsearch,vingupta3/elasticsearch,lks21c/elasticsearch,fooljohnny/elasticsearch,hafkensite/elasticsearch,hirdesh2008/elasticsearch,Rygbee/elasticsearch,awislowski/elasticsearch,phani546/elasticsearch,apepper/elasticsearch,infusionsoft/elasticsearch,nellicus/elasticsearch,lks21c/elasticsearch,andrestc/elasticsearch,easonC/elasticsearch,queirozfcom/elasticsearch,abibell/elasticsearch,camilojd/elasticsearch,gingerwizard/elasticsearch,pablocastro/elasticsearch,aglne/elasticsearch,umeshdangat/elasticsearch,jpountz/elasticsearch,sjohnr/elasticsearch,abhijitiitr/es,KimTaehee/elasticsearch,petabytedata/elasticsearch,mute/elasticsearch,YosuaMichael/elasticsearch,artnowo/elasticsearch,YosuaMichael/elasticsearch,girirajsharma/elasticsearch,vrkansagara/elasticsearch,achow/elasticsearch,opendatasoft/elasticsearch,pranavraman/elasticsearch,rlugojr/elasticsearch,Charlesdong/elasticsearch,HonzaKral/elasticsearch,sauravmondallive/elasticsearch,amaliujia/elasticsearch,jimczi/elasticsearch,Chhunlong/elasticsearch,phani546/elasticsearch,obourgain/elasticsearch,Shepard1212/elasticsearch,fubuki/elasticsearch,MisterAndersen/elasticsearch,zhaocloud/elasticsearch,kevinkluge/elasticsearch,JackyMai/elasticsearch,heng4fun/elasticsearch,clintongormley/elasticsearch,myelin/elasticsearch,VukDukic/elasticsearch,sc0ttkclark/elasticsearch,Siddartha07/elasticsearch,jimhooker2002/elasticsearch,rento19962/elasticsearch,mohsinh/elasticsearch,s1monw/elasticsearch,bestwpw/elasticsearch,mmaracic/elasticsearch,diendt/elasticsearch,tcucchietti/elasticsearch,jchampion/elasticsearch,MichaelLiZhou/elasticsearch,himanshuag/elasticsearch,mnylen/elasticsearch,Shekharrajak/elasticsearch,cwurm/elasticsearch,nellicus/elasticsearch,hanst/elasticsearch,mm0/elasticsearch,LeoYao/elasticsearch,elasticdog/elasticsearch,zkidkid/elasticsearch,wangtuo/elasticsearch,codebunt/elasticsearch,peschlowp/elasticsearch,HonzaKral/elasticsearch,AleksKochev/elasticsearch,TonyChai24/ESSource,markwalkom/elasticsearch,amit-shar/elasticsearch,codebunt/elasticsearch,sauravmondallive/elasticsearch,palecur/elasticsearch,strapdata/elassandra5-rc,anti-social/elasticsearch,dylan8902/elasticsearch,alexshadow007/elasticsearch,petmit/elasticsearch,zeroctu/elasticsearch,dylan8902/elasticsearch,mikemccand/elasticsearch,opendatasoft/elasticsearch,kimchy/elasticsearch,salyh/elasticsearch,TonyChai24/ESSource,iamjakob/elasticsearch,humandb/elasticsearch,MichaelLiZhou/elasticsearch,yuy168/elasticsearch,JSCooke/elasticsearch,dantuffery/elasticsearch,phani546/elasticsearch,gingerwizard/elasticsearch,kenshin233/elasticsearch,diendt/elasticsearch,sdauletau/elasticsearch,njlawton/elasticsearch,spiegela/elasticsearch,masterweb121/elasticsearch,HonzaKral/elasticsearch,sc0ttkclark/elasticsearch,zeroctu/elasticsearch,sarwarbhuiyan/elasticsearch,bestwpw/elasticsearch,Chhunlong/elasticsearch,jango2015/elasticsearch,sarwarbhuiyan/elasticsearch,tkssharma/elasticsearch,onegambler/elasticsearch,Rygbee/elasticsearch,marcuswr/elasticsearch-dateline,nrkkalyan/elasticsearch,fforbeck/elasticsearch,aglne/elasticsearch,dpursehouse/elasticsearch,szroland/elasticsearch,caengcjd/elasticsearch,kubum/elasticsearch,ivansun1010/elasticsearch,AshishThakur/elasticsearch,MjAbuz/elasticsearch,caengcjd/elasticsearch,fooljohnny/elasticsearch,ydsakyclguozi/elasticsearch,18098924759/elasticsearch,diendt/elasticsearch,socialrank/elasticsearch,rmuir/elasticsearch,iacdingping/elasticsearch,hechunwen/elasticsearch,raishiv/elasticsearch,yongminxia/elasticsearch,weipinghe/elasticsearch,xuzha/elasticsearch,mohit/elasticsearch,huanzhong/elasticsearch,strapdata/elassandra,PhaedrusTheGreek/elasticsearch,knight1128/elasticsearch,sreeramjayan/elasticsearch,elancom/elasticsearch,JackyMai/elasticsearch,mjason3/elasticsearch,ImpressTV/elasticsearch,infusionsoft/elasticsearch,rhoml/elasticsearch,jeteve/elasticsearch,andrejserafim/elasticsearch,yynil/elasticsearch,Charlesdong/elasticsearch,javachengwc/elasticsearch,yongminxia/elasticsearch,gmarz/elasticsearch,janmejay/elasticsearch,jimhooker2002/elasticsearch,caengcjd/elasticsearch,rento19962/elasticsearch,zhaocloud/elasticsearch,MichaelLiZhou/elasticsearch,LeoYao/elasticsearch,Collaborne/elasticsearch,KimTaehee/elasticsearch,masaruh/elasticsearch,rajanm/elasticsearch,humandb/elasticsearch,iacdingping/elasticsearch,chirilo/elasticsearch,martinstuga/elasticsearch,gmarz/elasticsearch,Collaborne/elasticsearch,AndreKR/elasticsearch,HarishAtGitHub/elasticsearch,pablocastro/elasticsearch,MichaelLiZhou/elasticsearch,awislowski/elasticsearch,hirdesh2008/elasticsearch,iamjakob/elasticsearch,andrestc/elasticsearch,obourgain/elasticsearch,ydsakyclguozi/elasticsearch,jeteve/elasticsearch,sdauletau/elasticsearch,kalburgimanjunath/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,lightslife/elasticsearch,LeoYao/elasticsearch,hanswang/elasticsearch,jpountz/elasticsearch,rmuir/elasticsearch,davidvgalbraith/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,HarishAtGitHub/elasticsearch,clintongormley/elasticsearch,yynil/elasticsearch,ricardocerq/elasticsearch,strapdata/elassandra5-rc,ThalaivaStars/OrgRepo1,achow/elasticsearch,fforbeck/elasticsearch,sarwarbhuiyan/elasticsearch,sposam/elasticsearch,sscarduzio/elasticsearch,acchen97/elasticsearch,feiqitian/elasticsearch,nknize/elasticsearch,yuy168/elasticsearch,xpandan/elasticsearch,Collaborne/elasticsearch,hanswang/elasticsearch,Asimov4/elasticsearch,springning/elasticsearch,vroyer/elasticassandra,sdauletau/elasticsearch,sarwarbhuiyan/elasticsearch,thecocce/elasticsearch,mkis-/elasticsearch,kunallimaye/elasticsearch,Widen/elasticsearch,EasonYi/elasticsearch,pritishppai/elasticsearch,JervyShi/elasticsearch,mm0/elasticsearch,markharwood/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,mjhennig/elasticsearch,MetSystem/elasticsearch,HarishAtGitHub/elasticsearch,schonfeld/elasticsearch,Rygbee/elasticsearch,anti-social/elasticsearch,hanswang/elasticsearch,khiraiwa/elasticsearch,drewr/elasticsearch,abhijitiitr/es,Siddartha07/elasticsearch,martinstuga/elasticsearch,ThalaivaStars/OrgRepo1,avikurapati/elasticsearch,zeroctu/elasticsearch,snikch/elasticsearch,pablocastro/elasticsearch,skearns64/elasticsearch,gfyoung/elasticsearch,vietlq/elasticsearch,uboness/elasticsearch,Microsoft/elasticsearch,xuzha/elasticsearch,Clairebi/ElasticsearchClone,yongminxia/elasticsearch,dataduke/elasticsearch,NBSW/elasticsearch,jsgao0/elasticsearch,kalimatas/elasticsearch,strapdata/elassandra-test,Microsoft/elasticsearch,janmejay/elasticsearch,likaiwalkman/elasticsearch,nazarewk/elasticsearch,vinsonlou/elasticsearch,masterweb121/elasticsearch,wbowling/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,Flipkart/elasticsearch,LewayneNaidoo/elasticsearch,hanswang/elasticsearch,combinatorist/elasticsearch,jango2015/elasticsearch,feiqitian/elasticsearch,smflorentino/elasticsearch,gingerwizard/elasticsearch,ouyangkongtong/elasticsearch,lchennup/elasticsearch,linglaiyao1314/elasticsearch,thecocce/elasticsearch,Asimov4/elasticsearch,andrestc/elasticsearch,MaineC/elasticsearch,strapdata/elassandra-test,andrewvc/elasticsearch,geidies/elasticsearch,wittyameta/elasticsearch,fernandozhu/elasticsearch,alexbrasetvik/elasticsearch,franklanganke/elasticsearch,lightslife/elasticsearch,rento19962/elasticsearch,kimchy/elasticsearch,hafkensite/elasticsearch,camilojd/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,humandb/elasticsearch,amaliujia/elasticsearch,abibell/elasticsearch,kimimj/elasticsearch,wenpos/elasticsearch,palecur/elasticsearch,jpountz/elasticsearch,djschny/elasticsearch,franklanganke/elasticsearch,hafkensite/elasticsearch,karthikjaps/elasticsearch,loconsolutions/elasticsearch,anti-social/elasticsearch,F0lha/elasticsearch,sauravmondallive/elasticsearch,rlugojr/elasticsearch,VukDukic/elasticsearch,smflorentino/elasticsearch,ckclark/elasticsearch,petabytedata/elasticsearch,SergVro/elasticsearch,girirajsharma/elasticsearch,rmuir/elasticsearch,libosu/elasticsearch,ESamir/elasticsearch,weipinghe/elasticsearch,Flipkart/elasticsearch,jaynblue/elasticsearch,polyfractal/elasticsearch,pranavraman/elasticsearch,mohsinh/elasticsearch,aglne/elasticsearch,golubev/elasticsearch,drewr/elasticsearch,geidies/elasticsearch,MisterAndersen/elasticsearch,mute/elasticsearch,KimTaehee/elasticsearch,sjohnr/elasticsearch,abibell/elasticsearch,skearns64/elasticsearch,hydro2k/elasticsearch,opendatasoft/elasticsearch,huypx1292/elasticsearch,dantuffery/elasticsearch,smflorentino/elasticsearch,dataduke/elasticsearch,springning/elasticsearch,wimvds/elasticsearch,kenshin233/elasticsearch,wangtuo/elasticsearch,salyh/elasticsearch,himanshuag/elasticsearch,himanshuag/elasticsearch,kingaj/elasticsearch,fekaputra/elasticsearch,kevinkluge/elasticsearch,koxa29/elasticsearch,kkirsche/elasticsearch,jaynblue/elasticsearch,masaruh/elasticsearch,huanzhong/elasticsearch,bestwpw/elasticsearch,LewayneNaidoo/elasticsearch,Stacey-Gammon/elasticsearch,sneivandt/elasticsearch,episerver/elasticsearch,StefanGor/elasticsearch,smflorentino/elasticsearch,khiraiwa/elasticsearch,iacdingping/elasticsearch,caengcjd/elasticsearch,nilabhsagar/elasticsearch,queirozfcom/elasticsearch,acchen97/elasticsearch,himanshuag/elasticsearch,s1monw/elasticsearch,sposam/elasticsearch,PhaedrusTheGreek/elasticsearch,hafkensite/elasticsearch,koxa29/elasticsearch,likaiwalkman/elasticsearch,mortonsykes/elasticsearch,Shekharrajak/elasticsearch,fekaputra/elasticsearch,Kakakakakku/elasticsearch,linglaiyao1314/elasticsearch,himanshuag/elasticsearch,nknize/elasticsearch,masaruh/elasticsearch,camilojd/elasticsearch,infusionsoft/elasticsearch,franklanganke/elasticsearch,chrismwendt/elasticsearch,jaynblue/elasticsearch,truemped/elasticsearch,kalimatas/elasticsearch,henakamaMSFT/elasticsearch,Charlesdong/elasticsearch,yongminxia/elasticsearch,chirilo/elasticsearch,jprante/elasticsearch,artnowo/elasticsearch,tebriel/elasticsearch,nomoa/elasticsearch,lightslife/elasticsearch,henakamaMSFT/elasticsearch,rento19962/elasticsearch,uboness/elasticsearch,ThiagoGarciaAlves/elasticsearch,uschindler/elasticsearch,golubev/elasticsearch,jw0201/elastic,yongminxia/elasticsearch,phani546/elasticsearch,tahaemin/elasticsearch,fekaputra/elasticsearch,Shepard1212/elasticsearch,njlawton/elasticsearch,LeoYao/elasticsearch,iamjakob/elasticsearch,xingguang2013/elasticsearch,brwe/elasticsearch,fubuki/elasticsearch,truemped/elasticsearch,skearns64/elasticsearch,beiske/elasticsearch,sauravmondallive/elasticsearch,wuranbo/elasticsearch,dantuffery/elasticsearch,Fsero/elasticsearch,robin13/elasticsearch,rento19962/elasticsearch,scottsom/elasticsearch,kenshin233/elasticsearch,mnylen/elasticsearch,rajanm/elasticsearch,ThiagoGarciaAlves/elasticsearch,LeoYao/elasticsearch,petabytedata/elasticsearch,dongjoon-hyun/elasticsearch,boliza/elasticsearch,glefloch/elasticsearch,ulkas/elasticsearch,Shepard1212/elasticsearch,ckclark/elasticsearch,martinstuga/elasticsearch,btiernay/elasticsearch,Ansh90/elasticsearch,camilojd/elasticsearch,JSCooke/elasticsearch,vietlq/elasticsearch,fred84/elasticsearch,ricardocerq/elasticsearch,linglaiyao1314/elasticsearch,beiske/elasticsearch,raishiv/elasticsearch,ImpressTV/elasticsearch,pozhidaevak/elasticsearch,tsohil/elasticsearch,MetSystem/elasticsearch,TonyChai24/ESSource,gmarz/elasticsearch,yanjunh/elasticsearch,heng4fun/elasticsearch,SergVro/elasticsearch,easonC/elasticsearch,koxa29/elasticsearch,areek/elasticsearch,kkirsche/elasticsearch,ajhalani/elasticsearch,slavau/elasticsearch,i-am-Nathan/elasticsearch,dylan8902/elasticsearch,humandb/elasticsearch,jimhooker2002/elasticsearch,Clairebi/ElasticsearchClone,bestwpw/elasticsearch,trangvh/elasticsearch,tahaemin/elasticsearch,mmaracic/elasticsearch,sreeramjayan/elasticsearch,mortonsykes/elasticsearch,aparo/elasticsearch,slavau/elasticsearch,Widen/elasticsearch,jw0201/elastic,markharwood/elasticsearch,robin13/elasticsearch,zhiqinghuang/elasticsearch,alexbrasetvik/elasticsearch,wuranbo/elasticsearch,queirozfcom/elasticsearch,nazarewk/elasticsearch,Charlesdong/elasticsearch,sposam/elasticsearch,fooljohnny/elasticsearch,andrestc/elasticsearch,rhoml/elasticsearch,Shepard1212/elasticsearch,fooljohnny/elasticsearch,btiernay/elasticsearch,kunallimaye/elasticsearch,ZTE-PaaS/elasticsearch,glefloch/elasticsearch,luiseduardohdbackup/elasticsearch,xpandan/elasticsearch,vietlq/elasticsearch,ouyangkongtong/elasticsearch,socialrank/elasticsearch,mapr/elasticsearch,andrestc/elasticsearch,hechunwen/elasticsearch,sauravmondallive/elasticsearch,kaneshin/elasticsearch,heng4fun/elasticsearch,ouyangkongtong/elasticsearch,sdauletau/elasticsearch,salyh/elasticsearch,sjohnr/elasticsearch,dylan8902/elasticsearch,mcku/elasticsearch,artnowo/elasticsearch,mm0/elasticsearch,iantruslove/elasticsearch,truemped/elasticsearch,F0lha/elasticsearch,aparo/elasticsearch,MetSystem/elasticsearch,hirdesh2008/elasticsearch,kingaj/elasticsearch,gingerwizard/elasticsearch,ESamir/elasticsearch,camilojd/elasticsearch,18098924759/elasticsearch,vvcephei/elasticsearch,Ansh90/elasticsearch,kalburgimanjunath/elasticsearch,EasonYi/elasticsearch,fernandozhu/elasticsearch,kalimatas/elasticsearch,ouyangkongtong/elasticsearch,jeteve/elasticsearch,petmit/elasticsearch,davidvgalbraith/elasticsearch,jaynblue/elasticsearch,kenshin233/elasticsearch,alexshadow007/elasticsearch,Ansh90/elasticsearch,girirajsharma/elasticsearch,Collaborne/elasticsearch,ZTE-PaaS/elasticsearch,zeroctu/elasticsearch,brandonkearby/elasticsearch,wenpos/elasticsearch,strapdata/elassandra-test,AshishThakur/elasticsearch,robin13/elasticsearch,huanzhong/elasticsearch,achow/elasticsearch,combinatorist/elasticsearch,kalimatas/elasticsearch,micpalmia/elasticsearch,PhaedrusTheGreek/elasticsearch,dongaihua/highlight-elasticsearch,petmit/elasticsearch,sposam/elasticsearch,YosuaMichael/elasticsearch,kingaj/elasticsearch,mgalushka/elasticsearch,wuranbo/elasticsearch,fubuki/elasticsearch,Collaborne/elasticsearch,kimimj/elasticsearch,apepper/elasticsearch,vingupta3/elasticsearch,wuranbo/elasticsearch,Charlesdong/elasticsearch,clintongormley/elasticsearch,dongjoon-hyun/elasticsearch,Shekharrajak/elasticsearch,adrianbk/elasticsearch,LeoYao/elasticsearch,F0lha/elasticsearch,micpalmia/elasticsearch,uschindler/elasticsearch,Microsoft/elasticsearch,ajhalani/elasticsearch,nilabhsagar/elasticsearch,scorpionvicky/elasticsearch,mnylen/elasticsearch,mikemccand/elasticsearch,mcku/elasticsearch,beiske/elasticsearch,MaineC/elasticsearch,robin13/elasticsearch,brandonkearby/elasticsearch,ESamir/elasticsearch,dpursehouse/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,spiegela/elasticsearch,queirozfcom/elasticsearch,socialrank/elasticsearch,loconsolutions/elasticsearch,strapdata/elassandra-test,kimimj/elasticsearch,vrkansagara/elasticsearch,raishiv/elasticsearch,yanjunh/elasticsearch,naveenhooda2000/elasticsearch,fekaputra/elasticsearch,huypx1292/elasticsearch,likaiwalkman/elasticsearch,janmejay/elasticsearch,elasticdog/elasticsearch,peschlowp/elasticsearch,NBSW/elasticsearch,episerver/elasticsearch,iamjakob/elasticsearch,hechunwen/elasticsearch,hanst/elasticsearch,tkssharma/elasticsearch,janmejay/elasticsearch,phani546/elasticsearch,wuranbo/elasticsearch,tebriel/elasticsearch,tahaemin/elasticsearch,StefanGor/elasticsearch,weipinghe/elasticsearch,vorce/es-metrics,dataduke/elasticsearch,feiqitian/elasticsearch,mmaracic/elasticsearch,henakamaMSFT/elasticsearch,JervyShi/elasticsearch,Helen-Zhao/elasticsearch,likaiwalkman/elasticsearch,cnfire/elasticsearch-1,lydonchandra/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,btiernay/elasticsearch,AshishThakur/elasticsearch,Uiho/elasticsearch,ulkas/elasticsearch,jeteve/elasticsearch,lmenezes/elasticsearch,tahaemin/elasticsearch,Ansh90/elasticsearch,elasticdog/elasticsearch,onegambler/elasticsearch,achow/elasticsearch,hanswang/elasticsearch,xingguang2013/elasticsearch,dataduke/elasticsearch,jbertouch/elasticsearch,Charlesdong/elasticsearch,pablocastro/elasticsearch,xuzha/elasticsearch,mapr/elasticsearch,TonyChai24/ESSource,djschny/elasticsearch,mapr/elasticsearch,kevinkluge/elasticsearch,onegambler/elasticsearch,JackyMai/elasticsearch,lks21c/elasticsearch,mkis-/elasticsearch,Helen-Zhao/elasticsearch,Microsoft/elasticsearch,Asimov4/elasticsearch,overcome/elasticsearch,zkidkid/elasticsearch,ZTE-PaaS/elasticsearch,Uiho/elasticsearch,karthikjaps/elasticsearch,springning/elasticsearch,lks21c/elasticsearch,caengcjd/elasticsearch,sreeramjayan/elasticsearch,caengcjd/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,aparo/elasticsearch,areek/elasticsearch,mbrukman/elasticsearch,xpandan/elasticsearch,rajanm/elasticsearch,strapdata/elassandra,petabytedata/elasticsearch,markwalkom/elasticsearch,fred84/elasticsearch,petabytedata/elasticsearch,AleksKochev/elasticsearch,acchen97/elasticsearch,sdauletau/elasticsearch,dongjoon-hyun/elasticsearch,adrianbk/elasticsearch,vvcephei/elasticsearch,bawse/elasticsearch,Brijeshrpatel9/elasticsearch,jsgao0/elasticsearch,Siddartha07/elasticsearch,strapdata/elassandra5-rc,springning/elasticsearch,MetSystem/elasticsearch,PhaedrusTheGreek/elasticsearch,jprante/elasticsearch,mrorii/elasticsearch,pranavraman/elasticsearch,pranavraman/elasticsearch,himanshuag/elasticsearch,amit-shar/elasticsearch,vorce/es-metrics,nezirus/elasticsearch,jango2015/elasticsearch,vrkansagara/elasticsearch,alexksikes/elasticsearch,GlenRSmith/elasticsearch,huanzhong/elasticsearch,GlenRSmith/elasticsearch,shreejay/elasticsearch,golubev/elasticsearch,ouyangkongtong/elasticsearch,girirajsharma/elasticsearch,wittyameta/elasticsearch,szroland/elasticsearch,wayeast/elasticsearch,iamjakob/elasticsearch,szroland/elasticsearch,JervyShi/elasticsearch,anti-social/elasticsearch,jango2015/elasticsearch,EasonYi/elasticsearch,Liziyao/elasticsearch,drewr/elasticsearch,diendt/elasticsearch,rhoml/elasticsearch,mrorii/elasticsearch,mnylen/elasticsearch,jw0201/elastic,opendatasoft/elasticsearch,trangvh/elasticsearch,micpalmia/elasticsearch,ajhalani/elasticsearch,dpursehouse/elasticsearch,iacdingping/elasticsearch,rajanm/elasticsearch,pablocastro/elasticsearch,vingupta3/elasticsearch,rlugojr/elasticsearch,strapdata/elassandra,qwerty4030/elasticsearch,jchampion/elasticsearch,iacdingping/elasticsearch,franklanganke/elasticsearch,jprante/elasticsearch,Fsero/elasticsearch,henakamaMSFT/elasticsearch,socialrank/elasticsearch,petabytedata/elasticsearch,Flipkart/elasticsearch,kubum/elasticsearch,ThalaivaStars/OrgRepo1,szroland/elasticsearch,mjhennig/elasticsearch,kkirsche/elasticsearch,lmtwga/elasticsearch,mortonsykes/elasticsearch,mgalushka/elasticsearch,sscarduzio/elasticsearch,djschny/elasticsearch,LewayneNaidoo/elasticsearch,mbrukman/elasticsearch,IanvsPoplicola/elasticsearch,18098924759/elasticsearch,wayeast/elasticsearch,zhiqinghuang/elasticsearch,polyfractal/elasticsearch,zhaocloud/elasticsearch,Fsero/elasticsearch,onegambler/elasticsearch,diendt/elasticsearch,springning/elasticsearch,markllama/elasticsearch,wangyuxue/elasticsearch,nellicus/elasticsearch,maddin2016/elasticsearch,scorpionvicky/elasticsearch,qwerty4030/elasticsearch,jimczi/elasticsearch,Uiho/elasticsearch,loconsolutions/elasticsearch,lightslife/elasticsearch,lmtwga/elasticsearch,hanst/elasticsearch,kevinkluge/elasticsearch,yanjunh/elasticsearch,lzo/elasticsearch-1,lzo/elasticsearch-1,mbrukman/elasticsearch,scottsom/elasticsearch,combinatorist/elasticsearch,wimvds/elasticsearch,naveenhooda2000/elasticsearch,jsgao0/elasticsearch,hanst/elasticsearch,beiske/elasticsearch,robin13/elasticsearch,kkirsche/elasticsearch,Liziyao/elasticsearch,MjAbuz/elasticsearch,hafkensite/elasticsearch,knight1128/elasticsearch,alexshadow007/elasticsearch,vvcephei/elasticsearch,andrestc/elasticsearch,brwe/elasticsearch,drewr/elasticsearch,winstonewert/elasticsearch,feiqitian/elasticsearch,Microsoft/elasticsearch,Flipkart/elasticsearch,VukDukic/elasticsearch,mjason3/elasticsearch,golubev/elasticsearch,wbowling/elasticsearch,jw0201/elastic,djschny/elasticsearch,overcome/elasticsearch,LewayneNaidoo/elasticsearch,huypx1292/elasticsearch,apepper/elasticsearch,brwe/elasticsearch,jw0201/elastic,alexshadow007/elasticsearch,Helen-Zhao/elasticsearch,elancom/elasticsearch,jimhooker2002/elasticsearch,andrewvc/elasticsearch,rento19962/elasticsearch,nellicus/elasticsearch,beiske/elasticsearch,mjhennig/elasticsearch,i-am-Nathan/elasticsearch,mortonsykes/elasticsearch,coding0011/elasticsearch,sauravmondallive/elasticsearch,SergVro/elasticsearch,mohit/elasticsearch,lydonchandra/elasticsearch,areek/elasticsearch,aglne/elasticsearch,F0lha/elasticsearch,apepper/elasticsearch,F0lha/elasticsearch,bawse/elasticsearch,alexksikes/elasticsearch,Widen/elasticsearch,tcucchietti/elasticsearch,dataduke/elasticsearch,davidvgalbraith/elasticsearch,yanjunh/elasticsearch,sscarduzio/elasticsearch,Fsero/elasticsearch,kenshin233/elasticsearch,njlawton/elasticsearch,lydonchandra/elasticsearch,jeteve/elasticsearch,18098924759/elasticsearch,strapdata/elassandra-test,MjAbuz/elasticsearch,obourgain/elasticsearch,tcucchietti/elasticsearch,dylan8902/elasticsearch,GlenRSmith/elasticsearch,infusionsoft/elasticsearch,lchennup/elasticsearch,kunallimaye/elasticsearch,mohit/elasticsearch,kevinkluge/elasticsearch,glefloch/elasticsearch,codebunt/elasticsearch,apepper/elasticsearch,TonyChai24/ESSource,sneivandt/elasticsearch,StefanGor/elasticsearch,easonC/elasticsearch,jsgao0/elasticsearch,nilabhsagar/elasticsearch,vingupta3/elasticsearch,scorpionvicky/elasticsearch,likaiwalkman/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,MjAbuz/elasticsearch,synhershko/elasticsearch,peschlowp/elasticsearch,springning/elasticsearch,petmit/elasticsearch,amaliujia/elasticsearch,MetSystem/elasticsearch,adrianbk/elasticsearch,i-am-Nathan/elasticsearch,zeroctu/elasticsearch,smflorentino/elasticsearch,palecur/elasticsearch,khiraiwa/elasticsearch,snikch/elasticsearch,nilabhsagar/elasticsearch,tahaemin/elasticsearch,yuy168/elasticsearch,fubuki/elasticsearch,vrkansagara/elasticsearch,AndreKR/elasticsearch,liweinan0423/elasticsearch,elasticdog/elasticsearch,PhaedrusTheGreek/elasticsearch,skearns64/elasticsearch,knight1128/elasticsearch,brandonkearby/elasticsearch,Helen-Zhao/elasticsearch,a2lin/elasticsearch,wimvds/elasticsearch,myelin/elasticsearch,TonyChai24/ESSource,Fsero/elasticsearch,aparo/elasticsearch,andrejserafim/elasticsearch,cnfire/elasticsearch-1,alexshadow007/elasticsearch,libosu/elasticsearch,AndreKR/elasticsearch,coding0011/elasticsearch,zhaocloud/elasticsearch,myelin/elasticsearch,mute/elasticsearch,alexkuk/elasticsearch,geidies/elasticsearch,kalburgimanjunath/elasticsearch,camilojd/elasticsearch,amit-shar/elasticsearch,likaiwalkman/elasticsearch,diendt/elasticsearch,slavau/elasticsearch,wittyameta/elasticsearch,wimvds/elasticsearch,YosuaMichael/elasticsearch,schonfeld/elasticsearch,myelin/elasticsearch,rhoml/elasticsearch,masaruh/elasticsearch,jbertouch/elasticsearch,Fsero/elasticsearch,zhiqinghuang/elasticsearch,markllama/elasticsearch,linglaiyao1314/elasticsearch,F0lha/elasticsearch,salyh/elasticsearch,YosuaMichael/elasticsearch,hirdesh2008/elasticsearch,jchampion/elasticsearch,javachengwc/elasticsearch,lchennup/elasticsearch,easonC/elasticsearch,iantruslove/elasticsearch,markwalkom/elasticsearch,mgalushka/elasticsearch,kcompher/elasticsearch,kaneshin/elasticsearch,mikemccand/elasticsearch,Rygbee/elasticsearch,kcompher/elasticsearch,pritishppai/elasticsearch,petabytedata/elasticsearch,humandb/elasticsearch,maddin2016/elasticsearch,mcku/elasticsearch,vinsonlou/elasticsearch,elancom/elasticsearch,mrorii/elasticsearch,sneivandt/elasticsearch,adrianbk/elasticsearch,glefloch/elasticsearch,mgalushka/elasticsearch,davidvgalbraith/elasticsearch,Shekharrajak/elasticsearch,vorce/es-metrics,mjhennig/elasticsearch,andrejserafim/elasticsearch,andrewvc/elasticsearch,awislowski/elasticsearch,truemped/elasticsearch,lmtwga/elasticsearch,umeshdangat/elasticsearch,xuzha/elasticsearch,vorce/es-metrics,EasonYi/elasticsearch,markwalkom/elasticsearch,GlenRSmith/elasticsearch,scottsom/elasticsearch,wimvds/elasticsearch,polyfractal/elasticsearch,Siddartha07/elasticsearch,Rygbee/elasticsearch,petmit/elasticsearch,jsgao0/elasticsearch,sscarduzio/elasticsearch,karthikjaps/elasticsearch,lmtwga/elasticsearch,hydro2k/elasticsearch,cwurm/elasticsearch,Stacey-Gammon/elasticsearch,IanvsPoplicola/elasticsearch,jprante/elasticsearch,btiernay/elasticsearch,knight1128/elasticsearch,libosu/elasticsearch,vroyer/elasticassandra,lchennup/elasticsearch,karthikjaps/elasticsearch,hydro2k/elasticsearch,AshishThakur/elasticsearch,codebunt/elasticsearch,zkidkid/elasticsearch,ricardocerq/elasticsearch,sneivandt/elasticsearch,markllama/elasticsearch,NBSW/elasticsearch,EasonYi/elasticsearch,coding0011/elasticsearch,mbrukman/elasticsearch,Clairebi/ElasticsearchClone,18098924759/elasticsearch,wbowling/elasticsearch,achow/elasticsearch,Shekharrajak/elasticsearch,milodky/elasticsearch,Ansh90/elasticsearch,brwe/elasticsearch,yuy168/elasticsearch,Uiho/elasticsearch,iantruslove/elasticsearch,kingaj/elasticsearch,opendatasoft/elasticsearch,wenpos/elasticsearch,jimczi/elasticsearch,lightslife/elasticsearch,dylan8902/elasticsearch,szroland/elasticsearch,mrorii/elasticsearch,naveenhooda2000/elasticsearch,Clairebi/ElasticsearchClone,kunallimaye/elasticsearch,girirajsharma/elasticsearch,Uiho/elasticsearch,janmejay/elasticsearch,sjohnr/elasticsearch,chrismwendt/elasticsearch,xingguang2013/elasticsearch,alexkuk/elasticsearch,hanswang/elasticsearch,fekaputra/elasticsearch,sneivandt/elasticsearch,18098924759/elasticsearch,xpandan/elasticsearch,MisterAndersen/elasticsearch,JervyShi/elasticsearch,milodky/elasticsearch,acchen97/elasticsearch,pritishppai/elasticsearch,bestwpw/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,jpountz/elasticsearch,loconsolutions/elasticsearch,gmarz/elasticsearch,milodky/elasticsearch,tsohil/elasticsearch,nrkkalyan/elasticsearch,gfyoung/elasticsearch,wayeast/elasticsearch,strapdata/elassandra-test,nezirus/elasticsearch,achow/elasticsearch,huanzhong/elasticsearch,ricardocerq/elasticsearch,mohit/elasticsearch,s1monw/elasticsearch,mkis-/elasticsearch,shreejay/elasticsearch,ckclark/elasticsearch,easonC/elasticsearch,artnowo/elasticsearch,JSCooke/elasticsearch,yongminxia/elasticsearch,cwurm/elasticsearch,yynil/elasticsearch,bestwpw/elasticsearch,jchampion/elasticsearch,Ansh90/elasticsearch,lzo/elasticsearch-1,loconsolutions/elasticsearch,strapdata/elassandra5-rc,ThiagoGarciaAlves/elasticsearch,Helen-Zhao/elasticsearch,HarishAtGitHub/elasticsearch,beiske/elasticsearch,mnylen/elasticsearch,kaneshin/elasticsearch,mortonsykes/elasticsearch,AndreKR/elasticsearch,nazarewk/elasticsearch,KimTaehee/elasticsearch,kcompher/elasticsearch,mjason3/elasticsearch,hafkensite/elasticsearch,amit-shar/elasticsearch,wangtuo/elasticsearch,JackyMai/elasticsearch,yuy168/elasticsearch,linglaiyao1314/elasticsearch,kingaj/elasticsearch,Kakakakakku/elasticsearch,dataduke/elasticsearch,martinstuga/elasticsearch,trangvh/elasticsearch,jchampion/elasticsearch,wayeast/elasticsearch,hirdesh2008/elasticsearch,Chhunlong/elasticsearch,wimvds/elasticsearch,aparo/elasticsearch,yuy168/elasticsearch,ajhalani/elasticsearch,ydsakyclguozi/elasticsearch,vvcephei/elasticsearch,lchennup/elasticsearch,jimhooker2002/elasticsearch,onegambler/elasticsearch,amaliujia/elasticsearch,smflorentino/elasticsearch,huanzhong/elasticsearch,sc0ttkclark/elasticsearch,ivansun1010/elasticsearch,masterweb121/elasticsearch,clintongormley/elasticsearch,boliza/elasticsearch,peschlowp/elasticsearch,nezirus/elasticsearch,s1monw/elasticsearch,naveenhooda2000/elasticsearch,anti-social/elasticsearch,shreejay/elasticsearch,peschlowp/elasticsearch,abibell/elasticsearch,polyfractal/elasticsearch,jimczi/elasticsearch,lzo/elasticsearch-1,sc0ttkclark/elasticsearch,micpalmia/elasticsearch,codebunt/elasticsearch,himanshuag/elasticsearch,huypx1292/elasticsearch,ThiagoGarciaAlves/elasticsearch,ImpressTV/elasticsearch,tebriel/elasticsearch,Collaborne/elasticsearch,obourgain/elasticsearch,lzo/elasticsearch-1,SergVro/elasticsearch,fubuki/elasticsearch,golubev/elasticsearch,kimimj/elasticsearch,gmarz/elasticsearch,dataduke/elasticsearch,xingguang2013/elasticsearch,strapdata/elassandra5-rc,pranavraman/elasticsearch,MetSystem/elasticsearch,mcku/elasticsearch,fooljohnny/elasticsearch,MaineC/elasticsearch,schonfeld/elasticsearch,elasticdog/elasticsearch,avikurapati/elasticsearch,Liziyao/elasticsearch,Uiho/elasticsearch,vingupta3/elasticsearch,franklanganke/elasticsearch,nknize/elasticsearch,sreeramjayan/elasticsearch,hanswang/elasticsearch,feiqitian/elasticsearch,maddin2016/elasticsearch,tkssharma/elasticsearch,ydsakyclguozi/elasticsearch,lightslife/elasticsearch,iantruslove/elasticsearch,ulkas/elasticsearch,rhoml/elasticsearch,mbrukman/elasticsearch,beiske/elasticsearch,fforbeck/elasticsearch,lzo/elasticsearch-1,yynil/elasticsearch,vietlq/elasticsearch,cnfire/elasticsearch-1,masterweb121/elasticsearch,sscarduzio/elasticsearch,a2lin/elasticsearch,nknize/elasticsearch,AleksKochev/elasticsearch,PhaedrusTheGreek/elasticsearch,wimvds/elasticsearch,martinstuga/elasticsearch,hirdesh2008/elasticsearch,Liziyao/elasticsearch,amit-shar/elasticsearch,linglaiyao1314/elasticsearch,mcku/elasticsearch,marcuswr/elasticsearch-dateline,pablocastro/elasticsearch,mapr/elasticsearch,nrkkalyan/elasticsearch,mjason3/elasticsearch,brwe/elasticsearch,girirajsharma/elasticsearch,mgalushka/elasticsearch,alexbrasetvik/elasticsearch,MaineC/elasticsearch,Brijeshrpatel9/elasticsearch,queirozfcom/elasticsearch,vroyer/elassandra,adrianbk/elasticsearch,ouyangkongtong/elasticsearch,franklanganke/elasticsearch,abibell/elasticsearch,apepper/elasticsearch,scottsom/elasticsearch,wangyuxue/elasticsearch,JSCooke/elasticsearch,mkis-/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,kunallimaye/elasticsearch,clintongormley/elasticsearch,fekaputra/elasticsearch,lmtwga/elasticsearch,spiegela/elasticsearch,jpountz/elasticsearch,umeshdangat/elasticsearch,kalburgimanjunath/elasticsearch,javachengwc/elasticsearch,alexksikes/elasticsearch,kimimj/elasticsearch,cnfire/elasticsearch-1,snikch/elasticsearch,iantruslove/elasticsearch,huypx1292/elasticsearch,acchen97/elasticsearch,marcuswr/elasticsearch-dateline,yynil/elasticsearch,bawse/elasticsearch,NBSW/elasticsearch,tkssharma/elasticsearch,kimimj/elasticsearch,sarwarbhuiyan/elasticsearch,koxa29/elasticsearch,kevinkluge/elasticsearch,luiseduardohdbackup/elasticsearch,rajanm/elasticsearch,wangtuo/elasticsearch,SergVro/elasticsearch,Rygbee/elasticsearch,vingupta3/elasticsearch,khiraiwa/elasticsearch,jimczi/elasticsearch,adrianbk/elasticsearch,qwerty4030/elasticsearch,Chhunlong/elasticsearch,kcompher/elasticsearch,ydsakyclguozi/elasticsearch,MjAbuz/elasticsearch,xuzha/elasticsearch,i-am-Nathan/elasticsearch,kubum/elasticsearch,kkirsche/elasticsearch,libosu/elasticsearch,IanvsPoplicola/elasticsearch,dongaihua/highlight-elasticsearch,onegambler/elasticsearch,combinatorist/elasticsearch,knight1128/elasticsearch,artnowo/elasticsearch,tebriel/elasticsearch,spiegela/elasticsearch,markharwood/elasticsearch,C-Bish/elasticsearch,hydro2k/elasticsearch,Brijeshrpatel9/elasticsearch,tkssharma/elasticsearch,ouyangkongtong/elasticsearch,mohit/elasticsearch,geidies/elasticsearch,uschindler/elasticsearch,EasonYi/elasticsearch,thecocce/elasticsearch,markllama/elasticsearch,MjAbuz/elasticsearch,slavau/elasticsearch,kkirsche/elasticsearch,wenpos/elasticsearch,nrkkalyan/elasticsearch,vvcephei/elasticsearch,wbowling/elasticsearch,winstonewert/elasticsearch,rhoml/elasticsearch,wittyameta/elasticsearch,VukDukic/elasticsearch,markwalkom/elasticsearch,myelin/elasticsearch,mikemccand/elasticsearch,qwerty4030/elasticsearch,ckclark/elasticsearch,nellicus/elasticsearch,btiernay/elasticsearch,jaynblue/elasticsearch,obourgain/elasticsearch,HarishAtGitHub/elasticsearch,njlawton/elasticsearch,palecur/elasticsearch,mikemccand/elasticsearch,luiseduardohdbackup/elasticsearch,javachengwc/elasticsearch,boliza/elasticsearch,andrestc/elasticsearch,overcome/elasticsearch,franklanganke/elasticsearch,anti-social/elasticsearch,YosuaMichael/elasticsearch,Brijeshrpatel9/elasticsearch,caengcjd/elasticsearch,gingerwizard/elasticsearch,Liziyao/elasticsearch,aglne/elasticsearch,marcuswr/elasticsearch-dateline,luiseduardohdbackup/elasticsearch,raishiv/elasticsearch,nknize/elasticsearch,Widen/elasticsearch,Chhunlong/elasticsearch,combinatorist/elasticsearch,18098924759/elasticsearch,Asimov4/elasticsearch,Stacey-Gammon/elasticsearch,vrkansagara/elasticsearch,tsohil/elasticsearch,markharwood/elasticsearch,ZTE-PaaS/elasticsearch,fernandozhu/elasticsearch,xuzha/elasticsearch,heng4fun/elasticsearch,kubum/elasticsearch,jeteve/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,zhiqinghuang/elasticsearch,glefloch/elasticsearch,zkidkid/elasticsearch,jprante/elasticsearch,karthikjaps/elasticsearch,mapr/elasticsearch,socialrank/elasticsearch,mnylen/elasticsearch,yynil/elasticsearch,geidies/elasticsearch,tcucchietti/elasticsearch,clintongormley/elasticsearch,schonfeld/elasticsearch,strapdata/elassandra,AshishThakur/elasticsearch,andrejserafim/elasticsearch,fforbeck/elasticsearch,cnfire/elasticsearch-1,kaneshin/elasticsearch,ckclark/elasticsearch,rmuir/elasticsearch,lmtwga/elasticsearch,sc0ttkclark/elasticsearch,alexbrasetvik/elasticsearch,jango2015/elasticsearch,alexkuk/elasticsearch,sjohnr/elasticsearch,queirozfcom/elasticsearch,dongjoon-hyun/elasticsearch,slavau/elasticsearch,marcuswr/elasticsearch-dateline,areek/elasticsearch,mjhennig/elasticsearch,trangvh/elasticsearch,xingguang2013/elasticsearch,drewr/elasticsearch,sposam/elasticsearch,polyfractal/elasticsearch,Collaborne/elasticsearch,alexkuk/elasticsearch,fekaputra/elasticsearch,feiqitian/elasticsearch,sposam/elasticsearch,mute/elasticsearch,KimTaehee/elasticsearch,liweinan0423/elasticsearch,achow/elasticsearch,fforbeck/elasticsearch,khiraiwa/elasticsearch,zhiqinghuang/elasticsearch,liweinan0423/elasticsearch,ImpressTV/elasticsearch,raishiv/elasticsearch,fred84/elasticsearch,masterweb121/elasticsearch,pritishppai/elasticsearch,tebriel/elasticsearch,nomoa/elasticsearch,vrkansagara/elasticsearch,thecocce/elasticsearch,huypx1292/elasticsearch,chrismwendt/elasticsearch,jimhooker2002/elasticsearch,ImpressTV/elasticsearch,thecocce/elasticsearch,sposam/elasticsearch,scorpionvicky/elasticsearch,brandonkearby/elasticsearch,PhaedrusTheGreek/elasticsearch,humandb/elasticsearch,micpalmia/elasticsearch,karthikjaps/elasticsearch,Siddartha07/elasticsearch,spiegela/elasticsearch,elancom/elasticsearch,masterweb121/elasticsearch,jchampion/elasticsearch,linglaiyao1314/elasticsearch,elancom/elasticsearch,kimchy/elasticsearch,bawse/elasticsearch,humandb/elasticsearch,maddin2016/elasticsearch,vietlq/elasticsearch,amit-shar/elasticsearch,MichaelLiZhou/elasticsearch,vorce/es-metrics,wangyuxue/elasticsearch,pritishppai/elasticsearch,Chhunlong/elasticsearch,iantruslove/elasticsearch,opendatasoft/elasticsearch,djschny/elasticsearch,davidvgalbraith/elasticsearch,Flipkart/elasticsearch,sreeramjayan/elasticsearch,iamjakob/elasticsearch,bestwpw/elasticsearch,schonfeld/elasticsearch,Asimov4/elasticsearch,ricardocerq/elasticsearch,luiseduardohdbackup/elasticsearch,jbertouch/elasticsearch,martinstuga/elasticsearch,weipinghe/elasticsearch,maddin2016/elasticsearch,dantuffery/elasticsearch,hirdesh2008/elasticsearch,LeoYao/elasticsearch,wangtuo/elasticsearch,kubum/elasticsearch,hechunwen/elasticsearch,uschindler/elasticsearch,bawse/elasticsearch,nrkkalyan/elasticsearch,fred84/elasticsearch,C-Bish/elasticsearch,chirilo/elasticsearch,vietlq/elasticsearch,ESamir/elasticsearch,kingaj/elasticsearch,mjhennig/elasticsearch,schonfeld/elasticsearch,gfyoung/elasticsearch,pozhidaevak/elasticsearch,winstonewert/elasticsearch,njlawton/elasticsearch,kingaj/elasticsearch,fred84/elasticsearch,abhijitiitr/es,skearns64/elasticsearch,NBSW/elasticsearch,shreejay/elasticsearch,elancom/elasticsearch,Shekharrajak/elasticsearch,socialrank/elasticsearch,Rygbee/elasticsearch,rmuir/elasticsearch,infusionsoft/elasticsearch,nazarewk/elasticsearch,TonyChai24/ESSource,JervyShi/elasticsearch,amaliujia/elasticsearch,mute/elasticsearch,Flipkart/elasticsearch,kaneshin/elasticsearch,xpandan/elasticsearch,alexksikes/elasticsearch,sarwarbhuiyan/elasticsearch,MetSystem/elasticsearch,mmaracic/elasticsearch,naveenhooda2000/elasticsearch,pozhidaevak/elasticsearch,nellicus/elasticsearch,yongminxia/elasticsearch,wayeast/elasticsearch,ThiagoGarciaAlves/elasticsearch,fernandozhu/elasticsearch,tkssharma/elasticsearch,mnylen/elasticsearch,milodky/elasticsearch,C-Bish/elasticsearch,AshishThakur/elasticsearch,Charlesdong/elasticsearch,AndreKR/elasticsearch,winstonewert/elasticsearch,alexksikes/elasticsearch,pritishppai/elasticsearch,coding0011/elasticsearch,btiernay/elasticsearch,polyfractal/elasticsearch,C-Bish/elasticsearch,shreejay/elasticsearch,zhiqinghuang/elasticsearch,infusionsoft/elasticsearch,hanst/elasticsearch,drewr/elasticsearch,kenshin233/elasticsearch,nomoa/elasticsearch,snikch/elasticsearch,djschny/elasticsearch,lmtwga/elasticsearch,tsohil/elasticsearch,episerver/elasticsearch,avikurapati/elasticsearch,truemped/elasticsearch,mm0/elasticsearch,hanst/elasticsearch,mohsinh/elasticsearch,drewr/elasticsearch,lydonchandra/elasticsearch,thecocce/elasticsearch,ivansun1010/elasticsearch,amit-shar/elasticsearch,mrorii/elasticsearch,mbrukman/elasticsearch,cnfire/elasticsearch-1,overcome/elasticsearch,kaneshin/elasticsearch,rajanm/elasticsearch,chirilo/elasticsearch,pozhidaevak/elasticsearch,kimimj/elasticsearch,skearns64/elasticsearch,salyh/elasticsearch,kcompher/elasticsearch,kunallimaye/elasticsearch,chirilo/elasticsearch,abhijitiitr/es,ulkas/elasticsearch,iamjakob/elasticsearch,jeteve/elasticsearch,chrismwendt/elasticsearch,MichaelLiZhou/elasticsearch,acchen97/elasticsearch,mohsinh/elasticsearch,uboness/elasticsearch,tsohil/elasticsearch,snikch/elasticsearch,xpandan/elasticsearch,JSCooke/elasticsearch,jango2015/elasticsearch,Chhunlong/elasticsearch,pritishppai/elasticsearch,lchennup/elasticsearch,ulkas/elasticsearch,sc0ttkclark/elasticsearch,Liziyao/elasticsearch,yuy168/elasticsearch,vvcephei/elasticsearch,AleksKochev/elasticsearch,liweinan0423/elasticsearch,abibell/elasticsearch,jaynblue/elasticsearch,Liziyao/elasticsearch,kalburgimanjunath/elasticsearch,elancom/elasticsearch,kalimatas/elasticsearch,milodky/elasticsearch,avikurapati/elasticsearch,cwurm/elasticsearch,LewayneNaidoo/elasticsearch,Brijeshrpatel9/elasticsearch,mjhennig/elasticsearch,MjAbuz/elasticsearch,jbertouch/elasticsearch,ivansun1010/elasticsearch,gfyoung/elasticsearch,i-am-Nathan/elasticsearch,Kakakakakku/elasticsearch,dpursehouse/elasticsearch,kcompher/elasticsearch,pranavraman/elasticsearch,Siddartha07/elasticsearch,chrismwendt/elasticsearch,javachengwc/elasticsearch,brandonkearby/elasticsearch,Kakakakakku/elasticsearch,hydro2k/elasticsearch,mohsinh/elasticsearch,Brijeshrpatel9/elasticsearch,infusionsoft/elasticsearch,mbrukman/elasticsearch,weipinghe/elasticsearch,Kakakakakku/elasticsearch,knight1128/elasticsearch,mrorii/elasticsearch,scorpionvicky/elasticsearch,wbowling/elasticsearch,wittyameta/elasticsearch,sreeramjayan/elasticsearch,areek/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,MaineC/elasticsearch,vingupta3/elasticsearch,strapdata/elassandra-test,lmenezes/elasticsearch,HarishAtGitHub/elasticsearch,vroyer/elasticassandra,Ansh90/elasticsearch,henakamaMSFT/elasticsearch,golubev/elasticsearch,libosu/elasticsearch,MisterAndersen/elasticsearch,Uiho/elasticsearch,abibell/elasticsearch,lchennup/elasticsearch,Brijeshrpatel9/elasticsearch,xingguang2013/elasticsearch,rento19962/elasticsearch,coding0011/elasticsearch,areek/elasticsearch,ivansun1010/elasticsearch,alexbrasetvik/elasticsearch,mapr/elasticsearch,schonfeld/elasticsearch,nomoa/elasticsearch,adrianbk/elasticsearch,davidvgalbraith/elasticsearch,mmaracic/elasticsearch,javachengwc/elasticsearch,fubuki/elasticsearch,uboness/elasticsearch,zeroctu/elasticsearch,kunallimaye/elasticsearch,mgalushka/elasticsearch,mkis-/elasticsearch,vroyer/elassandra,umeshdangat/elasticsearch,szroland/elasticsearch,cwurm/elasticsearch,fernandozhu/elasticsearch,koxa29/elasticsearch,uschindler/elasticsearch,MichaelLiZhou/elasticsearch,amaliujia/elasticsearch,YosuaMichael/elasticsearch,jsgao0/elasticsearch,codebunt/elasticsearch,acchen97/elasticsearch,sdauletau/elasticsearch,sdauletau/elasticsearch,ThiagoGarciaAlves/elasticsearch,mm0/elasticsearch,jango2015/elasticsearch,mute/elasticsearch,mute/elasticsearch,StefanGor/elasticsearch,nellicus/elasticsearch,jimhooker2002/elasticsearch,IanvsPoplicola/elasticsearch,KimTaehee/elasticsearch,socialrank/elasticsearch,jpountz/elasticsearch,ckclark/elasticsearch,avikurapati/elasticsearch,aparo/elasticsearch,MisterAndersen/elasticsearch,kubum/elasticsearch,Widen/elasticsearch,rlugojr/elasticsearch,palecur/elasticsearch,springning/elasticsearch,andrejserafim/elasticsearch,mjason3/elasticsearch,nezirus/elasticsearch,KimTaehee/elasticsearch,djschny/elasticsearch,wittyameta/elasticsearch,tkssharma/elasticsearch,mcku/elasticsearch,fooljohnny/elasticsearch,mcku/elasticsearch,Stacey-Gammon/elasticsearch
/* * Licensed to ElasticSearch and Shay Banon under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. ElasticSearch 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.elasticsearch.index.mapper.core; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.document.Field; import org.apache.lucene.document.Fieldable; import org.apache.lucene.search.Filter; import org.elasticsearch.common.Strings; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.support.XContentMapValues; import org.elasticsearch.index.analysis.NamedAnalyzer; import org.elasticsearch.index.analysis.NamedCustomAnalyzer; import org.elasticsearch.index.mapper.*; import org.elasticsearch.index.mapper.internal.AllFieldMapper; import java.io.IOException; import java.util.Map; import static org.elasticsearch.index.mapper.MapperBuilders.stringField; import static org.elasticsearch.index.mapper.core.TypeParsers.parseField; /** * */ public class StringFieldMapper extends AbstractFieldMapper<String> implements AllFieldMapper.IncludeInAll { public static final String CONTENT_TYPE = "string"; public static class Defaults extends AbstractFieldMapper.Defaults { // NOTE, when adding defaults here, make sure you add them in the builder public static final String NULL_VALUE = null; public static final int POSITION_OFFSET_GAP = 0; } public static class Builder extends AbstractFieldMapper.OpenBuilder<Builder, StringFieldMapper> { protected String nullValue = Defaults.NULL_VALUE; protected int positionOffsetGap = Defaults.POSITION_OFFSET_GAP; protected NamedAnalyzer searchQuotedAnalyzer; public Builder(String name) { super(name); builder = this; } public Builder nullValue(String nullValue) { this.nullValue = nullValue; return this; } @Override public Builder includeInAll(Boolean includeInAll) { this.includeInAll = includeInAll; return this; } @Override public Builder searchAnalyzer(NamedAnalyzer searchAnalyzer) { super.searchAnalyzer(searchAnalyzer); if (searchQuotedAnalyzer == null) { searchQuotedAnalyzer = searchAnalyzer; } return this; } public Builder positionOffsetGap(int positionOffsetGap) { this.positionOffsetGap = positionOffsetGap; return this; } public Builder searchQuotedAnalyzer(NamedAnalyzer analyzer) { this.searchQuotedAnalyzer = analyzer; return builder; } @Override public StringFieldMapper build(BuilderContext context) { if (positionOffsetGap > 0) { indexAnalyzer = new NamedCustomAnalyzer(indexAnalyzer, positionOffsetGap); searchAnalyzer = new NamedCustomAnalyzer(searchAnalyzer, positionOffsetGap); searchQuotedAnalyzer = new NamedCustomAnalyzer(searchQuotedAnalyzer, positionOffsetGap); } StringFieldMapper fieldMapper = new StringFieldMapper(buildNames(context), index, store, termVector, boost, omitNorms, omitTermFreqAndPositions, nullValue, indexAnalyzer, searchAnalyzer, searchQuotedAnalyzer, positionOffsetGap); fieldMapper.includeInAll(includeInAll); return fieldMapper; } } public static class TypeParser implements Mapper.TypeParser { @Override public Mapper.Builder parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException { StringFieldMapper.Builder builder = stringField(name); parseField(builder, name, node, parserContext); for (Map.Entry<String, Object> entry : node.entrySet()) { String propName = Strings.toUnderscoreCase(entry.getKey()); Object propNode = entry.getValue(); if (propName.equals("null_value")) { builder.nullValue(propNode.toString()); } else if (propName.equals("search_quote_analyzer")) { NamedAnalyzer analyzer = parserContext.analysisService().analyzer(propNode.toString()); if (analyzer == null) { throw new MapperParsingException("Analyzer [" + propNode.toString() + "] not found for field [" + name + "]"); } builder.searchQuotedAnalyzer(analyzer); } else if (propName.equals("position_offset_gap")) { builder.positionOffsetGap(XContentMapValues.nodeIntegerValue(propNode, -1)); // we need to update to actual analyzers if they are not set in this case... // so we can inject the position offset gap... if (builder.indexAnalyzer == null) { builder.indexAnalyzer = parserContext.analysisService().defaultIndexAnalyzer(); } if (builder.searchAnalyzer == null) { builder.searchAnalyzer = parserContext.analysisService().defaultSearchAnalyzer(); } if (builder.searchQuotedAnalyzer == null) { builder.searchQuotedAnalyzer = parserContext.analysisService().defaultSearchQuoteAnalyzer(); } } } return builder; } } private String nullValue; private Boolean includeInAll; private int positionOffsetGap; private NamedAnalyzer searchQuotedAnalyzer; protected StringFieldMapper(Names names, Field.Index index, Field.Store store, Field.TermVector termVector, float boost, boolean omitNorms, boolean omitTermFreqAndPositions, String nullValue, NamedAnalyzer indexAnalyzer, NamedAnalyzer searchAnalyzer) { this(names, index, store, termVector, boost, omitNorms, omitTermFreqAndPositions, nullValue, indexAnalyzer, searchAnalyzer, searchAnalyzer, Defaults.POSITION_OFFSET_GAP); } protected StringFieldMapper(Names names, Field.Index index, Field.Store store, Field.TermVector termVector, float boost, boolean omitNorms, boolean omitTermFreqAndPositions, String nullValue, NamedAnalyzer indexAnalyzer, NamedAnalyzer searchAnalyzer, NamedAnalyzer searchQuotedAnalyzer, int positionOffsetGap) { super(names, index, store, termVector, boost, omitNorms, omitTermFreqAndPositions, indexAnalyzer, searchAnalyzer); this.nullValue = nullValue; this.positionOffsetGap = positionOffsetGap; this.searchQuotedAnalyzer = searchQuotedAnalyzer != null ? searchQuotedAnalyzer : this.searchAnalyzer; } @Override public void includeInAll(Boolean includeInAll) { if (includeInAll != null) { this.includeInAll = includeInAll; } } @Override public void includeInAllIfNotSet(Boolean includeInAll) { if (includeInAll != null && this.includeInAll == null) { this.includeInAll = includeInAll; } } @Override public String value(Fieldable field) { return field.stringValue(); } @Override public String valueFromString(String value) { return value; } @Override public String valueAsString(Fieldable field) { return value(field); } @Override public String indexedValue(String value) { return value; } @Override protected boolean customBoost() { return true; } public int getPositionOffsetGap() { return this.positionOffsetGap; } @Override public Analyzer searchQuoteAnalyzer() { return this.searchQuotedAnalyzer; } @Override public Filter nullValueFilter() { if (nullValue == null) { return null; } return fieldFilter(nullValue, null); } @Override protected Field parseCreateField(ParseContext context) throws IOException { String value = nullValue; float boost = this.boost; if (context.externalValueSet()) { value = (String) context.externalValue(); } else { XContentParser parser = context.parser(); if (parser.currentToken() == XContentParser.Token.VALUE_NULL) { value = nullValue; } else if (parser.currentToken() == XContentParser.Token.START_OBJECT) { XContentParser.Token token; String currentFieldName = null; while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { currentFieldName = parser.currentName(); } else { if ("value".equals(currentFieldName) || "_value".equals(currentFieldName)) { value = parser.textOrNull(); } else if ("boost".equals(currentFieldName) || "_boost".equals(currentFieldName)) { boost = parser.floatValue(); } } } } else { value = parser.textOrNull(); } } if (value == null) { return null; } if (context.includeInAll(includeInAll, this)) { context.allEntries().addText(names.fullName(), value, boost); } if (!indexed() && !stored()) { context.ignoredValue(names.indexName(), value); return null; } Field field = new Field(names.indexName(), false, value, store, index, termVector); field.setBoost(boost); return field; } @Override protected String contentType() { return CONTENT_TYPE; } @Override public void merge(Mapper mergeWith, MergeContext mergeContext) throws MergeMappingException { super.merge(mergeWith, mergeContext); if (!this.getClass().equals(mergeWith.getClass())) { return; } if (!mergeContext.mergeFlags().simulate()) { this.includeInAll = ((StringFieldMapper) mergeWith).includeInAll; this.nullValue = ((StringFieldMapper) mergeWith).nullValue; } } @Override protected void doXContentBody(XContentBuilder builder) throws IOException { super.doXContentBody(builder); if (index != Defaults.INDEX) { builder.field("index", index.name().toLowerCase()); } if (store != Defaults.STORE) { builder.field("store", store.name().toLowerCase()); } if (termVector != Defaults.TERM_VECTOR) { builder.field("term_vector", termVector.name().toLowerCase()); } if (omitNorms != Defaults.OMIT_NORMS) { builder.field("omit_norms", omitNorms); } if (omitTermFreqAndPositions != Defaults.OMIT_TERM_FREQ_AND_POSITIONS) { builder.field("omit_term_freq_and_positions", omitTermFreqAndPositions); } if (nullValue != null) { builder.field("null_value", nullValue); } if (includeInAll != null) { builder.field("include_in_all", includeInAll); } if (positionOffsetGap != Defaults.POSITION_OFFSET_GAP) { builder.field("position_offset_gap", positionOffsetGap); } if (searchQuotedAnalyzer != null && searchAnalyzer != searchQuotedAnalyzer) { builder.field("search_quote_analyzer", searchQuotedAnalyzer.name()); } } }
src/main/java/org/elasticsearch/index/mapper/core/StringFieldMapper.java
/* * Licensed to ElasticSearch and Shay Banon under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. ElasticSearch 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.elasticsearch.index.mapper.core; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.document.Field; import org.apache.lucene.document.Fieldable; import org.apache.lucene.search.Filter; import org.elasticsearch.common.Strings; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.support.XContentMapValues; import org.elasticsearch.index.analysis.NamedAnalyzer; import org.elasticsearch.index.analysis.NamedCustomAnalyzer; import org.elasticsearch.index.mapper.*; import org.elasticsearch.index.mapper.internal.AllFieldMapper; import java.io.IOException; import java.util.Map; import static org.elasticsearch.index.mapper.MapperBuilders.stringField; import static org.elasticsearch.index.mapper.core.TypeParsers.parseField; /** * */ public class StringFieldMapper extends AbstractFieldMapper<String> implements AllFieldMapper.IncludeInAll { public static final String CONTENT_TYPE = "string"; public static class Defaults extends AbstractFieldMapper.Defaults { // NOTE, when adding defaults here, make sure you add them in the builder public static final String NULL_VALUE = null; public static final int POSITION_OFFSET_GAP = 0; } public static class Builder extends AbstractFieldMapper.OpenBuilder<Builder, StringFieldMapper> { protected String nullValue = Defaults.NULL_VALUE; protected int positionOffsetGap = Defaults.POSITION_OFFSET_GAP; protected NamedAnalyzer searchQuotedAnalyzer; public Builder(String name) { super(name); builder = this; } public Builder nullValue(String nullValue) { this.nullValue = nullValue; return this; } @Override public Builder includeInAll(Boolean includeInAll) { this.includeInAll = includeInAll; return this; } @Override public Builder searchAnalyzer(NamedAnalyzer searchAnalyzer) { super.searchAnalyzer(searchAnalyzer); if (searchQuotedAnalyzer == null) { searchQuotedAnalyzer = searchAnalyzer; } return this; } public Builder positionOffsetGap(int positionOffsetGap) { this.positionOffsetGap = positionOffsetGap; return this; } public Builder searchQuotedAnalyzer(NamedAnalyzer analyzer) { this.searchQuotedAnalyzer = analyzer; return builder; } @Override public StringFieldMapper build(BuilderContext context) { if (positionOffsetGap > 0) { indexAnalyzer = new NamedCustomAnalyzer(indexAnalyzer, positionOffsetGap); searchAnalyzer = new NamedCustomAnalyzer(searchAnalyzer, positionOffsetGap); searchQuotedAnalyzer = new NamedCustomAnalyzer(searchQuotedAnalyzer, positionOffsetGap); } StringFieldMapper fieldMapper = new StringFieldMapper(buildNames(context), index, store, termVector, boost, omitNorms, omitTermFreqAndPositions, nullValue, indexAnalyzer, searchAnalyzer, searchQuotedAnalyzer, positionOffsetGap); fieldMapper.includeInAll(includeInAll); return fieldMapper; } } public static class TypeParser implements Mapper.TypeParser { @Override public Mapper.Builder parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException { StringFieldMapper.Builder builder = stringField(name); parseField(builder, name, node, parserContext); for (Map.Entry<String, Object> entry : node.entrySet()) { String propName = Strings.toUnderscoreCase(entry.getKey()); Object propNode = entry.getValue(); if (propName.equals("null_value")) { builder.nullValue(propNode.toString()); } else if (propName.equals("search_quote_analyzer")) { NamedAnalyzer analyzer = parserContext.analysisService().analyzer(propNode.toString()); if (analyzer == null) { throw new MapperParsingException("Analyzer [" + propNode.toString() + "] not found for field [" + name + "]"); } builder.searchQuotedAnalyzer(analyzer); } else if (propName.equals("position_offset_gap")) { builder.positionOffsetGap(XContentMapValues.nodeIntegerValue(propNode, -1)); // we need to update to actual analyzers if they are not set in this case... // so we can inject the position offset gap... if (builder.indexAnalyzer == null) { builder.indexAnalyzer = parserContext.analysisService().defaultIndexAnalyzer(); } if (builder.searchAnalyzer == null) { builder.searchAnalyzer = parserContext.analysisService().defaultSearchAnalyzer(); } if (builder.searchQuotedAnalyzer == null) { builder.searchQuotedAnalyzer = parserContext.analysisService().defaultSearchQuoteAnalyzer(); } } } return builder; } } private String nullValue; private Boolean includeInAll; private int positionOffsetGap; private NamedAnalyzer searchQuotedAnalyzer; protected StringFieldMapper(Names names, Field.Index index, Field.Store store, Field.TermVector termVector, float boost, boolean omitNorms, boolean omitTermFreqAndPositions, String nullValue, NamedAnalyzer indexAnalyzer, NamedAnalyzer searchAnalyzer) { this(names, index, store, termVector, boost, omitNorms, omitTermFreqAndPositions, nullValue, indexAnalyzer, searchAnalyzer, searchAnalyzer, Defaults.POSITION_OFFSET_GAP); } protected StringFieldMapper(Names names, Field.Index index, Field.Store store, Field.TermVector termVector, float boost, boolean omitNorms, boolean omitTermFreqAndPositions, String nullValue, NamedAnalyzer indexAnalyzer, NamedAnalyzer searchAnalyzer, NamedAnalyzer searchQuotedAnalyzer, int positionOffsetGap) { super(names, index, store, termVector, boost, omitNorms, omitTermFreqAndPositions, indexAnalyzer, searchAnalyzer); this.nullValue = nullValue; this.positionOffsetGap = positionOffsetGap; this.searchQuotedAnalyzer = searchQuotedAnalyzer != null ? searchQuotedAnalyzer : searchAnalyzer; } @Override public void includeInAll(Boolean includeInAll) { if (includeInAll != null) { this.includeInAll = includeInAll; } } @Override public void includeInAllIfNotSet(Boolean includeInAll) { if (includeInAll != null && this.includeInAll == null) { this.includeInAll = includeInAll; } } @Override public String value(Fieldable field) { return field.stringValue(); } @Override public String valueFromString(String value) { return value; } @Override public String valueAsString(Fieldable field) { return value(field); } @Override public String indexedValue(String value) { return value; } @Override protected boolean customBoost() { return true; } public int getPositionOffsetGap() { return this.positionOffsetGap; } @Override public Analyzer searchQuoteAnalyzer() { return this.searchQuotedAnalyzer; } @Override public Filter nullValueFilter() { if (nullValue == null) { return null; } return fieldFilter(nullValue, null); } @Override protected Field parseCreateField(ParseContext context) throws IOException { String value = nullValue; float boost = this.boost; if (context.externalValueSet()) { value = (String) context.externalValue(); } else { XContentParser parser = context.parser(); if (parser.currentToken() == XContentParser.Token.VALUE_NULL) { value = nullValue; } else if (parser.currentToken() == XContentParser.Token.START_OBJECT) { XContentParser.Token token; String currentFieldName = null; while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { currentFieldName = parser.currentName(); } else { if ("value".equals(currentFieldName) || "_value".equals(currentFieldName)) { value = parser.textOrNull(); } else if ("boost".equals(currentFieldName) || "_boost".equals(currentFieldName)) { boost = parser.floatValue(); } } } } else { value = parser.textOrNull(); } } if (value == null) { return null; } if (context.includeInAll(includeInAll, this)) { context.allEntries().addText(names.fullName(), value, boost); } if (!indexed() && !stored()) { context.ignoredValue(names.indexName(), value); return null; } Field field = new Field(names.indexName(), false, value, store, index, termVector); field.setBoost(boost); return field; } @Override protected String contentType() { return CONTENT_TYPE; } @Override public void merge(Mapper mergeWith, MergeContext mergeContext) throws MergeMappingException { super.merge(mergeWith, mergeContext); if (!this.getClass().equals(mergeWith.getClass())) { return; } if (!mergeContext.mergeFlags().simulate()) { this.includeInAll = ((StringFieldMapper) mergeWith).includeInAll; this.nullValue = ((StringFieldMapper) mergeWith).nullValue; } } @Override protected void doXContentBody(XContentBuilder builder) throws IOException { super.doXContentBody(builder); if (index != Defaults.INDEX) { builder.field("index", index.name().toLowerCase()); } if (store != Defaults.STORE) { builder.field("store", store.name().toLowerCase()); } if (termVector != Defaults.TERM_VECTOR) { builder.field("term_vector", termVector.name().toLowerCase()); } if (omitNorms != Defaults.OMIT_NORMS) { builder.field("omit_norms", omitNorms); } if (omitTermFreqAndPositions != Defaults.OMIT_TERM_FREQ_AND_POSITIONS) { builder.field("omit_term_freq_and_positions", omitTermFreqAndPositions); } if (nullValue != null) { builder.field("null_value", nullValue); } if (includeInAll != null) { builder.field("include_in_all", includeInAll); } if (positionOffsetGap != Defaults.POSITION_OFFSET_GAP) { builder.field("position_offset_gap", positionOffsetGap); } if (searchQuotedAnalyzer != null && searchAnalyzer != searchQuotedAnalyzer) { builder.field("search_quote_analyzer", searchQuotedAnalyzer.name()); } } }
Quoted query_string gives NullPointerException with not_analyzed field (0.19.4), closes #2006.
src/main/java/org/elasticsearch/index/mapper/core/StringFieldMapper.java
Quoted query_string gives NullPointerException with not_analyzed field (0.19.4), closes #2006.
<ide><path>rc/main/java/org/elasticsearch/index/mapper/core/StringFieldMapper.java <ide> super(names, index, store, termVector, boost, omitNorms, omitTermFreqAndPositions, indexAnalyzer, searchAnalyzer); <ide> this.nullValue = nullValue; <ide> this.positionOffsetGap = positionOffsetGap; <del> this.searchQuotedAnalyzer = searchQuotedAnalyzer != null ? searchQuotedAnalyzer : searchAnalyzer; <add> this.searchQuotedAnalyzer = searchQuotedAnalyzer != null ? searchQuotedAnalyzer : this.searchAnalyzer; <ide> } <ide> <ide> @Override
JavaScript
mit
5c3e1b2eeb531422dfe7e05cefc71d99f213d96a
0
node-nock/nock
'use strict' const mixin = require('./mixin') const matchBody = require('./match_body') const common = require('./common') const _ = require('lodash') const debug = require('debug')('nock.interceptor') const stringify = require('json-stringify-safe') const qs = require('qs') let fs try { fs = require('fs') } catch (err) { // do nothing, we're in the browser } module.exports = Interceptor function Interceptor(scope, uri, method, requestBody, interceptorOptions) { // Check for leading slash. Uri can be either a string or a regexp, but // we only need to check strings. if (typeof uri === 'string' && /^[^/*]/.test(uri)) { throw Error( "Non-wildcard URL path strings must begin with a slash (otherwise they won't match anything)" ) } this.scope = scope this.interceptorMatchHeaders = [] if (typeof method === 'undefined' || !method) { throw new Error('The "method" parameter is required for an intercept call.') } this.method = method.toUpperCase() this.uri = uri this._key = `${this.method} ${scope.basePath}${scope.basePathname}${ typeof uri === 'string' ? '' : '/' }${uri}` this.basePath = this.scope.basePath this.path = typeof uri === 'string' ? scope.basePathname + uri : uri this.baseUri = `${this.method} ${scope.basePath}${scope.basePathname}` this.options = interceptorOptions || {} this.counter = 1 this._requestBody = requestBody // We use lower-case header field names throughout Nock. this.reqheaders = common.headersFieldNamesToLowerCase( (scope.scopeOptions && scope.scopeOptions.reqheaders) || {} ) this.badheaders = common.headersFieldsArrayToLowerCase( (scope.scopeOptions && scope.scopeOptions.badheaders) || [] ) this.delayInMs = 0 this.delayConnectionInMs = 0 this.optional = false } Interceptor.prototype.optionally = function optionally(value) { // The default behaviour of optionally() with no arguments is to make the mock optional. value = typeof value === 'undefined' ? true : value this.optional = value return this } Interceptor.prototype.replyWithError = function replyWithError(errorMessage) { this.errorMessage = errorMessage _.defaults(this.options, this.scope.scopeOptions) this.scope.add(this._key, this, this.scope, this.scopeOptions) return this.scope } Interceptor.prototype.reply = function reply(statusCode, body, rawHeaders) { if (arguments.length <= 2 && _.isFunction(statusCode)) { body = statusCode statusCode = 200 } this.statusCode = statusCode _.defaults(this.options, this.scope.scopeOptions) // If needed, convert rawHeaders from Array to Object. let headers = Array.isArray(rawHeaders) ? common.headersArrayToObject(rawHeaders) : rawHeaders if (this.scope._defaultReplyHeaders) { headers = headers || {} headers = common.headersFieldNamesToLowerCase(headers) headers = mixin(this.scope._defaultReplyHeaders, headers) } if (this.scope.date) { headers = headers || {} headers['date'] = this.scope.date.toUTCString() } if (headers !== undefined) { this.rawHeaders = [] for (const key in headers) { this.rawHeaders.push(key) this.rawHeaders.push(headers[key]) } // We use lower-case headers throughout Nock. this.headers = common.headersFieldNamesToLowerCase(headers) debug('reply.headers:', this.headers) debug('reply.rawHeaders:', this.rawHeaders) } // If the content is not encoded we may need to transform the response body. // Otherwise we leave it as it is. if (!common.isContentEncoded(this.headers)) { if ( body && typeof body !== 'string' && typeof body !== 'function' && !Buffer.isBuffer(body) && !common.isStream(body) ) { try { body = stringify(body) if (!this.headers) { this.headers = {} } if (!this.headers['content-type']) { this.headers['content-type'] = 'application/json' } if (this.scope.contentLen) { this.headers['content-length'] = body.length } } catch (err) { // TODO-coverage: Add a test covering this case. throw new Error('Error encoding response body into JSON') } } } this.body = body this.scope.add(this._key, this, this.scope, this.scopeOptions) return this.scope } Interceptor.prototype.replyWithFile = function replyWithFile( statusCode, filePath, headers ) { if (!fs) { // TODO-coverage: Add a `proxyquire` test covering this case. throw new Error('No fs') } const readStream = fs.createReadStream(filePath) readStream.pause() this.filePath = filePath return this.reply(statusCode, readStream, headers) } // Also match request headers // https://github.com/pgte/nock/issues/163 Interceptor.prototype.reqheaderMatches = function reqheaderMatches( options, key ) { // We don't try to match request headers if these weren't even specified in the request. if (!options.headers) { return true } const reqHeader = this.reqheaders[key] let header = options.headers[key] if (header && typeof header !== 'string' && header.toString) { header = header.toString() } // We skip 'host' header comparison unless it's available in both mock and actual request. // This because 'host' may get inserted by Nock itself and then get recorder. // NOTE: We use lower-case header field names throughout Nock. // TODO-coverage: This looks very special. Worth an investigation. if (key === 'host' && (_.isUndefined(header) || _.isUndefined(reqHeader))) { return true } if (!_.isUndefined(reqHeader) && !_.isUndefined(header)) { if (_.isFunction(reqHeader)) { return reqHeader(header) } else if (common.matchStringOrRegexp(header, reqHeader)) { return true } } debug("request header field doesn't match:", key, header, reqHeader) return false } Interceptor.prototype.match = function match(options, body, hostNameOnly) { if (debug.enabled) { // TODO-coverage: Find a way to work around this, or ignore it for // coverage purposes. debug('match %s, body = %s', stringify(options), stringify(body)) } if (hostNameOnly) { return options.hostname === this.scope.urlParts.hostname } const method = (options.method || 'GET').toUpperCase() let { path } = options let matches let matchKey const { proto } = options if (this.scope.transformPathFunction) { path = this.scope.transformPathFunction(path) } if (typeof body !== 'string') { body = body.toString() } if (this.scope.transformRequestBodyFunction) { body = this.scope.transformRequestBodyFunction(body, this._requestBody) } const checkHeaders = function(header) { if (_.isFunction(header.value)) { return header.value(options.getHeader(header.name)) } return common.matchStringOrRegexp( options.getHeader(header.name), header.value ) } if ( !this.scope.matchHeaders.every(checkHeaders) || !this.interceptorMatchHeaders.every(checkHeaders) ) { this.scope.logger("headers don't match") return false } const reqHeadersMatch = !this.reqheaders || Object.keys(this.reqheaders).every( this.reqheaderMatches.bind(this, options) ) if (!reqHeadersMatch) { return false } function reqheaderContains(header) { return _.has(options.headers, header) } const reqContainsBadHeaders = this.badheaders && _.some(this.badheaders, reqheaderContains) if (reqContainsBadHeaders) { return false } // If we have a filtered scope then we use it instead reconstructing // the scope from the request options (proto, host and port) as these // two won't necessarily match and we have to remove the scope that was // matched (vs. that was defined). if (this.__nock_filteredScope) { matchKey = this.__nock_filteredScope } else { matchKey = `${proto}://${options.host}` if ( options.port && options.host.indexOf(':') < 0 && (options.port !== 80 || options.proto !== 'http') && (options.port !== 443 || options.proto !== 'https') ) { matchKey += `:${options.port}` } } // Match query strings when using query() let matchQueries = true let queryIndex = -1 let queryString let queries if (this.queries) { queryIndex = path.indexOf('?') queryString = queryIndex !== -1 ? path.slice(queryIndex + 1) : '' queries = qs.parse(queryString) // Only check for query string matches if this.queries is an object if (_.isObject(this.queries)) { if (_.isFunction(this.queries)) { matchQueries = this.queries(queries) } else { // Make sure that you have an equal number of keys. We are // looping through the passed query params and not the expected values // if the user passes fewer query params than expected but all values // match this will throw a false positive. Testing that the length of the // passed query params is equal to the length of expected keys will prevent // us from doing any value checking BEFORE we know if they have all the proper // params debug('this.queries: %j', this.queries) debug('queries: %j', queries) if (_.size(this.queries) !== _.size(queries)) { matchQueries = false } else { const self = this _.forOwn(queries, function matchOneKeyVal(val, key) { const expVal = self.queries[key] let isMatch if (val === undefined || expVal === undefined) { isMatch = false } else if (expVal instanceof RegExp) { isMatch = common.matchStringOrRegexp(val, expVal) } else if (_.isArray(expVal) || _.isObject(expVal)) { isMatch = _.isEqual(val, expVal) } else { isMatch = common.matchStringOrRegexp(val, expVal) } matchQueries = matchQueries && !!isMatch }) } debug('matchQueries: %j', matchQueries) } } // Remove the query string from the path if (queryIndex !== -1) { path = path.substr(0, queryIndex) } } if (typeof this.uri === 'function') { matches = matchQueries && method === this.method && common.matchStringOrRegexp(matchKey, this.basePath) && // This is a false positive, as `uri` is not bound to `this`. // eslint-disable-next-line no-useless-call this.uri.call(this, path) } else { matches = method === this.method && common.matchStringOrRegexp(matchKey, this.basePath) && common.matchStringOrRegexp(path, this.path) && matchQueries } // special logger for query() if (queryIndex !== -1) { this.scope.logger( `matching ${matchKey}${path}?${queryString} to ${ this._key } with query(${stringify(this.queries)}): ${matches}` ) } else { this.scope.logger(`matching ${matchKey}${path} to ${this._key}: ${matches}`) } if (matches) { matches = matchBody.call(options, this._requestBody, body) if (!matches) { this.scope.logger("bodies don't match: \n", this._requestBody, '\n', body) } } return matches } Interceptor.prototype.matchIndependentOfBody = function matchIndependentOfBody( options ) { const isRegex = _.isRegExp(this.path) const isRegexBasePath = _.isRegExp(this.scope.basePath) const method = (options.method || 'GET').toUpperCase() let { path } = options const { proto } = options // NOTE: Do not split off the query params as the regex could use them if (!isRegex) { path = path ? path.split('?')[0] : '' } if (this.scope.transformPathFunction) { path = this.scope.transformPathFunction(path) } const checkHeaders = function(header) { return ( options.getHeader && common.matchStringOrRegexp(options.getHeader(header.name), header.value) ) } if ( !this.scope.matchHeaders.every(checkHeaders) || !this.interceptorMatchHeaders.every(checkHeaders) ) { return false } const comparisonKey = isRegex ? this.__nock_scopeKey : this._key const matchKey = `${method} ${proto}://${options.host}${path}` if (isRegex && !isRegexBasePath) { return !!matchKey.match(comparisonKey) && !!path.match(this.path) } if (isRegexBasePath) { return !!matchKey.match(this.scope.basePath) && !!path.match(this.path) } return comparisonKey === matchKey } Interceptor.prototype.filteringPath = function filteringPath() { if (_.isFunction(arguments[0])) { this.scope.transformFunction = arguments[0] } return this } Interceptor.prototype.discard = function discard() { if ((this.scope.shouldPersist() || this.counter > 0) && this.filePath) { this.body = fs.createReadStream(this.filePath) this.body.pause() } if (!this.scope.shouldPersist() && this.counter < 1) { this.scope.remove(this._key, this) } } Interceptor.prototype.matchHeader = function matchHeader(name, value) { this.interceptorMatchHeaders.push({ name, value }) return this } Interceptor.prototype.basicAuth = function basicAuth(options) { const username = options['user'] const password = options['pass'] || '' const name = 'authorization' const value = `Basic ${Buffer.from(`${username}:${password}`).toString( 'base64' )}` this.interceptorMatchHeaders.push({ name, value }) return this } /** * Set query strings for the interceptor * @name query * @param Object Object of query string name,values (accepts regexp values) * @public * @example * // Will match 'http://zombo.com/?q=t' * nock('http://zombo.com').get('/').query({q: 't'}); */ Interceptor.prototype.query = function query(queries) { this.queries = this.queries || {} // Allow all query strings to match this route if (queries === true) { this.queries = queries return this } if (_.isFunction(queries)) { this.queries = queries return this } let stringFormattingFn if (this.scope.scopeOptions.encodedQueryParams) { stringFormattingFn = common.percentDecode } for (const key in queries) { if (_.isUndefined(this.queries[key])) { const formattedPair = common.formatQueryValue( key, queries[key], stringFormattingFn ) this.queries[formattedPair[0]] = formattedPair[1] } } return this } /** * Set number of times will repeat the interceptor * @name times * @param Integer Number of times to repeat (should be > 0) * @public * @example * // Will repeat mock 5 times for same king of request * nock('http://zombo.com).get('/').times(5).reply(200, 'Ok'); */ Interceptor.prototype.times = function times(newCounter) { if (newCounter < 1) { return this } this.counter = newCounter return this } /** * An sugar syntax for times(1) * @name once * @see {@link times} * @public * @example * nock('http://zombo.com).get('/').once.reply(200, 'Ok'); */ Interceptor.prototype.once = function once() { return this.times(1) } /** * An sugar syntax for times(2) * @name twice * @see {@link times} * @public * @example * nock('http://zombo.com).get('/').twice.reply(200, 'Ok'); */ Interceptor.prototype.twice = function twice() { return this.times(2) } /** * An sugar syntax for times(3). * @name thrice * @see {@link times} * @public * @example * nock('http://zombo.com).get('/').thrice.reply(200, 'Ok'); */ Interceptor.prototype.thrice = function thrice() { return this.times(3) } /** * Delay the response by a certain number of ms. * * @param {(integer|object)} opts - Number of milliseconds to wait, or an object * @param {integer} [opts.head] - Number of milliseconds to wait before response is sent * @param {integer} [opts.body] - Number of milliseconds to wait before response body is sent * @return {interceptor} - the current interceptor for chaining */ Interceptor.prototype.delay = function delay(opts) { let headDelay = 0 let bodyDelay = 0 if (_.isNumber(opts)) { headDelay = opts } else if (_.isObject(opts)) { headDelay = opts.head || 0 bodyDelay = opts.body || 0 } else { throw new Error(`Unexpected input opts${opts}`) } return this.delayConnection(headDelay).delayBody(bodyDelay) } /** * Delay the response body by a certain number of ms. * * @param {integer} ms - Number of milliseconds to wait before response is sent * @return {interceptor} - the current interceptor for chaining */ Interceptor.prototype.delayBody = function delayBody(ms) { this.delayInMs += ms return this } /** * Delay the connection by a certain number of ms. * * @param {integer} ms - Number of milliseconds to wait * @return {interceptor} - the current interceptor for chaining */ Interceptor.prototype.delayConnection = function delayConnection(ms) { this.delayConnectionInMs += ms return this } Interceptor.prototype.getTotalDelay = function getTotalDelay() { return this.delayInMs + this.delayConnectionInMs } /** * Make the socket idle for a certain number of ms (simulated). * * @param {integer} ms - Number of milliseconds to wait * @return {interceptor} - the current interceptor for chaining */ Interceptor.prototype.socketDelay = function socketDelay(ms) { this.socketDelayInMs = ms return this }
lib/interceptor.js
'use strict' const mixin = require('./mixin') const matchBody = require('./match_body') const common = require('./common') const _ = require('lodash') const debug = require('debug')('nock.interceptor') const stringify = require('json-stringify-safe') const qs = require('qs') let fs try { fs = require('fs') } catch (err) { // do nothing, we're in the browser } module.exports = Interceptor function Interceptor(scope, uri, method, requestBody, interceptorOptions) { // Check for leading slash. Uri can be either a string or a regexp, but // we only need to check strings. if (typeof uri === 'string' && /^[^/*]/.test(uri)) { throw Error( "Non-wildcard URL path strings must begin with a slash (otherwise they won't match anything)" ) } this.scope = scope this.interceptorMatchHeaders = [] if (typeof method === 'undefined' || !method) { throw new Error('The "method" parameter is required for an intercept call.') } this.method = method.toUpperCase() this.uri = uri this._key = `${this.method} ${scope.basePath}${scope.basePathname}${ typeof uri === 'string' ? '' : '/' }${uri}` this.basePath = this.scope.basePath this.path = typeof uri === 'string' ? scope.basePathname + uri : uri this.baseUri = `${this.method} ${scope.basePath}${scope.basePathname}` this.options = interceptorOptions || {} this.counter = 1 this._requestBody = requestBody // We use lower-case header field names throughout Nock. this.reqheaders = common.headersFieldNamesToLowerCase( (scope.scopeOptions && scope.scopeOptions.reqheaders) || {} ) this.badheaders = common.headersFieldsArrayToLowerCase( (scope.scopeOptions && scope.scopeOptions.badheaders) || [] ) this.delayInMs = 0 this.delayConnectionInMs = 0 this.optional = false } Interceptor.prototype.optionally = function optionally(value) { // The default behaviour of optionally() with no arguments is to make the mock optional. value = typeof value === 'undefined' ? true : value this.optional = value return this } Interceptor.prototype.replyWithError = function replyWithError(errorMessage) { this.errorMessage = errorMessage _.defaults(this.options, this.scope.scopeOptions) this.scope.add(this._key, this, this.scope, this.scopeOptions) return this.scope } Interceptor.prototype.reply = function reply(statusCode, body, rawHeaders) { if (arguments.length <= 2 && _.isFunction(statusCode)) { body = statusCode statusCode = 200 } this.statusCode = statusCode _.defaults(this.options, this.scope.scopeOptions) // If needed, convert rawHeaders from Array to Object. let headers = Array.isArray(rawHeaders) ? common.headersArrayToObject(rawHeaders) : rawHeaders if (this.scope._defaultReplyHeaders) { headers = headers || {} headers = common.headersFieldNamesToLowerCase(headers) headers = mixin(this.scope._defaultReplyHeaders, headers) } if (this.scope.date) { headers = headers || {} headers['date'] = this.scope.date.toUTCString() } if (headers !== undefined) { this.rawHeaders = [] // makes sure all keys in headers are in lower case for (const key in headers) { // TODO-coverage: Remove this archaic check. if (headers.hasOwnProperty(key)) { this.rawHeaders.push(key) this.rawHeaders.push(headers[key]) } } // We use lower-case headers throughout Nock. this.headers = common.headersFieldNamesToLowerCase(headers) debug('reply.headers:', this.headers) debug('reply.rawHeaders:', this.rawHeaders) } // If the content is not encoded we may need to transform the response body. // Otherwise we leave it as it is. if (!common.isContentEncoded(this.headers)) { if ( body && typeof body !== 'string' && typeof body !== 'function' && !Buffer.isBuffer(body) && !common.isStream(body) ) { try { body = stringify(body) if (!this.headers) { this.headers = {} } if (!this.headers['content-type']) { this.headers['content-type'] = 'application/json' } if (this.scope.contentLen) { this.headers['content-length'] = body.length } } catch (err) { // TODO-coverage: Add a test covering this case. throw new Error('Error encoding response body into JSON') } } } this.body = body this.scope.add(this._key, this, this.scope, this.scopeOptions) return this.scope } Interceptor.prototype.replyWithFile = function replyWithFile( statusCode, filePath, headers ) { if (!fs) { // TODO-coverage: Add a `proxyquire` test covering this case. throw new Error('No fs') } const readStream = fs.createReadStream(filePath) readStream.pause() this.filePath = filePath return this.reply(statusCode, readStream, headers) } // Also match request headers // https://github.com/pgte/nock/issues/163 Interceptor.prototype.reqheaderMatches = function reqheaderMatches( options, key ) { // We don't try to match request headers if these weren't even specified in the request. if (!options.headers) { return true } const reqHeader = this.reqheaders[key] let header = options.headers[key] if (header && typeof header !== 'string' && header.toString) { header = header.toString() } // We skip 'host' header comparison unless it's available in both mock and actual request. // This because 'host' may get inserted by Nock itself and then get recorder. // NOTE: We use lower-case header field names throughout Nock. // TODO-coverage: This looks very special. Worth an investigation. if (key === 'host' && (_.isUndefined(header) || _.isUndefined(reqHeader))) { return true } if (!_.isUndefined(reqHeader) && !_.isUndefined(header)) { if (_.isFunction(reqHeader)) { return reqHeader(header) } else if (common.matchStringOrRegexp(header, reqHeader)) { return true } } debug("request header field doesn't match:", key, header, reqHeader) return false } Interceptor.prototype.match = function match(options, body, hostNameOnly) { if (debug.enabled) { // TODO-coverage: Find a way to work around this, or ignore it for // coverage purposes. debug('match %s, body = %s', stringify(options), stringify(body)) } if (hostNameOnly) { return options.hostname === this.scope.urlParts.hostname } const method = (options.method || 'GET').toUpperCase() let { path } = options let matches let matchKey const { proto } = options if (this.scope.transformPathFunction) { path = this.scope.transformPathFunction(path) } if (typeof body !== 'string') { body = body.toString() } if (this.scope.transformRequestBodyFunction) { body = this.scope.transformRequestBodyFunction(body, this._requestBody) } const checkHeaders = function(header) { if (_.isFunction(header.value)) { return header.value(options.getHeader(header.name)) } return common.matchStringOrRegexp( options.getHeader(header.name), header.value ) } if ( !this.scope.matchHeaders.every(checkHeaders) || !this.interceptorMatchHeaders.every(checkHeaders) ) { this.scope.logger("headers don't match") return false } const reqHeadersMatch = !this.reqheaders || Object.keys(this.reqheaders).every( this.reqheaderMatches.bind(this, options) ) if (!reqHeadersMatch) { return false } function reqheaderContains(header) { return _.has(options.headers, header) } const reqContainsBadHeaders = this.badheaders && _.some(this.badheaders, reqheaderContains) if (reqContainsBadHeaders) { return false } // If we have a filtered scope then we use it instead reconstructing // the scope from the request options (proto, host and port) as these // two won't necessarily match and we have to remove the scope that was // matched (vs. that was defined). if (this.__nock_filteredScope) { matchKey = this.__nock_filteredScope } else { matchKey = `${proto}://${options.host}` if ( options.port && options.host.indexOf(':') < 0 && (options.port !== 80 || options.proto !== 'http') && (options.port !== 443 || options.proto !== 'https') ) { matchKey += `:${options.port}` } } // Match query strings when using query() let matchQueries = true let queryIndex = -1 let queryString let queries if (this.queries) { queryIndex = path.indexOf('?') queryString = queryIndex !== -1 ? path.slice(queryIndex + 1) : '' queries = qs.parse(queryString) // Only check for query string matches if this.queries is an object if (_.isObject(this.queries)) { if (_.isFunction(this.queries)) { matchQueries = this.queries(queries) } else { // Make sure that you have an equal number of keys. We are // looping through the passed query params and not the expected values // if the user passes fewer query params than expected but all values // match this will throw a false positive. Testing that the length of the // passed query params is equal to the length of expected keys will prevent // us from doing any value checking BEFORE we know if they have all the proper // params debug('this.queries: %j', this.queries) debug('queries: %j', queries) if (_.size(this.queries) !== _.size(queries)) { matchQueries = false } else { const self = this _.forOwn(queries, function matchOneKeyVal(val, key) { const expVal = self.queries[key] let isMatch if (val === undefined || expVal === undefined) { isMatch = false } else if (expVal instanceof RegExp) { isMatch = common.matchStringOrRegexp(val, expVal) } else if (_.isArray(expVal) || _.isObject(expVal)) { isMatch = _.isEqual(val, expVal) } else { isMatch = common.matchStringOrRegexp(val, expVal) } matchQueries = matchQueries && !!isMatch }) } debug('matchQueries: %j', matchQueries) } } // Remove the query string from the path if (queryIndex !== -1) { path = path.substr(0, queryIndex) } } if (typeof this.uri === 'function') { matches = matchQueries && method === this.method && common.matchStringOrRegexp(matchKey, this.basePath) && // This is a false positive, as `uri` is not bound to `this`. // eslint-disable-next-line no-useless-call this.uri.call(this, path) } else { matches = method === this.method && common.matchStringOrRegexp(matchKey, this.basePath) && common.matchStringOrRegexp(path, this.path) && matchQueries } // special logger for query() if (queryIndex !== -1) { this.scope.logger( `matching ${matchKey}${path}?${queryString} to ${ this._key } with query(${stringify(this.queries)}): ${matches}` ) } else { this.scope.logger(`matching ${matchKey}${path} to ${this._key}: ${matches}`) } if (matches) { matches = matchBody.call(options, this._requestBody, body) if (!matches) { this.scope.logger("bodies don't match: \n", this._requestBody, '\n', body) } } return matches } Interceptor.prototype.matchIndependentOfBody = function matchIndependentOfBody( options ) { const isRegex = _.isRegExp(this.path) const isRegexBasePath = _.isRegExp(this.scope.basePath) const method = (options.method || 'GET').toUpperCase() let { path } = options const { proto } = options // NOTE: Do not split off the query params as the regex could use them if (!isRegex) { path = path ? path.split('?')[0] : '' } if (this.scope.transformPathFunction) { path = this.scope.transformPathFunction(path) } const checkHeaders = function(header) { return ( options.getHeader && common.matchStringOrRegexp(options.getHeader(header.name), header.value) ) } if ( !this.scope.matchHeaders.every(checkHeaders) || !this.interceptorMatchHeaders.every(checkHeaders) ) { return false } const comparisonKey = isRegex ? this.__nock_scopeKey : this._key const matchKey = `${method} ${proto}://${options.host}${path}` if (isRegex && !isRegexBasePath) { return !!matchKey.match(comparisonKey) && !!path.match(this.path) } if (isRegexBasePath) { return !!matchKey.match(this.scope.basePath) && !!path.match(this.path) } return comparisonKey === matchKey } Interceptor.prototype.filteringPath = function filteringPath() { if (_.isFunction(arguments[0])) { this.scope.transformFunction = arguments[0] } return this } Interceptor.prototype.discard = function discard() { if ((this.scope.shouldPersist() || this.counter > 0) && this.filePath) { this.body = fs.createReadStream(this.filePath) this.body.pause() } if (!this.scope.shouldPersist() && this.counter < 1) { this.scope.remove(this._key, this) } } Interceptor.prototype.matchHeader = function matchHeader(name, value) { this.interceptorMatchHeaders.push({ name, value }) return this } Interceptor.prototype.basicAuth = function basicAuth(options) { const username = options['user'] const password = options['pass'] || '' const name = 'authorization' const value = `Basic ${Buffer.from(`${username}:${password}`).toString( 'base64' )}` this.interceptorMatchHeaders.push({ name, value }) return this } /** * Set query strings for the interceptor * @name query * @param Object Object of query string name,values (accepts regexp values) * @public * @example * // Will match 'http://zombo.com/?q=t' * nock('http://zombo.com').get('/').query({q: 't'}); */ Interceptor.prototype.query = function query(queries) { this.queries = this.queries || {} // Allow all query strings to match this route if (queries === true) { this.queries = queries return this } if (_.isFunction(queries)) { this.queries = queries return this } let stringFormattingFn if (this.scope.scopeOptions.encodedQueryParams) { stringFormattingFn = common.percentDecode } for (const key in queries) { if (_.isUndefined(this.queries[key])) { const formattedPair = common.formatQueryValue( key, queries[key], stringFormattingFn ) this.queries[formattedPair[0]] = formattedPair[1] } } return this } /** * Set number of times will repeat the interceptor * @name times * @param Integer Number of times to repeat (should be > 0) * @public * @example * // Will repeat mock 5 times for same king of request * nock('http://zombo.com).get('/').times(5).reply(200, 'Ok'); */ Interceptor.prototype.times = function times(newCounter) { if (newCounter < 1) { return this } this.counter = newCounter return this } /** * An sugar syntax for times(1) * @name once * @see {@link times} * @public * @example * nock('http://zombo.com).get('/').once.reply(200, 'Ok'); */ Interceptor.prototype.once = function once() { return this.times(1) } /** * An sugar syntax for times(2) * @name twice * @see {@link times} * @public * @example * nock('http://zombo.com).get('/').twice.reply(200, 'Ok'); */ Interceptor.prototype.twice = function twice() { return this.times(2) } /** * An sugar syntax for times(3). * @name thrice * @see {@link times} * @public * @example * nock('http://zombo.com).get('/').thrice.reply(200, 'Ok'); */ Interceptor.prototype.thrice = function thrice() { return this.times(3) } /** * Delay the response by a certain number of ms. * * @param {(integer|object)} opts - Number of milliseconds to wait, or an object * @param {integer} [opts.head] - Number of milliseconds to wait before response is sent * @param {integer} [opts.body] - Number of milliseconds to wait before response body is sent * @return {interceptor} - the current interceptor for chaining */ Interceptor.prototype.delay = function delay(opts) { let headDelay = 0 let bodyDelay = 0 if (_.isNumber(opts)) { headDelay = opts } else if (_.isObject(opts)) { headDelay = opts.head || 0 bodyDelay = opts.body || 0 } else { throw new Error(`Unexpected input opts${opts}`) } return this.delayConnection(headDelay).delayBody(bodyDelay) } /** * Delay the response body by a certain number of ms. * * @param {integer} ms - Number of milliseconds to wait before response is sent * @return {interceptor} - the current interceptor for chaining */ Interceptor.prototype.delayBody = function delayBody(ms) { this.delayInMs += ms return this } /** * Delay the connection by a certain number of ms. * * @param {integer} ms - Number of milliseconds to wait * @return {interceptor} - the current interceptor for chaining */ Interceptor.prototype.delayConnection = function delayConnection(ms) { this.delayConnectionInMs += ms return this } Interceptor.prototype.getTotalDelay = function getTotalDelay() { return this.delayInMs + this.delayConnectionInMs } /** * Make the socket idle for a certain number of ms (simulated). * * @param {integer} ms - Number of milliseconds to wait * @return {interceptor} - the current interceptor for chaining */ Interceptor.prototype.socketDelay = function socketDelay(ms) { this.socketDelayInMs = ms return this }
refactor(interceptor): Remove an archaic check (#1430) Ref #1404
lib/interceptor.js
refactor(interceptor): Remove an archaic check (#1430)
<ide><path>ib/interceptor.js <ide> if (headers !== undefined) { <ide> this.rawHeaders = [] <ide> <del> // makes sure all keys in headers are in lower case <ide> for (const key in headers) { <del> // TODO-coverage: Remove this archaic check. <del> if (headers.hasOwnProperty(key)) { <del> this.rawHeaders.push(key) <del> this.rawHeaders.push(headers[key]) <del> } <del> } <del> <del> // We use lower-case headers throughout Nock. <add> this.rawHeaders.push(key) <add> this.rawHeaders.push(headers[key]) <add> } <add> <add> // We use lower-case headers throughout Nock. <ide> this.headers = common.headersFieldNamesToLowerCase(headers) <ide> <ide> debug('reply.headers:', this.headers)
Java
apache-2.0
7098a9400926d138a6b0451afb86328ade050e23
0
carewebframework/carewebframework-core,carewebframework/carewebframework-core,carewebframework/carewebframework-core,carewebframework/carewebframework-core
/** * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. * If a copy of the MPL was not distributed with this file, You can obtain one at * http://mozilla.org/MPL/2.0/. * * This Source Code Form is also subject to the terms of the Health-Related Additional * Disclaimer of Warranty and Limitation of Liability available at * http://www.carewebframework.org/licensing/disclaimer. */ package org.carewebframework.help; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Properties; import com.google.common.io.Files; import org.apache.commons.io.IOUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field.Store; import org.apache.lucene.document.TextField; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexWriterConfig; import org.apache.lucene.index.Term; import org.apache.lucene.search.BooleanClause.Occur; import org.apache.lucene.search.BooleanQuery; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.TopDocs; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; import org.apache.lucene.util.QueryBuilder; import org.apache.tika.Tika; import org.apache.tika.parser.html.HtmlParser; import org.carewebframework.common.MiscUtil; import org.carewebframework.common.StrUtil; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.core.io.Resource; import org.springframework.util.StringUtils; /** * Service for managing the search index and providing search capabilities using Lucene. */ public class HelpSearchService implements ApplicationContextAware { private static final Log log = LogFactory.getLog(HelpSearchService.class); /** * Callback interface for receiving search results. */ public interface IHelpSearchListener { /** * Called by search engine to report results. * * @param results List of search results (may be null to indicated no results or no search * capability). */ void onSearchComplete(List<HelpSearchHit> results); } private static class IndexTracker { private final File propertyFile; private final Properties properties = new Properties(); private boolean changed; /** * Initialize the index tracker from persistent storage. * * @param indexDirectoryPath The index directory path. The tracker properties file will be * located here. */ IndexTracker(File indexDirectoryPath) { this.propertyFile = new File(indexDirectoryPath, "tracker.properties"); try (InputStream is = new FileInputStream(propertyFile);) { properties.load(is); } catch (Exception e) { // Just ignore since we can recreate the property file. } } /** * Save the index tracker state if it has changed. */ void save() { if (changed) { try (OutputStream os = new FileOutputStream(propertyFile)) { properties.store(os, "Indexed help modules."); } catch (Exception e) { log.error("Failed to save index tracking information.", e); } changed = false; } } /** * Add a help module to the tracker data. * * @param module Help module to add. */ void add(HelpModule module) { properties.setProperty(module.getId(), module.getVersion()); changed = true; } /** * Remove a help module from the tracker data. * * @param module Help module to remove. */ void remove(HelpModule module) { properties.remove(module.getId()); changed = true; } /** * Returns true if the indexed module is the same as the loaded one. * * @param module The loaded help module. * @return True if the indexed module version is the same as the loaded one. */ boolean isSame(HelpModule module) { String v = properties.getProperty(module.getId()); if (v == null) { return false; } return v.equals(module.getVersion()); } } private static final HelpSearchService instance = new HelpSearchService(); private IndexWriter writer; private Directory indexDirectory; private IndexTracker indexTracker; private IndexSearcher indexSearcher; private IndexReader indexReader; private QueryBuilder queryBuilder; private Tika tika; private ApplicationContext appContext; public static HelpSearchService getInstance() { return instance; } /** * Enforce singleton instance. */ private HelpSearchService() { } /** * Setter for index directory path (injected by IOC container). * * @param path The index directory path (may be null or empty). * @throws IOException Unspecified IO exception. */ public void setIndexDirectory(String path) throws IOException { File indexDirectoryPath = resolveIndexDirectoryPath(path); indexDirectory = FSDirectory.open(indexDirectoryPath); indexTracker = new IndexTracker(indexDirectoryPath); } /** * Resolves the index directory path. If a path is not specified, one is created within * temporary storage. * * @param path The index directory path (may be null or empty). * @return The resolved index directory path. * @throws IOException Unspecified IO exception. */ private File resolveIndexDirectoryPath(String path) throws IOException { path = StringUtils.isEmpty(path) ? System.getProperty("java.io.tmpdir") + "/" + HelpUtil.class.getPackage().getName() : path; File dir = new File(path); Files.createParentDirs(dir); return dir; } /** * Index all HTML files within the content of the help module. * * @param helpModule Help module to be indexed. */ public void indexHelpModule(HelpModule helpModule) { try { if (indexTracker.isSame(helpModule)) { return; } unindexHelpModule(helpModule); log.info("Indexing help module " + helpModule.getId()); int i = helpModule.getUrl().lastIndexOf('/'); String pattern = "classpath:" + helpModule.getUrl().substring(0, i + 1) + "*.htm"; for (Resource resource : appContext.getResources(pattern)) { indexDocument(helpModule, resource); } writer.commit(); indexTracker.add(helpModule); } catch (Exception e) { throw MiscUtil.toUnchecked(e); } } /** * Removes the index for a help module. * * @param helpModule Help module whose index is to be removed. */ public void unindexHelpModule(HelpModule helpModule) { try { log.info("Removing index for help module " + helpModule.getId()); Term term = new Term("module", helpModule.getId()); writer.deleteDocuments(term); writer.commit(); indexTracker.remove(helpModule); } catch (IOException e) { MiscUtil.toUnchecked(e); } } /** * Index an HTML text file resource. * * @param helpModule The help module owning the resource. * @param resource The HTML text file resource. * @throws Exception Unspecified exception. */ private void indexDocument(HelpModule helpModule, Resource resource) throws Exception { String title = getTitle(resource); try (InputStream is = resource.getInputStream()) { Document document = new Document(); document.add(new TextField("module", helpModule.getId(), Store.YES)); document.add(new TextField("source", helpModule.getTitle(), Store.YES)); document.add(new TextField("title", title, Store.YES)); document.add(new TextField("url", resource.getURL().toString(), Store.YES)); document.add(new TextField("content", tika.parseToString(is), Store.NO)); writer.addDocument(document); } } /** * Extract the title of the document, if any. * * @param resource The document resource. * @return The document title, or null if not found. */ private String getTitle(Resource resource) { String title = null; try (InputStream is = resource.getInputStream()) { Iterator<String> iter = IOUtils.lineIterator(is, "UTF-8"); while (iter.hasNext()) { String line = iter.next().trim(); String lower = line.toLowerCase(); int i = lower.indexOf("<title>"); if (i > -1) { i += 7; int j = lower.indexOf("</title>", i); title = line.substring(i, j == -1 ? line.length() : j).trim(); title = title.replace("_no", "").replace('_', ' '); break; } } } catch (Exception e) { throw MiscUtil.toUnchecked(e); } return title; } /** * Performs a search query using the specified string on each registered query handler, calling * the listener for each set of results. * * @param words List of words to be located. * @param helpSets Help sets to be searched * @param listener Listener for search results. */ public void search(String words, Collection<IHelpSet> helpSets, IHelpSearchListener listener) { try { if (queryBuilder == null) { initQueryBuilder(); } Query searchForWords = queryBuilder.createBooleanQuery("content", words, Occur.MUST); Query searchForModules = queryBuilder.createBooleanQuery("module", StrUtil.fromList(helpSets, " ")); BooleanQuery query = new BooleanQuery(); query.add(searchForModules, Occur.MUST); query.add(searchForWords, Occur.MUST); TopDocs docs = indexSearcher.search(query, 9999); List<HelpSearchHit> hits = new ArrayList<>(docs.totalHits); for (ScoreDoc sdoc : docs.scoreDocs) { Document doc = indexSearcher.doc(sdoc.doc); String source = doc.get("source"); String title = doc.get("title"); String url = doc.get("url"); HelpTopic topic = new HelpTopic(new URL(url), title, source); HelpSearchHit hit = new HelpSearchHit(topic, sdoc.score); hits.add(hit); } listener.onSearchComplete(hits); } catch (Exception e) { MiscUtil.toUnchecked(e); } } /** * Initialize the index writer. * * @throws IOException Unspecified IO exception. */ public void init() throws IOException { tika = new Tika(null, new HtmlParser()); Analyzer analyzer = new StandardAnalyzer(); IndexWriterConfig config = new IndexWriterConfig(org.apache.lucene.util.Version.LATEST, analyzer); writer = new IndexWriter(indexDirectory, config); } /** * Performs a delayed initialization of the query builder to ensure that the index has been * fully created. * * @throws IOException Unspecified IO exception. */ private synchronized void initQueryBuilder() throws IOException { if (queryBuilder == null) { indexReader = DirectoryReader.open(indexDirectory); indexSearcher = new IndexSearcher(indexReader); queryBuilder = new QueryBuilder(writer.getAnalyzer()); } } /** * Release/update resources upon destruction. */ public void destroy() { try { if (indexReader != null) { indexReader.close(); } writer.close(); indexTracker.save(); } catch (IOException e) { throw MiscUtil.toUnchecked(e); } } /** * Application context is needed to iterate over help content resources. */ @Override public void setApplicationContext(ApplicationContext appContext) throws BeansException { this.appContext = appContext; } }
org.carewebframework.help-parent/org.carewebframework.help.core/src/main/java/org/carewebframework/help/HelpSearchService.java
/** * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. * If a copy of the MPL was not distributed with this file, You can obtain one at * http://mozilla.org/MPL/2.0/. * * This Source Code Form is also subject to the terms of the Health-Related Additional * Disclaimer of Warranty and Limitation of Liability available at * http://www.carewebframework.org/licensing/disclaimer. */ package org.carewebframework.help; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Properties; import com.google.common.io.Files; import org.apache.commons.io.IOUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field.Store; import org.apache.lucene.document.TextField; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexWriterConfig; import org.apache.lucene.index.Term; import org.apache.lucene.search.BooleanClause.Occur; import org.apache.lucene.search.BooleanQuery; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.TopDocs; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; import org.apache.lucene.util.QueryBuilder; import org.apache.tika.Tika; import org.apache.tika.parser.html.HtmlParser; import org.carewebframework.common.MiscUtil; import org.carewebframework.common.StrUtil; import org.carewebframework.common.Version; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.core.io.Resource; import org.springframework.util.StringUtils; /** * Service for managing the search index and providing search capabilities using Lucene. */ public class HelpSearchService implements ApplicationContextAware { private static final Log log = LogFactory.getLog(HelpSearchService.class); /** * Callback interface for receiving search results. */ public interface IHelpSearchListener { /** * Called by search engine to report results. * * @param results List of search results (may be null to indicated no results or no search * capability). */ void onSearchComplete(List<HelpSearchHit> results); } private static class IndexTracker { private final File propertyFile; private final Properties properties = new Properties(); private boolean changed; /** * Initialize the index tracker from persistent storage. * * @param indexDirectoryPath The index directory path. The tracker properties file will be * located here. */ IndexTracker(File indexDirectoryPath) { this.propertyFile = new File(indexDirectoryPath, "tracker.properties"); try (InputStream is = new FileInputStream(propertyFile);) { properties.load(is); } catch (Exception e) { // Just ignore since we can recreate the property file. } } /** * Save the index tracker state if it has changed. */ void save() { if (changed) { try (OutputStream os = new FileOutputStream(propertyFile)) { properties.store(os, "Indexed help modules."); } catch (Exception e) { log.error("Failed to save index tracking information.", e); } changed = false; } } /** * Add a help module to the tracker data. * * @param module Help module to add. */ void add(HelpModule module) { properties.setProperty(module.getId(), module.getVersion()); changed = true; } /** * Remove a help module from the tracker data. * * @param module Help module to remove. */ void remove(HelpModule module) { properties.remove(module.getId()); changed = true; } /** * Returns true if the tracked module is the same as the loaded one. * * @param module The loaded help module. * @return Try if the tracked module is current. */ boolean isCurrent(HelpModule module) { String v = properties.getProperty(module.getId()); if (v == null) { return false; } return new Version(v).equals(new Version(module.getVersion())); } } private static final HelpSearchService instance = new HelpSearchService(); private IndexWriter writer; private Directory indexDirectory; private IndexTracker indexTracker; private IndexSearcher indexSearcher; private IndexReader indexReader; private QueryBuilder queryBuilder; private Tika tika; private ApplicationContext appContext; public static HelpSearchService getInstance() { return instance; } /** * Enforce singleton instance. */ private HelpSearchService() { } /** * Setter for index directory path (injected by IOC container). * * @param path The index directory path (may be null or empty). * @throws IOException Unspecified IO exception. */ public void setIndexDirectory(String path) throws IOException { File indexDirectoryPath = resolveIndexDirectoryPath(path); indexDirectory = FSDirectory.open(indexDirectoryPath); indexTracker = new IndexTracker(indexDirectoryPath); } /** * Resolves the index directory path. If a path is not specified, one is created within * temporary storage. * * @param path The index directory path (may be null or empty). * @return The resolved index directory path. * @throws IOException Unspecified IO exception. */ private File resolveIndexDirectoryPath(String path) throws IOException { path = StringUtils.isEmpty(path) ? System.getProperty("java.io.tmpdir") + "/" + HelpUtil.class.getPackage().getName() : path; File dir = new File(path); Files.createParentDirs(dir); return dir; } /** * Index all HTML files within the content of the help module. * * @param helpModule Help module to be indexed. */ public void indexHelpModule(HelpModule helpModule) { try { if (indexTracker.isCurrent(helpModule)) { return; } unindexHelpModule(helpModule); log.info("Indexing help module " + helpModule.getId()); int i = helpModule.getUrl().lastIndexOf('/'); String pattern = "classpath:" + helpModule.getUrl().substring(0, i + 1) + "*.htm"; for (Resource resource : appContext.getResources(pattern)) { indexDocument(helpModule, resource); } writer.commit(); indexTracker.add(helpModule); } catch (Exception e) { throw MiscUtil.toUnchecked(e); } } /** * Removes the index for a help module. * * @param helpModule Help module whose index is to be removed. */ public void unindexHelpModule(HelpModule helpModule) { try { log.info("Removing index for help module " + helpModule.getId()); Term term = new Term("module", helpModule.getId()); writer.deleteDocuments(term); writer.commit(); indexTracker.remove(helpModule); } catch (IOException e) { MiscUtil.toUnchecked(e); } } /** * Index an HTML text file resource. * * @param helpModule The help module owning the resource. * @param resource The HTML text file resource. * @throws Exception Unspecified exception. */ private void indexDocument(HelpModule helpModule, Resource resource) throws Exception { String title = getTitle(resource); try (InputStream is = resource.getInputStream()) { Document document = new Document(); document.add(new TextField("module", helpModule.getId(), Store.YES)); document.add(new TextField("source", helpModule.getTitle(), Store.YES)); document.add(new TextField("title", title, Store.YES)); document.add(new TextField("url", resource.getURL().toString(), Store.YES)); document.add(new TextField("content", tika.parseToString(is), Store.NO)); writer.addDocument(document); } } /** * Extract the title of the document, if any. * * @param resource The document resource. * @return The document title, or null if not found. */ private String getTitle(Resource resource) { String title = null; try (InputStream is = resource.getInputStream()) { Iterator<String> iter = IOUtils.lineIterator(is, "UTF-8"); while (iter.hasNext()) { String line = iter.next().trim(); String lower = line.toLowerCase(); int i = lower.indexOf("<title>"); if (i > -1) { i += 7; int j = lower.indexOf("</title>", i); title = line.substring(i, j == -1 ? line.length() : j).trim(); title = title.replace("_no", "").replace('_', ' '); break; } } } catch (Exception e) { throw MiscUtil.toUnchecked(e); } return title; } /** * Performs a search query using the specified string on each registered query handler, calling * the listener for each set of results. * * @param words List of words to be located. * @param helpSets Help sets to be searched * @param listener Listener for search results. */ public void search(String words, Collection<IHelpSet> helpSets, IHelpSearchListener listener) { try { if (queryBuilder == null) { initQueryBuilder(); } Query searchForWords = queryBuilder.createBooleanQuery("content", words, Occur.MUST); Query searchForModules = queryBuilder.createBooleanQuery("module", StrUtil.fromList(helpSets, " ")); BooleanQuery query = new BooleanQuery(); query.add(searchForModules, Occur.MUST); query.add(searchForWords, Occur.MUST); TopDocs docs = indexSearcher.search(query, 9999); List<HelpSearchHit> hits = new ArrayList<>(docs.totalHits); for (ScoreDoc sdoc : docs.scoreDocs) { Document doc = indexSearcher.doc(sdoc.doc); String source = doc.get("source"); String title = doc.get("title"); String url = doc.get("url"); HelpTopic topic = new HelpTopic(new URL(url), title, source); HelpSearchHit hit = new HelpSearchHit(topic, sdoc.score); hits.add(hit); } listener.onSearchComplete(hits); } catch (Exception e) { MiscUtil.toUnchecked(e); } } /** * Initialize the index writer. * * @throws IOException Unspecified IO exception. */ public void init() throws IOException { tika = new Tika(null, new HtmlParser()); Analyzer analyzer = new StandardAnalyzer(); IndexWriterConfig config = new IndexWriterConfig(org.apache.lucene.util.Version.LATEST, analyzer); writer = new IndexWriter(indexDirectory, config); } /** * Performs a delayed initialization of the query builder to ensure that the index has been * fully created. * * @throws IOException Unspecified IO exception. */ private synchronized void initQueryBuilder() throws IOException { if (queryBuilder == null) { indexReader = DirectoryReader.open(indexDirectory); indexSearcher = new IndexSearcher(indexReader); queryBuilder = new QueryBuilder(writer.getAnalyzer()); } } /** * Release/update resources upon destruction. */ public void destroy() { try { if (indexReader != null) { indexReader.close(); } writer.close(); indexTracker.save(); } catch (IOException e) { throw MiscUtil.toUnchecked(e); } } /** * Application context is needed to iterate over help content resources. */ @Override public void setApplicationContext(ApplicationContext appContext) throws BeansException { this.appContext = appContext; } }
Minor coding change.
org.carewebframework.help-parent/org.carewebframework.help.core/src/main/java/org/carewebframework/help/HelpSearchService.java
Minor coding change.
<ide><path>rg.carewebframework.help-parent/org.carewebframework.help.core/src/main/java/org/carewebframework/help/HelpSearchService.java <ide> <ide> import org.carewebframework.common.MiscUtil; <ide> import org.carewebframework.common.StrUtil; <del>import org.carewebframework.common.Version; <ide> <ide> import org.springframework.beans.BeansException; <ide> import org.springframework.context.ApplicationContext; <ide> } <ide> <ide> /** <del> * Returns true if the tracked module is the same as the loaded one. <add> * Returns true if the indexed module is the same as the loaded one. <ide> * <ide> * @param module The loaded help module. <del> * @return Try if the tracked module is current. <del> */ <del> boolean isCurrent(HelpModule module) { <add> * @return True if the indexed module version is the same as the loaded one. <add> */ <add> boolean isSame(HelpModule module) { <ide> String v = properties.getProperty(module.getId()); <ide> <ide> if (v == null) { <ide> return false; <ide> } <ide> <del> return new Version(v).equals(new Version(module.getVersion())); <add> return v.equals(module.getVersion()); <ide> } <ide> } <ide> <ide> */ <ide> public void indexHelpModule(HelpModule helpModule) { <ide> try { <del> if (indexTracker.isCurrent(helpModule)) { <add> if (indexTracker.isSame(helpModule)) { <ide> return; <ide> } <ide>
Java
apache-2.0
fb0ec32a0673b6ecebfcb17522c439f5206397b6
0
GiraffaFS/giraffa,GiraffaFS/giraffa,GiraffaFS/giraffa,GiraffaFS/giraffa
/** * 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.giraffa; import java.io.FileNotFoundException; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.EnumSet; import java.util.List; import java.util.Map; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.ContentSummary; import org.apache.hadoop.fs.CreateFlag; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Options; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.XAttrSetFlag; import org.apache.hadoop.fs.permission.FsPermission; import org.apache.hadoop.hdfs.GiraffaClient; import org.apache.hadoop.hdfs.protocol.DirectoryListing; import org.apache.hadoop.hdfs.protocol.HdfsFileStatus; import org.apache.hadoop.io.IOUtils; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.util.Progressable; /** * Implementation of Giraffa FileSystem. * Giraffa stores its namespace in HBase table and retrieves data from * HDFS blocks, residing on DataNodes. */ public class GiraffaFileSystem extends FileSystem { GiraffaClient grfaClient; private URI hdfsUri; private URI hbaseUri; private Path workingDir; private URI uri; public GiraffaFileSystem() { // should be empty } @Override // FileSystem public FSDataOutputStream append(Path f, int bufferSize, Progressable progress) throws IOException { // Not implemented throw new IOException("append: Implement me. It is not easy."); } @Override public FSDataOutputStream create(Path f, FsPermission permission, EnumSet<CreateFlag> flags, int bufferSize, short replication, long blockSize, Progressable progress, Options.ChecksumOpt checksumOpt) throws IOException { return new FSDataOutputStream( grfaClient.create(getPathName(f), permission, flags, replication, blockSize, progress, bufferSize, checksumOpt), statistics); } @Override public FSDataOutputStream create(Path f, FsPermission permission, boolean overwrite, int bufferSize, short replication, long blockSize, Progressable progressable) throws IOException { return create(f, permission, overwrite ? EnumSet.of(CreateFlag.CREATE, CreateFlag.OVERWRITE) : EnumSet.of(CreateFlag.CREATE), bufferSize, replication, blockSize, progressable, new Options.ChecksumOpt( getServerDefaults(f).getChecksumType(), getServerDefaults(f).getBytesPerChecksum())); } @Override // FileSystem public boolean delete(Path f, boolean recursive) throws IOException { return grfaClient.delete(getPathName(f), recursive); } public static void format(GiraffaConfiguration conf, boolean isConfirmationNeeded) throws IOException { if (isConfirmationNeeded) { System.err.print("Re-format Giraffa file system ? (Y or N) "); int flag = System.in.read(); if (!(flag == 'Y') && !(flag == 'y')) { System.err.println("Format aborted."); return; } while(System.in.read() != '\n'); } GiraffaClient.format(conf); GiraffaFileSystem grfs = null; try { grfs = (GiraffaFileSystem) FileSystem.get(conf); grfs.mkdirs(grfs.workingDir); } finally { IOUtils.cleanup(LOG, grfs); } } @Override // FileSystem public ContentSummary getContentSummary(Path f) throws IOException { HdfsFileStatus s = grfaClient.getFileInfo(getPathName(f)); if (!s.isDir()) { // f is a file return new ContentSummary(s.getLen(), 1, 0, -1, s.getLen()*s.getReplication(), -1); } // f is a directory ContentSummary start = grfaClient.getContentSummary(getPathName(f)); HdfsFileStatus[] list = grfaClient.listPaths(getPathName(f), HdfsFileStatus.EMPTY_NAME).getPartialListing(); long[] summary = {0, 0, 1, start.getQuota(), 0, start.getSpaceQuota()}; for(HdfsFileStatus t : list) { Path path = t.getFullPath(f).makeQualified(getUri(), getWorkingDirectory()); // recursive if directory, else return file stats ContentSummary c = t.isDir() ? getContentSummary(path) : new ContentSummary(t.getLen(), 1, 0, -1, t.getLen()*t.getReplication(), -1); // compound results summary[0] += c.getLength(); summary[1] += c.getFileCount(); summary[2] += c.getDirectoryCount(); summary[4] += c.getSpaceConsumed(); } return new ContentSummary(summary[0], summary[1], summary[2], summary[3], summary[4], summary[5]); } @Override // FileSystem public FileStatus getFileStatus(Path f) throws IOException { HdfsFileStatus hdfsStatus = grfaClient.getFileInfo(getPathName(f)); if (hdfsStatus == null) throw new FileNotFoundException("File does not exist: " + f); return createFileStatus(hdfsStatus, f); } private FileStatus createFileStatus(HdfsFileStatus hdfsStatus, Path src) { return new FileStatus(hdfsStatus.getLen(), hdfsStatus.isDir(), hdfsStatus.getReplication(), hdfsStatus.getBlockSize(), hdfsStatus.getModificationTime(), hdfsStatus.getAccessTime(), hdfsStatus.getPermission(), hdfsStatus.getOwner(), hdfsStatus.getGroup(), (hdfsStatus.isSymlink() ? new Path(hdfsStatus.getSymlink()) : null), (hdfsStatus.getFullPath(src)).makeQualified( getUri(), getWorkingDirectory())); // fully-qualify path } URI getHBaseUri() { return hbaseUri; } URI getHDFSUri() { return hdfsUri; } @Override // FileSystem public URI getUri() { return uri; } @Override // FileSystem public Path getWorkingDirectory() { return workingDir; } @Override public String getScheme() { return GiraffaConfiguration.GRFA_URI_SCHEME; } @Override // FileSystem public void initialize(URI theUri, Configuration conf) throws IOException { GiraffaConfiguration grfaConf = conf instanceof GiraffaConfiguration ? (GiraffaConfiguration) conf : new GiraffaConfiguration(conf); super.initialize(theUri, grfaConf); // Initialize HDFS Client -- SHV!!! Not used try { this.setHDFSUri(new URI( conf.get(GiraffaConfiguration.GRFA_HDFS_ADDRESS_KEY, GiraffaConfiguration.GRFA_HDFS_ADDRESS_DEFAULT))); } catch (URISyntaxException e) { throw new IOException("Incorrect URI for " + GiraffaConfiguration.GRFA_HDFS_ADDRESS_KEY, e); } // Initialize HBase Client -- SHV!!! Not used try { this.setHBaseUri(new URI( conf.get(GiraffaConfiguration.GRFA_HBASE_ADDRESS_KEY, GiraffaConfiguration.GRFA_HBASE_ADDRESS_DEFAULT))); } catch (URISyntaxException e) { throw new IOException("Incorrect URI for " + GiraffaConfiguration.GRFA_HBASE_ADDRESS_KEY, e); } // closing this.uri = theUri; this.workingDir = makeQualified(new Path("/user/" + UserGroupInformation.getCurrentUser().getShortUserName())); grfaClient = new GiraffaClient(grfaConf, statistics); LOG.debug("uri = " + uri); LOG.debug("workingDir = " + workingDir); } private String getPathName(Path file) { return normalizePath(makeQualified(file).toUri().getPath()); } static String normalizePath(String src) { if (src.length() > 1 && src.endsWith("/")) { src = src.substring(0, src.length() - 1); } return src; } @Override // FileSystem public FileStatus[] listStatus(Path f) throws FileNotFoundException, IOException { String src = getPathName(f); // fetch the first batch of entries in the directory DirectoryListing thisListing = grfaClient.listPaths( src, HdfsFileStatus.EMPTY_NAME); if (thisListing == null) { // the directory does not exist throw new FileNotFoundException("File " + f + " does not exist."); } FileStatus[] fs = new FileStatus[thisListing.getPartialListing().length]; for(int i = 0; i < fs.length; i++) { HdfsFileStatus hdfsStatus = thisListing.getPartialListing()[i]; fs[i] = createFileStatus(hdfsStatus, f); } return fs; } @Override // FileSystem public boolean mkdirs(Path f, FsPermission permission) throws IOException { return grfaClient.mkdirs(getPathName(f), permission, true); } @Override // FileSystem public FSDataInputStream open(Path f, int bufferSize) throws IOException { return new FSDataInputStream( grfaClient.open(getPathName(f), bufferSize, true)); } @SuppressWarnings("deprecation") @Override public boolean rename(Path src, Path dst) throws IOException { return grfaClient.rename(getPathName(src), getPathName(dst)); } @Override // FileSystem public void rename(Path src, Path dst, Options.Rename... options) throws IOException { grfaClient.rename(getPathName(src), getPathName(dst), options); } void setHBaseUri(URI hBaseUri) { hbaseUri = hBaseUri; } void setHDFSUri(URI hDFSUri) { hdfsUri = hDFSUri; } @Override // FileSystem public boolean setReplication(Path p, short replication) throws IOException { return grfaClient.setReplication(getPathName(p), replication); } @Override // FileSystem public void setOwner(Path p, String username, String groupname) throws IOException { grfaClient.setOwner(getPathName(p), username, groupname); } @Override // FileSystem public void setPermission(Path p, FsPermission permission) throws IOException { grfaClient.setPermission(getPathName(p), permission); } @Override // FileSystem public void setTimes(Path p, long mtime, long atime) throws IOException { grfaClient.setTimes(getPathName(p), mtime, atime); } public void setQuota(Path src, long namespaceQuota, long diskspaceQuota) throws IOException { grfaClient.setQuota(getPathName(src), namespaceQuota, diskspaceQuota); } @Override // FileSystem public void setWorkingDirectory(Path new_dir) { workingDir = makeQualified( new_dir.isAbsolute() ? new_dir : new Path(workingDir, new_dir)); checkPath(workingDir); } @Override // FileSystem public void setXAttr(Path path, String name, byte[] value, EnumSet<XAttrSetFlag> flag) throws IOException { grfaClient.setXAttr(getPathName(path), name, value, flag); } @Override // FileSystem public List<String> listXAttrs(Path path) throws IOException { return grfaClient.listXAttrs(getPathName(path)); } @Override // FileSystem public byte[] getXAttr(Path path, String name) throws IOException { return grfaClient.getXAttr(getPathName(path), name); } @Override // FileSystem public Map<String, byte[]> getXAttrs(Path path) throws IOException { return grfaClient.getXAttrs(getPathName(path)); } @Override // FileSystem public Map<String, byte[]> getXAttrs(Path path, List<String> names) throws IOException { return grfaClient.getXAttrs(getPathName(path), names); } @Override // FileSystem public void removeXAttr(Path path, String name) throws IOException { grfaClient.removeXAttr(getPathName(path), name); } @Override // FileSystem public void close() throws IOException { super.close(); grfaClient.close(); } public static void main(String argv[]) throws Exception { try { GiraffaConfiguration conf = new GiraffaConfiguration(); if(argv.length > 0 && "format".equals(argv[0].toLowerCase())) GiraffaFileSystem.format(conf, true); } catch (Throwable e) { LOG.error(e); System.exit(-1); } } }
giraffa-core/src/main/java/org/apache/giraffa/GiraffaFileSystem.java
/** * 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.giraffa; import java.io.FileNotFoundException; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.EnumSet; import java.util.List; import java.util.Map; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.ContentSummary; import org.apache.hadoop.fs.CreateFlag; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Options; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.XAttrSetFlag; import org.apache.hadoop.fs.permission.FsPermission; import org.apache.hadoop.hdfs.GiraffaClient; import org.apache.hadoop.hdfs.protocol.DirectoryListing; import org.apache.hadoop.hdfs.protocol.HdfsFileStatus; import org.apache.hadoop.io.IOUtils; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.util.Progressable; /** * Implementation of Giraffa FileSystem. * Giraffa stores its namespace in HBase table and retrieves data from * HDFS blocks, residing on DataNodes. */ public class GiraffaFileSystem extends FileSystem { GiraffaClient grfaClient; private URI hdfsUri; private URI hbaseUri; private Path workingDir; private URI uri; public GiraffaFileSystem() { // should be empty } @Override // FileSystem public FSDataOutputStream append(Path f, int bufferSize, Progressable progress) throws IOException { // Not implemented throw new IOException("append: Implement me. It is not easy."); } @Override public FSDataOutputStream create(Path f, FsPermission permission, EnumSet<CreateFlag> flags, int bufferSize, short replication, long blockSize, Progressable progress, Options.ChecksumOpt checksumOpt) throws IOException { return new FSDataOutputStream( grfaClient.create(getPathName(f), permission, flags, replication, blockSize, progress, bufferSize, checksumOpt), statistics); } @Override public FSDataOutputStream create(Path f, FsPermission permission, boolean overwrite, int bufferSize, short replication, long blockSize, Progressable progressable) throws IOException { return create(f, permission, overwrite ? EnumSet.of(CreateFlag.CREATE, CreateFlag.OVERWRITE) : EnumSet.of(CreateFlag.CREATE), bufferSize, replication, blockSize, progressable, new Options.ChecksumOpt( getServerDefaults(f).getChecksumType(), getServerDefaults(f).getBytesPerChecksum())); } @Override // FileSystem public boolean delete(Path f, boolean recursive) throws IOException { return grfaClient.delete(getPathName(f), recursive); } public static void format(GiraffaConfiguration conf, boolean isConfirmationNeeded) throws IOException { if (isConfirmationNeeded) { System.err.print("Re-format Giraffa file system ? (Y or N) "); if (!(System.in.read() == 'Y')) { System.err.println("Format aborted."); return; } while(System.in.read() != '\n'); } GiraffaClient.format(conf); GiraffaFileSystem grfs = null; try { grfs = (GiraffaFileSystem) FileSystem.get(conf); grfs.mkdirs(grfs.workingDir); } finally { IOUtils.cleanup(LOG, grfs); } } @Override // FileSystem public ContentSummary getContentSummary(Path f) throws IOException { HdfsFileStatus s = grfaClient.getFileInfo(getPathName(f)); if (!s.isDir()) { // f is a file return new ContentSummary(s.getLen(), 1, 0, -1, s.getLen()*s.getReplication(), -1); } // f is a directory ContentSummary start = grfaClient.getContentSummary(getPathName(f)); HdfsFileStatus[] list = grfaClient.listPaths(getPathName(f), HdfsFileStatus.EMPTY_NAME).getPartialListing(); long[] summary = {0, 0, 1, start.getQuota(), 0, start.getSpaceQuota()}; for(HdfsFileStatus t : list) { Path path = t.getFullPath(f).makeQualified(getUri(), getWorkingDirectory()); // recursive if directory, else return file stats ContentSummary c = t.isDir() ? getContentSummary(path) : new ContentSummary(t.getLen(), 1, 0, -1, t.getLen()*t.getReplication(), -1); // compound results summary[0] += c.getLength(); summary[1] += c.getFileCount(); summary[2] += c.getDirectoryCount(); summary[4] += c.getSpaceConsumed(); } return new ContentSummary(summary[0], summary[1], summary[2], summary[3], summary[4], summary[5]); } @Override // FileSystem public FileStatus getFileStatus(Path f) throws IOException { HdfsFileStatus hdfsStatus = grfaClient.getFileInfo(getPathName(f)); if (hdfsStatus == null) throw new FileNotFoundException("File does not exist: " + f); return createFileStatus(hdfsStatus, f); } private FileStatus createFileStatus(HdfsFileStatus hdfsStatus, Path src) { return new FileStatus(hdfsStatus.getLen(), hdfsStatus.isDir(), hdfsStatus.getReplication(), hdfsStatus.getBlockSize(), hdfsStatus.getModificationTime(), hdfsStatus.getAccessTime(), hdfsStatus.getPermission(), hdfsStatus.getOwner(), hdfsStatus.getGroup(), (hdfsStatus.isSymlink() ? new Path(hdfsStatus.getSymlink()) : null), (hdfsStatus.getFullPath(src)).makeQualified( getUri(), getWorkingDirectory())); // fully-qualify path } URI getHBaseUri() { return hbaseUri; } URI getHDFSUri() { return hdfsUri; } @Override // FileSystem public URI getUri() { return uri; } @Override // FileSystem public Path getWorkingDirectory() { return workingDir; } @Override public String getScheme() { return GiraffaConfiguration.GRFA_URI_SCHEME; } @Override // FileSystem public void initialize(URI theUri, Configuration conf) throws IOException { GiraffaConfiguration grfaConf = conf instanceof GiraffaConfiguration ? (GiraffaConfiguration) conf : new GiraffaConfiguration(conf); super.initialize(theUri, grfaConf); // Initialize HDFS Client -- SHV!!! Not used try { this.setHDFSUri(new URI( conf.get(GiraffaConfiguration.GRFA_HDFS_ADDRESS_KEY, GiraffaConfiguration.GRFA_HDFS_ADDRESS_DEFAULT))); } catch (URISyntaxException e) { throw new IOException("Incorrect URI for " + GiraffaConfiguration.GRFA_HDFS_ADDRESS_KEY, e); } // Initialize HBase Client -- SHV!!! Not used try { this.setHBaseUri(new URI( conf.get(GiraffaConfiguration.GRFA_HBASE_ADDRESS_KEY, GiraffaConfiguration.GRFA_HBASE_ADDRESS_DEFAULT))); } catch (URISyntaxException e) { throw new IOException("Incorrect URI for " + GiraffaConfiguration.GRFA_HBASE_ADDRESS_KEY, e); } // closing this.uri = theUri; this.workingDir = makeQualified(new Path("/user/" + UserGroupInformation.getCurrentUser().getShortUserName())); grfaClient = new GiraffaClient(grfaConf, statistics); LOG.debug("uri = " + uri); LOG.debug("workingDir = " + workingDir); } private String getPathName(Path file) { return normalizePath(makeQualified(file).toUri().getPath()); } static String normalizePath(String src) { if (src.length() > 1 && src.endsWith("/")) { src = src.substring(0, src.length() - 1); } return src; } @Override // FileSystem public FileStatus[] listStatus(Path f) throws FileNotFoundException, IOException { String src = getPathName(f); // fetch the first batch of entries in the directory DirectoryListing thisListing = grfaClient.listPaths( src, HdfsFileStatus.EMPTY_NAME); if (thisListing == null) { // the directory does not exist throw new FileNotFoundException("File " + f + " does not exist."); } FileStatus[] fs = new FileStatus[thisListing.getPartialListing().length]; for(int i = 0; i < fs.length; i++) { HdfsFileStatus hdfsStatus = thisListing.getPartialListing()[i]; fs[i] = createFileStatus(hdfsStatus, f); } return fs; } @Override // FileSystem public boolean mkdirs(Path f, FsPermission permission) throws IOException { return grfaClient.mkdirs(getPathName(f), permission, true); } @Override // FileSystem public FSDataInputStream open(Path f, int bufferSize) throws IOException { return new FSDataInputStream( grfaClient.open(getPathName(f), bufferSize, true)); } @SuppressWarnings("deprecation") @Override public boolean rename(Path src, Path dst) throws IOException { return grfaClient.rename(getPathName(src), getPathName(dst)); } @Override // FileSystem public void rename(Path src, Path dst, Options.Rename... options) throws IOException { grfaClient.rename(getPathName(src), getPathName(dst), options); } void setHBaseUri(URI hBaseUri) { hbaseUri = hBaseUri; } void setHDFSUri(URI hDFSUri) { hdfsUri = hDFSUri; } @Override // FileSystem public boolean setReplication(Path p, short replication) throws IOException { return grfaClient.setReplication(getPathName(p), replication); } @Override // FileSystem public void setOwner(Path p, String username, String groupname) throws IOException { grfaClient.setOwner(getPathName(p), username, groupname); } @Override // FileSystem public void setPermission(Path p, FsPermission permission) throws IOException { grfaClient.setPermission(getPathName(p), permission); } @Override // FileSystem public void setTimes(Path p, long mtime, long atime) throws IOException { grfaClient.setTimes(getPathName(p), mtime, atime); } public void setQuota(Path src, long namespaceQuota, long diskspaceQuota) throws IOException { grfaClient.setQuota(getPathName(src), namespaceQuota, diskspaceQuota); } @Override // FileSystem public void setWorkingDirectory(Path new_dir) { workingDir = makeQualified( new_dir.isAbsolute() ? new_dir : new Path(workingDir, new_dir)); checkPath(workingDir); } @Override // FileSystem public void setXAttr(Path path, String name, byte[] value, EnumSet<XAttrSetFlag> flag) throws IOException { grfaClient.setXAttr(getPathName(path), name, value, flag); } @Override // FileSystem public List<String> listXAttrs(Path path) throws IOException { return grfaClient.listXAttrs(getPathName(path)); } @Override // FileSystem public byte[] getXAttr(Path path, String name) throws IOException { return grfaClient.getXAttr(getPathName(path), name); } @Override // FileSystem public Map<String, byte[]> getXAttrs(Path path) throws IOException { return grfaClient.getXAttrs(getPathName(path)); } @Override // FileSystem public Map<String, byte[]> getXAttrs(Path path, List<String> names) throws IOException { return grfaClient.getXAttrs(getPathName(path), names); } @Override // FileSystem public void removeXAttr(Path path, String name) throws IOException { grfaClient.removeXAttr(getPathName(path), name); } @Override // FileSystem public void close() throws IOException { super.close(); grfaClient.close(); } public static void main(String argv[]) throws Exception { try { GiraffaConfiguration conf = new GiraffaConfiguration(); if(argv.length > 0 && "format".equals(argv[0].toLowerCase())) GiraffaFileSystem.format(conf, true); } catch (Throwable e) { LOG.error(e); System.exit(-1); } } }
Issue-223: giraffa format should allow lower case 'y'. (Yuxiang)
giraffa-core/src/main/java/org/apache/giraffa/GiraffaFileSystem.java
Issue-223: giraffa format should allow lower case 'y'. (Yuxiang)
<ide><path>iraffa-core/src/main/java/org/apache/giraffa/GiraffaFileSystem.java <ide> boolean isConfirmationNeeded) throws IOException { <ide> if (isConfirmationNeeded) { <ide> System.err.print("Re-format Giraffa file system ? (Y or N) "); <del> if (!(System.in.read() == 'Y')) { <add> int flag = System.in.read(); <add> if (!(flag == 'Y') && !(flag == 'y')) { <ide> System.err.println("Format aborted."); <ide> return; <ide> }
JavaScript
apache-2.0
fdbdabe8a0a95aae2c22b821d3f76113103f11fd
0
GetThereSafe/GetThereSafe-nwHacks,GetThereSafe/GetThereSafe-nwHacks,GetThereSafe/GetThereSafe-nwHacks
var map; var polylines = []; function initMap() { console.log('init called'); var mapDiv = document.getElementById('map'); map = new google.maps.Map(mapDiv, { center: {lat: 48.428611, lng: -123.365556}, zoom: 14 }); } function mapRoute(routes) { console.log('mapRoute called'); console.log(routes); for(var j = 0; j < routes.length; j++){ latlngPoints = []; for(var i = 0; i < routes[j][2].length; i++) { latlngPoints.push({lat: routes[j][2][i][0], lng: routes[j][2][i][1]}); } console.log(latlngPoints); var strokeColor = '#FF0000'; var strokeWeight = 3; if(j >= 1){ strokeColor = '#0000FF'; strokeWeight = 1.5; } var polyline = new google.maps.Polyline({ path: latlngPoints, geodesic: true, strokeColor: strokeColor, strokeOpacity: 0.5, strokeWeight: strokeWeight }); polyline.setMap(map); polylines.push(polyline); } $("#info-text").text("Best route found with " + routes[0][0] + " street lights"); $("#info").show(); } function getRoutes(starting_point, ending_point) { console.log(starting_point); $("#error").hide(); $("#info").hide(); $("#spinner").show(); $.ajax({ url: '/route', type: 'POST', data: { start: starting_point, end:ending_point}, success: function(data) { routes = JSON.parse(data); console.log(routes); mapRoute(routes); }, error: function() { $("#error").show(); } }).always(function() { $("#spinner").hide(); }); } $("#bttn").click(function() { starting_point = $("#starting_point").val(); ending_point = $("#ending_point").val(); // Remove current path if(!!polylines) { for(var i = 0; i < polylines.length; i++) { polylines[i].setMap(null); } } routes = getRoutes(starting_point, ending_point); });
static/js/scripts.js
var map; var polylines = []; function initMap() { console.log('init called'); var mapDiv = document.getElementById('map'); map = new google.maps.Map(mapDiv, { center: {lat: 48.428611, lng: -123.365556}, zoom: 14 }); } function mapRoute(routes) { console.log('mapRoute called'); console.log(routes); for(var j = 0; j < routes.length; j++){ latlngPoints = []; for(var i = 0; i < routes[j][2].length; i++) { latlngPoints.push({lat: routes[j][2][i][0], lng: routes[j][2][i][1]}); } console.log(latlngPoints); var strokeColor = '#FF0000'; var strokeWeight = 3; if(j >= 1){ strokeColor = '#0000FF'; strokeWeight = 1.5; } var polyline = new google.maps.Polyline({ path: latlngPoints, geodesic: true, strokeColor: strokeColor, strokeOpacity: 0.5, strokeWeight: strokeWeight }); polyline.setMap(map); polylines.push(polyline); } $("#info-text").text("Best route found with " + routes[0][2] +" street lights"); $("#info").show(); } function getRoutes(starting_point, ending_point) { console.log(starting_point); $("#error").hide(); $("#info").hide(); $("#spinner").show(); $.ajax({ url: '/route', type: 'POST', data: { start: starting_point, end:ending_point}, success: function(data) { routes = JSON.parse(data); console.log(routes); mapRoute(routes); }, error: function() { $("#error").show(); } }).always(function() { $("#spinner").hide(); }); } $("#bttn").click(function() { starting_point = $("#starting_point").val(); ending_point = $("#ending_point").val(); // Remove current path if(!!polylines) { for(var i = 0; i < polylines.length; i++) { polylines[i].setMap(null); } } routes = getRoutes(starting_point, ending_point); });
info text
static/js/scripts.js
info text
<ide><path>tatic/js/scripts.js <ide> polylines.push(polyline); <ide> } <ide> <del> $("#info-text").text("Best route found with " + routes[0][2] +" street lights"); <add> $("#info-text").text("Best route found with " + routes[0][0] + " street lights"); <ide> $("#info").show(); <ide> } <ide>
Java
apache-2.0
8d41b160820224cc3f4204a8924eeb4bfde1062b
0
stefanorosanelli/jasper-service,stefanorosanelli/jasper-service
package net.bedita.export.jasper; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Locale; import java.util.Map; import net.sf.jasperreports.engine.JRException; import net.sf.jasperreports.engine.JRParameter; import net.sf.jasperreports.engine.JasperCompileManager; import net.sf.jasperreports.engine.JasperExportManager; import net.sf.jasperreports.engine.JasperFillManager; import net.sf.jasperreports.engine.JasperPrint; import net.sf.jasperreports.engine.export.JRRtfExporter; import net.sf.jasperreports.engine.export.oasis.JROdtExporter; import net.sf.jasperreports.engine.export.ooxml.JRDocxExporter; import net.sf.jasperreports.engine.query.JRXPathQueryExecuterFactory; import net.sf.jasperreports.engine.util.JRLoader; import net.sf.jasperreports.engine.util.JRXmlUtils; import net.sf.jasperreports.export.SimpleExporterInput; import net.sf.jasperreports.export.SimpleOutputStreamExporterOutput; import net.sf.jasperreports.export.SimpleWriterExporterOutput; import org.apache.commons.cli.BasicParser; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.w3c.dom.Document; public class JasperProcess { protected final Log log = LogFactory.getLog(getClass()); static protected Options options; /** * @param args * @throws JRException * @throws IOException * @throws ParseException */ public static void main(String[] args) throws JRException, IOException { try { // create the parser CommandLineParser parser = new BasicParser(); Options options = initOptions(); CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("h")) { usage(); return; } JasperProcess jasperProc = new JasperProcess(); if (cmd.hasOption("c")) { jasperProc.compileDir(cmd.getOptionValue("c")); return; } String report = cmd.getOptionValue("r"); String sub = cmd.getOptionValue("s"); String[] subReports = {}; if (sub != null) { subReports = sub.split(","); } String dataFile = cmd.getOptionValue("d"); String destFile = cmd.getOptionValue("o"); if (report == null || dataFile == null || destFile == null) { throw new ParseException("Missing parameters"); } String userParamsStr = cmd.getOptionValue("p"); Map<String, String> userParams = new HashMap<String, String>(); if (userParamsStr != null) { String[] p = {}; p = userParamsStr.split(","); for (String kv : p) { String[] keyVal = kv.split("="); if (keyVal.length != 2) { throw new ParseException("Bad parameter: " + kv); } userParams.put(keyVal[0], keyVal[1]); } } jasperProc.generate(report, subReports, dataFile, destFile, userParams); System.out.println("output file created: " + destFile); } catch (ParseException ex) { System.out.println("jasper-service stopped with errors"); System.err.println("error parsing commandline: " + ex.getMessage()); usage(); } } static public void usage() { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("jasper-service", options, true); } public void generate(String report, String[] subReports, String dataFile, String destFile, Map<String, String> userParams) throws IOException, JRException { // compile if needed compileReports(report, subReports); // prepare params Map<String, Object> params = readDataFile(dataFile); for (String k : userParams.keySet()) { params.put(k, userParams.get(k)); } log.debug("generating print data"); JasperPrint print = JasperFillManager.fillReport(report, params); log.debug("exporting to file: " + destFile); String extension = destFile.substring(destFile.lastIndexOf('.')+1).toLowerCase(); if("pdf".equals(extension)) { log.debug("using pdf format"); pdf(print, destFile); } else if("docx".equals(extension)) { log.debug("using docx format"); docx(print, destFile); } else if("rtf".equals(extension)) { log.debug("using rtf format"); rtf(print, destFile); } else if("odt".equals(extension)) { log.debug("using odt format"); odt(print, destFile); } else { log.warn("unsupported format for file: " + destFile); System.out.println("unsupported format for file: " + destFile); System.out.println("supported formats: pdf, docx, rtf and odt"); } } /** * Init options, parse arguments */ static private Options initOptions() { options = new Options(); // report option Option r = new Option("r", "report", true, "jasper report file path (.jasper file), absolute or relative"); options.addOption(r); // data file option Option d = new Option("d", "data-file", true, "data file path (i.e. .xml data file"); options.addOption(d); // param option Option p = new Option("p", "param", true, "comma separated list of params in this form: name1=value1,name2=value2"); options.addOption(p); // output file option Option o = new Option("o", "output", true, "output file path"); options.addOption(o); // subreport files option Option s = new Option("s", "sub-reports", true, "comma separeted list of jasper subreports file paths"); options.addOption(s); // compile directory option Option c = new Option("c", "compile-dir", true, "directory path containing .jrxml files to compile"); options.addOption(c); // help option options.addOption("h", "help", false, "this help message"); return options; } protected void compileDir(String dirPath) throws IOException, JRException { log.info("compiling reports in: " + dirPath); File dir = new File(dirPath); for (File fileEntry : dir.listFiles()) { if (!fileEntry.isDirectory()) { String filePath = fileEntry.getAbsolutePath(); int dotPos = filePath.lastIndexOf("."); if (dotPos != -1) { String extension = filePath.substring(dotPos); if (extension.equals(".jrxml")) { String jasperFile = filePath.substring(0, dotPos) + ".jasper"; compileReport(jasperFile); } } } } } protected void compileReports(String report, String[] subReports) throws IOException, JRException { log.info("compiling report: " + report); compileReport(report); for (String subRep : subReports) { log.info("compiling subreport: " + subRep); compileReport(subRep); } } protected Map<String, Object> readDataFile(String xmlDataFile) throws JRException { Document document = JRXmlUtils.parse(JRLoader.getLocationInputStream(xmlDataFile)); Map<String, Object> params = new HashMap<String, Object>(); params.put(JRXPathQueryExecuterFactory.PARAMETER_XML_DATA_DOCUMENT, document); params.put(JRXPathQueryExecuterFactory.XML_DATE_PATTERN, "yyyy-MM-dd"); params.put(JRXPathQueryExecuterFactory.XML_NUMBER_PATTERN, "#,##0.##"); params.put(JRXPathQueryExecuterFactory.XML_LOCALE, Locale.ENGLISH); params.put(JRParameter.REPORT_LOCALE, Locale.US); return params; } protected void pdf(JasperPrint print, String destFile) throws JRException, IOException { log.debug("exporting to pdf file: " + destFile); JasperExportManager.exportReportToPdfFile(print, destFile); } protected void docx(JasperPrint print, String destFile) throws JRException, IOException { log.debug("exporting to docx file: " + destFile); JRDocxExporter exporter = new JRDocxExporter(); exporter.setExporterInput(new SimpleExporterInput(print)); exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(destFile)); exporter.exportReport(); } protected void odt(JasperPrint print, String destFile) throws JRException, IOException { log.debug("exporting to odt file: " + destFile); JROdtExporter exporter = new JROdtExporter(); exporter.setExporterInput(new SimpleExporterInput(print)); exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(destFile)); exporter.exportReport(); } protected void rtf(JasperPrint print, String destFile) throws JRException, IOException { log.debug("exporting to rtf file: " + destFile); JRRtfExporter exporter = new JRRtfExporter(); exporter.setExporterInput(new SimpleExporterInput(print)); exporter.setExporterOutput(new SimpleWriterExporterOutput(destFile)); exporter.exportReport(); } /** * Compile jasper .jrxml source file if compiled .jasper is missing or older than source * * @param filename * @return JasperReport * @throws IOException * @throws JRException */ private void compileReport(String jasperFileName) throws IOException, JRException { if (!jasperFileName.endsWith(".jasper")) { throw new JRException("Bad file extension, should be .jasper: " + jasperFileName); } String sourceFileName = jasperFileName.substring(0, jasperFileName.length()-7) + ".jrxml"; File source = new File(sourceFileName); File compiled = new File(jasperFileName); if (!source.exists()) { throw new IOException("Missing source JRXML file " + sourceFileName); } if(!compiled.exists() || (compiled.lastModified() < source.lastModified())) { log.debug("compiling source report: " + sourceFileName); JasperCompileManager.compileReportToFile(sourceFileName, jasperFileName); } else { log.debug("source report compilation not needed"); } } }
src/net/bedita/export/jasper/JasperProcess.java
package net.bedita.export.jasper; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Locale; import java.util.Map; import net.sf.jasperreports.engine.JRException; import net.sf.jasperreports.engine.JRParameter; import net.sf.jasperreports.engine.JasperCompileManager; import net.sf.jasperreports.engine.JasperExportManager; import net.sf.jasperreports.engine.JasperFillManager; import net.sf.jasperreports.engine.JasperPrint; import net.sf.jasperreports.engine.export.JRRtfExporter; import net.sf.jasperreports.engine.export.oasis.JROdtExporter; import net.sf.jasperreports.engine.export.ooxml.JRDocxExporter; import net.sf.jasperreports.engine.query.JRXPathQueryExecuterFactory; import net.sf.jasperreports.engine.util.JRLoader; import net.sf.jasperreports.engine.util.JRXmlUtils; import net.sf.jasperreports.export.SimpleExporterInput; import net.sf.jasperreports.export.SimpleOutputStreamExporterOutput; import net.sf.jasperreports.export.SimpleWriterExporterOutput; import org.apache.commons.cli.BasicParser; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.w3c.dom.Document; public class JasperProcess { protected final Log log = LogFactory.getLog(getClass()); static protected Options options; /** * @param args * @throws JRException * @throws IOException * @throws ParseException */ public static void main(String[] args) throws JRException, IOException { try { // create the parser CommandLineParser parser = new BasicParser(); Options options = initOptions(); CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("h")) { usage(); return; } JasperProcess jasperProc = new JasperProcess(); if (cmd.hasOption("c")) { jasperProc.compileDir(cmd.getOptionValue("c")); return; } String report = cmd.getOptionValue("r"); String sub = cmd.getOptionValue("s"); String[] subReports = {}; if (sub != null) { subReports = sub.split(","); } String dataFile = cmd.getOptionValue("d"); String destFile = cmd.getOptionValue("o"); String userParamsStr = cmd.getOptionValue("p"); Map<String, String> userParams = new HashMap<String, String>(); if (userParamsStr != null) { String[] p = {}; p = userParamsStr.split(","); for (String kv : p) { String[] keyVal = kv.split("="); if (keyVal.length != 2) { throw new ParseException("Bad parameter: " + kv); } userParams.put(keyVal[0], keyVal[1]); } } jasperProc.generate(report, subReports, dataFile, destFile, userParams); System.out.println("output file created: " + destFile); } catch (ParseException ex) { System.out.println("jasper-service stopped with errors"); System.err.println("error parsing commandline: " + ex.getMessage()); usage(); } } static public void usage() { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("jasper-service", options, true); } public void generate(String report, String[] subReports, String dataFile, String destFile, Map<String, String> userParams) throws IOException, JRException { // compile if needed compileReports(report, subReports); // prepare params Map<String, Object> params = readDataFile(dataFile); for (String k : userParams.keySet()) { params.put(k, userParams.get(k)); } log.debug("generating print data"); JasperPrint print = JasperFillManager.fillReport(report, params); log.debug("exporting to file: " + destFile); String extension = destFile.substring(destFile.lastIndexOf('.')+1).toLowerCase(); if("pdf".equals(extension)) { log.debug("using pdf format"); pdf(print, destFile); } else if("docx".equals(extension)) { log.debug("using docx format"); docx(print, destFile); } else if("rtf".equals(extension)) { log.debug("using rtf format"); rtf(print, destFile); } else if("odt".equals(extension)) { log.debug("using odt format"); odt(print, destFile); } else { log.warn("unsupported format for file: " + destFile); System.out.println("unsupported format for file: " + destFile); System.out.println("supported formats: pdf, docx, rtf and odt"); } } /** * Init options, parse arguments */ static private Options initOptions() { options = new Options(); // report option Option r = new Option("r", "report", true, "jasper report file path (.jasper file), absolute or relative"); options.addOption(r); // data file option Option d = new Option("d", "data-file", true, "data file path (i.e. .xml data file"); options.addOption(d); // param option Option p = new Option("p", "param", true, "comma separated list of params in this form: name1=value1,name2=value2"); options.addOption(p); // output file option Option o = new Option("o", "output", true, "output file path"); options.addOption(o); // subreport files option Option s = new Option("s", "sub-reports", true, "comma saparated list of jasper subreports file paths"); options.addOption(s); // compile directory option Option c = new Option("c", "compile-dir", true, "directory path containing .jrxml files to compile"); options.addOption(c); // help option options.addOption("h", "help", false, "this help message"); return options; } protected void compileDir(String dirPath) throws IOException, JRException { } protected void compileReports(String report, String[] subReports) throws IOException, JRException { log.info("compiling report: " + report); compileReport(report); for (String subRep : subReports) { log.info("compiling subreport: " + subRep); compileReport(subRep); } } protected Map<String, Object> readDataFile(String xmlDataFile) throws JRException { Document document = JRXmlUtils.parse(JRLoader.getLocationInputStream(xmlDataFile)); Map<String, Object> params = new HashMap<String, Object>(); params.put(JRXPathQueryExecuterFactory.PARAMETER_XML_DATA_DOCUMENT, document); params.put(JRXPathQueryExecuterFactory.XML_DATE_PATTERN, "yyyy-MM-dd"); params.put(JRXPathQueryExecuterFactory.XML_NUMBER_PATTERN, "#,##0.##"); params.put(JRXPathQueryExecuterFactory.XML_LOCALE, Locale.ENGLISH); params.put(JRParameter.REPORT_LOCALE, Locale.US); return params; } protected void pdf(JasperPrint print, String destFile) throws JRException, IOException { log.debug("exporting to pdf file: " + destFile); JasperExportManager.exportReportToPdfFile(print, destFile); } protected void docx(JasperPrint print, String destFile) throws JRException, IOException { log.debug("exporting to docx file: " + destFile); JRDocxExporter exporter = new JRDocxExporter(); exporter.setExporterInput(new SimpleExporterInput(print)); exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(destFile)); exporter.exportReport(); } protected void odt(JasperPrint print, String destFile) throws JRException, IOException { log.debug("exporting to odt file: " + destFile); JROdtExporter exporter = new JROdtExporter(); exporter.setExporterInput(new SimpleExporterInput(print)); exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(destFile)); exporter.exportReport(); } protected void rtf(JasperPrint print, String destFile) throws JRException, IOException { log.debug("exporting to rtf file: " + destFile); JRRtfExporter exporter = new JRRtfExporter(); exporter.setExporterInput(new SimpleExporterInput(print)); exporter.setExporterOutput(new SimpleWriterExporterOutput(destFile)); exporter.exportReport(); } /** * Compile jasper .jrxml source file if compiled .jasper is missing or older than source * * @param filename * @return JasperReport * @throws IOException * @throws JRException */ private void compileReport(String jasperFileName) throws IOException, JRException { if (!jasperFileName.endsWith(".jasper")) { throw new JRException("Bad file extension, should be .jasper: " + jasperFileName); } String sourceFileName = jasperFileName.substring(0, jasperFileName.length()-7) + ".jrxml"; File source = new File(sourceFileName); File compiled = new File(jasperFileName); if (!source.exists()) { throw new IOException("Missing source JRXML file " + sourceFileName); } if(!compiled.exists() || (compiled.lastModified() < source.lastModified())) { log.debug("compiling source report: " + sourceFileName); JasperCompileManager.compileReportToFile(sourceFileName, jasperFileName); } else { log.debug("source report compilation not needed"); } } }
added compile directory option
src/net/bedita/export/jasper/JasperProcess.java
added compile directory option
<ide><path>rc/net/bedita/export/jasper/JasperProcess.java <ide> } <ide> String dataFile = cmd.getOptionValue("d"); <ide> String destFile = cmd.getOptionValue("o"); <add> if (report == null || dataFile == null || destFile == null) { <add> throw new ParseException("Missing parameters"); <add> } <add> <ide> String userParamsStr = cmd.getOptionValue("p"); <ide> Map<String, String> userParams = new HashMap<String, String>(); <ide> if (userParamsStr != null) { <ide> Option o = new Option("o", "output", true, "output file path"); <ide> options.addOption(o); <ide> // subreport files option <del> Option s = new Option("s", "sub-reports", true, "comma saparated list of jasper subreports file paths"); <add> Option s = new Option("s", "sub-reports", true, "comma separeted list of jasper subreports file paths"); <ide> options.addOption(s); <ide> // compile directory option <ide> Option c = new Option("c", "compile-dir", true, "directory path containing .jrxml files to compile"); <ide> } <ide> <ide> protected void compileDir(String dirPath) throws IOException, JRException { <del> <add> log.info("compiling reports in: " + dirPath); <add> File dir = new File(dirPath); <add> for (File fileEntry : dir.listFiles()) { <add> if (!fileEntry.isDirectory()) { <add> String filePath = fileEntry.getAbsolutePath(); <add> int dotPos = filePath.lastIndexOf("."); <add> if (dotPos != -1) { <add> String extension = filePath.substring(dotPos); <add> if (extension.equals(".jrxml")) { <add> String jasperFile = filePath.substring(0, dotPos) + ".jasper"; <add> compileReport(jasperFile); <add> } <add> } <add> } <add> } <ide> } <ide> <ide>
Java
apache-2.0
19257ae30aecce7e53faa36860bdc272c74e6cc1
0
tmitim/twittercli4j,tmitim/twittercli4j
package com.tmitim.twittercli.commands; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.apache.commons.lang3.StringUtils; import com.github.rvesse.airline.annotations.Arguments; import com.github.rvesse.airline.annotations.Command; import com.github.rvesse.airline.annotations.Option; import com.tmitim.twittercli.Printer; import twitter4j.Query; import twitter4j.Status; import twitter4j.Twitter; import twitter4j.TwitterException; import twitter4j.TwitterFactory; /** * Tweet to twitter * */ @Command(name = "search", description = "Search twitter") public class Search implements Runnable { @Arguments(description = "Search terms") private List<String> args; @Option(name = { "-r", "--recent" }, description = "Search recent tweets") private boolean searchRecent; @Option(name = { "-p", "--popular" }, description = "Search popular tweets") private boolean searchPopular; @Option(name = { "-m", "--mixed" }, description = "Search a mix of recent/popular tweets") private boolean searchMixed; @Override public void run() { String queryString = StringUtils.join(args, " "); Twitter twitter = TwitterFactory.getSingleton(); List<Status> statuses = new ArrayList<>(); try { System.out.println("Searching for: " + queryString); if (queryString != null && !queryString.isEmpty()) { Query query = new Query(queryString); if (searchRecent) { query.setResultType(Query.RECENT); } if (searchPopular) { query.setResultType(Query.POPULAR); } if ((searchPopular && searchRecent) || searchMixed) { query.setResultType(Query.MIXED); } System.out.println( "Searching " + (query.getResultType() == null ? Query.MIXED : query.getResultType()) + " results"); statuses = twitter.search(query).getTweets(); } } catch (TwitterException e) { // TODO Auto-generated catch block e.printStackTrace(); } Collections.reverse(statuses); new Printer().printStatuses(statuses); } }
src/main/java/com/tmitim/twittercli/commands/Search.java
package com.tmitim.twittercli.commands; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.apache.commons.lang3.StringUtils; import com.github.rvesse.airline.annotations.Arguments; import com.github.rvesse.airline.annotations.Command; import com.tmitim.twittercli.Printer; import twitter4j.Query; import twitter4j.Status; import twitter4j.Twitter; import twitter4j.TwitterException; import twitter4j.TwitterFactory; /** * Tweet to twitter * */ @Command(name = "search", description = "Search twitter") public class Search implements Runnable { @Arguments(description = "Additional arguments") private List<String> args; @Override public void run() { String query = StringUtils.join(args, " "); Twitter twitter = TwitterFactory.getSingleton(); List<Status> statuses = new ArrayList<>(); try { System.out.println("Searching for: " + query); if (query != null && !query.isEmpty()) { statuses = twitter.search(new Query(query)).getTweets(); } } catch (TwitterException e) { // TODO Auto-generated catch block e.printStackTrace(); } Collections.reverse(statuses); new Printer().printStatuses(statuses); } }
Add search flags for popular, recent, mixed searches
src/main/java/com/tmitim/twittercli/commands/Search.java
Add search flags for popular, recent, mixed searches
<ide><path>rc/main/java/com/tmitim/twittercli/commands/Search.java <ide> <ide> import com.github.rvesse.airline.annotations.Arguments; <ide> import com.github.rvesse.airline.annotations.Command; <add>import com.github.rvesse.airline.annotations.Option; <ide> import com.tmitim.twittercli.Printer; <ide> <ide> import twitter4j.Query; <ide> @Command(name = "search", description = "Search twitter") <ide> public class Search implements Runnable { <ide> <del> @Arguments(description = "Additional arguments") <add> @Arguments(description = "Search terms") <ide> private List<String> args; <add> <add> @Option(name = { "-r", "--recent" }, description = "Search recent tweets") <add> private boolean searchRecent; <add> <add> @Option(name = { "-p", "--popular" }, description = "Search popular tweets") <add> private boolean searchPopular; <add> <add> @Option(name = { "-m", "--mixed" }, description = "Search a mix of recent/popular tweets") <add> private boolean searchMixed; <ide> <ide> @Override <ide> public void run() { <del> String query = StringUtils.join(args, " "); <del> <add> String queryString = StringUtils.join(args, " "); <ide> <ide> Twitter twitter = TwitterFactory.getSingleton(); <ide> <ide> List<Status> statuses = new ArrayList<>(); <ide> try { <ide> <del> System.out.println("Searching for: " + query); <del> if (query != null && !query.isEmpty()) { <del> statuses = twitter.search(new Query(query)).getTweets(); <add> System.out.println("Searching for: " + queryString); <add> if (queryString != null && !queryString.isEmpty()) { <add> Query query = new Query(queryString); <add> if (searchRecent) { <add> query.setResultType(Query.RECENT); <add> } <add> <add> if (searchPopular) { <add> query.setResultType(Query.POPULAR); <add> } <add> <add> if ((searchPopular && searchRecent) || searchMixed) { <add> query.setResultType(Query.MIXED); <add> } <add> <add> System.out.println( <add> "Searching " + (query.getResultType() == null ? Query.MIXED : query.getResultType()) <add> + " results"); <add> statuses = twitter.search(query).getTweets(); <ide> } <ide> <ide> } catch (TwitterException e) {
Java
agpl-3.0
aae7e6a14bc975157681cd6fc165633e70e04175
0
paulmartel/voltdb,flybird119/voltdb,kobronson/cs-voltdb,flybird119/voltdb,simonzhangsm/voltdb,simonzhangsm/voltdb,deerwalk/voltdb,ingted/voltdb,flybird119/voltdb,wolffcm/voltdb,zuowang/voltdb,paulmartel/voltdb,wolffcm/voltdb,creative-quant/voltdb,migue/voltdb,migue/voltdb,deerwalk/voltdb,zuowang/voltdb,zuowang/voltdb,kumarrus/voltdb,zuowang/voltdb,zuowang/voltdb,kumarrus/voltdb,migue/voltdb,kobronson/cs-voltdb,simonzhangsm/voltdb,deerwalk/voltdb,VoltDB/voltdb,flybird119/voltdb,creative-quant/voltdb,simonzhangsm/voltdb,creative-quant/voltdb,VoltDB/voltdb,creative-quant/voltdb,simonzhangsm/voltdb,migue/voltdb,kobronson/cs-voltdb,kobronson/cs-voltdb,creative-quant/voltdb,zuowang/voltdb,VoltDB/voltdb,paulmartel/voltdb,VoltDB/voltdb,deerwalk/voltdb,paulmartel/voltdb,kobronson/cs-voltdb,kobronson/cs-voltdb,VoltDB/voltdb,kumarrus/voltdb,deerwalk/voltdb,kumarrus/voltdb,wolffcm/voltdb,VoltDB/voltdb,creative-quant/voltdb,kumarrus/voltdb,ingted/voltdb,flybird119/voltdb,wolffcm/voltdb,paulmartel/voltdb,wolffcm/voltdb,paulmartel/voltdb,ingted/voltdb,simonzhangsm/voltdb,migue/voltdb,kumarrus/voltdb,flybird119/voltdb,kobronson/cs-voltdb,deerwalk/voltdb,kumarrus/voltdb,deerwalk/voltdb,kumarrus/voltdb,wolffcm/voltdb,paulmartel/voltdb,wolffcm/voltdb,wolffcm/voltdb,VoltDB/voltdb,ingted/voltdb,migue/voltdb,flybird119/voltdb,flybird119/voltdb,kobronson/cs-voltdb,ingted/voltdb,simonzhangsm/voltdb,creative-quant/voltdb,simonzhangsm/voltdb,migue/voltdb,ingted/voltdb,deerwalk/voltdb,ingted/voltdb,creative-quant/voltdb,zuowang/voltdb,zuowang/voltdb,ingted/voltdb,paulmartel/voltdb,migue/voltdb
/* This file is part of VoltDB. * Copyright (C) 2008-2012 VoltDB Inc. * * 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 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. */ /* * This samples uses multiple threads to post synchronous requests to the * VoltDB server, simulating multiple client application posting * synchronous requests to the database, using the native VoltDB client * library. * * While synchronous processing can cause performance bottlenecks (each * caller waits for a transaction answer before calling another * transaction), the VoltDB cluster at large is still able to perform at * blazing speeds when many clients are connected to it. */ package voltkv; import java.util.Random; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import org.voltdb.CLIConfig; import org.voltdb.VoltTable; import org.voltdb.client.Client; import org.voltdb.client.ClientConfig; import org.voltdb.client.ClientFactory; import org.voltdb.client.ClientResponse; import org.voltdb.client.ClientStats; import org.voltdb.client.ClientStatsContext; import org.voltdb.client.ClientStatusListenerExt; import org.voltdb.client.NullCallback; public class SyncBenchmark { // handy, rather than typing this out several times static final String HORIZONTAL_RULE = "----------" + "----------" + "----------" + "----------" + "----------" + "----------" + "----------" + "----------" + "\n"; // validated command line configuration final KVConfig config; // Reference to the database connection we will use final Client client; // Timer for periodic stats printing Timer timer; // Benchmark start time long benchmarkStartTS; // Get a payload generator to create random Key-Value pairs to store in the database // and process (uncompress) pairs retrieved from the database. final PayloadProcessor processor; // random number generator with constant seed final Random rand = new Random(0); // Flags to tell the worker threads to stop or go AtomicBoolean warmupComplete = new AtomicBoolean(false); AtomicBoolean benchmarkComplete = new AtomicBoolean(false); // Statistics manager objects from the client final ClientStatsContext periodicStatsContext; // kv benchmark state final AtomicLong successfulGets = new AtomicLong(0); final AtomicLong missedGets = new AtomicLong(0); final AtomicLong failedGets = new AtomicLong(0); final AtomicLong rawGetData = new AtomicLong(0); final AtomicLong networkGetData = new AtomicLong(0); final AtomicLong successfulPuts = new AtomicLong(0); final AtomicLong failedPuts = new AtomicLong(0); final AtomicLong rawPutData = new AtomicLong(0); final AtomicLong networkPutData = new AtomicLong(0); /** * Uses included {@link CLIConfig} class to * declaratively state command line options with defaults * and validation. */ static class KVConfig extends CLIConfig { @Option(desc = "Interval for performance feedback, in seconds.") long displayinterval = 5; @Option(desc = "Benchmark duration, in seconds.") int duration = 10; @Option(desc = "Warmup duration in seconds.") int warmup = 5; @Option(desc = "Comma separated list of the form server[:port] to connect to.") String servers = "localhost"; @Option(desc = "Number of keys to preload.") int poolsize = 100000; @Option(desc = "Whether to preload a specified number of keys and values.") boolean preload = true; @Option(desc = "Fraction of ops that are gets (vs puts).") double getputratio = 0.90; @Option(desc = "Size of keys in bytes.") int keysize = 32; @Option(desc = "Minimum value size in bytes.") int minvaluesize = 1024; @Option(desc = "Maximum value size in bytes.") int maxvaluesize = 1024; @Option(desc = "Number of values considered for each value byte.") int entropy = 127; @Option(desc = "Compress values on the client side.") boolean usecompression= false; @Option(desc = "Number of concurrent threads synchronously calling procedures.") int threads = 40; @Option(desc = "Filename to write raw summary statistics to.") String statsfile = ""; @Override public void validate() { if (duration <= 0) exitWithMessageAndUsage("duration must be > 0"); if (warmup < 0) exitWithMessageAndUsage("warmup must be >= 0"); if (displayinterval <= 0) exitWithMessageAndUsage("displayinterval must be > 0"); if (poolsize <= 0) exitWithMessageAndUsage("poolsize must be > 0"); if (getputratio < 0) exitWithMessageAndUsage("getputratio must be >= 0"); if (getputratio > 1) exitWithMessageAndUsage("getputratio must be <= 1"); if (keysize <= 0) exitWithMessageAndUsage("keysize must be > 0"); if (keysize > 250) exitWithMessageAndUsage("keysize must be <= 250"); if (minvaluesize <= 0) exitWithMessageAndUsage("minvaluesize must be > 0"); if (maxvaluesize <= 0) exitWithMessageAndUsage("maxvaluesize must be > 0"); if (entropy <= 0) exitWithMessageAndUsage("entropy must be > 0"); if (entropy > 127) exitWithMessageAndUsage("entropy must be <= 127"); if (threads <= 0) exitWithMessageAndUsage("threads must be > 0"); } } /** * Provides a callback to be notified on node failure. * This example only logs the event. */ class StatusListener extends ClientStatusListenerExt { @Override public void connectionLost(String hostname, int port, int connectionsLeft, DisconnectCause cause) { // if the benchmark is still active if (benchmarkComplete.get() == false) { System.err.printf("Connection to %s:%d was lost.\n", hostname, port); } } } /** * Constructor for benchmark instance. * Configures VoltDB client and prints configuration. * * @param config Parsed & validated CLI options. */ public SyncBenchmark(KVConfig config) { this.config = config; ClientConfig clientConfig = new ClientConfig("", "", new StatusListener()); client = ClientFactory.createClient(clientConfig); periodicStatsContext = client.createStatsContext(); processor = new PayloadProcessor(config.keysize, config.minvaluesize, config.maxvaluesize, config.entropy, config.poolsize, config.usecompression); System.out.print(HORIZONTAL_RULE); System.out.println(" Command Line Configuration"); System.out.println(HORIZONTAL_RULE); System.out.println(config.getConfigDumpString()); } /** * Connect to a single server with retry. Limited exponential backoff. * No timeout. This will run until the process is killed if it's not * able to connect. * * @param server hostname:port or just hostname (hostname can be ip). */ void connectToOneServerWithRetry(String server) { int sleep = 1000; while (true) { try { client.createConnection(server); break; } catch (Exception e) { System.err.printf("Connection failed - retrying in %d second(s).\n", sleep / 1000); try { Thread.sleep(sleep); } catch (Exception interruted) {} if (sleep < 8000) sleep += sleep; } } System.out.printf("Connected to VoltDB node at: %s.\n", server); } /** * Connect to a set of servers in parallel. Each will retry until * connection. This call will block until all have connected. * * @param servers A comma separated list of servers using the hostname:port * syntax (where :port is optional). * @throws InterruptedException if anything bad happens with the threads. */ void connect(String servers) throws InterruptedException { System.out.println("Connecting to VoltDB..."); String[] serverArray = servers.split(","); final CountDownLatch connections = new CountDownLatch(serverArray.length); // use a new thread to connect to each server for (final String server : serverArray) { new Thread(new Runnable() { @Override public void run() { connectToOneServerWithRetry(server); connections.countDown(); } }).start(); } // block until all have connected connections.await(); } /** * Create a Timer task to display performance data on the Vote procedure * It calls printStatistics() every displayInterval seconds */ public void schedulePeriodicStats() { timer = new Timer(); TimerTask statsPrinting = new TimerTask() { @Override public void run() { printStatistics(); } }; timer.scheduleAtFixedRate(statsPrinting, config.displayinterval * 1000, config.displayinterval * 1000); } /** * Prints a one line update on performance that can be printed * periodically during a benchmark. */ public synchronized void printStatistics() { ClientStats stats = periodicStatsContext.fetchAndResetBaseline().getStats(); long time = Math.round((stats.getEndTimestamp() - benchmarkStartTS) / 1000.0); System.out.printf("%02d:%02d:%02d ", time / 3600, (time / 60) % 60, time % 60); System.out.printf("Throughput %d/s, ", stats.getTxnThroughput()); System.out.printf("Aborts/Failures %d/%d, ", stats.getInvocationAborts(), stats.getInvocationErrors()); System.out.printf("Avg/95%% Latency %f/%dms\n", stats.getAverageLatency(), stats.kPercentileLatency(0.95)); } /** * Prints the results of the voting simulation and statistics * about performance. * * @throws Exception if anything unexpected happens. */ public synchronized void printResults(ClientStats stats) throws Exception { // 1. Get/Put performance results String display = "\n" + HORIZONTAL_RULE + " KV Store Results\n" + HORIZONTAL_RULE + "\nA total of %,d operations were posted...\n" + " - GETs: %,9d Operations (%,d Misses and %,d Failures)\n" + " %,9d MB in compressed store data\n" + " %,9d MB in uncompressed application data\n" + " Network Throughput: %6.3f Gbps*\n" + " - PUTs: %,9d Operations (%,d Failures)\n" + " %,9d MB in compressed store data\n" + " %,9d MB in uncompressed application data\n" + " Network Throughput: %6.3f Gbps*\n" + " - Total Network Throughput: %6.3f Gbps*\n\n" + "* Figure includes key & value traffic but not database protocol overhead.\n\n"; double oneGigabit = (1024 * 1024 * 1024) / 8; long oneMB = (1024 * 1024); double getThroughput = networkGetData.get() + (successfulGets.get() * config.keysize); getThroughput /= (oneGigabit * config.duration); long totalPuts = successfulPuts.get() + failedPuts.get(); double putThroughput = networkGetData.get() + (totalPuts * config.keysize); putThroughput /= (oneGigabit * config.duration); System.out.printf(display, stats.getInvocationsCompleted(), successfulGets.get(), missedGets.get(), failedGets.get(), networkGetData.get() / oneMB, rawGetData.get() / oneMB, getThroughput, successfulPuts.get(), failedPuts.get(), networkPutData.get() / oneMB, rawPutData.get() / oneMB, putThroughput, getThroughput + putThroughput); // 2. Performance statistics System.out.print(HORIZONTAL_RULE); System.out.println(" Client Workload Statistics"); System.out.println(HORIZONTAL_RULE); System.out.printf("Average throughput: %,9d txns/sec\n", stats.getTxnThroughput()); System.out.printf("Average latency: %,9f ms\n", stats.getAverageLatency()); System.out.printf("95th percentile latency: %,9d ms\n", stats.kPercentileLatency(.95)); System.out.printf("99th percentile latency: %,9d ms\n", stats.kPercentileLatency(.99)); System.out.print("\n" + HORIZONTAL_RULE); System.out.println(" System Server Statistics"); System.out.println(HORIZONTAL_RULE); System.out.printf("Reported Internal Avg Latency: %,9f ms\n", stats.getAverageInternalLatency()); // 3. Write stats to file if requested client.writeSummaryCSV(stats, config.statsfile); } /** * While <code>benchmarkComplete</code> is set to false, run as many * synchronous procedure calls as possible and record the results. * */ class KVThread implements Runnable { @Override public void run() { while (warmupComplete.get() == false) { // Decide whether to perform a GET or PUT operation if (rand.nextDouble() < config.getputratio) { // Get a key/value pair, synchronously try { client.callProcedure("Get", processor.generateRandomKeyForRetrieval()); } catch (Exception e) {} } else { // Put a key/value pair, synchronously final PayloadProcessor.Pair pair = processor.generateForStore(); try { client.callProcedure("Put", pair.Key, pair.getStoreValue()); } catch (Exception e) {} } } while (benchmarkComplete.get() == false) { // Decide whether to perform a GET or PUT operation if (rand.nextDouble() < config.getputratio) { // Get a key/value pair, synchronously try { ClientResponse response = client.callProcedure("Get", processor.generateRandomKeyForRetrieval()); final VoltTable pairData = response.getResults()[0]; // Cache miss (Key does not exist) if (pairData.getRowCount() == 0) missedGets.incrementAndGet(); else { final PayloadProcessor.Pair pair = processor.retrieveFromStore(pairData.fetchRow(0).getString(0), pairData.fetchRow(0).getVarbinary(1)); successfulGets.incrementAndGet(); networkGetData.addAndGet(pair.getStoreValueLength()); rawGetData.addAndGet(pair.getRawValueLength()); } } catch (Exception e) { failedGets.incrementAndGet(); } } else { // Put a key/value pair, synchronously final PayloadProcessor.Pair pair = processor.generateForStore(); try { client.callProcedure("Put", pair.Key, pair.getStoreValue()); successfulPuts.incrementAndGet(); } catch (Exception e) { failedPuts.incrementAndGet(); } networkPutData.addAndGet(pair.getStoreValueLength()); rawPutData.addAndGet(pair.getRawValueLength()); } } } } /** * Core benchmark code. * Connect. Initialize. Run the loop. Cleanup. Print Results. * * @throws Exception if anything unexpected happens. */ public void runBenchmark() throws Exception { System.out.print(HORIZONTAL_RULE); System.out.println(" Setup & Initialization"); System.out.println(HORIZONTAL_RULE); // connect to one or more servers, loop until success connect(config.servers); // preload keys if requested System.out.println(); if (config.preload) { System.out.println("Preloading data store..."); for(int i=0; i < config.poolsize; i++) { client.callProcedure(new NullCallback(), "Put", String.format(processor.KeyFormat, i), processor.generateForStore().getStoreValue()); } client.drain(); System.out.println("Preloading complete.\n"); } System.out.print(HORIZONTAL_RULE); System.out.println("Starting Benchmark"); System.out.println(HORIZONTAL_RULE); // create/start the requested number of threads Thread[] kvThreads = new Thread[config.threads]; for (int i = 0; i < config.threads; ++i) { kvThreads[i] = new Thread(new KVThread()); kvThreads[i].start(); } // Run the benchmark loop for the requested warmup time System.out.println("Warming up..."); Thread.sleep(1000l * config.warmup); // signal to threads to end the warmup phase warmupComplete.set(true); // reset the stats after warmup periodicStatsContext.fetchAndResetBaseline(); // print periodic statistics to the console benchmarkStartTS = System.currentTimeMillis(); schedulePeriodicStats(); // Create the stats context here, so that we only capture the benchmark stats, // and not the warm-up and pre-loading ClientStatsContext fullStatsContext = client.createStatsContext(); fullStatsContext.fetchAndResetBaseline(); // Run the benchmark loop for the requested warmup time System.out.println("\nRunning benchmark..."); Thread.sleep(1000l * config.duration); // stop the threads benchmarkComplete.set(true); // cancel periodic stats printing timer.cancel(); // block until all outstanding txns return client.drain(); // join on the threads for (Thread t : kvThreads) { t.join(); } // print the summary results printResults(fullStatsContext.fetch().getStats()); // close down the client connections client.close(); } /** * Main routine creates a benchmark instance and kicks off the run method. * * @param args Command line arguments. * @throws Exception if anything goes wrong. * @see {@link KVConfig} */ public static void main(String[] args) throws Exception { // create a configuration from the arguments KVConfig config = new KVConfig(); config.parse(SyncBenchmark.class.getName(), args); SyncBenchmark benchmark = new SyncBenchmark(config); benchmark.runBenchmark(); } }
examples/voltkv/src/voltkv/SyncBenchmark.java
/* This file is part of VoltDB. * Copyright (C) 2008-2012 VoltDB Inc. * * 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 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. */ /* * This samples uses multiple threads to post synchronous requests to the * VoltDB server, simulating multiple client application posting * synchronous requests to the database, using the native VoltDB client * library. * * While synchronous processing can cause performance bottlenecks (each * caller waits for a transaction answer before calling another * transaction), the VoltDB cluster at large is still able to perform at * blazing speeds when many clients are connected to it. */ package voltkv; import java.util.Random; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import org.voltdb.CLIConfig; import org.voltdb.VoltTable; import org.voltdb.client.Client; import org.voltdb.client.ClientConfig; import org.voltdb.client.ClientFactory; import org.voltdb.client.ClientResponse; import org.voltdb.client.ClientStats; import org.voltdb.client.ClientStatsContext; import org.voltdb.client.ClientStatusListenerExt; import org.voltdb.client.NullCallback; public class SyncBenchmark { // handy, rather than typing this out several times static final String HORIZONTAL_RULE = "----------" + "----------" + "----------" + "----------" + "----------" + "----------" + "----------" + "----------" + "\n"; // validated command line configuration final KVConfig config; // Reference to the database connection we will use final Client client; // Timer for periodic stats printing Timer timer; // Benchmark start time long benchmarkStartTS; // Get a payload generator to create random Key-Value pairs to store in the database // and process (uncompress) pairs retrieved from the database. final PayloadProcessor processor; // random number generator with constant seed final Random rand = new Random(0); // Flags to tell the worker threads to stop or go AtomicBoolean warmupComplete = new AtomicBoolean(false); AtomicBoolean benchmarkComplete = new AtomicBoolean(false); // Statistics manager objects from the client final ClientStatsContext periodicStatsContext; // kv benchmark state final AtomicLong successfulGets = new AtomicLong(0); final AtomicLong missedGets = new AtomicLong(0); final AtomicLong failedGets = new AtomicLong(0); final AtomicLong rawGetData = new AtomicLong(0); final AtomicLong networkGetData = new AtomicLong(0); final AtomicLong successfulPuts = new AtomicLong(0); final AtomicLong failedPuts = new AtomicLong(0); final AtomicLong rawPutData = new AtomicLong(0); final AtomicLong networkPutData = new AtomicLong(0); /** * Uses included {@link CLIConfig} class to * declaratively state command line options with defaults * and validation. */ static class KVConfig extends CLIConfig { @Option(desc = "Interval for performance feedback, in seconds.") long displayinterval = 5; @Option(desc = "Benchmark duration, in seconds.") int duration = 10; @Option(desc = "Warmup duration in seconds.") int warmup = 5; @Option(desc = "Comma separated list of the form server[:port] to connect to.") String servers = "localhost"; @Option(desc = "Number of keys to preload.") int poolsize = 100000; @Option(desc = "Whether to preload a specified number of keys and values.") boolean preload = true; @Option(desc = "Fraction of ops that are gets (vs puts).") double getputratio = 0.90; @Option(desc = "Size of keys in bytes.") int keysize = 32; @Option(desc = "Minimum value size in bytes.") int minvaluesize = 1024; @Option(desc = "Maximum value size in bytes.") int maxvaluesize = 1024; @Option(desc = "Number of values considered for each value byte.") int entropy = 127; @Option(desc = "Compress values on the client side.") boolean usecompression= false; @Option(desc = "Number of concurrent threads synchronously calling procedures.") int threads = 1; @Option(desc = "Filename to write raw summary statistics to.") String statsfile = ""; @Override public void validate() { if (duration <= 0) exitWithMessageAndUsage("duration must be > 0"); if (warmup < 0) exitWithMessageAndUsage("warmup must be >= 0"); if (displayinterval <= 0) exitWithMessageAndUsage("displayinterval must be > 0"); if (poolsize <= 0) exitWithMessageAndUsage("poolsize must be > 0"); if (getputratio < 0) exitWithMessageAndUsage("getputratio must be >= 0"); if (getputratio > 1) exitWithMessageAndUsage("getputratio must be <= 1"); if (keysize <= 0) exitWithMessageAndUsage("keysize must be > 0"); if (keysize > 250) exitWithMessageAndUsage("keysize must be <= 250"); if (minvaluesize <= 0) exitWithMessageAndUsage("minvaluesize must be > 0"); if (maxvaluesize <= 0) exitWithMessageAndUsage("maxvaluesize must be > 0"); if (entropy <= 0) exitWithMessageAndUsage("entropy must be > 0"); if (entropy > 127) exitWithMessageAndUsage("entropy must be <= 127"); if (threads <= 0) exitWithMessageAndUsage("threads must be > 0"); } } /** * Provides a callback to be notified on node failure. * This example only logs the event. */ class StatusListener extends ClientStatusListenerExt { @Override public void connectionLost(String hostname, int port, int connectionsLeft, DisconnectCause cause) { // if the benchmark is still active if (benchmarkComplete.get() == false) { System.err.printf("Connection to %s:%d was lost.\n", hostname, port); } } } /** * Constructor for benchmark instance. * Configures VoltDB client and prints configuration. * * @param config Parsed & validated CLI options. */ public SyncBenchmark(KVConfig config) { this.config = config; ClientConfig clientConfig = new ClientConfig("", "", new StatusListener()); client = ClientFactory.createClient(clientConfig); periodicStatsContext = client.createStatsContext(); processor = new PayloadProcessor(config.keysize, config.minvaluesize, config.maxvaluesize, config.entropy, config.poolsize, config.usecompression); System.out.print(HORIZONTAL_RULE); System.out.println(" Command Line Configuration"); System.out.println(HORIZONTAL_RULE); System.out.println(config.getConfigDumpString()); } /** * Connect to a single server with retry. Limited exponential backoff. * No timeout. This will run until the process is killed if it's not * able to connect. * * @param server hostname:port or just hostname (hostname can be ip). */ void connectToOneServerWithRetry(String server) { int sleep = 1000; while (true) { try { client.createConnection(server); break; } catch (Exception e) { System.err.printf("Connection failed - retrying in %d second(s).\n", sleep / 1000); try { Thread.sleep(sleep); } catch (Exception interruted) {} if (sleep < 8000) sleep += sleep; } } System.out.printf("Connected to VoltDB node at: %s.\n", server); } /** * Connect to a set of servers in parallel. Each will retry until * connection. This call will block until all have connected. * * @param servers A comma separated list of servers using the hostname:port * syntax (where :port is optional). * @throws InterruptedException if anything bad happens with the threads. */ void connect(String servers) throws InterruptedException { System.out.println("Connecting to VoltDB..."); String[] serverArray = servers.split(","); final CountDownLatch connections = new CountDownLatch(serverArray.length); // use a new thread to connect to each server for (final String server : serverArray) { new Thread(new Runnable() { @Override public void run() { connectToOneServerWithRetry(server); connections.countDown(); } }).start(); } // block until all have connected connections.await(); } /** * Create a Timer task to display performance data on the Vote procedure * It calls printStatistics() every displayInterval seconds */ public void schedulePeriodicStats() { timer = new Timer(); TimerTask statsPrinting = new TimerTask() { @Override public void run() { printStatistics(); } }; timer.scheduleAtFixedRate(statsPrinting, config.displayinterval * 1000, config.displayinterval * 1000); } /** * Prints a one line update on performance that can be printed * periodically during a benchmark. */ public synchronized void printStatistics() { ClientStats stats = periodicStatsContext.fetchAndResetBaseline().getStats(); long time = Math.round((stats.getEndTimestamp() - benchmarkStartTS) / 1000.0); System.out.printf("%02d:%02d:%02d ", time / 3600, (time / 60) % 60, time % 60); System.out.printf("Throughput %d/s, ", stats.getTxnThroughput()); System.out.printf("Aborts/Failures %d/%d, ", stats.getInvocationAborts(), stats.getInvocationErrors()); System.out.printf("Avg/95%% Latency %f/%dms\n", stats.getAverageLatency(), stats.kPercentileLatency(0.95)); } /** * Prints the results of the voting simulation and statistics * about performance. * * @throws Exception if anything unexpected happens. */ public synchronized void printResults(ClientStats stats) throws Exception { // 1. Get/Put performance results String display = "\n" + HORIZONTAL_RULE + " KV Store Results\n" + HORIZONTAL_RULE + "\nA total of %,d operations were posted...\n" + " - GETs: %,9d Operations (%,d Misses and %,d Failures)\n" + " %,9d MB in compressed store data\n" + " %,9d MB in uncompressed application data\n" + " Network Throughput: %6.3f Gbps*\n" + " - PUTs: %,9d Operations (%,d Failures)\n" + " %,9d MB in compressed store data\n" + " %,9d MB in uncompressed application data\n" + " Network Throughput: %6.3f Gbps*\n" + " - Total Network Throughput: %6.3f Gbps*\n\n" + "* Figure includes key & value traffic but not database protocol overhead.\n\n"; double oneGigabit = (1024 * 1024 * 1024) / 8; long oneMB = (1024 * 1024); double getThroughput = networkGetData.get() + (successfulGets.get() * config.keysize); getThroughput /= (oneGigabit * config.duration); long totalPuts = successfulPuts.get() + failedPuts.get(); double putThroughput = networkGetData.get() + (totalPuts * config.keysize); putThroughput /= (oneGigabit * config.duration); System.out.printf(display, stats.getInvocationsCompleted(), successfulGets.get(), missedGets.get(), failedGets.get(), networkGetData.get() / oneMB, rawGetData.get() / oneMB, getThroughput, successfulPuts.get(), failedPuts.get(), networkPutData.get() / oneMB, rawPutData.get() / oneMB, putThroughput, getThroughput + putThroughput); // 2. Performance statistics System.out.print(HORIZONTAL_RULE); System.out.println(" Client Workload Statistics"); System.out.println(HORIZONTAL_RULE); System.out.printf("Average throughput: %,9d txns/sec\n", stats.getTxnThroughput()); System.out.printf("Average latency: %,9f ms\n", stats.getAverageLatency()); System.out.printf("95th percentile latency: %,9d ms\n", stats.kPercentileLatency(.95)); System.out.printf("99th percentile latency: %,9d ms\n", stats.kPercentileLatency(.99)); System.out.print("\n" + HORIZONTAL_RULE); System.out.println(" System Server Statistics"); System.out.println(HORIZONTAL_RULE); System.out.printf("Reported Internal Avg Latency: %,9f ms\n", stats.getAverageInternalLatency()); // 3. Write stats to file if requested client.writeSummaryCSV(stats, config.statsfile); } /** * While <code>benchmarkComplete</code> is set to false, run as many * synchronous procedure calls as possible and record the results. * */ class KVThread implements Runnable { @Override public void run() { while (warmupComplete.get() == false) { // Decide whether to perform a GET or PUT operation if (rand.nextDouble() < config.getputratio) { // Get a key/value pair, synchronously try { client.callProcedure("Get", processor.generateRandomKeyForRetrieval()); } catch (Exception e) {} } else { // Put a key/value pair, synchronously final PayloadProcessor.Pair pair = processor.generateForStore(); try { client.callProcedure("Put", pair.Key, pair.getStoreValue()); } catch (Exception e) {} } } while (benchmarkComplete.get() == false) { // Decide whether to perform a GET or PUT operation if (rand.nextDouble() < config.getputratio) { // Get a key/value pair, synchronously try { ClientResponse response = client.callProcedure("Get", processor.generateRandomKeyForRetrieval()); final VoltTable pairData = response.getResults()[0]; // Cache miss (Key does not exist) if (pairData.getRowCount() == 0) missedGets.incrementAndGet(); else { final PayloadProcessor.Pair pair = processor.retrieveFromStore(pairData.fetchRow(0).getString(0), pairData.fetchRow(0).getVarbinary(1)); successfulGets.incrementAndGet(); networkGetData.addAndGet(pair.getStoreValueLength()); rawGetData.addAndGet(pair.getRawValueLength()); } } catch (Exception e) { failedGets.incrementAndGet(); } } else { // Put a key/value pair, synchronously final PayloadProcessor.Pair pair = processor.generateForStore(); try { client.callProcedure("Put", pair.Key, pair.getStoreValue()); successfulPuts.incrementAndGet(); } catch (Exception e) { failedPuts.incrementAndGet(); } networkPutData.addAndGet(pair.getStoreValueLength()); rawPutData.addAndGet(pair.getRawValueLength()); } } } } /** * Core benchmark code. * Connect. Initialize. Run the loop. Cleanup. Print Results. * * @throws Exception if anything unexpected happens. */ public void runBenchmark() throws Exception { System.out.print(HORIZONTAL_RULE); System.out.println(" Setup & Initialization"); System.out.println(HORIZONTAL_RULE); // connect to one or more servers, loop until success connect(config.servers); // preload keys if requested System.out.println(); if (config.preload) { System.out.println("Preloading data store..."); for(int i=0; i < config.poolsize; i++) { client.callProcedure(new NullCallback(), "Put", String.format(processor.KeyFormat, i), processor.generateForStore().getStoreValue()); } client.drain(); System.out.println("Preloading complete.\n"); } System.out.print(HORIZONTAL_RULE); System.out.println("Starting Benchmark"); System.out.println(HORIZONTAL_RULE); // create/start the requested number of threads Thread[] kvThreads = new Thread[config.threads]; for (int i = 0; i < config.threads; ++i) { kvThreads[i] = new Thread(new KVThread()); kvThreads[i].start(); } // Run the benchmark loop for the requested warmup time System.out.println("Warming up..."); Thread.sleep(1000l * config.warmup); // signal to threads to end the warmup phase warmupComplete.set(true); // reset the stats after warmup periodicStatsContext.fetchAndResetBaseline(); // print periodic statistics to the console benchmarkStartTS = System.currentTimeMillis(); schedulePeriodicStats(); // Create the stats context here, so that we only capture the benchmark stats, // and not the warm-up and pre-loading ClientStatsContext fullStatsContext = client.createStatsContext(); fullStatsContext.fetchAndResetBaseline(); // Run the benchmark loop for the requested warmup time System.out.println("\nRunning benchmark..."); Thread.sleep(1000l * config.duration); // stop the threads benchmarkComplete.set(true); // cancel periodic stats printing timer.cancel(); // block until all outstanding txns return client.drain(); // join on the threads for (Thread t : kvThreads) { t.join(); } // print the summary results printResults(fullStatsContext.fetch().getStats()); // close down the client connections client.close(); } /** * Main routine creates a benchmark instance and kicks off the run method. * * @param args Command line arguments. * @throws Exception if anything goes wrong. * @see {@link KVConfig} */ public static void main(String[] args) throws Exception { // create a configuration from the arguments KVConfig config = new KVConfig(); config.parse(SyncBenchmark.class.getName(), args); SyncBenchmark benchmark = new SyncBenchmark(config); benchmark.runBenchmark(); } }
Revert thread count back to 40 for sync benchmark
examples/voltkv/src/voltkv/SyncBenchmark.java
Revert thread count back to 40 for sync benchmark
<ide><path>xamples/voltkv/src/voltkv/SyncBenchmark.java <ide> boolean usecompression= false; <ide> <ide> @Option(desc = "Number of concurrent threads synchronously calling procedures.") <del> int threads = 1; <add> int threads = 40; <ide> <ide> @Option(desc = "Filename to write raw summary statistics to.") <ide> String statsfile = "";
Java
apache-2.0
1c1f15c7d66a33eaf2ed2e65a599f45cdb5706a3
0
fthevenet/binjr,fthevenet/binjr
/* * Copyright 2017 Frederic Thevenet * * 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 eu.fthevenet.binjr.sources.jrds.adapters; import com.google.gson.Gson; import com.google.gson.JsonParseException; import eu.fthevenet.binjr.data.adapters.DataAdapter; import eu.fthevenet.binjr.data.adapters.HttpDataAdapterBase; import eu.fthevenet.binjr.data.adapters.TimeSeriesBinding; import eu.fthevenet.binjr.data.codec.CsvDecoder; import eu.fthevenet.binjr.data.exceptions.*; import eu.fthevenet.binjr.data.timeseries.DoubleTimeSeriesProcessor; import eu.fthevenet.binjr.dialogs.Dialogs; import eu.fthevenet.binjr.sources.jrds.adapters.json.JsonJrdsItem; import eu.fthevenet.binjr.sources.jrds.adapters.json.JsonJrdsTree; import eu.fthevenet.util.xml.XmlUtils; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.scene.control.TreeItem; import org.apache.http.HttpEntity; import org.apache.http.NameValuePair; import org.apache.http.StatusLine; import org.apache.http.client.HttpResponseException; import org.apache.http.client.utils.URIBuilder; import org.apache.http.impl.client.AbstractResponseHandler; import org.apache.http.impl.client.BasicResponseHandler; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import javax.xml.bind.JAXB; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.time.Instant; import java.time.ZoneId; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.util.*; import java.util.regex.Pattern; import java.util.stream.Collectors; /** * This class provides an implementation of {@link DataAdapter} for JRDS. * * @author Frederic Thevenet */ @XmlAccessorType(XmlAccessType.FIELD) public class JrdsDataAdapter extends HttpDataAdapterBase<Double, CsvDecoder<Double>> { private static final Logger logger = LogManager.getLogger(JrdsDataAdapter.class); private static final char DELIMITER = ','; public static final String JRDS_FILTER = "filter"; public static final String JRDS_TREE = "tree"; protected static final String ENCODING_PARAM_NAME = "encoding"; protected static final String ZONE_ID_PARAM_NAME = "zoneId"; protected static final String TREE_VIEW_TAB_PARAM_NAME = "treeViewTab"; private final JrdsSeriesBindingFactory bindingFactory = new JrdsSeriesBindingFactory(); private final static Pattern uriSchemePattern = Pattern.compile("^[a-zA-Z]*://"); private String filter; private ZoneId zoneId; private String encoding; private JrdsTreeViewTab treeViewTab; /** * Default constructor */ public JrdsDataAdapter() throws DataAdapterException { super(); } /** * Initializes a new instance of the {@link JrdsDataAdapter} class. * * @param zoneId the id of the time zone used to record dates. * @param encoding the encoding used by the download servlet. * @param treeViewTab the filter to apply to the tree view */ public JrdsDataAdapter(URL baseURL, ZoneId zoneId, String encoding, JrdsTreeViewTab treeViewTab, String filter) throws DataAdapterException { super(baseURL); this.zoneId = zoneId; this.encoding = encoding; this.treeViewTab = treeViewTab; this.filter = filter; } /** * Builds a new instance of the {@link JrdsDataAdapter} class from the provided parameters. * * @param address the URL to the JRDS webapp. * @param zoneId the id of the time zone used to record dates. * @return a new instance of the {@link JrdsDataAdapter} class. */ public static JrdsDataAdapter fromUrl(String address, ZoneId zoneId, JrdsTreeViewTab treeViewTab, String filter) throws DataAdapterException { try { // Detect if URL protocol is present. If not, assume http. if (!uriSchemePattern.matcher(address).find()) { address = "http://" + address; } URL url = new URL(address.replaceAll("/$", "")); if (url.getHost().trim().isEmpty()) { throw new CannotInitializeDataAdapterException("Malformed URL: no host"); } return new JrdsDataAdapter(url, zoneId, "utf-8", treeViewTab, filter); } catch (MalformedURLException e) { throw new CannotInitializeDataAdapterException("Malformed URL: " + e.getMessage(), e); } } //region [DataAdapter Members] @Override public TreeItem<TimeSeriesBinding<Double>> getBindingTree() throws DataAdapterException { Gson gson = new Gson(); try { JsonJrdsTree t = gson.fromJson(getJsonTree(treeViewTab.getCommand(), treeViewTab.getArgument(), filter), JsonJrdsTree.class); Map<String, JsonJrdsItem> m = Arrays.stream(t.items).collect(Collectors.toMap(o -> o.id, (o -> o))); TreeItem<TimeSeriesBinding<Double>> tree = new TreeItem<>(bindingFactory.of("", getSourceName(), "/", this)); for (JsonJrdsItem branch : Arrays.stream(t.items).filter(jsonJrdsItem -> JRDS_TREE.equals(jsonJrdsItem.type) || JRDS_FILTER.equals(jsonJrdsItem.type)).collect(Collectors.toList())) { attachNode(tree, branch.id, m); } return tree; } catch (JsonParseException e) { throw new DataAdapterException("An error occurred while parsing the json response to getBindingTree request", e); } catch (URISyntaxException e) { throw new SourceCommunicationException("Error building URI for request", e); } } @Override protected URI craftFetchUri(String path, Instant begin, Instant end) throws DataAdapterException { try { return new URIBuilder(getBaseAddress().toURI()) .setPath(getBaseAddress().getPath() + "/download") .addParameter("id", path) .addParameter("begin", Long.toString(begin.toEpochMilli())) .addParameter("end", Long.toString(end.toEpochMilli())).build(); } catch (URISyntaxException e) { throw new SourceCommunicationException("Error building URI for request", e); } } @Override public String getSourceName() { return new StringBuilder("[JRDS] ") .append(getBaseAddress() != null ? getBaseAddress().getHost() : "???") .append((getBaseAddress() != null && getBaseAddress().getPort() > 0) ? ":" + getBaseAddress().getPort() : "") .append(" - ") .append(treeViewTab != null ? treeViewTab : "???") .append(filter != null ? filter : "") .append(" (") .append(zoneId != null ? zoneId : "???") .append(")").toString(); } @Override public Map<String, String> getParams() { Map<String, String> params = new HashMap<>(super.getParams()); params.put(ZONE_ID_PARAM_NAME, zoneId.toString()); params.put(ENCODING_PARAM_NAME, encoding); params.put(TREE_VIEW_TAB_PARAM_NAME, treeViewTab.name()); params.put(JRDS_FILTER, this.filter); return params; } @Override public void loadParams(Map<String, String> params) throws DataAdapterException { if (params == null) { throw new InvalidAdapterParameterException("Could not find parameter list for adapter " + getSourceName()); } super.loadParams(params); encoding = validateParameterNullity(params, ENCODING_PARAM_NAME); zoneId = validateParameter(params, ZONE_ID_PARAM_NAME, s -> { if (s == null) { throw new InvalidAdapterParameterException("Parameter " + ZONE_ID_PARAM_NAME + " is missing in adapter " + getSourceName()); } return ZoneId.of(s); }); treeViewTab = validateParameter(params, TREE_VIEW_TAB_PARAM_NAME, s -> s == null ? JrdsTreeViewTab.valueOf(params.get(TREE_VIEW_TAB_PARAM_NAME)) : JrdsTreeViewTab.HOSTS_TAB); this.filter = params.get(JRDS_FILTER); } @Override public boolean ping() { try { return doHttpGet(craftRequestUri(""), new AbstractResponseHandler<Boolean>() { @Override public Boolean handleEntity(HttpEntity entity) throws IOException { String entityString = EntityUtils.toString(entity); logger.trace(entityString); return true; } }); } catch (Exception e) { logger.debug(() -> "Ping failed", e); return false; } } @Override public String getEncoding() { return encoding; } @Override public ZoneId getTimeZoneId() { return zoneId; } @Override public CsvDecoder<Double> getDecoder() { final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(getTimeZoneId()); return new CsvDecoder<>(getEncoding(), DELIMITER, DoubleTimeSeriesProcessor::new, s -> { Double val = Double.parseDouble(s); return val.isNaN() ? 0 : val; }, s -> ZonedDateTime.parse(s, formatter)); } @Override public void close() { super.close(); } //endregion public Collection<String> discoverFilters() throws DataAdapterException, URISyntaxException { Gson gson = new Gson(); try { JsonJrdsTree t = gson.fromJson(getJsonTree(treeViewTab.getCommand(), treeViewTab.getArgument()), JsonJrdsTree.class); return Arrays.stream(t.items).filter(jsonJrdsItem -> JRDS_FILTER.equals(jsonJrdsItem.type)).map(i -> i.filter).collect(Collectors.toList()); } catch (JsonParseException e) { throw new DataAdapterException("An error occurred while parsing the json response to getBindingTree request", e); } } private void attachNode(TreeItem<TimeSeriesBinding<Double>> tree, String id, Map<String, JsonJrdsItem> nodes) throws DataAdapterException { JsonJrdsItem n = nodes.get(id); String currentPath = normalizeId(n.id); TreeItem<TimeSeriesBinding<Double>> newBranch = new TreeItem<>(bindingFactory.of(tree.getValue().getTreeHierarchy(), n.name, currentPath, this)); if (JRDS_FILTER.equals(n.type)) { // add a dummy node so that the branch can be expanded newBranch.getChildren().add(new TreeItem<>(null)); // add a listener that will get the treeview filtered according to the selected filter/tag newBranch.expandedProperty().addListener(new FilteredViewListener(n, newBranch)); } else { if (n.children != null) { for (JsonJrdsItem.JsonTreeRef ref : n.children) { attachNode(newBranch, ref._reference, nodes); } } else { // add a dummy node so that the branch can be expanded newBranch.getChildren().add(new TreeItem<>(null)); // add a listener so that bindings for individual datastore are added lazily to avoid // dozens of individual call to "graphdesc" when the tree is built. newBranch.expandedProperty().addListener(new GraphDescListener(currentPath, newBranch, tree)); } } tree.getChildren().add(newBranch); } private String normalizeId(String id) { if (id == null || id.trim().length() == 0) { throw new IllegalArgumentException("Argument id cannot be null or blank"); } String[] data = id.split("\\."); return data[data.length - 1]; } private String getJsonTree(String tabName, String argName) throws DataAdapterException, URISyntaxException { return getJsonTree(tabName, argName, null); } private String getJsonTree(String tabName, String argName, String argValue) throws DataAdapterException, URISyntaxException { List<NameValuePair> params = new ArrayList<>(); params.add(new BasicNameValuePair("tab", tabName)); if (argName != null && argValue != null && argValue.trim().length() > 0) { params.add(new BasicNameValuePair(argName, argValue)); } String entityString = doHttpGet(craftRequestUri("/jsontree", params), new BasicResponseHandler()); logger.trace(entityString); return entityString; } private Graphdesc getGraphDescriptor(String id) throws DataAdapterException { URI requestUri = craftRequestUri("/graphdesc", new BasicNameValuePair("id", id)); return doHttpGet(requestUri, response -> { StatusLine statusLine = response.getStatusLine(); if (statusLine.getStatusCode() == 404) { // This is probably an older version of JRDS that doesn't provide the graphdesc service, // so we're falling back to recovering the datastore name from the csv file provided by // the download service. logger.warn("Cannot found graphdesc service; falling back to legacy mode."); try { return getGraphDescriptorLegacy(id); } catch (Exception e) { throw new IOException("", e); } } HttpEntity entity = response.getEntity(); if (statusLine.getStatusCode() >= 300) { EntityUtils.consume(entity); throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase()); } if (entity != null) { try { return JAXB.unmarshal(XmlUtils.toNonValidatingSAXSource(entity.getContent()), Graphdesc.class); } catch (Exception e) { throw new IOException("Failed to unmarshall graphdesc response", e); } } return null; }); } private Graphdesc getGraphDescriptorLegacy(String id) throws DataAdapterException { Instant now = ZonedDateTime.now().toInstant(); try (ByteArrayOutputStream out = new ByteArrayOutputStream()) { try (InputStream in = fetchRawData(id, now.minusSeconds(300), now, false)) { List<String> headers = getDecoder().getDataColumnHeaders(in); Graphdesc desc = new Graphdesc(); desc.seriesDescList = new ArrayList<>(); for (String header : headers) { Graphdesc.SeriesDesc d = new Graphdesc.SeriesDesc(); d.name = header; desc.seriesDescList.add(d); } return desc; } } catch (IOException e) { throw new FetchingDataFromAdapterException(e); } } private class GraphDescListener implements ChangeListener<Boolean> { private final String currentPath; private final TreeItem<TimeSeriesBinding<Double>> newBranch; private final TreeItem<TimeSeriesBinding<Double>> tree; public GraphDescListener(String currentPath, TreeItem<TimeSeriesBinding<Double>> newBranch, TreeItem<TimeSeriesBinding<Double>> tree) { this.currentPath = currentPath; this.newBranch = newBranch; this.tree = tree; } @Override public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { if (newValue) { try { Graphdesc graphdesc = getGraphDescriptor(currentPath); newBranch.setValue(bindingFactory.of(tree.getValue().getTreeHierarchy(), newBranch.getValue().getLegend(), graphdesc, currentPath, JrdsDataAdapter.this)); for (int i = 0; i < graphdesc.seriesDescList.size(); i++) { String graphType = graphdesc.seriesDescList.get(i).graphType; if (!"none".equalsIgnoreCase(graphType) && !"comment".equalsIgnoreCase(graphType)) { newBranch.getChildren().add(new TreeItem<>(bindingFactory.of(tree.getValue().getTreeHierarchy(), graphdesc, i, currentPath, JrdsDataAdapter.this))); } } //remove dummy node newBranch.getChildren().remove(0); // remove the listener so it isn't executed next time node is expanded newBranch.expandedProperty().removeListener(this); } catch (Exception e) { Dialogs.notifyException("Failed to retrieve graph description", e); } } } } private class FilteredViewListener implements ChangeListener<Boolean> { private final JsonJrdsItem n; private final TreeItem<TimeSeriesBinding<Double>> newBranch; public FilteredViewListener(JsonJrdsItem n, TreeItem<TimeSeriesBinding<Double>> newBranch) { this.n = n; this.newBranch = newBranch; } @Override public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { if (newValue) { try { JsonJrdsTree t = new Gson().fromJson(getJsonTree(treeViewTab.getCommand(), JRDS_FILTER, n.name), JsonJrdsTree.class); Map<String, JsonJrdsItem> m = Arrays.stream(t.items).collect(Collectors.toMap(o -> o.id, (o -> o))); for (JsonJrdsItem branch : Arrays.stream(t.items).filter(jsonJrdsItem -> JRDS_TREE.equals(jsonJrdsItem.type) || JRDS_FILTER.equals(jsonJrdsItem.type)).collect(Collectors.toList())) { attachNode(newBranch, branch.id, m); } //remove dummy node newBranch.getChildren().remove(0); // remove the listener so it isn't executed next time node is expanded newBranch.expandedProperty().removeListener(this); } catch (Exception e) { Dialogs.notifyException("Failed to retrieve graph description", e); } } } } }
binjr/src/main/java/eu/fthevenet/binjr/sources/jrds/adapters/JrdsDataAdapter.java
/* * Copyright 2017 Frederic Thevenet * * 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 eu.fthevenet.binjr.sources.jrds.adapters; import com.google.gson.Gson; import com.google.gson.JsonParseException; import eu.fthevenet.binjr.data.adapters.DataAdapter; import eu.fthevenet.binjr.data.adapters.HttpDataAdapterBase; import eu.fthevenet.binjr.data.adapters.TimeSeriesBinding; import eu.fthevenet.binjr.data.codec.CsvDecoder; import eu.fthevenet.binjr.data.exceptions.*; import eu.fthevenet.binjr.data.timeseries.DoubleTimeSeriesProcessor; import eu.fthevenet.binjr.dialogs.Dialogs; import eu.fthevenet.binjr.sources.jrds.adapters.json.JsonJrdsItem; import eu.fthevenet.binjr.sources.jrds.adapters.json.JsonJrdsTree; import eu.fthevenet.util.xml.XmlUtils; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.scene.control.TreeItem; import org.apache.http.HttpEntity; import org.apache.http.NameValuePair; import org.apache.http.StatusLine; import org.apache.http.client.HttpResponseException; import org.apache.http.client.utils.URIBuilder; import org.apache.http.impl.client.AbstractResponseHandler; import org.apache.http.impl.client.BasicResponseHandler; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import javax.xml.bind.JAXB; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.time.Instant; import java.time.ZoneId; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.util.*; import java.util.regex.Pattern; import java.util.stream.Collectors; /** * This class provides an implementation of {@link DataAdapter} for JRDS. * * @author Frederic Thevenet */ @XmlAccessorType(XmlAccessType.FIELD) public class JrdsDataAdapter extends HttpDataAdapterBase<Double, CsvDecoder<Double>> { private static final Logger logger = LogManager.getLogger(JrdsDataAdapter.class); private static final char DELIMITER = ','; public static final String JRDS_FILTER = "filter"; public static final String JRDS_TREE = "tree"; protected static final String ENCODING_PARAM_NAME = "encoding"; protected static final String ZONE_ID_PARAM_NAME = "zoneId"; protected static final String TREE_VIEW_TAB_PARAM_NAME = "treeViewTab"; private final JrdsSeriesBindingFactory bindingFactory = new JrdsSeriesBindingFactory(); private final static Pattern uriSchemePattern = Pattern.compile("^[a-zA-Z]*://"); private String filter; private ZoneId zoneId; private String encoding; private JrdsTreeViewTab treeViewTab; /** * Default constructor */ public JrdsDataAdapter() throws DataAdapterException { super(); } /** * Initializes a new instance of the {@link JrdsDataAdapter} class. * * @param zoneId the id of the time zone used to record dates. * @param encoding the encoding used by the download servlet. * @param treeViewTab the filter to apply to the tree view */ public JrdsDataAdapter(URL baseURL, ZoneId zoneId, String encoding, JrdsTreeViewTab treeViewTab, String filter) throws DataAdapterException { super(baseURL); this.zoneId = zoneId; this.encoding = encoding; this.treeViewTab = treeViewTab; this.filter = filter; } /** * Builds a new instance of the {@link JrdsDataAdapter} class from the provided parameters. * * @param address the URL to the JRDS webapp. * @param zoneId the id of the time zone used to record dates. * @return a new instance of the {@link JrdsDataAdapter} class. */ public static JrdsDataAdapter fromUrl(String address, ZoneId zoneId, JrdsTreeViewTab treeViewTab, String filter) throws DataAdapterException { try { // Detect if URL protocol is present. If not, assume http. if (!uriSchemePattern.matcher(address).find()) { address = "http://" + address; } URL url = new URL(address); if (url.getHost().trim().isEmpty()) { throw new CannotInitializeDataAdapterException("Malformed URL: no host"); } return new JrdsDataAdapter(url, zoneId, "utf-8", treeViewTab, filter); } catch (MalformedURLException e) { throw new CannotInitializeDataAdapterException("Malformed URL: " + e.getMessage(), e); } } //region [DataAdapter Members] @Override public TreeItem<TimeSeriesBinding<Double>> getBindingTree() throws DataAdapterException { Gson gson = new Gson(); try { JsonJrdsTree t = gson.fromJson(getJsonTree(treeViewTab.getCommand(), treeViewTab.getArgument(), filter), JsonJrdsTree.class); Map<String, JsonJrdsItem> m = Arrays.stream(t.items).collect(Collectors.toMap(o -> o.id, (o -> o))); TreeItem<TimeSeriesBinding<Double>> tree = new TreeItem<>(bindingFactory.of("", getSourceName(), "/", this)); for (JsonJrdsItem branch : Arrays.stream(t.items).filter(jsonJrdsItem -> JRDS_TREE.equals(jsonJrdsItem.type) || JRDS_FILTER.equals(jsonJrdsItem.type)).collect(Collectors.toList())) { attachNode(tree, branch.id, m); } return tree; } catch (JsonParseException e) { throw new DataAdapterException("An error occurred while parsing the json response to getBindingTree request", e); } catch (URISyntaxException e) { throw new SourceCommunicationException("Error building URI for request", e); } } @Override protected URI craftFetchUri(String path, Instant begin, Instant end) throws DataAdapterException { try { return new URIBuilder(getBaseAddress().toURI()) .setPath(getBaseAddress().getPath() + "/download") .addParameter("id", path) .addParameter("begin", Long.toString(begin.toEpochMilli())) .addParameter("end", Long.toString(end.toEpochMilli())).build(); } catch (URISyntaxException e) { throw new SourceCommunicationException("Error building URI for request", e); } } @Override public String getSourceName() { return new StringBuilder("[JRDS] ") .append(getBaseAddress() != null ? getBaseAddress().getHost() : "???") .append((getBaseAddress() != null && getBaseAddress().getPort() > 0) ? ":" + getBaseAddress().getPort() : "") .append(" - ") .append(treeViewTab != null ? treeViewTab : "???") .append(filter != null ? filter : "") .append(" (") .append(zoneId != null ? zoneId : "???") .append(")").toString(); } @Override public Map<String, String> getParams() { Map<String, String> params = new HashMap<>(super.getParams()); params.put(ZONE_ID_PARAM_NAME, zoneId.toString()); params.put(ENCODING_PARAM_NAME, encoding); params.put(TREE_VIEW_TAB_PARAM_NAME, treeViewTab.name()); params.put(JRDS_FILTER, this.filter); return params; } @Override public void loadParams(Map<String, String> params) throws DataAdapterException { if (params == null) { throw new InvalidAdapterParameterException("Could not find parameter list for adapter " + getSourceName()); } super.loadParams(params); encoding = validateParameterNullity(params, ENCODING_PARAM_NAME); zoneId = validateParameter(params, ZONE_ID_PARAM_NAME, s -> { if (s == null) { throw new InvalidAdapterParameterException("Parameter " + ZONE_ID_PARAM_NAME + " is missing in adapter " + getSourceName()); } return ZoneId.of(s); }); treeViewTab = validateParameter(params, TREE_VIEW_TAB_PARAM_NAME, s -> s == null ? JrdsTreeViewTab.valueOf(params.get(TREE_VIEW_TAB_PARAM_NAME)) : JrdsTreeViewTab.HOSTS_TAB); this.filter = params.get(JRDS_FILTER); } @Override public boolean ping() { try { return doHttpGet(craftRequestUri(""), new AbstractResponseHandler<Boolean>() { @Override public Boolean handleEntity(HttpEntity entity) throws IOException { String entityString = EntityUtils.toString(entity); logger.trace(entityString); return true; } }); } catch (Exception e) { logger.debug(() -> "Ping failed", e); return false; } } @Override public String getEncoding() { return encoding; } @Override public ZoneId getTimeZoneId() { return zoneId; } @Override public CsvDecoder<Double> getDecoder() { final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(getTimeZoneId()); return new CsvDecoder<>(getEncoding(), DELIMITER, DoubleTimeSeriesProcessor::new, s -> { Double val = Double.parseDouble(s); return val.isNaN() ? 0 : val; }, s -> ZonedDateTime.parse(s, formatter)); } @Override public void close() { super.close(); } //endregion public Collection<String> discoverFilters() throws DataAdapterException, URISyntaxException { Gson gson = new Gson(); try { JsonJrdsTree t = gson.fromJson(getJsonTree(treeViewTab.getCommand(), treeViewTab.getArgument()), JsonJrdsTree.class); return Arrays.stream(t.items).filter(jsonJrdsItem -> JRDS_FILTER.equals(jsonJrdsItem.type)).map(i -> i.filter).collect(Collectors.toList()); } catch (JsonParseException e) { throw new DataAdapterException("An error occurred while parsing the json response to getBindingTree request", e); } } private void attachNode(TreeItem<TimeSeriesBinding<Double>> tree, String id, Map<String, JsonJrdsItem> nodes) throws DataAdapterException { JsonJrdsItem n = nodes.get(id); String currentPath = normalizeId(n.id); TreeItem<TimeSeriesBinding<Double>> newBranch = new TreeItem<>(bindingFactory.of(tree.getValue().getTreeHierarchy(), n.name, currentPath, this)); if (JRDS_FILTER.equals(n.type)) { // add a dummy node so that the branch can be expanded newBranch.getChildren().add(new TreeItem<>(null)); // add a listener that will get the treeview filtered according to the selected filter/tag newBranch.expandedProperty().addListener(new FilteredViewListener(n, newBranch)); } else { if (n.children != null) { for (JsonJrdsItem.JsonTreeRef ref : n.children) { attachNode(newBranch, ref._reference, nodes); } } else { // add a dummy node so that the branch can be expanded newBranch.getChildren().add(new TreeItem<>(null)); // add a listener so that bindings for individual datastore are added lazily to avoid // dozens of individual call to "graphdesc" when the tree is built. newBranch.expandedProperty().addListener(new GraphDescListener(currentPath, newBranch, tree)); } } tree.getChildren().add(newBranch); } private String normalizeId(String id) { if (id == null || id.trim().length() == 0) { throw new IllegalArgumentException("Argument id cannot be null or blank"); } String[] data = id.split("\\."); return data[data.length - 1]; } private String getJsonTree(String tabName, String argName) throws DataAdapterException, URISyntaxException { return getJsonTree(tabName, argName, null); } private String getJsonTree(String tabName, String argName, String argValue) throws DataAdapterException, URISyntaxException { List<NameValuePair> params = new ArrayList<>(); params.add(new BasicNameValuePair("tab", tabName)); if (argName != null && argValue != null && argValue.trim().length() > 0) { params.add(new BasicNameValuePair(argName, argValue)); } String entityString = doHttpGet(craftRequestUri("/jsontree", params), new BasicResponseHandler()); logger.trace(entityString); return entityString; } private Graphdesc getGraphDescriptor(String id) throws DataAdapterException { URI requestUri = craftRequestUri("/graphdesc", new BasicNameValuePair("id", id)); return doHttpGet(requestUri, response -> { StatusLine statusLine = response.getStatusLine(); if (statusLine.getStatusCode() == 404) { // This is probably an older version of JRDS that doesn't provide the graphdesc service, // so we're falling back to recovering the datastore name from the csv file provided by // the download service. logger.warn("Cannot found graphdesc service; falling back to legacy mode."); try { return getGraphDescriptorLegacy(id); } catch (Exception e) { throw new IOException("", e); } } HttpEntity entity = response.getEntity(); if (statusLine.getStatusCode() >= 300) { EntityUtils.consume(entity); throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase()); } if (entity != null) { try { return JAXB.unmarshal(XmlUtils.toNonValidatingSAXSource(entity.getContent()), Graphdesc.class); } catch (Exception e) { throw new IOException("Failed to unmarshall graphdesc response", e); } } return null; }); } private Graphdesc getGraphDescriptorLegacy(String id) throws DataAdapterException { Instant now = ZonedDateTime.now().toInstant(); try (ByteArrayOutputStream out = new ByteArrayOutputStream()) { try (InputStream in = fetchRawData(id, now.minusSeconds(300), now, false)) { List<String> headers = getDecoder().getDataColumnHeaders(in); Graphdesc desc = new Graphdesc(); desc.seriesDescList = new ArrayList<>(); for (String header : headers) { Graphdesc.SeriesDesc d = new Graphdesc.SeriesDesc(); d.name = header; desc.seriesDescList.add(d); } return desc; } } catch (IOException e) { throw new FetchingDataFromAdapterException(e); } } private class GraphDescListener implements ChangeListener<Boolean> { private final String currentPath; private final TreeItem<TimeSeriesBinding<Double>> newBranch; private final TreeItem<TimeSeriesBinding<Double>> tree; public GraphDescListener(String currentPath, TreeItem<TimeSeriesBinding<Double>> newBranch, TreeItem<TimeSeriesBinding<Double>> tree) { this.currentPath = currentPath; this.newBranch = newBranch; this.tree = tree; } @Override public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { if (newValue) { try { Graphdesc graphdesc = getGraphDescriptor(currentPath); newBranch.setValue(bindingFactory.of(tree.getValue().getTreeHierarchy(), newBranch.getValue().getLegend(), graphdesc, currentPath, JrdsDataAdapter.this)); for (int i = 0; i < graphdesc.seriesDescList.size(); i++) { String graphType = graphdesc.seriesDescList.get(i).graphType; if (!"none".equalsIgnoreCase(graphType) && !"comment".equalsIgnoreCase(graphType)) { newBranch.getChildren().add(new TreeItem<>(bindingFactory.of(tree.getValue().getTreeHierarchy(), graphdesc, i, currentPath, JrdsDataAdapter.this))); } } //remove dummy node newBranch.getChildren().remove(0); // remove the listener so it isn't executed next time node is expanded newBranch.expandedProperty().removeListener(this); } catch (Exception e) { Dialogs.notifyException("Failed to retrieve graph description", e); } } } } private class FilteredViewListener implements ChangeListener<Boolean> { private final JsonJrdsItem n; private final TreeItem<TimeSeriesBinding<Double>> newBranch; public FilteredViewListener(JsonJrdsItem n, TreeItem<TimeSeriesBinding<Double>> newBranch) { this.n = n; this.newBranch = newBranch; } @Override public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { if (newValue) { try { JsonJrdsTree t = new Gson().fromJson(getJsonTree(treeViewTab.getCommand(), JRDS_FILTER, n.name), JsonJrdsTree.class); Map<String, JsonJrdsItem> m = Arrays.stream(t.items).collect(Collectors.toMap(o -> o.id, (o -> o))); for (JsonJrdsItem branch : Arrays.stream(t.items).filter(jsonJrdsItem -> JRDS_TREE.equals(jsonJrdsItem.type) || JRDS_FILTER.equals(jsonJrdsItem.type)).collect(Collectors.toList())) { attachNode(newBranch, branch.id, m); } //remove dummy node newBranch.getChildren().remove(0); // remove the listener so it isn't executed next time node is expanded newBranch.expandedProperty().removeListener(this); } catch (Exception e) { Dialogs.notifyException("Failed to retrieve graph description", e); } } } } }
Fixed JRDS adapter fails to connect to source if url contains a trailing slash
binjr/src/main/java/eu/fthevenet/binjr/sources/jrds/adapters/JrdsDataAdapter.java
Fixed JRDS adapter fails to connect to source if url contains a trailing slash
<ide><path>injr/src/main/java/eu/fthevenet/binjr/sources/jrds/adapters/JrdsDataAdapter.java <ide> if (!uriSchemePattern.matcher(address).find()) { <ide> address = "http://" + address; <ide> } <del> URL url = new URL(address); <add> URL url = new URL(address.replaceAll("/$", "")); <ide> if (url.getHost().trim().isEmpty()) { <ide> throw new CannotInitializeDataAdapterException("Malformed URL: no host"); <ide> }
Java
apache-2.0
0228bb4e30089e3a3c0075a28d776882a64d121b
0
DrMrSrTeacherSr/MMLS,DrMrSrTeacherSr/MMLS,DrMrSrTeacherSr/MMLS,DrMrSrTeacherSr/MMLS
import java.net.UnknownHostException; import com.mongodb.BasicDBList; import com.mongodb.BasicDBObject; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBCursor; import com.mongodb.DBObject; import com.mongodb.MongoClient; public class HandWritingWrapper { private MongoClient mongoClient; private DB db; private DBCollection coll; public HandWritingWrapper() { try { mongoClient = new MongoClient(); db = mongoClient.getDB("MasterDB"); coll = db.getCollection("mnist"); BasicDBObject query = new BasicDBObject("test",0); DBCursor data = coll.find(query); int count = 0; while(data.hasNext()){ DBObject temp = data.next(); double[] label = {(int) temp.get("label")}; double[] imageData = new double[28*28]; BasicDBList image = (BasicDBList) temp.get("image"); for(int i = 0; i < image.size(); i++){ imageData[i + 28*count] = Double.parseDouble(image.get(i).toString()); } count++; } System.out.println(db.getCollectionNames()); } catch (UnknownHostException e) { e.printStackTrace(); } } public static void main(String[] args){ new HandWritingWrapper(); } }
src/HandWritingWrapper.java
import java.net.UnknownHostException; import com.mongodb.BasicDBList; import com.mongodb.BasicDBObject; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBCursor; import com.mongodb.DBObject; import com.mongodb.MongoClient; public class HandWritingWrapper { private MongoClient mongoClient; private DB db; private DBCollection coll; public HandWritingWrapper() { try { mongoClient = new MongoClient(); db = mongoClient.getDB("MasterDB"); coll = db.getCollection("mnist"); BasicDBObject query = new BasicDBObject("test",0); DBCursor data = coll.find(query); while(data.hasNext()){ DBObject temp = data.next(); int label = (int) temp.get("label"); BasicDBList image = (BasicDBList) temp.get("image"); for(int i = 0; i < image.size(); i++){ System.out.println(image.get(i)); } } System.out.println(db.getCollectionNames()); } catch (UnknownHostException e) { e.printStackTrace(); } } public static void main(String[] args){ new HandWritingWrapper(); } }
HandWriting
src/HandWritingWrapper.java
HandWriting
<ide><path>rc/HandWritingWrapper.java <ide> <ide> BasicDBObject query = new BasicDBObject("test",0); <ide> DBCursor data = coll.find(query); <add> int count = 0; <ide> while(data.hasNext()){ <ide> DBObject temp = data.next(); <del> int label = (int) temp.get("label"); <add> double[] label = {(int) temp.get("label")}; <add> double[] imageData = new double[28*28]; <ide> BasicDBList image = (BasicDBList) temp.get("image"); <ide> <ide> for(int i = 0; i < image.size(); i++){ <del> System.out.println(image.get(i)); <add> imageData[i + 28*count] = Double.parseDouble(image.get(i).toString()); <ide> } <add> count++; <ide> } <ide> <ide> System.out.println(db.getCollectionNames());
Java
bsd-3-clause
18380df59e89a1a991ed31e0687d08983a3e395e
0
nuagenetworks/java-bambou
/* Copyright (c) 2015, Alcatel-Lucent Inc All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package net.nuagenetworks.bambou; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.codec.binary.Base64; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.databind.JsonNode; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import net.nuagenetworks.bambou.jms.RestPushCenterJmsActiveMQ; import net.nuagenetworks.bambou.jms.RestPushCenterJmsDirectActiveMQ; import net.nuagenetworks.bambou.jms.RestPushCenterJmsDirectJBoss; import net.nuagenetworks.bambou.jms.RestPushCenterJmsJBoss; import net.nuagenetworks.bambou.operation.RestSessionOperations; import net.nuagenetworks.bambou.service.RestClientService; import net.nuagenetworks.bambou.annotation.RestEntity; import net.nuagenetworks.bambou.util.BambouUtils; public class RestSession<R extends RestRootObject> implements RestSessionOperations { private static final String ORGANIZATION_HEADER = "X-Nuage-Organization"; private static final String CONTENT_TYPE_JSON = "application/json"; private static final Logger logger = LoggerFactory.getLogger(RestSession.class); private static final ThreadLocal<RestSession<?>> currentSession = new ThreadLocal<RestSession<?>>(); @Autowired private RestClientService restClientService; private String username; private String password; private String enterprise; private String apiUrl; private String apiPrefix; private String certificate; private String privateKey; private double version; private String apiKey; private Class<R> restRootObjClass; private R restRootObj; public RestSession(Class<R> restRootObjClass) { this.restRootObjClass = restRootObjClass; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getEnterprise() { return enterprise; } public void setEnterprise(String enterprise) { this.enterprise = enterprise; } public String getApiUrl() { return apiUrl; } public void setApiUrl(String apiUrl) { this.apiUrl = apiUrl; } public String getApiPrefix() { return apiPrefix; } public void setApiPrefix(String apiPrefix) { this.apiPrefix = apiPrefix; } public String getCertificate() { return certificate; } public void setCertificate(String certificate) { this.certificate = certificate; } public String getPrivateKey() { return privateKey; } public void setPrivateKey(String privateKey) { this.privateKey = privateKey; } public double getVersion() { return version; } public void setVersion(double version) { this.version = version; } protected void setApiKey(String apiKey) { this.apiKey = apiKey; } protected static RestSession<?> getCurrentSession() { return currentSession.get(); } public R getRootObject() { return restRootObj; } public String getVSDVersion() { try { ResponseEntity<JsonNode> resp = restClientService.sendRequest(HttpMethod.GET,this.apiUrl+"/nuage",null,null,JsonNode.class); JsonNode node = resp.getBody(); return node.get("vsdBuild").textValue(); } catch (Exception e) { logger.error("Error: ",e); } return null; } @Override public void start() throws RestException { currentSession.set(this); restClientService.prepareSSLAuthentication(certificate, privateKey); authenticate(); } @Override public void reset() { restRootObj = null; apiKey = null; currentSession.set(null); } /** * @deprecated use {@link #createPushCenter() or @link * #createPushCenter(RestPushCenterType)} instead. */ @Deprecated public RestPushCenter getPushCenter() { return createPushCenter(RestPushCenterType.LONG_POLL); } public RestPushCenter createPushCenter() { // PushCenter implementation defaults to JMS from now on return createPushCenter(RestPushCenterType.JMS); } public RestPushCenter createPushCenter(RestPushCenterType pushCenterType) { RestPushCenter pushCenter; if (pushCenterType == RestPushCenterType.JMS) { if (version >= 5.0) { // VSD version 5.0.x uses a different JMS client than previous // releases RestPushCenterJmsActiveMQ pushCenterJmsActiveMQ = new RestPushCenterJmsActiveMQ(); if (username != null && password != null && enterprise != null) { String jmsUser = username + "@" + enterprise; String jmsPassword = password; pushCenterJmsActiveMQ.setUser(jmsUser); pushCenterJmsActiveMQ.setPassword(jmsPassword); } pushCenter = pushCenterJmsActiveMQ; } else { pushCenter = new RestPushCenterJmsJBoss(); } } else if (pushCenterType == RestPushCenterType.JMS_NO_JNDI) { if (version >= 5.0) { // VSD version 5.0.x uses a different JMS client than previous // releases RestPushCenterJmsDirectActiveMQ pushCenterJmsActiveMQ = new RestPushCenterJmsDirectActiveMQ(); if (username != null && password != null && enterprise != null) { String jmsUser = username + "@" + enterprise; String jmsPassword = password; pushCenterJmsActiveMQ.setUser(jmsUser); pushCenterJmsActiveMQ.setPassword(jmsPassword); } pushCenter = pushCenterJmsActiveMQ; } else { pushCenter = new RestPushCenterJmsDirectJBoss(); } } else { pushCenter = new RestPushCenterLongPoll(this); } String url = getRestBaseUrl(); pushCenter.setUrl(url); return pushCenter; } @Override public <T extends RestObject> BulkResponse<T> bulkSave(List<T> objList) throws RestException { String params = BambouUtils.getResponseChoiceParam(1); ResponseEntity<BulkResponse> response = this.sendRequestWithRetry(HttpMethod.PUT, getResourceUrlForParentType(objList.get(0).getClass()), params, null, objList, BulkResponse.class); if (response.getStatusCode().series() == HttpStatus.Series.SUCCESSFUL) { return response.getBody(); // Success } else { // Error throw new RestException("Response received with status code: " + response.getStatusCode()); } } @Override public <T extends RestObject> BulkResponse<T> bulkDelete(List<T> objList) throws RestException { String params = BambouUtils.getResponseChoiceParam(1); for (T item : objList) { params += "&id="+item.getId(); } ResponseEntity<BulkResponse> response = this.sendRequestWithRetry(HttpMethod.DELETE, getResourceUrlForParentType(objList.get(0).getClass()), params, null, null, BulkResponse.class); if (response.getStatusCode().series() == HttpStatus.Series.SUCCESSFUL) { return response.getBody(); // Success } else { // Error throw new RestException("Response received with status code: " + response.getStatusCode()); } } @Override public <T extends RestObject> BulkResponse<T> createChildren(RestObject parent, List<T> children) throws RestException { return parent.createChildren(this,children); } @Override public void fetch(RestObject restObj) throws RestException { restObj.fetch(this); } @Override public void save(RestObject restObj) throws RestException { restObj.save(this); } @Override public void save(RestObject restObj, Integer responseChoice) throws RestException { restObj.save(this, responseChoice); } @Override public void delete(RestObject restObj) throws RestException { restObj.delete(this); } @Override public void delete(RestObject restObj, Integer responseChoice) throws RestException { restObj.delete(this, responseChoice); } @Override public void createChild(RestObject restObj, RestObject childRestObj) throws RestException { restObj.createChild(this, childRestObj); } @Override public void createChild(RestObject restObj, RestObject childRestObj, Integer responseChoice, boolean commit) throws RestException { restObj.createChild(this, childRestObj, responseChoice, commit); } @Override public void instantiateChild(RestObject restObj, RestObject childRestObj, RestObject fromTemplate) throws RestException { restObj.instantiateChild(this, childRestObj, fromTemplate); } @Override public void instantiateChild(RestObject restObj, RestObject childRestObj, RestObject fromTemplate, Integer responseChoice, boolean commit) throws RestException { restObj.instantiateChild(this, childRestObj, fromTemplate, responseChoice, commit); } @Override public void assign(RestObject restObj, List<? extends RestObject> childRestObjs) throws RestException { restObj.assign(this, childRestObjs); } @Override public void assign(RestObject restObj, List<? extends RestObject> childRestObjs, boolean commit) throws RestException { restObj.assign(this, childRestObjs, commit); } @Override public void assign(RestObject restObj, List<? extends RestObject> childRestObjs,Integer responseChoice, boolean commit) throws RestException { restObj.assign(this, childRestObjs, responseChoice, commit); } @Override public <T extends RestObject> List<T> get(RestFetcher<T> fetcher) throws RestException { return get(fetcher, null, null, null, null, null, null, true); } @Override public <T extends RestObject> List<T> fetch(RestFetcher<T> fetcher) throws RestException { return fetch(fetcher, null, null, null, null, null, null, true); } @Override public <T extends RestObject> T getFirst(RestFetcher<T> fetcher) throws RestException { return getFirst(fetcher, null, null, null, null, null, null, true); } @Override public <T extends RestObject> int count(RestFetcher<T> fetcher) throws RestException { return count(fetcher, null, null, null, null, null, null, true); } @Override public <T extends RestObject> List<T> get(RestFetcher<T> fetcher, String filter, String orderBy, String[] groupBy, Integer page, Integer pageSize, String queryParameters, boolean commit) throws RestException { return fetcher.get(this, filter, orderBy, groupBy, page, pageSize, queryParameters, commit); } @Override public <T extends RestObject> List<T> fetch(RestFetcher<T> fetcher, String filter, String orderBy, String[] groupBy, Integer page, Integer pageSize, String queryParameters, boolean commit) throws RestException { return fetcher.fetch(this, filter, orderBy, groupBy, page, pageSize, queryParameters, commit); } @Override public <T extends RestObject> T getFirst(RestFetcher<T> fetcher, String filter, String orderBy, String[] groupBy, Integer page, Integer pageSize, String queryParameters, boolean commit) throws RestException { return fetcher.getFirst(this, filter, orderBy, groupBy, page, pageSize, queryParameters, commit); } @Override public <T extends RestObject> int count(RestFetcher<T> fetcher, String filter, String orderBy, String[] groupBy, Integer page, Integer pageSize, String queryParameters, boolean commit) throws RestException { return fetcher.count(this, filter, orderBy, groupBy, page, pageSize, queryParameters, commit); } protected <T, U> ResponseEntity<T> sendRequestWithRetry(HttpMethod method, String url, String params, HttpHeaders headers, U requestObj, Class<T> responseType) throws RestException { if (params != null) { url += (url.indexOf('?') >= 0) ? ";" + params : "?" + params; } if (headers == null) { headers = new HttpHeaders(); } headers.set(HttpHeaders.CONTENT_TYPE, CONTENT_TYPE_JSON); headers.set(ORGANIZATION_HEADER, getEnterprise()); headers.set(HttpHeaders.AUTHORIZATION, getAuthenticationHeader()); logger.info(url); try { return restClientService.sendRequest(method, url, headers, requestObj, responseType); } catch (RestStatusCodeException ex) { if (ex.getStatusCode() == HttpStatus.UNAUTHORIZED) { // Debug logger.info("HTTP 401/Unauthorized response received"); // Make sure we are not already re-authenticating // in order to avoid infinite recursion if (!(method == HttpMethod.GET && url.equals(restRootObj.getResourceUrl(this)))) { // Re-authenticate the session and try to send the same // request again. A new API key might get issued as a result reset(); authenticate(); currentSession.set(this); // Update authorization header with new API key headers.set(HttpHeaders.AUTHORIZATION, getAuthenticationHeader()); return restClientService.sendRequest(method, url, headers, requestObj, responseType); } else { throw ex; } } else { throw ex; } } } protected String getRestBaseUrl() { int roundedVersion = (int)version; return String.format("%s/%s/v%s", apiUrl, apiPrefix, String.valueOf(roundedVersion)); } protected String getResourceUrlForParentType(Class<?> parentRestObjClass) { RestEntity annotation = parentRestObjClass.getAnnotation(RestEntity.class); String parentResourceName = annotation.resourceName(); return String.format("%s/%s", getRestBaseUrl(), parentResourceName); } private synchronized void authenticate() throws RestException { // Create the root object if needed if (restRootObj == null) { restRootObj = createRootObject(); fetch(restRootObj); } // Copy the API key from the root object apiKey = restRootObj.getApiKey(); // Debug logger.debug("Started session with username: " + username + " in enterprise: " + enterprise); } private R createRootObject() throws RestException { try { return restRootObjClass.newInstance(); } catch (InstantiationException | IllegalAccessException ex) { throw new RestException(ex); } } private String getAuthenticationHeader() { if (apiKey != null) { return String.format("XREST %s", Base64.encodeBase64String(String.format("%s:%s", username, apiKey).getBytes())); } else { return String.format("XREST %s", Base64.encodeBase64String(String.format("%s:%s", username, password).getBytes())); } } @Override public String toString() { return "RestSession [restClientService=" + restClientService + ", username=" + username + ", password=" + password + ", enterprise=" + enterprise + ", apiUrl=" + apiUrl + ", apiPrefix=" + apiPrefix + ", certificate=" + certificate + ", privateKey=" + privateKey + ", version=" + version + ", apiKey=" + apiKey + ", restRootObjClass=" + restRootObjClass + ", restRootObj=" + restRootObj + "]"; } }
src/main/java/net/nuagenetworks/bambou/RestSession.java
/* Copyright (c) 2015, Alcatel-Lucent Inc All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package net.nuagenetworks.bambou; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.codec.binary.Base64; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.databind.JsonNode; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import net.nuagenetworks.bambou.jms.RestPushCenterJmsActiveMQ; import net.nuagenetworks.bambou.jms.RestPushCenterJmsDirectActiveMQ; import net.nuagenetworks.bambou.jms.RestPushCenterJmsDirectJBoss; import net.nuagenetworks.bambou.jms.RestPushCenterJmsJBoss; import net.nuagenetworks.bambou.operation.RestSessionOperations; import net.nuagenetworks.bambou.service.RestClientService; import net.nuagenetworks.bambou.annotation.RestEntity; import net.nuagenetworks.bambou.util.BambouUtils; public class RestSession<R extends RestRootObject> implements RestSessionOperations { private static final String ORGANIZATION_HEADER = "X-Nuage-Organization"; private static final String CONTENT_TYPE_JSON = "application/json"; private static final Logger logger = LoggerFactory.getLogger(RestSession.class); private static final ThreadLocal<RestSession<?>> currentSession = new ThreadLocal<RestSession<?>>(); @Autowired private RestClientService restClientService; private String username; private String password; private String enterprise; private String apiUrl; private String apiPrefix; private String certificate; private String privateKey; private double version; private String apiKey; private Class<R> restRootObjClass; private R restRootObj; public RestSession(Class<R> restRootObjClass) { this.restRootObjClass = restRootObjClass; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getEnterprise() { return enterprise; } public void setEnterprise(String enterprise) { this.enterprise = enterprise; } public String getApiUrl() { return apiUrl; } public void setApiUrl(String apiUrl) { this.apiUrl = apiUrl; } public String getApiPrefix() { return apiPrefix; } public void setApiPrefix(String apiPrefix) { this.apiPrefix = apiPrefix; } public String getCertificate() { return certificate; } public void setCertificate(String certificate) { this.certificate = certificate; } public String getPrivateKey() { return privateKey; } public void setPrivateKey(String privateKey) { this.privateKey = privateKey; } public double getVersion() { return version; } public void setVersion(double version) { this.version = version; } protected void setApiKey(String apiKey) { this.apiKey = apiKey; } protected static RestSession<?> getCurrentSession() { return currentSession.get(); } public R getRootObject() { return restRootObj; } public String getVSDVersion() { try { ResponseEntity<JsonNode> resp = restClientService.sendRequest(HttpMethod.GET,this.apiUrl+"/nuage",null,null,JsonNode.class); JsonNode node = resp.getBody(); return node.get("vsdBuild").textValue(); } catch (Exception e) { logger.error("Error: ",e); } return null; } @Override public void start() throws RestException { currentSession.set(this); restClientService.prepareSSLAuthentication(certificate, privateKey); authenticate(); } @Override public void reset() { restRootObj = null; apiKey = null; currentSession.set(null); } /** * @deprecated use {@link #createPushCenter() or @link * #createPushCenter(RestPushCenterType)} instead. */ @Deprecated public RestPushCenter getPushCenter() { return createPushCenter(RestPushCenterType.LONG_POLL); } public RestPushCenter createPushCenter() { // PushCenter implementation defaults to JMS from now on return createPushCenter(RestPushCenterType.JMS); } public RestPushCenter createPushCenter(RestPushCenterType pushCenterType) { RestPushCenter pushCenter; if (pushCenterType == RestPushCenterType.JMS) { if (version >= 5.0) { // VSD version 5.0.x uses a different JMS client than previous // releases RestPushCenterJmsActiveMQ pushCenterJmsActiveMQ = new RestPushCenterJmsActiveMQ(); if (username != null && password != null && enterprise != null) { String jmsUser = username + "@" + enterprise; String jmsPassword = password; pushCenterJmsActiveMQ.setUser(jmsUser); pushCenterJmsActiveMQ.setPassword(jmsPassword); } pushCenter = pushCenterJmsActiveMQ; } else { pushCenter = new RestPushCenterJmsJBoss(); } } else if (pushCenterType == RestPushCenterType.JMS_NO_JNDI) { if (version >= 5.0) { // VSD version 5.0.x uses a different JMS client than previous // releases RestPushCenterJmsDirectActiveMQ pushCenterJmsActiveMQ = new RestPushCenterJmsDirectActiveMQ(); if (username != null && password != null && enterprise != null) { String jmsUser = username + "@" + enterprise; String jmsPassword = password; pushCenterJmsActiveMQ.setUser(jmsUser); pushCenterJmsActiveMQ.setPassword(jmsPassword); } pushCenter = pushCenterJmsActiveMQ; } else { pushCenter = new RestPushCenterJmsDirectJBoss(); } } else { pushCenter = new RestPushCenterLongPoll(this); } String url = getRestBaseUrl(); pushCenter.setUrl(url); return pushCenter; } @Override public <T extends RestObject> BulkResponse<T> bulkSave(List<T> objList) throws RestException { String params = BambouUtils.getResponseChoiceParam(1); ResponseEntity<BulkResponse> response = this.sendRequestWithRetry(HttpMethod.PUT, getResourceUrlForParentType(objList.get(0).getClass()), params, null, objList, BulkResponse.class); if (response.getStatusCode().series() == HttpStatus.Series.SUCCESSFUL) { return response.getBody(); // Success } else { // Error throw new RestException("Response received with status code: " + response.getStatusCode()); } } @Override public <T extends RestObject> BulkResponse<T> bulkDelete(List<T> objList) throws RestException { String params = BambouUtils.getResponseChoiceParam(1); for (T item : objList) { params += "&id="+item.getId(); } ResponseEntity<BulkResponse> response = this.sendRequestWithRetry(HttpMethod.DELETE, getResourceUrlForParentType(objList.get(0).getClass()), params, null, null, BulkResponse.class); if (response.getStatusCode().series() == HttpStatus.Series.SUCCESSFUL) { return response.getBody(); // Success } else { // Error throw new RestException("Response received with status code: " + response.getStatusCode()); } } @Override public <T extends RestObject> BulkResponse<T> createChildren(RestObject parent, List<T> children) throws RestException { return parent.createChildren(this,children); } @Override public void fetch(RestObject restObj) throws RestException { restObj.fetch(this); } @Override public void save(RestObject restObj) throws RestException { restObj.save(this); } @Override public void save(RestObject restObj, Integer responseChoice) throws RestException { restObj.save(this, responseChoice); } @Override public void delete(RestObject restObj) throws RestException { restObj.delete(this); } @Override public void delete(RestObject restObj, Integer responseChoice) throws RestException { restObj.delete(this, responseChoice); } @Override public void createChild(RestObject restObj, RestObject childRestObj) throws RestException { restObj.createChild(this, childRestObj); } @Override public void createChild(RestObject restObj, RestObject childRestObj, Integer responseChoice, boolean commit) throws RestException { restObj.createChild(this, childRestObj, responseChoice, commit); } @Override public void instantiateChild(RestObject restObj, RestObject childRestObj, RestObject fromTemplate) throws RestException { restObj.instantiateChild(this, childRestObj, fromTemplate); } @Override public void instantiateChild(RestObject restObj, RestObject childRestObj, RestObject fromTemplate, Integer responseChoice, boolean commit) throws RestException { restObj.instantiateChild(this, childRestObj, fromTemplate, responseChoice, commit); } @Override public void assign(RestObject restObj, List<? extends RestObject> childRestObjs) throws RestException { restObj.assign(this, childRestObjs); } @Override public void assign(RestObject restObj, List<? extends RestObject> childRestObjs, boolean commit) throws RestException { restObj.assign(this, childRestObjs, commit); } @Override public void assign(RestObject restObj, List<? extends RestObject> childRestObjs,Integer responseChoice, boolean commit) throws RestException { restObj.assign(this, childRestObjs, responseChoice, commit); } @Override public <T extends RestObject> List<T> get(RestFetcher<T> fetcher) throws RestException { return get(fetcher, null, null, null, null, null, null, true); } @Override public <T extends RestObject> List<T> fetch(RestFetcher<T> fetcher) throws RestException { return fetch(fetcher, null, null, null, null, null, null, true); } @Override public <T extends RestObject> T getFirst(RestFetcher<T> fetcher) throws RestException { return getFirst(fetcher, null, null, null, null, null, null, true); } @Override public <T extends RestObject> int count(RestFetcher<T> fetcher) throws RestException { return count(fetcher, null, null, null, null, null, null, true); } @Override public <T extends RestObject> List<T> get(RestFetcher<T> fetcher, String filter, String orderBy, String[] groupBy, Integer page, Integer pageSize, String queryParameters, boolean commit) throws RestException { return fetcher.get(this, filter, orderBy, groupBy, page, pageSize, queryParameters, commit); } @Override public <T extends RestObject> List<T> fetch(RestFetcher<T> fetcher, String filter, String orderBy, String[] groupBy, Integer page, Integer pageSize, String queryParameters, boolean commit) throws RestException { return fetcher.fetch(this, filter, orderBy, groupBy, page, pageSize, queryParameters, commit); } @Override public <T extends RestObject> T getFirst(RestFetcher<T> fetcher, String filter, String orderBy, String[] groupBy, Integer page, Integer pageSize, String queryParameters, boolean commit) throws RestException { return fetcher.getFirst(this, filter, orderBy, groupBy, page, pageSize, queryParameters, commit); } @Override public <T extends RestObject> int count(RestFetcher<T> fetcher, String filter, String orderBy, String[] groupBy, Integer page, Integer pageSize, String queryParameters, boolean commit) throws RestException { return fetcher.count(this, filter, orderBy, groupBy, page, pageSize, queryParameters, commit); } protected <T, U> ResponseEntity<T> sendRequestWithRetry(HttpMethod method, String url, String params, HttpHeaders headers, U requestObj, Class<T> responseType) throws RestException { if (params != null) { url += (url.indexOf('?') >= 0) ? ";" + params : "?" + params; } if (headers == null) { headers = new HttpHeaders(); } headers.set(HttpHeaders.CONTENT_TYPE, CONTENT_TYPE_JSON); headers.set(ORGANIZATION_HEADER, getEnterprise()); headers.set(HttpHeaders.AUTHORIZATION, getAuthenticationHeader()); logger.info(url); try { return restClientService.sendRequest(method, url, headers, requestObj, responseType); } catch (RestStatusCodeException ex) { if (ex.getStatusCode() == HttpStatus.UNAUTHORIZED) { // Debug logger.info("HTTP 401/Unauthorized response received"); // Make sure we are not already re-authenticating // in order to avoid infinite recursion if (!(method == HttpMethod.GET && url.equals(restRootObj.getResourceUrl(this)))) { // Re-authenticate the session and try to send the same // request again. A new API key might get issued as a result reset(); authenticate(); // Update authorization header with new API key headers.set(HttpHeaders.AUTHORIZATION, getAuthenticationHeader()); return restClientService.sendRequest(method, url, headers, requestObj, responseType); } else { throw ex; } } else { throw ex; } } } protected String getRestBaseUrl() { int roundedVersion = (int)version; return String.format("%s/%s/v%s", apiUrl, apiPrefix, String.valueOf(roundedVersion)); } protected String getResourceUrlForParentType(Class<?> parentRestObjClass) { RestEntity annotation = parentRestObjClass.getAnnotation(RestEntity.class); String parentResourceName = annotation.resourceName(); return String.format("%s/%s", getRestBaseUrl(), parentResourceName); } private synchronized void authenticate() throws RestException { // Create the root object if needed if (restRootObj == null) { restRootObj = createRootObject(); fetch(restRootObj); } // Copy the API key from the root object apiKey = restRootObj.getApiKey(); // Debug logger.debug("Started session with username: " + username + " in enterprise: " + enterprise); } private R createRootObject() throws RestException { try { return restRootObjClass.newInstance(); } catch (InstantiationException | IllegalAccessException ex) { throw new RestException(ex); } } private String getAuthenticationHeader() { if (apiKey != null) { return String.format("XREST %s", Base64.encodeBase64String(String.format("%s:%s", username, apiKey).getBytes())); } else { return String.format("XREST %s", Base64.encodeBase64String(String.format("%s:%s", username, password).getBytes())); } } @Override public String toString() { return "RestSession [restClientService=" + restClientService + ", username=" + username + ", password=" + password + ", enterprise=" + enterprise + ", apiUrl=" + apiUrl + ", apiPrefix=" + apiPrefix + ", certificate=" + certificate + ", privateKey=" + privateKey + ", version=" + version + ", apiKey=" + apiKey + ", restRootObjClass=" + restRootObjClass + ", restRootObj=" + restRootObj + "]"; } }
401 retries were failing. Now it's fixed
src/main/java/net/nuagenetworks/bambou/RestSession.java
401 retries were failing. Now it's fixed
<ide><path>rc/main/java/net/nuagenetworks/bambou/RestSession.java <ide> // request again. A new API key might get issued as a result <ide> reset(); <ide> authenticate(); <add> currentSession.set(this); <ide> <ide> // Update authorization header with new API key <ide> headers.set(HttpHeaders.AUTHORIZATION, getAuthenticationHeader());
JavaScript
mit
1eeea858c99bb7f94b795abb039b52e8868051b2
0
cah-grantjames/testspercard
var startTime = new Date().getTime(); var cliArgs = process.argv.slice(2); var EXPECTED_ARGS = "tpc <project_key>" +"<start UNIX epoch OR 0 for all> " +"<end UNIX epoch OR 0 for all> "; if(cliArgs && cliArgs[0] === "help") { console.log("\n\tEXPECTED ARGS:", EXPECTED_ARGS); console.log("\t\tRun from root of repo you're inquiring about\n"); return; } if(!cliArgs || cliArgs.length != 3){ console.log("Invalid ARGS!\n", EXPECTED_ARGS); return; } // var runner = new Runner(); var fs = require('fs'); var projectKey = cliArgs[0]; var time = { start : cliArgs[1], end : cliArgs[2] }; var glimrBuild = require(__dirname+'/node_modules/glimr/glimr/glimr_build.js')(); var diffParser = require(__dirname+"/lib/diff_parser.js")(); var fullPathToRepo = cliArgs[0]; runner.run("git", ["log"], function(logs){ var content = logs.toString(); var startDate = new Date(time.start *1); var endDate = new Date(time.end*1); if(time.start == 0 && time.end == 0){ startDate = undefined; endDate = undefined; } var logObjects = glimrBuild.toLogObjectsArray(content, startDate, endDate); var cardObjects = glimrBuild.cards.findUniqueCards(projectKey, logObjects); cardObjects = cardObjects.slice(0,30); diffParser.findTestsForEachCard(cardObjects, function(cardObjectsWithTestsForEachCard){ var R = {}; R.cardObjectsWithTestsForEachCard = cardObjectsWithTestsForEachCard; var timeExpired = ((new Date().getTime())-startTime); R.timeExpired = timeExpired+"ms"; R.numberOfCards = cardObjectsWithTestsForEachCard.length; R.timePerCard = (timeExpired/cardObjectsWithTestsForEachCard.length)+"ms"; var jsonResults = JSON.stringify(R, 0, 4); var dateStr = (new Date(startTime).toString()).replace(/\s/g,"_"); fs.writeFileSync("tpc_report_"+projectKey+"_"+dateStr+".json", jsonResults); //CSV var csv = "issue, file, test"; for(var i=0; i<R.cardObjectsWithTestsForEachCard.length; i++) { var card = R.cardObjectsWithTestsForEachCard[i]; var issue = card.key; for(var j=0; j<card.testsFound.length; j++) { var tf = card.testsFound[i]; var file = tf.file; for(var k=0; k<tf.tests.length; k++) { var test = tf.tests[k]; csv += "\n" + issue + "," + file + "," + test; } } } fs.writeFileSync("tpc_report_"+projectKey+"_"+dateStr+".csv", csv); }); }); function Runner() { this.isWin = /^win/.test(process.platform); this.child_process = require('child_process'); this.runInherit = function(cmd, cmdArgs, cb) { if(this.isWin){ if(cmd === "open"){ cmd = "start"; } } var msg = cmd; if(cmdArgs){ for(var i=0; i<cmdArgs.length; i++) { msg += " "+cmdArgs[i]; } } var spawn = this.child_process.spawn; spawn(cmd, cmdArgs, {stdio : 'inherit'}); cb && cb(); }; this.run = function(cmd, cmdArgs, cb) { if(this.isWin){ if(cmd === "open"){ cmd = "start"; } } var spawn = require('child_process').spawn, ls = spawn(cmd, cmdArgs); // console.log("RUNNING ", "[", cmd, cmdArgs.join(" "), "]"); var out = ""; var error = false; ls.stdout.on('data', function (data) { out += "\n" + (data ? data.toString() : ""); }); ls.stderr.on('data', function (data) { error = true; out += "\n" + (data ? data.toString() : ""); }); ls.on('close', function (code) { cb && cb(out, error); }); }; }
tpc.js
var startTime = new Date().getTime(); var cliArgs = process.argv.slice(2); var EXPECTED_ARGS = "tpc <project_key>" +"<start UNIX epoch OR 0 for all> " +"<end UNIX epoch OR 0 for all> "; if(cliArgs && cliArgs[0] === "help") { console.log("\n\tEXPECTED ARGS:", EXPECTED_ARGS); console.log("\t\tRun from root of repo you're inquiring about\n"); return; } if(!cliArgs || cliArgs.length != 3){ console.log("Invalid ARGS!\n", EXPECTED_ARGS); return; } // var runner = new Runner(); var fs = require('fs'); var projectKey = cliArgs[0]; var time = { start : cliArgs[1], end : cliArgs[2] }; var glimrBuild = require(__dirname+'/node_modules/glimr/glimr/glimr_build.js')(); var diffParser = require(__dirname+"/lib/diff_parser.js")(); var fullPathToRepo = cliArgs[0]; runner.run("git", ["log"], function(logs){ var content = logs.toString(); var startDate = new Date(time.start *1); var endDate = new Date(time.end*1); if(time.start == 0 && time.end == 0){ startDate = undefined; endDate = undefined; } var logObjects = glimrBuild.toLogObjectsArray(content, startDate, endDate); var cardObjects = glimrBuild.cards.findUniqueCards(projectKey, logObjects); diffParser.findTestsForEachCard(cardObjects, function(cardObjectsWithTestsForEachCard){ var R = {}; R.cardObjectsWithTestsForEachCard = cardObjectsWithTestsForEachCard; var timeExpired = ((new Date().getTime())-startTime); R.timeExpired = timeExpired+"ms"; R.numberOfCards = cardObjects.length; R.numberOfCardsWithTests = cardObjectsWithTestsForEachCard.length; R.timePerCard = (timeExpired/cardObjectsWithTestsForEachCard.length)+"ms"; console.log(JSON.stringify(R, 0, 4)); }); }); function Runner() { this.isWin = /^win/.test(process.platform); this.child_process = require('child_process'); this.runInherit = function(cmd, cmdArgs, cb) { if(this.isWin){ if(cmd === "open"){ cmd = "start"; } } var msg = cmd; if(cmdArgs){ for(var i=0; i<cmdArgs.length; i++) { msg += " "+cmdArgs[i]; } } var spawn = this.child_process.spawn; spawn(cmd, cmdArgs, {stdio : 'inherit'}); cb && cb(); }; this.run = function(cmd, cmdArgs, cb) { if(this.isWin){ if(cmd === "open"){ cmd = "start"; } } var spawn = require('child_process').spawn, ls = spawn(cmd, cmdArgs); // console.log("RUNNING ", "[", cmd, cmdArgs.join(" "), "]"); var out = ""; var error = false; ls.stdout.on('data', function (data) { out += "\n" + (data ? data.toString() : ""); }); ls.stderr.on('data', function (data) { error = true; out += "\n" + (data ? data.toString() : ""); }); ls.on('close', function (code) { cb && cb(out, error); }); }; }
wip CSV
tpc.js
wip CSV
<ide><path>pc.js <ide> } <ide> var logObjects = glimrBuild.toLogObjectsArray(content, startDate, endDate); <ide> var cardObjects = glimrBuild.cards.findUniqueCards(projectKey, logObjects); <add> cardObjects = cardObjects.slice(0,30); <ide> diffParser.findTestsForEachCard(cardObjects, function(cardObjectsWithTestsForEachCard){ <ide> var R = {}; <ide> R.cardObjectsWithTestsForEachCard = cardObjectsWithTestsForEachCard; <ide> var timeExpired = ((new Date().getTime())-startTime); <ide> R.timeExpired = timeExpired+"ms"; <del> R.numberOfCards = cardObjects.length; <del> R.numberOfCardsWithTests = cardObjectsWithTestsForEachCard.length; <add> R.numberOfCards = cardObjectsWithTestsForEachCard.length; <ide> R.timePerCard = (timeExpired/cardObjectsWithTestsForEachCard.length)+"ms"; <del> console.log(JSON.stringify(R, 0, 4)); <add> var jsonResults = JSON.stringify(R, 0, 4); <add> var dateStr = (new Date(startTime).toString()).replace(/\s/g,"_"); <add> fs.writeFileSync("tpc_report_"+projectKey+"_"+dateStr+".json", jsonResults); <add> //CSV <add> var csv = "issue, file, test"; <add> for(var i=0; i<R.cardObjectsWithTestsForEachCard.length; i++) { <add> var card = R.cardObjectsWithTestsForEachCard[i]; <add> var issue = card.key; <add> for(var j=0; j<card.testsFound.length; j++) { <add> var tf = card.testsFound[i]; <add> var file = tf.file; <add> for(var k=0; k<tf.tests.length; k++) { <add> var test = tf.tests[k]; <add> csv += "\n" + issue + "," + file + "," + test; <add> } <add> } <add> } <add> fs.writeFileSync("tpc_report_"+projectKey+"_"+dateStr+".csv", csv); <add> <ide> }); <ide> }); <ide>
Java
apache-2.0
656ec957890a96d19ebe93fb293bb395955f6b6b
0
Donnerbart/hazelcast,lmjacksoniii/hazelcast,tufangorel/hazelcast,juanavelez/hazelcast,emre-aydin/hazelcast,tkountis/hazelcast,tufangorel/hazelcast,mesutcelik/hazelcast,mdogan/hazelcast,emre-aydin/hazelcast,dsukhoroslov/hazelcast,mesutcelik/hazelcast,tombujok/hazelcast,dbrimley/hazelcast,dsukhoroslov/hazelcast,emrahkocaman/hazelcast,dbrimley/hazelcast,mdogan/hazelcast,tkountis/hazelcast,juanavelez/hazelcast,dbrimley/hazelcast,Donnerbart/hazelcast,mesutcelik/hazelcast,mdogan/hazelcast,tkountis/hazelcast,tufangorel/hazelcast,tombujok/hazelcast,lmjacksoniii/hazelcast,emre-aydin/hazelcast,emrahkocaman/hazelcast,Donnerbart/hazelcast
/* * Copyright (c) 2008-2012, Hazel Bilisim Ltd. All Rights Reserved. * * 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.hazelcast.impl; import com.hazelcast.cluster.AbstractRemotelyProcessable; import com.hazelcast.config.ListenerConfig; import com.hazelcast.core.*; import com.hazelcast.impl.base.PacketProcessor; import com.hazelcast.nio.*; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.logging.Level; import static com.hazelcast.impl.ClusterOperation.*; import static com.hazelcast.nio.IOUtil.toData; public class ListenerManager extends BaseManager { final ConcurrentMap<String, List<ListenerItem>> namedListeners = new ConcurrentHashMap<String, List<ListenerItem>>(100); ListenerManager(Node node) { super(node); registerPacketProcessor(ClusterOperation.EVENT, new PacketProcessor() { public void process(Packet packet) { handleEvent(packet); } }); registerPacketProcessor(ADD_LISTENER, new AddRemoveListenerOperationHandler()); registerPacketProcessor(REMOVE_LISTENER, new AddRemoveListenerOperationHandler()); registerPacketProcessor(ADD_LISTENER_NO_RESPONSE, new PacketProcessor() { public void process(Packet packet) { handleAddRemoveListener(true, packet); } }); } private void handleEvent(Packet packet) { int eventType = (int) packet.longValue; Data key = packet.getKeyData(); Data value = packet.getValueData(); String name = packet.name; Address from = packet.lockAddress; releasePacket(packet); enqueueEvent(eventType, name, key, value, from, false); } private void handleAddRemoveListener(boolean add, Packet packet) { Data key = packet.getKeyData(); boolean returnValue = (packet.longValue == 1); String name = packet.name; Address address = packet.conn.getEndPoint(); releasePacket(packet); registerListener(add, name, key, address, returnValue); } public void syncForDead(Address deadAddress) { //syncForAdd(); for (List<ListenerItem> listeners : namedListeners.values()) { for (ListenerItem listenerItem : listeners) { if (!listenerItem.localListener) { registerListener(false, listenerItem.name, toData(listenerItem.key), deadAddress, listenerItem.includeValue); } } } } public void syncForAdd() { for (List<ListenerItem> listeners : namedListeners.values()) { for (ListenerItem listenerItem : listeners) { if (!listenerItem.localListener) { registerListenerWithNoResponse(listenerItem.name, listenerItem.key, listenerItem.includeValue); } } } } public void syncForAdd(Address newAddress) { for (List<ListenerItem> listeners : namedListeners.values()) { for (ListenerItem listenerItem : listeners) { if (!listenerItem.localListener) { Data dataKey = null; if (listenerItem.key != null) { dataKey = ThreadContext.get().toData(listenerItem.key); } sendAddListener(newAddress, listenerItem.name, dataKey, listenerItem.includeValue); } } } } class AddRemoveListenerOperationHandler extends TargetAwareOperationHandler { boolean isRightRemoteTarget(Request request) { return (null == request.key) || thisAddress.equals(node.concurrentMapManager.getKeyOwner(request)); } void doOperation(Request request) { Address from = request.caller; logger.log(Level.FINEST, "AddListenerOperation from " + from + ", local=" + request.local + " key:" + request.key + " op:" + request.operation); if (from == null) throw new RuntimeException("Listener origin is not known!"); boolean add = (request.operation == ADD_LISTENER); boolean includeValue = (request.longValue == 1); registerListener(add, request.name, request.key, request.caller, includeValue); request.response = Boolean.TRUE; } } public class AddRemoveListener extends MultiCall<Boolean> { final String name; final boolean add; final boolean includeValue; public AddRemoveListener(String name, boolean add, boolean includeValue) { this.name = name; this.add = add; this.includeValue = includeValue; } SubCall createNewTargetAwareOp(Address target) { return new AddListenerAtTarget(target); } boolean onResponse(Object response) { return true; } Object returnResult() { return Boolean.TRUE; } protected boolean excludeLiteMember() { return false; } private final class AddListenerAtTarget extends SubCall { public AddListenerAtTarget(Address target) { super(target); ClusterOperation operation = (add) ? ADD_LISTENER : REMOVE_LISTENER; setLocal(operation, name, null, null, -1, -1); request.setBooleanRequest(); request.longValue = (includeValue) ? 1 : 0; } } } private void registerListener(String name, Object key, boolean add, boolean includeValue) { if (key == null) { AddRemoveListener addRemoveListener = new AddRemoveListener(name, add, includeValue); addRemoveListener.call(); } else { node.concurrentMapManager.new MAddKeyListener().addListener(name, add, key, includeValue); } } private void registerListenerWithNoResponse(String name, Object key, boolean includeValue) { Data dataKey = null; if (key != null) { dataKey = ThreadContext.get().toData(key); } enqueueAndReturn(new ListenerRegistrationProcess(name, dataKey, includeValue)); } final class ListenerRegistrationProcess implements Processable { final String name; final Data key; final boolean includeValue; public ListenerRegistrationProcess(String name, Data key, boolean includeValue) { super(); this.key = key; this.name = name; this.includeValue = includeValue; } public void process() { if (key != null) { processWithKey(); } else { processWithoutKey(); } } private void processWithKey() { Address owner = node.concurrentMapManager.getKeyOwner(key); if (owner.equals(thisAddress)) { registerListener(true, name, key, thisAddress, includeValue); } else { Packet packet = obtainPacket(); packet.set(name, ADD_LISTENER_NO_RESPONSE, key, null); packet.longValue = (includeValue) ? 1 : 0; sendOrReleasePacket(packet, owner); } } private void processWithoutKey() { for (MemberImpl member : lsMembers) { if (member.localMember()) { registerListener(true, name, null, thisAddress, includeValue); } else { sendAddListener(member.getAddress(), name, null, includeValue); } } } } void sendAddListener(Address toAddress, String name, Data key, boolean includeValue) { Packet packet = obtainPacket(); packet.set(name, ClusterOperation.ADD_LISTENER_NO_RESPONSE, key, null); packet.longValue = (includeValue) ? 1 : 0; sendOrReleasePacket(packet, toAddress); } public synchronized void addLocalListener(final String name, Object listener, Instance.InstanceType instanceType) { List<ListenerItem> listeners = getOrCreateListenerList(name); ListenerItem listenerItem = new ListenerItem(name, null, listener, true, instanceType, true); listeners.add(listenerItem); node.concurrentMapManager.enqueueAndWait(new Processable() { public void process() { node.concurrentMapManager.getOrCreateMap(name).addListener(null, node.getThisAddress(), true); } }, 10); } public synchronized List<ListenerItem> getOrCreateListenerList(String name) { List<ListenerItem> listeners = namedListeners.get(name); if (listeners == null) { listeners = new CopyOnWriteArrayList<ListenerItem>(); namedListeners.put(name, listeners); } return listeners; } public synchronized void addListener(String name, Object listener, Object key, boolean includeValue, Instance.InstanceType instanceType) { List<ListenerItem> listeners = getOrCreateListenerList(name); boolean remotelyRegister = true; for (ListenerItem listenerItem : listeners) { if (!remotelyRegister) { break; } // If existing listener is local then continue // and don't take into account for remote registration check. (issue:584) if (!listenerItem.localListener && listenerItem.name.equals(name)) { if (key == null) { if (listenerItem.key == null && (!includeValue || listenerItem.includeValue == includeValue)) { remotelyRegister = false; } } else if (listenerItem.key != null) { if (listenerItem.key.equals(key) && (!includeValue || listenerItem.includeValue == includeValue)) { remotelyRegister = false; } } } } if (remotelyRegister) { registerListener(name, key, true, includeValue); } ListenerItem listenerItem = new ListenerItem(name, key, listener, includeValue, instanceType); listeners.add(listenerItem); } public void removeListener(String name, Object listener, Object key) { List<ListenerItem> listeners = namedListeners.get(name); if (listeners == null) return; for (ListenerItem listenerItem : listeners) { if (listener == listenerItem.listener && listenerItem.name.equals(name)) { if (key == null && listenerItem.key == null) { listeners.remove(listenerItem); } else if (key != null && key.equals(listenerItem.key)) { listeners.remove(listenerItem); } } } boolean left = false; for (ListenerItem listenerItem : listeners) { if (key == null && listenerItem.key == null) { left = true; } else if (key != null && key.equals(listenerItem.key)) { left = true; } } if (!left) { registerListener(name, key, false, false); } } void removeAllRegisteredListeners(String name) { namedListeners.remove(name); } /** * Create and add ListenerItem during initialization of CMap, BQ and TopicInstance. */ void createAndAddListenerItem(String name, ListenerConfig lc, Instance.InstanceType instanceType) throws Exception { Object listener = lc.getImplementation(); if (listener == null) { listener = Serializer.newInstance(Serializer.loadClass(lc.getClassName())); } if (listener != null) { final ListenerItem listenerItem = new ListenerItem(name, null, listener, lc.isIncludeValue(), instanceType, lc.isLocal()); getOrCreateListenerList(name).add(listenerItem); } } void callListeners(DataAwareEntryEvent dataAwareEntryEvent) { List<ListenerItem> listeners = getOrCreateListenerList(dataAwareEntryEvent.getLongName()); for (ListenerItem listenerItem : listeners) { if (listenerItem.listens(dataAwareEntryEvent)) { try { callListener(listenerItem, dataAwareEntryEvent); } catch (Throwable e) { logger.log(Level.SEVERE, "Caught error while calling event listener; cause: " + e.getMessage(), e); } } } } private void callListener(final ListenerItem listenerItem, final DataAwareEntryEvent event) { if (listenerItem.localListener && !event.firedLocally) { return; } final Object listener = listenerItem.listener; final EntryEventType entryEventType = event.getEventType(); if (listenerItem.instanceType == Instance.InstanceType.MAP) { if (!listenerItem.name.startsWith(Prefix.MAP_HAZELCAST)) { Object proxy = node.factory.getOrCreateProxyByName(listenerItem.name); if (proxy instanceof MProxy) { MProxy mProxy = (MProxy) proxy; mProxy.getMapOperationCounter().incrementReceivedEvents(); } } } else if (listenerItem.instanceType == Instance.InstanceType.QUEUE) { if (!listenerItem.name.startsWith(Prefix.QUEUE_HAZELCAST)) { Object proxy = node.factory.getOrCreateProxyByName(listenerItem.name); if (proxy instanceof QProxy) { QProxy qProxy = (QProxy) proxy; qProxy.getQueueOperationCounter().incrementReceivedEvents(); } } } else if (listenerItem.instanceType == Instance.InstanceType.TOPIC) { if (!listenerItem.name.startsWith(Prefix.TOPIC_HAZELCAST)) { Object proxy = node.factory.getOrCreateProxyByName(listenerItem.name); if (proxy instanceof TopicProxy) { TopicProxy tProxy = (TopicProxy) proxy; tProxy.getTopicOperationCounter().incrementReceivedMessages(); } } } final EntryEvent event2 = listenerItem.includeValue ? event : // if new value is already null no need to create a new value-less event (event.getNewValueData() != null ? new DataAwareEntryEvent(event.getMember(), event.getEventType().getType(), event.getLongName(), event.getKeyData(), null, null, event.firedLocally) : event); switch (listenerItem.instanceType) { case MAP: case MULTIMAP: EntryListener entryListener = (EntryListener) listener; switch (entryEventType) { case ADDED: entryListener.entryAdded(event2); break; case REMOVED: entryListener.entryRemoved(event2); break; case UPDATED: entryListener.entryUpdated(event2); break; case EVICTED: entryListener.entryEvicted(event2); break; } break; case SET: case LIST: ItemListener itemListener = (ItemListener) listener; switch (entryEventType) { case ADDED: itemListener.itemAdded(new DataAwareItemEvent(listenerItem.name, ItemEventType.ADDED, event.getKeyData())); break; case REMOVED: itemListener.itemRemoved(new DataAwareItemEvent(listenerItem.name, ItemEventType.REMOVED, event.getKeyData())); break; } break; case TOPIC: MessageListener messageListener = (MessageListener) listener; messageListener.onMessage(new DataMessage(listenerItem.name, event.getNewValueData())); break; case QUEUE: ItemListener queueItemListener = (ItemListener) listener; switch (entryEventType) { case ADDED: queueItemListener.itemAdded(new DataAwareItemEvent(listenerItem.name, ItemEventType.ADDED, event.getNewValueData())); break; case REMOVED: queueItemListener.itemRemoved(new DataAwareItemEvent(listenerItem.name, ItemEventType.REMOVED, event.getNewValueData())); break; } break; } } public static class ListenerItem extends AbstractRemotelyProcessable implements DataSerializable { public String name; public Object key; public Object listener; public boolean includeValue; public Instance.InstanceType instanceType; public boolean localListener = false; public ListenerItem() { } public ListenerItem(String name, Object key, Object listener, boolean includeValue, Instance.InstanceType instanceType) { this(name, key, listener, includeValue, instanceType, false); } public ListenerItem(String name, Object key, Object listener, boolean includeValue, Instance.InstanceType instanceType, boolean localListener) { super(); this.key = key; this.listener = listener; this.name = name; this.includeValue = includeValue; this.instanceType = instanceType; this.localListener = localListener; } public boolean listens(DataAwareEntryEvent dataAwareEntryEvent) { String name = dataAwareEntryEvent.getLongName(); return this.name.equals(name) && (this.key == null || dataAwareEntryEvent.getKey().equals(this.key)); } public void writeData(DataOutput out) throws IOException { out.writeUTF(name); writeObject(out, key); out.writeBoolean(includeValue); } public void readData(DataInput in) throws IOException { name = in.readUTF(); key = readObject(in); includeValue = in.readBoolean(); } public void process() { getNode().listenerManager.registerListener(true, name, toData(key), getConnection().getEndPoint(), includeValue); } } }
hazelcast/src/main/java/com/hazelcast/impl/ListenerManager.java
/* * Copyright (c) 2008-2012, Hazel Bilisim Ltd. All Rights Reserved. * * 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.hazelcast.impl; import com.hazelcast.cluster.AbstractRemotelyProcessable; import com.hazelcast.config.ListenerConfig; import com.hazelcast.core.*; import com.hazelcast.impl.base.PacketProcessor; import com.hazelcast.nio.*; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.logging.Level; import static com.hazelcast.impl.ClusterOperation.*; import static com.hazelcast.nio.IOUtil.toData; public class ListenerManager extends BaseManager { final ConcurrentMap<String, List<ListenerItem>> namedListeners = new ConcurrentHashMap<String, List<ListenerItem>>(100); ListenerManager(Node node) { super(node); registerPacketProcessor(ClusterOperation.EVENT, new PacketProcessor() { public void process(Packet packet) { handleEvent(packet); } }); registerPacketProcessor(ADD_LISTENER, new AddRemoveListenerOperationHandler()); registerPacketProcessor(REMOVE_LISTENER, new AddRemoveListenerOperationHandler()); registerPacketProcessor(ADD_LISTENER_NO_RESPONSE, new PacketProcessor() { public void process(Packet packet) { handleAddRemoveListener(true, packet); } }); } private void handleEvent(Packet packet) { int eventType = (int) packet.longValue; Data key = packet.getKeyData(); Data value = packet.getValueData(); String name = packet.name; Address from = packet.lockAddress; releasePacket(packet); enqueueEvent(eventType, name, key, value, from, false); } private void handleAddRemoveListener(boolean add, Packet packet) { Data key = packet.getKeyData(); boolean returnValue = (packet.longValue == 1); String name = packet.name; Address address = packet.conn.getEndPoint(); releasePacket(packet); registerListener(add, name, key, address, returnValue); } public void syncForDead(Address deadAddress) { syncForAdd(); } public void syncForAdd() { for (List<ListenerItem> listeners : namedListeners.values()) { for (ListenerItem listenerItem : listeners) { if (!listenerItem.localListener) { registerListenerWithNoResponse(listenerItem.name, listenerItem.key, listenerItem.includeValue); } } } } public void syncForAdd(Address newAddress) { for (List<ListenerItem> listeners : namedListeners.values()) { for (ListenerItem listenerItem : listeners) { if (!listenerItem.localListener) { Data dataKey = null; if (listenerItem.key != null) { dataKey = ThreadContext.get().toData(listenerItem.key); } sendAddListener(newAddress, listenerItem.name, dataKey, listenerItem.includeValue); } } } } class AddRemoveListenerOperationHandler extends TargetAwareOperationHandler { boolean isRightRemoteTarget(Request request) { return (null == request.key) || thisAddress.equals(node.concurrentMapManager.getKeyOwner(request)); } void doOperation(Request request) { Address from = request.caller; logger.log(Level.FINEST, "AddListenerOperation from " + from + ", local=" + request.local + " key:" + request.key + " op:" + request.operation); if (from == null) throw new RuntimeException("Listener origin is not known!"); boolean add = (request.operation == ADD_LISTENER); boolean includeValue = (request.longValue == 1); registerListener(add, request.name, request.key, request.caller, includeValue); request.response = Boolean.TRUE; } } public class AddRemoveListener extends MultiCall<Boolean> { final String name; final boolean add; final boolean includeValue; public AddRemoveListener(String name, boolean add, boolean includeValue) { this.name = name; this.add = add; this.includeValue = includeValue; } SubCall createNewTargetAwareOp(Address target) { return new AddListenerAtTarget(target); } boolean onResponse(Object response) { return true; } Object returnResult() { return Boolean.TRUE; } protected boolean excludeLiteMember() { return false; } private final class AddListenerAtTarget extends SubCall { public AddListenerAtTarget(Address target) { super(target); ClusterOperation operation = (add) ? ADD_LISTENER : REMOVE_LISTENER; setLocal(operation, name, null, null, -1, -1); request.setBooleanRequest(); request.longValue = (includeValue) ? 1 : 0; } } } private void registerListener(String name, Object key, boolean add, boolean includeValue) { if (key == null) { AddRemoveListener addRemoveListener = new AddRemoveListener(name, add, includeValue); addRemoveListener.call(); } else { node.concurrentMapManager.new MAddKeyListener().addListener(name, add, key, includeValue); } } private void registerListenerWithNoResponse(String name, Object key, boolean includeValue) { Data dataKey = null; if (key != null) { dataKey = ThreadContext.get().toData(key); } enqueueAndReturn(new ListenerRegistrationProcess(name, dataKey, includeValue)); } final class ListenerRegistrationProcess implements Processable { final String name; final Data key; final boolean includeValue; public ListenerRegistrationProcess(String name, Data key, boolean includeValue) { super(); this.key = key; this.name = name; this.includeValue = includeValue; } public void process() { if (key != null) { processWithKey(); } else { processWithoutKey(); } } private void processWithKey() { Address owner = node.concurrentMapManager.getKeyOwner(key); if (owner.equals(thisAddress)) { registerListener(true, name, key, thisAddress, includeValue); } else { Packet packet = obtainPacket(); packet.set(name, ADD_LISTENER_NO_RESPONSE, key, null); packet.longValue = (includeValue) ? 1 : 0; sendOrReleasePacket(packet, owner); } } private void processWithoutKey() { for (MemberImpl member : lsMembers) { if (member.localMember()) { registerListener(true, name, null, thisAddress, includeValue); } else { sendAddListener(member.getAddress(), name, null, includeValue); } } } } void sendAddListener(Address toAddress, String name, Data key, boolean includeValue) { Packet packet = obtainPacket(); packet.set(name, ClusterOperation.ADD_LISTENER_NO_RESPONSE, key, null); packet.longValue = (includeValue) ? 1 : 0; sendOrReleasePacket(packet, toAddress); } public synchronized void addLocalListener(final String name, Object listener, Instance.InstanceType instanceType) { List<ListenerItem> listeners = getOrCreateListenerList(name); ListenerItem listenerItem = new ListenerItem(name, null, listener, true, instanceType, true); listeners.add(listenerItem); node.concurrentMapManager.enqueueAndWait(new Processable() { public void process() { node.concurrentMapManager.getOrCreateMap(name).addListener(null, node.getThisAddress(), true); } }, 10); } public synchronized List<ListenerItem> getOrCreateListenerList(String name) { List<ListenerItem> listeners = namedListeners.get(name); if (listeners == null) { listeners = new CopyOnWriteArrayList<ListenerItem>(); namedListeners.put(name, listeners); } return listeners; } public synchronized void addListener(String name, Object listener, Object key, boolean includeValue, Instance.InstanceType instanceType) { List<ListenerItem> listeners = getOrCreateListenerList(name); boolean remotelyRegister = true; for (ListenerItem listenerItem : listeners) { if (!remotelyRegister) { break; } // If existing listener is local then continue // and don't take into account for remote registration check. (issue:584) if (!listenerItem.localListener && listenerItem.name.equals(name)) { if (key == null) { if (listenerItem.key == null && (!includeValue || listenerItem.includeValue == includeValue)) { remotelyRegister = false; } } else if (listenerItem.key != null) { if (listenerItem.key.equals(key) && (!includeValue || listenerItem.includeValue == includeValue)) { remotelyRegister = false; } } } } if (remotelyRegister) { registerListener(name, key, true, includeValue); } ListenerItem listenerItem = new ListenerItem(name, key, listener, includeValue, instanceType); listeners.add(listenerItem); } public void removeListener(String name, Object listener, Object key) { List<ListenerItem> listeners = namedListeners.get(name); if (listeners == null) return; for (ListenerItem listenerItem : listeners) { if (listener == listenerItem.listener && listenerItem.name.equals(name)) { if (key == null && listenerItem.key == null) { listeners.remove(listenerItem); } else if (key != null && key.equals(listenerItem.key)) { listeners.remove(listenerItem); } } } boolean left = false; for (ListenerItem listenerItem : listeners) { if (key == null && listenerItem.key == null) { left = true; } else if (key != null && key.equals(listenerItem.key)) { left = true; } } if (!left) { registerListener(name, key, false, false); } } void removeAllRegisteredListeners(String name) { namedListeners.remove(name); } /** * Create and add ListenerItem during initialization of CMap, BQ and TopicInstance. */ void createAndAddListenerItem(String name, ListenerConfig lc, Instance.InstanceType instanceType) throws Exception { Object listener = lc.getImplementation(); if (listener == null) { listener = Serializer.newInstance(Serializer.loadClass(lc.getClassName())); } if (listener != null) { final ListenerItem listenerItem = new ListenerItem(name, null, listener, lc.isIncludeValue(), instanceType, lc.isLocal()); getOrCreateListenerList(name).add(listenerItem); } } void callListeners(DataAwareEntryEvent dataAwareEntryEvent) { List<ListenerItem> listeners = getOrCreateListenerList(dataAwareEntryEvent.getLongName()); for (ListenerItem listenerItem : listeners) { if (listenerItem.listens(dataAwareEntryEvent)) { try { callListener(listenerItem, dataAwareEntryEvent); } catch (Throwable e) { logger.log(Level.SEVERE, "Caught error while calling event listener; cause: " + e.getMessage(), e); } } } } private void callListener(final ListenerItem listenerItem, final DataAwareEntryEvent event) { if (listenerItem.localListener && !event.firedLocally) { return; } final Object listener = listenerItem.listener; final EntryEventType entryEventType = event.getEventType(); if (listenerItem.instanceType == Instance.InstanceType.MAP) { if (!listenerItem.name.startsWith(Prefix.MAP_HAZELCAST)) { Object proxy = node.factory.getOrCreateProxyByName(listenerItem.name); if (proxy instanceof MProxy) { MProxy mProxy = (MProxy) proxy; mProxy.getMapOperationCounter().incrementReceivedEvents(); } } } else if (listenerItem.instanceType == Instance.InstanceType.QUEUE) { if (!listenerItem.name.startsWith(Prefix.QUEUE_HAZELCAST)) { Object proxy = node.factory.getOrCreateProxyByName(listenerItem.name); if (proxy instanceof QProxy) { QProxy qProxy = (QProxy) proxy; qProxy.getQueueOperationCounter().incrementReceivedEvents(); } } } else if (listenerItem.instanceType == Instance.InstanceType.TOPIC) { if (!listenerItem.name.startsWith(Prefix.TOPIC_HAZELCAST)) { Object proxy = node.factory.getOrCreateProxyByName(listenerItem.name); if (proxy instanceof TopicProxy) { TopicProxy tProxy = (TopicProxy) proxy; tProxy.getTopicOperationCounter().incrementReceivedMessages(); } } } final EntryEvent event2 = listenerItem.includeValue ? event : // if new value is already null no need to create a new value-less event (event.getNewValueData() != null ? new DataAwareEntryEvent(event.getMember(), event.getEventType().getType(), event.getLongName(), event.getKeyData(), null, null, event.firedLocally) : event); switch (listenerItem.instanceType) { case MAP: case MULTIMAP: EntryListener entryListener = (EntryListener) listener; switch (entryEventType) { case ADDED: entryListener.entryAdded(event2); break; case REMOVED: entryListener.entryRemoved(event2); break; case UPDATED: entryListener.entryUpdated(event2); break; case EVICTED: entryListener.entryEvicted(event2); break; } break; case SET: case LIST: ItemListener itemListener = (ItemListener) listener; switch (entryEventType) { case ADDED: itemListener.itemAdded(new DataAwareItemEvent(listenerItem.name, ItemEventType.ADDED, event.getKeyData())); break; case REMOVED: itemListener.itemRemoved(new DataAwareItemEvent(listenerItem.name, ItemEventType.REMOVED, event.getKeyData())); break; } break; case TOPIC: MessageListener messageListener = (MessageListener) listener; messageListener.onMessage(new DataMessage(listenerItem.name, event.getNewValueData())); break; case QUEUE: ItemListener queueItemListener = (ItemListener) listener; switch (entryEventType) { case ADDED: queueItemListener.itemAdded(new DataAwareItemEvent(listenerItem.name, ItemEventType.ADDED, event.getNewValueData())); break; case REMOVED: queueItemListener.itemRemoved(new DataAwareItemEvent(listenerItem.name, ItemEventType.REMOVED, event.getNewValueData())); break; } break; } } public static class ListenerItem extends AbstractRemotelyProcessable implements DataSerializable { public String name; public Object key; public Object listener; public boolean includeValue; public Instance.InstanceType instanceType; public boolean localListener = false; public ListenerItem() { } public ListenerItem(String name, Object key, Object listener, boolean includeValue, Instance.InstanceType instanceType) { this(name, key, listener, includeValue, instanceType, false); } public ListenerItem(String name, Object key, Object listener, boolean includeValue, Instance.InstanceType instanceType, boolean localListener) { super(); this.key = key; this.listener = listener; this.name = name; this.includeValue = includeValue; this.instanceType = instanceType; this.localListener = localListener; } public boolean listens(DataAwareEntryEvent dataAwareEntryEvent) { String name = dataAwareEntryEvent.getLongName(); return this.name.equals(name) && (this.key == null || dataAwareEntryEvent.getKey().equals(this.key)); } public void writeData(DataOutput out) throws IOException { out.writeUTF(name); writeObject(out, key); out.writeBoolean(includeValue); } public void readData(DataInput in) throws IOException { name = in.readUTF(); key = readObject(in); includeValue = in.readBoolean(); } public void process() { getNode().listenerManager.registerListener(true, name, toData(key), getConnection().getEndPoint(), includeValue); } } }
Fixed listener deregistration on member leave.
hazelcast/src/main/java/com/hazelcast/impl/ListenerManager.java
Fixed listener deregistration on member leave.
<ide><path>azelcast/src/main/java/com/hazelcast/impl/ListenerManager.java <ide> } <ide> <ide> public void syncForDead(Address deadAddress) { <del> syncForAdd(); <add> //syncForAdd(); <add> for (List<ListenerItem> listeners : namedListeners.values()) { <add> for (ListenerItem listenerItem : listeners) { <add> if (!listenerItem.localListener) { <add> registerListener(false, listenerItem.name, <add> toData(listenerItem.key), deadAddress, listenerItem.includeValue); <add> } <add> } <add> } <ide> } <ide> <ide> public void syncForAdd() {
Java
bsd-3-clause
238e1c884c05e27c45f2c64cb987b8ea526af368
0
mbeiter/jaas
/* * #%L * This file is part of a common library for a set of universal JAAS modules. * %% * Copyright (C) 2014 - 2015 Michael Beiter <[email protected]> * %% * All rights reserved. * . * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the copyright holder nor the names of the * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * . * . * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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. * #L% */ package org.beiter.michael.authn.jaas.common.propsbuilder; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.Validate; import org.beiter.michael.authn.jaas.common.CommonProperties; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * This class builds a set of {@link CommonProperties} using the settings obtained from a * JAAS Properties Map. * <p> * <p> * Use the keys from the various KEY_* fields to properly populate the JAAS Properties Map before calling this class' * methods. */ // CHECKSTYLE:OFF // this is flagged in checkstyle with a missing whitespace before '}', which is a bug in checkstyle // suppress warnings about the long variable names @SuppressWarnings({"PMD.LongVariable"}) // CHECKSTYLE:ON public final class JaasBasedCommonPropsBuilder { /** * The logger object for this class */ private static final Logger LOG = LoggerFactory.getLogger(JaasBasedCommonPropsBuilder.class); // ################# // # Default values // ################# /** * @see CommonProperties#setAuditClassName(String) */ public static final String DEFAULT_AUDIT_CLASS_NAME = "org.beiter.michael.authn.jaas.common.audit.SampleAuditLogger"; /** * @see CommonProperties#setAuditEnabled(boolean) */ public static final boolean DEFAULT_AUDIT_IS_ENABLED = false; /** * @see CommonProperties#setAuditSingleton(boolean) */ public static final boolean DEFAULT_AUDIT_IS_SINGLETON = true; /** * @see CommonProperties#setMessageQueueClassName(String) */ public static final String DEFAULT_MESSAGEQ_CLASS_NAME = "org.beiter.michael.authn.jaas.common.messageq.SampleMessageLogger"; /** * @see CommonProperties#setMessageQueueEnabled(boolean) */ public static final boolean DEFAULT_MESSAGEQ_IS_ENABLED = false; /** * @see CommonProperties#setMessageQueueSingleton(boolean) */ public static final boolean DEFAULT_MESSAGEQ_IS_SINGLETON = true; /** * @see CommonProperties#setPasswordAuthenticatorClassName(String) */ public static final String DEFAULT_PASSWORD_AUTHENTICATOR_CLASS_NAME = null; /** * @see CommonProperties#setPasswordAuthenticatorSingleton(boolean) */ public static final boolean DEFAULT_PASSWORD_AUTHENTICATOR_IS_SINGLETON = true; /** * @see CommonProperties#setPasswordValidatorClassName(String) */ public static final String DEFAULT_PASSWORD_VALIDATOR_CLASS_NAME = null; /** * @see CommonProperties#setPasswordValidatorSingleton(boolean) */ public static final boolean DEFAULT_PASSWORD_VALIDATOR_IS_SINGLETON = true; // ##################### // # Configuration Keys // ##################### /** * @see CommonProperties#setAuditClassName(String) */ public static final String KEY_AUDIT_CLASS_NAME = "jaas.audit.class"; /** * @see CommonProperties#setAuditEnabled(boolean) */ public static final String KEY_AUDIT_IS_ENABLED = "jaas.audit.isEnabled"; /** * @see CommonProperties#setAuditSingleton(boolean) (boolean) */ public static final String KEY_AUDIT_IS_SINGLETON = "jaas.audit.isSingleton"; /** * @see CommonProperties#setMessageQueueClassName(String) */ public static final String KEY_MESSAGEQ_CLASS_NAME = "jaas.messageq.class"; /** * @see CommonProperties#setMessageQueueEnabled(boolean) */ public static final String KEY_MESSAGEQ_IS_ENABLED = "jaas.messageq.isEnabled"; /** * @see CommonProperties#setMessageQueueSingleton(boolean) */ public static final String KEY_MESSAGEQ_IS_SINGLETON = "jaas.messageq.isSingleton"; /** * @see CommonProperties#setPasswordAuthenticatorClassName(String) */ // Fortify will report a violation here for handling a hardcoded password, which is not the case. // This is a non-issue / false positive. public static final String KEY_PASSWORD_AUTHENTICATOR_CLASS_NAME = "jaas.password.authenticator.class"; /** * @see CommonProperties#setPasswordAuthenticatorSingleton(boolean) */ // Fortify will report a violation here for handling a hardcoded password, which is not the case. // This is a non-issue / false positive. public static final String KEY_PASSWORD_AUTHENTICATOR_IS_SINGLETON = "jaas.password.authenticator.isSingleton"; /** * @see CommonProperties#setPasswordValidatorClassName(String) */ // Fortify will report a violation here for handling a hardcoded password, which is not the case. // This is a non-issue / false positive. public static final String KEY_PASSWORD_VALIDATOR_CLASS_NAME = "jaas.password.validator.class"; /** * @see CommonProperties#setPasswordValidatorSingleton(boolean) */ // Fortify will report a violation here for handling a hardcoded password, which is not the case. // This is a non-issue / false positive. public static final String KEY_PASSWORD_VALIDATOR_IS_SINGLETON = "jaas.password.validator.isSingleton"; /** * A private constructor to prevent instantiation of this class */ private JaasBasedCommonPropsBuilder() { } /** * Creates a set of common properties that use the defaults as specified in this class. * * @return A set of database properties with (reasonable) defaults * @see JaasBasedCommonPropsBuilder */ public static CommonProperties buildDefault() { return build(new ConcurrentHashMap<String, String>()); } /** * Initialize a set of common properties based on key / values in a <code>HashMap</code>. * * @param properties A <code>HashMap</code> with configuration properties as required by the init() method in JAAS, * using the keys as specified in this class * @return A <code>DbProperties</code> object with default values, plus the provided parameters */ // CHECKSTYLE:OFF // this is flagged in checkstyle with a missing whitespace before '}', which is a bug in checkstyle // suppress warnings about this method being too long (not much point in splitting up this one!) // suppress warnings about this method being too complex (can't extract a generic subroutine to reduce exec paths) @SuppressWarnings({"PMD.ExcessiveMethodLength", "PMD.NPathComplexity", "PMD.CyclomaticComplexity", "PMD.StdCyclomaticComplexity", "PMD.ModifiedCyclomaticComplexity"}) // CHECKSTYLE:ON public static CommonProperties build(final Map<String, ?> properties) { Validate.notNull(properties); final CommonProperties commonProps = new CommonProperties(); String tmp = getOption(KEY_AUDIT_CLASS_NAME, properties); if (StringUtils.isNotEmpty(tmp)) { commonProps.setAuditClassName(tmp); logValue(KEY_AUDIT_CLASS_NAME, tmp); } else { commonProps.setAuditClassName(DEFAULT_AUDIT_CLASS_NAME); logDefault(KEY_AUDIT_CLASS_NAME, DEFAULT_AUDIT_CLASS_NAME); } tmp = getOption(KEY_AUDIT_IS_ENABLED, properties); if (StringUtils.isNotEmpty(tmp)) { commonProps.setAuditEnabled(Boolean.parseBoolean(tmp)); logValue(KEY_AUDIT_IS_ENABLED, tmp); } else { commonProps.setAuditEnabled(DEFAULT_AUDIT_IS_ENABLED); logDefault(KEY_AUDIT_IS_ENABLED, String.valueOf(DEFAULT_AUDIT_IS_ENABLED)); } tmp = getOption(KEY_AUDIT_IS_SINGLETON, properties); if (StringUtils.isNotEmpty(tmp)) { commonProps.setAuditSingleton(Boolean.parseBoolean(tmp)); logValue(KEY_AUDIT_IS_SINGLETON, tmp); } else { commonProps.setAuditSingleton(DEFAULT_AUDIT_IS_SINGLETON); logDefault(KEY_AUDIT_IS_SINGLETON, String.valueOf(DEFAULT_AUDIT_IS_SINGLETON)); } tmp = getOption(KEY_MESSAGEQ_CLASS_NAME, properties); if (StringUtils.isNotEmpty(tmp)) { commonProps.setMessageQueueClassName(tmp); logValue(KEY_MESSAGEQ_CLASS_NAME, tmp); } else { commonProps.setMessageQueueClassName(DEFAULT_MESSAGEQ_CLASS_NAME); logDefault(KEY_MESSAGEQ_CLASS_NAME, DEFAULT_MESSAGEQ_CLASS_NAME); } tmp = getOption(KEY_MESSAGEQ_IS_ENABLED, properties); if (StringUtils.isNotEmpty(tmp)) { commonProps.setMessageQueueEnabled(Boolean.parseBoolean(tmp)); logValue(KEY_MESSAGEQ_IS_ENABLED, tmp); } else { commonProps.setMessageQueueEnabled(DEFAULT_MESSAGEQ_IS_ENABLED); logDefault(KEY_MESSAGEQ_IS_ENABLED, String.valueOf(DEFAULT_MESSAGEQ_IS_ENABLED)); } tmp = getOption(KEY_MESSAGEQ_IS_SINGLETON, properties); if (StringUtils.isNotEmpty(tmp)) { commonProps.setMessageQueueSingleton(Boolean.parseBoolean(tmp)); logValue(KEY_MESSAGEQ_IS_SINGLETON, tmp); } else { commonProps.setMessageQueueSingleton(DEFAULT_MESSAGEQ_IS_SINGLETON); logDefault(KEY_MESSAGEQ_IS_SINGLETON, String.valueOf(DEFAULT_MESSAGEQ_IS_SINGLETON)); } tmp = getOption(KEY_PASSWORD_AUTHENTICATOR_CLASS_NAME, properties); if (StringUtils.isNotEmpty(tmp)) { commonProps.setPasswordAuthenticatorClassName(tmp); logValue(KEY_PASSWORD_AUTHENTICATOR_CLASS_NAME, tmp); } else { commonProps.setPasswordAuthenticatorClassName(DEFAULT_PASSWORD_AUTHENTICATOR_CLASS_NAME); logDefault(KEY_PASSWORD_AUTHENTICATOR_CLASS_NAME, DEFAULT_PASSWORD_AUTHENTICATOR_CLASS_NAME); } tmp = getOption(KEY_PASSWORD_AUTHENTICATOR_IS_SINGLETON, properties); if (StringUtils.isNotEmpty(tmp)) { commonProps.setPasswordAuthenticatorSingleton(Boolean.parseBoolean(tmp)); logValue(KEY_PASSWORD_AUTHENTICATOR_IS_SINGLETON, tmp); } else { commonProps.setPasswordAuthenticatorSingleton(DEFAULT_PASSWORD_AUTHENTICATOR_IS_SINGLETON); logDefault(KEY_PASSWORD_AUTHENTICATOR_IS_SINGLETON, String.valueOf(DEFAULT_PASSWORD_AUTHENTICATOR_IS_SINGLETON)); } tmp = getOption(KEY_PASSWORD_VALIDATOR_CLASS_NAME, properties); if (StringUtils.isNotEmpty(tmp)) { commonProps.setPasswordValidatorClassName(tmp); logValue(KEY_PASSWORD_VALIDATOR_CLASS_NAME, tmp); } else { commonProps.setPasswordValidatorClassName(DEFAULT_PASSWORD_VALIDATOR_CLASS_NAME); logDefault(KEY_PASSWORD_VALIDATOR_CLASS_NAME, DEFAULT_PASSWORD_VALIDATOR_CLASS_NAME); } tmp = getOption(KEY_PASSWORD_VALIDATOR_IS_SINGLETON, properties); if (StringUtils.isNotEmpty(tmp)) { commonProps.setPasswordValidatorSingleton(Boolean.parseBoolean(tmp)); logValue(KEY_PASSWORD_VALIDATOR_IS_SINGLETON, tmp); } else { commonProps.setPasswordValidatorSingleton(DEFAULT_PASSWORD_VALIDATOR_IS_SINGLETON); logDefault(KEY_PASSWORD_VALIDATOR_IS_SINGLETON, String.valueOf(DEFAULT_PASSWORD_VALIDATOR_IS_SINGLETON)); } // set the additional properties, preserving the originally provided properties // create a defensive copy of the map and all its properties // the code looks a little complicated that "putAll()", but it catches situations where a Map is provided that // supports null values (e.g. a HashMap) vs Map implementations that do not (e.g. ConcurrentHashMap). final Map<String, String> tempMap = new ConcurrentHashMap<>(); try { for (final Map.Entry<String, ?> entry : properties.entrySet()) { final String key = entry.getKey(); final String value = (String) entry.getValue(); if (value != null) { tempMap.put(key, value); } } } catch (ClassCastException e) { final String error = "The values of the configured JAAS properties must be Strings. " + "Sorry, but we do not support anything else here!"; throw new IllegalArgumentException(error, e); } commonProps.setAdditionalProperties(tempMap); return commonProps; } /** * Return the value of a JAAS configuration parameter. * * @param <T> The type of the element * @param key The key to retrieve from the options * @param properties The properties to retrieve values from * @return The configuration value for the provided key */ @SuppressWarnings("unchecked") private static <T> T getOption(final String key, final Map<String, ?> properties) { // private method asserts assert key != null : "The key cannot be null"; return (T) properties.get(key); } /** * Create a log entry when a value has been successfully configured. * * @param key The configuration key * @param value The value that is being used */ private static void logValue(final String key, final String value) { // Fortify will report a violation here because of disclosure of potentially confidential information. // However, the configuration keys are not confidential, which makes this a non-issue / false positive. if (LOG.isInfoEnabled()) { final StringBuilder msg = new StringBuilder("Key found in configuration ('") .append(key) .append("'), using configured value (not disclosed here for security reasons)"); LOG.info(msg.toString()); } // Fortify will report a violation here because of disclosure of potentially confidential information. // The configuration VALUES are confidential. DO NOT activate DEBUG logging in production. if (LOG.isDebugEnabled()) { final StringBuilder msg = new StringBuilder("Key found in configuration ('") .append(key) .append("'), using configured value ('"); if (value == null) { msg.append("null')"); } else { msg.append(value).append("')"); } LOG.debug(msg.toString()); } } /** * Create a log entry when a default value is being used in case the propsbuilder key has not been provided in the * configuration. * * @param key The configuration key * @param defaultValue The default value that is being used */ private static void logDefault(final String key, final String defaultValue) { // Fortify will report a violation here because of disclosure of potentially confidential information. // However, neither the configuration keys nor the default propsbuilder values are confidential, which makes // this a non-issue / false positive. if (LOG.isInfoEnabled()) { final StringBuilder msg = new StringBuilder("Key is not configured ('") .append(key) .append("'), using default value ('"); if (defaultValue == null) { msg.append("null')"); } else { msg.append(defaultValue).append("')"); } LOG.info(msg.toString()); } } }
common/src/main/java/org/beiter/michael/authn/jaas/common/propsbuilder/JaasBasedCommonPropsBuilder.java
/* * #%L * This file is part of a common library for a set of universal JAAS modules. * %% * Copyright (C) 2014 - 2015 Michael Beiter <[email protected]> * %% * All rights reserved. * . * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the copyright holder nor the names of the * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * . * . * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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. * #L% */ package org.beiter.michael.authn.jaas.common.propsbuilder; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.Validate; import org.beiter.michael.authn.jaas.common.CommonProperties; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * This class builds a set of {@link CommonProperties} using the settings obtained from a * JAAS Properties Map. * <p> * <p> * Use the keys from the various KEY_* fields to properly populate the JAAS Properties Map before calling this class' * methods. */ // CHECKSTYLE:OFF // this is flagged in checkstyle with a missing whitespace before '}', which is a bug in checkstyle // suppress warnings about the long variable names @SuppressWarnings({"PMD.LongVariable"}) // CHECKSTYLE:ON public final class JaasBasedCommonPropsBuilder { /** * The logger object for this class */ private static final Logger LOG = LoggerFactory.getLogger(JaasBasedCommonPropsBuilder.class); // ################# // # Default values // ################# /** * @see CommonProperties#setAuditClassName(String) */ public static final String DEFAULT_AUDIT_CLASS_NAME = "org.beiter.michael.authn.jaas.common.audit.SampleAuditLogger"; /** * @see CommonProperties#setAuditEnabled(boolean) */ public static final boolean DEFAULT_AUDIT_IS_ENABLED = false; /** * @see CommonProperties#setAuditSingleton(boolean) */ public static final boolean DEFAULT_AUDIT_IS_SINGLETON = true; /** * @see CommonProperties#setMessageQueueClassName(String) */ public static final String DEFAULT_MESSAGEQ_CLASS_NAME = "org.beiter.michael.authn.jaas.common.messageq.SampleMessageLogger"; /** * @see CommonProperties#setMessageQueueEnabled(boolean) */ public static final boolean DEFAULT_MESSAGEQ_IS_ENABLED = false; /** * @see CommonProperties#setMessageQueueSingleton(boolean) */ public static final boolean DEFAULT_MESSAGEQ_IS_SINGLETON = true; /** * @see CommonProperties#setPasswordAuthenticatorClassName(String) */ public static final String DEFAULT_PASSWORD_AUTHENTICATOR_CLASS_NAME = null; /** * @see CommonProperties#setPasswordAuthenticatorSingleton(boolean) */ public static final boolean DEFAULT_PASSWORD_AUTHENTICATOR_IS_SINGLETON = true; /** * @see CommonProperties#setPasswordValidatorClassName(String) */ public static final String DEFAULT_PASSWORD_VALIDATOR_CLASS_NAME = null; /** * @see CommonProperties#setPasswordValidatorSingleton(boolean) */ public static final boolean DEFAULT_PASSWORD_VALIDATOR_IS_SINGLETON = true; // ##################### // # Configuration Keys // ##################### /** * @see CommonProperties#setAuditClassName(String) */ public static final String KEY_AUDIT_CLASS_NAME = "jaas.audit.class"; /** * @see CommonProperties#setAuditEnabled(boolean) */ public static final String KEY_AUDIT_IS_ENABLED = "jaas.audit.isEnabled"; /** * @see CommonProperties#setAuditSingleton(boolean) (boolean) */ public static final String KEY_AUDIT_IS_SINGLETON = "jaas.audit.isSingleton"; /** * @see CommonProperties#setMessageQueueClassName(String) */ public static final String KEY_MESSAGEQ_CLASS_NAME = "jaas.messageq.class"; /** * @see CommonProperties#setMessageQueueEnabled(boolean) */ public static final String KEY_MESSAGEQ_IS_ENABLED = "jaas.messageq.isEnabled"; /** * @see CommonProperties#setMessageQueueSingleton(boolean) */ public static final String KEY_MESSAGEQ_IS_SINGLETON = "jaas.messageq.isSingleton"; /** * @see CommonProperties#setPasswordAuthenticatorClassName(String) */ // Fortify will report a violation here for handling a hardcoded password, which is not the case. // This is a non-issue / false positive. public static final String KEY_PASSWORD_AUTHENTICATOR_CLASS_NAME = "jaas.password.authenticator.class"; /** * @see CommonProperties#setPasswordAuthenticatorSingleton(boolean) */ // Fortify will report a violation here for handling a hardcoded password, which is not the case. // This is a non-issue / false positive. public static final String KEY_PASSWORD_AUTHENTICATOR_IS_SINGLETON = "jaas.password.authenticator.isSingleton"; /** * @see CommonProperties#setPasswordValidatorClassName(String) */ // Fortify will report a violation here for handling a hardcoded password, which is not the case. // This is a non-issue / false positive. public static final String KEY_PASSWORD_VALIDATOR_CLASS_NAME = "jaas.password.validator.class"; /** * @see CommonProperties#setPasswordValidatorSingleton(boolean) */ // Fortify will report a violation here for handling a hardcoded password, which is not the case. // This is a non-issue / false positive. public static final String KEY_PASSWORD_VALIDATOR_IS_SINGLETON = "jaas.password.validator.isSingleton"; /** * A private constructor to prevent instantiation of this class */ private JaasBasedCommonPropsBuilder() { } /** * Creates a set of database properties that use the defaults as specified in this class. * * @return A set of database properties with (reasonable) defaults * @see JaasBasedCommonPropsBuilder */ public static CommonProperties buildDefault() { return build(new ConcurrentHashMap<String, String>()); } /** * Initialize a set of common properties based on key / values in a <code>HashMap</code>. * * @param properties A <code>HashMap</code> with configuration properties as required by the init() method in JAAS, * using the keys as specified in this class * @return A <code>DbProperties</code> object with default values, plus the provided parameters */ // CHECKSTYLE:OFF // this is flagged in checkstyle with a missing whitespace before '}', which is a bug in checkstyle // suppress warnings about this method being too long (not much point in splitting up this one!) // suppress warnings about this method being too complex (can't extract a generic subroutine to reduce exec paths) @SuppressWarnings({"PMD.ExcessiveMethodLength", "PMD.NPathComplexity", "PMD.CyclomaticComplexity", "PMD.StdCyclomaticComplexity", "PMD.ModifiedCyclomaticComplexity"}) // CHECKSTYLE:ON public static CommonProperties build(final Map<String, ?> properties) { Validate.notNull(properties); final CommonProperties commonProps = new CommonProperties(); String tmp = getOption(KEY_AUDIT_CLASS_NAME, properties); if (StringUtils.isNotEmpty(tmp)) { commonProps.setAuditClassName(tmp); logValue(KEY_AUDIT_CLASS_NAME, tmp); } else { commonProps.setAuditClassName(DEFAULT_AUDIT_CLASS_NAME); logDefault(KEY_AUDIT_CLASS_NAME, DEFAULT_AUDIT_CLASS_NAME); } tmp = getOption(KEY_AUDIT_IS_ENABLED, properties); if (StringUtils.isNotEmpty(tmp)) { commonProps.setAuditEnabled(Boolean.parseBoolean(tmp)); logValue(KEY_AUDIT_IS_ENABLED, tmp); } else { commonProps.setAuditEnabled(DEFAULT_AUDIT_IS_ENABLED); logDefault(KEY_AUDIT_IS_ENABLED, String.valueOf(DEFAULT_AUDIT_IS_ENABLED)); } tmp = getOption(KEY_AUDIT_IS_SINGLETON, properties); if (StringUtils.isNotEmpty(tmp)) { commonProps.setAuditSingleton(Boolean.parseBoolean(tmp)); logValue(KEY_AUDIT_IS_SINGLETON, tmp); } else { commonProps.setAuditSingleton(DEFAULT_AUDIT_IS_SINGLETON); logDefault(KEY_AUDIT_IS_SINGLETON, String.valueOf(DEFAULT_AUDIT_IS_SINGLETON)); } tmp = getOption(KEY_MESSAGEQ_CLASS_NAME, properties); if (StringUtils.isNotEmpty(tmp)) { commonProps.setMessageQueueClassName(tmp); logValue(KEY_MESSAGEQ_CLASS_NAME, tmp); } else { commonProps.setMessageQueueClassName(DEFAULT_MESSAGEQ_CLASS_NAME); logDefault(KEY_MESSAGEQ_CLASS_NAME, DEFAULT_MESSAGEQ_CLASS_NAME); } tmp = getOption(KEY_MESSAGEQ_IS_ENABLED, properties); if (StringUtils.isNotEmpty(tmp)) { commonProps.setMessageQueueEnabled(Boolean.parseBoolean(tmp)); logValue(KEY_MESSAGEQ_IS_ENABLED, tmp); } else { commonProps.setMessageQueueEnabled(DEFAULT_MESSAGEQ_IS_ENABLED); logDefault(KEY_MESSAGEQ_IS_ENABLED, String.valueOf(DEFAULT_MESSAGEQ_IS_ENABLED)); } tmp = getOption(KEY_MESSAGEQ_IS_SINGLETON, properties); if (StringUtils.isNotEmpty(tmp)) { commonProps.setMessageQueueSingleton(Boolean.parseBoolean(tmp)); logValue(KEY_MESSAGEQ_IS_SINGLETON, tmp); } else { commonProps.setMessageQueueSingleton(DEFAULT_MESSAGEQ_IS_SINGLETON); logDefault(KEY_MESSAGEQ_IS_SINGLETON, String.valueOf(DEFAULT_MESSAGEQ_IS_SINGLETON)); } tmp = getOption(KEY_PASSWORD_AUTHENTICATOR_CLASS_NAME, properties); if (StringUtils.isNotEmpty(tmp)) { commonProps.setPasswordAuthenticatorClassName(tmp); logValue(KEY_PASSWORD_AUTHENTICATOR_CLASS_NAME, tmp); } else { commonProps.setPasswordAuthenticatorClassName(DEFAULT_PASSWORD_AUTHENTICATOR_CLASS_NAME); logDefault(KEY_PASSWORD_AUTHENTICATOR_CLASS_NAME, DEFAULT_PASSWORD_AUTHENTICATOR_CLASS_NAME); } tmp = getOption(KEY_PASSWORD_AUTHENTICATOR_IS_SINGLETON, properties); if (StringUtils.isNotEmpty(tmp)) { commonProps.setPasswordAuthenticatorSingleton(Boolean.parseBoolean(tmp)); logValue(KEY_PASSWORD_AUTHENTICATOR_IS_SINGLETON, tmp); } else { commonProps.setPasswordAuthenticatorSingleton(DEFAULT_PASSWORD_AUTHENTICATOR_IS_SINGLETON); logDefault(KEY_PASSWORD_AUTHENTICATOR_IS_SINGLETON, String.valueOf(DEFAULT_PASSWORD_AUTHENTICATOR_IS_SINGLETON)); } tmp = getOption(KEY_PASSWORD_VALIDATOR_CLASS_NAME, properties); if (StringUtils.isNotEmpty(tmp)) { commonProps.setPasswordValidatorClassName(tmp); logValue(KEY_PASSWORD_VALIDATOR_CLASS_NAME, tmp); } else { commonProps.setPasswordValidatorClassName(DEFAULT_PASSWORD_VALIDATOR_CLASS_NAME); logDefault(KEY_PASSWORD_VALIDATOR_CLASS_NAME, DEFAULT_PASSWORD_VALIDATOR_CLASS_NAME); } tmp = getOption(KEY_PASSWORD_VALIDATOR_IS_SINGLETON, properties); if (StringUtils.isNotEmpty(tmp)) { commonProps.setPasswordValidatorSingleton(Boolean.parseBoolean(tmp)); logValue(KEY_PASSWORD_VALIDATOR_IS_SINGLETON, tmp); } else { commonProps.setPasswordValidatorSingleton(DEFAULT_PASSWORD_VALIDATOR_IS_SINGLETON); logDefault(KEY_PASSWORD_VALIDATOR_IS_SINGLETON, String.valueOf(DEFAULT_PASSWORD_VALIDATOR_IS_SINGLETON)); } // set the additional properties, preserving the originally provided properties // create a defensive copy of the map and all its properties // the code looks a little complicated that "putAll()", but it catches situations where a Map is provided that // supports null values (e.g. a HashMap) vs Map implementations that do not (e.g. ConcurrentHashMap). final Map<String, String> tempMap = new ConcurrentHashMap<>(); try { for (final Map.Entry<String, ?> entry : properties.entrySet()) { final String key = entry.getKey(); final String value = (String) entry.getValue(); if (value != null) { tempMap.put(key, value); } } } catch (ClassCastException e) { final String error = "The values of the configured JAAS properties must be Strings. " + "Sorry, but we do not support anything else here!"; throw new IllegalArgumentException(error, e); } commonProps.setAdditionalProperties(tempMap); return commonProps; } /** * Return the value of a JAAS configuration parameter. * * @param <T> The type of the element * @param key The key to retrieve from the options * @param properties The properties to retrieve values from * @return The configuration value for the provided key */ @SuppressWarnings("unchecked") private static <T> T getOption(final String key, final Map<String, ?> properties) { // private method asserts assert key != null : "The key cannot be null"; return (T) properties.get(key); } /** * Create a log entry when a value has been successfully configured. * * @param key The configuration key * @param value The value that is being used */ private static void logValue(final String key, final String value) { // Fortify will report a violation here because of disclosure of potentially confidential information. // However, the configuration keys are not confidential, which makes this a non-issue / false positive. if (LOG.isInfoEnabled()) { final StringBuilder msg = new StringBuilder("Key found in configuration ('") .append(key) .append("'), using configured value (not disclosed here for security reasons)"); LOG.info(msg.toString()); } // Fortify will report a violation here because of disclosure of potentially confidential information. // The configuration VALUES are confidential. DO NOT activate DEBUG logging in production. if (LOG.isDebugEnabled()) { final StringBuilder msg = new StringBuilder("Key found in configuration ('") .append(key) .append("'), using configured value ('"); if (value == null) { msg.append("null')"); } else { msg.append(value).append("')"); } LOG.debug(msg.toString()); } } /** * Create a log entry when a default value is being used in case the propsbuilder key has not been provided in the * configuration. * * @param key The configuration key * @param defaultValue The default value that is being used */ private static void logDefault(final String key, final String defaultValue) { // Fortify will report a violation here because of disclosure of potentially confidential information. // However, neither the configuration keys nor the default propsbuilder values are confidential, which makes // this a non-issue / false positive. if (LOG.isInfoEnabled()) { final StringBuilder msg = new StringBuilder("Key is not configured ('") .append(key) .append("'), using default value ('"); if (defaultValue == null) { msg.append("null')"); } else { msg.append(defaultValue).append("')"); } LOG.info(msg.toString()); } } }
Javadocs
common/src/main/java/org/beiter/michael/authn/jaas/common/propsbuilder/JaasBasedCommonPropsBuilder.java
Javadocs
<ide><path>ommon/src/main/java/org/beiter/michael/authn/jaas/common/propsbuilder/JaasBasedCommonPropsBuilder.java <ide> } <ide> <ide> /** <del> * Creates a set of database properties that use the defaults as specified in this class. <add> * Creates a set of common properties that use the defaults as specified in this class. <ide> * <ide> * @return A set of database properties with (reasonable) defaults <ide> * @see JaasBasedCommonPropsBuilder
Java
lgpl-2.1
6963e887f84e7513e6324c3ed9d8b2bf70b13b22
0
xwiki/xwiki-platform,xwiki/xwiki-platform,pbondoer/xwiki-platform,pbondoer/xwiki-platform,pbondoer/xwiki-platform,xwiki/xwiki-platform,pbondoer/xwiki-platform,xwiki/xwiki-platform,xwiki/xwiki-platform,pbondoer/xwiki-platform
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.xwiki.activitystream; import java.util.Arrays; import org.junit.Before; import org.junit.Test; import org.xwiki.model.reference.DocumentReference; import org.xwiki.query.internal.ScriptQuery; import org.xwiki.query.script.QueryManagerScriptService; import org.xwiki.rendering.syntax.Syntax; import org.xwiki.script.service.ScriptService; import org.xwiki.test.page.PageTest; import com.xpn.xwiki.plugin.feed.FeedPlugin; import com.xpn.xwiki.plugin.feed.FeedPluginApi; import static org.mockito.Mockito.*; import static org.junit.Assert.*; /** * Unit tests for testing the {@code Main.WebRss} wiki page. * * @version $Id$ * @since 7.3M1 */ public class WebRssTest extends PageTest { private ScriptQuery query; @Before public void setUp() throws Exception { setOutputSyntax(Syntax.PLAIN_1_0); request.put("outputSyntax", "plain"); request.put("xpage", "plain"); QueryManagerScriptService qmss = mock(QueryManagerScriptService.class); oldcore.getMocker().registerComponent(ScriptService.class, "query", qmss); query = mock(ScriptQuery.class); when(qmss.xwql("where 1=1 order by doc.date desc")).thenReturn(query); } @Test public void webRssFiltersHiddenDocuments() throws Exception { // Render the page to test renderPage(new DocumentReference("xwiki", "Main", "WebRss")); // This is the real test!! // We want to verify that the hidden document filter is called when executing the XWQL // query to get the list of modified pages verify(query).addFilter("hidden/document"); } @Test public void webRssDisplay() throws Exception { when(query.addFilter(anyString())).thenReturn(query); when(query.setLimit(20)).thenReturn(query); when(query.setOffset(0)).thenReturn(query); when(query.execute()).thenReturn(Arrays.<Object>asList("Space1.Page1", "Space2.Page2")); FeedPlugin plugin = new FeedPlugin("feed", FeedPlugin.class.getName(), context); FeedPluginApi pluginApi = new FeedPluginApi(plugin, context); doReturn(pluginApi).when(xwiki).getPluginApi("feed", context); // Render the page to test String xml = renderPage(new DocumentReference("xwiki", "Main", "WebRss")); assertTrue(xml.contains("<title>activity.rss.feed.description</title>")); assertTrue(xml.contains("<title>Page1</title>")); assertTrue(xml.contains("<title>Page2</title>")); } }
xwiki-platform-core/xwiki-platform-activitystream/xwiki-platform-activitystream-ui/src/test/java/org/xwiki/activitystream/WebRssTest.java
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.xwiki.activitystream; import java.util.Arrays; import org.junit.Before; import org.junit.Test; import org.xwiki.model.reference.DocumentReference; import org.xwiki.query.internal.ScriptQuery; import org.xwiki.query.script.QueryManagerScriptService; import org.xwiki.rendering.syntax.Syntax; import org.xwiki.script.service.ScriptService; import org.xwiki.test.page.PageTest; import com.xpn.xwiki.plugin.feed.FeedPlugin; import com.xpn.xwiki.plugin.feed.FeedPluginApi; import static org.mockito.Mockito.*; import static org.junit.Assert.*; /** * Unit tests for testing the {@code Main.WebRss} wiki page. * * @version $Id$ * @since 7.3M1 */ public class WebRssTest extends PageTest { private ScriptQuery query; @Before public void setUp() throws Exception { setOutputSyntax(Syntax.PLAIN_1_0); request.put("outputSyntax", "plain"); request.put("xpage", "plain"); QueryManagerScriptService qmss = mock(QueryManagerScriptService.class); oldcore.getMocker().registerComponent(ScriptService.class, "query", qmss); query = mock(ScriptQuery.class); when(qmss.xwql("where 1=1 order by doc.date desc")).thenReturn(query); } @Test public void webRssFiltersHiddenDocuments() throws Exception { // Render the page to test renderPage(new DocumentReference("xwiki", "Main", "WebRss")); // This is the real test!! // We want to verify that the hidden document filter is called when executing the XWQL // query to get the list of modified pages verify(query).addFilter("hidden/document"); } @Test public void webRssDisplay() throws Exception { when(query.addFilter(anyString())).thenReturn(query); when(query.setLimit(20)).thenReturn(query); when(query.setOffset(0)).thenReturn(query); when(query.execute()).thenReturn(Arrays.<Object>asList("Space1.Page1", "Space2.Page2")); FeedPlugin plugin = new FeedPlugin("feed", FeedPlugin.class.getName(), context); FeedPluginApi pluginApi = new FeedPluginApi(plugin, context); when(xwiki.getPluginApi("feed", context)).thenReturn(pluginApi); // Render the page to test String xml = renderPage(new DocumentReference("xwiki", "Main", "WebRss")); assertTrue(xml.contains("<title>activity.rss.feed.description</title>")); assertTrue(xml.contains("<title>Page1</title>")); assertTrue(xml.contains("<title>Page2</title>")); } }
[misc] Make MockitoOldCore XWiki instane a spy instead of a mock
xwiki-platform-core/xwiki-platform-activitystream/xwiki-platform-activitystream-ui/src/test/java/org/xwiki/activitystream/WebRssTest.java
[misc] Make MockitoOldCore XWiki instane a spy instead of a mock
<ide><path>wiki-platform-core/xwiki-platform-activitystream/xwiki-platform-activitystream-ui/src/test/java/org/xwiki/activitystream/WebRssTest.java <ide> <ide> FeedPlugin plugin = new FeedPlugin("feed", FeedPlugin.class.getName(), context); <ide> FeedPluginApi pluginApi = new FeedPluginApi(plugin, context); <del> when(xwiki.getPluginApi("feed", context)).thenReturn(pluginApi); <add> doReturn(pluginApi).when(xwiki).getPluginApi("feed", context); <ide> <ide> // Render the page to test <ide> String xml = renderPage(new DocumentReference("xwiki", "Main", "WebRss"));
JavaScript
mit
4f7e1c1deb5e83c02abe566aa1f43ae2de658eaf
0
codevise/pageflow,tf/pageflow,tf/pageflow,tf/pageflow,codevise/pageflow,codevise/pageflow,tf/pageflow,codevise/pageflow
import React, {useState, useCallback, useRef} from 'react'; import {DraggableCore} from 'react-draggable'; import Measure from 'react-measure'; import classNames from 'classnames'; import {useI18n} from '../i18n'; import {formatTime} from './formatTime'; import styles from './ProgressIndicators.module.css'; export function ProgressIndicators({currentTime, duration, bufferedEnd, scrubTo, seekTo}) { const {t} = useI18n(); const [dragging, setDragging] = useState(); const progressBarsContainerWidth = useRef(); const positionToTime = useCallback((x) => { if (duration && progressBarsContainerWidth.current) { const fraction = Math.max(0, Math.min(1, x / progressBarsContainerWidth.current)); return fraction * duration; } else { return 0; } }, [duration]); const handleStop = useCallback((mouseEvent, dragEvent) => { setDragging(false); seekTo(positionToTime(dragEvent.x)); }, [seekTo, positionToTime]); const handleDrag = useCallback((mouseEvent, dragEvent) => { setDragging(true); scrubTo(positionToTime(dragEvent.x)); }, [scrubTo, positionToTime]); const handleKeyDown = useCallback(event => { let destination; if (event.key === 'ArrowLeft') { destination = Math.max(0, currentTime - 1); } else if (event.key === 'ArrowRight') { destination = Math.min(currentTime + 1, duration || Infinity); } seekTo(destination); }, [seekTo, currentTime, duration]); const loadProgress = duration > 0 ? Math.min(1, bufferedEnd / duration) : 0; const playProgress = duration > 0 ? Math.min(1, currentTime / duration) : 0; return ( <div className={classNames(styles.container, {[styles.dragging]: dragging})} aria-label={t('pageflow_scrolled.public.player_controls.progress', { currentTime: formatTime(currentTime), duration: formatTime(duration) })} onKeyDown={handleKeyDown} tabIndex="0"> <div className={styles.wrapper}> <Measure client onResize={contentRect => progressBarsContainerWidth.current = contentRect.client.width}> {({measureRef}) => <DraggableCore onStart={handleDrag} onDrag={handleDrag} onStop={handleStop}> <div className={classNames(styles.draggable)}> <div ref={measureRef} className={styles.bars}> <div className={styles.background} /> <div className={styles.loadingProgressBar} style={{width: toPercent(loadProgress)}} data-testid="loading-progress-bar"/> <div className={styles.playProgressBar} style={{width: toPercent(playProgress)}} data-testid="play-progress-bar"/> <div className={styles.sliderHandle} style={{left: toPercent(playProgress)}} data-testid="slider-handle"/> </div> </div> </DraggableCore> } </Measure> </div> </div> ); } function toPercent(value) { return value > 0 ? (value * 100) + '%' : 0; }
entry_types/scrolled/package/src/frontend/PlayerControls/ProgressIndicators.js
import React, {useState, useCallback, useRef} from 'react'; import {DraggableCore} from 'react-draggable'; import Measure from 'react-measure'; import classNames from 'classnames'; import {useI18n} from '../i18n'; import {formatTime} from './formatTime'; import styles from './ProgressIndicators.module.css'; export function ProgressIndicators({currentTime, duration, bufferedEnd, scrubTo, seekTo}) { const {t} = useI18n(); const [dragging, setDragging] = useState(); const progressBarsContainerWidth = useRef(); const positionToTime = useCallback((x) => { if (duration && progressBarsContainerWidth.current) { const fraction = Math.max(0, Math.min(1, x / progressBarsContainerWidth.current)); return fraction * duration; } else { return 0; } }, [duration]); const handleStop = useCallback((mouseEvent, dragEvent) => { setDragging(false); seekTo(positionToTime(dragEvent.x)); }, [seekTo, positionToTime]); const handleDrag = useCallback((mouseEvent, dragEvent) => { setDragging(true); scrubTo(positionToTime(dragEvent.x)); }, [scrubTo, positionToTime]); const handleKeyDown = useCallback(event => { let destination; if (event.key === 'ArrowLeft') { destination = Math.max(0, currentTime - 1); } else if (event.key === 'ArrowRight') { destination = Math.min(currentTime + 1, duration || Infinity); } seekTo(destination); }, [seekTo, currentTime, duration]); const loadProgress = duration > 0 ? (bufferedEnd / duration) : 0; const playProgress = duration > 0 ? (currentTime / duration) : 0; return ( <div className={classNames(styles.container, {[styles.dragging]: dragging})} aria-label={t('pageflow_scrolled.public.player_controls.progress', { currentTime: formatTime(currentTime), duration: formatTime(duration) })} onKeyDown={handleKeyDown} tabIndex="0"> <div className={styles.wrapper}> <Measure client onResize={contentRect => progressBarsContainerWidth.current = contentRect.client.width}> {({measureRef}) => <DraggableCore onStart={handleDrag} onDrag={handleDrag} onStop={handleStop}> <div className={classNames(styles.draggable)}> <div ref={measureRef} className={styles.bars}> <div className={styles.background} /> <div className={styles.loadingProgressBar} style={{width: toPercent(loadProgress)}} data-testid="loading-progress-bar"/> <div className={styles.playProgressBar} style={{width: toPercent(playProgress)}} data-testid="play-progress-bar"/> <div className={styles.sliderHandle} style={{left: toPercent(playProgress)}} data-testid="slider-handle"/> </div> </div> </DraggableCore> } </Measure> </div> </div> ); } function toPercent(value) { return value > 0 ? (value * 100) + '%' : 0; }
Prevent progress bar with more than 100% There appear to be race conditions where `progress` events are dispatched when the duration of media player has not been updated yet. REDMINE-17761
entry_types/scrolled/package/src/frontend/PlayerControls/ProgressIndicators.js
Prevent progress bar with more than 100%
<ide><path>ntry_types/scrolled/package/src/frontend/PlayerControls/ProgressIndicators.js <ide> seekTo(destination); <ide> }, [seekTo, currentTime, duration]); <ide> <del> const loadProgress = duration > 0 ? (bufferedEnd / duration) : 0; <del> const playProgress = duration > 0 ? (currentTime / duration) : 0; <add> const loadProgress = duration > 0 ? Math.min(1, bufferedEnd / duration) : 0; <add> const playProgress = duration > 0 ? Math.min(1, currentTime / duration) : 0; <ide> <ide> return ( <ide> <div className={classNames(styles.container, {[styles.dragging]: dragging})}
Java
apache-2.0
d4ec6a8e36fa6fc0b34aa3d2424e2cbdd93301b6
0
GFriedrich/logging-log4j2,renchunxiao/logging-log4j2,neuro-sys/logging-log4j2,lburgazzoli/apache-logging-log4j2,lburgazzoli/logging-log4j2,codescale/logging-log4j2,apache/logging-log4j2,lqbweb/logging-log4j2,lburgazzoli/apache-logging-log4j2,apache/logging-log4j2,ChetnaChaudhari/logging-log4j2,lburgazzoli/apache-logging-log4j2,neuro-sys/logging-log4j2,renchunxiao/logging-log4j2,xnslong/logging-log4j2,apache/logging-log4j2,codescale/logging-log4j2,xnslong/logging-log4j2,ChetnaChaudhari/logging-log4j2,jsnikhil/nj-logging-log4j2,jinxuan/logging-log4j2,pisfly/logging-log4j2,jinxuan/logging-log4j2,lburgazzoli/logging-log4j2,jsnikhil/nj-logging-log4j2,MagicWiz/log4j2,lqbweb/logging-log4j2,MagicWiz/log4j2,lqbweb/logging-log4j2,GFriedrich/logging-log4j2,pisfly/logging-log4j2,xnslong/logging-log4j2,codescale/logging-log4j2,GFriedrich/logging-log4j2,lburgazzoli/logging-log4j2
/* * 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.logging.log4j.spi; import java.util.EnumSet; /** * Standard Logging Levels as an enumeration for use internally. This enum is used as a parameter in * any public APIs. */ public enum StandardLevel { /** * No events will be logged. */ OFF(0), /** * A severe error that will prevent the application from continuing. */ FATAL(100), /** * An error in the application, possibly recoverable. */ ERROR(200), /** * An event that might possible lead to an error. */ WARN(300), /** * An event for informational purposes. */ INFO(400), /** * A general debugging event. */ DEBUG(500), /** * A fine-grained debug message, typically capturing the flow through the application. */ TRACE(600), /** * All events should be logged. */ ALL(Integer.MAX_VALUE); private final int intLevel; private static final EnumSet<StandardLevel> levelSet = EnumSet.allOf(StandardLevel.class); private StandardLevel(final int val) { intLevel = val; } /** * Returns the integer value of the Level. * @return the integer value of the Level. */ public int intLevel() { return intLevel; } /** * Method to convert custom Levels into a StandardLevel for conversion to other systems. * @param intLevel The integer value of the Level. * @return The StandardLevel. */ public static StandardLevel getStandardLevel(int intLevel) { StandardLevel level = StandardLevel.OFF; for (StandardLevel lvl : levelSet) { if (lvl.intLevel() > intLevel) { break; } level = lvl; } return level; } }
log4j-api/src/main/java/org/apache/logging/log4j/spi/StandardLevel.java
/* * 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.logging.log4j.spi; import java.util.EnumSet; /** * Standard Logging Levels as an enumeration for use internally. This enum is used as a parameter in * any public APIs. */ public enum StandardLevel { /** * No events will be logged. */ OFF(0), /** * A severe error that will prevent the application from continuing. */ FATAL(100), /** * An error in the application, possibly recoverable. */ ERROR(200), /** * An event that might possible lead to an error. */ WARN(300), /** * An event for informational purposes. */ INFO(400), /** * A general debugging event. */ DEBUG(500), /** * A fine-grained debug message, typically capturing the flow through the application. */ TRACE(600), /** * All events should be logged. */ ALL(Integer.MAX_VALUE); private final int intLevel; private static final EnumSet<StandardLevel> levelSet = EnumSet.allOf(StandardLevel.class); private StandardLevel(final int val) { intLevel = val; } /** * Returns the integer value of the Level. * @return the integer value of the Level. */ public int intLevel() { return intLevel; } /** * Method to convert custom Levels into a StdLevel for conversion to other systems. * @param intLevel The integer value of the Level. * @return The StdLevel. */ public static StandardLevel getStandardLevel(int intLevel) { StandardLevel level = StandardLevel.OFF; for (StandardLevel lvl : levelSet) { if (lvl.intLevel() > intLevel) { break; } level = lvl; } return level; } }
Javadoc fix. git-svn-id: de5ce936019686f47409c93bcc5e202a9739563b@1561790 13f79535-47bb-0310-9956-ffa450edef68
log4j-api/src/main/java/org/apache/logging/log4j/spi/StandardLevel.java
Javadoc fix.
<ide><path>og4j-api/src/main/java/org/apache/logging/log4j/spi/StandardLevel.java <ide> } <ide> <ide> /** <del> * Method to convert custom Levels into a StdLevel for conversion to other systems. <add> * Method to convert custom Levels into a StandardLevel for conversion to other systems. <ide> * @param intLevel The integer value of the Level. <del> * @return The StdLevel. <add> * @return The StandardLevel. <ide> */ <ide> public static StandardLevel getStandardLevel(int intLevel) { <ide> StandardLevel level = StandardLevel.OFF;
Java
isc
c2d78d0e0f88172f3292498066c434784f6529cc
0
steve-goldman/volksempfaenger
package net.x4a42.volksempfaenger.ui; import java.util.Collection; import java.util.HashSet; import java.util.List; import net.x4a42.volksempfaenger.PreferenceKeys; import net.x4a42.volksempfaenger.R; import net.x4a42.volksempfaenger.VolksempfaengerApplication; import net.x4a42.volksempfaenger.service.playlistdownload.PlaylistDownloadServiceIntentProvider; import net.x4a42.volksempfaenger.service.playlistdownload.PlaylistDownloadServiceIntentProviderBuilder; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.net.Uri; import android.os.Bundle; import android.preference.EditTextPreference; import android.preference.ListPreference; import android.preference.Preference; import android.preference.PreferenceActivity; import android.preference.PreferenceManager; import android.preference.PreferenceScreen; import android.text.InputType; import android.widget.EditText; public class SettingsActivity extends PreferenceActivity { private static final Collection<String> validFragments = new HashSet<>(); @Override public void onBuildHeaders(List<Header> target) { loadHeadersFromResource(R.xml.preference_headers, target); for (Header header : target) { validFragments.add(header.fragment); } } @Override public void invalidateHeaders() { validFragments.clear(); } @Override protected boolean isValidFragment(String fragmentName) { return validFragments.contains(fragmentName); } public static class DownloadFragment extends SettingsFragment implements OnSharedPreferenceChangeListener { private PreferenceScreen prefScreen; private ListPreference prefInterval; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preference_download); prefScreen = getPreferenceScreen(); prefInterval = (ListPreference) prefScreen .findPreference(PreferenceKeys.DOWNLOAD_INTERVAL); // TODO(#113) Use NumberPicker instead EditText concurrentEditText = ((EditTextPreference) prefScreen .findPreference(PreferenceKeys.DOWNLOAD_CONCURRENT)) .getEditText(); concurrentEditText.setInputType(InputType.TYPE_CLASS_NUMBER); } @Override public void onResume() { super.onResume(); CharSequence downloadInterval = prefInterval.getEntry(); if (downloadInterval == null) { downloadInterval = getString(R.string.settings_default_download_interval); String[] choices = getResources().getStringArray( R.array.settings_interval_values); for (int i = 0; i < choices.length; i++) { if (downloadInterval.equals(choices)) { downloadInterval = getResources().getStringArray( R.array.settings_interval_choices)[i]; break; } } } prefInterval.setSummary(downloadInterval); prefScreen.getSharedPreferences() .registerOnSharedPreferenceChangeListener(this); } @Override public void onPause() { super.onPause(); prefScreen.getSharedPreferences() .unregisterOnSharedPreferenceChangeListener(this); } @Override public void onSharedPreferenceChanged( SharedPreferences sharedPreferences, String key) { if (key.equals(PreferenceKeys.DOWNLOAD_INTERVAL)) { prefInterval.setSummary(prefInterval.getEntry().toString()); } else if (key.equals(PreferenceKeys.DOWNLOAD_WIFI)) { Intent intent = new PlaylistDownloadServiceIntentProviderBuilder().build(getContext()).getRunIntent(); getContext().startService(intent); } } } public static class StorageFragment extends SettingsFragment implements OnSharedPreferenceChangeListener { private PreferenceScreen prefScreen; private EditTextPreference prefLocation; private EditTextPreference prefQueueCount; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(getContext()).edit(); editor.putString(PreferenceKeys.DOWNLOADED_QUEUE_COUNT, ""); editor.apply(); addPreferencesFromResource(R.xml.preference_storage); prefScreen = getPreferenceScreen(); prefLocation = (EditTextPreference) prefScreen .findPreference(PreferenceKeys.STORAGE_LOCATION); prefQueueCount = (EditTextPreference) prefScreen .findPreference(PreferenceKeys.DOWNLOADED_QUEUE_COUNT); } @Override public void onResume() { super.onResume(); CharSequence storageLocation = prefLocation.getText(); if (storageLocation == null) { storageLocation = VolksempfaengerApplication .getDefaultStorageLocation(); } prefLocation.setSummary(storageLocation); prefScreen.getSharedPreferences() .registerOnSharedPreferenceChangeListener(this); } @Override public void onPause() { super.onPause(); prefScreen.getSharedPreferences() .unregisterOnSharedPreferenceChangeListener(this); } @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if (key.equals(PreferenceKeys.STORAGE_LOCATION)) { prefLocation.setSummary(prefLocation.getText()); } else if (key.equals(PreferenceKeys.DOWNLOADED_QUEUE_COUNT)) { try { //noinspection ResultOfMethodCallIgnored Integer.parseInt(prefQueueCount.getText()); } catch (NumberFormatException e) { String text = "" + getResources().getInteger(R.integer.default_downloaded_queue_count); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString(PreferenceKeys.DOWNLOADED_QUEUE_COUNT, text); editor.apply(); prefQueueCount.setText(text); } } } } public static class AboutFragment extends SettingsFragment { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preference_about); PreferenceScreen prefScreen = getPreferenceScreen(); VolksempfaengerApplication application = (VolksempfaengerApplication) getActivity() .getApplication(); Preference version = prefScreen .findPreference(PreferenceKeys.ABOUT_VERSION); version.setSummary(application.getVersionName()); } } public static class FlattrCallbackProxyActivity extends Activity { @Override public void onStart() { super.onStart(); Uri uri = getIntent().getData(); if (uri != null) { Intent intent = new Intent(this, SettingsActivity.class); intent.putExtra(EXTRA_SHOW_FRAGMENT, FlattrSettingsFragment.class.getName()); Bundle bundle = new Bundle(); bundle.putString("callback", uri.toString()); intent.putExtra(EXTRA_SHOW_FRAGMENT_ARGUMENTS, bundle); startActivity(intent); } } } }
app/src/main/java/net/x4a42/volksempfaenger/ui/SettingsActivity.java
package net.x4a42.volksempfaenger.ui; import java.util.Collection; import java.util.HashSet; import java.util.List; import net.x4a42.volksempfaenger.PreferenceKeys; import net.x4a42.volksempfaenger.R; import net.x4a42.volksempfaenger.VolksempfaengerApplication; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.net.Uri; import android.os.Bundle; import android.preference.EditTextPreference; import android.preference.ListPreference; import android.preference.Preference; import android.preference.PreferenceActivity; import android.preference.PreferenceManager; import android.preference.PreferenceScreen; import android.text.InputType; import android.widget.EditText; public class SettingsActivity extends PreferenceActivity { private static final Collection<String> validFragments = new HashSet<>(); @Override public void onBuildHeaders(List<Header> target) { loadHeadersFromResource(R.xml.preference_headers, target); for (Header header : target) { validFragments.add(header.fragment); } } @Override public void invalidateHeaders() { validFragments.clear(); } @Override protected boolean isValidFragment(String fragmentName) { return validFragments.contains(fragmentName); } public static class DownloadFragment extends SettingsFragment implements OnSharedPreferenceChangeListener { private PreferenceScreen prefScreen; private ListPreference prefInterval; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preference_download); prefScreen = getPreferenceScreen(); prefInterval = (ListPreference) prefScreen .findPreference(PreferenceKeys.DOWNLOAD_INTERVAL); // TODO(#113) Use NumberPicker instead EditText concurrentEditText = ((EditTextPreference) prefScreen .findPreference(PreferenceKeys.DOWNLOAD_CONCURRENT)) .getEditText(); concurrentEditText.setInputType(InputType.TYPE_CLASS_NUMBER); } @Override public void onResume() { super.onResume(); CharSequence downloadInterval = prefInterval.getEntry(); if (downloadInterval == null) { downloadInterval = getString(R.string.settings_default_download_interval); String[] choices = getResources().getStringArray( R.array.settings_interval_values); for (int i = 0; i < choices.length; i++) { if (downloadInterval.equals(choices)) { downloadInterval = getResources().getStringArray( R.array.settings_interval_choices)[i]; break; } } } prefInterval.setSummary(downloadInterval); prefScreen.getSharedPreferences() .registerOnSharedPreferenceChangeListener(this); } @Override public void onPause() { super.onPause(); prefScreen.getSharedPreferences() .unregisterOnSharedPreferenceChangeListener(this); } @Override public void onSharedPreferenceChanged( SharedPreferences sharedPreferences, String key) { if (key.equals(PreferenceKeys.DOWNLOAD_INTERVAL)) { prefInterval.setSummary(prefInterval.getEntry().toString()); } } } public static class StorageFragment extends SettingsFragment implements OnSharedPreferenceChangeListener { private PreferenceScreen prefScreen; private EditTextPreference prefLocation; private EditTextPreference prefQueueCount; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(getContext()).edit(); editor.putString(PreferenceKeys.DOWNLOADED_QUEUE_COUNT, ""); editor.apply(); addPreferencesFromResource(R.xml.preference_storage); prefScreen = getPreferenceScreen(); prefLocation = (EditTextPreference) prefScreen .findPreference(PreferenceKeys.STORAGE_LOCATION); prefQueueCount = (EditTextPreference) prefScreen .findPreference(PreferenceKeys.DOWNLOADED_QUEUE_COUNT); } @Override public void onResume() { super.onResume(); CharSequence storageLocation = prefLocation.getText(); if (storageLocation == null) { storageLocation = VolksempfaengerApplication .getDefaultStorageLocation(); } prefLocation.setSummary(storageLocation); prefScreen.getSharedPreferences() .registerOnSharedPreferenceChangeListener(this); } @Override public void onPause() { super.onPause(); prefScreen.getSharedPreferences() .unregisterOnSharedPreferenceChangeListener(this); } @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if (key.equals(PreferenceKeys.STORAGE_LOCATION)) { prefLocation.setSummary(prefLocation.getText()); } else if (key.equals(PreferenceKeys.DOWNLOADED_QUEUE_COUNT)) { try { //noinspection ResultOfMethodCallIgnored Integer.parseInt(prefQueueCount.getText()); } catch (NumberFormatException e) { String text = "" + getResources().getInteger(R.integer.default_downloaded_queue_count); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString(PreferenceKeys.DOWNLOADED_QUEUE_COUNT, text); editor.apply(); prefQueueCount.setText(text); } } } } public static class AboutFragment extends SettingsFragment { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preference_about); PreferenceScreen prefScreen = getPreferenceScreen(); VolksempfaengerApplication application = (VolksempfaengerApplication) getActivity() .getApplication(); Preference version = prefScreen .findPreference(PreferenceKeys.ABOUT_VERSION); version.setSummary(application.getVersionName()); } } public static class FlattrCallbackProxyActivity extends Activity { @Override public void onStart() { super.onStart(); Uri uri = getIntent().getData(); if (uri != null) { Intent intent = new Intent(this, SettingsActivity.class); intent.putExtra(EXTRA_SHOW_FRAGMENT, FlattrSettingsFragment.class.getName()); Bundle bundle = new Bundle(); bundle.putString("callback", uri.toString()); intent.putExtra(EXTRA_SHOW_FRAGMENT_ARGUMENTS, bundle); startActivity(intent); } } } }
kick off the playlist download service when certain prefs change
app/src/main/java/net/x4a42/volksempfaenger/ui/SettingsActivity.java
kick off the playlist download service when certain prefs change
<ide><path>pp/src/main/java/net/x4a42/volksempfaenger/ui/SettingsActivity.java <ide> import net.x4a42.volksempfaenger.PreferenceKeys; <ide> import net.x4a42.volksempfaenger.R; <ide> import net.x4a42.volksempfaenger.VolksempfaengerApplication; <add>import net.x4a42.volksempfaenger.service.playlistdownload.PlaylistDownloadServiceIntentProvider; <add>import net.x4a42.volksempfaenger.service.playlistdownload.PlaylistDownloadServiceIntentProviderBuilder; <add> <ide> import android.app.Activity; <ide> import android.content.Intent; <ide> import android.content.SharedPreferences; <ide> SharedPreferences sharedPreferences, String key) { <ide> if (key.equals(PreferenceKeys.DOWNLOAD_INTERVAL)) { <ide> prefInterval.setSummary(prefInterval.getEntry().toString()); <add> } <add> else if (key.equals(PreferenceKeys.DOWNLOAD_WIFI)) <add> { <add> Intent intent = new PlaylistDownloadServiceIntentProviderBuilder().build(getContext()).getRunIntent(); <add> getContext().startService(intent); <ide> } <ide> } <ide>
Java
bsd-3-clause
40b2be064a8816bc9ea0f9212a10c964b2736044
0
SoftwareIntrospectionLab/FixCache,SoftwareIntrospectionLab/FixCache
package Cache; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; import java.util.ArrayList; import java.util.Date; import Util.CmdLineParser; import Database.DBOperation; import Database.DatabaseManager; public class Simulator { static final int BLKDEFAULT = 3; static final int PFDEFAULT = 3; static final int CSIZEDEFAULT = 10; static final int PRODEFAULT = 1; public enum FileType{A, M, D, V, C, R} int blocksize; int prefetchsize; int cachesize; int pid; CacheReplacement.Policy cacheRep; Cache cache; DatabaseManager dbManager = DatabaseManager.getInstance(); Connection conn = dbManager.getConnection(); public Simulator(int bsize, int psize, int csize, int projid, CacheReplacement.Policy rep, String start) { blocksize = bsize; prefetchsize = psize; cachesize = csize; this.pid = projid; cacheRep = rep; cache = new Cache(cachesize, new CacheReplacement(rep), start); System.out.println("start to simulate"); } // input: initial commit ID // input: LOC for every file in initial commit ID // input: pre-fetch size // output: fills cache with pre-fetch size number of top-LOC files from initial commit public void preLoad(int prefetchSize, int pid) { // database query: top prefetchsize fileIDs (in terms of LOC) in the first commitID for pid // for each fileId in the list create a cacheItem //sql = "select file_id, LOC from actions where commit_id ="+startCId +" order by LOC DESC"; String sql; Statement stmt; ResultSet r; if (cache.startDate == null) sql = "select min(date) from scmlog"; else sql = "select min(date) from scmlog where repository_id="+pid+"and date >= '" +cache.startDate+"'"; String firstDate = ""; try{ stmt = conn.createStatement(); r = stmt.executeQuery(sql); while(r.next()) { firstDate = r.getDate(1).toString()+" "+r.getTime(1).toString(); } }catch (Exception e) { System.out.println(e); System.exit(0);} sql = "select file_id,content_loc.commit_id from content_loc, scmlog where content_loc.commit_id = scmlog.id and date ='"+ firstDate + "' order by loc DESC"; int fileId = 0; int startCommitId = 0; try { stmt = conn.createStatement(); r = stmt.executeQuery(sql); for (int size = 0; size < prefetchSize; size++) { if (r.next()) { fileId = r.getInt(1); startCommitId = r.getInt(2); cache.add(fileId, startCommitId, CacheItem.CacheReason.Prefetch); } } } catch (Exception e) { System.out.println(e); System.exit(0); } } private static void printUsage() { System.err.println("Example Usage: FixCache -b=10000 -c=500 -f=600 -r=\"LRU\" -p=1"); System.err.println("Example Usage: FixCache --blksize=10000 --csize=500 --pfsize=600 --cacherep=\"LRU\" --pid=1"); System.err.println("-p/--pid option is required"); } //TODO: find the bug introducing file id for a given bug fixding commitId public int getBugIntroCid(int fileId, int commitId, int pId) { // use the fileId and commitId to get a list of changed hunks from the hunk table. // for each changed hunk, get the blamedHunk from the hunk_blame table; get the commit id associated with this blamed hunk // take the maximum (in terms of date?) commit id and return it int bugIntroCId = -1; int hunkId; DatabaseManager dbManager = DatabaseManager.getInstance(); Connection conn = dbManager.getConnection(); Statement stmt; Statement stmt1; Statement stmt2; String sql = "select id from hunks where file_id = "+fileId+" and commit_id ="+commitId;//select the hunk id of fileId for a bug_introducing commitId ResultSet r; ResultSet r1; ResultSet r2; String rev; try{ stmt = conn.createStatement(); r = stmt.executeQuery(sql); while(r.next()) { hunkId = r.getInt(1); stmt1 = conn.createStatement(); sql = "select bug_rev from hunk_blames where hunk_id = "+ hunkId;//for each hunk find the bug introducing rev r1 = stmt1.executeQuery(sql); while(r1.next()) { rev = r1.getString(1); stmt2 = conn.createStatement(); sql = "select id from scmlog where rev = "+"'"+rev+"'" +" and repository_id = "+pId;//find the commit id according to rev and project id r2 = stmt2.executeQuery(sql); while(r2.next()) { if(r2.getInt(1) > bugIntroCId)//bugIntroCId is always the maximum bug introducing commit id { bugIntroCId = r2.getInt(1); } } } } }catch (Exception e) { System.out.println(e); System.exit(0);} return bugIntroCId; } public static void main(String args[]) { // TODO: write unit tests //String startDate, endDate; String start; int hit = 0; int miss = 0; CmdLineParser parser = new CmdLineParser(); CmdLineParser.Option blksz_opt = parser.addIntegerOption('b', "blksize"); CmdLineParser.Option csz_opt = parser.addIntegerOption('c', "csize"); CmdLineParser.Option pfsz_opt = parser.addIntegerOption('f', "pfsize"); CmdLineParser.Option crp_opt = parser.addStringOption('r', "cacherep"); CmdLineParser.Option pid_opt = parser.addIntegerOption('p', "pid"); CmdLineParser.Option dt_opt = parser.addStringOption('t',"datetime"); //CmdLineParser.Option sCId_opt = parser.addIntegerOption('s',"start"); //CmdLineParser.Option eCId_opt = parser.addIntegerOption('e',"end"); try { parser.parse(args); } catch ( CmdLineParser.OptionException e ) { System.err.println(e.getMessage()); printUsage(); System.exit(2); } Integer blksz = (Integer)parser.getOptionValue(blksz_opt, BLKDEFAULT); Integer csz = (Integer)parser.getOptionValue(csz_opt, CSIZEDEFAULT); Integer pfsz = (Integer)parser.getOptionValue(pfsz_opt, PFDEFAULT); String crp_string = (String)parser.getOptionValue(crp_opt, CacheReplacement.REPDEFAULT); Integer pid = (Integer)parser.getOptionValue(pid_opt, PRODEFAULT); String dt = (String)parser.getOptionValue(dt_opt, "2000-01-01 00:00:00"); CacheReplacement.Policy crp; try{ crp = CacheReplacement.Policy.valueOf(crp_string); } catch (IllegalArgumentException e){ System.err.println(e.getMessage()); System.err.println("Must specify a valid cache replacement policy"); crp = CacheReplacement.REPDEFAULT; } //startCId = (Integer)parser.getOptionValue(sCId_opt, STARTIDDEFAULT); //endCId = (Integer)parser.getOptionValue(eCId_opt, Integer.MAX_VALUE); // TODO: make command line input for start and end date start = dt; if (pid == null){ System.err.println("Error: must specify a Project Id"); System.exit(2); } // create a new simulator Simulator sim = new Simulator(blksz, pfsz, csz, pid, crp, start); sim.preLoad(sim.prefetchsize, pid); // if you order scmlog by commitid or by date, the order is different: so order by date String sql = "select id, is_bug_fix from scmlog where repository_id = "+pid+" and date>='"+sim.cache.startDate+"' order by date ASC"; DatabaseManager dbManager = DatabaseManager.getInstance(); Connection conn = dbManager.getConnection(); Statement stmt; Statement stmt1; ResultSet r; ResultSet r1; //select (id, bugfix) from scmlog orderedby date --- need join // main loop int id;//means commit_id in actions boolean isBugFix; int numprefetch = 0; //iterate over the selection int file_id; FileType type; int loc; try { stmt = conn.createStatement(); r = stmt.executeQuery(sql); while (r.next()) { id = r.getInt(1); isBugFix = r.getBoolean(2); //only deal with .java files sql = "select actions.file_id, type ,loc from actions, content_loc, files where actions.file_id = files.id and files.file_name like '%.java' and actions.file_id=content_loc.file_id and actions.commit_id = "+id+" and content_loc.commit_id ="+id+" and files.repository_id="+pid+" order by loc DESC"; // sql = "select actions.file_id, type ,loc from actions, content_loc where actions.file_id=content_loc.file_id and actions.commit_id = "+id+" and content_loc.commit_id ="+id+" order by loc DESC"; stmt1 = conn.createStatement(); r1 = stmt1.executeQuery(sql); // loop through those file ids while (r1.next()) { file_id = r1.getInt(1); type = FileType.valueOf(r1.getString(2)); loc = r1.getInt(3); switch (type) { case V: break; case R: if (numprefetch < sim.prefetchsize) { numprefetch++; sim.cache.add(file_id, id, CacheItem.CacheReason.NewEntity); } break; case C: if (numprefetch < sim.prefetchsize) { numprefetch++; sim.cache.add(file_id, id, CacheItem.CacheReason.NewEntity); } break; case A: if (numprefetch < sim.prefetchsize) { numprefetch++; sim.cache.add(file_id, id, CacheItem.CacheReason.NewEntity); }; break; case D: sim.cache.remove(file_id);// remove from the cache break; case M: // modified if (isBugFix) { int intro_cid = sim.getBugIntroCid(file_id, id, pid); if(sim.cache.cacheTable.containsKey(intro_cid)) { hit++; } else { miss++; } sim.cache.add(file_id, intro_cid, CacheItem.CacheReason.BugEntity); // XXX // should // this // be id // or // intro_cid? ArrayList<Integer> cochanges = CoChange.getCoChangeFileList(file_id, intro_cid, sim.blocksize); sim.cache.add(cochanges, id, CacheItem.CacheReason.CoChange); } else { if (numprefetch < sim.prefetchsize) { numprefetch++; sim.cache.add(file_id, id, CacheItem.CacheReason.ModifiedEntity); } } } } numprefetch = 0; } } catch (Exception e) { System.out.println(e); System.exit(0);} dbManager.close(); System.out.println(hit+"***"+miss); // select (file_id, type) from actions where commit_id == id, ordered_by loc // int file_id; // FileType type; // // // loop through those file ids // switch (type){ // case V: // case R: // case C: // case A: if (numprefetch < sim.prefetchsize) { // numprefetch++; // sim.cache.add(file_id, id, CacheItem.CacheReason.NewEntity); // }; // case D: sim.cache.remove(file_id);// remove from the cache // case M: // if (bugfix){ // int intro_cid = getBugIntroCid(file_id, id); // sim.cache.add(file_id, intro_cid, CacheItem.CacheReason.BugEntity); // XXX should this be id or intro_cid? // ArrayList<Integer> cochanges = CoChange.getCoChangeFileList(file_id, intro_cid, sim.blocksize); // sim.cache.add(cochanges, id, CacheItem.CacheReason.CoChange); // } else { // if (numprefetch < sim.prefetchsize) { // numprefetch++; // sim.cache.add(file_id, id, CacheItem.CacheReason.ModifiedEntity); // } // // } // } // } } }
src/Cache/Simulator.java
package Cache; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; import java.util.ArrayList; import java.util.Date; import Util.CmdLineParser; import Database.DBOperation; import Database.DatabaseManager; public class Simulator { static final int BLKDEFAULT = 3; static final int PFDEFAULT = 3; static final int CSIZEDEFAULT = 10; static final int PRODEFAULT = 1; public enum FileType{A, M, D, V, C, R} int blocksize; int prefetchsize; int cachesize; int pid; CacheReplacement.Policy cacheRep; Cache cache; DatabaseManager dbManager = DatabaseManager.getInstance(); Connection conn = dbManager.getConnection(); public Simulator(int bsize, int psize, int csize, int projid, CacheReplacement.Policy rep, String start) { blocksize = bsize; prefetchsize = psize; cachesize = csize; this.pid = projid; cacheRep = rep; cache = new Cache(cachesize, new CacheReplacement(rep), start); System.out.println("start to simulate"); } // input: initial commit ID // input: LOC for every file in initial commit ID // input: pre-fetch size // output: fills cache with pre-fetch size number of top-LOC files from initial commit public void preLoad(int prefetchSize) { // database query: top prefetchsize fileIDs (in terms of LOC) in the first commitID for pid // for each fileId in the list create a cacheItem //sql = "select file_id, LOC from actions where commit_id ="+startCId +" order by LOC DESC"; String sql; Statement stmt; ResultSet r; if (cache.startDate == null) sql = "select min(date) from scmlog"; else sql = "select min(date) from scmlog where date >= '" +cache.startDate+"'"; String firstDate = ""; try{ stmt = conn.createStatement(); r = stmt.executeQuery(sql); while(r.next()) { firstDate = r.getDate(1).toString()+" "+r.getTime(1).toString(); } }catch (Exception e) { System.out.println(e); System.exit(0);} sql = "select file_id,content_loc.commit_id from content_loc, scmlog where content_loc.commit_id = scmlog.id and date ='"+ firstDate + "' order by loc DESC"; int fileId = 0; int startCommitId = 0; try { stmt = conn.createStatement(); r = stmt.executeQuery(sql); for (int size = 0; size < prefetchSize; size++) { if (r.next()) { fileId = r.getInt(1); startCommitId = r.getInt(2); cache.add(fileId, startCommitId, CacheItem.CacheReason.Prefetch); } } } catch (Exception e) { System.out.println(e); System.exit(0); } } private static void printUsage() { System.err.println("Example Usage: FixCache -b=10000 -c=500 -f=600 -r=\"LRU\" -p=1"); System.err.println("Example Usage: FixCache --blksize=10000 --csize=500 --pfsize=600 --cacherep=\"LRU\" --pid=1"); System.err.println("-p/--pid option is required"); } //TODO: find the bug introducing file id for a given bug fixding commitId public int getBugIntroCid(int fileId, int commitId, int pId) { // use the fileId and commitId to get a list of changed hunks from the hunk table. // for each changed hunk, get the blamedHunk from the hunk_blame table; get the commit id associated with this blamed hunk // take the maximum (in terms of date?) commit id and return it int bugIntroCId = -1; int hunkId; DatabaseManager dbManager = DatabaseManager.getInstance(); Connection conn = dbManager.getConnection(); Statement stmt; Statement stmt1; Statement stmt2; String sql = "select id from hunks where file_id = "+fileId+" and commit_id ="+commitId;//select the hunk id of fileId for a bug_introducing commitId ResultSet r; ResultSet r1; ResultSet r2; String rev; try{ stmt = conn.createStatement(); r = stmt.executeQuery(sql); while(r.next()) { hunkId = r.getInt(1); stmt1 = conn.createStatement(); sql = "select bug_rev from hunk_blames where hunk_id = "+ hunkId;//for each hunk find the bug introducing rev r1 = stmt1.executeQuery(sql); while(r1.next()) { rev = r1.getString(1); stmt2 = conn.createStatement(); sql = "select id from scmlog where rev = "+"'"+rev+"'" +" and repository_id = "+pId;//find the commit id according to rev and project id r2 = stmt2.executeQuery(sql); while(r2.next()) { if(r2.getInt(1) > bugIntroCId)//bugIntroCId is always the maximum bug introducing commit id { bugIntroCId = r2.getInt(1); } } } } }catch (Exception e) { System.out.println(e); System.exit(0);} return bugIntroCId; } public static void main(String args[]) { // TODO: write unit tests //String startDate, endDate; String start; int hit = 0; int miss = 0; CmdLineParser parser = new CmdLineParser(); CmdLineParser.Option blksz_opt = parser.addIntegerOption('b', "blksize"); CmdLineParser.Option csz_opt = parser.addIntegerOption('c', "csize"); CmdLineParser.Option pfsz_opt = parser.addIntegerOption('f', "pfsize"); CmdLineParser.Option crp_opt = parser.addStringOption('r', "cacherep"); CmdLineParser.Option pid_opt = parser.addIntegerOption('p', "pid"); CmdLineParser.Option dt_opt = parser.addStringOption('t',"datetime"); //CmdLineParser.Option sCId_opt = parser.addIntegerOption('s',"start"); //CmdLineParser.Option eCId_opt = parser.addIntegerOption('e',"end"); try { parser.parse(args); } catch ( CmdLineParser.OptionException e ) { System.err.println(e.getMessage()); printUsage(); System.exit(2); } Integer blksz = (Integer)parser.getOptionValue(blksz_opt, BLKDEFAULT); Integer csz = (Integer)parser.getOptionValue(csz_opt, CSIZEDEFAULT); Integer pfsz = (Integer)parser.getOptionValue(pfsz_opt, PFDEFAULT); String crp_string = (String)parser.getOptionValue(crp_opt, CacheReplacement.REPDEFAULT); Integer pid = (Integer)parser.getOptionValue(pid_opt, PRODEFAULT); String dt = (String)parser.getOptionValue(dt_opt, "2000-01-01 00:00:00"); CacheReplacement.Policy crp; try{ crp = CacheReplacement.Policy.valueOf(crp_string); } catch (IllegalArgumentException e){ System.err.println(e.getMessage()); System.err.println("Must specify a valid cache replacement policy"); crp = CacheReplacement.REPDEFAULT; } //startCId = (Integer)parser.getOptionValue(sCId_opt, STARTIDDEFAULT); //endCId = (Integer)parser.getOptionValue(eCId_opt, Integer.MAX_VALUE); // TODO: make command line input for start and end date start = dt; if (pid == null){ System.err.println("Error: must specify a Project Id"); System.exit(2); } // create a new simulator Simulator sim = new Simulator(blksz, pfsz, csz, pid, crp, start); sim.preLoad(sim.prefetchsize); // if you order scmlog by commitid or by date, the order is different: so order by date String sql = "select id, is_bug_fix from scmlog where repository_id = "+pid+" and date>='"+sim.cache.startDate+"' order by date ASC"; DatabaseManager dbManager = DatabaseManager.getInstance(); Connection conn = dbManager.getConnection(); Statement stmt; Statement stmt1; ResultSet r; ResultSet r1; //select (id, bugfix) from scmlog orderedby date --- need join // main loop int id;//means commit_id in actions boolean isBugFix; int numprefetch = 0; //iterate over the selection int file_id; FileType type; int loc; try { stmt = conn.createStatement(); r = stmt.executeQuery(sql); while (r.next()) { id = r.getInt(1); isBugFix = r.getBoolean(2); //only deal with .java files sql = "select actions.file_id, type ,loc from actions, content_loc, files where actions.file_id = files.id and files.file_name like '%.java' and actions.file_id=content_loc.file_id and actions.commit_id = "+id+" and content_loc.commit_id ="+id+" order by loc DESC"; // sql = "select actions.file_id, type ,loc from actions, content_loc where actions.file_id=content_loc.file_id and actions.commit_id = "+id+" and content_loc.commit_id ="+id+" order by loc DESC"; stmt1 = conn.createStatement(); r1 = stmt1.executeQuery(sql); // loop through those file ids while (r1.next()) { file_id = r1.getInt(1); type = FileType.valueOf(r1.getString(2)); loc = r1.getInt(3); switch (type) { case V: break; case R: if (numprefetch < sim.prefetchsize) { numprefetch++; sim.cache.add(file_id, id, CacheItem.CacheReason.NewEntity); } break; case C: if (numprefetch < sim.prefetchsize) { numprefetch++; sim.cache.add(file_id, id, CacheItem.CacheReason.NewEntity); } break; case A: if (numprefetch < sim.prefetchsize) { numprefetch++; sim.cache.add(file_id, id, CacheItem.CacheReason.NewEntity); }; break; case D: sim.cache.remove(file_id);// remove from the cache break; case M: // modified if (isBugFix) { int intro_cid = sim.getBugIntroCid(file_id, id, pid); if(sim.cache.cacheTable.containsKey(intro_cid)) { hit++; } else { miss++; } sim.cache.add(file_id, intro_cid, CacheItem.CacheReason.BugEntity); // XXX // should // this // be id // or // intro_cid? ArrayList<Integer> cochanges = CoChange.getCoChangeFileList(file_id, intro_cid, sim.blocksize); sim.cache.add(cochanges, id, CacheItem.CacheReason.CoChange); } else { if (numprefetch < sim.prefetchsize) { numprefetch++; sim.cache.add(file_id, id, CacheItem.CacheReason.ModifiedEntity); } } } } numprefetch = 0; } } catch (Exception e) { System.out.println(e); System.exit(0);} dbManager.close(); System.out.println(hit+"***"+miss); // select (file_id, type) from actions where commit_id == id, ordered_by loc // int file_id; // FileType type; // // // loop through those file ids // switch (type){ // case V: // case R: // case C: // case A: if (numprefetch < sim.prefetchsize) { // numprefetch++; // sim.cache.add(file_id, id, CacheItem.CacheReason.NewEntity); // }; // case D: sim.cache.remove(file_id);// remove from the cache // case M: // if (bugfix){ // int intro_cid = getBugIntroCid(file_id, id); // sim.cache.add(file_id, intro_cid, CacheItem.CacheReason.BugEntity); // XXX should this be id or intro_cid? // ArrayList<Integer> cochanges = CoChange.getCoChangeFileList(file_id, intro_cid, sim.blocksize); // sim.cache.add(cochanges, id, CacheItem.CacheReason.CoChange); // } else { // if (numprefetch < sim.prefetchsize) { // numprefetch++; // sim.cache.add(file_id, id, CacheItem.CacheReason.ModifiedEntity); // } // // } // } // } } }
unit test using dbunit
src/Cache/Simulator.java
unit test using dbunit
<ide><path>rc/Cache/Simulator.java <ide> // input: LOC for every file in initial commit ID <ide> // input: pre-fetch size <ide> // output: fills cache with pre-fetch size number of top-LOC files from initial commit <del> public void preLoad(int prefetchSize) <add> public void preLoad(int prefetchSize, int pid) <ide> { <ide> // database query: top prefetchsize fileIDs (in terms of LOC) in the first commitID for pid <ide> // for each fileId in the list create a cacheItem <ide> if (cache.startDate == null) <ide> sql = "select min(date) from scmlog"; <ide> else <del> sql = "select min(date) from scmlog where date >= '" +cache.startDate+"'"; <add> sql = "select min(date) from scmlog where repository_id="+pid+"and date >= '" +cache.startDate+"'"; <ide> String firstDate = ""; <ide> try{ <ide> stmt = conn.createStatement(); <ide> <ide> // create a new simulator <ide> Simulator sim = new Simulator(blksz, pfsz, csz, pid, crp, start); <del> sim.preLoad(sim.prefetchsize); <add> sim.preLoad(sim.prefetchsize, pid); <ide> // if you order scmlog by commitid or by date, the order is different: so order by date <ide> String sql = "select id, is_bug_fix from scmlog where repository_id = "+pid+" and date>='"+sim.cache.startDate+"' order by date ASC"; <ide> <ide> id = r.getInt(1); <ide> isBugFix = r.getBoolean(2); <ide> //only deal with .java files <del> sql = "select actions.file_id, type ,loc from actions, content_loc, files where actions.file_id = files.id and files.file_name like '%.java' and actions.file_id=content_loc.file_id and actions.commit_id = "+id+" and content_loc.commit_id ="+id+" order by loc DESC"; <add> sql = "select actions.file_id, type ,loc from actions, content_loc, files where actions.file_id = files.id and files.file_name like '%.java' and actions.file_id=content_loc.file_id and actions.commit_id = "+id+" and content_loc.commit_id ="+id+" and files.repository_id="+pid+" order by loc DESC"; <ide> // sql = "select actions.file_id, type ,loc from actions, content_loc where actions.file_id=content_loc.file_id and actions.commit_id = "+id+" and content_loc.commit_id ="+id+" order by loc DESC"; <ide> stmt1 = conn.createStatement(); <ide> r1 = stmt1.executeQuery(sql);
Java
apache-2.0
4171ffa4ebf8e4db158ae91f5cb91f7f2dbdae38
0
apache/jmeter,etnetera/jmeter,ham1/jmeter,apache/jmeter,ham1/jmeter,ham1/jmeter,ham1/jmeter,etnetera/jmeter,benbenw/jmeter,benbenw/jmeter,apache/jmeter,ham1/jmeter,benbenw/jmeter,etnetera/jmeter,apache/jmeter,apache/jmeter,etnetera/jmeter,etnetera/jmeter,benbenw/jmeter
/* * 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.jorphan.reflect; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.StringTokenizer; import java.util.TreeSet; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import org.apache.jorphan.logging.LoggingManager; import org.apache.jorphan.util.JOrphanUtils; import org.apache.log.Logger; /** * This class finds classes that extend one of a set of parent classes * */ public final class ClassFinder { private static final Logger log = LoggingManager.getLoggerForClass(); private static final String DOT_JAR = ".jar"; // $NON-NLS-1$ private static final String DOT_CLASS = ".class"; // $NON-NLS-1$ private static final int DOT_CLASS_LEN = DOT_CLASS.length(); // static only private ClassFinder() { } /** * Filter updates to TreeSet by only storing classes * that extend one of the parent classes * * */ private static class FilterTreeSet extends TreeSet<String>{ private static final long serialVersionUID = 234L; private final Class<?>[] parents; // parent classes to check private final boolean inner; // are inner classes OK? // hack to reduce the need to load every class in non-GUI mode, which only needs functions // TODO perhaps use BCEL to scan class files instead? private final String contains; // class name should contain this string private final String notContains; // class name should not contain this string private final transient ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); // Potentially expensive; do it once FilterTreeSet(Class<?> []parents, boolean inner, String contains, String notContains){ super(); this.parents=parents; this.inner=inner; this.contains=contains; this.notContains=notContains; } /** * Override the superclass so we only add classnames that * meet the criteria. * * @param s - classname (must be a String) * @return true if it is a new entry * * @see java.util.TreeSet#add(java.lang.Object) */ @Override public boolean add(String s){ if (contains(s)) { return false;// No need to check it again } if (contains!=null && s.indexOf(contains) == -1){ return false; // It does not contain a required string } if (notContains!=null && s.indexOf(notContains) != -1){ return false; // It contains a banned string } if ((s.indexOf("$") == -1) || inner) { // $NON-NLS-1$ if (isChildOf(parents,s, contextClassLoader)) { return super.add(s); } } return false; } } private static class AnnoFilterTreeSet extends TreeSet<String>{ private final boolean inner; // are inner classes OK? private final Class<? extends Annotation>[] annotations; // annotation classes to check private final transient ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); // Potentially expensive; do it once AnnoFilterTreeSet(Class<? extends Annotation> []annotations, boolean inner){ super(); this.annotations = annotations; this.inner=inner; } /** * Override the superclass so we only add classnames that * meet the criteria. * * @param s - classname (must be a String) * @return true if it is a new entry * * @see java.util.TreeSet#add(java.lang.Object) */ @Override public boolean add(String s){ if (contains(s)) { return false;// No need to check it again } if ((s.indexOf("$") == -1) || inner) { // $NON-NLS-1$ if (hasAnnotationOnMethod(annotations,s, contextClassLoader)) { return super.add(s); } } return false; } } /** * Convenience method for * <code>findClassesThatExtend(Class[], boolean)</code> * with the option to include inner classes in the search set to false. * * @return List of Strings containing discovered class names. */ public static List<String> findClassesThatExtend(String[] paths, Class<?>[] superClasses) throws IOException { return findClassesThatExtend(paths, superClasses, false); } // For each directory in the search path, add all the jars found there private static String[] addJarsInPath(String[] paths) { Set<String> fullList = new HashSet<String>(); for (int i = 0; i < paths.length; i++) { final String path = paths[i]; fullList.add(path); // Keep the unexpanded path // TODO - allow directories to end with .jar by removing this check? if (!path.endsWith(DOT_JAR)) { File dir = new File(path); if (dir.exists() && dir.isDirectory()) { String[] jars = dir.list(new FilenameFilter() { public boolean accept(File f, String name) { return name.endsWith(DOT_JAR); } }); for (int x = 0; x < jars.length; x++) { fullList.add(jars[x]); } } } } return fullList.toArray(new String[0]); } /** * Find classes in the provided path(s)/jar(s) that extend the class(es). * @param strPathsOrJars - pathnames or jarfiles to search for classes * @param superClasses - required parent class(es) * @param innerClasses - should we include inner classes? * * @return List containing discovered classes */ public static List<String> findClassesThatExtend(String[] strPathsOrJars, final Class<?>[] superClasses, final boolean innerClasses) throws IOException { return findClassesThatExtend(strPathsOrJars,superClasses,innerClasses,null,null); } /** * Find classes in the provided path(s)/jar(s) that extend the class(es). * @param strPathsOrJars - pathnames or jarfiles to search for classes * @param superClasses - required parent class(es) * @param innerClasses - should we include inner classes? * @param contains - classname should contain this string * @param notContains - classname should not contain this string * * @return List containing discovered classes */ public static List<String> findClassesThatExtend(String[] strPathsOrJars, final Class<?>[] superClasses, final boolean innerClasses, String contains, String notContains) throws IOException { return findClassesThatExtend(strPathsOrJars, superClasses, innerClasses, contains, notContains, false); } /** * Find classes in the provided path(s)/jar(s) that extend the class(es). * @param strPathsOrJars - pathnames or jarfiles to search for classes * @param annotations - required annotations * @param innerClasses - should we include inner classes? * * @return List containing discovered classes */ public static List<String> findAnnotatedClasses(String[] strPathsOrJars, final Class<? extends Annotation>[] annotations, final boolean innerClasses) throws IOException { return findClassesThatExtend(strPathsOrJars, annotations, innerClasses, null, null, true); } /** * Find classes in the provided path(s)/jar(s) that extend the class(es). * @param strPathsOrJars - pathnames or jarfiles to search for classes * @param classNames - required parent class(es) or annotations * @param innerClasses - should we include inner classes? * @param contains - classname should contain this string * @param notContains - classname should not contain this string * @param annotations - true if classnames are annotations * * @return List containing discovered classes */ @SuppressWarnings("unchecked") public static List<String> findClassesThatExtend(String[] strPathsOrJars, final Class<?>[] classNames, final boolean innerClasses, String contains, String notContains, boolean annotations) throws IOException { if (log.isDebugEnabled()) { for (int i = 0; i < classNames.length ; i++){ log.debug("superclass: "+classNames[i].getName()); } } // Find all jars in the search path strPathsOrJars = addJarsInPath(strPathsOrJars); for (int k = 0; k < strPathsOrJars.length; k++) { strPathsOrJars[k] = fixPathEntry(strPathsOrJars[k]); if (log.isDebugEnabled()) { log.debug("strPathsOrJars : " + strPathsOrJars[k]); } } // Now eliminate any classpath entries that do not "match" the search List<String> listPaths = getClasspathMatches(strPathsOrJars); if (log.isDebugEnabled()) { Iterator<String> tIter = listPaths.iterator(); while (tIter.hasNext()) { log.debug("listPaths : " + tIter.next()); } } Set<String> listClasses = annotations ? new AnnoFilterTreeSet((Class<? extends Annotation>[]) classNames, innerClasses) : new FilterTreeSet(classNames, innerClasses, contains, notContains); // first get all the classes findClassesInPaths(listPaths, listClasses); if (log.isDebugEnabled()) { log.debug("listClasses.size()="+listClasses.size()); Iterator<String> tIter = listClasses.iterator(); while (tIter.hasNext()) { log.debug("listClasses : " + tIter.next()); } } // // Now keep only the required classes // Set subClassList = findAllSubclasses(superClasses, listClasses, innerClasses); // if (log.isDebugEnabled()) { // log.debug("subClassList.size()="+subClassList.size()); // Iterator tIter = subClassList.iterator(); // while (tIter.hasNext()) { // log.debug("subClassList : " + tIter.next()); // } // } return new ArrayList<String>(listClasses);//subClassList); } /* * Returns the classpath entries that match the search list of jars and paths */ private static List<String> getClasspathMatches(String[] strPathsOrJars) { final String javaClassPath = System.getProperty("java.class.path"); // $NON-NLS-1$ StringTokenizer stPaths = new StringTokenizer(javaClassPath, System.getProperty("path.separator")); // $NON-NLS-1$ if (log.isDebugEnabled()) { log.debug("Classpath = " + javaClassPath); for (int i = 0; i < strPathsOrJars.length; i++) { log.debug("strPathsOrJars[" + i + "] : " + strPathsOrJars[i]); } } // find all jar files or paths that end with strPathOrJar ArrayList<String> listPaths = new ArrayList<String>(); String strPath = null; while (stPaths.hasMoreTokens()) { strPath = fixPathEntry(stPaths.nextToken()); if (strPathsOrJars == null) { log.debug("Adding: " + strPath); listPaths.add(strPath); } else { boolean found = false; for (int i = 0; i < strPathsOrJars.length; i++) { if (strPath.endsWith(strPathsOrJars[i])) { found = true; log.debug("Adding " + strPath + " found at " + i); listPaths.add(strPath); break;// no need to look further } } if (!found) { log.debug("Did not find: " + strPath); } } } return listPaths; } /** * Fix a path: * - replace "." by current directory * - trim any trailing spaces * - replace \ by / * - replace // by / * - remove all trailing / */ private static String fixPathEntry(String path){ if (path == null ) { return null; } if (path.equals(".")) { // $NON-NLS-1$ return System.getProperty("user.dir"); // $NON-NLS-1$ } path = path.trim().replace('\\', '/'); // $NON-NLS-1$ // $NON-NLS-2$ path = JOrphanUtils.substitute(path, "//", "/"); // $NON-NLS-1$// $NON-NLS-2$ while (path.endsWith("/")) { // $NON-NLS-1$ path = path.substring(0, path.length() - 1); } return path; } /* * NOTUSED * Determine if the class implements the interface. * * @param theClass * the class to check * @param theInterface * the interface to look for * @return boolean true if it implements * * private static boolean classImplementsInterface( Class theClass, Class * theInterface) { HashMap mapInterfaces = new HashMap(); String strKey = * null; // pass in the map by reference since the method is recursive * getAllInterfaces(theClass, mapInterfaces); Iterator iterInterfaces = * mapInterfaces.keySet().iterator(); while (iterInterfaces.hasNext()) { * strKey = (String) iterInterfaces.next(); if (mapInterfaces.get(strKey) == * theInterface) { return true; } } return false; } */ /* * Finds all classes that extend the classes in the listSuperClasses * ArrayList, searching in the listAllClasses ArrayList. * * @param superClasses * the base classes to find subclasses for * @param listAllClasses * the collection of classes to search in * @param innerClasses * indicate whether to include inner classes in the search * @return ArrayList of the subclasses */ // private static Set findAllSubclasses(Class []superClasses, Set listAllClasses, boolean innerClasses) { // Set listSubClasses = new TreeSet(); // for (int i=0; i< superClasses.length; i++) { // findAllSubclassesOneClass(superClasses[i], listAllClasses, listSubClasses, innerClasses); // } // return listSubClasses; // } /* * Finds all classes that extend the class, searching in the listAllClasses * ArrayList. * * @param theClass * the parent class * @param listAllClasses * the collection of classes to search in * @param listSubClasses * the collection of discovered subclasses * @param innerClasses * indicates whether inners classes should be included in the * search */ // private static void findAllSubclassesOneClass(Class theClass, Set listAllClasses, Set listSubClasses, // boolean innerClasses) { // Iterator iterClasses = listAllClasses.iterator(); // while (iterClasses.hasNext()) { // String strClassName = (String) iterClasses.next(); // // only check classes if they are not inner classes // // or we intend to check for inner classes // if ((strClassName.indexOf("$") == -1) || innerClasses) { // $NON-NLS-1$ // // might throw an exception, assume this is ignorable // try { // Class c = Class.forName(strClassName, false, Thread.currentThread().getContextClassLoader()); // // if (!c.isInterface() && !Modifier.isAbstract(c.getModifiers())) { // if(theClass.isAssignableFrom(c)){ // listSubClasses.add(strClassName); // } // } // } catch (Throwable ignored) { // log.debug(ignored.getLocalizedMessage()); // } // } // } // } /** * * @param parentClasses list of classes to check for * @param strClassName name of class to be checked * @param innerClasses should we allow inner classes? * @param contextClassLoader the classloader to use * @return */ private static boolean isChildOf(Class<?> [] parentClasses, String strClassName, ClassLoader contextClassLoader){ // might throw an exception, assume this is ignorable try { Class<?> c = Class.forName(strClassName, false, contextClassLoader); if (!c.isInterface() && !Modifier.isAbstract(c.getModifiers())) { for (int i=0; i< parentClasses.length; i++) { if(parentClasses[i].isAssignableFrom(c)){ return true; } } } } catch (NoClassDefFoundError ignored) { log.debug(ignored.getLocalizedMessage()); } catch (ClassNotFoundException ignored) { log.debug(ignored.getLocalizedMessage()); } return false; } private static boolean hasAnnotationOnMethod(Class<? extends Annotation>[] annotations, String classInQuestion, ClassLoader contextClassLoader ){ try{ Class<?> c = Class.forName(classInQuestion, false, contextClassLoader); for(Method method : c.getMethods()) { for(int i = 0;i<annotations.length;i++) { Class<? extends Annotation> annotation = annotations[i]; if(method.isAnnotationPresent(annotation)) { return true; } } } } catch (NoClassDefFoundError ignored) { log.debug(ignored.getLocalizedMessage()); } catch (ClassNotFoundException ignored) { log.debug(ignored.getLocalizedMessage()); } return false; } /* * Converts a class file from the text stored in a Jar file to a version * that can be used in Class.forName(). * * @param strClassName * the class name from a Jar file * @return String the Java-style dotted version of the name */ private static String fixClassName(String strClassName) { strClassName = strClassName.replace('\\', '.'); // $NON-NLS-1$ // $NON-NLS-2$ strClassName = strClassName.replace('/', '.'); // $NON-NLS-1$ // $NON-NLS-2$ // remove ".class" strClassName = strClassName.substring(0, strClassName.length() - DOT_CLASS_LEN); return strClassName; } private static void findClassesInOnePath(String strPath, Set<String> listClasses) throws IOException { File file = new File(strPath); if (file.isDirectory()) { findClassesInPathsDir(strPath, file, listClasses); } else if (file.exists()) { ZipFile zipFile = null; try { zipFile = new ZipFile(file); Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { String strEntry = entries.nextElement().toString(); if (strEntry.endsWith(DOT_CLASS)) { listClasses.add(fixClassName(strEntry)); } } } catch (IOException e) { log.warn("Can not open the jar " + strPath + " " + e.getLocalizedMessage()); } finally { if(zipFile != null) { try {zipFile.close();} catch (Exception e) {} } } } } private static void findClassesInPaths(List<String> listPaths, Set<String> listClasses) throws IOException { Iterator<String> iterPaths = listPaths.iterator(); while (iterPaths.hasNext()) { findClassesInOnePath(iterPaths.next(), listClasses); } } private static void findClassesInPathsDir(String strPathElement, File dir, Set<String> listClasses) throws IOException { String[] list = dir.list(); for (int i = 0; i < list.length; i++) { File file = new File(dir, list[i]); if (file.isDirectory()) { // Recursive call findClassesInPathsDir(strPathElement, file, listClasses); } else if (list[i].endsWith(DOT_CLASS) && file.exists() && (file.length() != 0)) { final String path = file.getPath(); listClasses.add(path.substring(strPathElement.length() + 1, path.lastIndexOf(".")) // $NON-NLS-1$ .replace(File.separator.charAt(0), '.')); // $NON-NLS-1$ } } } }
src/jorphan/org/apache/jorphan/reflect/ClassFinder.java
/* * 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.jorphan.reflect; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.StringTokenizer; import java.util.TreeSet; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import org.apache.jorphan.logging.LoggingManager; import org.apache.jorphan.util.JOrphanUtils; import org.apache.log.Logger; /** * This class finds classes that extend one of a set of parent classes * */ public final class ClassFinder { private static final Logger log = LoggingManager.getLoggerForClass(); private static final String DOT_JAR = ".jar"; // $NON-NLS-1$ private static final String DOT_CLASS = ".class"; // $NON-NLS-1$ private static final int DOT_CLASS_LEN = DOT_CLASS.length(); // static only private ClassFinder() { } /** * Filter updates to TreeSet by only storing classes * that extend one of the parent classes * * */ private static class FilterTreeSet extends TreeSet<String>{ private static final long serialVersionUID = 234L; private final Class<?>[] parents; // parent classes to check private final boolean inner; // are inner classes OK? // hack to reduce the need to load every class in non-GUI mode, which only needs functions // TODO perhaps use BCEL to scan class files instead? private final String contains; // class name should contain this string private final String notContains; // class name should not contain this string private final transient ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); // Potentially expensive; do it once FilterTreeSet(Class<?> []parents, boolean inner, String contains, String notContains){ super(); this.parents=parents; this.inner=inner; this.contains=contains; this.notContains=notContains; } /** * Override the superclass so we only add classnames that * meet the criteria. * * @param s - classname (must be a String) * @return true if it is a new entry * * @see java.util.TreeSet#add(java.lang.Object) */ @Override public boolean add(String s){ if (contains(s)) { return false;// No need to check it again } if (contains!=null && s.indexOf(contains) == -1){ return false; // It does not contain a required string } if (notContains!=null && s.indexOf(notContains) != -1){ return false; // It contains a banned string } if ((s.indexOf("$") == -1) || inner) { // $NON-NLS-1$ if (isChildOf(parents,s, contextClassLoader)) { return super.add(s); } } return false; } } private static class AnnoFilterTreeSet extends TreeSet<String>{ private final boolean inner; // are inner classes OK? private final Class<? extends Annotation>[] annotations; // annotation classes to check private final transient ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); // Potentially expensive; do it once AnnoFilterTreeSet(Class<? extends Annotation> []annotations, boolean inner){ super(); this.annotations = annotations; this.inner=inner; } /** * Override the superclass so we only add classnames that * meet the criteria. * * @param s - classname (must be a String) * @return true if it is a new entry * * @see java.util.TreeSet#add(java.lang.Object) */ @Override public boolean add(String s){ if (contains(s)) { return false;// No need to check it again } if ((s.indexOf("$") == -1) || inner) { // $NON-NLS-1$ if (hasAnnotationOnMethod(annotations,s, contextClassLoader)) { return super.add(s); } } return false; } } /** * Convenience method for * <code>findClassesThatExtend(Class[], boolean)</code> * with the option to include inner classes in the search set to false. * * @return List of Strings containing discovered class names. */ public static List<String> findClassesThatExtend(String[] paths, Class<?>[] superClasses) throws IOException { return findClassesThatExtend(paths, superClasses, false); } // For each directory in the search path, add all the jars found there private static String[] addJarsInPath(String[] paths) { Set<String> fullList = new HashSet<String>(); for (int i = 0; i < paths.length; i++) { final String path = paths[i]; fullList.add(path); // Keep the unexpanded path // TODO - allow directories to end with .jar by removing this check? if (!path.endsWith(DOT_JAR)) { File dir = new File(path); if (dir.exists() && dir.isDirectory()) { String[] jars = dir.list(new FilenameFilter() { public boolean accept(File f, String name) { return name.endsWith(DOT_JAR); } }); for (int x = 0; x < jars.length; x++) { fullList.add(jars[x]); } } } } return fullList.toArray(new String[0]); } /** * Find classes in the provided path(s)/jar(s) that extend the class(es). * @param strPathsOrJars - pathnames or jarfiles to search for classes * @param superClasses - required parent class(es) * @param innerClasses - should we include inner classes? * * @return List containing discovered classes */ public static List<String> findClassesThatExtend(String[] strPathsOrJars, final Class<?>[] superClasses, final boolean innerClasses) throws IOException { return findClassesThatExtend(strPathsOrJars,superClasses,innerClasses,null,null); } /** * Find classes in the provided path(s)/jar(s) that extend the class(es). * @param strPathsOrJars - pathnames or jarfiles to search for classes * @param superClasses - required parent class(es) * @param innerClasses - should we include inner classes? * @param contains - classname should contain this string * @param notContains - classname should not contain this string * * @return List containing discovered classes */ public static List<String> findClassesThatExtend(String[] strPathsOrJars, final Class<?>[] superClasses, final boolean innerClasses, String contains, String notContains) throws IOException { return findClassesThatExtend(strPathsOrJars, superClasses, innerClasses, contains, notContains, false); } /** * Find classes in the provided path(s)/jar(s) that extend the class(es). * @param strPathsOrJars - pathnames or jarfiles to search for classes * @param annotations - required annotations * @param innerClasses - should we include inner classes? * * @return List containing discovered classes */ public static List<String> findAnnotatedClasses(String[] strPathsOrJars, final Class<? extends Annotation>[] annotations, final boolean innerClasses) throws IOException { return findClassesThatExtend(strPathsOrJars, annotations, innerClasses, null, null, true); } /** * Find classes in the provided path(s)/jar(s) that extend the class(es). * @param strPathsOrJars - pathnames or jarfiles to search for classes * @param classNames - required parent class(es) or annotations * @param innerClasses - should we include inner classes? * @param contains - classname should contain this string * @param notContains - classname should not contain this string * @param annotations - true if classnames are annotations * * @return List containing discovered classes */ @SuppressWarnings("unchecked") public static List<String> findClassesThatExtend(String[] strPathsOrJars, final Class<?>[] classNames, final boolean innerClasses, String contains, String notContains, boolean annotations) throws IOException { if (log.isDebugEnabled()) { for (int i = 0; i < classNames.length ; i++){ log.debug("superclass: "+classNames[i].getName()); } } // Find all jars in the search path strPathsOrJars = addJarsInPath(strPathsOrJars); for (int k = 0; k < strPathsOrJars.length; k++) { strPathsOrJars[k] = fixPathEntry(strPathsOrJars[k]); if (log.isDebugEnabled()) { log.debug("strPathsOrJars : " + strPathsOrJars[k]); } } // Now eliminate any classpath entries that do not "match" the search List<String> listPaths = getClasspathMatches(strPathsOrJars); if (log.isDebugEnabled()) { Iterator<String> tIter = listPaths.iterator(); while (tIter.hasNext()) { log.debug("listPaths : " + tIter.next()); } } Set<String> listClasses = annotations ? new AnnoFilterTreeSet((Class<? extends Annotation>[]) classNames, innerClasses) : new FilterTreeSet(classNames, innerClasses, contains, notContains); // first get all the classes findClassesInPaths(listPaths, listClasses); if (log.isDebugEnabled()) { log.debug("listClasses.size()="+listClasses.size()); Iterator<String> tIter = listClasses.iterator(); while (tIter.hasNext()) { log.debug("listClasses : " + tIter.next()); } } // // Now keep only the required classes // Set subClassList = findAllSubclasses(superClasses, listClasses, innerClasses); // if (log.isDebugEnabled()) { // log.debug("subClassList.size()="+subClassList.size()); // Iterator tIter = subClassList.iterator(); // while (tIter.hasNext()) { // log.debug("subClassList : " + tIter.next()); // } // } return new ArrayList<String>(listClasses);//subClassList); } /* * Returns the classpath entries that match the search list of jars and paths */ private static List<String> getClasspathMatches(String[] strPathsOrJars) { final String javaClassPath = System.getProperty("java.class.path"); // $NON-NLS-1$ StringTokenizer stPaths = new StringTokenizer(javaClassPath, System.getProperty("path.separator")); // $NON-NLS-1$ if (log.isDebugEnabled()) { log.debug("Classpath = " + javaClassPath); for (int i = 0; i < strPathsOrJars.length; i++) { log.debug("strPathsOrJars[" + i + "] : " + strPathsOrJars[i]); } } // find all jar files or paths that end with strPathOrJar ArrayList<String> listPaths = new ArrayList<String>(); String strPath = null; while (stPaths.hasMoreTokens()) { strPath = fixPathEntry(stPaths.nextToken()); if (strPathsOrJars == null) { log.debug("Adding: " + strPath); listPaths.add(strPath); } else { boolean found = false; for (int i = 0; i < strPathsOrJars.length; i++) { if (strPath.endsWith(strPathsOrJars[i])) { found = true; log.debug("Adding " + strPath + " found at " + i); listPaths.add(strPath); break;// no need to look further } } if (!found) { log.debug("Did not find: " + strPath); } } } return listPaths; } /** * Fix a path: * - replace "." by current directory * - trim any trailing spaces * - replace \ by / * - replace // by / * - remove all trailing / */ private static String fixPathEntry(String path){ if (path == null ) { return null; } if (path.equals(".")) { // $NON-NLS-1$ return System.getProperty("user.dir"); // $NON-NLS-1$ } path = path.trim().replace('\\', '/'); // $NON-NLS-1$ // $NON-NLS-2$ path = JOrphanUtils.substitute(path, "//", "/"); // $NON-NLS-1$// $NON-NLS-2$ while (path.endsWith("/")) { // $NON-NLS-1$ path = path.substring(0, path.length() - 1); } return path; } /* * NOTUSED * Determine if the class implements the interface. * * @param theClass * the class to check * @param theInterface * the interface to look for * @return boolean true if it implements * * private static boolean classImplementsInterface( Class theClass, Class * theInterface) { HashMap mapInterfaces = new HashMap(); String strKey = * null; // pass in the map by reference since the method is recursive * getAllInterfaces(theClass, mapInterfaces); Iterator iterInterfaces = * mapInterfaces.keySet().iterator(); while (iterInterfaces.hasNext()) { * strKey = (String) iterInterfaces.next(); if (mapInterfaces.get(strKey) == * theInterface) { return true; } } return false; } */ /* * Finds all classes that extend the classes in the listSuperClasses * ArrayList, searching in the listAllClasses ArrayList. * * @param superClasses * the base classes to find subclasses for * @param listAllClasses * the collection of classes to search in * @param innerClasses * indicate whether to include inner classes in the search * @return ArrayList of the subclasses */ // private static Set findAllSubclasses(Class []superClasses, Set listAllClasses, boolean innerClasses) { // Set listSubClasses = new TreeSet(); // for (int i=0; i< superClasses.length; i++) { // findAllSubclassesOneClass(superClasses[i], listAllClasses, listSubClasses, innerClasses); // } // return listSubClasses; // } /* * Finds all classes that extend the class, searching in the listAllClasses * ArrayList. * * @param theClass * the parent class * @param listAllClasses * the collection of classes to search in * @param listSubClasses * the collection of discovered subclasses * @param innerClasses * indicates whether inners classes should be included in the * search */ // private static void findAllSubclassesOneClass(Class theClass, Set listAllClasses, Set listSubClasses, // boolean innerClasses) { // Iterator iterClasses = listAllClasses.iterator(); // while (iterClasses.hasNext()) { // String strClassName = (String) iterClasses.next(); // // only check classes if they are not inner classes // // or we intend to check for inner classes // if ((strClassName.indexOf("$") == -1) || innerClasses) { // $NON-NLS-1$ // // might throw an exception, assume this is ignorable // try { // Class c = Class.forName(strClassName, false, Thread.currentThread().getContextClassLoader()); // // if (!c.isInterface() && !Modifier.isAbstract(c.getModifiers())) { // if(theClass.isAssignableFrom(c)){ // listSubClasses.add(strClassName); // } // } // } catch (Throwable ignored) { // log.debug(ignored.getLocalizedMessage()); // } // } // } // } /** * * @param parentClasses list of classes to check for * @param strClassName name of class to be checked * @param innerClasses should we allow inner classes? * @param contextClassLoader the classloader to use * @return */ private static boolean isChildOf(Class<?> [] parentClasses, String strClassName, ClassLoader contextClassLoader){ // might throw an exception, assume this is ignorable try { Class<?> c = Class.forName(strClassName, false, contextClassLoader); if (!c.isInterface() && !Modifier.isAbstract(c.getModifiers())) { for (int i=0; i< parentClasses.length; i++) { if(parentClasses[i].isAssignableFrom(c)){ return true; } } } } catch (ClassNotFoundException ignored) { log.debug(ignored.getLocalizedMessage()); } return false; } private static boolean hasAnnotationOnMethod(Class<? extends Annotation>[] annotations, String classInQuestion, ClassLoader contextClassLoader ){ try{ Class<?> c = Class.forName(classInQuestion, false, contextClassLoader); for(Method method : c.getMethods()) { for(int i = 0;i<annotations.length;i++) { Class<? extends Annotation> annotation = annotations[i]; if(method.isAnnotationPresent(annotation)) { return true; } } } } catch (ClassNotFoundException ignored) { log.debug(ignored.getLocalizedMessage()); } return false; } /* * Converts a class file from the text stored in a Jar file to a version * that can be used in Class.forName(). * * @param strClassName * the class name from a Jar file * @return String the Java-style dotted version of the name */ private static String fixClassName(String strClassName) { strClassName = strClassName.replace('\\', '.'); // $NON-NLS-1$ // $NON-NLS-2$ strClassName = strClassName.replace('/', '.'); // $NON-NLS-1$ // $NON-NLS-2$ // remove ".class" strClassName = strClassName.substring(0, strClassName.length() - DOT_CLASS_LEN); return strClassName; } private static void findClassesInOnePath(String strPath, Set<String> listClasses) throws IOException { File file = new File(strPath); if (file.isDirectory()) { findClassesInPathsDir(strPath, file, listClasses); } else if (file.exists()) { ZipFile zipFile = null; try { zipFile = new ZipFile(file); Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { String strEntry = entries.nextElement().toString(); if (strEntry.endsWith(DOT_CLASS)) { listClasses.add(fixClassName(strEntry)); } } } catch (IOException e) { log.warn("Can not open the jar " + strPath + " " + e.getLocalizedMessage()); } finally { if(zipFile != null) { try {zipFile.close();} catch (Exception e) {} } } } } private static void findClassesInPaths(List<String> listPaths, Set<String> listClasses) throws IOException { Iterator<String> iterPaths = listPaths.iterator(); while (iterPaths.hasNext()) { findClassesInOnePath(iterPaths.next(), listClasses); } } private static void findClassesInPathsDir(String strPathElement, File dir, Set<String> listClasses) throws IOException { String[] list = dir.list(); for (int i = 0; i < list.length; i++) { File file = new File(dir, list[i]); if (file.isDirectory()) { // Recursive call findClassesInPathsDir(strPathElement, file, listClasses); } else if (list[i].endsWith(DOT_CLASS) && file.exists() && (file.length() != 0)) { final String path = file.getPath(); listClasses.add(path.substring(strPathElement.length() + 1, path.lastIndexOf(".")) // $NON-NLS-1$ .replace(File.separator.charAt(0), '.')); // $NON-NLS-1$ } } } }
Allow for ClassDefNotFound when checking classes git-svn-id: https://svn.apache.org/repos/asf/jakarta/jmeter/trunk@816934 13f79535-47bb-0310-9956-ffa450edef68 Former-commit-id: fe73bc977ac8aabab34d188b9d2433d717665843
src/jorphan/org/apache/jorphan/reflect/ClassFinder.java
Allow for ClassDefNotFound when checking classes
<ide><path>rc/jorphan/org/apache/jorphan/reflect/ClassFinder.java <ide> } <ide> } <ide> } <add> } catch (NoClassDefFoundError ignored) { <add> log.debug(ignored.getLocalizedMessage()); <ide> } catch (ClassNotFoundException ignored) { <ide> log.debug(ignored.getLocalizedMessage()); <ide> } <ide> } <ide> } <ide> } <add> } catch (NoClassDefFoundError ignored) { <add> log.debug(ignored.getLocalizedMessage()); <ide> } catch (ClassNotFoundException ignored) { <ide> log.debug(ignored.getLocalizedMessage()); <ide> } <ide> String strEntry = entries.nextElement().toString(); <ide> if (strEntry.endsWith(DOT_CLASS)) { <ide> listClasses.add(fixClassName(strEntry)); <del> } <ide> } <add> } <ide> } catch (IOException e) { <ide> log.warn("Can not open the jar " + strPath + " " + e.getLocalizedMessage()); <ide> }
JavaScript
mit
284e965ae1c29e4c3731e8f6fcf3f8fb6647dd1e
0
calhacks/website2,calhacks/website2,calhacks/website2
//Location can be: “Field”, “Uni”, “Other” //Days can be: “fri”, “sat”, “sun” //start can be: [TIME][PERIOD] ie “12:00AM”, “12:45PM” //duration is duration in hours. ie 1 hour would be “1:00” var schedule = [ { title: "Registration Opens!", caption: "Near Gate 5", time: {day: "fri", start: "7:00PM", duration: "3:00"}, location: "", event_type: "Main timeline" }, { title: "Busses Arive", caption: "", time: {day: "fri", start: "7:00PM", duration: "3:00"}, location: "", event_type: "Main timeline" }, { title: "Opening Ceromony", caption: "", time: {day: "fri", start: "10:00PM", duration: "1:00"}, location: "", event_type: "Main timeline" }, { title: "Hacking Starts", caption: "Start forming teams!", time: {day: "fri", start: "11:00PM", duration: "1:00"}, location: "", event_type: "Main timeline" }, { title: "Snacks", caption: "", time: {day: "sat", start: "3:00AM", duration: "1:00"}, location: "", event_type: "Main timeline" }, { title: "Breakfast", caption: "", time: {day: "sat", start: "8:00AM", duration: "1:00"}, location: "", event_type: "Main timeline" }, { title: "Lunch", caption: "", time: {day: "sat", start: "12:00PM", duration: "1:00"}, location: "", event_type: "Main timeline" }, { title: "Snacks", caption: "", time: {day: "sat", start: "3:00PM", duration: "1:00"}, location: "", event_type: "Main timeline" }, { title: "Dinner", caption: "", time: {day: "sat", start: "7:00PM", duration: "1:00"}, location: "", event_type: "Main timeline" }, { title: "Midnight Snack", caption: "", time: {day: "sun", start: "12:00AM", duration: "1:00"}, location: "", event_type: "Main timeline" }, { title: "Snack", caption: "", time: {day: "sun", start: "4:00AM", duration: "1:00"}, location: "", event_type: "Main timeline" }, { title: "Breakfast", caption: "", time: {day: "sun", start: "8:00AM", duration: "1:00"}, location: "", event_type: "Main timeline" }, { title: "Hacking Expo", caption: "", time: {day: "sun", start: "11:00AM", duration: "3:00"}, location: "", event_type: "Main timeline" }, { title: "Lunch", caption: "", time: {day: "sun", start: "12:00PM", duration: "1:00"}, location: "", event_type: "Main timeline" }, { title: "Sponsor Judging", caption: "", time: {day: "sun", start: "2:00PM", duration: "1:00"}, location: "", event_type: "Main timeline" }, { title: "Closing Ceremony", caption: "", time: {day: "sun", start: "2:00PM", duration: "2:00"}, location: "", event_type: "Main timeline" }, { title: "Busses Depart", caption: "", time: {day: "sun", start: "5:00PM", duration: "1:00"}, location: "", event_type: "Main timeline" }, // workshops { title: "Visa Workshop", caption: "", time: {day: "sat", start: "9:15AM", duration: "0:30"}, location: "uni", event_type: "Workshops" }, { title: "Aerospike Workshop", caption: "", time: {day: "sat", start: "10:00AM", duration: "0:30"}, location: "uni", event_type: "Workshops" }, { title: "Here Workshop", caption: "", time: {day: "sat", start: "10:45AM", duration: "0:30"}, location: "uni", event_type: "Workshops" }, { title: "GM Workshop", caption: "", time: {day: "sat", start: "11:30AM", duration: "0:30"}, location: "uni", event_type: "Workshops" }, { title: "Capital One Workshop", caption: "", time: {day: "sat", start: "1:00PM", duration: "0:30"}, location: "uni", event_type: "Workshops" }, { title: "Microsoft Workshop", caption: "", time: {day: "sat", start: "2:00PM", duration: "1:00"}, location: "uni", event_type: "Workshops" }, { title: "Blackrock Workshop", caption: "Full-text search with Apache Solr", time: {day: "sat", start: "4:15PM", duration: "0:30"}, location: "uni", event_type: "Workshops" }, { title: "Gap Workshop", caption: "Agile methodologies", time: {day: "sat", start: "5:00PM", duration: "0:30"}, location: "uni", event_type: "Workshops" }, { title: "Illumio Workshop", caption: "", time: {day: "sat", start: "5:45PM", duration: "0:30"}, location: "uni", event_type: "Workshops" }, { title: "a16z Workshop", caption: "", time: {day: "sat", start: "6:30PM", duration: "0:30"}, location: "uni", event_type: "Workshops" }, { title: "Fireeye Workshop", caption: "", time: {day: "sat", start: "7:15PM", duration: "0:30"}, location: "uni", event_type: "Workshops" }, { title: "Uber Workshop", caption: "", time: {day: "sat", start: "8:00PM", duration: "0:30"}, location: "uni", event_type: "Workshops" }, { title: "Teespring Workshop", caption: "Intro to Canvas and SVG", time: {day: "sat", start: "8:45PM", duration: "0:30"}, location: "uni", event_type: "Workshops" }, // Events { title: "H@B Workshop", caption: "", time: {day: "fri", start: "11:00PM", duration: "2:00"}, location: "woz", event_type: "events" }, { title: "Netflix and Build", caption: "", time: {day: "sat", start: "12:00AM", duration: "3:00"}, location: "sdh", event_type: "events", offset: 1 }, { title: "Morning Meditation", caption: "", time: {day: "sat", start: "8:00AM", duration: "1:00"}, location: "uni", event_type: "events" }, { title: "Hacker Rank Code Sprints", caption: "", time: {day: "sat", start: "11:00AM", duration: "3:00"}, location: "sdh", event_type: "events" }, { title: "Smash Tournement", caption: "", time: {day: "sat", start: "1:00PM", duration: "9:00"}, location: "woz", event_type: "events", offset: 1 }, { title: "Massages", caption: "", time: {day: "sat", start: "2:00PM", duration: "3:00"}, location: "uni", event_type: "events", offset: 2 }, { title: "Faster Hacker Event", caption: "", time: {day: "sat", start: "5:00PM", duration: "1:00"}, location: "uni", event_type: "events", offset: 2 }, { title: "Netflix and Build", caption: "", time: {day: "sat", start: "8:00PM", duration: "1:00"}, location: "uni", event_type: "events", offset: 2 }, { title: "Big C Hike", caption: "", time: {day: "sat", start: "9:00PM", duration: "1:00"}, location: "uni", event_type: "events", offset: 2 }, { title: "Netflix and Build", caption: "", time: {day: "sun", start: "12:00AM", duration: "3:00"}, location: "sdh", event_type: "events" }, ]
assets/live/schedule.js
//Location can be: “Field”, “Uni”, “Other” //Days can be: “fri”, “sat”, “sun” //start can be: [TIME][PERIOD] ie “12:00AM”, “12:45PM” //duration is duration in hours. ie 1 hour would be “1:00” var schedule = [ { title: "Registration Opens + Busess Arrive!", caption: "Near Gate 5", time: {day: "fri", start: "7:00PM", duration: "3:00"}, location: "", event_type: "Main timeline" }, { title: "Opening Ceromony", caption: "", time: {day: "fri", start: "10:00PM", duration: "1:00"}, location: "", event_type: "Main timeline" }, { title: "Hacking Starts", caption: "Start forming teams!", time: {day: "fri", start: "11:00PM", duration: "1:00"}, location: "", event_type: "Main timeline" }, { title: "Snacks", caption: "", time: {day: "sat", start: "3:00AM", duration: "1:00"}, location: "", event_type: "Main timeline" }, { title: "Breakfast", caption: "", time: {day: "sat", start: "8:00AM", duration: "1:00"}, location: "", event_type: "Main timeline" }, { title: "Lunch", caption: "", time: {day: "sat", start: "12:00PM", duration: "1:00"}, location: "", event_type: "Main timeline" }, { title: "Snacks", caption: "", time: {day: "sat", start: "3:00PM", duration: "1:00"}, location: "", event_type: "Main timeline" }, { title: "Dinner", caption: "", time: {day: "sat", start: "7:00PM", duration: "1:00"}, location: "", event_type: "Main timeline" }, { title: "Midnight Snack", caption: "", time: {day: "sun", start: "12:00AM", duration: "1:00"}, location: "", event_type: "Main timeline" }, { title: "Snack", caption: "", time: {day: "sun", start: "4:00AM", duration: "1:00"}, location: "", event_type: "Main timeline" }, { title: "Breakfast", caption: "", time: {day: "sun", start: "8:00AM", duration: "1:00"}, location: "", event_type: "Main timeline" }, { title: "Hacking Expo", caption: "", time: {day: "sun", start: "11:00AM", duration: "3:00"}, location: "", event_type: "Main timeline" }, { title: "Lunch", caption: "", time: {day: "sun", start: "12:00PM", duration: "1:00"}, location: "", event_type: "Main timeline" }, { title: "Sponsor Judging", caption: "", time: {day: "sun", start: "2:00PM", duration: "1:00"}, location: "", event_type: "Main timeline" }, { title: "Closing Ceremony", caption: "", time: {day: "sun", start: "2:00PM", duration: "2:00"}, location: "", event_type: "Main timeline" }, { title: "Busses Depart", caption: "", time: {day: "sun", start: "5:00PM", duration: "1:00"}, location: "", event_type: "Main timeline" }, // workshops { title: "Visa Workshop", caption: "", time: {day: "sat", start: "9:15AM", duration: "0:30"}, location: "uni", event_type: "Workshops" }, { title: "Aerospike Workshop", caption: "", time: {day: "sat", start: "10:00AM", duration: "0:30"}, location: "uni", event_type: "Workshops" }, { title: "Here Workshop", caption: "", time: {day: "sat", start: "10:45AM", duration: "0:30"}, location: "uni", event_type: "Workshops" }, { title: "GM Workshop", caption: "", time: {day: "sat", start: "11:30AM", duration: "0:30"}, location: "uni", event_type: "Workshops" }, { title: "Capital One Workshop", caption: "", time: {day: "sat", start: "1:00PM", duration: "0:30"}, location: "uni", event_type: "Workshops" }, { title: "Microsoft Workshop", caption: "", time: {day: "sat", start: "2:00PM", duration: "1:00"}, location: "uni", event_type: "Workshops" }, { title: "Blackrock Workshop", caption: "Full-text search with Apache Solr", time: {day: "sat", start: "4:15PM", duration: "0:30"}, location: "uni", event_type: "Workshops" }, { title: "Gap Workshop", caption: "Agile methodologies", time: {day: "sat", start: "5:00PM", duration: "0:30"}, location: "uni", event_type: "Workshops" }, { title: "Illumio Workshop", caption: "", time: {day: "sat", start: "5:45PM", duration: "0:30"}, location: "uni", event_type: "Workshops" }, { title: "a16z Workshop", caption: "", time: {day: "sat", start: "6:30PM", duration: "0:30"}, location: "uni", event_type: "Workshops" }, { title: "Fireeye Workshop", caption: "", time: {day: "sat", start: "7:15PM", duration: "0:30"}, location: "uni", event_type: "Workshops" }, { title: "Uber Workshop", caption: "", time: {day: "sat", start: "8:00PM", duration: "0:30"}, location: "uni", event_type: "Workshops" }, { title: "Teespring Workshop", caption: "Intro to Canvas and SVG", time: {day: "sat", start: "8:45PM", duration: "0:30"}, location: "uni", event_type: "Workshops" }, // Events { title: "H@B Workshop", caption: "", time: {day: "fri", start: "11:00PM", duration: "2:00"}, location: "woz", event_type: "events" }, { title: "Netflix and Build", caption: "", time: {day: "sat", start: "12:00AM", duration: "3:00"}, location: "sdh", event_type: "events", offset: 1 }, { title: "Morning Meditation", caption: "", time: {day: "sat", start: "8:00AM", duration: "1:00"}, location: "uni", event_type: "events" }, { title: "Hacker Rank Code Sprints", caption: "", time: {day: "sat", start: "11:00AM", duration: "3:00"}, location: "sdh", event_type: "events" }, { title: "Smash Tournement", caption: "", time: {day: "sat", start: "1:00PM", duration: "9:00"}, location: "woz", event_type: "events", offset: 1 }, { title: "Massages", caption: "", time: {day: "sat", start: "2:00PM", duration: "3:00"}, location: "uni", event_type: "events", offset: 2 }, { title: "Faster Hacker Event", caption: "", time: {day: "sat", start: "5:00PM", duration: "1:00"}, location: "uni", event_type: "events", offset: 2 }, { title: "Netflix and Build", caption: "", time: {day: "sat", start: "8:00PM", duration: "1:00"}, location: "uni", event_type: "events", offset: 2 }, { title: "Big C Hike", caption: "", time: {day: "sat", start: "9:00PM", duration: "1:00"}, location: "uni", event_type: "events", offset: 2 }, { title: "Netflix and Build", caption: "", time: {day: "sun", start: "12:00AM", duration: "3:00"}, location: "sdh", event_type: "events" }, ]
updated live
assets/live/schedule.js
updated live
<ide><path>ssets/live/schedule.js <ide> <ide> var schedule = [ <ide> { <del> title: "Registration Opens + Busess Arrive!", <add> title: "Registration Opens!", <ide> caption: "Near Gate 5", <ide> time: {day: "fri", start: "7:00PM", duration: "3:00"}, <ide> location: "", <ide> event_type: "Main timeline" <ide> }, <ide> <add>{ <add> title: "Busses Arive", <add> caption: "", <add> time: {day: "fri", start: "7:00PM", duration: "3:00"}, <add> location: "", <add> event_type: "Main timeline" <add>}, <ide> <ide> { <ide> title: "Opening Ceromony",
Java
apache-2.0
5fbf03ec11e942662cbfb988e1af3cbf809dc3f2
0
aerogear/aerogear-unifiedpush-java-client,lewis-ing/aerogear-unifiedpush-java-client,yvnicolas/aerogear-unifiedpush-java-client,matzew/aerogear-unifiedpush-java-client
/** * JBoss, Home of Professional Open Source * Copyright Red Hat, Inc., and individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.aerogear.unifiedpush; import static org.jboss.aerogear.unifiedpush.utils.ValidationUtils.isEmpty; import static org.jboss.aerogear.unifiedpush.utils.ValidationUtils.isSuccess; import net.iharder.Base64; import org.codehaus.jackson.map.ObjectMapper; import org.jboss.aerogear.unifiedpush.message.MessageResponseCallback; import org.jboss.aerogear.unifiedpush.message.UnifiedMessage; import java.io.IOException; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.nio.charset.Charset; import java.util.LinkedHashMap; import java.util.Map; import java.util.logging.Logger; public class SenderClient implements JavaSender { private static final Logger logger = Logger.getLogger(SenderClient.class.getName()); private static final Charset UTF_8 = Charset.forName("UTF-8"); private String serverURL; public SenderClient(String rootServerURL) { if (isEmpty(rootServerURL)) { throw new IllegalStateException("server can not be null"); } this.setServerURL(rootServerURL); } public SenderClient() { } /** * Construct the URL fired against the Unified Push Server * * @return a StringBuilder containing the constructed URL */ protected String buildUrl() { if (isEmpty(serverURL)) { throw new IllegalStateException("server can not be null"); } return serverURL + "rest/sender/"; } @Override public void send(UnifiedMessage unifiedMessage, MessageResponseCallback callback) { final Map<String, Object> selectedPayloadObject = prepareMessage(unifiedMessage); int statusCode; // transform to JSONString: String payload = transformJSON(selectedPayloadObject); // fire! submitPayload(buildUrl(), payload, unifiedMessage.getPushApplicationId(), unifiedMessage.getMasterSecret(), callback); } @Override public void send(UnifiedMessage unifiedMessage) { this.send(unifiedMessage, null); } /** * Flatten the given {@link UnifiedMessage} into a {@link Map} * @param {@link UnifiedMessage} to be flatten * @return a {@link Map} */ private Map<String, Object> prepareMessage(UnifiedMessage unifiedMessage) { final Map<String, Object> payloadObject = new LinkedHashMap<String, Object>(); if (!isEmpty(unifiedMessage.getAliases())) { payloadObject.put("alias", unifiedMessage.getAliases()); } if (!isEmpty(unifiedMessage.getCategory())) { payloadObject.put("category", unifiedMessage.getCategory()); } if (!isEmpty(unifiedMessage.getDeviceType())) { payloadObject.put("deviceType", unifiedMessage.getDeviceType()); } if (!isEmpty(unifiedMessage.getVariants())) { payloadObject.put("variants", unifiedMessage.getVariants()); } if (!isEmpty(unifiedMessage.getSimplePushMap())) { payloadObject.put("simple-push", unifiedMessage.getSimplePushMap()); } if (!isEmpty(unifiedMessage.getAttributes())) { payloadObject.put("message", unifiedMessage.getAttributes()); } return payloadObject; } /** * The actual method that does the real send and connection handling * * @param url * @param jsonPayloadObject * @param pushApplicationId * @param masterSecret * @param callback */ private void submitPayload(String url, String jsonPayloadObject, String pushApplicationId, String masterSecret, MessageResponseCallback callback) { String credentials = pushApplicationId + ":" + masterSecret; int statusCode = 0; HttpURLConnection httpURLConnection = null; try { String encoded = Base64.encodeBytes(credentials.getBytes(UTF_8)); // POST the payload to the UnifiedPush Server httpURLConnection = post(url, encoded, jsonPayloadObject); statusCode = httpURLConnection.getResponseCode(); logger.info(String.format("HTTP Response code form UnifiedPush Server: %s", statusCode)); // if we got a redirect, let's extract the 'Location' header from the response // and submit the payload again if (isRedirect(statusCode)) { String redirectURL = httpURLConnection.getHeaderField("Location"); logger.info(String.format("Performing redirect to '%s'", redirectURL)); // execute the 'redirect' this.submitPayload(redirectURL, jsonPayloadObject, pushApplicationId, masterSecret, callback); } else { if(callback != null){ callback.onComplete(statusCode); } } } catch (Exception e) { logger.severe("Send did not succeed: " + e.getMessage()); if(callback != null){ callback.onError(e); } } finally { // tear down if (httpURLConnection != null) { httpURLConnection.disconnect(); } } } /** * Returns HttpURLConnection that 'posts' the given JSON to the given UnifiedPush Server URL. */ private HttpURLConnection post(String url, String encodedCredentials, String jsonPayloadObject) throws IOException { if (url == null || encodedCredentials == null || jsonPayloadObject == null) { throw new IllegalArgumentException("arguments cannot be null"); } byte[] bytes = jsonPayloadObject.getBytes(UTF_8); HttpURLConnection conn = getConnection(url); conn.setDoOutput(true); conn.setUseCaches(false); conn.setFixedLengthStreamingMode(bytes.length); conn.setRequestProperty("Authorization", "Basic " + encodedCredentials); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("Accept", "application/json"); conn.setRequestMethod("POST"); OutputStream out = null; try { out = conn.getOutputStream(); out.write(bytes); } finally { // in case something blows up, while writing // the payload, we wanna close the stream: if (out != null) { out.close(); } } return conn; } /** * Convenience method to open/establish a HttpURLConnection. */ private HttpURLConnection getConnection(String url) throws IOException { HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); return conn; } /** * checks if the given status code is a redirect (301, 302 or 303 response status code) */ private boolean isRedirect(int statusCode) { if (statusCode == HttpURLConnection.HTTP_MOVED_PERM || statusCode == HttpURLConnection.HTTP_MOVED_TEMP || statusCode == HttpURLConnection.HTTP_SEE_OTHER) { return true; } return false; } /** * A simple utility to tranform an {@link Object} into a json {@link String} */ private String transformJSON(Object value) { ObjectMapper om = new ObjectMapper(); String stringPayload = null; try { stringPayload = om.writeValueAsString(value); } catch (Exception e) { throw new IllegalStateException("Failed to encode JSON payload"); } return stringPayload; } public String getServerURL() { return serverURL; } public void setServerURL(String serverURL) { if (!serverURL.endsWith("/")) { serverURL = serverURL.concat("/"); } this.serverURL = serverURL; } }
src/main/java/org/jboss/aerogear/unifiedpush/SenderClient.java
/** * JBoss, Home of Professional Open Source * Copyright Red Hat, Inc., and individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.aerogear.unifiedpush; import static org.jboss.aerogear.unifiedpush.utils.ValidationUtils.isEmpty; import static org.jboss.aerogear.unifiedpush.utils.ValidationUtils.isSuccess; import net.iharder.Base64; import org.codehaus.jackson.map.ObjectMapper; import org.jboss.aerogear.unifiedpush.message.MessageResponseCallback; import org.jboss.aerogear.unifiedpush.message.UnifiedMessage; import java.io.IOException; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.nio.charset.Charset; import java.util.LinkedHashMap; import java.util.Map; import java.util.logging.Logger; public class SenderClient implements JavaSender { private static final Logger logger = Logger.getLogger(SenderClient.class.getName()); private static final Charset UTF_8 = Charset.forName("UTF-8"); private String serverURL; public SenderClient(String rootServerURL) { if (isEmpty(rootServerURL)) { throw new IllegalStateException("server can not be null"); } this.setServerURL(rootServerURL); } public SenderClient() { } /** * Construct the URL fired against the Unified Push Server * * @return a StringBuilder containing the constructed URL */ protected String buildUrl() { if (isEmpty(serverURL)) { throw new IllegalStateException("server can not be null"); } return serverURL + "rest/sender/"; } @Override public void send(UnifiedMessage unifiedMessage, MessageResponseCallback callback) { final Map<String, Object> selectedPayloadObject = prepareMessage(unifiedMessage); int statusCode; // transform to JSONString: String payload = transformJSON(selectedPayloadObject); // fire! submitPayload(buildUrl(), payload, unifiedMessage.getPushApplicationId(), unifiedMessage.getMasterSecret(), callback); } @Override public void send(UnifiedMessage unifiedMessage) { final Map<String, Object> selectedPayloadObject = prepareMessage(unifiedMessage); int statusCode; // transform to JSONString: String payload = transformJSON(selectedPayloadObject); // fire! submitPayload(buildUrl(), payload, unifiedMessage.getPushApplicationId(), unifiedMessage.getMasterSecret(), null); } /** * Flatten the given {@link UnifiedMessage} into a {@link Map} * @param {@link UnifiedMessage} to be flatten * @return a {@link Map} */ private Map<String, Object> prepareMessage(UnifiedMessage unifiedMessage) { final Map<String, Object> payloadObject = new LinkedHashMap<String, Object>(); if (!isEmpty(unifiedMessage.getAliases())) { payloadObject.put("alias", unifiedMessage.getAliases()); } if (!isEmpty(unifiedMessage.getCategory())) { payloadObject.put("category", unifiedMessage.getCategory()); } if (!isEmpty(unifiedMessage.getDeviceType())) { payloadObject.put("deviceType", unifiedMessage.getDeviceType()); } if (!isEmpty(unifiedMessage.getVariants())) { payloadObject.put("variants", unifiedMessage.getVariants()); } if (!isEmpty(unifiedMessage.getSimplePushMap())) { payloadObject.put("simple-push", unifiedMessage.getSimplePushMap()); } if (!isEmpty(unifiedMessage.getAttributes())) { payloadObject.put("message", unifiedMessage.getAttributes()); } return payloadObject; } /** * The actual method that does the real send and connection handling * * @param url * @param jsonPayloadObject * @param pushApplicationId * @param masterSecret * @param callback */ private void submitPayload(String url, String jsonPayloadObject, String pushApplicationId, String masterSecret, MessageResponseCallback callback) { String credentials = pushApplicationId + ":" + masterSecret; int statusCode = 0; HttpURLConnection httpURLConnection = null; try { String encoded = Base64.encodeBytes(credentials.getBytes(UTF_8)); // POST the payload to the UnifiedPush Server httpURLConnection = post(url, encoded, jsonPayloadObject); statusCode = httpURLConnection.getResponseCode(); logger.info(String.format("HTTP Response code form UnifiedPush Server: %s", statusCode)); // if we got a redirect, let's extract the 'Location' header from the response // and submit the payload again if (isRedirect(statusCode)) { String redirectURL = httpURLConnection.getHeaderField("Location"); logger.info(String.format("Performing redirect to '%s'", redirectURL)); // execute the 'redirect' this.submitPayload(redirectURL, jsonPayloadObject, pushApplicationId, masterSecret, callback); } else { if(callback != null){ callback.onComplete(statusCode); } } } catch (Exception e) { logger.severe("Send did not succeed: " + e.getMessage()); if(callback != null){ callback.onError(e); } } finally { // tear down if (httpURLConnection != null) { httpURLConnection.disconnect(); } } } /** * Returns HttpURLConnection that 'posts' the given JSON to the given UnifiedPush Server URL. */ private HttpURLConnection post(String url, String encodedCredentials, String jsonPayloadObject) throws IOException { if (url == null || encodedCredentials == null || jsonPayloadObject == null) { throw new IllegalArgumentException("arguments cannot be null"); } byte[] bytes = jsonPayloadObject.getBytes(UTF_8); HttpURLConnection conn = getConnection(url); conn.setDoOutput(true); conn.setUseCaches(false); conn.setFixedLengthStreamingMode(bytes.length); conn.setRequestProperty("Authorization", "Basic " + encodedCredentials); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("Accept", "application/json"); conn.setRequestMethod("POST"); OutputStream out = null; try { out = conn.getOutputStream(); out.write(bytes); } finally { // in case something blows up, while writing // the payload, we wanna close the stream: if (out != null) { out.close(); } } return conn; } /** * Convenience method to open/establish a HttpURLConnection. */ private HttpURLConnection getConnection(String url) throws IOException { HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); return conn; } /** * checks if the given status code is a redirect (301, 302 or 303 response status code) */ private boolean isRedirect(int statusCode) { if (statusCode == HttpURLConnection.HTTP_MOVED_PERM || statusCode == HttpURLConnection.HTTP_MOVED_TEMP || statusCode == HttpURLConnection.HTTP_SEE_OTHER) { return true; } return false; } /** * A simple utility to tranform an {@link Object} into a json {@link String} */ private String transformJSON(Object value) { ObjectMapper om = new ObjectMapper(); String stringPayload = null; try { stringPayload = om.writeValueAsString(value); } catch (Exception e) { throw new IllegalStateException("Failed to encode JSON payload"); } return stringPayload; } public String getServerURL() { return serverURL; } public void setServerURL(String serverURL) { if (!serverURL.endsWith("/")) { serverURL = serverURL.concat("/"); } this.serverURL = serverURL; } }
remove code duplication
src/main/java/org/jboss/aerogear/unifiedpush/SenderClient.java
remove code duplication
<ide><path>rc/main/java/org/jboss/aerogear/unifiedpush/SenderClient.java <ide> <ide> @Override <ide> public void send(UnifiedMessage unifiedMessage) { <del> final Map<String, Object> selectedPayloadObject = prepareMessage(unifiedMessage); <del> int statusCode; <del> // transform to JSONString: <del> String payload = transformJSON(selectedPayloadObject); <del> // fire! <del> submitPayload(buildUrl(), payload, unifiedMessage.getPushApplicationId(), unifiedMessage.getMasterSecret(), null); <add> this.send(unifiedMessage, null); <ide> } <ide> <ide> /**
Java
mit
1d1a8f6c070940660dea3f539cc256bd67271add
0
illuminoo/yasea,illuminoo/yasea,illuminoo/yasea,illuminoo/yasea,illuminoo/yasea,illuminoo/yasea
/* * Copyright (c) 2017 Illuminoo Projects BV. * This file is part of LISA and subject to the to the terms and conditions defined in file 'LICENSE', * which is part of this source code package. */ package net.ossrs.yasea; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Rect; import android.media.Image; import android.media.MediaCodec; import android.media.MediaCodecInfo; import android.media.MediaCodecList; import android.media.MediaFormat; import android.os.Handler; import android.os.HandlerThread; import android.util.Log; import java.io.IOException; import java.nio.ByteBuffer; /** * Implements an Advanced Video Codec encoder (H264) */ public class SrsAvcEncoder { private static final String TAG = "SrsAvcEncoder"; /** * Default encoder */ public static final String CODEC = "video/avc"; /** * Default color format */ private final static int DEFAULT_COLOR_FORMAT = MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420Planar; /** * Default video width */ public static final int WIDTH = 1920; /** * Default video height */ public static final int HEIGHT = 1080; // private final String x264Preset; private final int outWidth; private final int outHeight; private final int vBitrate; private final int vFps; private final int vGop; public MediaFormat mediaFormat; private final MediaCodec.BufferInfo vebi = new MediaCodec.BufferInfo(); private final String codecName; private MediaCodec vencoder; private final int inWidth; private final int inHeight; private int rotate = 0; private int rotateFlip = 180; private int y_rowstride; private int u_rowstride; private int v_rowstride; private int pixelstride; private final byte[] y_frame; private final byte[] u_frame; private final byte[] v_frame; private final int[] argb_frame; private final Bitmap overlayBitmap; private final Canvas overlay; private HandlerThread videoThread; private MediaCodec.Callback handler; /** * Implements an AVC encoder * * @param inWidth Input width * @param inHeight Input height * @param outWidth Output width * @param outHeight Output height * @param fps Output framerate * @param bitrate Output bitrate * @param handler Codec handler */ public SrsAvcEncoder(int inWidth, int inHeight, int outWidth, int outHeight, int fps, int bitrate, MediaCodec.Callback handler) { this.handler = handler; // Prepare input this.inWidth = inWidth; this.inHeight = inHeight; y_frame = new byte[inWidth * inHeight]; u_frame = new byte[(inWidth * inHeight) / 2 - 1]; v_frame = new byte[(inWidth * inHeight) / 2 - 1]; // Prepare video overlay overlayBitmap = Bitmap.createBitmap(outWidth, outHeight, Bitmap.Config.ARGB_8888); overlay = new Canvas(overlayBitmap); if (outWidth != WIDTH || outHeight != HEIGHT) { overlay.scale(outWidth * 1f / WIDTH, outHeight * 1f / HEIGHT); } // Prepare output this.outWidth = outWidth; this.outHeight = outHeight; argb_frame = new int[outWidth * outHeight]; setEncoderResolution(outWidth, outHeight); vFps = fps; vGop = 2 * fps; vBitrate = bitrate * 1024; // setEncoderFps(vFps); // setEncoderGop(vGop); // setEncoderBitrate(vBitrate); // setEncoderPreset("veryfast"); MediaCodecList list = new MediaCodecList(MediaCodecList.REGULAR_CODECS); mediaFormat = getMediaFormat(outWidth, outHeight, vFps, vGop, vBitrate); codecName = list.findEncoderForFormat(mediaFormat); } /** * Return media format for video streaming * * @param width Width in pixels * @param height Height in pixels * @param fps Frames Per Second * @param gop Group Of Picture in frames * @param bitrate Bitrate in kbps * @return Mediaformat for video streaming */ public static MediaFormat getMediaFormat(int width, int height, int fps, int gop, int bitrate) { MediaFormat mediaFormat = MediaFormat.createVideoFormat(CODEC, width, height); mediaFormat.setInteger(MediaFormat.KEY_COLOR_FORMAT, DEFAULT_COLOR_FORMAT); mediaFormat.setInteger(MediaFormat.KEY_BIT_RATE, bitrate); mediaFormat.setInteger(MediaFormat.KEY_FRAME_RATE, fps); mediaFormat.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, gop / fps); return mediaFormat; } /** * Start encoder * * @return True when successful */ public void start() throws IOException { vencoder = MediaCodec.createByCodecName(codecName); vencoder.configure(mediaFormat, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE); if (handler != null) { videoThread = new HandlerThread("Video"); videoThread.start(); vencoder.setCallback(handler, new Handler(videoThread.getLooper())); } vencoder.start(); } public void stop() { if (videoThread != null) { Log.i(TAG, "Stop background thread"); videoThread.quitSafely(); videoThread = null; } if (vencoder != null) { Log.i(TAG, "Stop encoder"); vencoder.stop(); vencoder.release(); vencoder = null; } } public void setCameraOrientation(int degrees) { if (degrees < 0) { rotate = 360 + degrees; rotateFlip = 180 - degrees; } else { rotate = degrees; rotateFlip = 180 + degrees; } } private void encodeYuvFrame(byte[] yuvFrame) { encodeYuvFrame(yuvFrame, System.nanoTime() / 1000); } private void encodeYuvFrame(byte[] yuvFrame, long pts) { int inBufferIndex = vencoder.dequeueInputBuffer(0); if (inBufferIndex >= 0) { encodeYuvFrame(yuvFrame, inBufferIndex, pts); } } public void encodeYuvFrame(byte[] yuvFrame, int index, long pts) { ByteBuffer bb = vencoder.getInputBuffer(index); bb.put(yuvFrame, 0, yuvFrame.length); vencoder.queueInputBuffer(index, 0, yuvFrame.length, pts, 0); } public boolean getH264Frame(Frame frame) { int outBufferIndex = vencoder.dequeueOutputBuffer(vebi, 0); if (outBufferIndex >= 0) { return getH264Frame(frame, outBufferIndex, vebi); } return false; } public boolean getH264Frame(Frame frame, int index, MediaCodec.BufferInfo info) { ByteBuffer bb = vencoder.getOutputBuffer(index); frame.data = new byte[info.size]; bb.get(frame.data, 0, info.size); frame.keyframe = (info.flags & MediaCodec.BUFFER_FLAG_KEY_FRAME) != 0; frame.timestamp = info.presentationTimeUs; vencoder.releaseOutputBuffer(index, false); return true; } public void onGetRgbaFrame(byte[] data, int width, int height) { encodeYuvFrame(RGBAtoYUV(data, width, height)); } public void onGetYuvNV21Frame(byte[] data, int width, int height, Rect boundingBox) { encodeYuvFrame(NV21toYUV(data, width, height, boundingBox)); } public void onGetYUV420_888Frame(Image image, Rect boundingBox, long pts) { encodeYuvFrame(YUV420_888toYUV(image, boundingBox), pts); } public void onGetArgbFrame(int[] data, int width, int height, Rect boundingBox) { encodeYuvFrame(ARGBtoYUV(data, width, height, boundingBox)); } public byte[] RGBAtoYUV(byte[] data, int width, int height) { switch (DEFAULT_COLOR_FORMAT) { case MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420Planar: return RGBAToI420(data, width, height, true, rotateFlip); case MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420SemiPlanar: return RGBAToNV12(data, width, height, true, rotateFlip); default: throw new IllegalStateException("Unsupported color format!"); } } public byte[] NV21toYUV(byte[] data, int width, int height, Rect boundingBox) { switch (DEFAULT_COLOR_FORMAT) { case MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420Planar: return NV21ToI420(data, width, height, true, rotateFlip, boundingBox.left, boundingBox.top, boundingBox.width(), boundingBox.height()); case MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420SemiPlanar: return NV21ToNV12(data, width, height, true, rotateFlip, boundingBox.left, boundingBox.top, boundingBox.width(), boundingBox.height()); default: throw new IllegalStateException("Unsupported color format!"); } } public byte[] YUV420_888toYUV(Image image, Rect cropArea) { if (image != null) { Image.Plane[] planes = image.getPlanes(); y_rowstride = planes[0].getRowStride(); u_rowstride = planes[1].getRowStride(); v_rowstride = planes[2].getRowStride(); pixelstride = planes[2].getPixelStride(); planes[0].getBuffer().get(y_frame); planes[1].getBuffer().get(u_frame); planes[2].getBuffer().get(v_frame); } return YUV420_888toI420(y_frame, y_rowstride, u_frame, u_rowstride, v_frame, v_rowstride, pixelstride, inWidth, inHeight, false, 0, cropArea.left, cropArea.top, cropArea.width(), cropArea.height()); } public Canvas getOverlay() { overlayBitmap.eraseColor(Color.TRANSPARENT); return overlay; } public void clearOverlay() { ARGBToOverlay(null, outWidth, outHeight, false, 0); } public void updateOverlay() { overlayBitmap.getPixels(argb_frame, 0, outWidth, 0, 0, outWidth, outHeight); ARGBToOverlay(argb_frame, outWidth, outHeight, false, 0); } public byte[] ARGBtoYUV(int[] data, int width, int height, Rect boundingBox) { switch (DEFAULT_COLOR_FORMAT) { case MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420Planar: return ARGBToI420(data, width, height, false, rotate, boundingBox.left, boundingBox.top, boundingBox.width(), boundingBox.height()); case MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420SemiPlanar: return ARGBToNV12(data, width, height, false, rotate, boundingBox.left, boundingBox.top, boundingBox.width(), boundingBox.height()); default: throw new IllegalStateException("Unsupported color format!"); } } private native void setEncoderResolution(int outWidth, int outHeight); private native void setEncoderFps(int fps); private native void setEncoderGop(int gop); private native void setEncoderBitrate(int bitrate); private native void setEncoderPreset(String preset); private native byte[] RGBAToI420(byte[] frame, int width, int height, boolean flip, int rotate); private native byte[] RGBAToNV12(byte[] frame, int width, int height, boolean flip, int rotate); private native byte[] ARGBToI420(int[] frame, int width, int height, boolean flip, int rotate, int crop_x, int crop_y, int crop_width, int crop_height); private native void ARGBToOverlay(int[] frame, int width, int height, boolean flip, int rotate); private native byte[] YUV420_888toI420(byte[] y_frame, int y_stride, byte[] u_frame, int u_stride, byte[] v_frame, int v_stride, int uv_stride, int width, int height, boolean flip, int rotate, int crop_x, int crop_y, int crop_width, int crop_height); private native byte[] ARGBToNV12(int[] frame, int width, int height, boolean flip, int rotate, int crop_x, int crop_y, int crop_width, int crop_height); private native byte[] NV21ToNV12(byte[] frame, int width, int height, boolean flip, int rotate, int crop_x, int crop_y, int crop_width, int crop_height); private native byte[] NV21ToI420(byte[] frame, int width, int height, boolean flip, int rotate, int crop_x, int crop_y, int crop_width, int crop_height); private native int RGBASoftEncode(byte[] frame, int width, int height, boolean flip, int rotate, long pts); private native boolean openSoftEncoder(); private native void closeSoftEncoder(); static { System.loadLibrary("yuv"); System.loadLibrary("enc"); } /** * @return Output format */ public MediaFormat getOutputFormat() { return vencoder.getOutputFormat(); } }
library/src/main/java/net/ossrs/yasea/SrsAvcEncoder.java
/* * Copyright (c) 2017 Illuminoo Projects BV. * This file is part of LISA and subject to the to the terms and conditions defined in file 'LICENSE', * which is part of this source code package. */ package net.ossrs.yasea; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Rect; import android.media.Image; import android.media.MediaCodec; import android.media.MediaCodecInfo; import android.media.MediaCodecList; import android.media.MediaFormat; import android.os.Handler; import android.os.HandlerThread; import android.util.Log; import java.io.IOException; import java.nio.ByteBuffer; /** * Implements an Advanced Video Codec encoder (H264) */ public class SrsAvcEncoder { private static final String TAG = "SrsAvcEncoder"; /** * Default encoder */ public static final String CODEC = "video/avc"; /** * Default video width */ public static final int WIDTH = 1920; /** * Default video height */ public static final int HEIGHT = 1080; // private final String x264Preset; private final int outWidth; private final int outHeight; private final int vBitrate; private final int vFps; private final int vGop; public MediaFormat mediaFormat; private final MediaCodec.BufferInfo vebi = new MediaCodec.BufferInfo(); private final int colorFormat; private final String codecName; private MediaCodec vencoder; private final int inWidth; private final int inHeight; private int rotate = 0; private int rotateFlip = 180; private int y_rowstride; private int u_rowstride; private int v_rowstride; private int pixelstride; private final byte[] y_frame; private final byte[] u_frame; private final byte[] v_frame; private final int[] argb_frame; private final Bitmap overlayBitmap; private final Canvas overlay; private HandlerThread videoThread; private MediaCodec.Callback handler; /** * Implements an AVC encoder * * @param inWidth Input width * @param inHeight Input height * @param outWidth Output width * @param outHeight Output height * @param fps Output framerate * @param bitrate Output bitrate * @param handler Codec handler */ public SrsAvcEncoder(int inWidth, int inHeight, int outWidth, int outHeight, int fps, int bitrate, MediaCodec.Callback handler) { this.handler = handler; // Prepare input this.inWidth = inWidth; this.inHeight = inHeight; y_frame = new byte[inWidth * inHeight]; u_frame = new byte[(inWidth * inHeight) / 2 - 1]; v_frame = new byte[(inWidth * inHeight) / 2 - 1]; // Prepare video overlay overlayBitmap = Bitmap.createBitmap(outWidth, outHeight, Bitmap.Config.ARGB_8888); overlay = new Canvas(overlayBitmap); if (outWidth != WIDTH || outHeight != HEIGHT) { overlay.scale(outWidth * 1f / WIDTH, outHeight * 1f / HEIGHT); } // Prepare output this.outWidth = outWidth; this.outHeight = outHeight; argb_frame = new int[outWidth * outHeight]; setEncoderResolution(outWidth, outHeight); vFps = fps; vGop = 2 * fps; vBitrate = bitrate * 1024; // setEncoderFps(vFps); // setEncoderGop(vGop); // setEncoderBitrate(vBitrate); // setEncoderPreset("veryfast"); MediaCodecList list = new MediaCodecList(MediaCodecList.REGULAR_CODECS); colorFormat = MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420Planar; mediaFormat = MediaFormat.createVideoFormat(CODEC, outWidth, outHeight); mediaFormat.setInteger(MediaFormat.KEY_COLOR_FORMAT, colorFormat); mediaFormat.setInteger(MediaFormat.KEY_BIT_RATE, vBitrate); mediaFormat.setInteger(MediaFormat.KEY_FRAME_RATE, vFps); mediaFormat.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, vGop / vFps); codecName = list.findEncoderForFormat(mediaFormat); } /** * Start encoder * * @return True when successful */ public void start() throws IOException { vencoder = MediaCodec.createByCodecName(codecName); vencoder.configure(mediaFormat, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE); if (handler != null) { videoThread = new HandlerThread("Video"); videoThread.start(); vencoder.setCallback(handler, new Handler(videoThread.getLooper())); } vencoder.start(); } public void stop() { if (videoThread != null) { Log.i(TAG, "Stop background thread"); videoThread.quitSafely(); videoThread = null; } if (vencoder != null) { Log.i(TAG, "Stop encoder"); vencoder.stop(); vencoder.release(); vencoder = null; } } public void setCameraOrientation(int degrees) { if (degrees < 0) { rotate = 360 + degrees; rotateFlip = 180 - degrees; } else { rotate = degrees; rotateFlip = 180 + degrees; } } private void encodeYuvFrame(byte[] yuvFrame) { encodeYuvFrame(yuvFrame, System.nanoTime() / 1000); } private void encodeYuvFrame(byte[] yuvFrame, long pts) { int inBufferIndex = vencoder.dequeueInputBuffer(0); if (inBufferIndex >= 0) { encodeYuvFrame(yuvFrame, inBufferIndex, pts); } } public void encodeYuvFrame(byte[] yuvFrame, int index, long pts) { ByteBuffer bb = vencoder.getInputBuffer(index); bb.put(yuvFrame, 0, yuvFrame.length); vencoder.queueInputBuffer(index, 0, yuvFrame.length, pts, 0); } public boolean getH264Frame(Frame frame) { int outBufferIndex = vencoder.dequeueOutputBuffer(vebi, 0); if (outBufferIndex >= 0) { return getH264Frame(frame, outBufferIndex, vebi); } return false; } public boolean getH264Frame(Frame frame, int index, MediaCodec.BufferInfo info) { ByteBuffer bb = vencoder.getOutputBuffer(index); frame.data = new byte[info.size]; bb.get(frame.data, 0, info.size); frame.keyframe = (info.flags & MediaCodec.BUFFER_FLAG_KEY_FRAME) != 0; frame.timestamp = info.presentationTimeUs; vencoder.releaseOutputBuffer(index, false); return true; } public void onGetRgbaFrame(byte[] data, int width, int height) { encodeYuvFrame(RGBAtoYUV(data, width, height)); } public void onGetYuvNV21Frame(byte[] data, int width, int height, Rect boundingBox) { encodeYuvFrame(NV21toYUV(data, width, height, boundingBox)); } public void onGetYUV420_888Frame(Image image, Rect boundingBox, long pts) { encodeYuvFrame(YUV420_888toYUV(image, boundingBox), pts); } public void onGetArgbFrame(int[] data, int width, int height, Rect boundingBox) { encodeYuvFrame(ARGBtoYUV(data, width, height, boundingBox)); } public byte[] RGBAtoYUV(byte[] data, int width, int height) { switch (colorFormat) { case MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420Planar: return RGBAToI420(data, width, height, true, rotateFlip); case MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420SemiPlanar: return RGBAToNV12(data, width, height, true, rotateFlip); default: throw new IllegalStateException("Unsupported color format!"); } } public byte[] NV21toYUV(byte[] data, int width, int height, Rect boundingBox) { switch (colorFormat) { case MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420Planar: return NV21ToI420(data, width, height, true, rotateFlip, boundingBox.left, boundingBox.top, boundingBox.width(), boundingBox.height()); case MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420SemiPlanar: return NV21ToNV12(data, width, height, true, rotateFlip, boundingBox.left, boundingBox.top, boundingBox.width(), boundingBox.height()); default: throw new IllegalStateException("Unsupported color format!"); } } public byte[] YUV420_888toYUV(Image image, Rect cropArea) { if (image != null) { Image.Plane[] planes = image.getPlanes(); y_rowstride = planes[0].getRowStride(); u_rowstride = planes[1].getRowStride(); v_rowstride = planes[2].getRowStride(); pixelstride = planes[2].getPixelStride(); planes[0].getBuffer().get(y_frame); planes[1].getBuffer().get(u_frame); planes[2].getBuffer().get(v_frame); } return YUV420_888toI420(y_frame, y_rowstride, u_frame, u_rowstride, v_frame, v_rowstride, pixelstride, inWidth, inHeight, false, 0, cropArea.left, cropArea.top, cropArea.width(), cropArea.height()); } public Canvas getOverlay() { overlayBitmap.eraseColor(Color.TRANSPARENT); return overlay; } public void clearOverlay() { ARGBToOverlay(null, outWidth, outHeight, false, 0); } public void updateOverlay() { overlayBitmap.getPixels(argb_frame, 0, outWidth, 0, 0, outWidth, outHeight); ARGBToOverlay(argb_frame, outWidth, outHeight, false, 0); } public byte[] ARGBtoYUV(int[] data, int width, int height, Rect boundingBox) { switch (colorFormat) { case MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420Planar: return ARGBToI420(data, width, height, false, rotate, boundingBox.left, boundingBox.top, boundingBox.width(), boundingBox.height()); case MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420SemiPlanar: return ARGBToNV12(data, width, height, false, rotate, boundingBox.left, boundingBox.top, boundingBox.width(), boundingBox.height()); default: throw new IllegalStateException("Unsupported color format!"); } } private native void setEncoderResolution(int outWidth, int outHeight); private native void setEncoderFps(int fps); private native void setEncoderGop(int gop); private native void setEncoderBitrate(int bitrate); private native void setEncoderPreset(String preset); private native byte[] RGBAToI420(byte[] frame, int width, int height, boolean flip, int rotate); private native byte[] RGBAToNV12(byte[] frame, int width, int height, boolean flip, int rotate); private native byte[] ARGBToI420(int[] frame, int width, int height, boolean flip, int rotate, int crop_x, int crop_y, int crop_width, int crop_height); private native void ARGBToOverlay(int[] frame, int width, int height, boolean flip, int rotate); private native byte[] YUV420_888toI420(byte[] y_frame, int y_stride, byte[] u_frame, int u_stride, byte[] v_frame, int v_stride, int uv_stride, int width, int height, boolean flip, int rotate, int crop_x, int crop_y, int crop_width, int crop_height); private native byte[] ARGBToNV12(int[] frame, int width, int height, boolean flip, int rotate, int crop_x, int crop_y, int crop_width, int crop_height); private native byte[] NV21ToNV12(byte[] frame, int width, int height, boolean flip, int rotate, int crop_x, int crop_y, int crop_width, int crop_height); private native byte[] NV21ToI420(byte[] frame, int width, int height, boolean flip, int rotate, int crop_x, int crop_y, int crop_width, int crop_height); private native int RGBASoftEncode(byte[] frame, int width, int height, boolean flip, int rotate, long pts); private native boolean openSoftEncoder(); private native void closeSoftEncoder(); static { System.loadLibrary("yuv"); System.loadLibrary("enc"); } /** * @return Output format */ public MediaFormat getOutputFormat() { return vencoder.getOutputFormat(); } }
#121 Separate Director - Added settings for additional RTMP stream and local recording - Added support for running as director only
library/src/main/java/net/ossrs/yasea/SrsAvcEncoder.java
#121 Separate Director
<ide><path>ibrary/src/main/java/net/ossrs/yasea/SrsAvcEncoder.java <ide> public static final String CODEC = "video/avc"; <ide> <ide> /** <add> * Default color format <add> */ <add> private final static int DEFAULT_COLOR_FORMAT = MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420Planar; <add> <add> /** <ide> * Default video width <ide> */ <ide> public static final int WIDTH = 1920; <ide> <ide> public MediaFormat mediaFormat; <ide> private final MediaCodec.BufferInfo vebi = new MediaCodec.BufferInfo(); <del> private final int colorFormat; <ide> private final String codecName; <ide> private MediaCodec vencoder; <ide> <ide> private HandlerThread videoThread; <ide> <ide> private MediaCodec.Callback handler; <add> <ide> <ide> /** <ide> * Implements an AVC encoder <ide> // setEncoderPreset("veryfast"); <ide> <ide> MediaCodecList list = new MediaCodecList(MediaCodecList.REGULAR_CODECS); <del> colorFormat = MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420Planar; <del> mediaFormat = MediaFormat.createVideoFormat(CODEC, outWidth, outHeight); <del> mediaFormat.setInteger(MediaFormat.KEY_COLOR_FORMAT, colorFormat); <del> mediaFormat.setInteger(MediaFormat.KEY_BIT_RATE, vBitrate); <del> mediaFormat.setInteger(MediaFormat.KEY_FRAME_RATE, vFps); <del> mediaFormat.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, vGop / vFps); <add> mediaFormat = getMediaFormat(outWidth, outHeight, vFps, vGop, vBitrate); <ide> codecName = list.findEncoderForFormat(mediaFormat); <add> } <add> <add> /** <add> * Return media format for video streaming <add> * <add> * @param width Width in pixels <add> * @param height Height in pixels <add> * @param fps Frames Per Second <add> * @param gop Group Of Picture in frames <add> * @param bitrate Bitrate in kbps <add> * @return Mediaformat for video streaming <add> */ <add> public static MediaFormat getMediaFormat(int width, int height, int fps, int gop, int bitrate) { <add> MediaFormat mediaFormat = MediaFormat.createVideoFormat(CODEC, width, height); <add> mediaFormat.setInteger(MediaFormat.KEY_COLOR_FORMAT, DEFAULT_COLOR_FORMAT); <add> mediaFormat.setInteger(MediaFormat.KEY_BIT_RATE, bitrate); <add> mediaFormat.setInteger(MediaFormat.KEY_FRAME_RATE, fps); <add> mediaFormat.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, gop / fps); <add> return mediaFormat; <ide> } <ide> <ide> /** <ide> } <ide> <ide> public byte[] RGBAtoYUV(byte[] data, int width, int height) { <del> switch (colorFormat) { <add> switch (DEFAULT_COLOR_FORMAT) { <ide> case MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420Planar: <ide> return RGBAToI420(data, width, height, true, rotateFlip); <ide> case MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420SemiPlanar: <ide> } <ide> <ide> public byte[] NV21toYUV(byte[] data, int width, int height, Rect boundingBox) { <del> switch (colorFormat) { <add> switch (DEFAULT_COLOR_FORMAT) { <ide> case MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420Planar: <ide> return NV21ToI420(data, width, height, true, rotateFlip, boundingBox.left, boundingBox.top, boundingBox.width(), boundingBox.height()); <ide> case MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420SemiPlanar: <ide> } <ide> <ide> public byte[] ARGBtoYUV(int[] data, int width, int height, Rect boundingBox) { <del> switch (colorFormat) { <add> switch (DEFAULT_COLOR_FORMAT) { <ide> case MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420Planar: <ide> return ARGBToI420(data, width, height, false, rotate, boundingBox.left, boundingBox.top, boundingBox.width(), boundingBox.height()); <ide> case MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420SemiPlanar:
Java
apache-2.0
be8271aad64669f150920197c8d785fe86b4e862
0
trixon/netbeans-toolbox-idiot,trixon/netbeans-toolbox-idiot
/* * Copyright 2015 Patrik Karlsson. * * 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 se.trixon.toolbox.idiot.task; import it.sauronsoftware.cron4j.Scheduler; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Date; import java.util.ResourceBundle; import java.util.prefs.Preferences; import javax.swing.DefaultListModel; import javax.swing.ImageIcon; import org.apache.commons.io.FileUtils; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.JSONValue; import org.openide.awt.Notification; import org.openide.awt.NotificationDisplayer; import org.openide.util.NbBundle; import org.openide.util.NbPreferences; import org.openide.windows.IOProvider; import org.openide.windows.InputOutput; import org.openide.windows.OutputWriter; import se.trixon.almond.dictionary.Dict; import se.trixon.toolbox.idiot.Options; import se.trixon.toolbox.core.JsonHelper; import se.trixon.toolbox.idiot.IdiotTopComponent; /** * * @author Patrik Karlsson <[email protected]> */ public enum TaskManager { INSTANCE; private static final String KEY_ACTIVE = "active"; private static final String KEY_CRON = "cron"; private static final String KEY_DESCRIPTION = "description"; private static final String KEY_DESTINATION = "destination"; private static final String KEY_ID = "id"; private static final String KEY_NAME = "name"; private static final String KEY_TASKS = "tasks"; private static final String KEY_URL = "url"; private static final String KEY_VERSION = "version"; private static final int sVersion = 1; private final ResourceBundle mBundle; private final InputOutput mInputOutput; private final DefaultListModel mModel = new DefaultListModel<>(); private final Preferences mPreferences; private Scheduler mScheduler = new Scheduler(); private int mVersion; private TaskManager() { mBundle = NbBundle.getBundle(IdiotTopComponent.class); mPreferences = NbPreferences.forModule(this.getClass()); mInputOutput = IOProvider.getDefault().getIO(mBundle.getString("Tool-Name"), false); mInputOutput.select(); } public boolean exists(Task task) { boolean exists = false; for (int i = 0; i < mModel.getSize(); i++) { Task existingTask = (Task) mModel.elementAt(i); if (task.getId() == existingTask.getId()) { exists = true; break; } } return exists; } public DefaultListModel getModel() { return mModel; } public Task getTaskById(long id) { Task foundTask = null; for (int i = 0; i < mModel.getSize(); i++) { Task task = (Task) mModel.elementAt(i); if (task.getId() == id) { foundTask = task; break; } } return foundTask; } public int getVersion() { return mVersion; } public boolean hasActiveTasks() { Task[] tasks = Arrays.copyOf(mModel.toArray(), mModel.toArray().length, Task[].class); for (Task task : tasks) { if (task.isActive()) { return true; } } return false; } public void load() throws IOException { if (Options.INSTANCE.getConfigFile().exists()) { JSONObject jsonObject = (JSONObject) JSONValue.parse(FileUtils.readFileToString(Options.INSTANCE.getConfigFile())); mVersion = JsonHelper.getInt(jsonObject, KEY_VERSION); JSONArray tasksArray = (JSONArray) jsonObject.get(KEY_TASKS); jsonArrayToModel(tasksArray); } } public synchronized void log(String string) { String timeStamp = new SimpleDateFormat("yyyy-MM-dd HH.mm.ss").format(new Date(System.currentTimeMillis())); try (OutputWriter writer = mInputOutput.getOut()) { writer.append(String.format("%s %s\n", timeStamp, string)); } } public void save() throws IOException { JSONObject jsonObject = new JSONObject(); jsonObject.put(KEY_TASKS, modelToJsonArray()); jsonObject.put(KEY_VERSION, sVersion); String jsonString = jsonObject.toJSONString(); FileUtils.writeStringToFile(Options.INSTANCE.getConfigFile(), jsonString); //Backup to preferences. String tag = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); mPreferences.put(tag, jsonString); if (Options.INSTANCE.isActive()) { restart(); } } public void sortModel() { Object[] objects = mModel.toArray(); Arrays.sort(objects); mModel.clear(); for (Object object : objects) { mModel.addElement(object); } } public void start() { Options.INSTANCE.setActive(true); restart(); notifyStatus(); } public void stop() { Options.INSTANCE.setActive(false); mScheduler.stop(); notifyStatus(); } private void jsonArrayToModel(JSONArray array) { for (Object arrayItem : array) { JSONObject object = (JSONObject) arrayItem; Task task = new Task(); task.setId(JsonHelper.getLong(object, KEY_ID)); task.setName((String) object.get(KEY_NAME)); task.setDescription((String) object.get(KEY_DESCRIPTION)); task.setUrl((String) object.get(KEY_URL)); task.setDestination((String) object.get(KEY_DESTINATION)); task.setCron((String) object.get(KEY_CRON)); task.setActive((boolean) object.get(KEY_ACTIVE)); mModel.addElement(task); } sortModel(); } private JSONArray modelToJsonArray() { JSONArray array = new JSONArray(); for (int i = 0; i < mModel.getSize(); i++) { Task task = (Task) mModel.elementAt(i); JSONObject object = new JSONObject(); object.put(KEY_ID, task.getId()); object.put(KEY_NAME, task.getName()); object.put(KEY_DESCRIPTION, task.getDescription()); object.put(KEY_URL, task.getUrl()); object.put(KEY_DESTINATION, task.getDestination()); object.put(KEY_CRON, task.getCron()); object.put(KEY_ACTIVE, task.isActive()); array.add(object); } return array; } private void notifyStatus() { String status = Options.INSTANCE.isActive() ? Dict.STARTED.getString() : Dict.STOPPED.getString(); String message = String.format("%s: %s", Dict.DOWNLOAD_SCHEDULED.getString(), status); Notification notification = NotificationDisplayer.getDefault().notify( mBundle.getString("Tool-Name"), new ImageIcon(), message, null); log(message); } private void restart() { if (mScheduler.isStarted()) { mScheduler.stop(); } mScheduler = new Scheduler(); Task[] tasks = Arrays.copyOf(mModel.toArray(), mModel.toArray().length, Task[].class); for (Task task : tasks) { if (task.isActive()) { mScheduler.schedule(task.getCron(), task); } } mScheduler.start(); } }
idiot/src/se/trixon/toolbox/idiot/task/TaskManager.java
/* * Copyright 2015 Patrik Karlsson. * * 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 se.trixon.toolbox.idiot.task; import it.sauronsoftware.cron4j.Scheduler; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Date; import java.util.ResourceBundle; import java.util.prefs.Preferences; import javax.swing.DefaultListModel; import javax.swing.ImageIcon; import org.apache.commons.io.FileUtils; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.JSONValue; import org.openide.awt.Notification; import org.openide.awt.NotificationDisplayer; import org.openide.util.NbBundle; import org.openide.util.NbPreferences; import org.openide.windows.*; import se.trixon.almond.dialogs.Message; import se.trixon.almond.dictionary.Dict; import se.trixon.toolbox.idiot.Options; import se.trixon.toolbox.core.JsonHelper; import se.trixon.toolbox.idiot.IdiotTopComponent; /** * * @author Patrik Karlsson <[email protected]> */ public enum TaskManager { INSTANCE; private static final String KEY_ACTIVE = "active"; private static final String KEY_CRON = "cron"; private static final String KEY_DESCRIPTION = "description"; private static final String KEY_DESTINATION = "destination"; private static final String KEY_ID = "id"; private static final String KEY_NAME = "name"; private static final String KEY_TASKS = "tasks"; private static final String KEY_URL = "url"; private static final String KEY_VERSION = "version"; private static final int sVersion = 1; private ResourceBundle mBundle; private InputOutput mInputOutput; private final DefaultListModel mModel = new DefaultListModel<>(); private final Preferences mPreferences; private Scheduler mScheduler = new Scheduler(); private int mVersion; private TaskManager() { mBundle = NbBundle.getBundle(IdiotTopComponent.class); mPreferences = NbPreferences.forModule(this.getClass()); mInputOutput = IOProvider.getDefault().getIO(mBundle.getString("Tool-Name"), false); mInputOutput.select(); } public boolean exists(Task task) { boolean exists = false; for (int i = 0; i < mModel.getSize(); i++) { Task existingTask = (Task) mModel.elementAt(i); if (task.getId() == existingTask.getId()) { exists = true; break; } } return exists; } public DefaultListModel getModel() { return mModel; } public Task getTaskById(long id) { Task foundTask = null; for (int i = 0; i < mModel.getSize(); i++) { Task task = (Task) mModel.elementAt(i); if (task.getId() == id) { foundTask = task; break; } } return foundTask; } public int getVersion() { return mVersion; } public boolean hasActiveTasks() { Task[] tasks = Arrays.copyOf(mModel.toArray(), mModel.toArray().length, Task[].class); for (Task task : tasks) { if (task.isActive()) { return true; } } return false; } public void load() throws IOException { if (Options.INSTANCE.getConfigFile().exists()) { JSONObject jsonObject = (JSONObject) JSONValue.parse(FileUtils.readFileToString(Options.INSTANCE.getConfigFile())); mVersion = JsonHelper.getInt(jsonObject, KEY_VERSION); JSONArray tasksArray = (JSONArray) jsonObject.get(KEY_TASKS); jsonArrayToModel(tasksArray); } } public synchronized void log(String string) { String timeStamp = new SimpleDateFormat("yyyy-MM-dd HH.mm.ss").format(new Date(System.currentTimeMillis())); try (OutputWriter writer = mInputOutput.getOut()) { writer.append(String.format("%s %s\n", timeStamp, string)); } } public void save() throws IOException { JSONObject jsonObject = new JSONObject(); jsonObject.put(KEY_TASKS, modelToJsonArray()); jsonObject.put(KEY_VERSION, sVersion); String jsonString = jsonObject.toJSONString(); FileUtils.writeStringToFile(Options.INSTANCE.getConfigFile(), jsonString); //Backup to preferences. String tag = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); mPreferences.put(tag, jsonString); } public void sortModel() { Object[] objects = mModel.toArray(); Arrays.sort(objects); mModel.clear(); for (Object object : objects) { mModel.addElement(object); } } public void start() { Options.INSTANCE.setActive(true); mScheduler = new Scheduler(); Task[] tasks = Arrays.copyOf(mModel.toArray(), mModel.toArray().length, Task[].class); for (Task task : tasks) { if (task.isActive()) { mScheduler.schedule(task.getCron(), task); } } mScheduler.start(); notifyStatus(); } public void stop() { Options.INSTANCE.setActive(false); mScheduler.stop(); notifyStatus(); } private void jsonArrayToModel(JSONArray array) { for (Object arrayItem : array) { JSONObject object = (JSONObject) arrayItem; Task task = new Task(); task.setId(JsonHelper.getLong(object, KEY_ID)); task.setName((String) object.get(KEY_NAME)); task.setDescription((String) object.get(KEY_DESCRIPTION)); task.setUrl((String) object.get(KEY_URL)); task.setDestination((String) object.get(KEY_DESTINATION)); task.setCron((String) object.get(KEY_CRON)); task.setActive((boolean) object.get(KEY_ACTIVE)); mModel.addElement(task); } sortModel(); } private JSONArray modelToJsonArray() { JSONArray array = new JSONArray(); for (int i = 0; i < mModel.getSize(); i++) { Task task = (Task) mModel.elementAt(i); JSONObject object = new JSONObject(); object.put(KEY_ID, task.getId()); object.put(KEY_NAME, task.getName()); object.put(KEY_DESCRIPTION, task.getDescription()); object.put(KEY_URL, task.getUrl()); object.put(KEY_DESTINATION, task.getDestination()); object.put(KEY_CRON, task.getCron()); object.put(KEY_ACTIVE, task.isActive()); array.add(object); } return array; } private void notifyStatus() { String status = Options.INSTANCE.isActive() ? Dict.STARTED.getString() : Dict.STOPPED.getString(); String message = String.format("%s: %s", Dict.DOWNLOAD_SCHEDULED.getString(), status); Notification notification = NotificationDisplayer.getDefault().notify( mBundle.getString("Tool-Name"), new ImageIcon(), message, null); log(message); } }
Start/restart
idiot/src/se/trixon/toolbox/idiot/task/TaskManager.java
Start/restart
<ide><path>diot/src/se/trixon/toolbox/idiot/task/TaskManager.java <ide> import org.openide.awt.NotificationDisplayer; <ide> import org.openide.util.NbBundle; <ide> import org.openide.util.NbPreferences; <del>import org.openide.windows.*; <del>import se.trixon.almond.dialogs.Message; <add>import org.openide.windows.IOProvider; <add>import org.openide.windows.InputOutput; <add>import org.openide.windows.OutputWriter; <ide> import se.trixon.almond.dictionary.Dict; <ide> import se.trixon.toolbox.idiot.Options; <ide> import se.trixon.toolbox.core.JsonHelper; <ide> private static final String KEY_URL = "url"; <ide> private static final String KEY_VERSION = "version"; <ide> private static final int sVersion = 1; <del> private ResourceBundle mBundle; <del> private InputOutput mInputOutput; <add> private final ResourceBundle mBundle; <add> private final InputOutput mInputOutput; <ide> <ide> private final DefaultListModel mModel = new DefaultListModel<>(); <ide> private final Preferences mPreferences; <ide> //Backup to preferences. <ide> String tag = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); <ide> mPreferences.put(tag, jsonString); <add> if (Options.INSTANCE.isActive()) { <add> restart(); <add> } <ide> } <ide> <ide> public void sortModel() { <ide> <ide> public void start() { <ide> Options.INSTANCE.setActive(true); <del> mScheduler = new Scheduler(); <del> Task[] tasks = Arrays.copyOf(mModel.toArray(), mModel.toArray().length, Task[].class); <del> <del> for (Task task : tasks) { <del> if (task.isActive()) { <del> mScheduler.schedule(task.getCron(), task); <del> } <del> } <del> <del> mScheduler.start(); <add> restart(); <ide> notifyStatus(); <ide> } <ide> <ide> <ide> log(message); <ide> } <add> <add> private void restart() { <add> if (mScheduler.isStarted()) { <add> mScheduler.stop(); <add> } <add> <add> mScheduler = new Scheduler(); <add> Task[] tasks = Arrays.copyOf(mModel.toArray(), mModel.toArray().length, Task[].class); <add> <add> for (Task task : tasks) { <add> if (task.isActive()) { <add> mScheduler.schedule(task.getCron(), task); <add> } <add> } <add> <add> mScheduler.start(); <add> } <ide> }
Java
apache-2.0
de78f05707586e56128b7eba8f0a946710c459c1
0
spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework
/* * Copyright 2002-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.test.web.servlet.result; import java.lang.reflect.Method; import org.hamcrest.Matcher; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.ResultMatcher; import org.springframework.util.ClassUtils; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder; import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder.MethodInvocationInfo; import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter; import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; import static org.hamcrest.MatcherAssert.assertThat; import static org.springframework.test.util.AssertionErrors.assertEquals; import static org.springframework.test.util.AssertionErrors.assertTrue; import static org.springframework.test.util.AssertionErrors.fail; /** * Factory for assertions on the selected handler or handler method. * <p>An instance of this class is typically accessed via * {@link MockMvcResultMatchers#handler}. * * <p><strong>Note:</strong> Expectations that assert the controller method * used to process the request work only for requests processed with * {@link RequestMappingHandlerMapping} and {@link RequestMappingHandlerAdapter} * which is used by default with the Spring MVC Java config and XML namespace. * * @author Rossen Stoyanchev * @author Sam Brannen * @since 3.2 */ public class HandlerResultMatchers { /** * Protected constructor. * Use {@link MockMvcResultMatchers#handler()}. */ protected HandlerResultMatchers() { } /** * Assert the type of the handler that processed the request. */ public ResultMatcher handlerType(final Class<?> type) { return new ResultMatcher() { @Override public void match(MvcResult result) throws Exception { Object handler = result.getHandler(); assertTrue("No handler: ", handler != null); Class<?> actual = handler.getClass(); if (HandlerMethod.class.isInstance(handler)) { actual = ((HandlerMethod) handler).getBeanType(); } assertEquals("Handler type", type, ClassUtils.getUserClass(actual)); } }; } /** * Assert the controller method used to process the request. * <p>The expected method is specified through a "mock" controller method * invocation similar to {@link MvcUriComponentsBuilder#fromMethodCall(Object)}. * <p>For example, given this controller: * <pre class="code"> * &#064;RestController * public class SimpleController { * * &#064;RequestMapping("/") * public ResponseEntity<Void> handle() { * return ResponseEntity.ok().build(); * } * } * </pre> * <p>A test that has statically imported {@link MvcUriComponentsBuilder#on} * can be performed as follows: * <pre class="code"> * mockMvc.perform(get("/")) * .andExpect(handler().methodCall(on(SimpleController.class).handle())); * </pre> * * @param obj either the value returned from a "mock" controller invocation * or the "mock" controller itself after an invocation */ public ResultMatcher methodCall(final Object obj) { return new ResultMatcher() { @Override public void match(MvcResult result) throws Exception { if (!MethodInvocationInfo.class.isInstance(obj)) { fail(String.format("The supplied object [%s] is not an instance of %s. " + "Ensure that you invoke the handler method via MvcUriComponentsBuilder.on().", obj, MethodInvocationInfo.class.getName())); } MethodInvocationInfo invocationInfo = (MethodInvocationInfo) obj; Method expected = invocationInfo.getControllerMethod(); Method actual = getHandlerMethod(result).getMethod(); assertEquals("Handler method", expected, actual); } }; } /** * Assert the name of the controller method used to process the request * using the given Hamcrest {@link Matcher}. */ public ResultMatcher methodName(final Matcher<? super String> matcher) { return new ResultMatcher() { @Override public void match(MvcResult result) throws Exception { HandlerMethod handlerMethod = getHandlerMethod(result); assertThat("Handler method", handlerMethod.getMethod().getName(), matcher); } }; } /** * Assert the name of the controller method used to process the request. */ public ResultMatcher methodName(final String name) { return new ResultMatcher() { @Override public void match(MvcResult result) throws Exception { HandlerMethod handlerMethod = getHandlerMethod(result); assertEquals("Handler method", name, handlerMethod.getMethod().getName()); } }; } /** * Assert the controller method used to process the request. */ public ResultMatcher method(final Method method) { return new ResultMatcher() { @Override public void match(MvcResult result) throws Exception { HandlerMethod handlerMethod = getHandlerMethod(result); assertEquals("Handler method", method, handlerMethod.getMethod()); } }; } private static HandlerMethod getHandlerMethod(MvcResult result) { Object handler = result.getHandler(); assertTrue("No handler: ", handler != null); assertTrue("Not a HandlerMethod: " + handler, HandlerMethod.class.isInstance(handler)); return (HandlerMethod) handler; } }
spring-test/src/main/java/org/springframework/test/web/servlet/result/HandlerResultMatchers.java
/* * Copyright 2002-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.test.web.servlet.result; import java.lang.reflect.Method; import org.hamcrest.Matcher; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.ResultMatcher; import org.springframework.util.ClassUtils; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder; import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder.MethodInvocationInfo; import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter; import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; import static org.hamcrest.MatcherAssert.assertThat; import static org.springframework.test.util.AssertionErrors.assertEquals; import static org.springframework.test.util.AssertionErrors.assertTrue; import static org.springframework.test.util.AssertionErrors.fail; /** * Factory for assertions on the selected handler or handler method. * <p>An instance of this class is typically accessed via * {@link MockMvcResultMatchers#handler}. * * <p><strong>Note:</strong> Expectations that assert the controller method * used to process the request work only for requests processed with * {@link RequestMappingHandlerMapping} and {@link RequestMappingHandlerAdapter} * which is used by default with the Spring MVC Java config and XML namespace. * * @author Rossen Stoyanchev * @author Sam Brannen * @since 3.2 */ public class HandlerResultMatchers { /** * Protected constructor. * Use {@link MockMvcResultMatchers#handler()}. */ protected HandlerResultMatchers() { } /** * Assert the type of the handler that processed the request. */ public ResultMatcher handlerType(final Class<?> type) { return new ResultMatcher() { @Override public void match(MvcResult result) throws Exception { Object handler = result.getHandler(); assertTrue("No handler: ", handler != null); Class<?> actual = handler.getClass(); if (HandlerMethod.class.isInstance(handler)) { actual = ((HandlerMethod) handler).getBeanType(); } assertEquals("Handler type", type, ClassUtils.getUserClass(actual)); } }; } /** * Assert the controller method used to process the request. * <p>The expected method is specified through a "mock" controller method * invocation similar to {@link MvcUriComponentsBuilder#fromMethodCall(Object)}. * <p>For example, given this controller: * <pre class="code"> * &#064;RestController * public class SimpleController { * * &#064;RequestMapping("/") * public ResponseEntity<Void> handle() { * return ResponseEntity.ok().build(); * } * } * </pre> * <p>A test that has statically imported {@link MvcUriComponentsBuilder#on} * can be performed as follows: * <pre class="code"> * mockMvc.perform(get("/")) * .andExpect(handler().methodCall(on(SimpleController.class).handle())); * </pre> * * @param obj either the value returned from a "mock" controller invocation * or the "mock" controller itself after an invocation */ public ResultMatcher methodCall(final Object obj) { return new ResultMatcher() { @Override public void match(MvcResult result) throws Exception { if (!MethodInvocationInfo.class.isInstance(obj)) { fail(String.format("The supplied object [%s] is not an instance of %s. " + "Ensure that you invoke the handler method via MvcUriComponentsBuilder.on().", obj, MethodInvocationInfo.class.getName())); } MethodInvocationInfo invocationInfo = (MethodInvocationInfo) obj; Method expected = invocationInfo.getControllerMethod(); Method actual = getHandlerMethod(result).getMethod(); assertEquals("Handler method", expected, actual); } }; } /** * Assert the name of the controller method used to process the request * using the given Hamcrest {@link Matcher}. */ public ResultMatcher methodName(final Matcher<? super String> matcher) { return new ResultMatcher() { @Override public void match(MvcResult result) throws Exception { HandlerMethod handlerMethod = getHandlerMethod(result); assertThat("HandlerMethod", handlerMethod.getMethod().getName(), matcher); } }; } /** * Assert the name of the controller method used to process the request. */ public ResultMatcher methodName(final String name) { return new ResultMatcher() { @Override public void match(MvcResult result) throws Exception { HandlerMethod handlerMethod = getHandlerMethod(result); assertEquals("HandlerMethod", name, handlerMethod.getMethod().getName()); } }; } /** * Assert the controller method used to process the request. */ public ResultMatcher method(final Method method) { return new ResultMatcher() { @Override public void match(MvcResult result) throws Exception { HandlerMethod handlerMethod = getHandlerMethod(result); assertEquals("HandlerMethod", method, handlerMethod.getMethod()); } }; } private static HandlerMethod getHandlerMethod(MvcResult result) { Object handler = result.getHandler(); assertTrue("No handler: ", handler != null); assertTrue("Not a HandlerMethod: " + handler, HandlerMethod.class.isInstance(handler)); return (HandlerMethod) handler; } }
Polishing
spring-test/src/main/java/org/springframework/test/web/servlet/result/HandlerResultMatchers.java
Polishing
<ide><path>pring-test/src/main/java/org/springframework/test/web/servlet/result/HandlerResultMatchers.java <ide> @Override <ide> public void match(MvcResult result) throws Exception { <ide> HandlerMethod handlerMethod = getHandlerMethod(result); <del> assertThat("HandlerMethod", handlerMethod.getMethod().getName(), matcher); <add> assertThat("Handler method", handlerMethod.getMethod().getName(), matcher); <ide> } <ide> }; <ide> } <ide> @Override <ide> public void match(MvcResult result) throws Exception { <ide> HandlerMethod handlerMethod = getHandlerMethod(result); <del> assertEquals("HandlerMethod", name, handlerMethod.getMethod().getName()); <add> assertEquals("Handler method", name, handlerMethod.getMethod().getName()); <ide> } <ide> }; <ide> } <ide> @Override <ide> public void match(MvcResult result) throws Exception { <ide> HandlerMethod handlerMethod = getHandlerMethod(result); <del> assertEquals("HandlerMethod", method, handlerMethod.getMethod()); <add> assertEquals("Handler method", method, handlerMethod.getMethod()); <ide> } <ide> }; <ide> }
Java
mit
0ab65be368dbd91fa1f212fbeeaadee95e611ca8
0
basecrm/basecrm-java
package com.getbase.models; import com.fasterxml.jackson.annotation.JsonView; import com.getbase.serializer.Views; import org.joda.time.DateTime; import java.util.ArrayList; import java.util.List; public class User { protected @JsonView(Views.ReadOnly.class) Long id; protected @JsonView(Views.ReadOnly.class) Boolean confirmed; protected @JsonView(Views.ReadOnly.class) DateTime createdAt; protected @JsonView(Views.ReadOnly.class) String role; protected @JsonView(Views.ReadOnly.class) String status; protected @JsonView(Views.ReadOnly.class) DateTime updatedAt; protected @JsonView(Views.ReadWrite.class) String email; protected @JsonView(Views.ReadWrite.class) String name; protected @JsonView(Views.ReadOnly.class) DateTime deletedAt; protected @JsonView(Views.ReadOnly.class) Long reportsTo; protected @JsonView(Views.ReadOnly.class) String timezone; protected @JsonView(Views.ReadOnly.class) String phoneNumber; protected @JsonView(Views.ReadOnly.class) String teamName; protected @JsonView(Views.ReadOnly.class) Group group; protected @JsonView(Views.ReadOnly.class) List<Role> roles = new ArrayList<Role>(); public User() { } public Long getId() { return this.id; } public Boolean getConfirmed() { return this.confirmed; } public DateTime getCreatedAt() { return this.createdAt; } public String getRole() { return this.role; } public String getStatus() { return this.status; } public DateTime getUpdatedAt() { return this.updatedAt; } public String getEmail() { return this.email; } public String getName() { return this.name; } public void setEmail(String email) { this.email = email; } public void setName(String name) { this.name = name; } public DateTime getDeletedAt() { return this.deletedAt; } public Long getReportsTo() { return this.reportsTo; } public String getTimezone() { return this.timezone; } public String getPhoneNumber() { return phoneNumber; } public String getTeamName() { return teamName; } public Group getGroup() { return this.group; } public List<Role> getRoles() { return this.roles; } @Override public String toString() { return "User{" + "id=" + id + ", confirmed=" + confirmed + ", createdAt=" + createdAt + ", role='" + role + '\'' + ", status='" + status + '\'' + ", updatedAt=" + updatedAt + ", email='" + email + '\'' + ", name='" + name + '\'' + ", deletedAt='" + deletedAt + '\'' + ", reportsTo='" + reportsTo + '\'' + ", timezone='" + timezone + '\'' + ", phoneNumber='" + phoneNumber + '\'' + ", teamName='" + teamName + '\'' + ", group='" + group + '\'' + ", roles=" + roles + "}"; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; User user = (User) o; if (id != null ? !id.equals(user.id) : user.id != null) return false; if (confirmed != null ? !confirmed.equals(user.confirmed) : user.confirmed != null) return false; if (createdAt != null ? !createdAt.equals(user.createdAt) : user.createdAt != null) return false; if (role != null ? !role.equals(user.role) : user.role != null) return false; if (status != null ? !status.equals(user.status) : user.status != null) return false; if (updatedAt != null ? !updatedAt.equals(user.updatedAt) : user.updatedAt != null) return false; if (email != null ? !email.equals(user.email) : user.email != null) return false; if (name != null ? !name.equals(user.name) : user.name != null) return false; if (deletedAt != null ? !deletedAt.equals(user.deletedAt) : user.deletedAt != null) return false; if (reportsTo != null ? !reportsTo.equals(user.reportsTo) : user.reportsTo != null) return false; if (timezone != null ? !timezone.equals(user.timezone) : user.timezone != null) return false; if (phoneNumber != null ? !phoneNumber.equals(user.phoneNumber) : user.phoneNumber != null) return false; if (teamName != null ? !teamName.equals(user.teamName) : user.teamName != null) return false; if (group != null ? !group.equals(user.group) : user.group != null) return false; if (!roles.equals(user.roles)) return false; return true; } @Override public int hashCode() { int result = id != null ? id.hashCode() : 0; result = 31 * result + (id != null ? id.hashCode() : 0); result = 31 * result + (confirmed != null ? confirmed.hashCode() : 0); result = 31 * result + (createdAt != null ? createdAt.hashCode() : 0); result = 31 * result + (role != null ? role.hashCode() : 0); result = 31 * result + (status != null ? status.hashCode() : 0); result = 31 * result + (updatedAt != null ? updatedAt.hashCode() : 0); result = 31 * result + (email != null ? email.hashCode() : 0); result = 31 * result + (name != null ? name.hashCode() : 0); result = 31 * result + (deletedAt != null ? deletedAt.hashCode() : 0); result = 31 * result + (reportsTo != null ? reportsTo.hashCode() : 0); result = 31 * result + (timezone != null ? timezone.hashCode() : 0); result = 31 * result + (phoneNumber != null ? phoneNumber.hashCode() : 0); result = 31 * result + (teamName != null ? teamName.hashCode() : 0); result = 31 * result + (group != null ? group.hashCode() : 0); result = 31 * result + roles.hashCode(); return result; } public static class Group { protected @JsonView(Views.ReadOnly.class) Long id; protected @JsonView(Views.ReadOnly.class) String name; public Group() { } public Long getId() { return this.id; } public String getName() { return this.name; } @Override public String toString() { return "Group{" + "id=" + id + ", name='" + name + '\'' + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Group group = (Group) o; if (id != null ? !id.equals(group.id) : group.id != null) return false; if (name != null ? !name.equals(group.name) : group.name != null) return false; return true; } @Override public int hashCode() { int result = id != null ? id.hashCode() : 0; result = 31 * result + (id != null ? id.hashCode() : 0); result = 31 * result + (name != null ? name.hashCode() : 0); return result; } } public static class Role { protected @JsonView(Views.ReadOnly.class) Long id; protected @JsonView(Views.ReadOnly.class) String name; public Role() { } public Long getId() { return this.id; } public String getName() { return this.name; } @Override public String toString() { return "Role{" + "id=" + id + ", name='" + name + '\'' + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Role role = (Role) o; if (id != null ? !id.equals(role.id) : role.id != null) return false; if (name != null ? !name.equals(role.name) : role.name != null) return false; return true; } @Override public int hashCode() { int result = id != null ? id.hashCode() : 0; result = 31 * result + (id != null ? id.hashCode() : 0); result = 31 * result + (name != null ? name.hashCode() : 0); return result; } } }
src/main/java/com/getbase/models/User.java
package com.getbase.models; import com.fasterxml.jackson.annotation.JsonView; import com.getbase.serializer.Views; import org.joda.time.DateTime; import java.util.ArrayList; import java.util.List; public class User { protected @JsonView(Views.ReadOnly.class) Long id; protected @JsonView(Views.ReadOnly.class) Boolean confirmed; protected @JsonView(Views.ReadOnly.class) DateTime createdAt; protected @JsonView(Views.ReadOnly.class) String role; protected @JsonView(Views.ReadOnly.class) String status; protected @JsonView(Views.ReadOnly.class) DateTime updatedAt; protected @JsonView(Views.ReadWrite.class) String email; protected @JsonView(Views.ReadWrite.class) String name; protected @JsonView(Views.ReadOnly.class) DateTime deletedAt; protected @JsonView(Views.ReadOnly.class) Long reportsTo; protected @JsonView(Views.ReadOnly.class) String timezone; protected @JsonView(Views.ReadOnly.class) String phoneNumber; protected @JsonView(Views.ReadOnly.class) String teamName; protected @JsonView(Views.ReadOnly.class) Group group; protected @JsonView(Views.ReadOnly.class) List<Role> roles = new ArrayList<Role>(); public User() { } public Long getId() { return this.id; } public Boolean getConfirmed() { return this.confirmed; } public DateTime getCreatedAt() { return this.createdAt; } public String getRole() { return this.role; } public String getStatus() { return this.status; } public DateTime getUpdatedAt() { return this.updatedAt; } public String getEmail() { return this.email; } public String getName() { return this.name; } public void setEmail(String email) { this.email = email; } public void setName(String name) { this.name = name; } public DateTime getDeletedAt() { return this.deletedAt; } public Long getReportsTo() { return this.reportsTo; } public String getTimezone() { return this.timezone; } public String getPhoneNumber() { return phoneNumber; } public String getTeamName() { return teamName; } public Group getGroup() { return this.group; } public List<Role> getRoles() { return this.roles; } @Override public String toString() { return "User{" + "id=" + id + ", confirmed=" + confirmed + ", createdAt=" + createdAt + ", role='" + role + '\'' + ", status='" + status + '\'' + ", updatedAt=" + updatedAt + ", email='" + email + '\'' + ", name='" + name + '\'' + ", deletedAt='" + deletedAt + '\'' + ", reportsTo='" + reportsTo + '\'' + ", timezone='" + timezone + '\'' + ", phoneNumber='" + phoneNumber + '\'' + ", teamName='" + teamName + '\'' + ", group='" + group + '\'' + ", roles=" + roles + "}"; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; User user = (User) o; if (id != null ? !id.equals(user.id) : user.id != null) return false; if (confirmed != null ? !confirmed.equals(user.confirmed) : user.confirmed != null) return false; if (createdAt != null ? !createdAt.equals(user.createdAt) : user.createdAt != null) return false; if (role != null ? !role.equals(user.role) : user.role != null) return false; if (status != null ? !status.equals(user.status) : user.status != null) return false; if (updatedAt != null ? !updatedAt.equals(user.updatedAt) : user.updatedAt != null) return false; if (email != null ? !email.equals(user.email) : user.email != null) return false; if (name != null ? !name.equals(user.name) : user.name != null) return false; if (deletedAt != null ? !deletedAt.equals(user.deletedAt) : user.deletedAt != null) return false; if (reportsTo != null ? !reportsTo.equals(user.reportsTo) : user.reportsTo != null) return false; if (timezone != null ? !timezone.equals(user.timezone) : user.timezone != null) return false; if (phoneNumber != null ? !phoneNumber.equals(user.phoneNumber) : user.phoneNumber != null) return false; if (teamName != null ? !teamName.equals(user.teamName) : user.teamName != null) return false; if (group != null ? !group.equals(user.group) : user.group != null) return false; if (!roles.equals(user.roles)) return false; return true; } @Override public int hashCode() { int result = id != null ? id.hashCode() : 0; result = 31 * result + (id != null ? id.hashCode() : 0); result = 31 * result + (confirmed != null ? confirmed.hashCode() : 0); result = 31 * result + (createdAt != null ? createdAt.hashCode() : 0); result = 31 * result + (role != null ? role.hashCode() : 0); result = 31 * result + (status != null ? status.hashCode() : 0); result = 31 * result + (updatedAt != null ? updatedAt.hashCode() : 0); result = 31 * result + (email != null ? email.hashCode() : 0); result = 31 * result + (name != null ? name.hashCode() : 0); result = 31 * result + (deletedAt != null ? deletedAt.hashCode() : 0); result = 31 * result + (reportsTo != null ? reportsTo.hashCode() : 0); result = 31 * result + (timezone != null ? timezone.hashCode() : 0); result = 31 * result + (group != null ? group.hashCode() : 0); result = 31 * result + roles.hashCode(); return result; } public static class Group { protected @JsonView(Views.ReadOnly.class) Long id; protected @JsonView(Views.ReadOnly.class) String name; public Group() { } public Long getId() { return this.id; } public String getName() { return this.name; } @Override public String toString() { return "Group{" + "id=" + id + ", name='" + name + '\'' + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Group group = (Group) o; if (id != null ? !id.equals(group.id) : group.id != null) return false; if (name != null ? !name.equals(group.name) : group.name != null) return false; return true; } @Override public int hashCode() { int result = id != null ? id.hashCode() : 0; result = 31 * result + (id != null ? id.hashCode() : 0); result = 31 * result + (name != null ? name.hashCode() : 0); return result; } } public static class Role { protected @JsonView(Views.ReadOnly.class) Long id; protected @JsonView(Views.ReadOnly.class) String name; public Role() { } public Long getId() { return this.id; } public String getName() { return this.name; } @Override public String toString() { return "Role{" + "id=" + id + ", name='" + name + '\'' + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Role role = (Role) o; if (id != null ? !id.equals(role.id) : role.id != null) return false; if (name != null ? !name.equals(role.name) : role.name != null) return false; return true; } @Override public int hashCode() { int result = id != null ? id.hashCode() : 0; result = 31 * result + (id != null ? id.hashCode() : 0); result = 31 * result + (name != null ? name.hashCode() : 0); return result; } } }
hashcode method fixed.
src/main/java/com/getbase/models/User.java
hashcode method fixed.
<ide><path>rc/main/java/com/getbase/models/User.java <ide> result = 31 * result + (deletedAt != null ? deletedAt.hashCode() : 0); <ide> result = 31 * result + (reportsTo != null ? reportsTo.hashCode() : 0); <ide> result = 31 * result + (timezone != null ? timezone.hashCode() : 0); <add> result = 31 * result + (phoneNumber != null ? phoneNumber.hashCode() : 0); <add> result = 31 * result + (teamName != null ? teamName.hashCode() : 0); <ide> result = 31 * result + (group != null ? group.hashCode() : 0); <ide> result = 31 * result + roles.hashCode(); <ide> return result;
Java
agpl-3.0
f179d48e5731b542327836c3df422eebe5ae697e
0
duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test
7183cbdc-2e61-11e5-9284-b827eb9e62be
hello.java
717e5e68-2e61-11e5-9284-b827eb9e62be
7183cbdc-2e61-11e5-9284-b827eb9e62be
hello.java
7183cbdc-2e61-11e5-9284-b827eb9e62be
<ide><path>ello.java <del>717e5e68-2e61-11e5-9284-b827eb9e62be <add>7183cbdc-2e61-11e5-9284-b827eb9e62be
JavaScript
mit
62b3fa10c04130991250448a68da5fb9f3cf167d
0
markelog/dbuilder
require('babel-polyfill'); import { resolve } from 'path'; import { stringify } from 'querystring'; import { EventEmitter } from 'events'; import pump from 'pump'; import Docker from 'dockerode'; import build from 'dockerode-build'; export default class DBuilder { /** * Promise constructor, for test stubbing * @static * @type {Function} */ static Promise = Promise; /** * dockerode-build function, for test stubbing * @static * @type {Function} */ static build = build; /** * pump function, for test stubbing * @static * @type {Function} */ static pump = pump; /** * @constructor * @param {Object} opts * @param {String} opts.name - name of container, which will be used for build and run * @param {Number} opts.port - host port * @param {Number} opts.exposed - exposed container port, should correlate with "EXPOSED" * @param {Object} opts.envs - environment vars which will be used when starting container * @param {string} opts.image - image path */ constructor(opts = {}) { /** * Name of the container * @type {String} */ this.name = opts.name; /** * Host port * @type {String} */ this.port = opts.port.toString(); /** * Container port * @type {String} */ this.exposed = opts.exposed.toString(); /** * Image path * @type {[type]} */ this.image = resolve(opts.image); /** * Environment vars which will be used when starting container * @type {String} */ this.envs = opts.envs ? stringify(opts.envs).split('&') : ''; /** * Event emitter instance * @type {EventEmitter} */ this.events = new EventEmitter(); /** * Dockerode object * @type {Object} */ this.docker = new Docker(); /** * Build instance * @type {Object} */ this.builder = null; /** * EventEmitter#addEventListener bridge * @type {Function} */ this.on = this.events.on.bind(this.events); const portProtocol = `${this.exposed}/tcp`; /** * Ports map * @type {Object} */ this.ports = {}; this.ports[portProtocol] = [{ HostPort: this.port.toString() }]; } /** * Pump everything to the console * Useful for debug and when console is needed */ pump() { DBuilder.pump(this.builder, process.stdout, err => { /* eslint-disable no-console */ if (err) { console.error(err); } }); return this; } /** * DBuilder#build -> DBuilder#run * @returns {Promise} */ up() { return this.build().then(() => this.run()); } /** * Build container * @return {Promise} */ build() { this.builder = DBuilder.build(this.image, { t: this.name }); return new DBuilder.Promise((resolve, reject) => { this.builder.on('complete', () => { this.events.emit('complete'); this.docker.listContainers({ all: true }, (listError, containers) => { if (listError) { this.events.emit('error', listError); return; } const dup = containers.filter(container => container.Image === this.name)[0]; if (!dup) { resolve(); } else { this.stopAndRemove(dup.Id).then(resolve, reject); } }); }); }); } /** * Stop and remove container * @param {String} id - container id * @return {Promise} */ stopAndRemove(id) { return new DBuilder.Promise((resolve, reject) => { const container = this.docker.getContainer(id); container.stop(() => { container.remove(removeErr => { if (removeErr) { this.events.emit('error', removeErr); reject(); return; } this.events.emit('stopped and removed'); resolve(); }); }); }); } /** * Create, attach and start container * @return {Promise} */ run() { return new DBuilder.Promise((resolve, reject) => { this.docker.createContainer({ Image: this.name, name: this.name, Env: this.envs, PortBindings: this.ports }, (createErr, container) => { if (createErr) { this.events.emit('error', createErr); reject(); return; } this.events.emit('run'); container.attach({ stream: true, stdout: true, stderr: true }, (attachErr, stream) => { stream.on('data', () => resolve()); stream.on('data', data => this.events.emit('data', data)); }); container.start(startErr => { if (startErr) { this.events.emit('error', startErr); reject(); } }); }); }); } }
index.js
import { resolve } from 'path'; import { stringify } from 'querystring'; import { EventEmitter } from 'events'; import pump from 'pump'; import Docker from 'dockerode'; import build from 'dockerode-build'; export default class DBuilder { static Promise = Promise; static build = build; static pump = pump; /** * @constructor * @param {Object} opts * @param {String} opts.name - name of container, which will be used for build and run * @param {Number} opts.port - host port * @param {Number} opts.exposed - exposed container port, should correlate with "EXPOSED" * @param {Object} opts.envs - environment vars which will be used when starting container * @param {string} opts.image - image path */ constructor(opts = {}) { /** * Name of the container * @type {String} */ this.name = opts.name; /** * Host port * @type {String} */ this.port = opts.port.toString(); /** * Container port * @type {String} */ this.exposed = opts.exposed.toString(); /** * Image path * @type {[type]} */ this.image = resolve(opts.image); /** * Environment vars which will be used when starting container * @type {String} */ this.envs = opts.envs ? stringify(opts.envs).split('&') : ''; /** * Event emitter instance * @type {EventEmitter} */ this.events = new EventEmitter(); /** * Dockerode object * @type {Object} */ this.docker = new Docker(); /** * Build instance * @type {Object} */ this.builder = null; /** * EventEmitter#addEventListener bridge * @type {Function} */ this.on = this.events.on.bind(this.events); const portProtocol = `${this.exposed}/tcp`; /** * Ports map * @type {Object} */ this.ports = {}; this.ports[portProtocol] = [{ HostPort: this.port.toString() }]; } /** * Pump everything to the console * Useful for debug and when console is needed */ pump() { DBuilder.pump(this.builder, process.stdout, err => { /* eslint-disable no-console */ if (err) { console.error(err); } }); return this; } /** * DBuilder#build -> DBuilder#run * @returns {Promise} */ up() { return this.build().then(() => this.run()); } /** * Build container * @return {Promise} */ build() { this.builder = DBuilder.build(this.image, { t: this.name }); return new DBuilder.Promise((resolve, reject) => { this.builder.on('complete', () => { this.events.emit('complete'); this.docker.listContainers({ all: true }, (listError, containers) => { if (listError) { this.events.emit('error', listError); return; } const dup = containers.filter(container => container.Image === this.name)[0]; if (!dup) { resolve(); } else { this.stopAndRemove(dup.Id).then(resolve, reject); } }); }); }); } /** * Stop and remove container * @param {String} id - container id * @return {Promise} */ stopAndRemove(id) { return new DBuilder.Promise((resolve, reject) => { const container = this.docker.getContainer(id); container.stop(() => { container.remove(removeErr => { if (removeErr) { this.events.emit('error', removeErr); reject(); return; } this.events.emit('stopped and removed'); resolve(); }); }); }); } /** * Create, attach and start container * @return {Promise} */ run() { return new DBuilder.Promise((resolve, reject) => { this.docker.createContainer({ Image: this.name, name: this.name, Env: this.envs, PortBindings: this.ports }, (createErr, container) => { if (createErr) { this.events.emit('error', createErr); reject(); return; } this.events.emit('run'); container.attach({ stream: true, stdout: true, stderr: true }, (attachErr, stream) => { stream.on('data', () => resolve()); stream.on('data', data => this.events.emit('data', data)); }); container.start(startErr => { if (startErr) { this.events.emit('error', startErr); reject(); } }); }); }); } }
Add JSDoc for static properties & use of `babel-polyfill` package
index.js
Add JSDoc for static properties & use of `babel-polyfill` package
<ide><path>ndex.js <add>require('babel-polyfill'); <add> <ide> import { resolve } from 'path'; <ide> import { stringify } from 'querystring'; <ide> import { EventEmitter } from 'events'; <ide> import build from 'dockerode-build'; <ide> <ide> export default class DBuilder { <add> /** <add> * Promise constructor, for test stubbing <add> * @static <add> * @type {Function} <add> */ <ide> static Promise = Promise; <add> /** <add> * dockerode-build function, for test stubbing <add> * @static <add> * @type {Function} <add> */ <ide> static build = build; <add> /** <add> * pump function, for test stubbing <add> * @static <add> * @type {Function} <add> */ <ide> static pump = pump; <ide> <ide> /**
Java
mit
b553f7190d887ab5f42a00ac91a3fc48d928957a
0
fvasquezjatar/fermat-unused,fvasquezjatar/fermat-unused
package unit.com.bitdubai.fermat_dmp_plugin.layer.transaction.outgoing_extra_user.developer.bitdubai.version_1.structure.OutgoingExtraUserTransactionManager; import com.bitdubai.fermat_api.layer.all_definition.enums.Actors; import com.bitdubai.fermat_api.layer.all_definition.enums.CryptoCurrency; import com.bitdubai.fermat_api.layer.all_definition.money.CryptoAddress; import com.bitdubai.fermat_api.layer.dmp_basic_wallet.bitcoin_wallet.exceptions.CantCalculateBalanceException; import com.bitdubai.fermat_api.layer.dmp_basic_wallet.bitcoin_wallet.exceptions.CantLoadWalletException; import com.bitdubai.fermat_api.layer.dmp_basic_wallet.bitcoin_wallet.interfaces.BitcoinWalletBalance; import com.bitdubai.fermat_api.layer.dmp_basic_wallet.bitcoin_wallet.interfaces.BitcoinWalletManager; import com.bitdubai.fermat_api.layer.dmp_basic_wallet.bitcoin_wallet.interfaces.BitcoinWalletWallet; import com.bitdubai.fermat_api.layer.dmp_transaction.outgoing_extrauser.exceptions.CantSendFundsException; import com.bitdubai.fermat_api.layer.dmp_transaction.outgoing_extrauser.exceptions.InsufficientFundsException; import com.bitdubai.fermat_api.layer.osa_android.database_system.Database; import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseFactory; import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseTable; import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseTableFactory; import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseTableRecord; import com.bitdubai.fermat_api.layer.osa_android.database_system.PluginDatabaseSystem; import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.CantInsertRecordException; import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.CantOpenDatabaseException; import com.bitdubai.fermat_api.layer.pip_platform_service.error_manager.ErrorManager; import com.bitdubai.fermat_api.layer.pip_platform_service.event_manager.EventManager; import com.bitdubai.fermat_cry_api.layer.crypto_vault.CryptoVaultManager; import com.bitdubai.fermat_dmp_plugin.layer.transaction.outgoing_extra_user.developer.bitdubai.version_1.OutgoingExtraUserTransactionPluginRoot; import com.bitdubai.fermat_dmp_plugin.layer.transaction.outgoing_extra_user.developer.bitdubai.version_1.structure.OutgoingExtraUserDao; import com.bitdubai.fermat_dmp_plugin.layer.transaction.outgoing_extra_user.developer.bitdubai.version_1.structure.OutgoingExtraUserDatabaseConstants; import com.bitdubai.fermat_dmp_plugin.layer.transaction.outgoing_extra_user.developer.bitdubai.version_1.structure.OutgoingExtraUserTransactionManager; import org.fest.assertions.api.Assertions; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import java.util.UUID; import static com.googlecode.catchexception.CatchException.catchException; import static com.googlecode.catchexception.CatchException.caughtException; import static org.fest.assertions.api.Assertions.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyLong; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.when; /** * Created by natalia on 10/07/15. */ @RunWith(MockitoJUnitRunner.class) public class sendTest { @Mock private BitcoinWalletManager mockBitcoinWalletManager; @Mock private BitcoinWalletWallet mockBitcoinWalletWallet; @Mock private BitcoinWalletBalance mockBitcoinWalletBalance; @Mock private CryptoVaultManager mockCryptoVaultManager; @Mock private ErrorManager mockErrorManager; @Mock private PluginDatabaseSystem mockPluginDatabaseSystem; @Mock private EventManager mockEventManager; @Mock private DatabaseFactory mockDatabaseFactory; @Mock private DatabaseTableFactory mockTableFactory; @Mock private Database mockDatabase; @Mock private DatabaseTable mockTable; @Mock private DatabaseTableRecord mockRecord; private CryptoAddress cryptoAddress; private UUID testId; private UUID testwalletID; private String testDataBaseName; private OutgoingExtraUserTransactionManager testTransactionManager; public void setUpTestValues(){ cryptoAddress = new CryptoAddress(); cryptoAddress.setCryptoCurrency(CryptoCurrency.BITCOIN); cryptoAddress.setAddress(UUID.randomUUID().toString()); testwalletID = UUID.randomUUID(); testId = UUID.randomUUID(); testDataBaseName = OutgoingExtraUserDatabaseConstants.OUTGOING_EXTRA_USER_DATABASE_NAME; } public void setUpGeneralMockitoRules() throws Exception{ when(mockPluginDatabaseSystem.createDatabase(testId, testDataBaseName)).thenReturn(mockDatabase); when(mockPluginDatabaseSystem.openDatabase(testId, testDataBaseName)).thenReturn(mockDatabase); when(mockDatabase.getDatabaseFactory()).thenReturn(mockDatabaseFactory); when(mockDatabaseFactory.newTableFactory(any(UUID.class), anyString())).thenReturn(mockTableFactory); when(mockBitcoinWalletManager.loadWallet(any(UUID.class))).thenReturn(mockBitcoinWalletWallet); when(mockBitcoinWalletWallet.getAvailableBalance()).thenReturn(mockBitcoinWalletBalance); when(mockDatabase.getTable(anyString())).thenReturn(mockTable); when(mockTable.getEmptyRecord()).thenReturn(mockRecord); } @Before public void setUp() throws Exception{ setUpTestValues(); setUpGeneralMockitoRules(); } @Test public void Send_Succesfully() throws Exception { testTransactionManager = new OutgoingExtraUserTransactionManager(); testTransactionManager.setPluginDatabaseSystem(mockPluginDatabaseSystem); testTransactionManager.setPluginId(testId); testTransactionManager.setErrorManager(mockErrorManager); testTransactionManager.setBitcoinWalletManager(mockBitcoinWalletManager); testTransactionManager.setCryptoVaultManager(mockCryptoVaultManager); catchException(testTransactionManager).send(testwalletID, cryptoAddress, 0, "test", UUID.randomUUID(), Actors.EXTRA_USER, UUID.randomUUID(), Actors.EXTRA_USER); assertThat(caughtException()).isNull(); } @Test public void Send_InsufficientFunds_TrowsInsufficientFundsException() throws Exception { testTransactionManager = new OutgoingExtraUserTransactionManager(); testTransactionManager.setPluginDatabaseSystem(mockPluginDatabaseSystem); testTransactionManager.setPluginId(testId); testTransactionManager.setErrorManager(mockErrorManager); testTransactionManager.setBitcoinWalletManager(mockBitcoinWalletManager); testTransactionManager.setCryptoVaultManager(mockCryptoVaultManager); catchException(testTransactionManager).send(testwalletID, cryptoAddress, 20, "test", UUID.randomUUID(), Actors.EXTRA_USER, UUID.randomUUID(), Actors.EXTRA_USER); assertThat(caughtException()).isInstanceOf(InsufficientFundsException.class); } @Test public void Send_FailedCalculateBalance_ThrowsCantSendFundsException() throws Exception { when(mockBitcoinWalletWallet.getAvailableBalance().getBalance()).thenThrow(new CantCalculateBalanceException("Mock", null, null, null)); testTransactionManager = new OutgoingExtraUserTransactionManager(); testTransactionManager.setPluginDatabaseSystem(mockPluginDatabaseSystem); testTransactionManager.setPluginId(testId); testTransactionManager.setErrorManager(mockErrorManager); testTransactionManager.setBitcoinWalletManager(mockBitcoinWalletManager); testTransactionManager.setCryptoVaultManager(mockCryptoVaultManager); catchException(testTransactionManager).send(testwalletID, cryptoAddress, 0, "test", UUID.randomUUID(),Actors.EXTRA_USER,UUID.randomUUID(),Actors.EXTRA_USER); assertThat(caughtException()).isInstanceOf(CantSendFundsException.class); } @Test public void Send_FailedDaoInitialize_ThrowsCantSendFundsException() throws Exception { when(mockPluginDatabaseSystem.openDatabase(testId, testDataBaseName)).thenThrow(new CantOpenDatabaseException()); testTransactionManager = new OutgoingExtraUserTransactionManager(); testTransactionManager.setPluginDatabaseSystem(mockPluginDatabaseSystem); testTransactionManager.setPluginId(testId); testTransactionManager.setErrorManager(mockErrorManager); testTransactionManager.setBitcoinWalletManager(mockBitcoinWalletManager); testTransactionManager.setCryptoVaultManager(mockCryptoVaultManager); catchException(testTransactionManager).send(testwalletID, cryptoAddress, 0, "test", UUID.randomUUID(),Actors.EXTRA_USER,UUID.randomUUID(),Actors.EXTRA_USER); assertThat(caughtException()).isInstanceOf(CantSendFundsException.class); } @Test public void Send_FailedWalletLoad_ThrowsCantSendFundsException() throws Exception { when(mockBitcoinWalletManager.loadWallet(any(UUID.class))).thenThrow(new CantLoadWalletException("Mock", null, null, null)); testTransactionManager = new OutgoingExtraUserTransactionManager(); testTransactionManager.setPluginDatabaseSystem(mockPluginDatabaseSystem); testTransactionManager.setPluginId(testId); testTransactionManager.setErrorManager(mockErrorManager); testTransactionManager.setBitcoinWalletManager(mockBitcoinWalletManager); testTransactionManager.setCryptoVaultManager(mockCryptoVaultManager); catchException(testTransactionManager).send(testwalletID, cryptoAddress, 0, "test", UUID.randomUUID(),Actors.EXTRA_USER,UUID.randomUUID(),Actors.EXTRA_USER); assertThat(caughtException()).isInstanceOf(CantSendFundsException.class); } }
DMP/plugin/transaction/fermat-dmp-plugin-transaction-outgoing-extra-user-bitdubai/src/test/java/unit/com/bitdubai/fermat_dmp_plugin/layer/transaction/outgoing_extra_user/developer/bitdubai/version_1/structure/OutgoingExtraUserTransactionManager/sendTest.java
package unit.com.bitdubai.fermat_dmp_plugin.layer.transaction.outgoing_extra_user.developer.bitdubai.version_1.structure.OutgoingExtraUserTransactionManager; import com.bitdubai.fermat_api.layer.all_definition.enums.CryptoCurrency; import com.bitdubai.fermat_api.layer.all_definition.enums.ServiceStatus; import com.bitdubai.fermat_api.layer.all_definition.money.CryptoAddress; import com.bitdubai.fermat_api.layer.dmp_basic_wallet.bitcoin_wallet.interfaces.BitcoinWalletBalance; import com.bitdubai.fermat_api.layer.dmp_basic_wallet.bitcoin_wallet.interfaces.BitcoinWalletManager; import com.bitdubai.fermat_api.layer.dmp_basic_wallet.bitcoin_wallet.interfaces.BitcoinWalletWallet; import com.bitdubai.fermat_api.layer.dmp_transaction.outgoing_extrauser.exceptions.CantSendFundsException; import com.bitdubai.fermat_api.layer.dmp_transaction.outgoing_extrauser.exceptions.InsufficientFundsException; import com.bitdubai.fermat_api.layer.osa_android.database_system.Database; import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseFactory; import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseTable; import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseTableFactory; import com.bitdubai.fermat_api.layer.osa_android.database_system.DealsWithPluginDatabaseSystem; import com.bitdubai.fermat_api.layer.osa_android.database_system.PluginDatabaseSystem; import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.CantInsertRecordException; import com.bitdubai.fermat_api.layer.pip_platform_service.error_manager.DealsWithErrors; import com.bitdubai.fermat_api.layer.pip_platform_service.error_manager.ErrorManager; import com.bitdubai.fermat_api.layer.pip_platform_service.event_manager.EventManager; import com.bitdubai.fermat_cry_api.layer.crypto_vault.CryptoVaultManager; import com.bitdubai.fermat_dmp_plugin.layer.transaction.outgoing_extra_user.developer.bitdubai.version_1.OutgoingExtraUserTransactionPluginRoot; import com.bitdubai.fermat_dmp_plugin.layer.transaction.outgoing_extra_user.developer.bitdubai.version_1.structure.OutgoingExtraUserDao; import com.bitdubai.fermat_dmp_plugin.layer.transaction.outgoing_extra_user.developer.bitdubai.version_1.structure.OutgoingExtraUserDatabaseConstants; import com.bitdubai.fermat_dmp_plugin.layer.transaction.outgoing_extra_user.developer.bitdubai.version_1.structure.OutgoingExtraUserTransactionManager; import org.fest.assertions.api.Assertions; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import java.util.UUID; import static com.googlecode.catchexception.CatchException.catchException; import static com.googlecode.catchexception.CatchException.caughtException; import static org.fest.assertions.api.Assertions.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyLong; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.when; /** * Created by natalia on 10/07/15. */ @RunWith(MockitoJUnitRunner.class) public class sendTest { @Mock private BitcoinWalletManager mockBitcoinWalletManager; @Mock private BitcoinWalletWallet mockBitcoinWalletWallet; @Mock private BitcoinWalletBalance mockBitcoinWalletBalance; @Mock private CryptoVaultManager mockCryptoVaultManager; @Mock private ErrorManager mockErrorManager; @Mock private PluginDatabaseSystem mockPluginDatabaseSystem; @Mock private EventManager mockEventManager; @Mock private DatabaseFactory mockDatabaseFactory; @Mock private DatabaseTableFactory mockTableFactory; @Mock private Database mockDatabase; @Mock private DatabaseTable mockTable; private CryptoAddress cryptoAddress; private UUID testId; private UUID testwalletID; private String testDataBaseName; private OutgoingExtraUserTransactionManager testTransactionManager; public void setUpTestValues(){ cryptoAddress = new CryptoAddress(); cryptoAddress.setCryptoCurrency(CryptoCurrency.BITCOIN); cryptoAddress.setAddress(UUID.randomUUID().toString()); testwalletID = UUID.randomUUID(); testId = UUID.randomUUID(); testDataBaseName = OutgoingExtraUserDatabaseConstants.OUTGOING_EXTRA_USER_DATABASE_NAME; } public void setUpGeneralMockitoRules() throws Exception{ when(mockPluginDatabaseSystem.createDatabase(testId, testDataBaseName)).thenReturn(mockDatabase); when(mockDatabase.getDatabaseFactory()).thenReturn(mockDatabaseFactory); when(mockDatabaseFactory.newTableFactory(any(UUID.class), anyString())).thenReturn(mockTableFactory); when(mockBitcoinWalletManager.loadWallet(any(UUID.class))).thenReturn(mockBitcoinWalletWallet); when(mockBitcoinWalletWallet.getAvailableBalance()).thenReturn(mockBitcoinWalletBalance); when(mockDatabase.getTable(anyString())).thenReturn(mockTable); } @Before public void setUp() throws Exception{ setUpTestValues(); setUpGeneralMockitoRules(); } //TODO:I need execute before OutgoingExtraUserDao.initialize because database object is null @Test public void Send_ThrowsInsufficientFundsException() throws Exception { testTransactionManager = new OutgoingExtraUserTransactionManager(); testTransactionManager.setPluginDatabaseSystem(mockPluginDatabaseSystem); testTransactionManager.setPluginId(testId); testTransactionManager.setErrorManager(mockErrorManager); testTransactionManager.setBitcoinWalletManager(mockBitcoinWalletManager); testTransactionManager.setCryptoVaultManager(mockCryptoVaultManager); catchException(testTransactionManager).send(testwalletID, cryptoAddress, 20, "test"); assertThat(caughtException()).isInstanceOf(InsufficientFundsException.class); } @Test public void Send_ThrowsCantSendFundsException() throws Exception { testTransactionManager = new OutgoingExtraUserTransactionManager(); testTransactionManager.setPluginDatabaseSystem(mockPluginDatabaseSystem); testTransactionManager.setPluginId(testId); testTransactionManager.setErrorManager(mockErrorManager); testTransactionManager.setBitcoinWalletManager(mockBitcoinWalletManager); testTransactionManager.setCryptoVaultManager(mockCryptoVaultManager); catchException(testTransactionManager).send(testwalletID, cryptoAddress, 0, "test"); assertThat(caughtException()).isInstanceOf(CantInsertRecordException.class); } }
Fix #436- Outgoing Extra User: Unit Test corrections.
DMP/plugin/transaction/fermat-dmp-plugin-transaction-outgoing-extra-user-bitdubai/src/test/java/unit/com/bitdubai/fermat_dmp_plugin/layer/transaction/outgoing_extra_user/developer/bitdubai/version_1/structure/OutgoingExtraUserTransactionManager/sendTest.java
Fix #436- Outgoing Extra User: Unit Test corrections.
<ide><path>MP/plugin/transaction/fermat-dmp-plugin-transaction-outgoing-extra-user-bitdubai/src/test/java/unit/com/bitdubai/fermat_dmp_plugin/layer/transaction/outgoing_extra_user/developer/bitdubai/version_1/structure/OutgoingExtraUserTransactionManager/sendTest.java <ide> package unit.com.bitdubai.fermat_dmp_plugin.layer.transaction.outgoing_extra_user.developer.bitdubai.version_1.structure.OutgoingExtraUserTransactionManager; <ide> <add>import com.bitdubai.fermat_api.layer.all_definition.enums.Actors; <ide> import com.bitdubai.fermat_api.layer.all_definition.enums.CryptoCurrency; <del>import com.bitdubai.fermat_api.layer.all_definition.enums.ServiceStatus; <add> <ide> import com.bitdubai.fermat_api.layer.all_definition.money.CryptoAddress; <add>import com.bitdubai.fermat_api.layer.dmp_basic_wallet.bitcoin_wallet.exceptions.CantCalculateBalanceException; <add>import com.bitdubai.fermat_api.layer.dmp_basic_wallet.bitcoin_wallet.exceptions.CantLoadWalletException; <ide> import com.bitdubai.fermat_api.layer.dmp_basic_wallet.bitcoin_wallet.interfaces.BitcoinWalletBalance; <ide> import com.bitdubai.fermat_api.layer.dmp_basic_wallet.bitcoin_wallet.interfaces.BitcoinWalletManager; <ide> import com.bitdubai.fermat_api.layer.dmp_basic_wallet.bitcoin_wallet.interfaces.BitcoinWalletWallet; <add> <ide> import com.bitdubai.fermat_api.layer.dmp_transaction.outgoing_extrauser.exceptions.CantSendFundsException; <ide> import com.bitdubai.fermat_api.layer.dmp_transaction.outgoing_extrauser.exceptions.InsufficientFundsException; <ide> import com.bitdubai.fermat_api.layer.osa_android.database_system.Database; <ide> import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseFactory; <ide> import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseTable; <ide> import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseTableFactory; <del>import com.bitdubai.fermat_api.layer.osa_android.database_system.DealsWithPluginDatabaseSystem; <add> <add>import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseTableRecord; <ide> import com.bitdubai.fermat_api.layer.osa_android.database_system.PluginDatabaseSystem; <ide> import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.CantInsertRecordException; <del>import com.bitdubai.fermat_api.layer.pip_platform_service.error_manager.DealsWithErrors; <add> <add>import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.CantOpenDatabaseException; <ide> import com.bitdubai.fermat_api.layer.pip_platform_service.error_manager.ErrorManager; <ide> import com.bitdubai.fermat_api.layer.pip_platform_service.event_manager.EventManager; <ide> import com.bitdubai.fermat_cry_api.layer.crypto_vault.CryptoVaultManager; <ide> private DatabaseTable mockTable; <ide> <ide> <add> @Mock <add> private DatabaseTableRecord mockRecord; <add> <ide> private CryptoAddress cryptoAddress; <ide> private UUID testId; <ide> private UUID testwalletID; <ide> public void setUpGeneralMockitoRules() throws Exception{ <ide> <ide> when(mockPluginDatabaseSystem.createDatabase(testId, testDataBaseName)).thenReturn(mockDatabase); <add> when(mockPluginDatabaseSystem.openDatabase(testId, testDataBaseName)).thenReturn(mockDatabase); <ide> when(mockDatabase.getDatabaseFactory()).thenReturn(mockDatabaseFactory); <ide> when(mockDatabaseFactory.newTableFactory(any(UUID.class), anyString())).thenReturn(mockTableFactory); <ide> when(mockBitcoinWalletManager.loadWallet(any(UUID.class))).thenReturn(mockBitcoinWalletWallet); <ide> when(mockBitcoinWalletWallet.getAvailableBalance()).thenReturn(mockBitcoinWalletBalance); <ide> <ide> when(mockDatabase.getTable(anyString())).thenReturn(mockTable); <del> <add> when(mockTable.getEmptyRecord()).thenReturn(mockRecord); <ide> } <ide> <ide> @Before <ide> setUpGeneralMockitoRules(); <ide> } <ide> <del> //TODO:I need execute before OutgoingExtraUserDao.initialize because database object is null <del> <del> @Test <del> public void Send_ThrowsInsufficientFundsException() throws Exception { <del> testTransactionManager = new OutgoingExtraUserTransactionManager(); <del> testTransactionManager.setPluginDatabaseSystem(mockPluginDatabaseSystem); <del> testTransactionManager.setPluginId(testId); <del> testTransactionManager.setErrorManager(mockErrorManager); <del> <del> <del> <del> testTransactionManager.setBitcoinWalletManager(mockBitcoinWalletManager); <del> testTransactionManager.setCryptoVaultManager(mockCryptoVaultManager); <del> <del> catchException(testTransactionManager).send(testwalletID, cryptoAddress, 20, "test"); <add> <add> <add> @Test <add> public void Send_Succesfully() throws Exception { <add> <add> testTransactionManager = new OutgoingExtraUserTransactionManager(); <add> testTransactionManager.setPluginDatabaseSystem(mockPluginDatabaseSystem); <add> testTransactionManager.setPluginId(testId); <add> testTransactionManager.setErrorManager(mockErrorManager); <add> <add> testTransactionManager.setBitcoinWalletManager(mockBitcoinWalletManager); <add> testTransactionManager.setCryptoVaultManager(mockCryptoVaultManager); <add> <add> catchException(testTransactionManager).send(testwalletID, cryptoAddress, 0, "test", UUID.randomUUID(), Actors.EXTRA_USER, UUID.randomUUID(), Actors.EXTRA_USER); <add> <add> assertThat(caughtException()).isNull(); <add> <add> <add> } <add> <add> @Test <add> public void Send_InsufficientFunds_TrowsInsufficientFundsException() throws Exception { <add> testTransactionManager = new OutgoingExtraUserTransactionManager(); <add> testTransactionManager.setPluginDatabaseSystem(mockPluginDatabaseSystem); <add> testTransactionManager.setPluginId(testId); <add> testTransactionManager.setErrorManager(mockErrorManager); <add> <add> <add> <add> testTransactionManager.setBitcoinWalletManager(mockBitcoinWalletManager); <add> testTransactionManager.setCryptoVaultManager(mockCryptoVaultManager); <add> <add> catchException(testTransactionManager).send(testwalletID, cryptoAddress, 20, "test", UUID.randomUUID(), Actors.EXTRA_USER, UUID.randomUUID(), Actors.EXTRA_USER); <ide> <ide> assertThat(caughtException()).isInstanceOf(InsufficientFundsException.class); <ide> <ide> <ide> } <ide> <del> @Test <del> public void Send_ThrowsCantSendFundsException() throws Exception { <del> <del> testTransactionManager = new OutgoingExtraUserTransactionManager(); <del> testTransactionManager.setPluginDatabaseSystem(mockPluginDatabaseSystem); <del> testTransactionManager.setPluginId(testId); <del> testTransactionManager.setErrorManager(mockErrorManager); <del> <del> <del> <del> testTransactionManager.setBitcoinWalletManager(mockBitcoinWalletManager); <del> testTransactionManager.setCryptoVaultManager(mockCryptoVaultManager); <del> <del> <del> catchException(testTransactionManager).send(testwalletID, cryptoAddress, 0, "test"); <del> <del> assertThat(caughtException()).isInstanceOf(CantInsertRecordException.class); <del> <add> <add> @Test <add> public void Send_FailedCalculateBalance_ThrowsCantSendFundsException() throws Exception { <add> when(mockBitcoinWalletWallet.getAvailableBalance().getBalance()).thenThrow(new CantCalculateBalanceException("Mock", null, null, null)); <add> <add> testTransactionManager = new OutgoingExtraUserTransactionManager(); <add> testTransactionManager.setPluginDatabaseSystem(mockPluginDatabaseSystem); <add> testTransactionManager.setPluginId(testId); <add> testTransactionManager.setErrorManager(mockErrorManager); <add> testTransactionManager.setBitcoinWalletManager(mockBitcoinWalletManager); <add> testTransactionManager.setCryptoVaultManager(mockCryptoVaultManager); <add> <add> catchException(testTransactionManager).send(testwalletID, cryptoAddress, 0, "test", UUID.randomUUID(),Actors.EXTRA_USER,UUID.randomUUID(),Actors.EXTRA_USER); <add> <add> assertThat(caughtException()).isInstanceOf(CantSendFundsException.class); <add> } <add> <add> @Test <add> public void Send_FailedDaoInitialize_ThrowsCantSendFundsException() throws Exception { <add> when(mockPluginDatabaseSystem.openDatabase(testId, testDataBaseName)).thenThrow(new CantOpenDatabaseException()); <add> <add> testTransactionManager = new OutgoingExtraUserTransactionManager(); <add> testTransactionManager.setPluginDatabaseSystem(mockPluginDatabaseSystem); <add> testTransactionManager.setPluginId(testId); <add> testTransactionManager.setErrorManager(mockErrorManager); <add> testTransactionManager.setBitcoinWalletManager(mockBitcoinWalletManager); <add> testTransactionManager.setCryptoVaultManager(mockCryptoVaultManager); <add> <add> catchException(testTransactionManager).send(testwalletID, cryptoAddress, 0, "test", UUID.randomUUID(),Actors.EXTRA_USER,UUID.randomUUID(),Actors.EXTRA_USER); <add> <add> assertThat(caughtException()).isInstanceOf(CantSendFundsException.class); <add> } <add> <add> <add> <add> @Test <add> public void Send_FailedWalletLoad_ThrowsCantSendFundsException() throws Exception { <add> when(mockBitcoinWalletManager.loadWallet(any(UUID.class))).thenThrow(new CantLoadWalletException("Mock", null, null, null)); <add> <add> testTransactionManager = new OutgoingExtraUserTransactionManager(); <add> testTransactionManager.setPluginDatabaseSystem(mockPluginDatabaseSystem); <add> testTransactionManager.setPluginId(testId); <add> testTransactionManager.setErrorManager(mockErrorManager); <add> testTransactionManager.setBitcoinWalletManager(mockBitcoinWalletManager); <add> testTransactionManager.setCryptoVaultManager(mockCryptoVaultManager); <add> <add> catchException(testTransactionManager).send(testwalletID, cryptoAddress, 0, "test", UUID.randomUUID(),Actors.EXTRA_USER,UUID.randomUUID(),Actors.EXTRA_USER); <add> <add> assertThat(caughtException()).isInstanceOf(CantSendFundsException.class); <ide> } <ide> <ide> }
Java
apache-2.0
278de271cfce69521d822b00c8dbd96515e143b8
0
cushon/error-prone,google/error-prone,cushon/error-prone,cushon/error-prone,google/error-prone,cushon/error-prone
/* * Copyright 2018 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.time; import static com.google.errorprone.BugPattern.ProvidesFix.REQUIRES_HUMAN_ATTENTION; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import com.google.common.collect.ImmutableSet; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.fixes.SuggestedFixes; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.google.errorprone.matchers.Matchers; import com.google.errorprone.matchers.method.MethodMatchers; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MethodInvocationTree; import java.util.ArrayList; import java.util.List; /** * Check for calls to JodaTime's {@code type.plus(long)} and {@code type.minus(long)} where {@code * <type> = {Duration,Instant,DateTime,DateMidnight}}. */ @BugPattern( name = "JodaPlusMinusLong", summary = "Use of JodaTime's type.plus(long) or type.minus(long) is not allowed (where <type> = " + "{Duration,Instant,DateTime,DateMidnight}). Please use " + "type.plus(Duration.millis(long)) or type.minus(Duration.millis(long)) instead.", explanation = "JodaTime's type.plus(long) and type.minus(long) methods are often a source of bugs " + "because the units of the parameters are ambiguous. Please use " + "type.plus(Duration.millis(long)) or type.minus(Duration.millis(long)) instead.", severity = WARNING, providesFix = REQUIRES_HUMAN_ATTENTION) public final class JodaPlusMinusLong extends BugChecker implements MethodInvocationTreeMatcher { private static final ImmutableSet<String> TYPES = ImmutableSet.of("DateMidnight", "DateTime", "Duration", "Instant"); private static final ImmutableSet<String> METHODS = ImmutableSet.of("plus", "minus"); private static final Matcher<ExpressionTree> MATCHER = Matchers.allOf( buildMatcher(), // Allow usage by JodaTime itself Matchers.not(Matchers.packageStartsWith("org.joda.time"))); private static final Matcher<ExpressionTree> DURATION_GET_MILLIS_MATCHER = MethodMatchers.instanceMethod() .onDescendantOf("org.joda.time.ReadableDuration") .named("getMillis"); private static Matcher<ExpressionTree> buildMatcher() { List<Matcher<ExpressionTree>> matchers = new ArrayList<>(); for (String type : TYPES) { for (String method : METHODS) { matchers.add( Matchers.instanceMethod() .onExactClass("org.joda.time." + type) .named(method) .withParameters("long")); } } return Matchers.anyOf(matchers); } @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { if (!MATCHER.matches(tree, state)) { return Description.NO_MATCH; } SuggestedFix.Builder builder = SuggestedFix.builder(); ExpressionTree firstArgumentTree = tree.getArguments().get(0); String firstArgumentReplacement; if (DURATION_GET_MILLIS_MATCHER.matches(firstArgumentTree, state)) { // This is passing {@code someDuration.getMillis()} as the parameter. we can replace this // with {@code someDuration}. firstArgumentReplacement = state.getSourceForNode(ASTHelpers.getReceiver(firstArgumentTree)); } else { // Wrap the long as a Duration. firstArgumentReplacement = SuggestedFixes.qualifyType(state, builder, "org.joda.time.Duration") + ".millis(" + state.getSourceForNode(firstArgumentTree) + ")"; } builder.replace(firstArgumentTree, firstArgumentReplacement); return describeMatch(tree, builder.build()); } }
core/src/main/java/com/google/errorprone/bugpatterns/time/JodaPlusMinusLong.java
/* * Copyright 2018 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.time; import static com.google.errorprone.BugPattern.ProvidesFix.REQUIRES_HUMAN_ATTENTION; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import com.google.common.collect.ImmutableSet; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.fixes.SuggestedFixes; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.google.errorprone.matchers.Matchers; import com.google.errorprone.matchers.method.MethodMatchers; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MethodInvocationTree; import java.util.ArrayList; import java.util.List; /** * Check for calls to JodaTime's {@code type.plus(long)} and {@code type.minus(long)} where {@code * <type> = {Duration,Instant,DateTime,DateMidnight}}. */ @BugPattern( name = "JodaPlusMinusLong", summary = "Use of JodaTime's type.plus(long) or type.minus(long) is not allowed (where <type> = " + "{Duration,Instant,DateTime,DateMidnight}). Please use " + " type.plus(Duration.millis(long)) or type.minus(Duration.millis(long)) instead.", explanation = "JodaTime's type.plus(long) and type.minus(long) methods are often a source of bugs " + "because the units of the parameters are ambiguous. Please use " + "type.plus(Duration.millis(long)) or type.minus(Duration.millis(long)) instead.", severity = WARNING, providesFix = REQUIRES_HUMAN_ATTENTION) public final class JodaPlusMinusLong extends BugChecker implements MethodInvocationTreeMatcher { private static final ImmutableSet<String> TYPES = ImmutableSet.of("DateMidnight", "DateTime", "Duration", "Instant"); private static final ImmutableSet<String> METHODS = ImmutableSet.of("plus", "minus"); private static final Matcher<ExpressionTree> MATCHER = Matchers.allOf( buildMatcher(), // Allow usage by JodaTime itself Matchers.not(Matchers.packageStartsWith("org.joda.time"))); private static final Matcher<ExpressionTree> DURATION_GET_MILLIS_MATCHER = MethodMatchers.instanceMethod() .onDescendantOf("org.joda.time.ReadableDuration") .named("getMillis"); private static Matcher<ExpressionTree> buildMatcher() { List<Matcher<ExpressionTree>> matchers = new ArrayList<>(); for (String type : TYPES) { for (String method : METHODS) { matchers.add( Matchers.instanceMethod() .onExactClass("org.joda.time." + type) .named(method) .withParameters("long")); } } return Matchers.anyOf(matchers); } @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { if (!MATCHER.matches(tree, state)) { return Description.NO_MATCH; } SuggestedFix.Builder builder = SuggestedFix.builder(); ExpressionTree firstArgumentTree = tree.getArguments().get(0); String firstArgumentReplacement; if (DURATION_GET_MILLIS_MATCHER.matches(firstArgumentTree, state)) { // This is passing {@code someDuration.getMillis()} as the parameter. we can replace this // with {@code someDuration}. firstArgumentReplacement = state.getSourceForNode(ASTHelpers.getReceiver(firstArgumentTree)); } else { // Wrap the long as a Duration. firstArgumentReplacement = SuggestedFixes.qualifyType(state, builder, "org.joda.time.Duration") + ".millis(" + state.getSourceForNode(firstArgumentTree) + ")"; } builder.replace(firstArgumentTree, firstArgumentReplacement); return describeMatch(tree, builder.build()); } }
Fix an extraneous space in the JodaPlusMinusLong summary. ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=274626494
core/src/main/java/com/google/errorprone/bugpatterns/time/JodaPlusMinusLong.java
Fix an extraneous space in the JodaPlusMinusLong summary.
<ide><path>ore/src/main/java/com/google/errorprone/bugpatterns/time/JodaPlusMinusLong.java <ide> summary = <ide> "Use of JodaTime's type.plus(long) or type.minus(long) is not allowed (where <type> = " <ide> + "{Duration,Instant,DateTime,DateMidnight}). Please use " <del> + " type.plus(Duration.millis(long)) or type.minus(Duration.millis(long)) instead.", <add> + "type.plus(Duration.millis(long)) or type.minus(Duration.millis(long)) instead.", <ide> explanation = <ide> "JodaTime's type.plus(long) and type.minus(long) methods are often a source of bugs " <ide> + "because the units of the parameters are ambiguous. Please use "
Java
bsd-3-clause
876a95e31717c3fe0f6fab1b79d448eb8ae3e054
0
NCIP/cab2b,NCIP/cab2b,NCIP/cab2b
package edu.wustl.cab2b.common.util; import static edu.wustl.cab2b.common.util.Constants.CONNECTOR; import static edu.wustl.cab2b.common.util.Constants.PROJECT_VERSION; import static edu.wustl.cab2b.common.util.Constants.TYPE_CATEGORY; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.io.Writer; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.Session; import edu.common.dynamicextensions.domain.BooleanAttributeTypeInformation; import edu.common.dynamicextensions.domain.DateAttributeTypeInformation; import edu.common.dynamicextensions.domain.DoubleAttributeTypeInformation; import edu.common.dynamicextensions.domain.FloatAttributeTypeInformation; import edu.common.dynamicextensions.domain.IntegerAttributeTypeInformation; import edu.common.dynamicextensions.domain.LongAttributeTypeInformation; import edu.common.dynamicextensions.domain.StringAttributeTypeInformation; import edu.common.dynamicextensions.domaininterface.AbstractAttributeInterface; import edu.common.dynamicextensions.domaininterface.AbstractMetadataInterface; import edu.common.dynamicextensions.domaininterface.AssociationInterface; import edu.common.dynamicextensions.domaininterface.AttributeInterface; import edu.common.dynamicextensions.domaininterface.AttributeTypeInformationInterface; import edu.common.dynamicextensions.domaininterface.EntityGroupInterface; import edu.common.dynamicextensions.domaininterface.EntityInterface; import edu.common.dynamicextensions.domaininterface.PermissibleValueInterface; import edu.common.dynamicextensions.domaininterface.TaggedValueInterface; import edu.common.dynamicextensions.domaininterface.UserDefinedDEInterface; import edu.wustl.cab2b.common.errorcodes.ErrorCodeConstants; import edu.wustl.cab2b.common.exception.RuntimeException; import edu.wustl.cab2b.common.queryengine.result.IQueryResult; import edu.wustl.cab2b.common.queryengine.result.IRecord; import edu.wustl.common.querysuite.metadata.associations.IAssociation; import edu.wustl.common.querysuite.metadata.path.IPath; import edu.wustl.common.querysuite.queryobject.DataType; import edu.wustl.common.util.dbManager.DBUtil; import edu.wustl.common.util.logger.Logger; /** * Utility Class contain general methods used through out the application. * * @author Chandrakant Talele * @author Gautam Shetty */ public class Utility { /** * Checks whether passed attribute/association is inherited. * * @param abstractAttribute * Attribute/Association to check. * @return TRUE if it is inherited else returns FALSE */ public static boolean isInherited(AbstractAttributeInterface abstractAttribute) { for (TaggedValueInterface tag : abstractAttribute.getTaggedValueCollection()) { if (tag.getKey().equals(Constants.TYPE_DERIVED)) { return true; } } return false; } /** * Generates unique string identifier for given association. It is generated * by concatenating * * sourceEntityName +{@link Constants#CONNECTOR} + sourceRoleName +{@link Constants#CONNECTOR} + * targetRoleName +{@link Constants#CONNECTOR} + TargetEntityName * * @param association * Association * @return Unique string to represent given association */ public static String generateUniqueId(AssociationInterface association) { return concatStrings(association.getEntity().getName(), association.getSourceRole() .getName(), association.getTargetRole().getName(), association.getTargetEntity() .getName()); } /** * @param s1 * String * @param s2 * String * @param s3 * String * @param s4 * String * @return Concatenated string made after connecting s1, s2, s3, s4 by * {@link Constants#CONNECTOR} */ public static String concatStrings(String s1, String s2, String s3, String s4) { StringBuffer buff = new StringBuffer(); buff.append(s1); buff.append(CONNECTOR); buff.append(s2); buff.append(CONNECTOR); buff.append(s3); buff.append(CONNECTOR); buff.append(s4); return buff.toString(); } // /** // * Compares whether given searchPattern is present in passed searchString // * // * @param searchPattern search Pattern to look for // * @param searchString String which is to be searched // * @return Returns TRUE if given searchPattern is present in searchString // , // * else return returns false. // */ // public static boolean compareRegEx(String searchPattern, String // searchString) { // searchPattern = searchPattern.replace("*", ".*"); // Pattern pat = Pattern.compile(searchPattern, Pattern.CASE_INSENSITIVE); // Matcher mat = pat.matcher(searchString); // return mat.matches(); // } /** * Compares whether given searchPattern is present in passed searchString. * If it is present returns the position where match found. Otherwise it * returns -1. * * @param searchPattern * @param searchString * @return The position where match found, otherwise returns -1. */ public static int indexOfRegEx(String searchPattern, String searchString) { Pattern pat = Pattern.compile(searchPattern, Pattern.CASE_INSENSITIVE); Matcher mat = pat.matcher(searchString); int position = -1; if (mat.find()) { position = mat.start(); } return position; } /* *//** * Returns all the URLs of the data services which are exposing given entity * * @param entity * Entity to check * @return Returns the List of URLs *//* public static String[] getServiceURLS(EntityInterface entity) { EntityGroupInterface eg = getEntityGroup(entity); String longName = eg.getLongName(); return getServiceURLs(longName); } *//** * Returns all the URLs of the data services which are confirming model of * given application * * @param appName * Aplication name * @return Returns the List of URLs *//* public static String[] getServiceURLs(String appName) { EntityGroupInterface inputEntityGroup = null; Collection<String> returnUrls = new HashSet<String>(); try { inputEntityGroup = EntityManager.getInstance().getEntityGroupByName(appName); } catch (DynamicExtensionsSystemException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (DynamicExtensionsApplicationException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } Long inputEntityGroupId = inputEntityGroup.getId(); // TODO currently hardcoded. Later this id is to be taken from session User user = getUser(new Long(2L)); Collection<ServiceURLInterface> serviceCollection = user.getServiceURLCollection(); if (serviceCollection != null && !serviceCollection.isEmpty()) { for (ServiceURLInterface serviceURL : serviceCollection) { if (serviceURL.getEntityGroupInterface().getId() == inputEntityGroupId) { returnUrls.add(serviceURL.getUrlLocation()); } } } else { returnUrls = getAdminServiceUrls(inputEntityGroupId); } return returnUrls.toArray(new String[0]); } *//** * @param inputEntityGroupId * @return *//* public static Collection<String> getAdminServiceUrls(Long inputEntityGroupId) { Collection<String> adminReturnUrls = new HashSet<String>(); User user = getUser(new Long(1L)); Collection<ServiceURLInterface> serviceCollection = user.getServiceURLCollection(); for (ServiceURLInterface serviceURL : serviceCollection) { if (serviceURL.getEntityGroupInterface().getId() == inputEntityGroupId) { adminReturnUrls.add(serviceURL.getUrlLocation()); } } return adminReturnUrls; } *//** * @param id * @return *//* public static User getUser(Long id) { UserBusinessInterface userBusinessInterface = (UserBusinessInterface) CommonUtils.getBusinessInterface( EjbNamesConstants.USER_BEAN, UserHome.class, null); User user = null; try { user = userBusinessInterface.getUserById(id); } catch (RemoteException e) { e.printStackTrace(); } return user; }*/ /** * Returns the entity group of given entity * * @param entity * Entity to check * @return Returns parent Entity Group */ public static EntityGroupInterface getEntityGroup(EntityInterface entity) { for (EntityGroupInterface entityGroup : entity.getEntityGroupCollection()) { Collection<TaggedValueInterface> taggedValues = entityGroup.getTaggedValueCollection(); if (getTaggedValue(taggedValues, Constants.CAB2B_ENTITY_GROUP) != null) { return entityGroup; } } throw new RuntimeException("This entity does not have DE entity group", new java.lang.RuntimeException(), ErrorCodeConstants.DE_0003); } /** * @param taggedValues * collection of TaggedValueInterface * @param key * string * @return The tagged value for given key in given tagged value collection. */ public static TaggedValueInterface getTaggedValue( Collection<TaggedValueInterface> taggedValues, String key) { for (TaggedValueInterface taggedValue : taggedValues) { if (taggedValue.getKey().equals(key)) { return taggedValue; } } return null; } /** * @param taggable * taggable object * @param key * string * @return The tagged value for given key. */ public static TaggedValueInterface getTaggedValue(AbstractMetadataInterface taggable, String key) { return getTaggedValue(taggable.getTaggedValueCollection(), key); } /** * Checks whether passed Entity is a category or not. * * @param entity * Entity to check * @return Returns TRUE if given entity is Category, else returns false. */ public static boolean isCategory(EntityInterface entity) { TaggedValueInterface tag = getTaggedValue(entity.getTaggedValueCollection(), TYPE_CATEGORY); return tag != null; } /** * Converts DE data type to queryObject dataType. * * @param type * the DE attribute type. * @return the DataType. */ public static DataType getDataType(AttributeTypeInformationInterface type) { if (type instanceof StringAttributeTypeInformation) { return DataType.String; } else if (type instanceof DoubleAttributeTypeInformation) { return DataType.Double; } else if (type instanceof IntegerAttributeTypeInformation) { return DataType.Integer; } else if (type instanceof DateAttributeTypeInformation) { return DataType.Date; } else if (type instanceof FloatAttributeTypeInformation) { return DataType.Float; } else if (type instanceof BooleanAttributeTypeInformation) { return DataType.Boolean; } else if (type instanceof LongAttributeTypeInformation) { return DataType.Long; } else { throw new RuntimeException("Unknown Attribute type"); } } // RecordsTableModel.getColumnClass() has similar implementation. // public static Class<?> getJavaType(AttributeInterface attribute) { // DataType dataType = // Utility.getDataType(attribute.getAttributeTypeInformation()); // // if (dataType.equals(DataType.Date)) { // return DataType.String.getJavaType(); // } // // return dataType.getJavaType(); // } /** * @param attribute * Check will be done for this Attribute. * @return TRUE if there are any permissible values associated with this * attribute, otherwise returns false. */ public static boolean isEnumerated(AttributeInterface attribute) { if (attribute.getAttributeTypeInformation().getDataElement() instanceof UserDefinedDEInterface) { UserDefinedDEInterface de = (UserDefinedDEInterface) attribute .getAttributeTypeInformation().getDataElement(); return de.getPermissibleValueCollection().size() != 0; } return false; } /** * @param attribute * Attribute to process. * @return Returns all the permissible values associated with this * attribute. */ public static Collection<PermissibleValueInterface> getPermissibleValues( AttributeInterface attribute) { if (isEnumerated(attribute)) { UserDefinedDEInterface de = (UserDefinedDEInterface) attribute .getAttributeTypeInformation().getDataElement(); return de.getPermissibleValueCollection(); } return new ArrayList<PermissibleValueInterface>(0); } /** * Returns the display name if present as tagged value. Else returns the * actual name of the entity * * @param entity * The entity to process * @return The display name. */ public static String getDisplayName(EntityInterface entity) { String name = entity.getName(); if (isCategory(entity)) { return name; } EntityGroupInterface eg = getEntityGroup(entity); String version = ""; for (TaggedValueInterface tag : eg.getTaggedValueCollection()) { if (tag.getKey().equals(PROJECT_VERSION)) { version = tag.getValue(); break; } } // As per Bug# 4577 <class name> (app_name v<version name) e.g. // Participant (caTissue Core v1.1) String projectName = eg.getLongName(); if (projectName.equals("caFE Server 1.1")) { projectName = "caFE Server"; } StringBuffer buff = new StringBuffer(); buff.append(name.substring(name.lastIndexOf(".") + 1, name.length())); buff.append(" ("); buff.append(projectName); buff.append(" v"); buff.append(version); buff.append(")"); ; return buff.toString(); } /** * This method trims out packaceg name form the entity name * * @param entity * @return */ public static String getOnlyEntityName(EntityInterface entity) { String name = entity.getName(); String displayName = name.substring(name.lastIndexOf(".") + 1, name.length()); return displayName; } /** * @param path * A IPath object * @return Display string for given path */ public static String getPathDisplayString(IPath path) { String text = "<HTML><B>Path</B>:"; // text=text.concat("<HTML><B>Path</B>:"); List<IAssociation> pathList = path.getIntermediateAssociations(); text = text.concat(Utility.getDisplayName(path.getSourceEntity())); for (int i = 0; i < pathList.size(); i++) { text = text.concat("<B>----></B>"); text = text.concat(Utility.getDisplayName(pathList.get(i).getTargetEntity())); } text = text.concat("</HTML>"); Logger.out.debug(text); StringBuffer sb = new StringBuffer(); int textLength = text.length(); Logger.out.debug(textLength); int currentStart = 0; String currentString = null; int offset = 100; int strLen = 0; int len = 0; while (currentStart < textLength && textLength > offset) { currentString = text.substring(currentStart, (currentStart + offset)); strLen = strLen + currentString.length() + len; sb.append(currentString); int index = text.indexOf("<B>----></B>", (currentStart + offset)); if (index == -1) { index = text.indexOf(")", (currentStart + offset))+1; } if (index == -1) { index = text.indexOf(",", (currentStart + offset)); } if (index == -1) { index = text.indexOf(" ", (currentStart + offset)); } if (index != -1) { len = index - strLen; currentString = text.substring((currentStart + offset), (currentStart + offset + len)); sb.append(currentString); sb.append("<P>"); } else { if (currentStart == 0) { currentStart = offset; } sb.append(text.substring(currentStart)); return sb.toString(); } currentStart = currentStart + offset + len; if ((currentStart + offset + len) > textLength) break; } sb.append(text.substring(currentStart)); return sb.toString(); } /** * @param entity * Entity to check * @return Attribute whose name is "identifier" OR "id" */ public static AttributeInterface getIdAttribute(EntityInterface entity) { for (AttributeInterface attribute : entity.getAttributeCollection()) { if (isIdentifierAttribute(attribute)) { return attribute; } } return null; } // /** // * Returns true if an application returns associatied objects information // in // * result of CQLs. // * // * @param entity Entity to check // * @return true/false // */ // public static boolean isOutGoingAssociationSupported(EntityInterface // entity) { // EntityGroupInterface eg = getEntityGroup(entity); // String shortName = eg.getShortName(); // boolean isOutGoingAssociationSupported = false; // // String supportOutGoingAssociation = props.getProperty(shortName + // ".supportOutGoingAssociation"); // if (supportOutGoingAssociation != null && // supportOutGoingAssociation.equalsIgnoreCase("true")) { // isOutGoingAssociationSupported = true; // } // // return isOutGoingAssociationSupported; // } /** * @param entity * Entity to check * @return Name of the application to which given entity belongs */ public static String getApplicationName(EntityInterface entity) { return getEntityGroup(entity).getName(); } /** * @param attribute * Attribute to check * @return TRUE if attribute name is "identifier" OR "id" */ public static boolean isIdentifierAttribute(AttributeInterface attribute) { String attribName = attribute.getName(); return attribName.equalsIgnoreCase("id") || attribName.equalsIgnoreCase("identifier"); } /** * Converts attribute set into a alphabatically sorted list. * * @param inputAttributeSet * Attribute set to sort * @return Sorted list of attributes */ public static List<AttributeInterface> getAttributeList( Set<AttributeInterface> inputAttributeSet) { List<AttributeInterface> attributes = new ArrayList<AttributeInterface>(inputAttributeSet); Collections.sort(attributes, new AttributeInterfaceComparator()); return attributes; } // /** // * @param queryResult Query result to process. // * @return Total no of records present in query set (i.e for all services) // */ // public static int getNoOfRecords(IQueryResult queryResult) { // int size = 0; // Map<String, List<IRecord>> allRecords = queryResult.getRecords(); // // for (List<IRecord> valueList : allRecords.values()) { // size += valueList.size(); // } // return size; // } /** * @param queryResult * Query result to process. * @return List of attributes from query result */ public static List<AttributeInterface> getAttributeList(IQueryResult<IRecord> queryResult) { Map<String, List<IRecord>> allRecords = queryResult.getRecords(); List<AttributeInterface> attributeList = new ArrayList<AttributeInterface>(); for (List<IRecord> recordList : allRecords.values()) { if (!recordList.isEmpty()) { IRecord record = recordList.get(0); attributeList = getAttributeList(record.getAttributes()); break; } } return attributeList; } /** * This method converts stack trace to the string representation * * @param aThrowable * throwable object * @return String representation of the stack trace */ public static String getStackTrace(Throwable throwable) { final Writer result = new StringWriter(); final PrintWriter printWriter = new PrintWriter(result); throwable.printStackTrace(printWriter); return result.toString(); } /** * Get the specified resource first look into the cab2b.home otherwise look * into the classpath * * @param resource * the name of the resource * @return the URL for the resource * @throws MalformedURLException */ public static URL getResource(String resource) { String home = System.getProperty("cab2b.home"); File file = new File(home + "/conf", resource); if (file.exists()) { try { return file.toURI().toURL(); } catch (MalformedURLException e) { Logger.out.error("File not found in cab2b_home, will use default file ", e); } } // is there a better way of getting a non-null class loader ? ClassLoader loader = Utility.class.getClassLoader(); return loader.getResource(resource); } /** * @param queryName * @param values * @return * @throws HibernateException */ public static Collection<?> executeHQL(String queryName, List<Object> values) throws HibernateException { Session session = DBUtil.currentSession(); Query q = session.getNamedQuery(queryName); if (values != null) { for (int counter = 0; counter < values.size(); counter++) { Object value = values.get(counter); String objectType = value.getClass().getName(); String onlyClassName = objectType.substring(objectType.lastIndexOf(".") + 1, objectType.length()); if (onlyClassName.equals("String")) { q.setString(counter, (String) value); } else if (onlyClassName.equals("Integer")) { q.setInteger(counter, Integer.parseInt(value.toString())); } else if (onlyClassName.equals("Long")) { q.setLong(counter, Long.parseLong(value.toString())); } } } return q.list(); } /** * @param queryName * @return * @throws HibernateException */ public static Collection<?> executeHQL(String queryName) throws HibernateException { return executeHQL(queryName, null); } /** * This method replaces the occurrence of find string with replacement in * original string. * * @param original * @param find * @param replacement * @return */ public static String replaceAllWords(String original, String find, String replacement) { if (original == null || find == null || replacement == null) { return null; } for (int i = original.indexOf(find); i > -1;) { String partBefore = original.substring(0, i); String partAfter = original.substring(i + find.length()); original = partBefore + replacement + partAfter; i = original.indexOf(find, i + 1); } return original; } /** * Loads properties from a file present in classpath to java objects. * If any exception occurs, it is callers responsibility to handle it. * @param propertyfile Name of property file. It MUST be present in classpath * @return Properties loaded from given file. */ public static Properties getPropertiesFromFile(String propertyfile) { Properties properties = null; try { URL url = getResource(propertyfile); InputStream is = url.openStream(); if (is == null) { Logger.out.error("Unable fo find property file : " + propertyfile + "\n please put this file in classpath"); } properties = new Properties(); properties.load(is); } catch (IOException e) { Logger.out.error("Unable to load properties from : " + propertyfile); e.printStackTrace(); } return properties; } }
source/common/main/edu/wustl/cab2b/common/util/Utility.java
package edu.wustl.cab2b.common.util; import static edu.wustl.cab2b.common.util.Constants.CONNECTOR; import static edu.wustl.cab2b.common.util.Constants.PROJECT_VERSION; import static edu.wustl.cab2b.common.util.Constants.TYPE_CATEGORY; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.io.Writer; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.Session; import edu.common.dynamicextensions.domain.BooleanAttributeTypeInformation; import edu.common.dynamicextensions.domain.DateAttributeTypeInformation; import edu.common.dynamicextensions.domain.DoubleAttributeTypeInformation; import edu.common.dynamicextensions.domain.FloatAttributeTypeInformation; import edu.common.dynamicextensions.domain.IntegerAttributeTypeInformation; import edu.common.dynamicextensions.domain.LongAttributeTypeInformation; import edu.common.dynamicextensions.domain.StringAttributeTypeInformation; import edu.common.dynamicextensions.domaininterface.AbstractAttributeInterface; import edu.common.dynamicextensions.domaininterface.AbstractMetadataInterface; import edu.common.dynamicextensions.domaininterface.AssociationInterface; import edu.common.dynamicextensions.domaininterface.AttributeInterface; import edu.common.dynamicextensions.domaininterface.AttributeTypeInformationInterface; import edu.common.dynamicextensions.domaininterface.EntityGroupInterface; import edu.common.dynamicextensions.domaininterface.EntityInterface; import edu.common.dynamicextensions.domaininterface.PermissibleValueInterface; import edu.common.dynamicextensions.domaininterface.TaggedValueInterface; import edu.common.dynamicextensions.domaininterface.UserDefinedDEInterface; import edu.wustl.cab2b.common.errorcodes.ErrorCodeConstants; import edu.wustl.cab2b.common.exception.RuntimeException; import edu.wustl.cab2b.common.queryengine.result.IQueryResult; import edu.wustl.cab2b.common.queryengine.result.IRecord; import edu.wustl.common.querysuite.metadata.associations.IAssociation; import edu.wustl.common.querysuite.metadata.path.IPath; import edu.wustl.common.querysuite.queryobject.DataType; import edu.wustl.common.util.dbManager.DBUtil; import edu.wustl.common.util.logger.Logger; /** * Utility Class contain general methods used through out the application. * * @author Chandrakant Talele * @author Gautam Shetty */ public class Utility { /** * Checks whether passed attribute/association is inherited. * * @param abstractAttribute * Attribute/Association to check. * @return TRUE if it is inherited else returns FALSE */ public static boolean isInherited(AbstractAttributeInterface abstractAttribute) { for (TaggedValueInterface tag : abstractAttribute.getTaggedValueCollection()) { if (tag.getKey().equals(Constants.TYPE_DERIVED)) { return true; } } return false; } /** * Generates unique string identifier for given association. It is generated * by concatenating * * sourceEntityName +{@link Constants#CONNECTOR} + sourceRoleName +{@link Constants#CONNECTOR} + * targetRoleName +{@link Constants#CONNECTOR} + TargetEntityName * * @param association * Association * @return Unique string to represent given association */ public static String generateUniqueId(AssociationInterface association) { return concatStrings(association.getEntity().getName(), association.getSourceRole() .getName(), association.getTargetRole().getName(), association.getTargetEntity() .getName()); } /** * @param s1 * String * @param s2 * String * @param s3 * String * @param s4 * String * @return Concatenated string made after connecting s1, s2, s3, s4 by * {@link Constants#CONNECTOR} */ public static String concatStrings(String s1, String s2, String s3, String s4) { StringBuffer buff = new StringBuffer(); buff.append(s1); buff.append(CONNECTOR); buff.append(s2); buff.append(CONNECTOR); buff.append(s3); buff.append(CONNECTOR); buff.append(s4); return buff.toString(); } // /** // * Compares whether given searchPattern is present in passed searchString // * // * @param searchPattern search Pattern to look for // * @param searchString String which is to be searched // * @return Returns TRUE if given searchPattern is present in searchString // , // * else return returns false. // */ // public static boolean compareRegEx(String searchPattern, String // searchString) { // searchPattern = searchPattern.replace("*", ".*"); // Pattern pat = Pattern.compile(searchPattern, Pattern.CASE_INSENSITIVE); // Matcher mat = pat.matcher(searchString); // return mat.matches(); // } /** * Compares whether given searchPattern is present in passed searchString. * If it is present returns the position where match found. Otherwise it * returns -1. * * @param searchPattern * @param searchString * @return The position where match found, otherwise returns -1. */ public static int indexOfRegEx(String searchPattern, String searchString) { Pattern pat = Pattern.compile(searchPattern, Pattern.CASE_INSENSITIVE); Matcher mat = pat.matcher(searchString); int position = -1; if (mat.find()) { position = mat.start(); } return position; } /* *//** * Returns all the URLs of the data services which are exposing given entity * * @param entity * Entity to check * @return Returns the List of URLs *//* public static String[] getServiceURLS(EntityInterface entity) { EntityGroupInterface eg = getEntityGroup(entity); String longName = eg.getLongName(); return getServiceURLs(longName); } *//** * Returns all the URLs of the data services which are confirming model of * given application * * @param appName * Aplication name * @return Returns the List of URLs *//* public static String[] getServiceURLs(String appName) { EntityGroupInterface inputEntityGroup = null; Collection<String> returnUrls = new HashSet<String>(); try { inputEntityGroup = EntityManager.getInstance().getEntityGroupByName(appName); } catch (DynamicExtensionsSystemException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (DynamicExtensionsApplicationException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } Long inputEntityGroupId = inputEntityGroup.getId(); // TODO currently hardcoded. Later this id is to be taken from session User user = getUser(new Long(2L)); Collection<ServiceURLInterface> serviceCollection = user.getServiceURLCollection(); if (serviceCollection != null && !serviceCollection.isEmpty()) { for (ServiceURLInterface serviceURL : serviceCollection) { if (serviceURL.getEntityGroupInterface().getId() == inputEntityGroupId) { returnUrls.add(serviceURL.getUrlLocation()); } } } else { returnUrls = getAdminServiceUrls(inputEntityGroupId); } return returnUrls.toArray(new String[0]); } *//** * @param inputEntityGroupId * @return *//* public static Collection<String> getAdminServiceUrls(Long inputEntityGroupId) { Collection<String> adminReturnUrls = new HashSet<String>(); User user = getUser(new Long(1L)); Collection<ServiceURLInterface> serviceCollection = user.getServiceURLCollection(); for (ServiceURLInterface serviceURL : serviceCollection) { if (serviceURL.getEntityGroupInterface().getId() == inputEntityGroupId) { adminReturnUrls.add(serviceURL.getUrlLocation()); } } return adminReturnUrls; } *//** * @param id * @return *//* public static User getUser(Long id) { UserBusinessInterface userBusinessInterface = (UserBusinessInterface) CommonUtils.getBusinessInterface( EjbNamesConstants.USER_BEAN, UserHome.class, null); User user = null; try { user = userBusinessInterface.getUserById(id); } catch (RemoteException e) { e.printStackTrace(); } return user; }*/ /** * Returns the entity group of given entity * * @param entity * Entity to check * @return Returns parent Entity Group */ public static EntityGroupInterface getEntityGroup(EntityInterface entity) { for (EntityGroupInterface entityGroup : entity.getEntityGroupCollection()) { Collection<TaggedValueInterface> taggedValues = entityGroup.getTaggedValueCollection(); if (getTaggedValue(taggedValues, Constants.CAB2B_ENTITY_GROUP) != null) { return entityGroup; } } throw new RuntimeException("This entity does not have DE entity group", new java.lang.RuntimeException(), ErrorCodeConstants.DE_0003); } /** * @param taggedValues * collection of TaggedValueInterface * @param key * string * @return The tagged value for given key in given tagged value collection. */ public static TaggedValueInterface getTaggedValue( Collection<TaggedValueInterface> taggedValues, String key) { for (TaggedValueInterface taggedValue : taggedValues) { if (taggedValue.getKey().equals(key)) { return taggedValue; } } return null; } /** * @param taggable * taggable object * @param key * string * @return The tagged value for given key. */ public static TaggedValueInterface getTaggedValue(AbstractMetadataInterface taggable, String key) { return getTaggedValue(taggable.getTaggedValueCollection(), key); } /** * Checks whether passed Entity is a category or not. * * @param entity * Entity to check * @return Returns TRUE if given entity is Category, else returns false. */ public static boolean isCategory(EntityInterface entity) { TaggedValueInterface tag = getTaggedValue(entity.getTaggedValueCollection(), TYPE_CATEGORY); return tag != null; } /** * Converts DE data type to queryObject dataType. * * @param type * the DE attribute type. * @return the DataType. */ public static DataType getDataType(AttributeTypeInformationInterface type) { if (type instanceof StringAttributeTypeInformation) { return DataType.String; } else if (type instanceof DoubleAttributeTypeInformation) { return DataType.Double; } else if (type instanceof IntegerAttributeTypeInformation) { return DataType.Integer; } else if (type instanceof DateAttributeTypeInformation) { return DataType.Date; } else if (type instanceof FloatAttributeTypeInformation) { return DataType.Float; } else if (type instanceof BooleanAttributeTypeInformation) { return DataType.Boolean; } else if (type instanceof LongAttributeTypeInformation) { return DataType.Long; } else { throw new RuntimeException("Unknown Attribute type"); } } // RecordsTableModel.getColumnClass() has similar implementation. // public static Class<?> getJavaType(AttributeInterface attribute) { // DataType dataType = // Utility.getDataType(attribute.getAttributeTypeInformation()); // // if (dataType.equals(DataType.Date)) { // return DataType.String.getJavaType(); // } // // return dataType.getJavaType(); // } /** * @param attribute * Check will be done for this Attribute. * @return TRUE if there are any permissible values associated with this * attribute, otherwise returns false. */ public static boolean isEnumerated(AttributeInterface attribute) { if (attribute.getAttributeTypeInformation().getDataElement() instanceof UserDefinedDEInterface) { UserDefinedDEInterface de = (UserDefinedDEInterface) attribute .getAttributeTypeInformation().getDataElement(); return de.getPermissibleValueCollection().size() != 0; } return false; } /** * @param attribute * Attribute to process. * @return Returns all the permissible values associated with this * attribute. */ public static Collection<PermissibleValueInterface> getPermissibleValues( AttributeInterface attribute) { if (isEnumerated(attribute)) { UserDefinedDEInterface de = (UserDefinedDEInterface) attribute .getAttributeTypeInformation().getDataElement(); return de.getPermissibleValueCollection(); } return new ArrayList<PermissibleValueInterface>(0); } /** * Returns the display name if present as tagged value. Else returns the * actual name of the entity * * @param entity * The entity to process * @return The display name. */ public static String getDisplayName(EntityInterface entity) { String name = entity.getName(); if (isCategory(entity)) { return name; } EntityGroupInterface eg = getEntityGroup(entity); String version = ""; for (TaggedValueInterface tag : eg.getTaggedValueCollection()) { if (tag.getKey().equals(PROJECT_VERSION)) { version = tag.getValue(); break; } } // As per Bug# 4577 <class name> (app_name v<version name) e.g. // Participant (caTissue Core v1.1) String projectName = eg.getLongName(); if (projectName.equals("caFE Server 1.1")) { projectName = "caFE Server"; } StringBuffer buff = new StringBuffer(); buff.append(name.substring(name.lastIndexOf(".") + 1, name.length())); buff.append(" ("); buff.append(projectName); buff.append(" v"); buff.append(version); buff.append(")"); ; return buff.toString(); } /** * This method trims out packaceg name form the entity name * * @param entity * @return */ public static String getOnlyEntityName(EntityInterface entity) { String name = entity.getName(); String displayName = name.substring(name.lastIndexOf(".") + 1, name.length()); return displayName; } /** * @param path * A IPath object * @return Display string for given path */ public static String getPathDisplayString(IPath path) { String text = "<HTML><B>Path</B>:"; // text=text.concat("<HTML><B>Path</B>:"); List<IAssociation> pathList = path.getIntermediateAssociations(); text = text.concat(Utility.getDisplayName(path.getSourceEntity())); for (int i = 0; i < pathList.size(); i++) { text = text.concat("<B>----></B>"); text = text.concat(Utility.getDisplayName(pathList.get(i).getTargetEntity())); } text = text.concat("</HTML>"); Logger.out.debug(text); StringBuffer sb = new StringBuffer(); int textLength = text.length(); Logger.out.debug(textLength); int currentStart = 0; String currentString = null; int offset = 100; int strLen = 0; int len = 0; while (currentStart < textLength && textLength > offset) { currentString = text.substring(currentStart, (currentStart + offset)); strLen = strLen + currentString.length() + len; sb.append(currentString); int index = text.indexOf("<B>----></B>", (currentStart + offset)); if (index == -1) { index = text.indexOf(".", (currentStart + offset)); } if (index == -1) { index = text.indexOf(",", (currentStart + offset)); } if (index == -1) { index = text.indexOf(" ", (currentStart + offset)); } if (index != -1) { len = index - strLen; currentString = text.substring((currentStart + offset), (currentStart + offset + len)); sb.append(currentString); sb.append("<P>"); } else { if (currentStart == 0) { currentStart = offset; } sb.append(text.substring(currentStart)); return sb.toString(); } currentStart = currentStart + offset + len; if ((currentStart + offset + len) > textLength) break; } sb.append(text.substring(currentStart)); return sb.toString(); } /** * @param entity * Entity to check * @return Attribute whose name is "identifier" OR "id" */ public static AttributeInterface getIdAttribute(EntityInterface entity) { for (AttributeInterface attribute : entity.getAttributeCollection()) { if (isIdentifierAttribute(attribute)) { return attribute; } } return null; } // /** // * Returns true if an application returns associatied objects information // in // * result of CQLs. // * // * @param entity Entity to check // * @return true/false // */ // public static boolean isOutGoingAssociationSupported(EntityInterface // entity) { // EntityGroupInterface eg = getEntityGroup(entity); // String shortName = eg.getShortName(); // boolean isOutGoingAssociationSupported = false; // // String supportOutGoingAssociation = props.getProperty(shortName + // ".supportOutGoingAssociation"); // if (supportOutGoingAssociation != null && // supportOutGoingAssociation.equalsIgnoreCase("true")) { // isOutGoingAssociationSupported = true; // } // // return isOutGoingAssociationSupported; // } /** * @param entity * Entity to check * @return Name of the application to which given entity belongs */ public static String getApplicationName(EntityInterface entity) { return getEntityGroup(entity).getName(); } /** * @param attribute * Attribute to check * @return TRUE if attribute name is "identifier" OR "id" */ public static boolean isIdentifierAttribute(AttributeInterface attribute) { String attribName = attribute.getName(); return attribName.equalsIgnoreCase("id") || attribName.equalsIgnoreCase("identifier"); } /** * Converts attribute set into a alphabatically sorted list. * * @param inputAttributeSet * Attribute set to sort * @return Sorted list of attributes */ public static List<AttributeInterface> getAttributeList( Set<AttributeInterface> inputAttributeSet) { List<AttributeInterface> attributes = new ArrayList<AttributeInterface>(inputAttributeSet); Collections.sort(attributes, new AttributeInterfaceComparator()); return attributes; } // /** // * @param queryResult Query result to process. // * @return Total no of records present in query set (i.e for all services) // */ // public static int getNoOfRecords(IQueryResult queryResult) { // int size = 0; // Map<String, List<IRecord>> allRecords = queryResult.getRecords(); // // for (List<IRecord> valueList : allRecords.values()) { // size += valueList.size(); // } // return size; // } /** * @param queryResult * Query result to process. * @return List of attributes from query result */ public static List<AttributeInterface> getAttributeList(IQueryResult<IRecord> queryResult) { Map<String, List<IRecord>> allRecords = queryResult.getRecords(); List<AttributeInterface> attributeList = new ArrayList<AttributeInterface>(); for (List<IRecord> recordList : allRecords.values()) { if (!recordList.isEmpty()) { IRecord record = recordList.get(0); attributeList = getAttributeList(record.getAttributes()); break; } } return attributeList; } /** * This method converts stack trace to the string representation * * @param aThrowable * throwable object * @return String representation of the stack trace */ public static String getStackTrace(Throwable throwable) { final Writer result = new StringWriter(); final PrintWriter printWriter = new PrintWriter(result); throwable.printStackTrace(printWriter); return result.toString(); } /** * Get the specified resource first look into the cab2b.home otherwise look * into the classpath * * @param resource * the name of the resource * @return the URL for the resource * @throws MalformedURLException */ public static URL getResource(String resource) { String home = System.getProperty("cab2b.home"); File file = new File(home + "/conf", resource); if (file.exists()) { try { return file.toURI().toURL(); } catch (MalformedURLException e) { Logger.out.error("File not found in cab2b_home, will use default file ", e); } } // is there a better way of getting a non-null class loader ? ClassLoader loader = Utility.class.getClassLoader(); return loader.getResource(resource); } /** * @param queryName * @param values * @return * @throws HibernateException */ public static Collection<?> executeHQL(String queryName, List<Object> values) throws HibernateException { Session session = DBUtil.currentSession(); Query q = session.getNamedQuery(queryName); if (values != null) { for (int counter = 0; counter < values.size(); counter++) { Object value = values.get(counter); String objectType = value.getClass().getName(); String onlyClassName = objectType.substring(objectType.lastIndexOf(".") + 1, objectType.length()); if (onlyClassName.equals("String")) { q.setString(counter, (String) value); } else if (onlyClassName.equals("Integer")) { q.setInteger(counter, Integer.parseInt(value.toString())); } else if (onlyClassName.equals("Long")) { q.setLong(counter, Long.parseLong(value.toString())); } } } return q.list(); } /** * @param queryName * @return * @throws HibernateException */ public static Collection<?> executeHQL(String queryName) throws HibernateException { return executeHQL(queryName, null); } /** * This method replaces the occurrence of find string with replacement in * original string. * * @param original * @param find * @param replacement * @return */ public static String replaceAllWords(String original, String find, String replacement) { if (original == null || find == null || replacement == null) { return null; } for (int i = original.indexOf(find); i > -1;) { String partBefore = original.substring(0, i); String partAfter = original.substring(i + find.length()); original = partBefore + replacement + partAfter; i = original.indexOf(find, i + 1); } return original; } /** * Loads properties from a file present in classpath to java objects. * If any exception occurs, it is callers responsibility to handle it. * @param propertyfile Name of property file. It MUST be present in classpath * @return Properties loaded from given file. */ public static Properties getPropertiesFromFile(String propertyfile) { Properties properties = null; try { URL url = getResource(propertyfile); InputStream is = url.openStream(); if (is == null) { Logger.out.error("Unable fo find property file : " + propertyfile + "\n please put this file in classpath"); } properties = new Properties(); properties.load(is); } catch (IOException e) { Logger.out.error("Unable to load properties from : " + propertyfile); e.printStackTrace(); } return properties; } }
Bug 4584
source/common/main/edu/wustl/cab2b/common/util/Utility.java
Bug 4584
<ide><path>ource/common/main/edu/wustl/cab2b/common/util/Utility.java <ide> sb.append(currentString); <ide> int index = text.indexOf("<B>----></B>", (currentStart + offset)); <ide> if (index == -1) { <del> index = text.indexOf(".", (currentStart + offset)); <add> index = text.indexOf(")", (currentStart + offset))+1; <ide> } <ide> if (index == -1) { <ide> index = text.indexOf(",", (currentStart + offset));
JavaScript
bsd-3-clause
c63eb3fda7932f525a3613480c39129b51051b9f
0
amigocloud/modeify,tismart/modeify,tismart/modeify,amigocloud/modeify,tismart/modeify,amigocloud/modified-tripplanner,amigocloud/modeify,amigocloud/modeify,tismart/modeify,amigocloud/modified-tripplanner,amigocloud/modified-tripplanner,amigocloud/modified-tripplanner
var Batch = require('batch'); var debounce = require('debounce'); var geocode = require('geocode'); var Journey = require('journey'); var Location = require('location'); var log = require('./client/log')('plan'); var defaults = require('model-defaults'); var model = require('model'); var ProfileQuery = require('profile-query'); var ProfileScorer = require('otp-profile-score'); var qs = require('querystring'); var get = require('./client/request').get; var loadPlan = require('./load'); var store = require('./store'); var updateRoutes = require('./update-routes'); /** * Debounce updates to once every 50ms */ var DEBOUNCE_UPDATES = 5; var LIMIT = 2; /** * Expose `Plan` */ var Plan = module.exports = model('Plan') .use(defaults({ bike: true, bikeShare: false, bus: true, car: false, days: 'M—F', end_time: (new Date()).getHours() + 4, from: '', from_valid: false, loading: true, options: [], query: new ProfileQuery(), scorer: new ProfileScorer(), start_time: (new Date()).getHours() - 1, to: '', to_valid: false, train: true, tripsPerYear: 235, walk: true })) .attr('bike') .attr('bikeShare') .attr('bus') .attr('car') .attr('days') .attr('end_time') .attr('from') .attr('from_id') .attr('from_ll') .attr('from_valid') .attr('loading') .attr('journey') .attr('options') .attr('query') .attr('scorer') .attr('start_time') .attr('to') .attr('to_id') .attr('to_ll') .attr('to_valid') .attr('train') .attr('tripsPerYear') .attr('walk'); /** * Expose `load` */ module.exports.load = function(ctx, next) { loadPlan(Plan, ctx, next); }; /** * Sync plans with localStorage */ Plan.on('change', function(plan, name, val) { log('plan.%s changed to %s', name, val); // Store in localStorage & track the change if (name !== 'options' && name !== 'journey' && name !== 'loading') plan.store(); }); /** * Keep start/end times in sync */ Plan.on('change start_time', function(plan, val, prev) { if (val >= plan.end_time()) plan.end_time(val + 1); }); Plan.on('change end_time', function(plan, val, prev) { if (val <= plan.start_time()) plan.start_time(val - 1); }); /** * Update routes. Restrict to once every 25ms. */ Plan.prototype.updateRoutes = debounce(function(opts, callback) { updateRoutes(this, opts, callback); }, DEBOUNCE_UPDATES); /** * Geocode */ Plan.prototype.geocode = function(dest, callback) { if (!callback) callback = function() {}; var plan = this; var address = plan[dest](); var ll = plan[dest + '_ll'](); if (address && address.length > 0) { geocode(address, function(err, ll) { if (err) { callback(err); } else { plan[dest + '_ll'](ll); callback(null, ll); } }); } else { callback(null, ll); } }; /** * Save Journey */ Plan.prototype.saveJourney = function(callback) { var opts = {}; var skipKeys = ['options', 'journey', 'scorer']; for (var key in this.attrs) { if (skipKeys.indexOf(key) !== -1 || key.indexOf('to') === 0 || key.indexOf('from') === 0) { continue; } opts[key] = this.attrs[key]; } // Create new journey var journey = new Journey({ locations: [{ _id: this.from_id() }, { _id: this.to_id() }], opts: opts }); // Save journey.save(callback); }; /** * Valid coordinates */ Plan.prototype.validCoordinates = function() { return this.coordinateIsValid(this.from_ll()) && this.coordinateIsValid(this.to_ll()); }; /** * Set Address */ Plan.prototype.setAddress = function(name, address, callback, extra) { console.log("name", name); console.log("address", address); console.log("callback", callback); console.log("extra", extra); callback = callback || function() {}; // noop callback var location = new Location(); var plan = this; var c = address.split(','); var isCoordinate = c.length === 2 && !isNaN(parseFloat(c[0])) && !isNaN(parseFloat(c[1])); if (!address || address.length < 1) return callback(); console.log("Location declarada ->", location); console.log("HOLA BEBE", geocode.reverseAmigo(c, callback)); if (isCoordinate) { location.coordinate({ lat: parseFloat(c[1]), lng: parseFloat(c[0]) }); var callbackAmigo = function (err, reverse) { console.log("Ahora si llama", reverse); if (reverse) { console.log("ejecuta reverse -> ", reverse); var geocode_features = reverse.features; var changes = {}; if (isCoordinate) changes[name] = geocode_features[0].properties.label; else changes[name] = address; changes[name + '_ll'] = {lat: parseFloat(geocode_features[0].geometry.coordinates[1]), lng: parseFloat(geocode_features[0].geometry.coordinates[0])}; changes[name + '_id'] = geocode_features[0].properties.id; changes[name + '_valid'] = true; console.log("CHANGES PLAN SET", changes); plan.set(changes); callback(null, res.body); } else { if (isCoordinate) { var changes = {}; changes[name] = extra.properties.label; changes[name + '_ll'] = location.coordinate(); changes[name + '_valid'] = true; plan.set(changes); callback(null, extra); } else { callback(err); } } } geocode.reverseAmigo(c, callbackAmigo); //}); }else { plan.setAddress('', '', callback); } }; /** * Set both addresses */ Plan.prototype.setAddresses = function(from, to, callback) { // Initialize the default locations var plan = this; Batch() .push(function(done) { plan.setAddress('from', from, done); }) .push(function(done) { plan.setAddress('to', to, done); }).end(callback); }; /** * Rescore Options */ Plan.prototype.rescoreOptions = function() { var scorer = this.scorer(); var options = this.options(); options.forEach(function(o) { o.rescore(scorer); }); this.store(); }; /** * To Lower Case */ function toLowerCase(s) { return s ? s.toLowerCase() : ''; } Plan.prototype.coordinateIsValid = function(c) { return !!c && !!parseFloat(c.lat) && !!parseFloat(c.lng) && parseFloat(c.lat) !== 0.0 && parseFloat(c.lng) !== 0.0; }; /** * Modes as a CSV */ Plan.prototype.modesCSV = function() { var modes = []; if (this.bike()) modes.push('BICYCLE'); if (this.bikeShare()) modes.push('BICYCLE_RENT'); if (this.bus()) modes.push('BUSISH'); if (this.train()) modes.push('TRAINISH'); if (this.walk()) modes.push('WALK'); if (this.car()) modes.push('CAR'); return modes.join(','); }; /** * Set modes from string */ Plan.prototype.setModes = function(csv) { if (!csv || csv.length < 1) return; var modes = csv.split ? csv.split(',') : csv; this.bike(modes.indexOf('BICYCLE') !== -1); // this.bikeShare(modes.indexOf('BICYCLE_RENT') !== -1); this.bikeShare(false); this.bus(true); // this.bus(modes.indexOf('BUSISH') !== -1); this.train(modes.indexOf('TRAINISH') !== -1); this.car(modes.indexOf('CAR') !== -1); }; /** * Generate Query Parameters for this plan */ Plan.prototype.generateQuery = function() { var from = this.from_ll() || {}; var to = this.to_ll() || {}; // Transit modes var modes = [];//['WALK']; if (this.bikeShare()) modes.push('BICYCLE_RENT'); if (this.car()) { modes.push('CAR'); } if (this.bike()) { modes.push('BICYCLE'); } else { modes.push('WALK'); } if (this.bus()) modes.push('BUSISH'); if (this.train()) modes.push('TRAINISH'); if (modes.length==0) modes.push('WALK'); var startTime = this.start_time(); var endTime = this.end_time(); var scorer = this.scorer(); // Convert the hours into strings startTime += ':00'; endTime = endTime === 24 ? '23:59' : endTime + ':00'; return { date: this.nextDate(), mode: modes.join(','), time: startTime, fromPlace: (from.lat + ',' + from.lng), toPlace: (to.lat + ',' + to.lng), numItineraries: 3, maxWalkDistance: 20000, bikeSpeed: 10, bikeBoardCost: 15, walkReluctance: 10, clampInitialWait: 60, // waitAtBeginningFactor: 0.5, triangleSafetyFactor: 0.9, triangleSlopeFactor: 0.5, triangleTimeFactor: 0.9, optimize: 'QUICK' }; }; /** * Store in localStorage. Restrict this I/O to once every 25ms. */ Plan.prototype.store = debounce(function() { store(this); }, DEBOUNCE_UPDATES); /** * Clear localStorage */ Plan.prototype.clearStore = store.clear; /** * Save URL */ Plan.prototype.saveURL = function() { console.log("Query planer change ciudad -> ", this.generateQueryString()); window.history.replaceState(null, '', '/planner?' + this.generateQueryString()); }; /** * Get next date for day of the week */ Plan.prototype.nextDate = function() { var now = new Date(); var date = now.getDate(); var dayOfTheWeek = now.getDay(); switch (this.days()) { case 'M—F': if (dayOfTheWeek === 0) now.setDate(date + 1); if (dayOfTheWeek === 6) now.setDate(date + 2); break; case 'Sat': now.setDate(date + (6 - dayOfTheWeek)); break; case 'Sun': now.setDate(date + (7 - dayOfTheWeek)); break; } return now.toISOString().split('T')[0]; }; /** * Generate `places` for transitive */ Plan.prototype.generatePlaces = function() { var fll = this.from_ll(); var tll = this.to_ll(); if (!fll || !tll) return []; return [{ place_id: 'from', place_lat: fll.lat, place_lon: fll.lng, place_name: 'From' }, { place_id: 'to', place_lat: tll.lat, place_lon: tll.lng, place_name: 'To' }]; }; /** * Generate QueryString */ Plan.prototype.generateQueryString = function() { return qs.stringify({ from: this.from(), to: this.to(), modes: this.modesCSV(), start_time: this.start_time(), end_time: this.end_time(), days: this.days() }); };
client/plan/index.js
var Batch = require('batch'); var debounce = require('debounce'); var geocode = require('geocode'); var Journey = require('journey'); var Location = require('location'); var log = require('./client/log')('plan'); var defaults = require('model-defaults'); var model = require('model'); var ProfileQuery = require('profile-query'); var ProfileScorer = require('otp-profile-score'); var qs = require('querystring'); var get = require('./client/request').get; var loadPlan = require('./load'); var store = require('./store'); var updateRoutes = require('./update-routes'); /** * Debounce updates to once every 50ms */ var DEBOUNCE_UPDATES = 5; var LIMIT = 2; /** * Expose `Plan` */ var Plan = module.exports = model('Plan') .use(defaults({ bike: true, bikeShare: false, bus: true, car: false, days: 'M—F', end_time: (new Date()).getHours() + 4, from: '', from_valid: false, loading: true, options: [], query: new ProfileQuery(), scorer: new ProfileScorer(), start_time: (new Date()).getHours() - 1, to: '', to_valid: false, train: true, tripsPerYear: 235, walk: true })) .attr('bike') .attr('bikeShare') .attr('bus') .attr('car') .attr('days') .attr('end_time') .attr('from') .attr('from_id') .attr('from_ll') .attr('from_valid') .attr('loading') .attr('journey') .attr('options') .attr('query') .attr('scorer') .attr('start_time') .attr('to') .attr('to_id') .attr('to_ll') .attr('to_valid') .attr('train') .attr('tripsPerYear') .attr('walk'); /** * Expose `load` */ module.exports.load = function(ctx, next) { loadPlan(Plan, ctx, next); }; /** * Sync plans with localStorage */ Plan.on('change', function(plan, name, val) { log('plan.%s changed to %s', name, val); // Store in localStorage & track the change if (name !== 'options' && name !== 'journey' && name !== 'loading') plan.store(); }); /** * Keep start/end times in sync */ Plan.on('change start_time', function(plan, val, prev) { if (val >= plan.end_time()) plan.end_time(val + 1); }); Plan.on('change end_time', function(plan, val, prev) { if (val <= plan.start_time()) plan.start_time(val - 1); }); /** * Update routes. Restrict to once every 25ms. */ Plan.prototype.updateRoutes = debounce(function(opts, callback) { updateRoutes(this, opts, callback); }, DEBOUNCE_UPDATES); /** * Geocode */ Plan.prototype.geocode = function(dest, callback) { if (!callback) callback = function() {}; var plan = this; var address = plan[dest](); var ll = plan[dest + '_ll'](); if (address && address.length > 0) { geocode(address, function(err, ll) { if (err) { callback(err); } else { plan[dest + '_ll'](ll); callback(null, ll); } }); } else { callback(null, ll); } }; /** * Save Journey */ Plan.prototype.saveJourney = function(callback) { var opts = {}; var skipKeys = ['options', 'journey', 'scorer']; for (var key in this.attrs) { if (skipKeys.indexOf(key) !== -1 || key.indexOf('to') === 0 || key.indexOf('from') === 0) { continue; } opts[key] = this.attrs[key]; } // Create new journey var journey = new Journey({ locations: [{ _id: this.from_id() }, { _id: this.to_id() }], opts: opts }); // Save journey.save(callback); }; /** * Valid coordinates */ Plan.prototype.validCoordinates = function() { return this.coordinateIsValid(this.from_ll()) && this.coordinateIsValid(this.to_ll()); }; /** * Set Address */ Plan.prototype.setAddress = function(name, address, callback, extra) { console.log("name", name); console.log("address", address); console.log("callback", callback); console.log("extra", extra); callback = callback || function() {}; // noop callback var location = new Location(); var plan = this; var c = address.split(','); var isCoordinate = c.length === 2 && !isNaN(parseFloat(c[0])) && !isNaN(parseFloat(c[1])); if (!address || address.length < 1) return callback(); console.log("Location declarada ->", location); console.log("HOLA BEBE", geocode.reverseAmigo(c, callback)); if (isCoordinate) { location.coordinate({ lat: parseFloat(c[1]), lng: parseFloat(c[0]) }); var callbackAmigo = function (err, reverse) { console.log("Ahora si llama", reverse); if (reserve) { console.log("ejecuta reverse -> ", reverse); var geocode_features = reserve.features; var changes = {}; if (isCoordinate) changes[name] = geocode_features[0].properties.label; else changes[name] = address; changes[name + '_ll'] = {lat: parseFloat(geocode_features[0].geometry.coordinates[1]), lng: parseFloat(geocode_features[0].geometry.coordinates[0])}; changes[name + '_id'] = geocode_features[0].properties.id; changes[name + '_valid'] = true; console.log("CHANGES PLAN SET", changes); plan.set(changes); callback(null, res.body); } else { if (isCoordinate) { var changes = {}; changes[name] = extra.properties.label; changes[name + '_ll'] = location.coordinate(); changes[name + '_valid'] = true; plan.set(changes); callback(null, extra); } else { callback(err); } } } // get("https://www.amigocloud.com/api/v1/me/geocoder/reverse?token=R:DNiePlGOMsw93cEgde88woWAQxm1xzWt7lvVXe&point.lon="+ c[0] + "&point.lat="+c[1], function(err, res) { //callbackAmigo(); var reserve = geocode.reverseAmigo(c, callbackAmigo); //}); }else { plan.setAddress('', '', callback); } }; /** * Set both addresses */ Plan.prototype.setAddresses = function(from, to, callback) { // Initialize the default locations var plan = this; Batch() .push(function(done) { plan.setAddress('from', from, done); }) .push(function(done) { plan.setAddress('to', to, done); }).end(callback); }; /** * Rescore Options */ Plan.prototype.rescoreOptions = function() { var scorer = this.scorer(); var options = this.options(); options.forEach(function(o) { o.rescore(scorer); }); this.store(); }; /** * To Lower Case */ function toLowerCase(s) { return s ? s.toLowerCase() : ''; } Plan.prototype.coordinateIsValid = function(c) { return !!c && !!parseFloat(c.lat) && !!parseFloat(c.lng) && parseFloat(c.lat) !== 0.0 && parseFloat(c.lng) !== 0.0; }; /** * Modes as a CSV */ Plan.prototype.modesCSV = function() { var modes = []; if (this.bike()) modes.push('BICYCLE'); if (this.bikeShare()) modes.push('BICYCLE_RENT'); if (this.bus()) modes.push('BUSISH'); if (this.train()) modes.push('TRAINISH'); if (this.walk()) modes.push('WALK'); if (this.car()) modes.push('CAR'); return modes.join(','); }; /** * Set modes from string */ Plan.prototype.setModes = function(csv) { if (!csv || csv.length < 1) return; var modes = csv.split ? csv.split(',') : csv; this.bike(modes.indexOf('BICYCLE') !== -1); // this.bikeShare(modes.indexOf('BICYCLE_RENT') !== -1); this.bikeShare(false); this.bus(true); // this.bus(modes.indexOf('BUSISH') !== -1); this.train(modes.indexOf('TRAINISH') !== -1); this.car(modes.indexOf('CAR') !== -1); }; /** * Generate Query Parameters for this plan */ Plan.prototype.generateQuery = function() { var from = this.from_ll() || {}; var to = this.to_ll() || {}; // Transit modes var modes = [];//['WALK']; if (this.bikeShare()) modes.push('BICYCLE_RENT'); if (this.car()) { modes.push('CAR'); } if (this.bike()) { modes.push('BICYCLE'); } else { modes.push('WALK'); } if (this.bus()) modes.push('BUSISH'); if (this.train()) modes.push('TRAINISH'); if (modes.length==0) modes.push('WALK'); var startTime = this.start_time(); var endTime = this.end_time(); var scorer = this.scorer(); // Convert the hours into strings startTime += ':00'; endTime = endTime === 24 ? '23:59' : endTime + ':00'; return { date: this.nextDate(), mode: modes.join(','), time: startTime, fromPlace: (from.lat + ',' + from.lng), toPlace: (to.lat + ',' + to.lng), numItineraries: 3, maxWalkDistance: 20000, bikeSpeed: 10, bikeBoardCost: 15, walkReluctance: 10, clampInitialWait: 60, // waitAtBeginningFactor: 0.5, triangleSafetyFactor: 0.9, triangleSlopeFactor: 0.5, triangleTimeFactor: 0.9, optimize: 'QUICK' }; }; /** * Store in localStorage. Restrict this I/O to once every 25ms. */ Plan.prototype.store = debounce(function() { store(this); }, DEBOUNCE_UPDATES); /** * Clear localStorage */ Plan.prototype.clearStore = store.clear; /** * Save URL */ Plan.prototype.saveURL = function() { console.log("Query planer change ciudad -> ", this.generateQueryString()); window.history.replaceState(null, '', '/planner?' + this.generateQueryString()); }; /** * Get next date for day of the week */ Plan.prototype.nextDate = function() { var now = new Date(); var date = now.getDate(); var dayOfTheWeek = now.getDay(); switch (this.days()) { case 'M—F': if (dayOfTheWeek === 0) now.setDate(date + 1); if (dayOfTheWeek === 6) now.setDate(date + 2); break; case 'Sat': now.setDate(date + (6 - dayOfTheWeek)); break; case 'Sun': now.setDate(date + (7 - dayOfTheWeek)); break; } return now.toISOString().split('T')[0]; }; /** * Generate `places` for transitive */ Plan.prototype.generatePlaces = function() { var fll = this.from_ll(); var tll = this.to_ll(); if (!fll || !tll) return []; return [{ place_id: 'from', place_lat: fll.lat, place_lon: fll.lng, place_name: 'From' }, { place_id: 'to', place_lat: tll.lat, place_lon: tll.lng, place_name: 'To' }]; }; /** * Generate QueryString */ Plan.prototype.generateQueryString = function() { return qs.stringify({ from: this.from(), to: this.to(), modes: this.modesCSV(), start_time: this.start_time(), end_time: this.end_time(), days: this.days() }); };
fixed bug reverse geocode
client/plan/index.js
fixed bug reverse geocode
<ide><path>lient/plan/index.js <ide> lat: parseFloat(c[1]), <ide> lng: parseFloat(c[0]) <ide> }); <add> <ide> var callbackAmigo = function (err, reverse) { <ide> console.log("Ahora si llama", reverse); <del> if (reserve) { <add> if (reverse) { <add> <ide> console.log("ejecuta reverse -> ", reverse); <del> var geocode_features = reserve.features; <add> <add> var geocode_features = reverse.features; <ide> var changes = {}; <ide> if (isCoordinate) <ide> changes[name] = geocode_features[0].properties.label; <ide> <ide> } <ide> } <del> // get("https://www.amigocloud.com/api/v1/me/geocoder/reverse?token=R:DNiePlGOMsw93cEgde88woWAQxm1xzWt7lvVXe&point.lon="+ c[0] + "&point.lat="+c[1], function(err, res) { <del> <del> //callbackAmigo(); <del> <del> var reserve = geocode.reverseAmigo(c, callbackAmigo); <add> <add> <add> geocode.reverseAmigo(c, callbackAmigo); <ide> <ide> <ide> //});
Java
mit
error: pathspec 'LAPPS-backend/src/main/java/de/rwth/dbis/layers/lapps/resource/HttpStatusCode.java' did not match any file(s) known to git
8af527f0cd3c3100e4de18a417cb7d42d69064d5
1
learning-layers/LAPPS,learning-layers/LAPPS
package de.rwth.dbis.layers.lapps.resource; public class HttpStatusCode { // Taken from: http://en.wikipedia.org/wiki/List_of_HTTP_status_codes // 1xx Informational public static final int CONTINUE = 100; public static final int SWITCHTING_PROTOCOLS = 101; public static final int PROCESSING = 102; // 2xx Success public static final int OK = 200; public static final int CREATED = 201; public static final int ACCEPTED = 202; public static final int NON_AUTHORATIVE_INOFORMATION = 203; public static final int NO_CONTENT = 204; public static final int RESET_CONTENT = 205; public static final int PARTIAL_CONTENT = 206; public static final int MULTI_STATUS = 207; public static final int ALREADY_REPORTED = 208; public static final int IM_USED = 226; // 3xx Redirection public static final int MULTIPLE_CHOICES = 300; public static final int MOVED_PERMANENTLY = 301; public static final int FOUND = 302; public static final int SEE_OTHER = 303; public static final int NOT_MODIFIED = 304; public static final int USE_PROXY = 305; public static final int SWITCH_PROXY = 306; public static final int TEMPORARY_REDIRECT = 307; public static final int PERMANENT_REDIRECT = 308; // 4xx Client Error public static final int BAD_REQUEST = 400; public static final int UNAUTHORIZED = 401; public static final int PAYMENT_REQUIRED = 402; public static final int INVALID_AUTHENFICATION = 401; public static final int FORBIDDEN = 403; public static final int NOT_FOUND = 404; public static final int METHOD_NOT_ALLOWED = 405; public static final int NOT_ACCEPTABLE = 406; public static final int PROXY_AUTHENTICATION_REQUIRED = 407; public static final int REQUEST_TIMEOUT = 408; public static final int CONFLICT = 409; public static final int GONE = 410; public static final int LENGTH_REQUIRED = 411; public static final int PRECONDITION_FAILED = 412; public static final int REQUEST_ENTRY_TOO_LARGE = 413; public static final int REQUEST_URI_TOO_LONG = 414; public static final int UNSUPPORTED_MEDIA_TYPE = 415; public static final int REQUEST_RANGE_NOT_SATISFIABLE = 416; public static final int EXPECTATION_FAILED = 417; public static final int UNPROCESSABLE_ENTITY = 422; public static final int LOCKED = 423; public static final int FAILED_DEPENDENCY = 424; public static final int UPGRADE_REQUIRED = 426; public static final int PRECONDITION_REQUIRED = 428; public static final int TOO_MANY_REQUESTS = 429; public static final int REQUEST_HEADER_FIELDS_TOO_LARGE = 431; // 5xx Server Error public static final int INTERNAL_SERVER_ERROR = 500; public static final int NOT_IMPLEMENTED = 501; public static final int SERVICE_UNAVAILABLE = 503; public static final int GATEWAY_TIMEOUT = 504; public static final int HTTP_VERSION_NOT_SUPPORTED = 505; public static final int VARIANT_ALSO_NEGOTIATES = 506; public static final int INSUFFICIENT_STORAGE = 507; public static final int LOOP_DETECTED = 508; public static final int NOT_EXTENDED = 510; public static final int NETWORK_AUTHENTICATION_REQUIRED = 511; }
LAPPS-backend/src/main/java/de/rwth/dbis/layers/lapps/resource/HttpStatusCode.java
LAPPS-72 created list with status codes
LAPPS-backend/src/main/java/de/rwth/dbis/layers/lapps/resource/HttpStatusCode.java
LAPPS-72 created list with status codes
<ide><path>APPS-backend/src/main/java/de/rwth/dbis/layers/lapps/resource/HttpStatusCode.java <add>package de.rwth.dbis.layers.lapps.resource; <add> <add>public class HttpStatusCode { <add> // Taken from: http://en.wikipedia.org/wiki/List_of_HTTP_status_codes <add> <add> // 1xx Informational <add> public static final int CONTINUE = 100; <add> public static final int SWITCHTING_PROTOCOLS = 101; <add> public static final int PROCESSING = 102; <add> <add> // 2xx Success <add> public static final int OK = 200; <add> public static final int CREATED = 201; <add> public static final int ACCEPTED = 202; <add> public static final int NON_AUTHORATIVE_INOFORMATION = 203; <add> public static final int NO_CONTENT = 204; <add> public static final int RESET_CONTENT = 205; <add> public static final int PARTIAL_CONTENT = 206; <add> public static final int MULTI_STATUS = 207; <add> public static final int ALREADY_REPORTED = 208; <add> public static final int IM_USED = 226; <add> <add> // 3xx Redirection <add> public static final int MULTIPLE_CHOICES = 300; <add> public static final int MOVED_PERMANENTLY = 301; <add> public static final int FOUND = 302; <add> public static final int SEE_OTHER = 303; <add> public static final int NOT_MODIFIED = 304; <add> public static final int USE_PROXY = 305; <add> public static final int SWITCH_PROXY = 306; <add> public static final int TEMPORARY_REDIRECT = 307; <add> public static final int PERMANENT_REDIRECT = 308; <add> <add> // 4xx Client Error <add> public static final int BAD_REQUEST = 400; <add> public static final int UNAUTHORIZED = 401; <add> public static final int PAYMENT_REQUIRED = 402; <add> public static final int INVALID_AUTHENFICATION = 401; <add> public static final int FORBIDDEN = 403; <add> public static final int NOT_FOUND = 404; <add> public static final int METHOD_NOT_ALLOWED = 405; <add> public static final int NOT_ACCEPTABLE = 406; <add> public static final int PROXY_AUTHENTICATION_REQUIRED = 407; <add> public static final int REQUEST_TIMEOUT = 408; <add> public static final int CONFLICT = 409; <add> public static final int GONE = 410; <add> public static final int LENGTH_REQUIRED = 411; <add> public static final int PRECONDITION_FAILED = 412; <add> public static final int REQUEST_ENTRY_TOO_LARGE = 413; <add> public static final int REQUEST_URI_TOO_LONG = 414; <add> public static final int UNSUPPORTED_MEDIA_TYPE = 415; <add> public static final int REQUEST_RANGE_NOT_SATISFIABLE = 416; <add> public static final int EXPECTATION_FAILED = 417; <add> public static final int UNPROCESSABLE_ENTITY = 422; <add> public static final int LOCKED = 423; <add> public static final int FAILED_DEPENDENCY = 424; <add> public static final int UPGRADE_REQUIRED = 426; <add> public static final int PRECONDITION_REQUIRED = 428; <add> public static final int TOO_MANY_REQUESTS = 429; <add> public static final int REQUEST_HEADER_FIELDS_TOO_LARGE = 431; <add> <add> // 5xx Server Error <add> public static final int INTERNAL_SERVER_ERROR = 500; <add> public static final int NOT_IMPLEMENTED = 501; <add> public static final int SERVICE_UNAVAILABLE = 503; <add> public static final int GATEWAY_TIMEOUT = 504; <add> public static final int HTTP_VERSION_NOT_SUPPORTED = 505; <add> public static final int VARIANT_ALSO_NEGOTIATES = 506; <add> public static final int INSUFFICIENT_STORAGE = 507; <add> public static final int LOOP_DETECTED = 508; <add> public static final int NOT_EXTENDED = 510; <add> public static final int NETWORK_AUTHENTICATION_REQUIRED = 511; <add> <add>}
Java
apache-2.0
ead72edbb91343bd9fd8db5636e44f9af7bbcafc
0
Heart2009/retrofit,checkdroid/retrofit,jimxj/retrofit,lncosie/retrofit,f2prateek/retrofit,Jackear/retrofit,iagreen/retrofit,vamsirajendra/retrofit,MaTriXy/retrofit,maany/retrofit,pitatensai/retrofit,zhupengGitHub/retrofit,JunyiZhou/retrofit,java02014/retrofit,promeG/retrofit,iagreen/retrofit,davidcrotty/retrofit,PlumaBrava/retrofit,pitatensai/retrofit,mbStavola/retrofit,equinoxel/retrofit,enieber/retrofit,dmitryustimov/retrofit,10045125/retrofit,msdgwzhy6/retrofit,hgl888/retrofit,lncosie/retrofit,jimxj/retrofit,pitatensai/retrofit,geekinpink/retrofit,cnso/retrofit,zheng1733/retrofit,huihui4045/retrofit,Gary111/retrofit,barodapride/retrofit,noikiy/retrofit,sitexa/retrofit,tmxdyf/retrofit,J-Sizzle/retrofit,huihui4045/retrofit,dmitryustimov/retrofit,java02014/retrofit,Gaantz/retrofit,elijah513/retrofit,NikoYuwono/retrofit,equinoxel/retrofit,zero21ke/retrofit,dlew/retrofit,YlJava110/retrofit,AungWinnHtut/retrofit,f2prateek/retrofit,square/retrofit,iagreen/retrofit,artem-zinnatullin/retrofit,leasual/retrofit,jianxiansining/retrofit,FilippoMito/retrofit,Heart2009/retrofit,andforce/retrofit,loiclefloch/retrofit,ztelur/retrofit,ltshddx/retrofit,andypliu/retrofit,vamsirajendra/retrofit,lncosie/retrofit,larsgrefer/retrofit,vignesh-iopex/retrofit,ggchxx/retrofit,AungWinnHtut/retrofit,ianrumac/retrofit,Gaantz/retrofit,fjg1989/retrofit,Gaantz/retrofit,barodapride/retrofit,chundongwang/retrofit,messipuyol/retrofit,janzoner/retrofit,xiaomeixw/NotRetrofit,dlew/retrofit,avbk/retrofit,JunyiZhou/retrofit,yoslabs/retrofit,tmxdyf/retrofit,checkdroid/retrofit,lemaiyan/retrofit,Appstrakt/retrofit,barodapride/retrofit,shihabmi7/retrofit,AmauryEsparza/retrofit,avbk/retrofit,square/retrofit,airbnb/retrofit,c0deh4xor/retrofit,PlumaBrava/retrofit,fjg1989/retrofit,c0deh4xor/retrofit,Heart2009/retrofit,junenn/retrofit,andforce/retrofit,dmitryustimov/retrofit,shermax/retrofit,elijah513/retrofit,Sellegit/retrofit,sunios/retrofit,shauvik/retrofit,square/retrofit,bhargav1/retrofit,Jackear/retrofit,dlew/retrofit,xfumihiro/retrofit,jianxiansining/retrofit,ggchxx/retrofit,renatohsc/retrofit,guoGavin/retrofit,ze-pequeno/retrofit,noikiy/retrofit,Appstrakt/retrofit,zace-yuan/retrofit,yoslabs/retrofit,sarvex/retrofit,xiaozuzu/retrofit,maduhu/retrofit,PlumaBrava/retrofit,larsgrefer/retrofit,hgl888/retrofit,sitexa/retrofit,michelangelo13/retrofit,geekinpink/retrofit,wlrhnh-David/retrofit,melbic/retrofit,sarvex/retrofit,xfumihiro/retrofit,ze-pequeno/retrofit,ltshddx/retrofit,larsgrefer/retrofit,shauvik/retrofit,ChinaKim/retrofit,lgx0955/retrofit,jianxiansining/retrofit,Pannarrow/retrofit,artem-zinnatullin/retrofit,WiiliamChik/retrofit,viacheslavokolitiy/retrofit,loiclefloch/retrofit,NightlyNexus/retrofit,NikoYuwono/retrofit,ChinaKim/retrofit,ze-pequeno/retrofit,sitexa/retrofit,FilippoMito/retrofit,thangtc/retrofit,ajju4455/retrofit,janzoner/retrofit,Pannarrow/retrofit,andypliu/retrofit,zace-yuan/retrofit,Jackear/retrofit,Gary111/retrofit,deshion/retrofit,shermax/retrofit,sunios/retrofit,vabym8/NotRetrofit,vignesh-iopex/retrofit,zheng1733/retrofit,J-Sizzle/retrofit,lichblitz/retrofit,ruhaly/retrofit,java02014/retrofit,msdgwzhy6/retrofit,zero21ke/retrofit,AungWinnHtut/retrofit,chundongwang/retrofit,xsingHu/retrofit,ajju4455/retrofit,juliendn/retrofit,pmk2429/retrofit,siilobv/retrofit,xsingHu/retrofit,yongjhih/retrofit2,google/retrofit,bestwpw/retrofit,chundongwang/retrofit,Gary111/retrofit,ztelur/retrofit,wanjingyan001/retrofit,YlJava110/retrofit,lgx0955/retrofit,davidcrotty/retrofit,melbic/retrofit,wlrhnh-David/retrofit,squery/retrofit,c0deh4xor/retrofit,YOLOSPAGHETTI/final-project,mbStavola/retrofit,aurae/retrofit,janzoner/retrofit,segmentio/retrofit,maduhu/retrofit,NightlyNexus/retrofit,yuhuayi/retrofit,deshion/retrofit,f2prateek/retrofit,michelangelo13/retrofit,timehop/retrofit,promeG/retrofit,messipuyol/retrofit,lichblitz/retrofit,ianrumac/retrofit,bhargav1/retrofit,airbnb/retrofit,squery/retrofit,bestwpw/retrofit,aurae/retrofit,mbStavola/retrofit,guoGavin/retrofit,bhargav1/retrofit,maduhu/retrofit,enieber/retrofit,yongjhih/NotRetrofit,YOLOSPAGHETTI/final-project,ruhaly/retrofit,lichblitz/retrofit,fjg1989/retrofit,GovindaPaliwal/retrofit,tmxdyf/retrofit,pmk2429/retrofit,NikoYuwono/retrofit,vignesh-iopex/retrofit,YOLOSPAGHETTI/final-project,NightlyNexus/retrofit,bestwpw/retrofit,Sellegit/retrofit,ajju4455/retrofit,nsmolenskii/retrofit,zhupengGitHub/retrofit,msdgwzhy6/retrofit,cnso/retrofit,YlJava110/retrofit,sarvex/retrofit,murat8505/REST_client_retrofit,deshion/retrofit,juliendn/retrofit,aurae/retrofit,ztelur/retrofit,ggchxx/retrofit,shihabmi7/retrofit,J-Sizzle/retrofit,andypliu/retrofit,murat8505/REST_client_retrofit,thangtc/retrofit,airbnb/retrofit,ianrumac/retrofit,JunyiZhou/retrofit,equinoxel/retrofit,loiclefloch/retrofit,leasual/retrofit,google/retrofit,yoslabs/retrofit,pmk2429/retrofit,AmauryEsparza/retrofit,shihabmi7/retrofit,enieber/retrofit,10045125/retrofit,michelangelo13/retrofit,maany/retrofit,wanjingyan001/retrofit,xiaozuzu/retrofit,juliendn/retrofit,nsmolenskii/retrofit,andforce/retrofit,cnso/retrofit,Appstrakt/retrofit,messipuyol/retrofit,renatohsc/retrofit,ze-pequeno/retrofit,murat8505/REST_client_retrofit,davidcrotty/retrofit,sunios/retrofit,squery/retrofit,MaTriXy/retrofit,segmentio/retrofit,promeG/retrofit,timehop/retrofit,wanjingyan001/retrofit,siilobv/retrofit,renatohsc/retrofit,junenn/retrofit,b-cuts/retrofit,ruhaly/retrofit,nsmolenskii/retrofit,xiaozuzu/retrofit,shauvik/retrofit,leasual/retrofit,hgl888/retrofit,artem-zinnatullin/retrofit,zace-yuan/retrofit,xfumihiro/retrofit,huihui4045/retrofit,avbk/retrofit,WiiliamChik/retrofit,GovindaPaliwal/retrofit,viacheslavokolitiy/retrofit,b-cuts/retrofit,noikiy/retrofit,zhupengGitHub/retrofit,MaTriXy/retrofit,ChinaKim/retrofit,xsingHu/retrofit,geekinpink/retrofit,wlrhnh-David/retrofit,lemaiyan/retrofit,thangtc/retrofit,siilobv/retrofit,Pannarrow/retrofit,yuhuayi/retrofit,checkdroid/retrofit,zero21ke/retrofit,jimxj/retrofit,lemaiyan/retrofit,yuhuayi/retrofit,ltshddx/retrofit,guoGavin/retrofit,square/retrofit,elijah513/retrofit,Sellegit/retrofit,maany/retrofit,WiiliamChik/retrofit,viacheslavokolitiy/retrofit,junenn/retrofit,GovindaPaliwal/retrofit,FilippoMito/retrofit,zheng1733/retrofit,segmentio/retrofit,shermax/retrofit,melbic/retrofit,b-cuts/retrofit,lgx0955/retrofit,vamsirajendra/retrofit
package retrofit; import java.util.concurrent.Executor; import java.util.concurrent.FutureTask; import rx.Observable; import rx.Subscriber; import rx.subscriptions.Subscriptions; /** * Utilities for supporting RxJava Observables. * <p> * RxJava might not be on the available to use. Check {@link Platform#HAS_RX_JAVA} before calling. */ final class RxSupport { /** A callback into {@link RestAdapter} to actually invoke the request. */ interface Invoker { /** Invoke the request. The interceptor will be "tape" from the time of subscription. */ ResponseWrapper invoke(RequestInterceptor requestInterceptor); } private final Executor executor; private final ErrorHandler errorHandler; private final RequestInterceptor requestInterceptor; RxSupport(Executor executor, ErrorHandler errorHandler, RequestInterceptor requestInterceptor) { this.executor = executor; this.errorHandler = errorHandler; this.requestInterceptor = requestInterceptor; } Observable createRequestObservable(final Invoker invoker) { return Observable.create(new Observable.OnSubscribe<Object>() { @Override public void call(Subscriber<? super Object> subscriber) { RequestInterceptorTape interceptorTape = new RequestInterceptorTape(); requestInterceptor.intercept(interceptorTape); Runnable runnable = getRunnable(subscriber, invoker, interceptorTape); FutureTask<Void> task = new FutureTask<Void>(runnable, null); // Subscribe to the future task of the network call allowing unsubscription. subscriber.add(Subscriptions.from(task)); executor.execute(task); } }); } private Runnable getRunnable(final Subscriber<? super Object> subscriber, final Invoker invoker, final RequestInterceptorTape interceptorTape) { return new Runnable() { @Override public void run() { try { if (subscriber.isUnsubscribed()) { return; } ResponseWrapper wrapper = invoker.invoke(interceptorTape); subscriber.onNext(wrapper.responseBody); subscriber.onCompleted(); } catch (RetrofitError e) { subscriber.onError(errorHandler.handleError(e)); } } }; } }
retrofit/src/main/java/retrofit/RxSupport.java
package retrofit; import java.util.concurrent.Executor; import java.util.concurrent.FutureTask; import rx.Observable; import rx.Subscriber; import rx.subscriptions.Subscriptions; /** * Utilities for supporting RxJava Observables. * <p> * RxJava might not be on the available to use. Check {@link Platform#HAS_RX_JAVA} before calling. */ final class RxSupport { /** A callback into {@link RestAdapter} to actually invoke the request. */ interface Invoker { /** Invoke the request. The interceptor will be "tape" from the time of subscription. */ ResponseWrapper invoke(RequestInterceptor requestInterceptor); } private final Executor executor; private final ErrorHandler errorHandler; private final RequestInterceptor requestInterceptor; RxSupport(Executor executor, ErrorHandler errorHandler, RequestInterceptor requestInterceptor) { this.executor = executor; this.errorHandler = errorHandler; this.requestInterceptor = requestInterceptor; } Observable createRequestObservable(final Invoker invoker) { return Observable.create(new Observable.OnSubscribe<Object>() { @Override public void call(Subscriber<? super Object> subscriber) { RequestInterceptorTape interceptorTape = new RequestInterceptorTape(); requestInterceptor.intercept(interceptorTape); Runnable runnable = getRunnable(subscriber, invoker, interceptorTape); FutureTask<Void> task = new FutureTask<Void>(runnable, null); // Subscribe to the future task of the network call allowing unsubscription. subscriber.add(Subscriptions.from(task)); executor.execute(task); } }); } private Runnable getRunnable(final Subscriber<? super Object> subscriber, final Invoker invoker, final RequestInterceptorTape interceptorTape) { return new Runnable() { @Override public void run() { try { if (subscriber.isUnsubscribed()) { return; } ResponseWrapper wrapper = invoker.invoke(interceptorTape); subscriber.onNext(wrapper.responseBody); subscriber.onCompleted(); } catch (RetrofitError e) { subscriber.onError(errorHandler.handleError(e)); } catch (Exception e) { // This is from the Callable. It shouldn't actually throw. throw new RuntimeException(e); } } }; } }
Remove unnecessary catch block from RxSupport.
retrofit/src/main/java/retrofit/RxSupport.java
Remove unnecessary catch block from RxSupport.
<ide><path>etrofit/src/main/java/retrofit/RxSupport.java <ide> subscriber.onCompleted(); <ide> } catch (RetrofitError e) { <ide> subscriber.onError(errorHandler.handleError(e)); <del> } catch (Exception e) { <del> // This is from the Callable. It shouldn't actually throw. <del> throw new RuntimeException(e); <ide> } <ide> } <ide> };
Java
apache-2.0
9cf064eb97c7f5fc77f57988343a380db7269d47
0
remkop/picocli,remkop/picocli,remkop/picocli,remkop/picocli
/* Copyright 2017 Remko Popma 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 picocli; import org.junit.After; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.contrib.java.lang.system.ProvideSystemProperty; import org.junit.contrib.java.lang.system.SystemErrRule; import org.junit.contrib.java.lang.system.SystemOutRule; import picocli.CommandLine.Command; import picocli.CommandLine.ExecutionException; import picocli.CommandLine.Help; import picocli.CommandLine.Help.Ansi.IStyle; import picocli.CommandLine.Help.Ansi.Style; import picocli.CommandLine.Help.Ansi.Text; import picocli.CommandLine.Help.ColorScheme; import picocli.CommandLine.Help.TextTable; import picocli.CommandLine.HelpCommand; import picocli.CommandLine.IHelpFactory; import picocli.CommandLine.IHelpSectionRenderer; import picocli.CommandLine.InitializationException; import picocli.CommandLine.Model; import picocli.CommandLine.Model.ArgSpec; import picocli.CommandLine.Model.CommandSpec; import picocli.CommandLine.Model.OptionSpec; import picocli.CommandLine.Model.PositionalParamSpec; import picocli.CommandLine.Model.UsageMessageSpec; import picocli.CommandLine.Option; import picocli.CommandLine.Parameters; import picocli.CommandLine.ParseResult; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.io.PrintWriter; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.net.InetAddress; import java.net.URI; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import java.util.regex.Pattern; import static java.lang.String.format; import static org.junit.Assert.*; import static picocli.CommandLine.Help.Visibility.ALWAYS; import static picocli.CommandLine.Help.Visibility.NEVER; import static picocli.CommandLine.Help.Visibility.ON_DEMAND; import static picocli.TestUtil.textArray; import static picocli.TestUtil.usageString; import static picocli.TestUtil.options; /** * Tests for picocli's "Usage" help functionality. */ public class HelpTest { private static final String LINESEP = System.getProperty("line.separator"); @Rule public final ProvideSystemProperty autoWidthOff = new ProvideSystemProperty("picocli.usage.width", null); @Rule public final ProvideSystemProperty ansiOFF = new ProvideSystemProperty("picocli.ansi", "false"); @Rule public final SystemOutRule systemOutRule = new SystemOutRule().enableLog().muteForSuccessfulTests(); @Rule public final SystemErrRule systemErrRule = new SystemErrRule().enableLog().muteForSuccessfulTests(); @After public void after() { System.getProperties().remove("picocli.color.commands"); System.getProperties().remove("picocli.color.options"); System.getProperties().remove("picocli.color.parameters"); System.getProperties().remove("picocli.color.optionParams"); } @Test public void testShowDefaultValuesDemo() { @Command(showDefaultValues = true) class FineGrainedDefaults { @Option(names = "-a", description = "ALWAYS shown even if null", showDefaultValue = ALWAYS) String optionA; @Option(names = "-b", description = "NEVER shown", showDefaultValue = NEVER) String optionB = "xyz"; @Option(names = "-c", description = "ON_DEMAND hides null", showDefaultValue = ON_DEMAND) String optionC; @Option(names = "-d", description = "ON_DEMAND shows non-null", showDefaultValue = ON_DEMAND) String optionD = "abc"; } String result = usageString(new FineGrainedDefaults(), Help.Ansi.OFF); assertEquals(format("" + "Usage: <main class> [-a=<optionA>] [-b=<optionB>] [-c=<optionC>] [-d=<optionD>]%n" + " -a=<optionA> ALWAYS shown even if null%n" + " Default: null%n" + " -b=<optionB> NEVER shown%n" + " -c=<optionC> ON_DEMAND hides null%n" + " -d=<optionD> ON_DEMAND shows non-null%n" + " Default: abc%n"), result); } @Test public void testCommandWithoutShowDefaultValuesOptionOnDemandNullValue_hidesDefault() { @Command() class Params { @Option(names = {"-f", "--file"}, required = true, description = "the file to use") File file; @Option(names = {"-o", "--opt"}, required = true, description = "another option", showDefaultValue = Help.Visibility.ON_DEMAND) File other; } String result = usageString(new Params(), Help.Ansi.OFF); assertEquals(format("" + "Usage: <main class> -f=<file> -o=<other>%n" + " -f, --file=<file> the file to use%n" + " -o, --opt=<other> another option%n"), result); } @Test public void testCommandWithoutShowDefaultValuesOptionOnDemandNonNullValue_hidesDefault() { @Command() class Params { @Option(names = {"-f", "--file"}, required = true, description = "the file to use") File file = new File("/tmp/file"); @Option(names = {"-o", "--opt"}, required = true, description = "another option", showDefaultValue = Help.Visibility.ON_DEMAND) File other = new File("/tmp/other"); } String result = usageString(new Params(), Help.Ansi.OFF); assertEquals(format("" + "Usage: <main class> -f=<file> -o=<other>%n" + " -f, --file=<file> the file to use%n" + " -o, --opt=<other> another option%n"), result); } @Test public void testCommandWithoutShowDefaultValuesOptionAlwaysNullValue_showsNullDefault() { @Command() class Params { @Option(names = {"-f", "--file"}, required = true, description = "the file to use", showDefaultValue = Help.Visibility.ALWAYS) File file; } String result = usageString(new Params(), Help.Ansi.OFF); assertEquals(format("" + "Usage: <main class> -f=<file>%n" + " -f, --file=<file> the file to use%n" + " Default: null%n"), result); } @Test public void testCommandWithoutShowDefaultValuesOptionAlwaysNonNullValue_showsDefault() { @Command() class Params { @Option(names = {"-f", "--file"}, required = true, description = "the file to use", showDefaultValue = Help.Visibility.ALWAYS) File file = new File("/tmp/file"); } String result = usageString(new Params(), Help.Ansi.OFF); assertEquals(format("" + "Usage: <main class> -f=<file>%n" + " -f, --file=<file> the file to use%n" + " Default: %s%n", new File("/tmp/file")), result); } @Test public void testCommandShowDefaultValuesOptionOnDemandNullValue_hidesDefault() { @Command(showDefaultValues = true) class Params { @Option(names = {"-f", "--file"}, required = true, description = "the file to use") File file; @Option(names = {"-o", "--opt"}, required = true, description = "another option", showDefaultValue = Help.Visibility.ON_DEMAND) File other; } String result = usageString(new Params(), Help.Ansi.OFF); assertEquals(format("" + "Usage: <main class> -f=<file> -o=<other>%n" + " -f, --file=<file> the file to use%n" + " -o, --opt=<other> another option%n"), result); } @Test public void testCommandShowDefaultValuesOptionNeverNullValue_hidesDefault() { @Command(showDefaultValues = true) class Params { @Option(names = {"-f", "--file"}, required = true, description = "the file to use") File file; @Option(names = {"-o", "--opt"}, required = true, description = "another option", showDefaultValue = Help.Visibility.NEVER) File other; } String result = usageString(new Params(), Help.Ansi.OFF); assertEquals(format("" + "Usage: <main class> -f=<file> -o=<other>%n" + " -f, --file=<file> the file to use%n" + " -o, --opt=<other> another option%n"), result); } @Test public void testCommandShowDefaultValuesOptionAlwaysNullValue_showsNullDefault() { @Command(showDefaultValues = true) class Params { @Option(names = {"-f", "--file"}, required = true, description = "the file to use") File file; @Option(names = {"-o", "--opt"}, required = true, description = "another option", showDefaultValue = Help.Visibility.ALWAYS) File other; } String result = usageString(new Params(), Help.Ansi.OFF); assertEquals(format("" + "Usage: <main class> -f=<file> -o=<other>%n" + " -f, --file=<file> the file to use%n" + " -o, --opt=<other> another option%n" + " Default: null%n"), result); } @Test public void testCommandShowDefaultValuesOptionOnDemandNonNullValue_showsDefault() { @Command(showDefaultValues = true) class Params { @Option(names = {"-f", "--file"}, required = true, description = "the file to use") File file = new File("theDefault.txt"); @Option(names = {"-o", "--opt"}, required = true, description = "another option", showDefaultValue = Help.Visibility.ON_DEMAND) File other = new File("other.txt"); } String result = usageString(new Params(), Help.Ansi.OFF); assertEquals(format("" + "Usage: <main class> -f=<file> -o=<other>%n" + " -f, --file=<file> the file to use%n" + " Default: theDefault.txt%n" + " -o, --opt=<other> another option%n" + " Default: other.txt%n"), result); } @Test public void testCommandShowDefaultValuesOptionNeverNonNullValue_hidesDefault() { @Command(showDefaultValues = true) class Params { @Option(names = {"-f", "--file"}, required = true, description = "the file to use") File file = new File("theDefault.txt"); @Option(names = {"-o", "--opt"}, required = true, description = "another option", showDefaultValue = Help.Visibility.NEVER) File other = new File("other.txt"); } String result = usageString(new Params(), Help.Ansi.OFF); assertEquals(format("" + "Usage: <main class> -f=<file> -o=<other>%n" + " -f, --file=<file> the file to use%n" + " Default: theDefault.txt%n" + " -o, --opt=<other> another option%n"), result); } @Test public void testCommandShowDefaultValuesOptionAlwaysNonNullValue_hidesDefault() { @Command(showDefaultValues = true) class Params { @Option(names = {"-f", "--file"}, required = true, description = "the file to use") File file = new File("theDefault.txt"); @Option(names = {"-o", "--opt"}, required = true, description = "another option", showDefaultValue = Help.Visibility.ALWAYS) File other = new File("other.txt"); } String result = usageString(new Params(), Help.Ansi.OFF); assertEquals(format("" + "Usage: <main class> -f=<file> -o=<other>%n" + " -f, --file=<file> the file to use%n" + " Default: theDefault.txt%n" + " -o, --opt=<other> another option%n" + " Default: other.txt%n"), result); } @Test public void testCommandShowDefaultValuesOptionOnDemandArrayField() { @Command(showDefaultValues = true) class Params { @Option(names = {"-x", "--array"}, required = true, description = "the array") int[] array = {1, 5, 11, 23}; @Option(names = {"-y", "--other"}, required = true, description = "the other", showDefaultValue = Help.Visibility.ON_DEMAND) int[] other = {1, 5, 11, 23}; } String result = usageString(new Params(), Help.Ansi.OFF); assertEquals(format("" + "Usage: <main class> -x=<array> [-x=<array>]... -y=<other> [-y=<other>]...%n" + " -x, --array=<array> the array%n" + " Default: [1, 5, 11, 23]%n" + " -y, --other=<other> the other%n" + " Default: [1, 5, 11, 23]%n"), result); } @Test public void testCommandShowDefaultValuesOptionNeverArrayField_hidesDefault() { @Command(showDefaultValues = true) class Params { @Option(names = {"-x", "--array"}, required = true, description = "the array") int[] array = {1, 5, 11, 23}; @Option(names = {"-y", "--other"}, required = true, description = "the other", showDefaultValue = Help.Visibility.NEVER) int[] other = {1, 5, 11, 23}; } String result = usageString(new Params(), Help.Ansi.OFF); assertEquals(format("" + "Usage: <main class> -x=<array> [-x=<array>]... -y=<other> [-y=<other>]...%n" + " -x, --array=<array> the array%n" + " Default: [1, 5, 11, 23]%n" + " -y, --other=<other> the other%n"), result); } @Test public void testCommandShowDefaultValuesOptionAlwaysNullArrayField_showsNull() { @Command(showDefaultValues = true) class Params { @Option(names = {"-x", "--array"}, required = true, description = "the array") int[] array; @Option(names = {"-y", "--other"}, required = true, description = "the other", showDefaultValue = Help.Visibility.ALWAYS) int[] other; } String result = usageString(new Params(), Help.Ansi.OFF); assertEquals(format("" + "Usage: <main class> -x=<array> [-x=<array>]... -y=<other> [-y=<other>]...%n" + " -x, --array=<array> the array%n" + " -y, --other=<other> the other%n" + " Default: null%n"), result); } @Test public void testCommandShowDefaultValuesVariableForArrayField() { @Command class Params { @Option(names = {"-x", "--array"}, required = true, description = "null array: Default: ${DEFAULT-VALUE}") int[] nil; @Option(names = {"-y", "--other"}, required = true, description = "non-null: Default: ${DEFAULT-VALUE}") int[] other = {1, 5, 11, 23}; } String result = usageString(new Params(), Help.Ansi.OFF); assertEquals(format("" + "Usage: <main class> -x=<nil> [-x=<nil>]... -y=<other> [-y=<other>]...%n" + " -x, --array=<nil> null array: Default: null%n" + " -y, --other=<other> non-null: Default: [1, 5, 11, 23]%n"), result); } @Test public void testOptionSpec_defaultValue_overwritesInitialValue() { @Command(showDefaultValues = true) class Params { @Option(names = {"-x", "--array"}, required = true, paramLabel = "INT", description = "the array") int[] array = {1, 5, 11, 23}; } CommandLine cmd = new CommandLine(new Params()); OptionSpec x = cmd.getCommandSpec().posixOptionsMap().get('x').toBuilder().defaultValue("5,4,3,2,1").splitRegex(",").build(); cmd = new CommandLine(CommandSpec.create().addOption(x)); cmd.getCommandSpec().usageMessage().showDefaultValues(true); String result = usageString(cmd, Help.Ansi.OFF); assertEquals(format("" + "Usage: <main class> [-x=INT[,INT...]]...%n" + " -x, --array=INT[,INT...] the array%n" + " Default: 5,4,3,2,1%n"), result); } @Test public void testCommandWithoutShowDefaultValuesPositionalOnDemandNullValue_hidesDefault() { @Command() class Params { @Parameters(index = "0", description = "the file to use") File file; @Parameters(index = "1", description = "another option", showDefaultValue = Help.Visibility.ON_DEMAND) File other; } String result = usageString(new Params(), Help.Ansi.OFF); assertEquals(format("" + "Usage: <main class> <file> <other>%n" + " <file> the file to use%n" + " <other> another option%n"), result); } @Test public void testCommandWithoutShowDefaultValuesPositionalOnDemandNonNullValue_hidesDefault() { @Command() class Params { @Parameters(index = "0", description = "the file to use") File file = new File("/tmp/file"); @Parameters(index = "1", description = "another option", showDefaultValue = Help.Visibility.ON_DEMAND) File other = new File("/tmp/other"); } String result = usageString(new Params(), Help.Ansi.OFF); assertEquals(format("" + "Usage: <main class> <file> <other>%n" + " <file> the file to use%n" + " <other> another option%n"), result); } @Test public void testCommandWithoutShowDefaultValuesPositionalAlwaysNullValue_showsNullDefault() { @Command() class Params { @Parameters(index = "0", description = "the file to use", showDefaultValue = Help.Visibility.ALWAYS) File file; } String result = usageString(new Params(), Help.Ansi.OFF); assertEquals(format("" + "Usage: <main class> <file>%n" + " <file> the file to use%n" + " Default: null%n"), result); } @Test public void testCommandWithoutShowDefaultValuesPositionalAlwaysNonNullValue_showsDefault() { @Command() class Params { @Parameters(index = "0", description = "the file to use", showDefaultValue = Help.Visibility.ALWAYS) File file = new File("/tmp/file"); } String result = usageString(new Params(), Help.Ansi.OFF); assertEquals(format("" + "Usage: <main class> <file>%n" + " <file> the file to use%n" + " Default: %s%n", new File("/tmp/file")), result); } @Test public void testCommandShowDefaultValuesPositionalOnDemandNullValue_hidesDefault() { @Command(showDefaultValues = true) class Params { @Parameters(index = "0", description = "the file to use") File file; @Parameters(index = "1", description = "another option", showDefaultValue = Help.Visibility.ON_DEMAND) File other; } String result = usageString(new Params(), Help.Ansi.OFF); assertEquals(format("" + "Usage: <main class> <file> <other>%n" + " <file> the file to use%n" + " <other> another option%n"), result); } @Test public void testCommandShowDefaultValuesPositionalNeverNullValue_hidesDefault() { @Command(showDefaultValues = true) class Params { @Parameters(index = "0", description = "the file to use") File file; @Parameters(index = "1", description = "another option", showDefaultValue = Help.Visibility.NEVER) File other; } String result = usageString(new Params(), Help.Ansi.OFF); assertEquals(format("" + "Usage: <main class> <file> <other>%n" + " <file> the file to use%n" + " <other> another option%n"), result); } @Test public void testCommandShowDefaultValuesPositionalAlwaysNullValue_showsNullDefault() { @Command(showDefaultValues = true) class Params { @Parameters(index = "0", description = "the file to use") File file; @Parameters(index = "1", description = "another option", showDefaultValue = Help.Visibility.ALWAYS) File other; } String result = usageString(new Params(), Help.Ansi.OFF); assertEquals(format("" + "Usage: <main class> <file> <other>%n" + " <file> the file to use%n" + " <other> another option%n" + " Default: null%n"), result); } @Test public void testCommandShowDefaultValuesPositionalOnDemandNonNullValue_showsDefault() { @Command(showDefaultValues = true) class Params { @Parameters(index = "0", description = "the file to use") File file = new File("theDefault.txt"); @Parameters(index = "1", description = "another option", showDefaultValue = Help.Visibility.ON_DEMAND) File other = new File("other.txt"); } String result = usageString(new Params(), Help.Ansi.OFF); assertEquals(format("" + "Usage: <main class> <file> <other>%n" + " <file> the file to use%n" + " Default: theDefault.txt%n" + " <other> another option%n" + " Default: other.txt%n"), result); } @Test public void testCommandShowDefaultValuesPositionalNeverNonNullValue_hidesDefault() { @Command(showDefaultValues = true) class Params { @Parameters(index = "0", description = "the file to use") File file = new File("theDefault.txt"); @Parameters(index = "1", description = "another option", showDefaultValue = Help.Visibility.NEVER) File other = new File("other.txt"); } String result = usageString(new Params(), Help.Ansi.OFF); assertEquals(format("" + "Usage: <main class> <file> <other>%n" + " <file> the file to use%n" + " Default: theDefault.txt%n" + " <other> another option%n"), result); } @Test public void testCommandShowDefaultValuesPositionalAlwaysNonNullValue_hidesDefault() { @Command(showDefaultValues = true) class Params { @Parameters(index = "0", description = "the file to use") File file = new File("theDefault.txt"); @Parameters(index = "1", description = "another option", showDefaultValue = Help.Visibility.ALWAYS) File other = new File("other.txt"); } String result = usageString(new Params(), Help.Ansi.OFF); assertEquals(format("" + "Usage: <main class> <file> <other>%n" + " <file> the file to use%n" + " Default: theDefault.txt%n" + " <other> another option%n" + " Default: other.txt%n"), result); } @Test public void testPositionalParamSpec_defaultValue_overwritesInitialValue() { @Command(showDefaultValues = true) class Params { @Parameters(paramLabel = "INT", description = "the array") int[] value = {1, 5, 11, 23}; } CommandLine cmd = new CommandLine(new Params()); PositionalParamSpec x = cmd.getCommandSpec().positionalParameters().get(0).toBuilder().defaultValue("5,4,3,2,1").splitRegex(",").build(); cmd = new CommandLine(CommandSpec.create().add(x)); cmd.getCommandSpec().usageMessage().showDefaultValues(true); String result = usageString(cmd, Help.Ansi.OFF); assertEquals(format("" + "Usage: <main class> [INT[,INT...]...]%n" + " [INT[,INT...]...] the array%n" + " Default: 5,4,3,2,1%n"), result); } @Test public void testUsageSeparatorWithoutDefault() { @Command() class Params { @Option(names = {"-f", "--file"}, required = true, description = "the file to use") File file = new File("def.txt"); } String result = usageString(new Params(), Help.Ansi.OFF); assertEquals(format("" + "Usage: <main class> -f=<file>%n" + " -f, --file=<file> the file to use%n"), result); } @Test public void testUsageSeparator() { @Command(showDefaultValues = true) class Params { @Option(names = {"-f", "--file"}, required = true, description = "the file to use") File file = new File("def.txt"); } String result = usageString(new Params(), Help.Ansi.OFF); assertEquals(format("" + "Usage: <main class> -f=<file>%n" + " -f, --file=<file> the file to use%n" + " Default: def.txt%n"), result); } @Test public void testUsageParamLabels() { @Command() class ParamLabels { @Option(names = "-P", paramLabel = "KEY=VALUE", type = {String.class, String.class}, description = "Project properties (key-value pairs)") Map<String, String> props; @Option(names = "-f", paramLabel = "FILE", description = "files") File[] f; @Option(names = "-n", description = "a number option") int number; @Parameters(index = "0", paramLabel = "NUM", description = "number param") int n; @Parameters(index = "1", description = "the host parameter") InetAddress host; } String result = usageString(new ParamLabels(), Help.Ansi.OFF); assertEquals(format("" + "Usage: <main class> [-n=<number>] [-f=FILE]... [-P=KEY=VALUE]... NUM <host>%n" + " NUM number param%n" + " <host> the host parameter%n" + " -f=FILE files%n" + " -n=<number> a number option%n" + " -P=KEY=VALUE Project properties (key-value pairs)%n"), result); } @Test public void testUsageParamLabelsWithLongMapOptionName() { @Command() class ParamLabels { @Option(names = {"-P", "--properties"}, paramLabel = "KEY=VALUE", type = {String.class, String.class}, description = "Project properties (key-value pairs)") Map<String, String> props; @Option(names = "-f", paramLabel = "FILE", description = "a file") File f; @Option(names = "-n", description = "a number option") int number; @Parameters(index = "0", paramLabel = "NUM", description = "number param") int n; @Parameters(index = "1", description = "the host parameter") InetAddress host; } String result = usageString(new ParamLabels(), Help.Ansi.OFF); assertEquals(format("" + "Usage: <main class> [-f=FILE] [-n=<number>] [-P=KEY=VALUE]... NUM <host>%n" + " NUM number param%n" + " <host> the host parameter%n" + " -f=FILE a file%n" + " -n=<number> a number option%n" + " -P, --properties=KEY=VALUE%n" + " Project properties (key-value pairs)%n"), result); } // --------------- @Test public void testUsageVariableArityRequiredShortOptionArray() throws UnsupportedEncodingException { // if option is required at least once and can be specified multiple times: // -f=ARG [-f=ARG]... class Args { @Option(names = "-a", required = true, paramLabel = "ARG") // default String[] a; @Option(names = "-b", required = true, paramLabel = "ARG", arity = "0..*") List<String> b; @Option(names = "-c", required = true, paramLabel = "ARG", arity = "1..*") String[] c; @Option(names = "-d", required = true, paramLabel = "ARG", arity = "2..*") List<String> d; } String expected = String.format("" + "Usage: <main class> -a=ARG [-a=ARG]... -b[=ARG...] [-b[=ARG...]]... -c=ARG...%n" + " [-c=ARG...]... -d=ARG ARG... [-d=ARG ARG...]...%n" + " -a=ARG%n" + " -b=[ARG...]%n" + " -c=ARG...%n" + " -d=ARG ARG...%n"); //CommandLine.usage(new Args(), System.out); assertEquals(expected, usageString(new Args(), Help.Ansi.OFF)); } @Test public void testUsageVariableArityShortOptionArray() throws UnsupportedEncodingException { class Args { @Option(names = "-a", paramLabel = "ARG") // default List<String> a; @Option(names = "-b", paramLabel = "ARG", arity = "0..*") String[] b; @Option(names = "-c", paramLabel = "ARG", arity = "1..*") List<String> c; @Option(names = "-d", paramLabel = "ARG", arity = "2..*") String[] d; } String expected = String.format("" + "Usage: <main class> [-a=ARG]... [-b[=ARG...]]... [-c=ARG...]... [-d=ARG%n" + " ARG...]...%n" + " -a=ARG%n" + " -b=[ARG...]%n" + " -c=ARG...%n" + " -d=ARG ARG...%n"); //CommandLine.usage(new Args(), System.out); assertEquals(expected, usageString(new Args(), Help.Ansi.OFF)); } @Test public void testUsageRangeArityRequiredShortOptionArray() throws UnsupportedEncodingException { // if option is required at least once and can be specified multiple times: // -f=ARG [-f=ARG]... class Args { @Option(names = "-a", required = true, paramLabel = "ARG", arity = "0..1") List<String> a; @Option(names = "-b", required = true, paramLabel = "ARG", arity = "1..2") String[] b; @Option(names = "-c", required = true, paramLabel = "ARG", arity = "1..3") String[] c; @Option(names = "-d", required = true, paramLabel = "ARG", arity = "2..4") String[] d; } String expected = String.format("" + "Usage: <main class> -a[=ARG] [-a[=ARG]]... -b=ARG [ARG] [-b=ARG [ARG]]...%n" + " -c=ARG [ARG [ARG]] [-c=ARG [ARG [ARG]]]... -d=ARG ARG [ARG%n" + " [ARG]] [-d=ARG ARG [ARG [ARG]]]...%n" + " -a=[ARG]%n" + " -b=ARG [ARG]%n" + " -c=ARG [ARG [ARG]]%n" + " -d=ARG ARG [ARG [ARG]]%n"); //CommandLine.usage(new Args(), System.out); assertEquals(expected, usageString(new Args(), Help.Ansi.OFF)); } @Test public void testUsageRangeArityShortOptionArray() throws UnsupportedEncodingException { class Args { @Option(names = "-a", paramLabel = "ARG", arity = "0..1") List<String> a; @Option(names = "-b", paramLabel = "ARG", arity = "1..2") String[] b; @Option(names = "-c", paramLabel = "ARG", arity = "1..3") String[] c; @Option(names = "-d", paramLabel = "ARG", arity = "2..4") String[] d; } String expected = String.format("" + "Usage: <main class> [-a[=ARG]]... [-b=ARG [ARG]]... [-c=ARG [ARG [ARG]]]...%n" + " [-d=ARG ARG [ARG [ARG]]]...%n" + " -a=[ARG]%n" + " -b=ARG [ARG]%n" + " -c=ARG [ARG [ARG]]%n" + " -d=ARG ARG [ARG [ARG]]%n"); //CommandLine.usage(new Args(), System.out); assertEquals(expected, usageString(new Args(), Help.Ansi.OFF)); } @Test public void testUsageFixedArityRequiredShortOptionArray() throws UnsupportedEncodingException { // if option is required at least once and can be specified multiple times: // -f=ARG [-f=ARG]... class Args { @Option(names = "-a", required = true, paramLabel = "ARG") // default String[] a; @Option(names = "-b", required = true, paramLabel = "ARG", arity = "0") String[] b; @Option(names = "-c", required = true, paramLabel = "ARG", arity = "1") String[] c; @Option(names = "-d", required = true, paramLabel = "ARG", arity = "2") String[] d; } String expected = String.format("" + "Usage: <main class> -b [-b]... -a=ARG [-a=ARG]... -c=ARG [-c=ARG]... -d=ARG ARG%n" + " [-d=ARG ARG]...%n" + " -a=ARG%n" + " -b%n" + " -c=ARG%n" + " -d=ARG ARG%n"); //CommandLine.usage(new Args(), System.out); assertEquals(expected, usageString(new Args(), Help.Ansi.OFF)); } @Test public void testUsageFixedArityShortOptionArray() throws UnsupportedEncodingException { class Args { @Option(names = "-a", paramLabel = "ARG") // default String[] a; @Option(names = "-b", paramLabel = "ARG", arity = "0") String[] b; @Option(names = "-c", paramLabel = "ARG", arity = "1") String[] c; @Option(names = "-d", paramLabel = "ARG", arity = "2") String[] d; } String expected = String.format("" + "Usage: <main class> [-b]... [-a=ARG]... [-c=ARG]... [-d=ARG ARG]...%n" + " -a=ARG%n" + " -b%n" + " -c=ARG%n" + " -d=ARG ARG%n"); //CommandLine.usage(new Args(), System.out); assertEquals(expected, usageString(new Args(), Help.Ansi.OFF)); } //-------------- @Test public void testUsageVariableArityRequiredLongOptionArray() throws UnsupportedEncodingException { // if option is required at least once and can be specified multiple times: // -f=ARG [-f=ARG]... class Args { @Option(names = "--aa", required = true, paramLabel = "ARG") // default String[] a; @Option(names = "--bb", required = true, paramLabel = "ARG", arity = "0..*") List<String> b; @Option(names = "--cc", required = true, paramLabel = "ARG", arity = "1..*") String[] c; @Option(names = "--dd", required = true, paramLabel = "ARG", arity = "2..*") List<String> d; } String expected = String.format("" + "Usage: <main class> --aa=ARG [--aa=ARG]... --bb[=ARG...] [--bb[=ARG...]]...%n" + " --cc=ARG... [--cc=ARG...]... --dd=ARG ARG... [--dd=ARG%n" + " ARG...]...%n" + " --aa=ARG%n" + " --bb[=ARG...]%n" + " --cc=ARG...%n" + " --dd=ARG ARG...%n"); //CommandLine.usage(new Args(), System.out); assertEquals(expected, usageString(new Args(), Help.Ansi.OFF)); } @Test public void testUsageVariableArityLongOptionArray() throws UnsupportedEncodingException { class Args { @Option(names = "--aa", paramLabel = "ARG") // default List<String> a; @Option(names = "--bb", paramLabel = "ARG", arity = "0..*") String[] b; @Option(names = "--cc", paramLabel = "ARG", arity = "1..*") List<String> c; @Option(names = "--dd", paramLabel = "ARG", arity = "2..*") String[] d; } String expected = String.format("" + "Usage: <main class> [--aa=ARG]... [--bb[=ARG...]]... [--cc=ARG...]... [--dd=ARG%n" + " ARG...]...%n" + " --aa=ARG%n" + " --bb[=ARG...]%n" + " --cc=ARG...%n" + " --dd=ARG ARG...%n"); //CommandLine.usage(new Args(), System.out); assertEquals(expected, usageString(new Args(), Help.Ansi.OFF)); } @Test public void testUsageRangeArityRequiredLongOptionArray() throws UnsupportedEncodingException { // if option is required at least once and can be specified multiple times: // -f=ARG [-f=ARG]... class Args { @Option(names = "--aa", required = true, paramLabel = "ARG", arity = "0..1") List<String> a; @Option(names = "--bb", required = true, paramLabel = "ARG", arity = "1..2") String[] b; @Option(names = "--cc", required = true, paramLabel = "ARG", arity = "1..3") String[] c; @Option(names = "--dd", required = true, paramLabel = "ARG", arity = "2..4", description = "foobar") String[] d; } String expected = String.format("" + "Usage: <main class> --aa[=ARG] [--aa[=ARG]]... --bb=ARG [ARG] [--bb=ARG%n" + " [ARG]]... --cc=ARG [ARG [ARG]] [--cc=ARG [ARG [ARG]]]...%n" + " --dd=ARG ARG [ARG [ARG]] [--dd=ARG ARG [ARG [ARG]]]...%n" + " --aa[=ARG]%n" + " --bb=ARG [ARG]%n" + " --cc=ARG [ARG [ARG]]%n" + " --dd=ARG ARG [ARG [ARG]]%n" + " foobar%n"); //CommandLine.usage(new Args(), System.out); assertEquals(expected, usageString(new Args(), Help.Ansi.OFF)); } @Test public void testUsageRangeArityLongOptionArray() throws UnsupportedEncodingException { class Args { @Option(names = "--aa", paramLabel = "ARG", arity = "0..1") List<String> a; @Option(names = "--bb", paramLabel = "ARG", arity = "1..2") String[] b; @Option(names = "--cc", paramLabel = "ARG", arity = "1..3") String[] c; @Option(names = "--dd", paramLabel = "ARG", arity = "2..4", description = "foobar") String[] d; } String expected = String.format("" + "Usage: <main class> [--aa[=ARG]]... [--bb=ARG [ARG]]... [--cc=ARG [ARG%n" + " [ARG]]]... [--dd=ARG ARG [ARG [ARG]]]...%n" + " --aa[=ARG]%n" + " --bb=ARG [ARG]%n" + " --cc=ARG [ARG [ARG]]%n" + " --dd=ARG ARG [ARG [ARG]]%n" + " foobar%n"); //CommandLine.usage(new Args(), System.out); assertEquals(expected, usageString(new Args(), Help.Ansi.OFF)); } @Test public void testUsageFixedArityRequiredLongOptionArray() throws UnsupportedEncodingException { // if option is required at least once and can be specified multiple times: // -f=ARG [-f=ARG]... class Args { @Option(names = "--aa", required = true, paramLabel = "ARG") // default String[] a; @Option(names = "--bb", required = true, paramLabel = "ARG", arity = "0") String[] b; @Option(names = "--cc", required = true, paramLabel = "ARG", arity = "1") String[] c; @Option(names = "--dd", required = true, paramLabel = "ARG", arity = "2") String[] d; } String expected = String.format("" + "Usage: <main class> --bb [--bb]... --aa=ARG [--aa=ARG]... --cc=ARG%n" + " [--cc=ARG]... --dd=ARG ARG [--dd=ARG ARG]...%n" + " --aa=ARG%n" + " --bb%n" + " --cc=ARG%n" + " --dd=ARG ARG%n"); //CommandLine.usage(new Args(), System.out); assertEquals(expected, usageString(new Args(), Help.Ansi.OFF)); } @Test public void testUsageFixedArityLongOptionArray() throws UnsupportedEncodingException { class Args { @Option(names = "--aa", paramLabel = "ARG") // default String[] a; @Option(names = "--bb", paramLabel = "ARG", arity = "0") String[] b; @Option(names = "--cc", paramLabel = "ARG", arity = "1") String[] c; @Option(names = "--dd", paramLabel = "ARG", arity = "2") String[] d; } String expected = String.format("" + "Usage: <main class> [--bb]... [--aa=ARG]... [--cc=ARG]... [--dd=ARG ARG]...%n" + " --aa=ARG%n" + " --bb%n" + " --cc=ARG%n" + " --dd=ARG ARG%n"); //CommandLine.usage(new Args(), System.out); assertEquals(expected, usageString(new Args(), Help.Ansi.OFF)); } //------------------ @Test public void testUsageVariableArityRequiredShortOptionMap() throws UnsupportedEncodingException { // if option is required at least once and can be specified multiple times: // -f=ARG [-f=ARG]... class Args { @Option(names = "-a", required = true, paramLabel = "KEY=VAL") // default Map<String, String> a; @Option(names = "-b", required = true, arity = "0..*") @SuppressWarnings("unchecked") Map b; @Option(names = "-c", required = true, arity = "1..*", type = {String.class, TimeUnit.class}) Map<String, TimeUnit> c; @Option(names = "-d", required = true, arity = "2..*", type = {Integer.class, URL.class}, description = "description") Map<Integer, URL> d; } String expected = String.format("" + "Usage: <main class> -a=KEY=VAL [-a=KEY=VAL]... -b[=<String=String>...] [-b%n" + " [=<String=String>...]]... -c=<String=TimeUnit>...%n" + " [-c=<String=TimeUnit>...]... -d=<Integer=URL>%n" + " <Integer=URL>... [-d=<Integer=URL> <Integer=URL>...]...%n" + " -a=KEY=VAL%n" + " -b=[<String=String>...]%n" + " -c=<String=TimeUnit>...%n" + " -d=<Integer=URL> <Integer=URL>...%n" + " description%n"); //CommandLine.usage(new Args(), System.out); assertEquals(expected, usageString(new Args(), Help.Ansi.OFF)); } @Test public void testUsageVariableArityOptionMap() throws UnsupportedEncodingException { class Args { @Option(names = "-a") // default Map<String, String> a; @Option(names = "-b", arity = "0..*", type = {Integer.class, Integer.class}) Map<Integer, Integer> b; @Option(names = "-c", paramLabel = "KEY=VALUE", arity = "1..*", type = {String.class, TimeUnit.class}) Map<String, TimeUnit> c; @Option(names = "-d", arity = "2..*", type = {String.class, URL.class}, description = "description") Map<String, URL> d; } String expected = String.format("" + "Usage: <main class> [-a=<String=String>]... [-b[=<Integer=Integer>...]]...%n" + " [-c=KEY=VALUE...]... [-d=<String=URL> <String=URL>...]...%n" + " -a=<String=String>%n" + " -b=[<Integer=Integer>...]%n" + "%n" + // TODO " -c=KEY=VALUE...%n" + " -d=<String=URL> <String=URL>...%n" + " description%n"); //CommandLine.usage(new Args(), System.out); assertEquals(expected, usageString(new Args(), Help.Ansi.OFF)); } @Test public void testUsageRangeArityRequiredOptionMap() throws UnsupportedEncodingException { // if option is required at least once and can be specified multiple times: // -f=ARG [-f=ARG]... class Args { @Option(names = "-a", required = true, arity = "0..1", description = "a description") Map<String, String> a; @Option(names = "-b", required = true, arity = "1..2", type = {Integer.class, Integer.class}, description = "b description") Map<Integer, Integer> b; @Option(names = "-c", required = true, arity = "1..3", type = {String.class, URL.class}, description = "c description") Map<String, URL> c; @Option(names = "-d", required = true, paramLabel = "K=URL", arity = "2..4", description = "d description") Map<String, URL> d; } String expected = String.format("" + "Usage: <main class> -a[=<String=String>] [-a[=<String=String>]]...%n" + " -b=<Integer=Integer> [<Integer=Integer>]%n" + " [-b=<Integer=Integer> [<Integer=Integer>]]...%n" + " -c=<String=URL> [<String=URL> [<String=URL>]]%n" + " [-c=<String=URL> [<String=URL> [<String=URL>]]]... -d=K=URL%n" + " K=URL [K=URL [K=URL]] [-d=K=URL K=URL [K=URL [K=URL]]]...%n" + " -a=[<String=String>] a description%n" + " -b=<Integer=Integer> [<Integer=Integer>]%n" + " b description%n" + " -c=<String=URL> [<String=URL> [<String=URL>]]%n" + " c description%n" + " -d=K=URL K=URL [K=URL [K=URL]]%n" + " d description%n"); //CommandLine.usage(new Args(), System.out); assertEquals(expected, usageString(new Args(), Help.Ansi.OFF)); } @Test public void testUsageRangeArityOptionMap() throws UnsupportedEncodingException { class Args { @Option(names = "-a", arity = "0..1"/*, type = {UUID.class, URL.class}*/, description = "a description") Map<UUID, URL> a; @Option(names = "-b", arity = "1..2", type = {Long.class, UUID.class}, description = "b description") Map<?, ?> b; @Option(names = "-c", arity = "1..3", type = {Long.class}, description = "c description") Map<?, ?> c; @Option(names = "-d", paramLabel = "K=V", arity = "2..4", description = "d description") Map<?, ?> d; } String expected = String.format("" + "Usage: <main class> [-a[=<UUID=URL>]]... [-b=<Long=UUID> [<Long=UUID>]]...%n" + " [-c=<String=String> [<String=String> [<String=String>]]]...%n" + " [-d=K=V K=V [K=V [K=V]]]...%n" + " -a=[<UUID=URL>] a description%n" + " -b=<Long=UUID> [<Long=UUID>]%n" + " b description%n" + " -c=<String=String> [<String=String> [<String=String>]]%n" + " c description%n" + " -d=K=V K=V [K=V [K=V]] d description%n"); //CommandLine.usage(new Args(), System.out); assertEquals(expected, usageString(new Args(), Help.Ansi.OFF)); } @Test public void testUsageFixedArityRequiredOptionMap() throws UnsupportedEncodingException { // if option is required at least once and can be specified multiple times: // -f=ARG [-f=ARG]... class Args { @Option(names = "-a", required = true, description = "a description") Map<Short, Field> a; @Option(names = "-b", required = true, paramLabel = "KEY=VAL", arity = "0", description = "b description") @SuppressWarnings("unchecked") Map<?, ?> b; @Option(names = "-c", required = true, arity = "1", type = {Long.class, File.class}, description = "c description") Map<Long, File> c; @Option(names = "-d", required = true, arity = "2", type = {URI.class, URL.class}, description = "d description") Map<URI, URL> d; } String expected = String.format("" + "Usage: <main class> -b [-b]... -a=<Short=Field> [-a=<Short=Field>]...%n" + " -c=<Long=File> [-c=<Long=File>]... -d=<URI=URL> <URI=URL>%n" + " [-d=<URI=URL> <URI=URL>]...%n" + " -a=<Short=Field> a description%n" + " -b b description%n" + " -c=<Long=File> c description%n" + " -d=<URI=URL> <URI=URL> d description%n"); //CommandLine.usage(new Args(), System.out); assertEquals(expected, usageString(new Args(), Help.Ansi.OFF)); } @Test public void testUsageFixedArityOptionMap() throws UnsupportedEncodingException { class Args { @Option(names = "-a", type = {Short.class, Field.class}, description = "a description") Map<Short, Field> a; @Option(names = "-b", arity = "0", type = {UUID.class, Long.class}, description = "b description") @SuppressWarnings("unchecked") Map<?, ?> b; @Option(names = "-c", arity = "1", description = "c description") Map<Long, File> c; @Option(names = "-d", arity = "2", type = {URI.class, URL.class}, description = "d description") Map<URI, URL> d; } String expected = String.format("" + "Usage: <main class> [-b]... [-a=<Short=Field>]... [-c=<Long=File>]...%n" + " [-d=<URI=URL> <URI=URL>]...%n" + " -a=<Short=Field> a description%n" + " -b b description%n" + " -c=<Long=File> c description%n" + " -d=<URI=URL> <URI=URL> d description%n"); //CommandLine.usage(new Args(), System.out); assertEquals(expected, usageString(new Args(), Help.Ansi.OFF)); } //-------------- @Test public void testUsageVariableArityParametersArray() throws UnsupportedEncodingException { // if option is required at least once and can be specified multiple times: // -f=ARG [-f=ARG]... class Args { @Parameters(paramLabel = "APARAM", description = "APARAM description") String[] a; @Parameters(arity = "0..*", description = "b description") List<String> b; @Parameters(arity = "1..*", description = "c description") String[] c; @Parameters(arity = "2..*", description = "d description") List<String> d; } String expected = String.format("" + "Usage: <main class> [APARAM...] [<b>...] <c>... <d> <d>...%n" + " [APARAM...] APARAM description%n" + " [<b>...] b description%n" + " <c>... c description%n" + " <d> <d>... d description%n"); //CommandLine.usage(new Args(), System.out); assertEquals(expected, usageString(new Args(), Help.Ansi.OFF)); } @Test public void testUsageRangeArityParameterArray() throws UnsupportedEncodingException { class Args { @Parameters(index = "0", paramLabel = "PARAMA", arity = "0..1", description = "PARAMA description") List<String> a; @Parameters(index = "0", paramLabel = "PARAMB", arity = "1..2", description = "PARAMB description") String[] b; @Parameters(index = "0", paramLabel = "PARAMC", arity = "1..3", description = "PARAMC description") String[] c; @Parameters(index = "0", paramLabel = "PARAMD", arity = "2..4", description = "PARAMD description") String[] d; } String expected = String.format("" + "Usage: <main class> [PARAMA] PARAMB [PARAMB] PARAMC [PARAMC [PARAMC]] PARAMD%n" + " PARAMD [PARAMD [PARAMD]]%n" + " [PARAMA] PARAMA description%n" + " PARAMB [PARAMB] PARAMB description%n" + " PARAMC [PARAMC [PARAMC]]%n" + " PARAMC description%n" + " PARAMD PARAMD [PARAMD [PARAMD]]%n" + " PARAMD description%n"); //CommandLine.usage(new Args(), System.out); assertEquals(expected, usageString(new Args(), Help.Ansi.OFF)); } @Test public void testUsageFixedArityParametersArray() throws UnsupportedEncodingException { class Args { @Parameters(description = "a description (default arity)") String[] a; @Parameters(index = "0", arity = "0", description = "b description (arity=0)") String[] b; @Parameters(index = "1", arity = "1", description = "b description (arity=1)") String[] c; @Parameters(index = "2", arity = "2", description = "b description (arity=2)") String[] d; } String expected = String.format("" + "Usage: <main class> [<a>...] <c> <d> <d>%n" + " b description (arity=0)%n" + " [<a>...] a description (default arity)%n" + " <c> b description (arity=1)%n" + " <d> <d> b description (arity=2)%n"); //CommandLine.usage(new Args(), System.out); assertEquals(expected, usageString(new Args(), Help.Ansi.OFF)); } @Test public void testUsageVariableArityParametersMap() throws UnsupportedEncodingException { class Args { @Parameters() Map<String, String> a; @Parameters(arity = "0..*", description = "a description (arity=0..*)") Map<Integer, Integer> b; @Parameters(paramLabel = "KEY=VALUE", arity = "1..*", type = {String.class, TimeUnit.class}) Map<String, TimeUnit> c; @Parameters(arity = "2..*", type = {String.class, URL.class}, description = "description") Map<String, URL> d; } String expected = String.format("" + "Usage: <main class> [<String=String>...] [<Integer=Integer>...] KEY=VALUE...%n" + " <String=URL> <String=URL>...%n" + " [<String=String>...]%n" + " [<Integer=Integer>...] a description (arity=0..*)%n" + " KEY=VALUE...%n" + " <String=URL> <String=URL>...%n" + " description%n"); //CommandLine.usage(new Args(), System.out); assertEquals(expected, usageString(new Args(), Help.Ansi.OFF)); } @Test public void testUsageRangeArityParametersMap() throws UnsupportedEncodingException { class Args { @Parameters(index = "0", arity = "0..1"/*, type = {UUID.class, URL.class}*/, description = "a description") Map<UUID, URL> a; @Parameters(index = "1", arity = "1..2", type = {Long.class, UUID.class}, description = "b description") Map<?, ?> b; @Parameters(index = "2", arity = "1..3", type = {Long.class}, description = "c description") Map<?, ?> c; @Parameters(index = "3", paramLabel = "K=V", arity = "2..4", description = "d description") Map<?, ?> d; } String expected = String.format("" + "Usage: <main class> [<UUID=URL>] <Long=UUID> [<Long=UUID>] <String=String>%n" + " [<String=String> [<String=String>]] K=V K=V [K=V [K=V]]%n" + " [<UUID=URL>] a description%n" + " <Long=UUID> [<Long=UUID>]%n" + " b description%n" + " <String=String> [<String=String> [<String=String>]]%n" + " c description%n" + " K=V K=V [K=V [K=V]] d description%n"); //CommandLine.usage(new Args(), System.out); assertEquals(expected, usageString(new Args(), Help.Ansi.OFF)); } @Test public void testUsageFixedArityParametersMap() throws UnsupportedEncodingException { class Args { @Parameters(type = {Short.class, Field.class}, description = "a description") Map<Short, Field> a; @Parameters(index = "0", arity = "0", type = {UUID.class, Long.class}, description = "b description (arity=0)") @SuppressWarnings("unchecked") Map<?, ?> b; @Parameters(index = "1", arity = "1", description = "c description") Map<Long, File> c; @Parameters(index = "2", arity = "2", type = {URI.class, URL.class}, description = "d description") Map<URI, URL> d; } String expected = String.format("" + "Usage: <main class> [<Short=Field>...] <Long=File> <URI=URL> <URI=URL>%n" + " b description (arity=0)%n" + " [<Short=Field>...] a description%n" + " <Long=File> c description%n" + " <URI=URL> <URI=URL> d description%n"); //CommandLine.usage(new Args(), System.out); assertEquals(expected, usageString(new Args(), Help.Ansi.OFF)); } //---------- @Test public void testShortestFirstComparator_sortsShortestFirst() { String[] values = {"12345", "12", "123", "123456", "1", "", "1234"}; Arrays.sort(values, new Help.ShortestFirst()); String[] expected = {"", "1", "12", "123", "1234", "12345", "123456"}; assertArrayEquals(expected, values); } @Test public void testShortestFirstComparator_sortsShortestFirst2() { String[] values = {"12345", "12", "123", "123456", "1", "", "1234"}; Arrays.sort(values, Help.shortestFirst()); String[] expected = {"", "1", "12", "123", "1234", "12345", "123456"}; assertArrayEquals(expected, values); } @Test public void testShortestFirstComparator_sortsDeclarationOrderIfEqualLength() { String[] values = {"-d", "-", "-a", "--alpha", "--b", "--a", "--beta"}; Arrays.sort(values, new Help.ShortestFirst()); String[] expected = {"-", "-d", "-a", "--b", "--a", "--beta", "--alpha"}; assertArrayEquals(expected, values); } @Test public void testSortByShortestOptionNameComparator() throws Exception { class App { @Option(names = {"-t", "--aaaa"}) boolean aaaa; @Option(names = {"--bbbb", "-k"}) boolean bbbb; @Option(names = {"-c", "--cccc"}) boolean cccc; } OptionSpec[] fields = options(new App(), "aaaa", "bbbb", "cccc"); // -tkc Arrays.sort(fields, new Help.SortByShortestOptionNameAlphabetically()); OptionSpec[] expected = options(new App(), "cccc", "bbbb", "aaaa"); // -ckt assertEquals(expected[0], fields[0]); assertEquals(expected[1], fields[1]); assertEquals(expected[2], fields[2]); assertArrayEquals(expected, fields); } @Test public void testSortByOptionArityAndNameComparator_sortsByMaxThenMinThenName() throws Exception { class App { @Option(names = {"-t", "--aaaa"} ) boolean tImplicitArity0; @Option(names = {"-e", "--EEE"}, arity = "1" ) boolean explicitArity1; @Option(names = {"--bbbb", "-k"} ) boolean kImplicitArity0; @Option(names = {"--AAAA", "-a"} ) int aImplicitArity1; @Option(names = {"--BBBB", "-z"} ) String[] zImplicitArity1; @Option(names = {"--ZZZZ", "-b"}, arity = "1..3") String[] bExplicitArity1_3; @Option(names = {"-f", "--ffff"} ) boolean fImplicitArity0; } OptionSpec[] fields = options(new App(), "tImplicitArity0", "explicitArity1", "kImplicitArity0", "aImplicitArity1", "zImplicitArity1", "bExplicitArity1_3", "fImplicitArity0"); Arrays.sort(fields, new Help.SortByOptionArityAndNameAlphabetically()); OptionSpec[] expected = options(new App(), "fImplicitArity0", "kImplicitArity0", "tImplicitArity0", "aImplicitArity1", "explicitArity1", "zImplicitArity1", "bExplicitArity1_3"); assertArrayEquals(expected, fields); } @Test public void testSortByShortestOptionNameAlphabetically_handlesNulls() throws Exception { Help.SortByShortestOptionNameAlphabetically sort = new Help.SortByShortestOptionNameAlphabetically(); OptionSpec a = OptionSpec.builder("-a").build(); OptionSpec b = OptionSpec.builder("-b").build(); assertEquals(1, sort.compare(null, a)); assertEquals(-1, sort.compare(a, null)); assertEquals(-1, sort.compare(a, b)); assertEquals(0, sort.compare(a, a)); assertEquals(1, sort.compare(b, a)); } @Test public void testSortByOptionOrder() throws Exception { class App { @Option(names = {"-a"}, order = 9) boolean a; @Option(names = {"-b"}, order = 8) boolean b; @Option(names = {"-c"}, order = 7) boolean c; @Option(names = {"-d"}, order = 6) int d; @Option(names = {"-e"}, order = 5) String[] e; @Option(names = {"-f"}, order = 4) String[] f; @Option(names = {"-g"}, order = 3) boolean g; } OptionSpec[] fields = options(new App(), "a", "b", "c", "d", "e", "f", "g"); Arrays.sort(fields, Help.createOrderComparator()); OptionSpec[] expected = options(new App(), "g", "f", "e", "d", "c", "b", "a"); assertArrayEquals(expected, fields); } @Test public void testSortByOptionOrderAllowsGaps() throws Exception { @Command(sortOptions = false) class App { @Option(names = {"-a"}, order = 9) boolean a; @Option(names = {"-b"}, order = 8) boolean b; @Option(names = {"-c"}, order = 7) boolean c; @Option(names = {"-d"}, order = 6) int d; @Option(names = {"-e"}, order = 3) String[] e; @Option(names = {"-f"}, order = 1) String[] f; @Option(names = {"-g"}, order = 0) boolean g; } OptionSpec[] fields = options(new App(), "a", "b", "c", "d", "e", "f", "g"); Arrays.sort(fields, Help.createOrderComparator()); OptionSpec[] expected = options(new App(), "g", "f", "e", "d", "c", "b", "a"); assertArrayEquals(expected, fields); String expectedUsage = String.format("" + "Usage: <main class> [-abcg] [-d=<d>] [-e=<e>]... [-f=<f>]...%n" + " -g%n" + " -f=<f>%n" + " -e=<e>%n" + " -d=<d>%n" + " -c%n" + " -b%n" + " -a%n"); assertEquals(expectedUsage, new CommandLine(new App()).getUsageMessage()); } @Test public void testSortByOptionOrderStableSortWhenEqualOrder() throws Exception { @Command(sortOptions = false) class App { @Option(names = {"-a"}, order = 9) boolean a; @Option(names = {"-b"}, order = 8) boolean b; @Option(names = {"-c"}, order = 7) boolean c; @Option(names = {"-d"}, order = 7) int d; @Option(names = {"-e"}, order = 7) String[] e; @Option(names = {"-f"}, order = 7) String[] f; @Option(names = {"-g"}, order = 0) boolean g; } OptionSpec[] fields = options(new App(), "a", "b", "c", "d", "e", "f", "g"); Arrays.sort(fields, Help.createOrderComparator()); OptionSpec[] expected = options(new App(), "g", "c", "d", "e", "f", "b", "a"); assertArrayEquals(expected, fields); String expectedUsage = String.format("" + "Usage: <main class> [-abcg] [-d=<d>] [-e=<e>]... [-f=<f>]...%n" + " -g%n" + " -c%n" + " -d=<d>%n" + " -e=<e>%n" + " -f=<f>%n" + " -b%n" + " -a%n"); assertEquals(expectedUsage, new CommandLine(new App()).getUsageMessage()); } @Test public void testSortDeclarationOrderWhenOrderAttributeOmitted() { @Command(sortOptions = false) class App { @Option(names = {"-a"}) boolean a; @Option(names = {"-b"}) boolean b; @Option(names = {"-c"}) boolean c; @Option(names = {"-d"}) int d; @Option(names = {"-e"}) String[] e; @Option(names = {"-f"}) String[] f; @Option(names = {"-g"}) boolean g; } String expectedUsage = String.format("" + "Usage: <main class> [-abcg] [-d=<d>] [-e=<e>]... [-f=<f>]...%n" + " -a%n" + " -b%n" + " -c%n" + " -d=<d>%n" + " -e=<e>%n" + " -f=<f>%n" + " -g%n"); assertEquals(expectedUsage, new CommandLine(new App()).getUsageMessage()); } @Test public void testCreateMinimalOptionRenderer_ReturnsMinimalOptionRenderer() { assertEquals(Help.MinimalOptionRenderer.class, Help.createMinimalOptionRenderer().getClass()); } @Test public void testMinimalOptionRenderer_rendersFirstDeclaredOptionNameAndDescription() { class Example { @Option(names = {"---long", "-L"}, description = "long description") String longField; @Option(names = {"-b", "-a", "--alpha"}, description = "other") String otherField; } Help.IOptionRenderer renderer = Help.createMinimalOptionRenderer(); Help help = new Help(new Example(), Help.Ansi.ON); Help.IParamLabelRenderer parameterRenderer = help.createDefaultParamLabelRenderer(); OptionSpec option = help.options().get(0); Text[][] row1 = renderer.render(option, parameterRenderer, Help.defaultColorScheme( help.ansi())); assertEquals(1, row1.length); //assertArrayEquals(new String[]{"---long=<longField>", "long description"}, row1[0]); assertArrayEquals(new Text[]{ help.ansi().new Text(format("%s---long%s=%s<longField>%s", "@|fg(yellow) ", "|@", "@|italic ", "|@")), help.ansi().new Text("long description")}, row1[0]); OptionSpec option2 = help.options().get(1); Text[][] row2 = renderer.render(option2, parameterRenderer, Help.defaultColorScheme( help.ansi())); assertEquals(1, row2.length); //assertArrayEquals(new String[]{"-b=<otherField>", "other"}, row2[0]); assertArrayEquals(new Text[]{ help.ansi().new Text(format("%s-b%s=%s<otherField>%s", "@|fg(yellow) ", "|@", "@|italic ", "|@")), help.ansi().new Text("other")}, row2[0]); } @Test public void testCreateDefaultOptionRenderer_ReturnsDefaultOptionRenderer() { assertEquals(Help.DefaultOptionRenderer.class, new Help(new UsageDemo()).createDefaultOptionRenderer().getClass()); } @Test public void testDefaultOptionRenderer_rendersShortestOptionNameThenOtherOptionNamesAndDescription() { @Command(showDefaultValues = true) class Example { @Option(names = {"---long", "-L"}, description = "long description") String longField; @Option(names = {"-b", "-a", "--alpha"}, description = "other") String otherField = "abc"; } Help help = new Help(new Example()); Help.IOptionRenderer renderer = help.createDefaultOptionRenderer(); Help.IParamLabelRenderer parameterRenderer = help.createDefaultParamLabelRenderer(); OptionSpec option = help.options().get(0); Text[][] row1 = renderer.render(option, parameterRenderer, help.colorScheme()); assertEquals(1, row1.length); assertArrayEquals(Arrays.toString(row1[0]), textArray(help, "", "-L", ",", "---long=<longField>", "long description"), row1[0]); //assertArrayEquals(Arrays.toString(row1[1]), textArray(help, "", "", "", "", " Default: null"), row1[1]); // #201 don't show null defaults option = help.options().get(1); Text[][] row2 = renderer.render(option, parameterRenderer, help.colorScheme()); assertEquals(2, row2.length); assertArrayEquals(Arrays.toString(row2[0]), textArray(help, "", "-b", ",", "-a, --alpha=<otherField>", "other"), row2[0]); assertArrayEquals(Arrays.toString(row2[1]), textArray(help, "", "", "", "", " Default: abc"), row2[1]); } @Test public void testDefaultOptionRenderer_rendersSpecifiedMarkerForRequiredOptionsWithDefault() { @Command(requiredOptionMarker = '*', showDefaultValues = true) class Example { @Option(names = {"-b", "-a", "--alpha"}, required = true, description = "other") String otherField ="abc"; } Help help = new Help(new Example()); Help.IOptionRenderer renderer = help.createDefaultOptionRenderer(); Help.IParamLabelRenderer parameterRenderer = help.createDefaultParamLabelRenderer(); OptionSpec option = help.options().get(0); Text[][] row = renderer.render(option, parameterRenderer, help.colorScheme()); assertEquals(2, row.length); assertArrayEquals(Arrays.toString(row[0]), textArray(help, "*", "-b", ",", "-a, --alpha=<otherField>", "other"), row[0]); assertArrayEquals(Arrays.toString(row[1]), textArray(help, "", "", "", "", " Default: abc"), row[1]); } @Test public void testDefaultOptionRenderer_rendersSpecifiedMarkerForRequiredOptionsWithoutDefault() { @Command(requiredOptionMarker = '*') class Example { @Option(names = {"-b", "-a", "--alpha"}, required = true, description = "other") String otherField ="abc"; } Help help = new Help(new Example()); Help.IOptionRenderer renderer = help.createDefaultOptionRenderer(); Help.IParamLabelRenderer parameterRenderer = help.createDefaultParamLabelRenderer(); OptionSpec option = help.options().get(0); Text[][] row = renderer.render(option, parameterRenderer, help.colorScheme()); assertEquals(1, row.length); assertArrayEquals(Arrays.toString(row[0]), textArray(help, "*", "-b", ",", "-a, --alpha=<otherField>", "other"), row[0]); } @Test public void testDefaultOptionRenderer_rendersSpacePrefixByDefaultForRequiredOptionsWithoutDefaultValue() { class Example { @Option(names = {"-b", "-a", "--alpha"}, required = true, description = "other") String otherField; } Help help = new Help(new Example()); Help.IOptionRenderer renderer = help.createDefaultOptionRenderer(); Help.IParamLabelRenderer parameterRenderer = help.createDefaultParamLabelRenderer(); OptionSpec option = help.options().get(0); Text[][] row = renderer.render(option, parameterRenderer, help.colorScheme()); assertEquals(1, row.length); assertArrayEquals(Arrays.toString(row[0]), textArray(help, " ", "-b", ",", "-a, --alpha=<otherField>", "other"), row[0]); } @Test public void testDefaultOptionRenderer_rendersSpacePrefixByDefaultForRequiredOptionsWithDefaultValue() { //@Command(showDefaultValues = true) // set programmatically class Example { @Option(names = {"-b", "-a", "--alpha"}, required = true, description = "other") String otherField; } Help help = new Help(new Example()); help.commandSpec().usageMessage().showDefaultValues(true); Help.IOptionRenderer renderer = help.createDefaultOptionRenderer(); Help.IParamLabelRenderer parameterRenderer = help.createDefaultParamLabelRenderer(); OptionSpec option = help.options().get(0); Text[][] row = renderer.render(option, parameterRenderer, help.colorScheme()); assertEquals(1, row.length); assertArrayEquals(Arrays.toString(row[0]), textArray(help, " ", "-b", ",", "-a, --alpha=<otherField>", "other"), row[0]); // assertArrayEquals(Arrays.toString(row[1]), textArray(help, "", "", "", "", " Default: null"), row[1]); // #201 don't show null defaults } @Test public void testDefaultParameterRenderer_rendersSpacePrefixByDefaultForParametersWithPositiveArity() { class Required { @Parameters(description = "required") String required; } Help help = new Help(new Required()); Help.IParameterRenderer renderer = help.createDefaultParameterRenderer(); Help.IParamLabelRenderer parameterRenderer = Help.createMinimalParamLabelRenderer(); PositionalParamSpec param = help.positionalParameters().get(0); Text[][] row1 = renderer.render(param, parameterRenderer, help.colorScheme()); assertEquals(1, row1.length); assertArrayEquals(Arrays.toString(row1[0]), textArray(help, " ", "", "", "<required>", "required"), row1[0]); } @Test public void testDefaultParameterRenderer_rendersSpecifiedMarkerForParametersWithPositiveArity() { @Command(requiredOptionMarker = '*') class Required { @Parameters(description = "required") String required; } Help help = new Help(new Required()); Help.IParameterRenderer renderer = help.createDefaultParameterRenderer(); Help.IParamLabelRenderer parameterRenderer = Help.createMinimalParamLabelRenderer(); PositionalParamSpec param = help.positionalParameters().get(0); Text[][] row1 = renderer.render(param, parameterRenderer, help.colorScheme()); assertEquals(1, row1.length); assertArrayEquals(Arrays.toString(row1[0]), textArray(help, "*", "", "", "<required>", "required"), row1[0]); } @Test public void testDefaultParameterRenderer_rendersSpacePrefixForParametersWithZeroArity() { @Command(requiredOptionMarker = '*') class Optional { @Parameters(arity = "0..1", description = "optional") String optional; } Help help = new Help(new Optional()); Help.IParameterRenderer renderer = help.createDefaultParameterRenderer(); Help.IParamLabelRenderer parameterRenderer = Help.createMinimalParamLabelRenderer(); PositionalParamSpec param = help.positionalParameters().get(0); Text[][] row1 = renderer.render(param, parameterRenderer, help.colorScheme()); assertEquals(1, row1.length); assertArrayEquals(Arrays.toString(row1[0]), textArray(help, "", "", "", "<optional>", "optional"), row1[0]); } @Test public void testDefaultOptionRenderer_rendersCommaOnlyIfBothShortAndLongOptionNamesExist() { class Example { @Option(names = {"-v"}, description = "shortBool") boolean shortBoolean; @Option(names = {"--verbose"}, description = "longBool") boolean longBoolean; @Option(names = {"-x", "--xeno"}, description = "combiBool") boolean combiBoolean; @Option(names = {"-s"}, description = "shortOnly") String shortOnlyField; @Option(names = {"--long"}, description = "longOnly") String longOnlyField; @Option(names = {"-b", "--beta"}, description = "combi") String combiField; } Help help = new Help(new Example()); help.commandSpec().usageMessage().showDefaultValues(false); // omit default values from description column Help.IOptionRenderer renderer = help.createDefaultOptionRenderer(); Help.IParamLabelRenderer parameterRenderer = help.createDefaultParamLabelRenderer(); String[][] expected = new String[][] { {"", "-v", "", "", "shortBool"}, {"", "", "", "--verbose", "longBool"}, {"", "-x", ",", "--xeno", "combiBool"}, {"", "-s", "=", "<shortOnlyField>", "shortOnly"}, {"", "", "", "--long=<longOnlyField>", "longOnly"}, {"", "-b", ",", "--beta=<combiField>", "combi"}, }; int i = -1; for (OptionSpec option : help.options()) { Text[][] row = renderer.render(option, parameterRenderer, help.colorScheme()); assertEquals(1, row.length); assertArrayEquals(Arrays.toString(row[0]), textArray(help, expected[++i]), row[0]); } } @Test public void testDefaultOptionRenderer_omitsDefaultValuesForBooleanFields() { @Command(showDefaultValues = true) class Example { @Option(names = {"-v"}, description = "shortBool") boolean shortBoolean; @Option(names = {"--verbose"}, description = "longBool") Boolean longBoolean; @Option(names = {"-s"}, description = "shortOnly") String shortOnlyField = "short"; @Option(names = {"--long"}, description = "longOnly") String longOnlyField = "long"; @Option(names = {"-b", "--beta"}, description = "combi") int combiField = 123; } Help help = new Help(new Example()); Help.IOptionRenderer renderer = help.createDefaultOptionRenderer(); Help.IParamLabelRenderer parameterRenderer = help.createDefaultParamLabelRenderer(); String[][] expected = new String[][] { {"", "-v", "", "", "shortBool"}, {"", "", "", "--verbose", "longBool"}, {"", "-s", "=", "<shortOnlyField>", "shortOnly"}, {"", "", "", "", "Default: short"}, {"", "", "", "--long=<longOnlyField>", "longOnly"}, {"", "", "", "", "Default: long"}, {"", "-b", ",", "--beta=<combiField>", "combi"}, {"", "", "", "", "Default: 123"}, }; int[] rowCount = {1, 1, 2, 2, 2}; int i = -1; int rowIndex = 0; for (OptionSpec option : help.options()) { Text[][] row = renderer.render(option, parameterRenderer, help.colorScheme()); assertEquals(rowCount[++i], row.length); assertArrayEquals(Arrays.toString(row[0]), textArray(help, expected[rowIndex]), row[0]); rowIndex += rowCount[i]; } } @Test public void testCreateDefaultParameterRenderer_ReturnsDefaultParameterRenderer() { assertEquals(Help.DefaultParamLabelRenderer.class, new Help(new UsageDemo()).createDefaultParamLabelRenderer().getClass()); } @Test public void testDefaultParameterRenderer_showsParamLabelIfPresentOrFieldNameOtherwise() { class Example { @Option(names = "--without" ) String longField; @Option(names = "--with", paramLabel = "LABEL") String otherField; } Help help = new Help(new Example()); Help.IParamLabelRenderer equalSeparatedParameterRenderer = help.createDefaultParamLabelRenderer(); Help help2 = new Help(new Example()); help2.commandSpec().parser().separator(" "); Help.IParamLabelRenderer spaceSeparatedParameterRenderer = help2.createDefaultParamLabelRenderer(); String[] expected = new String[] { "<longField>", "LABEL", }; int i = -1; for (OptionSpec option : help.options()) { i++; Text withSpace = spaceSeparatedParameterRenderer.renderParameterLabel(option, help.ansi(), Collections.<IStyle>emptyList()); assertEquals(withSpace.toString(), " " + expected[i], withSpace.toString()); Text withEquals = equalSeparatedParameterRenderer.renderParameterLabel(option, help.ansi(), Collections.<IStyle>emptyList()); assertEquals(withEquals.toString(), "=" + expected[i], withEquals.toString()); } } @Test public void testDefaultParameterRenderer_appliesToPositionalArgumentsIgnoresSeparator() { class WithLabel { @Parameters(paramLabel = "POSITIONAL_ARGS") String positional; } class WithoutLabel { @Parameters() String positional; } Help withLabel = new Help(new WithLabel()); Help.IParamLabelRenderer equals = withLabel.createDefaultParamLabelRenderer(); withLabel.commandSpec().parser().separator("="); Help.IParamLabelRenderer spaced = withLabel.createDefaultParamLabelRenderer(); Text withSpace = spaced.renderParameterLabel(withLabel.positionalParameters().get(0), withLabel.ansi(), Collections.<IStyle>emptyList()); assertEquals(withSpace.toString(), "POSITIONAL_ARGS", withSpace.toString()); Text withEquals = equals.renderParameterLabel(withLabel.positionalParameters().get(0), withLabel.ansi(), Collections.<IStyle>emptyList()); assertEquals(withEquals.toString(), "POSITIONAL_ARGS", withEquals.toString()); Help withoutLabel = new Help(new WithoutLabel()); withSpace = spaced.renderParameterLabel(withoutLabel.positionalParameters().get(0), withoutLabel.ansi(), Collections.<IStyle>emptyList()); assertEquals(withSpace.toString(), "<positional>", withSpace.toString()); withEquals = equals.renderParameterLabel(withoutLabel.positionalParameters().get(0), withoutLabel.ansi(), Collections.<IStyle>emptyList()); assertEquals(withEquals.toString(), "<positional>", withEquals.toString()); } @Test public void testUsageOptions_hideParamSyntax_on() { class App { @Option(names = "-x1") String single; @Option(names = "-s1", arity = "2") String[] multi; @Option(names = "-x2", hideParamSyntax = true) String singleHide; @Option(names = "-s2", hideParamSyntax = true, arity = "2") String[] multiHide; @Option(names = "-o3", hideParamSyntax = false, split = ",") String[] multiSplit; @Option(names = "-s3", hideParamSyntax = true, split = ",") String[] multiHideSplit; } String actual = new CommandLine(new App()).getUsageMessage(Help.Ansi.OFF); String expected = String.format("" + "Usage: <main class> [-x1=<single>] [-x2=<singleHide>] [-o3=<multiSplit>[,%n" + " <multiSplit>...]]... [-s3=<multiHideSplit>]... [-s1=<multi>%n" + " <multi>]... [-s2=<multiHide>]...%n" + " -o3=<multiSplit>[,<multiSplit>...]%n" + "%n" + " -s1=<multi> <multi>%n" + " -s2=<multiHide>%n" + " -s3=<multiHideSplit>%n" + " -x1=<single>%n" + " -x2=<singleHide>%n"); assertEquals(expected, actual); } @Test public void testUsageParameters_hideParamSyntax_on() { class App { @Parameters() String single; @Parameters(arity = "2") String[] multi; @Parameters(hideParamSyntax = true) String singleHide; @Parameters(hideParamSyntax = true, arity = "2") String[] multiHide; @Parameters(hideParamSyntax = false, split = ",") String[] multiSplit; @Parameters(hideParamSyntax = true, split = ",") String[] multiHideSplit; } String actual = new CommandLine(new App()).getUsageMessage(Help.Ansi.OFF); String expected = String.format("" + "Usage: <main class> [<multiSplit>[,<multiSplit>...]...] <multiHideSplit>%n" + " <single> <singleHide> (<multi> <multi>)... <multiHide>%n" + " [<multiSplit>[,<multiSplit>...]...]%n" + "%n" + " <multiHideSplit>%n" + " <single>%n" + " <singleHide>%n" + " (<multi> <multi>)...%n" + " <multiHide>%n"); assertEquals(expected, actual); } @Test public void testDefaultParameterRenderer_hideParamSyntax_on() { class App { @Parameters(index = "0") String single; @Parameters(index = "1", arity = "2") String[] multi; @Parameters(index = "2", hideParamSyntax = true) String singleHide; @Parameters(index = "3", hideParamSyntax = true, arity = "2") String[] multiHide; @Parameters(index = "4", hideParamSyntax = false, arity = "*", split = ",") String[] multiSplit; @Parameters(index = "5", hideParamSyntax = true, arity = "*", split = ",") String[] multiHideSplit; } Help withLabel = new Help(new App(), Help.Ansi.OFF); withLabel.commandSpec().parser().separator("="); Help.IParamLabelRenderer equals = withLabel.createDefaultParamLabelRenderer(); withLabel.commandSpec().parser().separator(" "); Help.IParamLabelRenderer spaced = withLabel.createDefaultParamLabelRenderer(); String[] expected = new String[] { "<single>", // "<multi> <multi>", // "<singleHide>", // "<multiHide>", // "[<multiSplit>[,<multiSplit>...]...]", // "<multiHideSplit>", // }; for (int i = 0; i < expected.length; i++) { Text withEquals = equals.renderParameterLabel(withLabel.positionalParameters().get(i), withLabel.ansi(), Collections.<IStyle>emptyList()); Text withSpace = spaced.renderParameterLabel(withLabel.positionalParameters().get(i), withLabel.ansi(), Collections.<IStyle>emptyList()); assertEquals(withEquals.toString(), expected[i], withEquals.toString()); assertEquals(withSpace.toString(), expected[i], withSpace.toString()); } } @Test public void testDefaultLayout_addsEachRowToTable() { final Text[][] values = { textArray(Help.Ansi.OFF, "a", "b", "c", "d"), textArray(Help.Ansi.OFF, "1", "2", "3", "4") }; final int[] count = {0}; TextTable tt = TextTable.forDefaultColumns(Help.Ansi.OFF, UsageMessageSpec.DEFAULT_USAGE_WIDTH); tt = new TextTable(Help.Ansi.OFF, tt.columns()) { @Override public void addRowValues(Text[] columnValues) { assertArrayEquals(values[count[0]], columnValues); count[0]++; } }; Help.Layout layout = new Help.Layout(Help.defaultColorScheme(Help.Ansi.OFF), tt); layout.layout(null, values); assertEquals(2, count[0]); } @Test public void testAbreviatedSynopsis_withoutParameters() { @Command(abbreviateSynopsis = true) class App { @Option(names = {"--verbose", "-v"}) boolean verbose; @Option(names = {"--count", "-c"}) int count; @Option(names = {"--help", "-h"}, hidden = true) boolean helpRequested; } Help help = new Help(new App(), Help.Ansi.OFF); assertEquals("<main class> [OPTIONS]" + LINESEP, help.synopsis(0)); } @Test public void testAbreviatedSynopsis_withoutParameters_ANSI() { @Command(abbreviateSynopsis = true) class App { @Option(names = {"--verbose", "-v"}) boolean verbose; @Option(names = {"--count", "-c"}) int count; @Option(names = {"--help", "-h"}, hidden = true) boolean helpRequested; } Help help = new Help(new App(), Help.Ansi.ON); assertEquals(Help.Ansi.ON.new Text("@|bold <main class>|@ [OPTIONS]" + LINESEP).toString(), help.synopsis(0)); } @Test public void testAbreviatedSynopsis_commandNameCustomizableDeclaratively() throws UnsupportedEncodingException { @Command(abbreviateSynopsis = true, name = "aprogram") class App { @Option(names = {"--verbose", "-v"}) boolean verbose; @Option(names = {"--count", "-c"}) int count; @Option(names = {"--help", "-h"}, hidden = true) boolean helpRequested; @Parameters File[] files; } String expected = "" + "Usage: aprogram [OPTIONS] [<files>...]%n" + " [<files>...]%n" + " -c, --count=<count>%n" + " -v, --verbose%n"; String actual = usageString(new CommandLine(new App()), Help.Ansi.OFF); assertEquals(String.format(expected), actual); } @Test public void testAbreviatedSynopsis_commandNameCustomizableProgrammatically() throws UnsupportedEncodingException { @Command(abbreviateSynopsis = true) class App { @Option(names = {"--verbose", "-v"}) boolean verbose; @Option(names = {"--count", "-c"}) int count; @Option(names = {"--help", "-h"}, hidden = true) boolean helpRequested; @Parameters File[] files; } String expected = "" + "Usage: anotherProgram [OPTIONS] [<files>...]%n" + " [<files>...]%n" + " -c, --count=<count>%n" + " -v, --verbose%n"; String actual = usageString(new CommandLine(new App()).setCommandName("anotherProgram"), Help.Ansi.OFF); assertEquals(String.format(expected), actual); } @Test public void testSynopsis_commandNameCustomizableDeclaratively() throws UnsupportedEncodingException { @Command(name = "aprogram") class App { @Option(names = {"--verbose", "-v"}) boolean verbose; @Option(names = {"--count", "-c"}) int count; @Option(names = {"--help", "-h"}, hidden = true) boolean helpRequested; @Parameters File[] files; } String expected = "" + "Usage: aprogram [-v] [-c=<count>] [<files>...]%n" + " [<files>...]%n" + " -c, --count=<count>%n" + " -v, --verbose%n"; String actual = usageString(new CommandLine(new App()), Help.Ansi.OFF); assertEquals(String.format(expected), actual); } @Test public void testSynopsis_commandNameCustomizableProgrammatically() throws UnsupportedEncodingException { class App { @Option(names = {"--verbose", "-v"}) boolean verbose; @Option(names = {"--count", "-c"}) int count; @Option(names = {"--help", "-h"}, hidden = true) boolean helpRequested; @Parameters File[] files; } String expected = "" + "Usage: anotherProgram [-v] [-c=<count>] [<files>...]%n" + " [<files>...]%n" + " -c, --count=<count>%n" + " -v, --verbose%n"; String actual = usageString(new CommandLine(new App()).setCommandName("anotherProgram"), Help.Ansi.OFF); assertEquals(String.format(expected), actual); } @Test public void testSynopsis_optionalOptionArity1_n_withDefaultSeparator() { @Command() class App { @Option(names = {"--verbose", "-v"}) boolean verbose; @Option(names = {"--count", "-c"}, arity = "1..*") int count; @Option(names = {"--help", "-h"}, hidden = true) boolean helpRequested; } Help help = new Help(new App(), Help.Ansi.OFF); assertEquals("<main class> [-v] [-c=<count>...]" + LINESEP, help.synopsis(0)); } @Test public void testSynopsis_optionalOptionArity1_n_withDefaultSeparator_ANSI() { @Command() class App { @Option(names = {"--verbose", "-v"}) boolean verbose; @Option(names = {"--count", "-c"}, arity = "1..*") int count; @Option(names = {"--help", "-h"}, hidden = true) boolean helpRequested; } Help help = new Help(new App(), Help.Ansi.ON); assertEquals(Help.Ansi.ON.new Text("@|bold <main class>|@ [@|yellow -v|@] [@|yellow -c|@=@|italic <count>|@...]" + LINESEP), help.synopsis(0)); } @Test public void testSynopsis_optionalOptionArity0_1_withSpaceSeparator() { @Command(separator = " ") class App { @Option(names = {"--verbose", "-v"}) boolean verbose; @Option(names = {"--count", "-c"}, arity = "0..1") int count; @Option(names = {"--help", "-h"}, hidden = true) boolean helpRequested; } Help help = new Help(new App(), Help.Ansi.OFF); assertEquals("<main class> [-v] [-c [<count>]]" + LINESEP, help.synopsis(0)); } @Test public void testSynopsis_optionalOptionArity0_1_withSpaceSeparator_ANSI() { @Command(separator = " ") class App { @Option(names = {"--verbose", "-v"}) boolean verbose; @Option(names = {"--count", "-c"}, arity = "0..1") int count; @Option(names = {"--help", "-h"}, hidden = true) boolean helpRequested; } Help help = new Help(new App(), Help.Ansi.ON); assertEquals(Help.Ansi.ON.new Text("@|bold <main class>|@ [@|yellow -v|@] [@|yellow -c|@ [@|italic <count>|@]]" + LINESEP), help.synopsis(0)); } @Test public void testSynopsis_requiredOptionWithSeparator() { @Command() class App { @Option(names = {"--verbose", "-v"}) boolean verbose; @Option(names = {"--count", "-c"}, required = true) int count; @Option(names = {"--help", "-h"}, hidden = true) boolean helpRequested; } Help help = new Help(new App(), Help.Ansi.OFF); assertEquals("<main class> [-v] -c=<count>" + LINESEP, help.synopsis(0)); } @Test public void testSynopsis_requiredOptionWithSeparator_ANSI() { @Command() class App { @Option(names = {"--verbose", "-v"}) boolean verbose; @Option(names = {"--count", "-c"}, required = true) int count; @Option(names = {"--help", "-h"}, hidden = true) boolean helpRequested; } Help help = new Help(new App(), Help.Ansi.ON); assertEquals(Help.Ansi.ON.new Text("@|bold <main class>|@ [@|yellow -v|@] @|yellow -c|@=@|italic <count>|@" + LINESEP), help.synopsis(0)); } @Test public void testSynopsis_optionalOption_withSpaceSeparator() { @Command(separator = " ") class App { @Option(names = {"--verbose", "-v"}) boolean verbose; @Option(names = {"--count", "-c"}) int count; @Option(names = {"--help", "-h"}, hidden = true) boolean helpRequested; } Help help = new Help(new App(), Help.Ansi.OFF); assertEquals("<main class> [-v] [-c <count>]" + LINESEP, help.synopsis(0)); } @Test public void testSynopsis_optionalOptionArity0_1__withSeparator() { class App { @Option(names = {"--verbose", "-v"}) boolean verbose; @Option(names = {"--count", "-c"}, arity = "0..1") int count; @Option(names = {"--help", "-h"}, hidden = true) boolean helpRequested; } Help help = new Help(new App(), Help.Ansi.OFF); assertEquals("<main class> [-v] [-c[=<count>]]" + LINESEP, help.synopsis(0)); } @Test public void testSynopsis_optionalOptionArity0_n__withSeparator() { @Command(separator = "=") class App { @Option(names = {"--verbose", "-v"}) boolean verbose; @Option(names = {"--count", "-c"}, arity = "0..*") int count; @Option(names = {"--help", "-h"}, hidden = true) boolean helpRequested; } Help help = new Help(new App(), Help.Ansi.OFF); // NOTE Expected :<main class> [-v] [-c[=<count>]...] but arity=0 for int field is weird anyway... assertEquals("<main class> [-v] [-c[=<count>...]]" + LINESEP, help.synopsis(0)); } @Test public void testSynopsis_optionalOptionArity1_n__withSeparator() { @Command(separator = "=") class App { @Option(names = {"--verbose", "-v"}) boolean verbose; @Option(names = {"--count", "-c"}, arity = "1..*") int count; @Option(names = {"--help", "-h"}, hidden = true) boolean helpRequested; } Help help = new Help(new App(), Help.Ansi.OFF); assertEquals("<main class> [-v] [-c=<count>...]" + LINESEP, help.synopsis(0)); } @Test public void testSynopsis_withProgrammaticallySetSeparator_withParameters() throws UnsupportedEncodingException { class App { @Option(names = {"--verbose", "-v"}) boolean verbose; @Option(names = {"--count", "-c"}) int count; @Option(names = {"--help", "-h"}, hidden = true) boolean helpRequested; @Parameters File[] files; } CommandLine commandLine = new CommandLine(new App()).setSeparator(":"); String actual = usageString(commandLine, Help.Ansi.OFF); String expected = "" + "Usage: <main class> [-v] [-c:<count>] [<files>...]%n" + " [<files>...]%n" + " -c, --count:<count>%n" + " -v, --verbose%n"; assertEquals(String.format(expected), actual); } @Test public void testSynopsis_clustersBooleanOptions() { @Command(separator = "=") class App { @Option(names = {"--verbose", "-v"}) boolean verbose; @Option(names = {"--aaaa", "-a"}) boolean aBoolean; @Option(names = {"--xxxx", "-x"}) Boolean xBoolean; @Option(names = {"--count", "-c"}, paramLabel = "COUNT") int count; } Help help = new Help(new App(), Help.Ansi.OFF); assertEquals("<main class> [-avx] [-c=COUNT]" + LINESEP, help.synopsis(0)); } @Test public void testSynopsis_clustersRequiredBooleanOptions() { @Command(separator = "=") class App { @Option(names = {"--verbose", "-v"}, required = true) boolean verbose; @Option(names = {"--aaaa", "-a"}, required = true) boolean aBoolean; @Option(names = {"--xxxx", "-x"}, required = true) Boolean xBoolean; @Option(names = {"--count", "-c"}, paramLabel = "COUNT") int count; } Help help = new Help(new App(), Help.Ansi.OFF); assertEquals("<main class> -avx [-c=COUNT]" + LINESEP, help.synopsis(0)); } @Test public void testCustomSynopsis() { @Command(customSynopsis = { "<the-app> --number=NUMBER --other-option=<aargh>", " --more=OTHER --and-other-option=<aargh>", "<the-app> --number=NUMBER --and-other-option=<aargh>", }) class App {@Option(names = "--ignored") boolean ignored;} Help help = new Help(new App(), Help.Ansi.OFF); assertEquals(String.format( "<the-app> --number=NUMBER --other-option=<aargh>%n" + " --more=OTHER --and-other-option=<aargh>%n" + "<the-app> --number=NUMBER --and-other-option=<aargh>%n"), help.synopsis(0)); } @Test public void testTextTable() { TextTable table = TextTable.forDefaultColumns(Help.Ansi.OFF, UsageMessageSpec.DEFAULT_USAGE_WIDTH); table.addRowValues(textArray(Help.Ansi.OFF, "", "-v", ",", "--verbose", "show what you're doing while you are doing it")); table.addRowValues(textArray(Help.Ansi.OFF, "", "-p", null, null, "the quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog.")); assertEquals(String.format( " -v, --verbose show what you're doing while you are doing it%n" + " -p the quick brown fox jumped over the lazy dog. The%n" + " quick brown fox jumped over the lazy dog.%n" ,""), table.toString(new StringBuilder()).toString()); } @Test(expected = IllegalArgumentException.class) public void testTextTableAddsNewRowWhenTooManyValuesSpecified() { TextTable table = TextTable.forDefaultColumns(Help.Ansi.OFF, UsageMessageSpec.DEFAULT_USAGE_WIDTH); table.addRowValues(textArray(Help.Ansi.OFF, "", "-c", ",", "--create", "description", "INVALID", "Row 3")); // assertEquals(String.format("" + // " -c, --create description %n" + // " INVALID %n" + // " Row 3 %n" // ,""), table.toString(new StringBuilder()).toString()); } @Test public void testTextTableAddsNewRowWhenAnyColumnTooLong() { TextTable table = TextTable.forDefaultColumns(Help.Ansi.OFF, UsageMessageSpec.DEFAULT_USAGE_WIDTH); table.addRowValues("*", "-c", ",", "--create, --create2, --create3, --create4, --create5, --create6, --create7, --create8", "description"); assertEquals(String.format("" + "* -c, --create, --create2, --create3, --create4, --create5, --create6,%n" + " --create7, --create8%n" + " description%n" ,""), table.toString(new StringBuilder()).toString()); table = TextTable.forDefaultColumns(Help.Ansi.OFF, UsageMessageSpec.DEFAULT_USAGE_WIDTH); table.addRowValues("", "-c", ",", "--create, --create2, --create3, --create4, --create5, --create6, --createAA7, --create8", "description"); assertEquals(String.format("" + " -c, --create, --create2, --create3, --create4, --create5, --create6,%n" + " --createAA7, --create8%n" + " description%n" ,""), table.toString(new StringBuilder()).toString()); } @Test public void testCatUsageFormat() { @Command(name = "cat", customSynopsis = "cat [OPTIONS] [FILE...]", description = "Concatenate FILE(s), or standard input, to standard output.", footer = "Copyright(c) 2017") class Cat { @Parameters(paramLabel = "FILE", hidden = true, description = "Files whose contents to display") List<File> files; @Option(names = "--help", help = true, description = "display this help and exit") boolean help; @Option(names = "--version", help = true, description = "output version information and exit") boolean version; @Option(names = "-u", description = "(ignored)") boolean u; @Option(names = "-t", description = "equivalent to -vT") boolean t; @Option(names = "-e", description = "equivalent to -vET") boolean e; @Option(names = {"-A", "--show-all"}, description = "equivalent to -vET") boolean showAll; @Option(names = {"-s", "--squeeze-blank"}, description = "suppress repeated empty output lines") boolean squeeze; @Option(names = {"-v", "--show-nonprinting"}, description = "use ^ and M- notation, except for LDF and TAB") boolean v; @Option(names = {"-b", "--number-nonblank"}, description = "number nonempty output lines, overrides -n") boolean b; @Option(names = {"-T", "--show-tabs"}, description = "display TAB characters as ^I") boolean T; @Option(names = {"-E", "--show-ends"}, description = "display $ at end of each line") boolean E; @Option(names = {"-n", "--number"}, description = "number all output lines") boolean n; } ByteArrayOutputStream baos = new ByteArrayOutputStream(); CommandLine.usage(new Cat(), new PrintStream(baos), Help.Ansi.OFF); String expected = String.format( "Usage: cat [OPTIONS] [FILE...]%n" + "Concatenate FILE(s), or standard input, to standard output.%n" + " -A, --show-all equivalent to -vET%n" + " -b, --number-nonblank number nonempty output lines, overrides -n%n" + " -e equivalent to -vET%n" + " -E, --show-ends display $ at end of each line%n" + " -n, --number number all output lines%n" + " -s, --squeeze-blank suppress repeated empty output lines%n" + " -t equivalent to -vT%n" + " -T, --show-tabs display TAB characters as ^I%n" + " -u (ignored)%n" + " -v, --show-nonprinting use ^ and M- notation, except for LDF and TAB%n" + " --help display this help and exit%n" + " --version output version information and exit%n" + "Copyright(c) 2017%n", ""); assertEquals(expected, baos.toString()); } @Test public void testZipUsageFormat() { String expected = String.format("" + "Copyright (c) 1990-2008 Info-ZIP - Type 'zip \"-L\"' for software license.%n" + "Zip 3.0 (July 5th 2008). Command:%n" + "zip [-options] [-b path] [-t mmddyyyy] [-n suffixes] [zipfile list] [-xi list]%n" + " The default action is to add or replace zipfile entries from list, which%n" + " can include the special name - to compress standard input.%n" + " If zipfile and list are omitted, zip compresses stdin to stdout.%n" + " -f freshen: only changed files -u update: only changed or new files%n" + " -d delete entries in zipfile -m move into zipfile (delete OS files)%n" + " -r recurse into directories -j junk (don't record) directory names%n" + " -0 store only -l convert LF to CR LF (-ll CR LF to LF)%n" + " -1 compress faster -9 compress better%n" + " -q quiet operation -v verbose operation/print version info%n" + " -c add one-line comments -z add zipfile comment%n" + " -@ read names from stdin -o make zipfile as old as latest entry%n" + " -x exclude the following names -i include only the following names%n" + " -F fix zipfile (-FF try harder) -D do not add directory entries%n" + " -A adjust self-extracting exe -J junk zipfile prefix (unzipsfx)%n" + " -T test zipfile integrity -X eXclude eXtra file attributes%n" + " -y store symbolic links as the link instead of the referenced file%n" + " -e encrypt -n don't compress these suffixes%n" + " -h2 show more help%n"); assertEquals(expected, CustomLayoutDemo.createZipUsageFormat(Help.Ansi.OFF)); } @Test public void testNetstatUsageFormat() { String expected = String.format("" + "Displays protocol statistics and current TCP/IP network connections.%n" + "%n" + "NETSTAT [-a] [-b] [-e] [-f] [-n] [-o] [-p proto] [-q] [-r] [-s] [-t] [-x] [-y]%n" + " [interval]%n" + "%n" + " -a Displays all connections and listening ports.%n" + " -b Displays the executable involved in creating each connection or%n" + " listening port. In some cases well-known executables host%n" + " multiple independent components, and in these cases the%n" + " sequence of components involved in creating the connection or%n" + " listening port is displayed. In this case the executable name%n" + " is in [] at the bottom, on top is the component it called, and%n" + " so forth until TCP/IP was reached. Note that this option can be%n" + " time-consuming and will fail unless you have sufficient%n" + " permissions.%n" + " -e Displays Ethernet statistics. This may be combined with the -s%n" + " option.%n" + " -f Displays Fully Qualified Domain Names (FQDN) for foreign%n" + " addresses.%n" + " -n Displays addresses and port numbers in numerical form.%n" + " -o Displays the owning process ID associated with each connection.%n" + " -p proto Shows connections for the protocol specified by proto; proto%n" + " may be any of: TCP, UDP, TCPv6, or UDPv6. If used with the -s%n" + " option to display per-protocol statistics, proto may be any of:%n" + " IP, IPv6, ICMP, ICMPv6, TCP, TCPv6, UDP, or UDPv6.%n" + " -q Displays all connections, listening ports, and bound%n" + " nonlistening TCP ports. Bound nonlistening ports may or may not%n" + " be associated with an active connection.%n" + " -r Displays the routing table.%n" + " -s Displays per-protocol statistics. By default, statistics are%n" + " shown for IP, IPv6, ICMP, ICMPv6, TCP, TCPv6, UDP, and UDPv6;%n" + " the -p option may be used to specify a subset of the default.%n" + " -t Displays the current connection offload state.%n" + " -x Displays NetworkDirect connections, listeners, and shared%n" + " endpoints.%n" + " -y Displays the TCP connection template for all connections.%n" + " Cannot be combined with the other options.%n" + " interval Redisplays selected statistics, pausing interval seconds%n" + " between each display. Press CTRL+C to stop redisplaying%n" + " statistics. If omitted, netstat will print the current%n" + " configuration information once.%n" , ""); assertEquals(expected, CustomLayoutDemo.createNetstatUsageFormat(Help.Ansi.OFF)); } @Test public void testUsageIndexedPositionalParameters() throws UnsupportedEncodingException { @Command() class App { @Parameters(index = "0", description = "source host") InetAddress host1; @Parameters(index = "1", description = "source port") int port1; @Parameters(index = "2", description = "destination host") InetAddress host2; @Parameters(index = "3", arity = "1..2", description = "destination port range") int[] port2range; @Parameters(index = "4..*", description = "files to transfer") String[] files; @Parameters(hidden = true) String[] all; } String actual = usageString(new App(), Help.Ansi.OFF); String expected = String.format( "Usage: <main class> <host1> <port1> <host2> <port2range> [<port2range>]%n" + " [<files>...]%n" + " <host1> source host%n" + " <port1> source port%n" + " <host2> destination host%n" + " <port2range> [<port2range>]%n" + " destination port range%n" + " [<files>...] files to transfer%n" ); assertEquals(expected, actual); } @Command(name = "base", abbreviateSynopsis = true, commandListHeading = "c o m m a n d s", customSynopsis = "cust", description = "base description", descriptionHeading = "base descr heading", footer = "base footer", footerHeading = "base footer heading", header = "base header", headerHeading = "base header heading", optionListHeading = "base option heading", parameterListHeading = "base param heading", requiredOptionMarker = '&', separator = ";", showDefaultValues = true, sortOptions = false, synopsisHeading = "abcd") class Base { } @Test public void testAttributesInheritedWhenSubclassingForReuse() throws UnsupportedEncodingException { @Command class EmptySub extends Base {} Help help = new Help(new EmptySub()); assertEquals("base", help.commandName()); assertEquals(String.format("cust%n"), help.synopsis(0)); assertEquals(String.format("cust%n"), help.customSynopsis()); assertEquals(String.format("base%n"), help.abbreviatedSynopsis()); assertEquals(String.format("base%n"), help.detailedSynopsis(0,null, true)); assertEquals("abcd", help.synopsisHeading()); assertEquals("", help.commandList()); assertEquals("", help.commandListHeading()); assertEquals("c o m m a n d s", help.commandSpec().usageMessage().commandListHeading()); assertEquals(String.format("base description%n"), help.description()); assertEquals("base descr heading", help.descriptionHeading()); assertEquals(String.format("base footer%n"), help.footer()); assertEquals("base footer heading", help.footerHeading()); assertEquals(String.format("base header%n"), help.header()); assertEquals("base header heading", help.headerHeading()); assertEquals("", help.optionList()); assertEquals("", help.optionListHeading()); assertEquals("base option heading", help.commandSpec().usageMessage().optionListHeading()); assertEquals("", help.parameterList()); assertEquals("", help.parameterListHeading()); assertEquals("base param heading", help.commandSpec().usageMessage().parameterListHeading()); assertEquals(";", help.commandSpec().parser().separator()); assertEquals('&', help.commandSpec().usageMessage().requiredOptionMarker()); assertTrue(help.commandSpec().usageMessage().abbreviateSynopsis()); assertTrue(help.commandSpec().usageMessage().showDefaultValues()); assertFalse(help.commandSpec().usageMessage().sortOptions()); } @Test public void testSubclassAttributesOverrideEmptySuper() { @Command class EmptyBase {} @Command(name = "base", abbreviateSynopsis = true, commandListHeading = "c o m m a n d s", customSynopsis = "cust", description = "base description", descriptionHeading = "base descr heading", footer = "base footer", footerHeading = "base footer heading", header = "base header", headerHeading = "base header heading", optionListHeading = "base option heading", parameterListHeading = "base param heading", requiredOptionMarker = '&', separator = ";", showDefaultValues = true, sortOptions = false, synopsisHeading = "abcd", subcommands = Sub.class) class FullBase extends EmptyBase{ } Help help = new Help(new FullBase()); assertEquals("base", help.commandName()); assertEquals(String.format("cust%n"), help.synopsis(0)); assertEquals(String.format("cust%n"), help.customSynopsis()); assertEquals(String.format("base [COMMAND]%n"), help.abbreviatedSynopsis()); assertEquals(String.format("base [COMMAND]%n"), help.detailedSynopsis(0, null, true)); assertEquals("abcd", help.synopsisHeading()); assertEquals(String.format(" sub This is a subcommand%n"), help.commandList()); assertEquals("c o m m a n d s", help.commandListHeading()); assertEquals(String.format("base description%n"), help.description()); assertEquals("base descr heading", help.descriptionHeading()); assertEquals(String.format("base footer%n"), help.footer()); assertEquals("base footer heading", help.footerHeading()); assertEquals(String.format("base header%n"), help.header()); assertEquals("base header heading", help.headerHeading()); assertEquals("", help.optionList()); assertEquals("base option heading", help.commandSpec().usageMessage().optionListHeading()); assertEquals("", help.optionListHeading()); // because no options assertEquals("", help.parameterList()); assertEquals("base param heading", help.commandSpec().usageMessage().parameterListHeading()); assertEquals("", help.parameterListHeading()); // because no parameters assertTrue(help.commandSpec().usageMessage().abbreviateSynopsis()); assertTrue(help.commandSpec().usageMessage().showDefaultValues()); assertFalse(help.commandSpec().usageMessage().sortOptions()); assertEquals(";", help.commandSpec().parser().separator()); assertEquals('&', help.commandSpec().usageMessage().requiredOptionMarker()); } @Test public void testSubclassAttributesOverrideSuperValues() { @Command(name = "sub", abbreviateSynopsis = false, commandListHeading = "subc o m m a n d s", customSynopsis = "subcust", description = "sub description", descriptionHeading = "sub descr heading", footer = "sub footer", footerHeading = "sub footer heading", header = "sub header", headerHeading = "sub header heading", optionListHeading = "sub option heading", parameterListHeading = "sub param heading", requiredOptionMarker = '%', separator = ":", showDefaultValues = false, sortOptions = true, synopsisHeading = "xyz") class FullSub extends Base{ } Help help = new Help(new FullSub()); assertEquals("sub", help.commandName()); assertEquals(String.format("subcust%n"), help.synopsis(0)); assertEquals(String.format("subcust%n"), help.customSynopsis()); assertEquals(String.format("sub%n"), help.abbreviatedSynopsis()); assertEquals(String.format("sub%n"), help.detailedSynopsis(0,null, true)); assertEquals("xyz", help.synopsisHeading()); assertEquals("", help.commandList()); assertEquals("", help.commandListHeading()); // empty: no commands assertEquals("subc o m m a n d s", help.commandSpec().usageMessage().commandListHeading()); assertEquals(String.format("sub description%n"), help.description()); assertEquals("sub descr heading", help.descriptionHeading()); assertEquals(String.format("sub footer%n"), help.footer()); assertEquals("sub footer heading", help.footerHeading()); assertEquals(String.format("sub header%n"), help.header()); assertEquals("sub header heading", help.headerHeading()); assertEquals("", help.optionList()); assertEquals("", help.optionListHeading()); assertEquals("sub option heading", help.commandSpec().usageMessage().optionListHeading()); assertEquals("", help.parameterList()); assertEquals("", help.parameterListHeading()); assertEquals("sub param heading", help.commandSpec().usageMessage().parameterListHeading()); assertTrue(help.commandSpec().usageMessage().abbreviateSynopsis()); assertTrue(help.commandSpec().usageMessage().showDefaultValues()); assertFalse(help.commandSpec().usageMessage().sortOptions()); assertEquals(":", help.commandSpec().parser().separator()); assertEquals('%', help.commandSpec().usageMessage().requiredOptionMarker()); } static class UsageDemo { @Option(names = "-a", description = "boolean option with short name only") boolean a; @Option(names = "-b", paramLabel = "INT", description = "short option with a parameter") int b; @Option(names = {"-c", "--c-option"}, description = "boolean option with short and long name") boolean c; @Option(names = {"-d", "--d-option"}, paramLabel = "FILE", description = "option with parameter and short and long name") File d; @Option(names = "--e-option", description = "boolean option with only a long name") boolean e; @Option(names = "--f-option", paramLabel = "STRING", description = "option with parameter and only a long name") String f; @Option(names = {"-g", "--g-option-with-a-name-so-long-that-it-runs-into-the-descriptions-column"}, description = "boolean option with short and long name") boolean g; @Parameters(index = "0", paramLabel = "0BLAH", description = "first parameter") String param0; @Parameters(index = "1", paramLabel = "1PARAMETER-with-a-name-so-long-that-it-runs-into-the-descriptions-column", description = "2nd parameter") String param1; @Parameters(index = "2..*", paramLabel = "remaining", description = "remaining parameters") String param2_n; @Parameters(index = "*", paramLabel = "all", description = "all parameters") String param_n; } @Test public void testSubclassedCommandHelp() { @Command(name = "parent", description = "parent description") class ParentOption { } @Command(name = "child", description = "child description") class ChildOption extends ParentOption { } String actual = usageString(new ChildOption(), Help.Ansi.OFF); assertEquals(String.format( "Usage: child%n" + "child description%n"), actual); } @Test public void testSynopsisOrderCorrectWhenParametersDeclaredOutOfOrder() { class WithParams { @Parameters(index = "1") String param1; @Parameters(index = "0") String param0; } Help help = new Help(new WithParams()); assertEquals(format("<main class> <param0> <param1>%n"), help.synopsis(0)); } @Test public void testSynopsisOrderCorrectWhenSubClassAddsParameters() { class BaseWithParams { @Parameters(index = "1") String param1; @Parameters(index = "0") String param0; } class SubWithParams extends BaseWithParams { @Parameters(index = "3") String param3; @Parameters(index = "2") String param2; } Help help = new Help(new SubWithParams()); assertEquals(format("<main class> <param0> <param1> <param2> <param3>%n"), help.synopsis(0)); } @Test public void testUsageNestedSubcommand() throws IOException { @Command(name = "main") class MainCommand { @Option(names = "-a") boolean a; @Option(names = "-h", help = true) boolean h;} @Command(name = "cmd1") class ChildCommand1 { @Option(names = "-b") boolean b; } @Command(name = "cmd2") class ChildCommand2 { @Option(names = "-c") boolean c; @Option(names = "-h", help = true) boolean h;} @Command(name = "sub11") class GrandChild1Command1 { @Option(names = "-d") boolean d; } @Command(name = "sub12") class GrandChild1Command2 { @Option(names = "-e") int e; } @Command(name = "sub21") class GrandChild2Command1 { @Option(names = "-h", help = true) boolean h; } @Command(name = "sub22") class GrandChild2Command2 { @Option(names = "-g") boolean g; } @Command(name = "sub22sub1") class GreatGrandChild2Command2_1 { @Option(names = "-h", help = true) boolean h; @Option(names = {"-t", "--type"}) String customType; } CommandLine commandLine = new CommandLine(new MainCommand()); commandLine .addSubcommand("cmd1", new CommandLine(new ChildCommand1()) .addSubcommand("sub11", new GrandChild1Command1()) .addSubcommand("sub12", new GrandChild1Command2()) ) .addSubcommand("cmd2", new CommandLine(new ChildCommand2()) .addSubcommand("sub21", new GrandChild2Command1()) .addSubcommand("sub22", new CommandLine(new GrandChild2Command2()) .addSubcommand("sub22sub1", new GreatGrandChild2Command2_1()) ) ); String main = usageString(commandLine, Help.Ansi.OFF); assertEquals(String.format("" + "Usage: main [-ah] [COMMAND]%n" + " -a%n" + " -h%n" + "Commands:%n" + " cmd1%n" + " cmd2%n"), main); String cmd2 = usageString(commandLine.getSubcommands().get("cmd2"), Help.Ansi.OFF); assertEquals(String.format("" + "Usage: main cmd2 [-ch] [COMMAND]%n" + " -c%n" + " -h%n" + "Commands:%n" + " sub21%n" + " sub22%n"), cmd2); String sub22 = usageString(commandLine.getSubcommands().get("cmd2").getSubcommands().get("sub22"), Help.Ansi.OFF); assertEquals(String.format("" + "Usage: main cmd2 sub22 [-g] [COMMAND]%n" + " -g%n" + "Commands:%n" + " sub22sub1%n"), sub22); } @Test public void testLayoutConstructorCreatesDefaultColumns() { ColorScheme colorScheme = new ColorScheme.Builder().build(); Help.Layout layout = new Help.Layout(colorScheme, 99); TextTable expected = TextTable.forDefaultColumns(Help.Ansi.OFF, 99); assertEquals(expected.columns().length, layout.table.columns().length); for (int i = 0; i < expected.columns().length; i++) { assertEquals(expected.columns()[i].indent, layout.table.columns()[i].indent); assertEquals(expected.columns()[i].width, layout.table.columns()[i].width); assertEquals(expected.columns()[i].overflow, layout.table.columns()[i].overflow); } } @Test public void testHelpCreateLayout_CreatesDefaultColumns() { Help help = new Help(CommandSpec.create(), new ColorScheme.Builder(Help.Ansi.OFF).build()); Help.Layout layout = help.createDefaultLayout(); int[] widthsForNoOptions = {2, 2, 1, 3, 72}; TextTable expected = TextTable.forDefaultColumns(Help.Ansi.OFF, 80); assertEquals(expected.columns().length, layout.table.columns().length); for (int i = 0; i < expected.columns().length; i++) { assertEquals(expected.columns()[i].indent, layout.table.columns()[i].indent); assertEquals(widthsForNoOptions[i], layout.table.columns()[i].width); assertEquals(expected.columns()[i].overflow, layout.table.columns()[i].overflow); } } @Test public void testMinimalParameterLabelRenderer() { Help.IParamLabelRenderer renderer = Help.createMinimalParamLabelRenderer(); assertEquals("", renderer.separator()); } @Test public void testMinimalOptionRenderer() { Help.MinimalOptionRenderer renderer = new Help.MinimalOptionRenderer(); Text[][] texts = renderer.render(OptionSpec.builder("-x").build(), Help.createMinimalParamLabelRenderer(), new ColorScheme.Builder().build()); assertEquals("", texts[0][1].plainString()); } @Test public void testMinimalParameterRenderer() { Help.MinimalParameterRenderer renderer = new Help.MinimalParameterRenderer(); Text[][] texts = renderer.render(PositionalParamSpec.builder().build(), Help.createMinimalParamLabelRenderer(), new ColorScheme.Builder().build()); assertEquals("", texts[0][1].plainString()); } @Test public void testTextTableConstructorRequiresAtLeastOneColumn() { try { new TextTable(Help.Ansi.OFF, new Help.Column[0]); } catch (IllegalArgumentException ex) { assertEquals("At least one column is required", ex.getMessage()); } } @Test public void testTextTablePutValue_DisallowsInvalidRowIndex() { TextTable tt = new TextTable(Help.Ansi.OFF, new Help.Column[] {new Help.Column(30, 2, Help.Column.Overflow.SPAN)}); try { tt.putValue(1, 0, Help.Ansi.OFF.text("abc")); } catch (IllegalArgumentException ex) { assertEquals("Cannot write to row 1: rowCount=0", ex.getMessage()); } } @Test public void testTextTablePutValue_NullOrEmpty() { TextTable tt = new TextTable(Help.Ansi.OFF, new Help.Column[] {new Help.Column(30, 2, Help.Column.Overflow.SPAN)}); tt.addEmptyRow(); TextTable.Cell cell00 = tt.putValue(0, 0, null); assertEquals(0, cell00.column); assertEquals(0, cell00.row); TextTable.Cell other00 = tt.putValue(0, 0, Help.Ansi.EMPTY_TEXT); assertEquals(0, other00.column); assertEquals(0, other00.row); } @Test public void testTextTableAddRowValues() { TextTable tt = new TextTable(Help.Ansi.OFF, new Help.Column[] {new Help.Column(30, 2, Help.Column.Overflow.SPAN)}); tt.addRowValues(new String[] {null}); assertEquals(Help.Ansi.EMPTY_TEXT, tt.textAt(0, 0)); } @SuppressWarnings("deprecation") @Test public void testTextTableCellAt() { TextTable tt = new TextTable(Help.Ansi.OFF, new Help.Column[] {new Help.Column(30, 2, Help.Column.Overflow.SPAN)}); tt.addRowValues(new String[] {null}); assertEquals(Help.Ansi.EMPTY_TEXT, tt.cellAt(0, 0)); } @Test public void testJoin() throws Exception { Method m = Help.class.getDeclaredMethod("join", String[].class, int.class, int.class, String.class); m.setAccessible(true); String result = (String) m.invoke(null, (String[]) null, 0, 0, "abc"); assertEquals("", result); } @Test public void testFormat() throws Exception { Method m = CommandLine.class.getDeclaredMethod("format", String.class, Object[].class); m.setAccessible(true); String result = (String) m.invoke(null, (String) null, new Object[]{"abc"}); assertEquals("", result); } @Test @Deprecated public void testJoin2Deprecated() { StringBuilder sb = Help.join(Help.Ansi.OFF, 80, null, new StringBuilder("abc")); assertEquals("abc", sb.toString()); } @Test public void testJoin2() { StringBuilder sb = Help.join(Help.Ansi.OFF, 80, true,null, new StringBuilder("abc")); assertEquals("abc", sb.toString()); } @Test public void testCountTrailingSpaces() throws Exception { Method m = Help.class.getDeclaredMethod("countTrailingSpaces", String.class); m.setAccessible(true); int result = (Integer) m.invoke(null, (String) null); assertEquals(0, result); } @Test public void testHeading() throws Exception { Method m = Help.class.getDeclaredMethod("heading", Help.Ansi.class, int.class, boolean.class, String.class, Object[].class); m.setAccessible(true); String result = (String) m.invoke(null, Help.Ansi.OFF, 80, true, "\r\n", new Object[0]); assertEquals(String.format("%n"), result); String result2 = (String) m.invoke(null, Help.Ansi.OFF, 80, false, "boom", new Object[0]); assertEquals(String.format("boom"), result2); String result3 = (String) m.invoke(null, Help.Ansi.OFF, 80, true, null, new Object[0]); assertEquals("", result3); } @Test public void trimTrailingLineSeparator() { assertEquals("abc", Help.trimLineSeparator("abc")); String lineSep = System.getProperty("line.separator"); assertEquals("abc", Help.trimLineSeparator("abc" + lineSep)); assertEquals("abc" + lineSep, Help.trimLineSeparator("abc" + lineSep + lineSep)); } @Test public void testHelpCreateDetailedSynopsisOptionsText() { Help help = new Help(CommandSpec.create().addOption(OptionSpec.builder("xx").build()), new ColorScheme.Builder(Help.Ansi.OFF).build()); Text text = help.createDetailedSynopsisOptionsText(new ArrayList<ArgSpec>(), null, true); assertEquals(" [xx]", text.toString()); } @Test public void testAddAllSubcommands() { Help help = new Help(CommandSpec.create(), new ColorScheme.Builder(Help.Ansi.OFF).build()); help.addAllSubcommands(null); assertTrue(help.subcommands().isEmpty()); } @SuppressWarnings("deprecation") @Test public void testDetailedSynopsis() { Help help = new Help(CommandSpec.create(), new ColorScheme.Builder(Help.Ansi.OFF).build()); String str = help.detailedSynopsis(new Help.SortByShortestOptionNameAlphabetically(), true); assertEquals(String.format("<main class>%n"), str); } @Test public void testCreateDescriptionFirstLines() throws Exception { Method m = Help.class.getDeclaredMethod("createDescriptionFirstLines", Help.ColorScheme.class, Model.ArgSpec.class, String[].class, boolean[].class); m.setAccessible(true); String[][] input = new String[][] { new String[0], new String[] {""}, new String[] {"a", "b", "c"} }; Help.Ansi.Text[][] expectedOutput = new Help.Ansi.Text[][] { new Help.Ansi.Text[] {Help.Ansi.OFF.text("")}, new Help.Ansi.Text[] {Help.Ansi.OFF.text("")}, new Help.Ansi.Text[] {Help.Ansi.OFF.text("a"), Help.Ansi.OFF.text("b"), Help.Ansi.OFF.text("c")} }; for (int i = 0; i < input.length; i++) { String[] description = input[i]; Help.Ansi.Text[] result = (Help.Ansi.Text[]) m.invoke(null, new ColorScheme.Builder(Help.Ansi.OFF).build(), null, description, new boolean[3]); Help.Ansi.Text[] expected = expectedOutput[i]; for (int j = 0; j < result.length; j++) { assertEquals(expected[j], result[j]); } } } @Test public void testAbbreviatedSynopsis() { CommandSpec spec = CommandSpec.create(); spec.addPositional(PositionalParamSpec.builder().paramLabel("a").hidden(true).build()); spec.addPositional(PositionalParamSpec.builder().paramLabel("b").build()); Help help = new Help(spec, new ColorScheme.Builder(Help.Ansi.OFF).build()); String actual = help.abbreviatedSynopsis(); assertEquals(String.format("<main class> b...%n"), actual); } @SuppressWarnings("deprecation") @Test public void testSynopsis() { Help help = new Help(CommandSpec.create(), new ColorScheme.Builder(Help.Ansi.OFF).build()); String actual = help.synopsis(); assertEquals(String.format("<main class>%n"), actual); } @SuppressWarnings("deprecation") @Test public void testAddSubcommand() { @Command(name = "app", mixinStandardHelpOptions = true) class App { } Help help = new Help(new CommandLine(CommandSpec.create()).getCommandSpec(), new ColorScheme.Builder(Help.Ansi.OFF).build()); help.addSubcommand("boo", new App()); assertEquals(1, help.subcommands().size()); assertEquals("app", help.subcommands().get("boo").commandSpec().name()); } @Test public void testEmbeddedNewLinesInUsageSections() throws UnsupportedEncodingException { @Command(description = "first line\nsecond line\nthird line", headerHeading = "headerHeading1\nheaderHeading2", header = "header1\nheader2", descriptionHeading = "descriptionHeading1\ndescriptionHeading2", footerHeading = "footerHeading1\nfooterHeading2", footer = "footer1\nfooter2") class App { @Option(names = {"-v", "--verbose"}, description = "optionDescription1\noptionDescription2") boolean v; @Parameters(description = "paramDescription1\nparamDescription2") String file; } String actual = usageString(new App(), Help.Ansi.OFF); String expected = String.format("" + "headerHeading1%n" + "headerHeading2header1%n" + "header2%n" + "Usage: <main class> [-v] <file>%n" + "descriptionHeading1%n" + "descriptionHeading2first line%n" + "second line%n" + "third line%n" + " <file> paramDescription1%n" + " paramDescription2%n" + " -v, --verbose optionDescription1%n" + " optionDescription2%n" + "footerHeading1%n" + "footerHeading2footer1%n" + "footer2%n"); assertEquals(expected, actual); } @Test public void testRepeatingGroup() { class App { @Parameters(arity = "2", description = "description") String[] twoArgs; } String actual = usageString(new App(), Help.Ansi.OFF); String expected = String.format("" + "Usage: <main class> (<twoArgs> <twoArgs>)...%n" + " (<twoArgs> <twoArgs>)...%n" + " description%n"); assertEquals(expected, actual); } @Test public void testMapFieldHelp_with_unlimitedSplit() { class App { @Parameters(arity = "2", split = "\\|", paramLabel = "FIXTAG=VALUE", description = "Repeating group of two lists of vertical bar '|'-separated FIXTAG=VALUE pairs.") Map<Integer,String> message; @Option(names = {"-P", "-map"}, split = ",", paramLabel = "TIMEUNIT=VALUE", description = "Any number of TIMEUNIT=VALUE pairs. These may be specified separately (-PTIMEUNIT=VALUE) or as a comma-separated list.") Map<TimeUnit, String> map; } String actual = usageString(new App(), Help.Ansi.OFF); String expected = String.format("" + "Usage: <main class> [-P=TIMEUNIT=VALUE[,TIMEUNIT=VALUE...]]... (FIXTAG=VALUE%n" + " [\\|FIXTAG=VALUE...] FIXTAG=VALUE[\\|FIXTAG=VALUE...])...%n" + " (FIXTAG=VALUE[\\|FIXTAG=VALUE...] FIXTAG=VALUE[\\|FIXTAG=VALUE...])...%n" + " Repeating group of two lists of vertical bar '|'-separated%n" + " FIXTAG=VALUE pairs.%n" + " -P, -map=TIMEUNIT=VALUE[,TIMEUNIT=VALUE...]%n" + " Any number of TIMEUNIT=VALUE pairs. These may be specified separately%n" + " (-PTIMEUNIT=VALUE) or as a comma-separated list.%n"); assertEquals(expected, actual); } @Test public void testMapFieldHelpSplit_with_limitSplit() { class App { @Parameters(arity = "2", split = "\\|", paramLabel = "FIXTAG=VALUE", description = "Exactly two lists of vertical bar '|'-separated FIXTAG=VALUE pairs.") Map<Integer,String> message; @Option(names = {"-P", "-map"}, split = ",", paramLabel = "TIMEUNIT=VALUE", description = "Any number of TIMEUNIT=VALUE pairs. These may be specified separately (-PTIMEUNIT=VALUE) or as a comma-separated list.") Map<TimeUnit, String> map; } CommandSpec spec = CommandSpec.forAnnotatedObject(new App()); spec.parser().limitSplit(true); String actual = usageString(new CommandLine(spec), Help.Ansi.OFF); String expected = String.format("" + "Usage: <main class> [-P=TIMEUNIT=VALUE[,TIMEUNIT=VALUE]...]...%n" + " (FIXTAG=VALUE\\|FIXTAG=VALUE)...%n" + " (FIXTAG=VALUE\\|FIXTAG=VALUE)...%n" + " Exactly two lists of vertical bar '|'-separated FIXTAG=VALUE pairs.%n" + " -P, -map=TIMEUNIT=VALUE[,TIMEUNIT=VALUE]...%n" + " Any number of TIMEUNIT=VALUE pairs. These may be specified separately%n" + " (-PTIMEUNIT=VALUE) or as a comma-separated list.%n"); assertEquals(expected, actual); } // def cli = new CliBuilder(name:'ant', // header:'Options:') // cli.help('print this message') // cli.logfile(type:File, argName:'file', 'use given file for log') // cli.D(type:Map, argName:'property=value', args: '+', 'use value for given property') // cli.lib(argName:'path', valueSeparator:',', args: '3', // 'comma-separated list of up to 3 paths to search for jars and classes') @Test public void testMultiValueCliBuilderCompatibility() { class App { @Option(names = "--help", description = "print this message") boolean help; @Option(names = "--logfile", description = "use given file for log") File file; @Option(names = "-P", arity = "0..*", paramLabel = "<key=ppp>", description = "use value for project key") Map projectMap; @Option(names = "-D", arity = "1..*", paramLabel = "<key=ddd>", description = "use value for given property") Map map; @Option(names = "-S", arity = "0..*", split = ",", paramLabel = "<key=sss>", description = "use value for project key") Map sss; @Option(names = "-T", arity = "1..*", split = ",", paramLabel = "<key=ttt>", description = "use value for given property") Map ttt; @Option(names = "--x", arity = "0..2", split = ",", description = "comma-separated list of up to 2 xxx's") String[] x; @Option(names = "--y", arity = "3", split = ",", description = "exactly 3 y's") String[] y; @Option(names = "--lib", arity = "1..3", split = ",", description = "comma-separated list of up to 3 paths to search for jars and classes") String[] path; } CommandSpec spec = CommandSpec.forAnnotatedObject(new App()); spec.parser().limitSplit(true); String actual = usageString(new CommandLine(spec), Help.Ansi.OFF); String expected = String.format("" + "Usage: <main class> [--help] [--logfile=<file>] [--x[=<x>[,<x>]]]...%n" + " [--lib=<path>[,<path>[,<path>]]]... [--y=<y>,<y>,<y>]... [-P%n" + " [=<key=ppp>...]]... [-S[=<key=sss>[,<key=sss>]...]]...%n" + " [-D=<key=ddd>...]... [-T=<key=ttt>[,<key=ttt>]...]...%n" + " -D=<key=ddd>... use value for given property%n" + " --help print this message%n" + " --lib=<path>[,<path>[,<path>]]%n" + " comma-separated list of up to 3 paths to search for%n" + " jars and classes%n" + " --logfile=<file> use given file for log%n" + " -P=[<key=ppp>...] use value for project key%n" + " -S=[<key=sss>[,<key=sss>]...]%n" + " use value for project key%n" + " -T=<key=ttt>[,<key=ttt>]...%n" + " use value for given property%n" + " --x[=<x>[,<x>]] comma-separated list of up to 2 xxx's%n" + " --y=<y>,<y>,<y> exactly 3 y's%n" ); assertEquals(expected, actual); } @Test public void testMapFieldTypeInference() throws UnsupportedEncodingException { class App { @Option(names = "-a") Map<Integer, URI> a; @Option(names = "-b") Map<TimeUnit, StringBuilder> b; @SuppressWarnings("unchecked") @Option(names = "-c") Map c; @Option(names = "-d") List<File> d; @Option(names = "-e") Map<? extends Integer, ? super Long> e; @Option(names = "-f", type = {Long.class, Float.class}) Map<? extends Number, ? super Number> f; @SuppressWarnings("unchecked") @Option(names = "-g", type = {TimeUnit.class, Float.class}) Map<?, ?> g; } String actual = usageString(new App(), Help.Ansi.OFF); String expected = String.format("" + "Usage: <main class> [-a=<Integer=URI>]... [-b=<TimeUnit=StringBuilder>]...%n" + " [-c=<String=String>]... [-d=<d>]... [-e=<Integer=Long>]...%n" + " [-f=<Long=Float>]... [-g=<TimeUnit=Float>]...%n" + " -a=<Integer=URI>%n" + " -b=<TimeUnit=StringBuilder>%n" + "%n" + " -c=<String=String>%n" + " -d=<d>%n" + " -e=<Integer=Long>%n" + " -f=<Long=Float>%n" + " -g=<TimeUnit=Float>%n"); assertEquals(expected, actual); } @Test public void test200NPEWithEmptyCommandName() throws UnsupportedEncodingException { @Command(name = "") class Args {} String actual = usageString(new Args(), Help.Ansi.OFF); String expected = String.format("" + "Usage: %n" + ""); assertEquals(expected, actual); } @SuppressWarnings("deprecation") @Test public void testPrintHelpIfRequested1ReturnsTrueForUsageHelp() throws IOException { class App { @Option(names = "-h", usageHelp = true) boolean usageRequested; } List<CommandLine> list = new CommandLine(new App()).parse("-h"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); final PrintStream out = new PrintStream(baos); assertTrue(CommandLine.printHelpIfRequested(list, out, Help.Ansi.OFF)); String expected = String.format("" + "Usage: <main class> [-h]%n" + " -h%n"); assertEquals(expected, baos.toString()); } @Test public void testPrintHelpIfRequestedWithParseResultReturnsTrueForUsageHelp() throws IOException { class App { @Option(names = "-h", usageHelp = true) boolean usageRequested; } ParseResult parseResult = new CommandLine(new App()).parseArgs("-h"); assertTrue(CommandLine.printHelpIfRequested(parseResult)); String expected = String.format("" + "Usage: <main class> [-h]%n" + " -h%n"); assertEquals(expected, systemOutRule.getLog()); } @SuppressWarnings("deprecation") @Test public void testPrintHelpIfRequested2ReturnsTrueForUsageHelp() throws IOException { class App { @Option(names = "-h", usageHelp = true) boolean usageRequested; } List<CommandLine> list = new CommandLine(new App()).parse("-h"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); final PrintStream out = new PrintStream(baos); assertTrue(CommandLine.printHelpIfRequested(list, out, out, Help.Ansi.OFF)); String expected = String.format("" + "Usage: <main class> [-h]%n" + " -h%n"); assertEquals(expected, baos.toString()); } @SuppressWarnings("deprecation") @Test public void testPrintHelpIfRequestedWithCustomColorScheme() { ColorScheme customColorScheme = new ColorScheme.Builder(Help.Ansi.ON) .optionParams(Style.fg_magenta) .commands(Style.bg_cyan) .options(Style.fg_green) .parameters(Style.bg_white).build(); @Command(mixinStandardHelpOptions = true) class App { @Option(names = { "-f" }, paramLabel = "ARCHIVE", description = "the archive file") File archive; @Parameters(paramLabel = "POSITIONAL", description = "positional arg") String arg; } List<CommandLine> list = new CommandLine(new App()).parse("--help"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); final PrintStream out = new PrintStream(baos); assertTrue(CommandLine.printHelpIfRequested(list, out, out, customColorScheme)); String expected = Help.Ansi.ON.string(String.format("" + "Usage: @|bg_cyan <main class>|@ [@|green -hV|@] [@|green -f|@=@|magenta ARCHIVE|@] @|bg_white POSITIONAL|@%n" + "@|bg_white |@ @|bg_white POSITIONAL|@ positional arg%n" + " @|green -f|@=@|magenta A|@@|magenta RCHIVE|@ the archive file%n" + " @|green -h|@, @|green --help|@ Show this help message and exit.%n" + " @|green -V|@, @|green --version|@ Print version information and exit.%n")); assertEquals(expected, baos.toString()); } @SuppressWarnings("deprecation") @Test public void testPrintHelpIfRequestedReturnsTrueForVersionHelp() throws IOException { @Command(version = "abc 1.2.3 myversion") class App { @Option(names = "-V", versionHelp = true) boolean versionRequested; } List<CommandLine> list = new CommandLine(new App()).parse("-V"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); final PrintStream out = new PrintStream(baos); assertTrue(CommandLine.printHelpIfRequested(list, out, out, Help.Ansi.OFF)); String expected = String.format("abc 1.2.3 myversion%n"); assertEquals(expected, baos.toString()); } @SuppressWarnings("deprecation") @Test public void testPrintHelpIfRequestedReturnsFalseForNoHelp() throws IOException { class App { @Option(names = "-v") boolean verbose; } List<CommandLine> list = new CommandLine(new App()).parse("-v"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); final PrintStream out = new PrintStream(baos); assertFalse(CommandLine.printHelpIfRequested(list, out, out, Help.Ansi.OFF)); String expected = ""; assertEquals(expected, baos.toString()); } @Test public void testPrintHelpIfRequestedForHelpCommandThatDoesNotImplementIHelpCommandInitializable() { @Command(name = "help", helpCommand = true) class MyHelp implements Runnable { public void run() { } } @Command(subcommands = MyHelp.class) class App implements Runnable { public void run() { } } CommandLine cmd = new CommandLine(new App(), new InnerClassFactory(this)); ParseResult result = cmd.parseArgs("help"); assertTrue(CommandLine.printHelpIfRequested(result)); } @Command(name = "top", subcommands = {Sub.class}) static class Top { @Option(names = "-o", required = true) String mandatory; @Option(names = "-h", usageHelp = true) boolean isUsageHelpRequested; } @Command(name = "sub", description = "This is a subcommand") static class Sub {} @SuppressWarnings("deprecation") @Test public void test244SubcommandsNotParsed() { List<CommandLine> list = new CommandLine(new Top()).parse("-h", "sub"); assertEquals(2, list.size()); assertTrue(list.get(0).getCommand() instanceof Top); assertTrue(list.get(1).getCommand() instanceof Sub); assertTrue(((Top) list.get(0).getCommand()).isUsageHelpRequested); } @Test public void testDemoUsage() { String expected = String.format("" + " .__ .__ .__%n" + "______ |__| ____ ____ ____ | | |__|%n" + "\\____ \\| |/ ___\\/ _ \\_/ ___\\| | | |%n" + "| |_> > \\ \\__( <_> ) \\___| |_| |%n" + "| __/|__|\\___ >____/ \\___ >____/__|%n" + "|__| \\/ \\/%n" + "%n" + "Usage: picocli.Demo [-123airtV] [--simple]%n" + "%n" + "Demonstrates picocli subcommands parsing and usage help.%n" + "%n" + "Options:%n" + " -a, --autocomplete Generate sample autocomplete script for git%n" + " -1, --showUsageForSubcommandGitCommit%n" + " Shows usage help for the git-commit subcommand%n" + " -2, --showUsageForMainCommand%n" + " Shows usage help for a command with subcommands%n" + " -3, --showUsageForSubcommandGitStatus%n" + " Shows usage help for the git-status subcommand%n" + " --simple Show help for the first simple Example in the manual%n" + " -i, --index Show 256 color palette index values%n" + " -r, --rgb Show 256 color palette RGB component values%n" + " -t, --tests Runs all tests in this class%n" + " -V, --version Show version information and exit%n" + "%n" + "VM Options:%n" + "Run with -ea to enable assertions used in the tests.%n" + "Run with -Dpicocli.ansi=true to force picocli to use ansi codes,%n" + " or with -Dpicocli.ansi=false to force picocli to NOT use ansi codes.%n" + "(By default picocli will use ansi codes if the platform supports it.)%n" + "%n" + "If you would like to contribute or report an issue%n" + "go to github: https://github.com/remkop/picocli%n" + "%n" + "If you like the project star it on github and follow me on twitter!%n" + "This project is created and maintained by Remko Popma (@remkopopma)%n" + "%n"); assertEquals(expected, usageString(new Demo(), Help.Ansi.OFF)); } @Test public void testHelpCannotBeAddedAsSubcommand() { @Command(subcommands = Help.class) class App{} try { new CommandLine(new App(), new InnerClassFactory(this)); } catch (InitializationException ex) { assertEquals("picocli.CommandLine$Help is not a valid subcommand. Did you mean picocli.CommandLine$HelpCommand?", ex.getMessage()); } } @SuppressWarnings("deprecation") @Test public void testAutoHelpMixinUsageHelpOption() { @Command(mixinStandardHelpOptions = true) class App {} String[] helpOptions = {"-h", "--help"}; for (String option : helpOptions) { List<CommandLine> list = new CommandLine(new App()).parse(option); assertTrue(list.get(0).isUsageHelpRequested()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); final PrintStream out = new PrintStream(baos); assertTrue(CommandLine.printHelpIfRequested(list, out, out, Help.Ansi.OFF)); String expected = String.format("" + "Usage: <main class> [-hV]%n" + " -h, --help Show this help message and exit.%n" + " -V, --version Print version information and exit.%n"); assertEquals(expected, baos.toString()); } } @SuppressWarnings("deprecation") @Test public void testAutoHelpMixinVersionHelpOption() { @Command(mixinStandardHelpOptions = true, version = "1.2.3") class App {} String[] versionOptions = {"-V", "--version"}; for (String option : versionOptions) { List<CommandLine> list = new CommandLine(new App()).parse(option); assertTrue(list.get(0).isVersionHelpRequested()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); final PrintStream out = new PrintStream(baos); assertTrue(CommandLine.printHelpIfRequested(list, out, out, Help.Ansi.OFF)); String expected = String.format("1.2.3%n"); assertEquals(expected, baos.toString()); } } @SuppressWarnings("deprecation") @Test public void testAutoHelpMixinUsageHelpSubcommandOnAppWithoutSubcommands() { @Command(mixinStandardHelpOptions = true, subcommands = HelpCommand.class) class App {} List<CommandLine> list = new CommandLine(new App()).parse("help"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); final PrintStream out = new PrintStream(baos); assertTrue(CommandLine.printHelpIfRequested(list, out, out, Help.Ansi.OFF)); String expected = String.format("" + "Usage: <main class> [-hV] [COMMAND]%n" + " -h, --help Show this help message and exit.%n" + " -V, --version Print version information and exit.%n" + "Commands:%n" + " help Displays help information about the specified command%n"); assertEquals(expected, baos.toString()); } @Test public void testAutoHelpMixinRunHelpSubcommandOnAppWithoutSubcommands() { @Command(mixinStandardHelpOptions = true, subcommands = HelpCommand.class) class App implements Runnable{ public void run(){}} StringWriter sw = new StringWriter(); new CommandLine(new App()) .setOut(new PrintWriter(sw)) .setColorScheme(Help.defaultColorScheme(Help.Ansi.OFF)) .execute("help"); String expected = String.format("" + "Usage: <main class> [-hV] [COMMAND]%n" + " -h, --help Show this help message and exit.%n" + " -V, --version Print version information and exit.%n" + "Commands:%n" + " help Displays help information about the specified command%n"); assertEquals(expected, sw.toString()); } @Test public void testHelpSubcommandWithValidCommand() { @Command(subcommands = {Sub.class, HelpCommand.class}) class App implements Runnable{ public void run(){}} StringWriter sw = new StringWriter(); new CommandLine(new App()) .setOut(new PrintWriter(sw)) .setColorScheme(Help.defaultColorScheme(Help.Ansi.OFF)) .execute("help", "sub"); String expected = String.format("" + "Usage: <main class> sub%n" + "This is a subcommand%n"); assertEquals(expected, sw.toString()); } @Test public void testHelpSubcommandWithInvalidCommand() { @Command(mixinStandardHelpOptions = true, subcommands = {Sub.class, HelpCommand.class}) class App implements Runnable{ public void run(){}} StringWriter sw = new StringWriter(); new CommandLine(new App()) .setErr(new PrintWriter(sw)) .setColorScheme(Help.defaultColorScheme(Help.Ansi.OFF)) .execute("help", "abcd"); String expected = String.format("" + "Unknown subcommand 'abcd'.%n" + "Usage: <main class> [-hV] [COMMAND]%n" + " -h, --help Show this help message and exit.%n" + " -V, --version Print version information and exit.%n" + "Commands:%n" + " sub This is a subcommand%n" + " help Displays help information about the specified command%n"); assertEquals(expected, sw.toString()); } @Test public void testHelpSubcommandWithHelpOption() { @Command(subcommands = {Sub.class, HelpCommand.class}) class App implements Runnable{ public void run(){}} StringWriter sw = new StringWriter(); new CommandLine(new App()) .setOut(new PrintWriter(sw)) .setColorScheme(Help.defaultColorScheme(Help.Ansi.OFF)) .execute("help", "-h"); String expected = String.format("" + "Displays help information about the specified command%n" + "%n" + "Usage: <main class> help [-h] [COMMAND...]%n" + "%n" + "When no COMMAND is given, the usage help for the main command is displayed.%n" + "If a COMMAND is specified, the help for that command is shown.%n" + "%n" + " [COMMAND...] The COMMAND to display the usage help message for.%n" + " -h, --help Show usage help for the help command and exit.%n"); assertEquals(expected, sw.toString()); sw = new StringWriter(); new CommandLine(new App()).getSubcommands().get("help").usage(new PrintWriter(sw)); assertEquals(expected, sw.toString()); } @Test public void testHelpSubcommandWithoutCommand() { @Command(mixinStandardHelpOptions = true, subcommands = {Sub.class, HelpCommand.class}) class App implements Runnable{ public void run(){}} StringWriter sw = new StringWriter(); new CommandLine(new App()) .setOut(new PrintWriter(sw)) .setColorScheme(Help.defaultColorScheme(Help.Ansi.OFF)) .execute("help"); String expected = String.format("" + "Usage: <main class> [-hV] [COMMAND]%n" + " -h, --help Show this help message and exit.%n" + " -V, --version Print version information and exit.%n" + "Commands:%n" + " sub This is a subcommand%n" + " help Displays help information about the specified command%n"); assertEquals(expected, sw.toString()); sw = new StringWriter(); new CommandLine(new App()).usage(new PrintWriter(sw), Help.Ansi.OFF); assertEquals(expected, sw.toString()); } @Test public void testHelpSubcommandRunDoesNothingIfParentNotSet() { HelpCommand cmd = new HelpCommand(); cmd.run(); assertEquals("", this.systemOutRule.getLog()); } @SuppressWarnings({"deprecation"}) @Test public void testHelpSubcommandRunPrintsParentUsageIfParentSet() { HelpCommand cmd = new HelpCommand(); CommandLine help = new CommandLine(cmd); CommandSpec spec = CommandSpec.create().name("parent"); spec.usageMessage().description("the parent command"); spec.addSubcommand("parent", help); new CommandLine(spec); // make sure parent spec has a CommandLine cmd.init(help, Help.Ansi.OFF, System.out, System.err); cmd.run(); String expected = String.format("" + "Usage: parent [COMMAND]%n" + "the parent command%n" + "Commands:%n" + " parent Displays help information about the specified command%n"); assertEquals(expected, this.systemOutRule.getLog()); } @Test public void testHelpSubcommand2RunPrintsParentUsageIfParentSet() { HelpCommand cmd = new HelpCommand(); CommandLine help = new CommandLine(cmd); CommandSpec spec = CommandSpec.create().name("parent"); spec.usageMessage().description("the parent command"); spec.addSubcommand("parent", help); new CommandLine(spec); // make sure parent spec has a CommandLine cmd.init(help, Help.defaultColorScheme(Help.Ansi.OFF), new PrintWriter(System.out), new PrintWriter(System.err)); cmd.run(); String expected = String.format("" + "Usage: parent [COMMAND]%n" + "the parent command%n" + "Commands:%n" + " parent Displays help information about the specified command%n"); assertEquals(expected, this.systemOutRule.getLog()); } @Test public void testUsageHelpForNestedSubcommands() { @Command(name = "subsub", mixinStandardHelpOptions = true) class SubSub { } @Command(name = "sub", subcommands = {SubSub.class}) class Sub { } @Command(name = "main", subcommands = {Sub.class}) class App { } CommandLine app = new CommandLine(new App(), new InnerClassFactory(this)); //ParseResult result = app.parseArgs("sub", "subsub", "--help"); //CommandLine.printHelpIfRequested(result); CommandLine subsub = app.getSubcommands().get("sub").getSubcommands().get("subsub"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); subsub.usage(new PrintStream(baos), Help.Ansi.OFF); String expected = String.format("" + "Usage: main sub subsub [-hV]%n" + " -h, --help Show this help message and exit.%n" + " -V, --version Print version information and exit.%n"); assertEquals(expected, baos.toString()); } @Test public void testUsageTextWithHiddenSubcommand() { @Command(name = "foo", description = "This is a visible subcommand") class Foo { } @Command(name = "bar", description = "This is a hidden subcommand", hidden = true) class Bar { } @Command(name = "app", subcommands = {Foo.class, Bar.class}) class App { } CommandLine app = new CommandLine(new App(), new InnerClassFactory(this)); ByteArrayOutputStream baos = new ByteArrayOutputStream(); app.usage(new PrintStream(baos)); String expected = format("" + "Usage: app [COMMAND]%n" + "Commands:%n" + " foo This is a visible subcommand%n"); assertEquals(expected, baos.toString()); } @Test public void testUsage_NoHeaderIfAllSubcommandHidden() { @Command(name = "foo", description = "This is a foo sub-command", hidden = true) class Foo { } @Command(name = "bar", description = "This is a foo sub-command", hidden = true) class Bar { } @Command(name = "app", abbreviateSynopsis = true) class App { } CommandLine app = new CommandLine(new App()) .addSubcommand("foo", new Foo()) .addSubcommand("bar", new Bar()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); app.usage(new PrintStream(baos)); String expected = format("" + "Usage: app [COMMAND]%n"); assertEquals(expected, baos.toString()); } @Test public void test282BrokenValidationWhenNoOptionsToCompareWith() { class App implements Runnable { @Parameters(paramLabel = "FILES", arity = "1..*", description = "List of files") private List<File> files = new ArrayList<File>(); public void run() { } } String[] args = new String[] {"-unknown"}; StringWriter sw = new StringWriter(); new CommandLine(new App()) .setErr(new PrintWriter(sw)) .setColorScheme(Help.defaultColorScheme(Help.Ansi.OFF)) .execute(args); String expected = format("" + "Missing required parameter: FILES%n" + "Usage: <main class> FILES...%n" + " FILES... List of files%n"); assertEquals(expected, sw.toString()); } @Test public void test282ValidationWorksWhenOptionToCompareWithExists() { class App implements Runnable { @Parameters(paramLabel = "FILES", arity = "1..*", description = "List of files") private List<File> files = new ArrayList<File>(); @CommandLine.Option(names = {"-v"}, description = "Print output") private boolean verbose; public void run() { } } String[] args = new String[] {"-unknown"}; StringWriter sw = new StringWriter(); new CommandLine(new App()) .setErr(new PrintWriter(sw)) .setColorScheme(Help.defaultColorScheme(Help.Ansi.OFF)) .execute(args); String expected = format("" + "Missing required parameter: FILES%n" + "Usage: <main class> [-v] FILES...%n" + " FILES... List of files%n" + " -v Print output%n"); assertEquals(expected, sw.toString()); } @Test public void testShouldGetUsageWidthFromSystemProperties() { int defaultWidth = new UsageMessageSpec().width(); assertEquals(80, defaultWidth); try { System.setProperty("picocli.usage.width", "123"); int width = new UsageMessageSpec().width(); assertEquals(123, width); } finally { System.setProperty("picocli.usage.width", String.valueOf(defaultWidth)); } } @Test public void testInvalidUsageWidthPropertyValue() throws UnsupportedEncodingException { PrintStream originalErr = System.err; ByteArrayOutputStream baos = new ByteArrayOutputStream(2500); System.setErr(new PrintStream(baos)); System.clearProperty("picocli.trace"); System.setProperty("picocli.usage.width", "INVALID"); int actual = new UsageMessageSpec().width(); System.setErr(originalErr); System.clearProperty("picocli.usage.width"); assertEquals(80, actual); assertEquals(format("[picocli WARN] Invalid picocli.usage.width value 'INVALID'. Using usage width 80.%n"), baos.toString("UTF-8")); } @Test public void testUsageWidthFromCommandAttribute() { @Command(usageHelpWidth = 60, description = "0123456789012345678901234567890123456789012345678901234567890123456789") class App {} CommandLine cmd = new CommandLine(new App()); assertEquals(60, cmd.getUsageHelpWidth()); assertEquals(60, cmd.getCommandSpec().usageMessage().width()); } @Test public void testUsageWidthFromSystemPropertyOverridesCommandAttribute() { @Command(usageHelpWidth = 60, description = "0123456789012345678901234567890123456789012345678901234567890123456789") class App {} System.setProperty("picocli.usage.width", "123"); try { CommandLine cmd = new CommandLine(new App()); assertEquals(123, cmd.getUsageHelpWidth()); assertEquals(123, cmd.getCommandSpec().usageMessage().width()); } finally { System.clearProperty("picocli.usage.width"); } } @Test public void testInvalidUsageWidthCommandAttribute() throws UnsupportedEncodingException { @Command(usageHelpWidth = 40) class App {} try { new CommandLine(new App()); fail("Expected exception"); } catch (InitializationException ex) { assertEquals("Invalid usage message width 40. Minimum value is 55", ex.getMessage()); }; } @Test public void testTooSmallUsageWidthPropertyValue() throws UnsupportedEncodingException { PrintStream originalErr = System.err; ByteArrayOutputStream baos = new ByteArrayOutputStream(2500); System.setErr(new PrintStream(baos)); System.clearProperty("picocli.trace"); System.setProperty("picocli.usage.width", "54"); int actual = new UsageMessageSpec().width(); System.setErr(originalErr); System.clearProperty("picocli.usage.width"); assertEquals(55, actual); assertEquals(format("[picocli WARN] Invalid picocli.usage.width value 54. Using minimum usage width 55.%n"), baos.toString("UTF-8")); } @Test public void testTextTableWithLargeWidth() { TextTable table = TextTable.forDefaultColumns(Help.Ansi.OFF, 200); table.addRowValues(textArray(Help.Ansi.OFF, "", "-v", ",", "--verbose", "show what you're doing while you are doing it")); table.addRowValues(textArray(Help.Ansi.OFF, "", "-p", null, null, "the quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy doooooooooooooooog.")); assertEquals(String.format( " -v, --verbose show what you're doing while you are doing it%n" + " -p the quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy doooooooooooooooog.%n" ), table.toString(new StringBuilder()).toString()); } @Test public void testLongMultiLineSynopsisIndentedWithLargeWidth() { System.setProperty("picocli.usage.width", "200"); try { @Command(name = "<best-app-ever>") class App { @Option(names = "--long-option-name", paramLabel = "<long-option-value>") int a; @Option(names = "--another-long-option-name", paramLabel = "<another-long-option-value>") int b; @Option(names = "--third-long-option-name", paramLabel = "<third-long-option-value>") int c; @Option(names = "--fourth-long-option-name", paramLabel = "<fourth-long-option-value>") int d; } Help help = new Help(new App(), Help.Ansi.OFF); assertEquals(String.format( "<best-app-ever> [--another-long-option-name=<another-long-option-value>] [--fourth-long-option-name=<fourth-long-option-value>] [--long-option-name=<long-option-value>]%n" + " [--third-long-option-name=<third-long-option-value>]%n"), help.synopsis(0)); } finally { System.setProperty("picocli.usage.width", String.valueOf(UsageMessageSpec.DEFAULT_USAGE_WIDTH)); } } @Command(description = "The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog.") static class WideDescriptionApp { @Option(names = "-s", description = "The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The a quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog.") String shortOption; @Option(names = "--very-very-very-looooooooooooooooong-option-name", description = "The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog.") String lengthyOption; static final String expected = format("Usage: <main class> [-s=<shortOption>] [--very-very-very-looooooooooooooooong-option-name=<lengthyOption>]%n" + "The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The quick brown fox jumped%n" + "over the lazy dog. The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The%n" + "quick brown fox jumped over the lazy dog.%n" + " -s=<shortOption> The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The a%n" + " quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog.%n" + " --very-very-very-looooooooooooooooong-option-name=<lengthyOption>%n" + " The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The%n" + " quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog.%n" ); } @Test public void testWideUsageViaSystemProperty() { System.setProperty("picocli.usage.width", String.valueOf(120)); try { String actual = usageString(new WideDescriptionApp(), Help.Ansi.OFF); assertEquals(WideDescriptionApp.expected, actual); } finally { System.setProperty("picocli.usage.width", String.valueOf(80)); } } @Test public void testWideUsage() { CommandLine cmd = new CommandLine(new WideDescriptionApp()); cmd.setUsageHelpWidth(120); String actual = usageString(cmd, Help.Ansi.OFF); assertEquals(WideDescriptionApp.expected, actual); } @Test public void testUsageHelpAutoWidthViaSystemProperty() { CommandLine cmd = new CommandLine(new WideDescriptionApp()); assertFalse(cmd.isUsageHelpAutoWidth()); assertFalse(cmd.getCommandSpec().usageMessage().autoWidth()); System.setProperty("picocli.usage.width", "AUTO"); assertTrue(cmd.isUsageHelpAutoWidth()); assertTrue(cmd.getCommandSpec().usageMessage().autoWidth()); System.setProperty("picocli.usage.width", "TERM"); assertTrue(cmd.isUsageHelpAutoWidth()); assertTrue(cmd.getCommandSpec().usageMessage().autoWidth()); System.setProperty("picocli.usage.width", "TERMINAL"); assertTrue(cmd.isUsageHelpAutoWidth()); assertTrue(cmd.getCommandSpec().usageMessage().autoWidth()); System.setProperty("picocli.usage.width", "X"); assertFalse(cmd.isUsageHelpAutoWidth()); assertFalse(cmd.getCommandSpec().usageMessage().autoWidth()); } @Test public void testGetTerminalWidthLinux() { String sttyResult = "speed 38400 baud; rows 50; columns 123; line = 0;\n" + "intr = ^C; quit = ^\\; erase = ^?; kill = ^U; eof = ^D; eol = <undef>; eol2 = <undef>; swtch = ^Z; start = ^Q; stop = ^S;\n" + "susp = ^Z; rprnt = ^R; werase = ^W; lnext = ^V; discard = ^O; min = 1; time = 0;\n" + "-parenb -parodd cs8 -hupcl -cstopb cread -clocal -crtscts\n" + "-ignbrk brkint -ignpar -parmrk -inpck -istrip -inlcr -igncr icrnl ixon -ixoff -iuclc ixany imaxbel iutf8\n" + "opost -olcuc -ocrnl onlcr -onocr -onlret -ofill -ofdel nl0 cr0 tab0 bs0 vt0 ff0\n" + "isig icanon iexten echo echoe echok -echonl -noflsh -tostop echoctl echoke -flusho\n"; Pattern pattern = Pattern.compile(".*olumns(:)?\\s+(\\d+)\\D.*", Pattern.DOTALL); Matcher matcher = pattern.matcher(sttyResult); assertTrue(matcher.matches()); assertEquals(123, Integer.parseInt(matcher.group(2))); } @Test public void testGetTerminalWidthWindows() { String sttyResult = "\n" + "Status for device CON:\n" + "----------------------\n" + " Lines: 9001\n" + " Columns: 113\n" + " Keyboard rate: 31\n" + " Keyboard delay: 1\n" + " Code page: 932\n" + "\n"; Pattern pattern = Pattern.compile(".*olumns(:)?\\s+(\\d+)\\D.*", Pattern.DOTALL); Matcher matcher = pattern.matcher(sttyResult); assertTrue(matcher.matches()); assertEquals(113, Integer.parseInt(matcher.group(2))); } @Test public void testAutoWidthDisabledBySystemProperty() { @Command(usageHelpAutoWidth = true) class App {} System.setProperty("picocli.usage.width", "123"); CommandLine cmd = new CommandLine(new App()); assertFalse(cmd.isUsageHelpAutoWidth()); assertFalse(cmd.getCommandSpec().usageMessage().autoWidth()); assertEquals(123, cmd.getCommandSpec().usageMessage().width()); } @Test public void testAutoWidthEnabledProgrammatically() { @Command(usageHelpAutoWidth = true) class App {} CommandLine cmd = new CommandLine(new App()); assertTrue(cmd.isUsageHelpAutoWidth()); assertTrue(cmd.getCommandSpec().usageMessage().autoWidth()); // the below may fail when this test is running on Cygwin or MINGW assertEquals(80, cmd.getCommandSpec().usageMessage().width()); } @Test public void testCliBuilderLsExample() { @Command(name="ls") class App { @Option(names = "-a", description = "display all files") boolean a; @Option(names = "-l", description = "use a long listing format") boolean l; @Option(names = "-t", description = "sort by modification time") boolean t; } String actual = usageString(new App(), Help.Ansi.OFF); assertEquals(String.format("" + "Usage: ls [-alt]%n" + " -a display all files%n" + " -l use a long listing format%n" + " -t sort by modification time%n"), actual); } @Test public void testAnsiText() { String markup = "@|bg(red),white,underline some text|@"; Help.Ansi.Text txt = Help.Ansi.ON.text(markup); Help.Ansi.Text txt2 = Help.Ansi.ON.new Text(markup); assertEquals(txt, txt2); } @Test public void testAnsiString() { String msg = "some text"; String markup = "@|bg(red),white,underline " + msg + "|@"; String ansiTxt = Help.Ansi.ON.string(markup); String ansiTxt2 = Help.Ansi.ON.new Text(markup).toString(); assertEquals(ansiTxt, ansiTxt2); } @Test public void testAnsiValueOf() { assertEquals("true=ON", Help.Ansi.ON, Help.Ansi.valueOf(true)); assertEquals("false=OFF", Help.Ansi.OFF, Help.Ansi.valueOf(false)); } @Test public void testIssue430NewlineInSubcommandDescriptionList() { // courtesy [Benny Bottema](https://github.com/bbottema) CommandSpec rootCmd = createCmd("newlines", "Displays subcommands, one of which contains description newlines"); rootCmd.addSubcommand("subA", createCmd("subA", "regular description for subA")); rootCmd.addSubcommand("subB", createCmd("subB", "very,\nspecial,\nChristopher Walken style,\ndescription.")); rootCmd.addSubcommand("subC", createCmd("subC", "not so,%nspecial,%nJon Voight style,%ndescription.")); rootCmd.addSubcommand("subD", createCmd("subD", "regular description for subD")); assertEquals(String.format("" + "Usage: newlines [-hV] [COMMAND]%n" + "Displays subcommands, one of which contains description newlines%n" + " -h, --help Show this help message and exit.%n" + " -V, --version Print version information and exit.%n" + "Commands:%n" + " subA regular description for subA%n" + " subB very,%n" + " special,%n" + " Christopher Walken style,%n" + " description.%n" + " subC not so,%n" + " special,%n" + " Jon Voight style,%n" + " description.%n" + " subD regular description for subD%n"), new CommandLine(rootCmd).getUsageMessage()); } @Test public void testMultiLineWrappedDescription() { CommandSpec rootCmd = createCmd("wrapDescriptions", "Displays sub commands, with extra long descriptions"); CommandSpec oneLineCmd = createCmd("oneLine", "The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog."); CommandSpec multiLineCmd = createCmd("multiLine", "The quick brown fox jumped over the lazy dog.%nThe quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog.%n%nThe quick brown fox jumped over the lazy dog."); rootCmd.addSubcommand("oneLine", oneLineCmd); rootCmd.addSubcommand("multiLine", multiLineCmd); assertEquals(String.format("" + "Usage: wrapDescriptions [-hV] [COMMAND]%n" + "Displays sub commands, with extra long descriptions%n" + " -h, --help Show this help message and exit.%n" + " -V, --version Print version information and exit.%n" + "Commands:%n" + " oneLine The quick brown fox jumped over the lazy dog. The quick brown fox%n" + " jumped over the lazy dog. The quick brown fox jumped over the%n" + " lazy dog. The quick brown fox jumped over the lazy dog. The%n" + " quick brown fox jumped over the lazy dog. The quick brown fox%n" + " jumped over the lazy dog.%n" + " multiLine The quick brown fox jumped over the lazy dog.%n" + " The quick brown fox jumped over the lazy dog. The quick brown fox%n" + " jumped over the lazy dog. The quick brown fox jumped over the%n" + " lazy dog. The quick brown fox jumped over the lazy dog.%n%n" + " The quick brown fox jumped over the lazy dog.%n"), new CommandLine(rootCmd).getUsageMessage()); assertEquals(String.format( "Usage: wrapDescriptions oneLine [-hV]%n" + "The quick brown fox jumped over the lazy dog. The quick brown fox jumped over%n" + "the lazy dog. The quick brown fox jumped over the lazy dog. The quick brown fox%n" + "jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The%n" + "quick brown fox jumped over the lazy dog.%n" + " -h, --help Show this help message and exit.%n" + " -V, --version Print version information and exit.%n"), new CommandLine(oneLineCmd).getUsageMessage()); assertEquals(String.format( "Usage: wrapDescriptions multiLine [-hV]%n" + "The quick brown fox jumped over the lazy dog.%n" + "The quick brown fox jumped over the lazy dog. The quick brown fox jumped over%n" + "the lazy dog. The quick brown fox jumped over the lazy dog. The quick brown fox%n" + "jumped over the lazy dog.%n%n" + "The quick brown fox jumped over the lazy dog.%n" + " -h, --help Show this help message and exit.%n" + " -V, --version Print version information and exit.%n"), new CommandLine(multiLineCmd).getUsageMessage()); } @Test public void testMultiLineWrappedDefaultValueWontRunIntoInfiniteLoop(){ class Args { @Parameters(arity = "1..*", description = "description", defaultValue = "/long/value/length/equals/columnValue/maxlength/and/non/null/offset/xxx", showDefaultValue = ALWAYS) String[] c; } String expected = String.format("" + "Usage: <main class> <c>...%n" + " <c>... description%n" + " Default:%n" + " /long/value/length/equals/columnValue/maxlength/and/non/null/of%n" + " fset/xxx%n"); assertEquals(expected, usageString(new Args(), Help.Ansi.OFF)); } private static CommandSpec createCmd(String name, String description) { CommandSpec cmd = CommandSpec.create().name(name).mixinStandardHelpOptions(true); cmd.usageMessage().description(description); return cmd; } @Test public void testHelpFactoryIsUsedWhenSet() { @Command() class TestCommand { } IHelpFactory helpFactoryWithOverridenHelpMethod = new IHelpFactory() { public Help create(CommandSpec commandSpec, ColorScheme colorScheme) { return new Help(commandSpec, colorScheme) { @Override public String detailedSynopsis(int synopsisHeadingLength, Comparator<OptionSpec> optionSort, boolean clusterBooleanOptions) { return "<custom detailed synopsis>"; } }; } }; CommandLine commandLineWithCustomHelpFactory = new CommandLine(new TestCommand()).setHelpFactory(helpFactoryWithOverridenHelpMethod); assertEquals("Usage: <custom detailed synopsis>", commandLineWithCustomHelpFactory.getUsageMessage(Help.Ansi.OFF)); ByteArrayOutputStream baos = new ByteArrayOutputStream(); commandLineWithCustomHelpFactory.usage(new PrintStream(baos, true)); assertEquals("Usage: <custom detailed synopsis>", baos.toString()); } @Test public void testCustomizableHelpSections() { @Command(header="<header> (%s)", description="<description>") class TestCommand { } CommandLine commandLineWithCustomHelpSections = new CommandLine(new TestCommand()); IHelpSectionRenderer renderer = new IHelpSectionRenderer() { public String render(Help help) { return help.header("<custom header param>"); } }; commandLineWithCustomHelpSections.getHelpSectionMap().put("customSectionExtendsHeader", renderer); commandLineWithCustomHelpSections.setHelpSectionKeys(Arrays.asList( UsageMessageSpec.SECTION_KEY_DESCRIPTION, UsageMessageSpec.SECTION_KEY_SYNOPSIS_HEADING, "customSectionExtendsHeader")); String expected = String.format("" + "<description>%n" + "Usage: <header> (<custom header param>)%n"); assertEquals(expected, commandLineWithCustomHelpSections.getUsageMessage(Help.Ansi.OFF)); } @Test public void testNullSectionRenderer() { CommandLine cmd = new CommandLine(new UsageDemo()); cmd.getHelpSectionMap().clear(); cmd.getHelpSectionMap().put(UsageMessageSpec.SECTION_KEY_HEADER, null); cmd.getHelpSectionMap().put(UsageMessageSpec.SECTION_KEY_DESCRIPTION, new IHelpSectionRenderer() { public String render(Help help) { return "abc"; } }); String actual = cmd.getUsageMessage(); String expected = "abc"; assertEquals(expected, actual); } @Test public void testBooleanOptionWithArity1() { @Command(mixinStandardHelpOptions = true) class ExampleCommand { @Option(names = { "-b" }, arity = "1") boolean booleanWithArity1; } String expected = String.format("" + "Usage: <main class> [-hV] [-b=<booleanWithArity1>]%n" + " -b=<booleanWithArity1>%n" + " -h, --help Show this help message and exit.%n" + " -V, --version Print version information and exit.%n"); assertEquals(expected, new CommandLine(new ExampleCommand()).getUsageMessage(Help.Ansi.OFF)); } @Test public void testIssue615DescriptionContainingPercentChar() { class App { @Option(names = {"--excludebase"}, arity="1..*", description = "exclude child files of cTree (only works with --ctree).%n" + "Currently must be explicit or with trailing % for truncated glob." ) public String[] excludeBase; } String expected = String.format("" + "Usage: <main class> [--excludebase=<excludeBase>...]...%n" + " --excludebase=<excludeBase>...%n" + " exclude child files of cTree (only works with --ctree).%%nCurrently%n" + " must be explicit or with trailing %% for truncated glob.%n"); String actual = new CommandLine(new App()).getUsageMessage(); assertEquals(expected, actual); assertTrue(systemErrRule.getLog().contains( "[picocli WARN] Could not format 'exclude child files of cTree (only works with --ctree).%n" + "Currently must be explicit or with trailing % for truncated glob.' " + "(Underlying error:")); assertTrue(systemErrRule.getLog().contains( "). " + "Using raw String: '%n' format strings have not been replaced with newlines. " + "Please ensure to escape '%' characters with another '%'.")); } @Test public void testDescriptionWithDefaultValueContainingPercentChar() { class App { @Option(names = {"-f"}, defaultValue = "%s - page %d of %d", description = "format string. Default: ${DEFAULT-VALUE}") public String formatString; } String expected = String.format("" + "Usage: <main class> [-f=<formatString>]%n" + " -f=<formatString> format string. Default: %%s - page %%d of %%d%n"); String actual = new CommandLine(new App()).getUsageMessage(); assertEquals(expected, actual); assertFalse(systemErrRule.getLog().contains( "[picocli WARN] Could not format 'format string. Default: %s - page %d of %d' " + "(Underlying error:")); assertFalse(systemErrRule.getLog().contains( "). " + "Using raw String: '%n' format strings have not been replaced with newlines. " + "Please ensure to escape '%' characters with another '%'.")); } @Test public void testDescriptionWithFallbackValueContainingPercentChar() { class App { @Option(names = {"-f"}, fallbackValue = "%s - page %d of %d", description = "format string. Fallback: ${FALLBACK-VALUE}") public String formatString; } String expected = String.format("" + "Usage: <main class> [-f=<formatString>]%n" + " -f=<formatString> format string. Fallback: %%s - page %%d of %%d%n"); String actual = new CommandLine(new App()).getUsageMessage(); assertEquals(expected, actual); assertFalse(systemErrRule.getLog().contains( "picocli WARN")); } @Test public void testCharCJKDoubleWidthTextByDefault() { @Command(name = "cjk", mixinStandardHelpOptions = true, description = { "12345678901234567890123456789012345678901234567890123456789012345678901234567890", "CUI\u306fGUI\u3068\u6bd4\u3079\u3066\u76f4\u611f\u7684\u306a\u64cd\u4f5c\u304c\u3067\u304d\u306a\u3044\u306a\u3069\u306e\u6b20\u70b9\u304c\u3042\u308b\u3082\u306e\u306e\u3001\u30e1\u30a4\u30f3\u30e1\u30e2\u30ea\u304a\u3088\u3073\u30d3\u30c7\u30aa\u30e1\u30e2\u30ea\u306a\u3069\u306e\u30b3\u30f3\u30d4\u30e5\u30fc\u30bf\u8cc7\u6e90\u306e\u6d88\u8cbb\u304c\u5c11\u306a\u3044\u3053\u3068\u304b\u3089\u3001" + "\u6027\u80fd\u306e\u4f4e\u3044\u521d\u671f\u306e\u30b3\u30f3\u30d4\u30e5\u30fc\u30bf\u3067\u306fCUI\u306b\u3088\u308b\u5bfe\u8a71\u74b0\u5883\u304c\u4e3b\u6d41\u3060\u3063\u305f\u3002\u305d\u306e\u5f8c\u3001\u30b3\u30f3\u30d4\u30e5\u30fc\u30bf\u306e\u6027\u80fd\u304c\u5411\u4e0a\u3057\u3001\u30de\u30a6\u30b9\u306a\u3069\u306e\u30dd\u30a4\u30f3\u30c6\u30a3\u30f3\u30b0\u30c7\u30d0\u30a4\u30b9\u306b\u3088\u3063\u3066" + "\u76f4\u611f\u7684\u306a\u64cd\u4f5c\u306e\u3067\u304d\u308bGUI\u74b0\u5883\u304cMacintosh\u3084Windows 95\u306a\u3069\u306b\u3088\u3063\u3066\u30aa\u30d5\u30a3\u30b9\u3084\u4e00\u822c\u5bb6\u5ead\u306b\u3082\u666e\u53ca\u3057\u3001" + "CUI\u306f\u65e2\u5b9a\u306e\u30a4\u30f3\u30bf\u30fc\u30d5\u30a7\u30a4\u30b9\u3067\u306f\u306a\u304f\u306a\u3063\u3066\u3044\u3063\u305f\u3002\u30d1\u30fc\u30bd\u30ca\u30eb\u30b3\u30f3\u30d4\u30e5\u30fc\u30bf (PC) \u5411\u3051\u3084\u30b5\u30fc\u30d0\u30fc\u5411\u3051\u306e\u30aa\u30da\u30ec\u30fc\u30c6\u30a3\u30f3\u30b0\u30b7\u30b9\u30c6\u30e0 (OS) " + "\u306b\u306f\u3001\u65e2\u5b9a\u306e\u30a4\u30f3\u30bf\u30fc\u30d5\u30a7\u30a4\u30b9\u304cGUI\u3067\u3042\u3063\u3066\u3082\u30b3\u30de\u30f3\u30c9\u30e9\u30a4\u30f3\u30bf\u30fc\u30df\u30ca\u30eb\u306a\u3069\u306eCUI\u74b0\u5883\u304c\u4f9d\u7136\u3068\u3057\u3066\u7528\u610f\u3055\u308c\u3066\u3044\u308b\u304c\u3001\u30b9\u30de\u30fc\u30c8\u30d5\u30a9\u30f3\u306a\u3069\u306e\u30e2\u30d0\u30a4\u30eb" + "\u7aef\u672b\u5411\u3051OS\u306b\u306f\u6a19\u6e96\u3067\u7528\u610f\u3055\u308c\u3066\u304a\u3089\u305a\u3001GUI\u304c\u4e3b\u6d41\u3068\u306a\u3063\u3066\u3044\u308b\u3002"}) class App { @Option(names = {"-x", "--long"}, description = "\u3057\u304b\u3057\u3001GUI\u74b0\u5883\u3067\u3042\u308c\u3070\u30dd\u30a4\u30f3\u30c6\u30a3\u30f3\u30b0\u30c7\u30d0\u30a4\u30b9\u306b\u3088\u308b\u64cd\u4f5c\u3092\u7e70\u308a\u8fd4\u3057\u884c\u308f\u306a\u3051\u308c\u3070\u306a\u3089\u306a\u3044\u3088\u3046\u306a\u7169\u96d1\u306a\u4f5c\u696d\u3092\u3001CUI\u74b0\u5883\u3067\u3042\u308c\u3070\u7c21\u5358\u306a\u30b3\u30de\u30f3\u30c9\u306e\u7d44\u307f\u5408\u308f\u305b\u3067\u5b9f\u884c\u3067\u304d\u308b\u5834\u5408\u3082\u3042\u308b\u306a\u3069\u3001CUI\u306b\u3082\u4f9d\u7136\u3068\u3057\u3066\u5229\u70b9\u306f\u3042\u308b\u3002\u7279\u306b\u30a8\u30f3\u30c9\u30e6\u30fc\u30b6\u30fc\u3060\u3051\u3067\u306a\u304f\u30cd\u30c3\u30c8\u30ef\u30fc\u30af\u7ba1\u7406\u8005\u3084\u30bd\u30d5\u30c8\u30a6\u30a7\u30a2\u958b\u767a\u8005\u3082\u5229\u7528\u3059\u308bPC\u3084\u30b5\u30fc\u30d0\u30fc\u306b\u304a\u3044\u3066\u306f\u3001GUI\u3068CUI\u306f\u7528\u9014\u306b\u3088\u3063\u3066\u4f4f\u307f\u5206\u3051\u3066\u4f75\u5b58\u3057\u3066\u3044\u308b\u3082\u306e\u3067\u3042\u308a\u3001CUI\u306f\u5b8c\u5168\u306b\u5ec3\u308c\u305f\u308f\u3051\u3067\u306f\u306a\u3044\u3002") int x; } String usageMessage = new CommandLine(new App()).getUsageMessage(); String expected = String.format("" + "Usage: cjk [-hV] [-x=<x>]%n" + "12345678901234567890123456789012345678901234567890123456789012345678901234567890%n" + "CUI\u306fGUI\u3068\u6bd4\u3079\u3066\u76f4\u611f\u7684\u306a\u64cd\u4f5c\u304c\u3067\u304d\u306a\u3044\u306a\u3069\u306e\u6b20\u70b9\u304c\u3042\u308b\u3082\u306e\u306e\u3001\u30e1\u30a4\u30f3\u30e1\u30e2\u30ea\u304a\u3088\u3073%n" + "\u30d3\u30c7\u30aa\u30e1\u30e2\u30ea\u306a\u3069\u306e\u30b3\u30f3\u30d4\u30e5\u30fc\u30bf\u8cc7\u6e90\u306e\u6d88\u8cbb\u304c\u5c11\u306a\u3044\u3053\u3068\u304b\u3089\u3001\u6027\u80fd\u306e\u4f4e\u3044\u521d\u671f\u306e\u30b3\u30f3%n" + "\u30d4\u30e5\u30fc\u30bf\u3067\u306fCUI\u306b\u3088\u308b\u5bfe\u8a71\u74b0\u5883\u304c\u4e3b\u6d41\u3060\u3063\u305f\u3002\u305d\u306e\u5f8c\u3001\u30b3\u30f3\u30d4\u30e5\u30fc\u30bf\u306e\u6027\u80fd\u304c\u5411\u4e0a\u3057\u3001%n" + "\u30de\u30a6\u30b9\u306a\u3069\u306e\u30dd\u30a4\u30f3\u30c6\u30a3\u30f3\u30b0\u30c7\u30d0\u30a4\u30b9\u306b\u3088\u3063\u3066\u76f4\u611f\u7684\u306a\u64cd\u4f5c\u306e\u3067\u304d\u308bGUI\u74b0\u5883\u304cMacintosh%n" + "\u3084Windows 95\u306a\u3069\u306b\u3088\u3063\u3066\u30aa\u30d5\u30a3\u30b9\u3084\u4e00\u822c\u5bb6\u5ead\u306b\u3082\u666e\u53ca\u3057\u3001CUI\u306f\u65e2\u5b9a\u306e\u30a4\u30f3\u30bf\u30fc\u30d5\u30a7\u30a4%n" + "\u30b9\u3067\u306f\u306a\u304f\u306a\u3063\u3066\u3044\u3063\u305f\u3002\u30d1\u30fc\u30bd\u30ca\u30eb\u30b3\u30f3\u30d4\u30e5\u30fc\u30bf (PC) \u5411\u3051\u3084\u30b5\u30fc\u30d0\u30fc\u5411\u3051\u306e\u30aa\u30da\u30ec\u30fc%n" + "\u30c6\u30a3\u30f3\u30b0\u30b7\u30b9\u30c6\u30e0 (OS) \u306b\u306f\u3001\u65e2\u5b9a\u306e\u30a4\u30f3\u30bf\u30fc\u30d5\u30a7\u30a4\u30b9\u304cGUI\u3067\u3042\u3063\u3066\u3082\u30b3\u30de\u30f3\u30c9\u30e9\u30a4\u30f3%n" + "\u30bf\u30fc\u30df\u30ca\u30eb\u306a\u3069\u306eCUI\u74b0\u5883\u304c\u4f9d\u7136\u3068\u3057\u3066\u7528\u610f\u3055\u308c\u3066\u3044\u308b\u304c\u3001\u30b9\u30de\u30fc\u30c8\u30d5\u30a9\u30f3\u306a\u3069\u306e\u30e2\u30d0\u30a4%n" + "\u30eb\u7aef\u672b\u5411\u3051OS\u306b\u306f\u6a19\u6e96\u3067\u7528\u610f\u3055\u308c\u3066\u304a\u3089\u305a\u3001GUI\u304c\u4e3b\u6d41\u3068\u306a\u3063\u3066\u3044\u308b\u3002%n" + " -h, --help Show this help message and exit.%n" + " -V, --version Print version information and exit.%n" + " -x, --long=<x> \u3057\u304b\u3057\u3001GUI\u74b0\u5883\u3067\u3042\u308c\u3070\u30dd\u30a4\u30f3\u30c6\u30a3\u30f3\u30b0\u30c7\u30d0\u30a4\u30b9\u306b\u3088\u308b\u64cd\u4f5c\u3092\u7e70\u308a%n" + " \u8fd4\u3057\u884c\u308f\u306a\u3051\u308c\u3070\u306a\u3089\u306a\u3044\u3088\u3046\u306a\u7169\u96d1\u306a\u4f5c\u696d\u3092\u3001CUI\u74b0\u5883\u3067\u3042\u308c\u3070%n" + " \u7c21\u5358\u306a\u30b3\u30de\u30f3\u30c9\u306e\u7d44\u307f\u5408\u308f\u305b\u3067\u5b9f\u884c\u3067\u304d\u308b\u5834\u5408\u3082\u3042\u308b\u306a\u3069\u3001CUI\u306b%n" + " \u3082\u4f9d\u7136\u3068\u3057\u3066\u5229\u70b9\u306f\u3042\u308b\u3002\u7279\u306b\u30a8\u30f3\u30c9\u30e6\u30fc\u30b6\u30fc\u3060\u3051\u3067\u306a\u304f\u30cd\u30c3\u30c8%n" + " \u30ef\u30fc\u30af\u7ba1\u7406\u8005\u3084\u30bd\u30d5\u30c8\u30a6\u30a7\u30a2\u958b\u767a\u8005\u3082\u5229\u7528\u3059\u308bPC\u3084\u30b5\u30fc\u30d0\u30fc\u306b\u304a%n" + " \u3044\u3066\u306f\u3001GUI\u3068CUI\u306f\u7528\u9014\u306b\u3088\u3063\u3066\u4f4f\u307f\u5206\u3051\u3066\u4f75\u5b58\u3057\u3066\u3044\u308b\u3082\u306e\u3067%n" + " \u3042\u308a\u3001CUI\u306f\u5b8c\u5168\u306b\u5ec3\u308c\u305f\u308f\u3051\u3067\u306f\u306a\u3044\u3002%n"); assertEquals(expected, usageMessage); } @Test public void testCharCJKDoubleWidthTextCanBeSwitchedOff() { @Command(name = "cjk", mixinStandardHelpOptions = true, description = { "12345678901234567890123456789012345678901234567890123456789012345678901234567890", "CUI\u306fGUI\u3068\u6bd4\u3079\u3066\u76f4\u611f\u7684\u306a\u64cd\u4f5c\u304c\u3067\u304d\u306a\u3044\u306a\u3069\u306e\u6b20\u70b9\u304c\u3042\u308b\u3082\u306e\u306e\u3001\u30e1\u30a4\u30f3\u30e1\u30e2\u30ea\u304a\u3088\u3073\u30d3\u30c7\u30aa\u30e1\u30e2\u30ea\u306a\u3069\u306e\u30b3\u30f3\u30d4\u30e5\u30fc\u30bf\u8cc7\u6e90\u306e\u6d88\u8cbb\u304c\u5c11\u306a\u3044\u3053\u3068\u304b\u3089\u3001" + "\u6027\u80fd\u306e\u4f4e\u3044\u521d\u671f\u306e\u30b3\u30f3\u30d4\u30e5\u30fc\u30bf\u3067\u306fCUI\u306b\u3088\u308b\u5bfe\u8a71\u74b0\u5883\u304c\u4e3b\u6d41\u3060\u3063\u305f\u3002\u305d\u306e\u5f8c\u3001\u30b3\u30f3\u30d4\u30e5\u30fc\u30bf\u306e\u6027\u80fd\u304c\u5411\u4e0a\u3057\u3001\u30de\u30a6\u30b9\u306a\u3069\u306e\u30dd\u30a4\u30f3\u30c6\u30a3\u30f3\u30b0\u30c7\u30d0\u30a4\u30b9\u306b\u3088\u3063\u3066" + "\u76f4\u611f\u7684\u306a\u64cd\u4f5c\u306e\u3067\u304d\u308bGUI\u74b0\u5883\u304cMacintosh\u3084Windows 95\u306a\u3069\u306b\u3088\u3063\u3066\u30aa\u30d5\u30a3\u30b9\u3084\u4e00\u822c\u5bb6\u5ead\u306b\u3082\u666e\u53ca\u3057\u3001" + "CUI\u306f\u65e2\u5b9a\u306e\u30a4\u30f3\u30bf\u30fc\u30d5\u30a7\u30a4\u30b9\u3067\u306f\u306a\u304f\u306a\u3063\u3066\u3044\u3063\u305f\u3002\u30d1\u30fc\u30bd\u30ca\u30eb\u30b3\u30f3\u30d4\u30e5\u30fc\u30bf (PC) \u5411\u3051\u3084\u30b5\u30fc\u30d0\u30fc\u5411\u3051\u306e\u30aa\u30da\u30ec\u30fc\u30c6\u30a3\u30f3\u30b0\u30b7\u30b9\u30c6\u30e0 (OS) " + "\u306b\u306f\u3001\u65e2\u5b9a\u306e\u30a4\u30f3\u30bf\u30fc\u30d5\u30a7\u30a4\u30b9\u304cGUI\u3067\u3042\u3063\u3066\u3082\u30b3\u30de\u30f3\u30c9\u30e9\u30a4\u30f3\u30bf\u30fc\u30df\u30ca\u30eb\u306a\u3069\u306eCUI\u74b0\u5883\u304c\u4f9d\u7136\u3068\u3057\u3066\u7528\u610f\u3055\u308c\u3066\u3044\u308b\u304c\u3001\u30b9\u30de\u30fc\u30c8\u30d5\u30a9\u30f3\u306a\u3069\u306e\u30e2\u30d0\u30a4\u30eb" + "\u7aef\u672b\u5411\u3051OS\u306b\u306f\u6a19\u6e96\u3067\u7528\u610f\u3055\u308c\u3066\u304a\u3089\u305a\u3001GUI\u304c\u4e3b\u6d41\u3068\u306a\u3063\u3066\u3044\u308b\u3002"}) class App { @Option(names = {"-x", "--long"}, description = "\u3057\u304b\u3057\u3001GUI\u74b0\u5883\u3067\u3042\u308c\u3070\u30dd\u30a4\u30f3\u30c6\u30a3\u30f3\u30b0\u30c7\u30d0\u30a4\u30b9\u306b\u3088\u308b\u64cd\u4f5c\u3092\u7e70\u308a\u8fd4\u3057\u884c\u308f\u306a\u3051\u308c\u3070\u306a\u3089\u306a\u3044\u3088\u3046\u306a\u7169\u96d1\u306a\u4f5c\u696d\u3092\u3001CUI\u74b0\u5883\u3067\u3042\u308c\u3070\u7c21\u5358\u306a\u30b3\u30de\u30f3\u30c9\u306e\u7d44\u307f\u5408\u308f\u305b\u3067\u5b9f\u884c\u3067\u304d\u308b\u5834\u5408\u3082\u3042\u308b\u306a\u3069\u3001CUI\u306b\u3082\u4f9d\u7136\u3068\u3057\u3066\u5229\u70b9\u306f\u3042\u308b\u3002\u7279\u306b\u30a8\u30f3\u30c9\u30e6\u30fc\u30b6\u30fc\u3060\u3051\u3067\u306a\u304f\u30cd\u30c3\u30c8\u30ef\u30fc\u30af\u7ba1\u7406\u8005\u3084\u30bd\u30d5\u30c8\u30a6\u30a7\u30a2\u958b\u767a\u8005\u3082\u5229\u7528\u3059\u308bPC\u3084\u30b5\u30fc\u30d0\u30fc\u306b\u304a\u3044\u3066\u306f\u3001GUI\u3068CUI\u306f\u7528\u9014\u306b\u3088\u3063\u3066\u4f4f\u307f\u5206\u3051\u3066\u4f75\u5b58\u3057\u3066\u3044\u308b\u3082\u306e\u3067\u3042\u308a\u3001CUI\u306f\u5b8c\u5168\u306b\u5ec3\u308c\u305f\u308f\u3051\u3067\u306f\u306a\u3044\u3002") int x; } String usageMessage = new CommandLine(new App()) .setAdjustLineBreaksForWideCJKCharacters(false) .getUsageMessage(); String expected = String.format("" + "Usage: cjk [-hV] [-x=<x>]%n" + "12345678901234567890123456789012345678901234567890123456789012345678901234567890%n" + "CUI\u306fGUI\u3068\u6bd4\u3079\u3066\u76f4\u611f\u7684\u306a\u64cd\u4f5c\u304c\u3067\u304d\u306a\u3044\u306a\u3069\u306e\u6b20\u70b9\u304c\u3042\u308b\u3082\u306e\u306e\u3001\u30e1\u30a4\u30f3\u30e1\u30e2\u30ea\u304a\u3088\u3073\u30d3\u30c7\u30aa\u30e1\u30e2\u30ea\u306a\u3069\u306e\u30b3\u30f3\u30d4\u30e5\u30fc\u30bf\u8cc7\u6e90\u306e\u6d88\u8cbb\u304c\u5c11\u306a\u3044\u3053\u3068\u304b\u3089\u3001\u6027\u80fd\u306e\u4f4e\u3044\u521d\u671f\u306e%n" + "\u30b3\u30f3\u30d4\u30e5\u30fc\u30bf\u3067\u306fCUI\u306b\u3088\u308b\u5bfe\u8a71\u74b0\u5883\u304c\u4e3b\u6d41\u3060\u3063\u305f\u3002\u305d\u306e\u5f8c\u3001\u30b3\u30f3\u30d4\u30e5\u30fc\u30bf\u306e\u6027\u80fd\u304c\u5411\u4e0a\u3057\u3001\u30de\u30a6\u30b9\u306a\u3069\u306e\u30dd\u30a4\u30f3\u30c6\u30a3\u30f3\u30b0\u30c7\u30d0\u30a4\u30b9\u306b\u3088\u3063\u3066\u76f4\u611f\u7684\u306a\u64cd\u4f5c\u306e\u3067\u304d\u308bGUI\u74b0\u5883\u304c%n" + "Macintosh\u3084Windows 95\u306a\u3069\u306b\u3088\u3063\u3066\u30aa\u30d5\u30a3\u30b9\u3084\u4e00\u822c\u5bb6\u5ead\u306b\u3082\u666e\u53ca\u3057\u3001CUI\u306f\u65e2\u5b9a\u306e\u30a4\u30f3\u30bf\u30fc\u30d5\u30a7\u30a4\u30b9\u3067\u306f\u306a\u304f\u306a\u3063\u3066\u3044\u3063\u305f\u3002\u30d1\u30fc\u30bd\u30ca\u30eb\u30b3\u30f3\u30d4\u30e5\u30fc\u30bf (%n" + "PC) \u5411\u3051\u3084\u30b5\u30fc\u30d0\u30fc\u5411\u3051\u306e\u30aa\u30da\u30ec\u30fc\u30c6\u30a3\u30f3\u30b0\u30b7\u30b9\u30c6\u30e0 (OS) \u306b\u306f\u3001\u65e2\u5b9a\u306e\u30a4\u30f3\u30bf\u30fc\u30d5\u30a7\u30a4\u30b9\u304cGUI\u3067\u3042\u3063\u3066\u3082\u30b3\u30de\u30f3\u30c9\u30e9\u30a4\u30f3\u30bf\u30fc\u30df\u30ca\u30eb\u306a\u3069\u306eCUI\u74b0\u5883\u304c\u4f9d\u7136\u3068\u3057%n" + "\u3066\u7528\u610f\u3055\u308c\u3066\u3044\u308b\u304c\u3001\u30b9\u30de\u30fc\u30c8\u30d5\u30a9\u30f3\u306a\u3069\u306e\u30e2\u30d0\u30a4\u30eb\u7aef\u672b\u5411\u3051OS\u306b\u306f\u6a19\u6e96\u3067\u7528\u610f\u3055\u308c\u3066\u304a\u3089\u305a\u3001GUI\u304c\u4e3b\u6d41\u3068\u306a\u3063\u3066\u3044\u308b\u3002%n" + " -h, --help Show this help message and exit.%n" + " -V, --version Print version information and exit.%n" + " -x, --long=<x> \u3057\u304b\u3057\u3001GUI\u74b0\u5883\u3067\u3042\u308c\u3070\u30dd\u30a4\u30f3\u30c6\u30a3\u30f3\u30b0\u30c7\u30d0\u30a4\u30b9\u306b\u3088\u308b\u64cd\u4f5c\u3092\u7e70\u308a\u8fd4\u3057\u884c\u308f\u306a\u3051\u308c\u3070\u306a\u3089\u306a\u3044\u3088\u3046\u306a\u7169\u96d1\u306a\u4f5c\u696d\u3092\u3001CUI\u74b0\u5883\u3067\u3042%n" + " \u308c\u3070\u7c21\u5358\u306a\u30b3\u30de\u30f3\u30c9\u306e\u7d44\u307f\u5408\u308f\u305b\u3067\u5b9f\u884c\u3067\u304d\u308b\u5834\u5408\u3082\u3042\u308b\u306a\u3069\u3001CUI\u306b\u3082\u4f9d\u7136\u3068\u3057\u3066\u5229\u70b9\u306f\u3042\u308b\u3002\u7279\u306b\u30a8\u30f3\u30c9\u30e6\u30fc\u30b6\u30fc\u3060\u3051\u3067\u306a\u304f%n" + " \u30cd\u30c3\u30c8\u30ef\u30fc\u30af\u7ba1\u7406\u8005\u3084\u30bd\u30d5\u30c8\u30a6\u30a7\u30a2\u958b\u767a\u8005\u3082\u5229\u7528\u3059\u308bPC\u3084\u30b5\u30fc\u30d0\u30fc\u306b\u304a\u3044\u3066\u306f\u3001GUI\u3068CUI\u306f\u7528\u9014\u306b\u3088\u3063\u3066\u4f4f\u307f\u5206\u3051\u3066\u4f75\u5b58\u3057%n" + " \u3066\u3044\u308b\u3082\u306e\u3067\u3042\u308a\u3001CUI\u306f\u5b8c\u5168\u306b\u5ec3\u308c\u305f\u308f\u3051\u3067\u306f\u306a\u3044\u3002%n"); assertEquals(expected, usageMessage); } @Test public void testTextTableAjustForWideCJKCharsByDefault() { assertTrue(TextTable.forDefaultColumns(Help.Ansi.OFF, 80).isAdjustLineBreaksForWideCJKCharacters()); assertTrue(TextTable.forColumnWidths(Help.Ansi.OFF, 3, 4, 6, 30).isAdjustLineBreaksForWideCJKCharacters()); assertTrue(TextTable.forDefaultColumns(Help.Ansi.OFF, 20, 80).isAdjustLineBreaksForWideCJKCharacters()); } @Test public void testTextTableAjustForWideCJKCharsByDefaultIsMutable() { TextTable textTable = TextTable.forDefaultColumns(Help.Ansi.OFF, 80); assertTrue(textTable.isAdjustLineBreaksForWideCJKCharacters()); textTable.setAdjustLineBreaksForWideCJKCharacters(false); assertFalse(textTable.isAdjustLineBreaksForWideCJKCharacters()); } @Command(name = "top", subcommands = { SubcommandWithStandardHelpOptions.class, CommandLine.HelpCommand.class }) static class ParentCommandWithRequiredOption implements Runnable { @Option(names = "--required", required = true) String required; public void run() { } } @Command(name = "sub", mixinStandardHelpOptions = true) static class SubcommandWithStandardHelpOptions implements Runnable { public void run() { } } @Ignore @Test // https://github.com/remkop/picocli/issues/743 public void testSubcommandHelpWhenParentCommandHasRequiredOption_743() { CommandLine cmd = new CommandLine(new ParentCommandWithRequiredOption()); cmd.execute("help", "sub"); String expected = String.format("" + "Usage: top sub [-hV]%n" + " -h, --help Show this help message and exit.%n" + " -V, --version Print version information and exit.%n"); assertEquals(expected, this.systemOutRule.getLog()); assertEquals("", this.systemErrRule.getLog()); systemErrRule.clearLog(); systemOutRule.clearLog(); cmd.execute("sub", "--help"); assertEquals("", this.systemErrRule.getLog()); assertEquals(expected, this.systemOutRule.getLog()); } @Test //https://github.com/remkop/picocli/issues/739 public void testIssue739CommandName72Chars() { @Command(name = "123456789012345678901234567890123456789012345678901234567890123456789012", mixinStandardHelpOptions = true) class App { @Option(names = "-a") String aaaaaa; @Option(names = "-b", arity = "2") String[] bbbbbbb; @Option(names = "-c", split = ",") String[] cccccccc; } String expected = String.format("" + "Usage: 123456789012345678901234567890123456789012345678901234567890123456789012%n" + " [-hV] [-a=<aaaaaa>] [-c=<cccccccc>[,<cccccccc>...]]... [-b=<bbbbbbb>%n" + " <bbbbbbb>]...%n" + " -a=<aaaaaa>%n" + " -b=<bbbbbbb> <bbbbbbb>%n" + " -c=<cccccccc>[,<cccccccc>...]%n" + "%n" + " -h, --help Show this help message and exit.%n" + " -V, --version Print version information and exit.%n"); String actual = new CommandLine(new App()).getUsageMessage(); assertEquals(expected, actual); } @Test //https://github.com/remkop/picocli/issues/739 public void testIssue739CommandName73Chars() { @Command(name = "1234567890123456789012345678901234567890123456789012345678901234567890123", mixinStandardHelpOptions = true) class App { @Option(names = "-a") String aaaaaa; @Option(names = "-b", arity = "2") String[] bbbbbbb; @Option(names = "-c", split = ",") String[] cccccccc; } String expected = String.format("" + "Usage: 1234567890123456789012345678901234567890123456789012345678901234567890123%n" + " [-hV] [-a=<aaaaaa>] [-c=<cccccccc>[,<cccccccc>...]]... [-b=<bbbbbbb>%n" + " <bbbbbbb>]...%n" + " -a=<aaaaaa>%n" + " -b=<bbbbbbb> <bbbbbbb>%n" + " -c=<cccccccc>[,<cccccccc>...]%n" + "%n" + " -h, --help Show this help message and exit.%n" + " -V, --version Print version information and exit.%n"); String actual = new CommandLine(new App()).getUsageMessage(); assertEquals(expected, actual); } @Test //https://github.com/remkop/picocli/issues/739 public void testIssue739CommandName80Chars() { @Command(name = "12345678901234567890123456789012345678901234567890123456789012345678901234567890", mixinStandardHelpOptions = true) class App { @Option(names = "-a") String aaaaaa; @Option(names = "-b", arity = "2") String[] bbbbbbb; @Option(names = "-c", split = ",") String[] cccccccc; } String expected = String.format("" + "Usage: 1234567890123456789012345678901234567890123456789012345678901234567890123%n" + " 4567890 [-hV] [-a=<aaaaaa>] [-c=<cccccccc>[,<cccccccc>...]]...%n" + " [-b=<bbbbbbb> <bbbbbbb>]...%n" + " -a=<aaaaaa>%n" + " -b=<bbbbbbb> <bbbbbbb>%n" + " -c=<cccccccc>[,<cccccccc>...]%n" + "%n" + " -h, --help Show this help message and exit.%n" + " -V, --version Print version information and exit.%n"); String actual = new CommandLine(new App()).getUsageMessage(); assertEquals(expected, actual); } @Test //https://github.com/remkop/picocli/issues/739 public void testIssue739CommandName40Chars_customSynopsisMaxIndent() { @Command(name = "1234567890123456789012345678901234567890", mixinStandardHelpOptions = true) class App { @Option(names = "-a") String aaaaaa; @Option(names = "-b", arity = "2") String[] bbbbbbb; @Option(names = "-c", split = ",") String[] cccccccc; } String expected = String.format("" + "Usage: 1234567890123456789012345678901234567890 [-hV] [-a=<aaaaaa>]%n" + " [-c=<cccccccc>[,<cccccccc>...]]...%n" + " [-b=<bbbbbbb> <bbbbbbb>]...%n" + " -a=<aaaaaa>%n" + " -b=<bbbbbbb> <bbbbbbb>%n" + " -c=<cccccccc>[,<cccccccc>...]%n" + "%n" + " -h, --help Show this help message and exit.%n" + " -V, --version Print version information and exit.%n"); CommandLine cmd = new CommandLine(new App()); cmd.getCommandSpec().usageMessage().synopsisAutoIndentThreshold(47.0 / 80); cmd.getCommandSpec().usageMessage().synopsisIndent(40); String actual = cmd.getUsageMessage(); assertEquals(expected, actual); cmd.getCommandSpec().usageMessage().synopsisIndent(20); assertEquals(String.format("" + "Usage: 1234567890123456789012345678901234567890 [-hV] [-a=<aaaaaa>]%n" + " [-c=<cccccccc>[,<cccccccc>...]]... [-b=<bbbbbbb>%n" + " <bbbbbbb>]...%n" + " -a=<aaaaaa>%n" + " -b=<bbbbbbb> <bbbbbbb>%n" + " -c=<cccccccc>[,<cccccccc>...]%n" + "%n" + " -h, --help Show this help message and exit.%n" + " -V, --version Print version information and exit.%n"), cmd.getUsageMessage()); cmd.getCommandSpec().usageMessage().synopsisIndent(-1); assertEquals(String.format("" + "Usage: 1234567890123456789012345678901234567890 [-hV] [-a=<aaaaaa>]%n" + " [-c=<cccccccc>[,<cccccccc>...]]... [-b=<bbbbbbb> <bbbbbbb>]...%n" + " -a=<aaaaaa>%n" + " -b=<bbbbbbb> <bbbbbbb>%n" + " -c=<cccccccc>[,<cccccccc>...]%n" + "%n" + " -h, --help Show this help message and exit.%n" + " -V, --version Print version information and exit.%n"), cmd.getUsageMessage()); } @Test public void testSynopsisAutoIndentThresholdDefault() { assertEquals(0.5, new UsageMessageSpec().synopsisAutoIndentThreshold(), 0.00001); } @Test public void testSynopsisAutoIndentThresholdDisallowsNegativeValue() { try { new UsageMessageSpec().synopsisAutoIndentThreshold(-0.1); fail("Expected exception"); } catch (IllegalArgumentException ex) { assertEquals("synopsisAutoIndentThreshold must be between 0.0 and 0.9 (inclusive), but was -0.1", ex.getMessage()); } } @Test public void testSynopsisAutoIndentThresholdDisallowsValueLargerThan0_9() { try { new UsageMessageSpec().synopsisAutoIndentThreshold(0.90001); fail("Expected exception"); } catch (IllegalArgumentException ex) { assertEquals("synopsisAutoIndentThreshold must be between 0.0 and 0.9 (inclusive), but was 0.90001", ex.getMessage()); } } @Test public void testSynopsisAutoIndentThresholdAcceptsValueZero() { assertEquals(0.0, new UsageMessageSpec().synopsisAutoIndentThreshold(0.0).synopsisAutoIndentThreshold(), 0.0001); } @Test public void testSynopsisAutoIndentThresholdAcceptsValue0_9() { assertEquals(0.9, new UsageMessageSpec().synopsisAutoIndentThreshold(0.9).synopsisAutoIndentThreshold(), 0.0001); } @Test public void testSynopsisIndentDefault() { assertEquals(-1, new UsageMessageSpec().synopsisIndent()); } @Test //https://github.com/remkop/picocli/issues/739 public void testIssue739CommandName32Chars() { @Command(name = "12345678901234567890123456789012", mixinStandardHelpOptions = true) class App { @Option(names = "-a") String aaaaaa; @Option(names = "-b", arity = "2") String[] bbbbbbb; @Option(names = "-c", split = ",") String[] cccccccc; } String expected = String.format("" + "Usage: 12345678901234567890123456789012 [-hV] [-a=<aaaaaa>] [-c=<cccccccc>[,%n" + " <cccccccc>...]]... [-b=<bbbbbbb>%n" + " <bbbbbbb>]...%n" + " -a=<aaaaaa>%n" + " -b=<bbbbbbb> <bbbbbbb>%n" + " -c=<cccccccc>[,<cccccccc>...]%n" + "%n" + " -h, --help Show this help message and exit.%n" + " -V, --version Print version information and exit.%n"); String actual = new CommandLine(new App()).getUsageMessage(); assertEquals(expected, actual); } @Command(name = "showenv", mixinStandardHelpOptions = true, version = "showenv 1.0", description = "Demonstrates a usage help message with " + "an additional section for environment variables.", exitCodeListHeading = "Exit Codes:%n", exitCodeList = { " 0:Successful program execution", "64:Usage error: user input for the command was incorrect, " + "e.g., the wrong number of arguments, a bad flag, " + "a bad syntax in a parameter, etc.", "70:Internal software error: an exception occurred when invoking " + "the business logic of this command." } ) public class EnvironmentVariablesSection { } @Test public void testCustomTabularSection() { String SECTION_KEY_ENV_HEADING = "environmentVariablesHeading"; String SECTION_KEY_ENV_DETAILS = "environmentVariables"; // the data to display final Map<String, String> env = new LinkedHashMap<String, String>(); env.put("FOO", "explanation of foo. If very long, then the line is wrapped and the wrapped line is indented with two spaces."); env.put("BAR", "explanation of bar"); env.put("XYZ", "xxxx yyyy zzz"); // register the custom section renderers CommandLine cmd = new CommandLine(new EnvironmentVariablesSection()); cmd.getHelpSectionMap().put(SECTION_KEY_ENV_HEADING, new IHelpSectionRenderer() { public String render(Help help) { return help.createHeading("Environment Variables:%n"); } }); cmd.getHelpSectionMap().put(SECTION_KEY_ENV_DETAILS, new IHelpSectionRenderer() { public String render(Help help) { return help.createTextTable(env).toString(); } }); // specify the location of the new sections List<String> keys = new ArrayList<String>(cmd.getHelpSectionKeys()); int index = keys.indexOf(CommandLine.Model.UsageMessageSpec.SECTION_KEY_FOOTER_HEADING); keys.add(index, SECTION_KEY_ENV_HEADING); keys.add(index + 1, SECTION_KEY_ENV_DETAILS); cmd.setHelpSectionKeys(keys); String expected = String.format("" + "Usage: showenv [-hV]%n" + "Demonstrates a usage help message with an additional section for environment%n" + "variables.%n" + " -h, --help Show this help message and exit.%n" + " -V, --version Print version information and exit.%n" + "Exit Codes:%n" + " 0 Successful program execution%n" + " 64 Usage error: user input for the command was incorrect, e.g., the wrong%n" + " number of arguments, a bad flag, a bad syntax in a parameter, etc.%n" + " 70 Internal software error: an exception occurred when invoking the%n" + " business logic of this command.%n" + "Environment Variables:%n" + " FOO explanation of foo. If very long, then the line is wrapped and the%n" + " wrapped line is indented with two spaces.%n" + " BAR explanation of bar%n" + " XYZ xxxx yyyy zzz%n"); assertEquals(expected, cmd.getUsageMessage(Help.Ansi.OFF)); } @Test public void testFullSynopsis() { Help help = new Help(CommandSpec.create(), CommandLine.Help.defaultColorScheme(Help.Ansi.OFF)); String syn1 = help.fullSynopsis(); assertEquals(syn1, new Help(CommandSpec.create(), CommandLine.Help.defaultColorScheme(Help.Ansi.OFF)).fullSynopsis()); } @Ignore("#934") @Test public void testConfigurableLongOptionsColumnLength() { @Command(name = "myapp", mixinStandardHelpOptions = true) class MyApp { @Option(names = {"-o", "--out"}, description = "Output location full path") File outputFolder; //public static void main(String[] args) { // new CommandLine(new MyApp()) // .setUsageHelpLongOptionsMaxWidth(25) // .execute(args); //} } new CommandLine(new MyApp()).usage(System.out); String expected = String.format("" + "Usage: myapp [-hV] [-o=<outputFolder>]%n" + " -h, --help Show this help message and exit.%n" + " -o, --output=<outputFolder>%n" + " Output location full path%n" + " -V, --version Print version information and exit.%n"); assertEquals("", this.systemOutRule.getLog()); } }
src/test/java/picocli/HelpTest.java
/* Copyright 2017 Remko Popma 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 picocli; import org.junit.After; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.contrib.java.lang.system.ProvideSystemProperty; import org.junit.contrib.java.lang.system.SystemErrRule; import org.junit.contrib.java.lang.system.SystemOutRule; import picocli.CommandLine.Command; import picocli.CommandLine.ExecutionException; import picocli.CommandLine.Help; import picocli.CommandLine.Help.Ansi.IStyle; import picocli.CommandLine.Help.Ansi.Style; import picocli.CommandLine.Help.Ansi.Text; import picocli.CommandLine.Help.ColorScheme; import picocli.CommandLine.Help.TextTable; import picocli.CommandLine.HelpCommand; import picocli.CommandLine.IHelpFactory; import picocli.CommandLine.IHelpSectionRenderer; import picocli.CommandLine.InitializationException; import picocli.CommandLine.Model; import picocli.CommandLine.Model.ArgSpec; import picocli.CommandLine.Model.CommandSpec; import picocli.CommandLine.Model.OptionSpec; import picocli.CommandLine.Model.PositionalParamSpec; import picocli.CommandLine.Model.UsageMessageSpec; import picocli.CommandLine.Option; import picocli.CommandLine.Parameters; import picocli.CommandLine.ParseResult; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.io.PrintWriter; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.net.InetAddress; import java.net.URI; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import java.util.regex.Pattern; import static java.lang.String.format; import static org.junit.Assert.*; import static picocli.CommandLine.Help.Visibility.ALWAYS; import static picocli.CommandLine.Help.Visibility.NEVER; import static picocli.CommandLine.Help.Visibility.ON_DEMAND; import static picocli.TestUtil.textArray; import static picocli.TestUtil.usageString; import static picocli.TestUtil.options; /** * Tests for picocli's "Usage" help functionality. */ public class HelpTest { private static final String LINESEP = System.getProperty("line.separator"); @Rule public final ProvideSystemProperty autoWidthOff = new ProvideSystemProperty("picocli.usage.width", null); @Rule public final ProvideSystemProperty ansiOFF = new ProvideSystemProperty("picocli.ansi", "false"); @Rule public final SystemOutRule systemOutRule = new SystemOutRule().enableLog().muteForSuccessfulTests(); @Rule public final SystemErrRule systemErrRule = new SystemErrRule().enableLog().muteForSuccessfulTests(); @After public void after() { System.getProperties().remove("picocli.color.commands"); System.getProperties().remove("picocli.color.options"); System.getProperties().remove("picocli.color.parameters"); System.getProperties().remove("picocli.color.optionParams"); } @Test public void testShowDefaultValuesDemo() { @Command(showDefaultValues = true) class FineGrainedDefaults { @Option(names = "-a", description = "ALWAYS shown even if null", showDefaultValue = ALWAYS) String optionA; @Option(names = "-b", description = "NEVER shown", showDefaultValue = NEVER) String optionB = "xyz"; @Option(names = "-c", description = "ON_DEMAND hides null", showDefaultValue = ON_DEMAND) String optionC; @Option(names = "-d", description = "ON_DEMAND shows non-null", showDefaultValue = ON_DEMAND) String optionD = "abc"; } String result = usageString(new FineGrainedDefaults(), Help.Ansi.OFF); assertEquals(format("" + "Usage: <main class> [-a=<optionA>] [-b=<optionB>] [-c=<optionC>] [-d=<optionD>]%n" + " -a=<optionA> ALWAYS shown even if null%n" + " Default: null%n" + " -b=<optionB> NEVER shown%n" + " -c=<optionC> ON_DEMAND hides null%n" + " -d=<optionD> ON_DEMAND shows non-null%n" + " Default: abc%n"), result); } @Test public void testCommandWithoutShowDefaultValuesOptionOnDemandNullValue_hidesDefault() { @Command() class Params { @Option(names = {"-f", "--file"}, required = true, description = "the file to use") File file; @Option(names = {"-o", "--opt"}, required = true, description = "another option", showDefaultValue = Help.Visibility.ON_DEMAND) File other; } String result = usageString(new Params(), Help.Ansi.OFF); assertEquals(format("" + "Usage: <main class> -f=<file> -o=<other>%n" + " -f, --file=<file> the file to use%n" + " -o, --opt=<other> another option%n"), result); } @Test public void testCommandWithoutShowDefaultValuesOptionOnDemandNonNullValue_hidesDefault() { @Command() class Params { @Option(names = {"-f", "--file"}, required = true, description = "the file to use") File file = new File("/tmp/file"); @Option(names = {"-o", "--opt"}, required = true, description = "another option", showDefaultValue = Help.Visibility.ON_DEMAND) File other = new File("/tmp/other"); } String result = usageString(new Params(), Help.Ansi.OFF); assertEquals(format("" + "Usage: <main class> -f=<file> -o=<other>%n" + " -f, --file=<file> the file to use%n" + " -o, --opt=<other> another option%n"), result); } @Test public void testCommandWithoutShowDefaultValuesOptionAlwaysNullValue_showsNullDefault() { @Command() class Params { @Option(names = {"-f", "--file"}, required = true, description = "the file to use", showDefaultValue = Help.Visibility.ALWAYS) File file; } String result = usageString(new Params(), Help.Ansi.OFF); assertEquals(format("" + "Usage: <main class> -f=<file>%n" + " -f, --file=<file> the file to use%n" + " Default: null%n"), result); } @Test public void testCommandWithoutShowDefaultValuesOptionAlwaysNonNullValue_showsDefault() { @Command() class Params { @Option(names = {"-f", "--file"}, required = true, description = "the file to use", showDefaultValue = Help.Visibility.ALWAYS) File file = new File("/tmp/file"); } String result = usageString(new Params(), Help.Ansi.OFF); assertEquals(format("" + "Usage: <main class> -f=<file>%n" + " -f, --file=<file> the file to use%n" + " Default: %s%n", new File("/tmp/file")), result); } @Test public void testCommandShowDefaultValuesOptionOnDemandNullValue_hidesDefault() { @Command(showDefaultValues = true) class Params { @Option(names = {"-f", "--file"}, required = true, description = "the file to use") File file; @Option(names = {"-o", "--opt"}, required = true, description = "another option", showDefaultValue = Help.Visibility.ON_DEMAND) File other; } String result = usageString(new Params(), Help.Ansi.OFF); assertEquals(format("" + "Usage: <main class> -f=<file> -o=<other>%n" + " -f, --file=<file> the file to use%n" + " -o, --opt=<other> another option%n"), result); } @Test public void testCommandShowDefaultValuesOptionNeverNullValue_hidesDefault() { @Command(showDefaultValues = true) class Params { @Option(names = {"-f", "--file"}, required = true, description = "the file to use") File file; @Option(names = {"-o", "--opt"}, required = true, description = "another option", showDefaultValue = Help.Visibility.NEVER) File other; } String result = usageString(new Params(), Help.Ansi.OFF); assertEquals(format("" + "Usage: <main class> -f=<file> -o=<other>%n" + " -f, --file=<file> the file to use%n" + " -o, --opt=<other> another option%n"), result); } @Test public void testCommandShowDefaultValuesOptionAlwaysNullValue_showsNullDefault() { @Command(showDefaultValues = true) class Params { @Option(names = {"-f", "--file"}, required = true, description = "the file to use") File file; @Option(names = {"-o", "--opt"}, required = true, description = "another option", showDefaultValue = Help.Visibility.ALWAYS) File other; } String result = usageString(new Params(), Help.Ansi.OFF); assertEquals(format("" + "Usage: <main class> -f=<file> -o=<other>%n" + " -f, --file=<file> the file to use%n" + " -o, --opt=<other> another option%n" + " Default: null%n"), result); } @Test public void testCommandShowDefaultValuesOptionOnDemandNonNullValue_showsDefault() { @Command(showDefaultValues = true) class Params { @Option(names = {"-f", "--file"}, required = true, description = "the file to use") File file = new File("theDefault.txt"); @Option(names = {"-o", "--opt"}, required = true, description = "another option", showDefaultValue = Help.Visibility.ON_DEMAND) File other = new File("other.txt"); } String result = usageString(new Params(), Help.Ansi.OFF); assertEquals(format("" + "Usage: <main class> -f=<file> -o=<other>%n" + " -f, --file=<file> the file to use%n" + " Default: theDefault.txt%n" + " -o, --opt=<other> another option%n" + " Default: other.txt%n"), result); } @Test public void testCommandShowDefaultValuesOptionNeverNonNullValue_hidesDefault() { @Command(showDefaultValues = true) class Params { @Option(names = {"-f", "--file"}, required = true, description = "the file to use") File file = new File("theDefault.txt"); @Option(names = {"-o", "--opt"}, required = true, description = "another option", showDefaultValue = Help.Visibility.NEVER) File other = new File("other.txt"); } String result = usageString(new Params(), Help.Ansi.OFF); assertEquals(format("" + "Usage: <main class> -f=<file> -o=<other>%n" + " -f, --file=<file> the file to use%n" + " Default: theDefault.txt%n" + " -o, --opt=<other> another option%n"), result); } @Test public void testCommandShowDefaultValuesOptionAlwaysNonNullValue_hidesDefault() { @Command(showDefaultValues = true) class Params { @Option(names = {"-f", "--file"}, required = true, description = "the file to use") File file = new File("theDefault.txt"); @Option(names = {"-o", "--opt"}, required = true, description = "another option", showDefaultValue = Help.Visibility.ALWAYS) File other = new File("other.txt"); } String result = usageString(new Params(), Help.Ansi.OFF); assertEquals(format("" + "Usage: <main class> -f=<file> -o=<other>%n" + " -f, --file=<file> the file to use%n" + " Default: theDefault.txt%n" + " -o, --opt=<other> another option%n" + " Default: other.txt%n"), result); } @Test public void testCommandShowDefaultValuesOptionOnDemandArrayField() { @Command(showDefaultValues = true) class Params { @Option(names = {"-x", "--array"}, required = true, description = "the array") int[] array = {1, 5, 11, 23}; @Option(names = {"-y", "--other"}, required = true, description = "the other", showDefaultValue = Help.Visibility.ON_DEMAND) int[] other = {1, 5, 11, 23}; } String result = usageString(new Params(), Help.Ansi.OFF); assertEquals(format("" + "Usage: <main class> -x=<array> [-x=<array>]... -y=<other> [-y=<other>]...%n" + " -x, --array=<array> the array%n" + " Default: [1, 5, 11, 23]%n" + " -y, --other=<other> the other%n" + " Default: [1, 5, 11, 23]%n"), result); } @Test public void testCommandShowDefaultValuesOptionNeverArrayField_hidesDefault() { @Command(showDefaultValues = true) class Params { @Option(names = {"-x", "--array"}, required = true, description = "the array") int[] array = {1, 5, 11, 23}; @Option(names = {"-y", "--other"}, required = true, description = "the other", showDefaultValue = Help.Visibility.NEVER) int[] other = {1, 5, 11, 23}; } String result = usageString(new Params(), Help.Ansi.OFF); assertEquals(format("" + "Usage: <main class> -x=<array> [-x=<array>]... -y=<other> [-y=<other>]...%n" + " -x, --array=<array> the array%n" + " Default: [1, 5, 11, 23]%n" + " -y, --other=<other> the other%n"), result); } @Test public void testCommandShowDefaultValuesOptionAlwaysNullArrayField_showsNull() { @Command(showDefaultValues = true) class Params { @Option(names = {"-x", "--array"}, required = true, description = "the array") int[] array; @Option(names = {"-y", "--other"}, required = true, description = "the other", showDefaultValue = Help.Visibility.ALWAYS) int[] other; } String result = usageString(new Params(), Help.Ansi.OFF); assertEquals(format("" + "Usage: <main class> -x=<array> [-x=<array>]... -y=<other> [-y=<other>]...%n" + " -x, --array=<array> the array%n" + " -y, --other=<other> the other%n" + " Default: null%n"), result); } @Test public void testCommandShowDefaultValuesVariableForArrayField() { @Command class Params { @Option(names = {"-x", "--array"}, required = true, description = "null array: Default: ${DEFAULT-VALUE}") int[] nil; @Option(names = {"-y", "--other"}, required = true, description = "non-null: Default: ${DEFAULT-VALUE}") int[] other = {1, 5, 11, 23}; } String result = usageString(new Params(), Help.Ansi.OFF); assertEquals(format("" + "Usage: <main class> -x=<nil> [-x=<nil>]... -y=<other> [-y=<other>]...%n" + " -x, --array=<nil> null array: Default: null%n" + " -y, --other=<other> non-null: Default: [1, 5, 11, 23]%n"), result); } @Test public void testOptionSpec_defaultValue_overwritesInitialValue() { @Command(showDefaultValues = true) class Params { @Option(names = {"-x", "--array"}, required = true, paramLabel = "INT", description = "the array") int[] array = {1, 5, 11, 23}; } CommandLine cmd = new CommandLine(new Params()); OptionSpec x = cmd.getCommandSpec().posixOptionsMap().get('x').toBuilder().defaultValue("5,4,3,2,1").splitRegex(",").build(); cmd = new CommandLine(CommandSpec.create().addOption(x)); cmd.getCommandSpec().usageMessage().showDefaultValues(true); String result = usageString(cmd, Help.Ansi.OFF); assertEquals(format("" + "Usage: <main class> [-x=INT[,INT...]]...%n" + " -x, --array=INT[,INT...] the array%n" + " Default: 5,4,3,2,1%n"), result); } @Test public void testCommandWithoutShowDefaultValuesPositionalOnDemandNullValue_hidesDefault() { @Command() class Params { @Parameters(index = "0", description = "the file to use") File file; @Parameters(index = "1", description = "another option", showDefaultValue = Help.Visibility.ON_DEMAND) File other; } String result = usageString(new Params(), Help.Ansi.OFF); assertEquals(format("" + "Usage: <main class> <file> <other>%n" + " <file> the file to use%n" + " <other> another option%n"), result); } @Test public void testCommandWithoutShowDefaultValuesPositionalOnDemandNonNullValue_hidesDefault() { @Command() class Params { @Parameters(index = "0", description = "the file to use") File file = new File("/tmp/file"); @Parameters(index = "1", description = "another option", showDefaultValue = Help.Visibility.ON_DEMAND) File other = new File("/tmp/other"); } String result = usageString(new Params(), Help.Ansi.OFF); assertEquals(format("" + "Usage: <main class> <file> <other>%n" + " <file> the file to use%n" + " <other> another option%n"), result); } @Test public void testCommandWithoutShowDefaultValuesPositionalAlwaysNullValue_showsNullDefault() { @Command() class Params { @Parameters(index = "0", description = "the file to use", showDefaultValue = Help.Visibility.ALWAYS) File file; } String result = usageString(new Params(), Help.Ansi.OFF); assertEquals(format("" + "Usage: <main class> <file>%n" + " <file> the file to use%n" + " Default: null%n"), result); } @Test public void testCommandWithoutShowDefaultValuesPositionalAlwaysNonNullValue_showsDefault() { @Command() class Params { @Parameters(index = "0", description = "the file to use", showDefaultValue = Help.Visibility.ALWAYS) File file = new File("/tmp/file"); } String result = usageString(new Params(), Help.Ansi.OFF); assertEquals(format("" + "Usage: <main class> <file>%n" + " <file> the file to use%n" + " Default: %s%n", new File("/tmp/file")), result); } @Test public void testCommandShowDefaultValuesPositionalOnDemandNullValue_hidesDefault() { @Command(showDefaultValues = true) class Params { @Parameters(index = "0", description = "the file to use") File file; @Parameters(index = "1", description = "another option", showDefaultValue = Help.Visibility.ON_DEMAND) File other; } String result = usageString(new Params(), Help.Ansi.OFF); assertEquals(format("" + "Usage: <main class> <file> <other>%n" + " <file> the file to use%n" + " <other> another option%n"), result); } @Test public void testCommandShowDefaultValuesPositionalNeverNullValue_hidesDefault() { @Command(showDefaultValues = true) class Params { @Parameters(index = "0", description = "the file to use") File file; @Parameters(index = "1", description = "another option", showDefaultValue = Help.Visibility.NEVER) File other; } String result = usageString(new Params(), Help.Ansi.OFF); assertEquals(format("" + "Usage: <main class> <file> <other>%n" + " <file> the file to use%n" + " <other> another option%n"), result); } @Test public void testCommandShowDefaultValuesPositionalAlwaysNullValue_showsNullDefault() { @Command(showDefaultValues = true) class Params { @Parameters(index = "0", description = "the file to use") File file; @Parameters(index = "1", description = "another option", showDefaultValue = Help.Visibility.ALWAYS) File other; } String result = usageString(new Params(), Help.Ansi.OFF); assertEquals(format("" + "Usage: <main class> <file> <other>%n" + " <file> the file to use%n" + " <other> another option%n" + " Default: null%n"), result); } @Test public void testCommandShowDefaultValuesPositionalOnDemandNonNullValue_showsDefault() { @Command(showDefaultValues = true) class Params { @Parameters(index = "0", description = "the file to use") File file = new File("theDefault.txt"); @Parameters(index = "1", description = "another option", showDefaultValue = Help.Visibility.ON_DEMAND) File other = new File("other.txt"); } String result = usageString(new Params(), Help.Ansi.OFF); assertEquals(format("" + "Usage: <main class> <file> <other>%n" + " <file> the file to use%n" + " Default: theDefault.txt%n" + " <other> another option%n" + " Default: other.txt%n"), result); } @Test public void testCommandShowDefaultValuesPositionalNeverNonNullValue_hidesDefault() { @Command(showDefaultValues = true) class Params { @Parameters(index = "0", description = "the file to use") File file = new File("theDefault.txt"); @Parameters(index = "1", description = "another option", showDefaultValue = Help.Visibility.NEVER) File other = new File("other.txt"); } String result = usageString(new Params(), Help.Ansi.OFF); assertEquals(format("" + "Usage: <main class> <file> <other>%n" + " <file> the file to use%n" + " Default: theDefault.txt%n" + " <other> another option%n"), result); } @Test public void testCommandShowDefaultValuesPositionalAlwaysNonNullValue_hidesDefault() { @Command(showDefaultValues = true) class Params { @Parameters(index = "0", description = "the file to use") File file = new File("theDefault.txt"); @Parameters(index = "1", description = "another option", showDefaultValue = Help.Visibility.ALWAYS) File other = new File("other.txt"); } String result = usageString(new Params(), Help.Ansi.OFF); assertEquals(format("" + "Usage: <main class> <file> <other>%n" + " <file> the file to use%n" + " Default: theDefault.txt%n" + " <other> another option%n" + " Default: other.txt%n"), result); } @Test public void testPositionalParamSpec_defaultValue_overwritesInitialValue() { @Command(showDefaultValues = true) class Params { @Parameters(paramLabel = "INT", description = "the array") int[] value = {1, 5, 11, 23}; } CommandLine cmd = new CommandLine(new Params()); PositionalParamSpec x = cmd.getCommandSpec().positionalParameters().get(0).toBuilder().defaultValue("5,4,3,2,1").splitRegex(",").build(); cmd = new CommandLine(CommandSpec.create().add(x)); cmd.getCommandSpec().usageMessage().showDefaultValues(true); String result = usageString(cmd, Help.Ansi.OFF); assertEquals(format("" + "Usage: <main class> [INT[,INT...]...]%n" + " [INT[,INT...]...] the array%n" + " Default: 5,4,3,2,1%n"), result); } @Test public void testUsageSeparatorWithoutDefault() { @Command() class Params { @Option(names = {"-f", "--file"}, required = true, description = "the file to use") File file = new File("def.txt"); } String result = usageString(new Params(), Help.Ansi.OFF); assertEquals(format("" + "Usage: <main class> -f=<file>%n" + " -f, --file=<file> the file to use%n"), result); } @Test public void testUsageSeparator() { @Command(showDefaultValues = true) class Params { @Option(names = {"-f", "--file"}, required = true, description = "the file to use") File file = new File("def.txt"); } String result = usageString(new Params(), Help.Ansi.OFF); assertEquals(format("" + "Usage: <main class> -f=<file>%n" + " -f, --file=<file> the file to use%n" + " Default: def.txt%n"), result); } @Test public void testUsageParamLabels() { @Command() class ParamLabels { @Option(names = "-P", paramLabel = "KEY=VALUE", type = {String.class, String.class}, description = "Project properties (key-value pairs)") Map<String, String> props; @Option(names = "-f", paramLabel = "FILE", description = "files") File[] f; @Option(names = "-n", description = "a number option") int number; @Parameters(index = "0", paramLabel = "NUM", description = "number param") int n; @Parameters(index = "1", description = "the host parameter") InetAddress host; } String result = usageString(new ParamLabels(), Help.Ansi.OFF); assertEquals(format("" + "Usage: <main class> [-n=<number>] [-f=FILE]... [-P=KEY=VALUE]... NUM <host>%n" + " NUM number param%n" + " <host> the host parameter%n" + " -f=FILE files%n" + " -n=<number> a number option%n" + " -P=KEY=VALUE Project properties (key-value pairs)%n"), result); } @Test public void testUsageParamLabelsWithLongMapOptionName() { @Command() class ParamLabels { @Option(names = {"-P", "--properties"}, paramLabel = "KEY=VALUE", type = {String.class, String.class}, description = "Project properties (key-value pairs)") Map<String, String> props; @Option(names = "-f", paramLabel = "FILE", description = "a file") File f; @Option(names = "-n", description = "a number option") int number; @Parameters(index = "0", paramLabel = "NUM", description = "number param") int n; @Parameters(index = "1", description = "the host parameter") InetAddress host; } String result = usageString(new ParamLabels(), Help.Ansi.OFF); assertEquals(format("" + "Usage: <main class> [-f=FILE] [-n=<number>] [-P=KEY=VALUE]... NUM <host>%n" + " NUM number param%n" + " <host> the host parameter%n" + " -f=FILE a file%n" + " -n=<number> a number option%n" + " -P, --properties=KEY=VALUE%n" + " Project properties (key-value pairs)%n"), result); } // --------------- @Test public void testUsageVariableArityRequiredShortOptionArray() throws UnsupportedEncodingException { // if option is required at least once and can be specified multiple times: // -f=ARG [-f=ARG]... class Args { @Option(names = "-a", required = true, paramLabel = "ARG") // default String[] a; @Option(names = "-b", required = true, paramLabel = "ARG", arity = "0..*") List<String> b; @Option(names = "-c", required = true, paramLabel = "ARG", arity = "1..*") String[] c; @Option(names = "-d", required = true, paramLabel = "ARG", arity = "2..*") List<String> d; } String expected = String.format("" + "Usage: <main class> -a=ARG [-a=ARG]... -b[=ARG...] [-b[=ARG...]]... -c=ARG...%n" + " [-c=ARG...]... -d=ARG ARG... [-d=ARG ARG...]...%n" + " -a=ARG%n" + " -b=[ARG...]%n" + " -c=ARG...%n" + " -d=ARG ARG...%n"); //CommandLine.usage(new Args(), System.out); assertEquals(expected, usageString(new Args(), Help.Ansi.OFF)); } @Test public void testUsageVariableArityShortOptionArray() throws UnsupportedEncodingException { class Args { @Option(names = "-a", paramLabel = "ARG") // default List<String> a; @Option(names = "-b", paramLabel = "ARG", arity = "0..*") String[] b; @Option(names = "-c", paramLabel = "ARG", arity = "1..*") List<String> c; @Option(names = "-d", paramLabel = "ARG", arity = "2..*") String[] d; } String expected = String.format("" + "Usage: <main class> [-a=ARG]... [-b[=ARG...]]... [-c=ARG...]... [-d=ARG%n" + " ARG...]...%n" + " -a=ARG%n" + " -b=[ARG...]%n" + " -c=ARG...%n" + " -d=ARG ARG...%n"); //CommandLine.usage(new Args(), System.out); assertEquals(expected, usageString(new Args(), Help.Ansi.OFF)); } @Test public void testUsageRangeArityRequiredShortOptionArray() throws UnsupportedEncodingException { // if option is required at least once and can be specified multiple times: // -f=ARG [-f=ARG]... class Args { @Option(names = "-a", required = true, paramLabel = "ARG", arity = "0..1") List<String> a; @Option(names = "-b", required = true, paramLabel = "ARG", arity = "1..2") String[] b; @Option(names = "-c", required = true, paramLabel = "ARG", arity = "1..3") String[] c; @Option(names = "-d", required = true, paramLabel = "ARG", arity = "2..4") String[] d; } String expected = String.format("" + "Usage: <main class> -a[=ARG] [-a[=ARG]]... -b=ARG [ARG] [-b=ARG [ARG]]...%n" + " -c=ARG [ARG [ARG]] [-c=ARG [ARG [ARG]]]... -d=ARG ARG [ARG%n" + " [ARG]] [-d=ARG ARG [ARG [ARG]]]...%n" + " -a=[ARG]%n" + " -b=ARG [ARG]%n" + " -c=ARG [ARG [ARG]]%n" + " -d=ARG ARG [ARG [ARG]]%n"); //CommandLine.usage(new Args(), System.out); assertEquals(expected, usageString(new Args(), Help.Ansi.OFF)); } @Test public void testUsageRangeArityShortOptionArray() throws UnsupportedEncodingException { class Args { @Option(names = "-a", paramLabel = "ARG", arity = "0..1") List<String> a; @Option(names = "-b", paramLabel = "ARG", arity = "1..2") String[] b; @Option(names = "-c", paramLabel = "ARG", arity = "1..3") String[] c; @Option(names = "-d", paramLabel = "ARG", arity = "2..4") String[] d; } String expected = String.format("" + "Usage: <main class> [-a[=ARG]]... [-b=ARG [ARG]]... [-c=ARG [ARG [ARG]]]...%n" + " [-d=ARG ARG [ARG [ARG]]]...%n" + " -a=[ARG]%n" + " -b=ARG [ARG]%n" + " -c=ARG [ARG [ARG]]%n" + " -d=ARG ARG [ARG [ARG]]%n"); //CommandLine.usage(new Args(), System.out); assertEquals(expected, usageString(new Args(), Help.Ansi.OFF)); } @Test public void testUsageFixedArityRequiredShortOptionArray() throws UnsupportedEncodingException { // if option is required at least once and can be specified multiple times: // -f=ARG [-f=ARG]... class Args { @Option(names = "-a", required = true, paramLabel = "ARG") // default String[] a; @Option(names = "-b", required = true, paramLabel = "ARG", arity = "0") String[] b; @Option(names = "-c", required = true, paramLabel = "ARG", arity = "1") String[] c; @Option(names = "-d", required = true, paramLabel = "ARG", arity = "2") String[] d; } String expected = String.format("" + "Usage: <main class> -b [-b]... -a=ARG [-a=ARG]... -c=ARG [-c=ARG]... -d=ARG ARG%n" + " [-d=ARG ARG]...%n" + " -a=ARG%n" + " -b%n" + " -c=ARG%n" + " -d=ARG ARG%n"); //CommandLine.usage(new Args(), System.out); assertEquals(expected, usageString(new Args(), Help.Ansi.OFF)); } @Test public void testUsageFixedArityShortOptionArray() throws UnsupportedEncodingException { class Args { @Option(names = "-a", paramLabel = "ARG") // default String[] a; @Option(names = "-b", paramLabel = "ARG", arity = "0") String[] b; @Option(names = "-c", paramLabel = "ARG", arity = "1") String[] c; @Option(names = "-d", paramLabel = "ARG", arity = "2") String[] d; } String expected = String.format("" + "Usage: <main class> [-b]... [-a=ARG]... [-c=ARG]... [-d=ARG ARG]...%n" + " -a=ARG%n" + " -b%n" + " -c=ARG%n" + " -d=ARG ARG%n"); //CommandLine.usage(new Args(), System.out); assertEquals(expected, usageString(new Args(), Help.Ansi.OFF)); } //-------------- @Test public void testUsageVariableArityRequiredLongOptionArray() throws UnsupportedEncodingException { // if option is required at least once and can be specified multiple times: // -f=ARG [-f=ARG]... class Args { @Option(names = "--aa", required = true, paramLabel = "ARG") // default String[] a; @Option(names = "--bb", required = true, paramLabel = "ARG", arity = "0..*") List<String> b; @Option(names = "--cc", required = true, paramLabel = "ARG", arity = "1..*") String[] c; @Option(names = "--dd", required = true, paramLabel = "ARG", arity = "2..*") List<String> d; } String expected = String.format("" + "Usage: <main class> --aa=ARG [--aa=ARG]... --bb[=ARG...] [--bb[=ARG...]]...%n" + " --cc=ARG... [--cc=ARG...]... --dd=ARG ARG... [--dd=ARG%n" + " ARG...]...%n" + " --aa=ARG%n" + " --bb[=ARG...]%n" + " --cc=ARG...%n" + " --dd=ARG ARG...%n"); //CommandLine.usage(new Args(), System.out); assertEquals(expected, usageString(new Args(), Help.Ansi.OFF)); } @Test public void testUsageVariableArityLongOptionArray() throws UnsupportedEncodingException { class Args { @Option(names = "--aa", paramLabel = "ARG") // default List<String> a; @Option(names = "--bb", paramLabel = "ARG", arity = "0..*") String[] b; @Option(names = "--cc", paramLabel = "ARG", arity = "1..*") List<String> c; @Option(names = "--dd", paramLabel = "ARG", arity = "2..*") String[] d; } String expected = String.format("" + "Usage: <main class> [--aa=ARG]... [--bb[=ARG...]]... [--cc=ARG...]... [--dd=ARG%n" + " ARG...]...%n" + " --aa=ARG%n" + " --bb[=ARG...]%n" + " --cc=ARG...%n" + " --dd=ARG ARG...%n"); //CommandLine.usage(new Args(), System.out); assertEquals(expected, usageString(new Args(), Help.Ansi.OFF)); } @Test public void testUsageRangeArityRequiredLongOptionArray() throws UnsupportedEncodingException { // if option is required at least once and can be specified multiple times: // -f=ARG [-f=ARG]... class Args { @Option(names = "--aa", required = true, paramLabel = "ARG", arity = "0..1") List<String> a; @Option(names = "--bb", required = true, paramLabel = "ARG", arity = "1..2") String[] b; @Option(names = "--cc", required = true, paramLabel = "ARG", arity = "1..3") String[] c; @Option(names = "--dd", required = true, paramLabel = "ARG", arity = "2..4", description = "foobar") String[] d; } String expected = String.format("" + "Usage: <main class> --aa[=ARG] [--aa[=ARG]]... --bb=ARG [ARG] [--bb=ARG%n" + " [ARG]]... --cc=ARG [ARG [ARG]] [--cc=ARG [ARG [ARG]]]...%n" + " --dd=ARG ARG [ARG [ARG]] [--dd=ARG ARG [ARG [ARG]]]...%n" + " --aa[=ARG]%n" + " --bb=ARG [ARG]%n" + " --cc=ARG [ARG [ARG]]%n" + " --dd=ARG ARG [ARG [ARG]]%n" + " foobar%n"); //CommandLine.usage(new Args(), System.out); assertEquals(expected, usageString(new Args(), Help.Ansi.OFF)); } @Test public void testUsageRangeArityLongOptionArray() throws UnsupportedEncodingException { class Args { @Option(names = "--aa", paramLabel = "ARG", arity = "0..1") List<String> a; @Option(names = "--bb", paramLabel = "ARG", arity = "1..2") String[] b; @Option(names = "--cc", paramLabel = "ARG", arity = "1..3") String[] c; @Option(names = "--dd", paramLabel = "ARG", arity = "2..4", description = "foobar") String[] d; } String expected = String.format("" + "Usage: <main class> [--aa[=ARG]]... [--bb=ARG [ARG]]... [--cc=ARG [ARG%n" + " [ARG]]]... [--dd=ARG ARG [ARG [ARG]]]...%n" + " --aa[=ARG]%n" + " --bb=ARG [ARG]%n" + " --cc=ARG [ARG [ARG]]%n" + " --dd=ARG ARG [ARG [ARG]]%n" + " foobar%n"); //CommandLine.usage(new Args(), System.out); assertEquals(expected, usageString(new Args(), Help.Ansi.OFF)); } @Test public void testUsageFixedArityRequiredLongOptionArray() throws UnsupportedEncodingException { // if option is required at least once and can be specified multiple times: // -f=ARG [-f=ARG]... class Args { @Option(names = "--aa", required = true, paramLabel = "ARG") // default String[] a; @Option(names = "--bb", required = true, paramLabel = "ARG", arity = "0") String[] b; @Option(names = "--cc", required = true, paramLabel = "ARG", arity = "1") String[] c; @Option(names = "--dd", required = true, paramLabel = "ARG", arity = "2") String[] d; } String expected = String.format("" + "Usage: <main class> --bb [--bb]... --aa=ARG [--aa=ARG]... --cc=ARG%n" + " [--cc=ARG]... --dd=ARG ARG [--dd=ARG ARG]...%n" + " --aa=ARG%n" + " --bb%n" + " --cc=ARG%n" + " --dd=ARG ARG%n"); //CommandLine.usage(new Args(), System.out); assertEquals(expected, usageString(new Args(), Help.Ansi.OFF)); } @Test public void testUsageFixedArityLongOptionArray() throws UnsupportedEncodingException { class Args { @Option(names = "--aa", paramLabel = "ARG") // default String[] a; @Option(names = "--bb", paramLabel = "ARG", arity = "0") String[] b; @Option(names = "--cc", paramLabel = "ARG", arity = "1") String[] c; @Option(names = "--dd", paramLabel = "ARG", arity = "2") String[] d; } String expected = String.format("" + "Usage: <main class> [--bb]... [--aa=ARG]... [--cc=ARG]... [--dd=ARG ARG]...%n" + " --aa=ARG%n" + " --bb%n" + " --cc=ARG%n" + " --dd=ARG ARG%n"); //CommandLine.usage(new Args(), System.out); assertEquals(expected, usageString(new Args(), Help.Ansi.OFF)); } //------------------ @Test public void testUsageVariableArityRequiredShortOptionMap() throws UnsupportedEncodingException { // if option is required at least once and can be specified multiple times: // -f=ARG [-f=ARG]... class Args { @Option(names = "-a", required = true, paramLabel = "KEY=VAL") // default Map<String, String> a; @Option(names = "-b", required = true, arity = "0..*") @SuppressWarnings("unchecked") Map b; @Option(names = "-c", required = true, arity = "1..*", type = {String.class, TimeUnit.class}) Map<String, TimeUnit> c; @Option(names = "-d", required = true, arity = "2..*", type = {Integer.class, URL.class}, description = "description") Map<Integer, URL> d; } String expected = String.format("" + "Usage: <main class> -a=KEY=VAL [-a=KEY=VAL]... -b[=<String=String>...] [-b%n" + " [=<String=String>...]]... -c=<String=TimeUnit>...%n" + " [-c=<String=TimeUnit>...]... -d=<Integer=URL>%n" + " <Integer=URL>... [-d=<Integer=URL> <Integer=URL>...]...%n" + " -a=KEY=VAL%n" + " -b=[<String=String>...]%n" + " -c=<String=TimeUnit>...%n" + " -d=<Integer=URL> <Integer=URL>...%n" + " description%n"); //CommandLine.usage(new Args(), System.out); assertEquals(expected, usageString(new Args(), Help.Ansi.OFF)); } @Test public void testUsageVariableArityOptionMap() throws UnsupportedEncodingException { class Args { @Option(names = "-a") // default Map<String, String> a; @Option(names = "-b", arity = "0..*", type = {Integer.class, Integer.class}) Map<Integer, Integer> b; @Option(names = "-c", paramLabel = "KEY=VALUE", arity = "1..*", type = {String.class, TimeUnit.class}) Map<String, TimeUnit> c; @Option(names = "-d", arity = "2..*", type = {String.class, URL.class}, description = "description") Map<String, URL> d; } String expected = String.format("" + "Usage: <main class> [-a=<String=String>]... [-b[=<Integer=Integer>...]]...%n" + " [-c=KEY=VALUE...]... [-d=<String=URL> <String=URL>...]...%n" + " -a=<String=String>%n" + " -b=[<Integer=Integer>...]%n" + "%n" + // TODO " -c=KEY=VALUE...%n" + " -d=<String=URL> <String=URL>...%n" + " description%n"); //CommandLine.usage(new Args(), System.out); assertEquals(expected, usageString(new Args(), Help.Ansi.OFF)); } @Test public void testUsageRangeArityRequiredOptionMap() throws UnsupportedEncodingException { // if option is required at least once and can be specified multiple times: // -f=ARG [-f=ARG]... class Args { @Option(names = "-a", required = true, arity = "0..1", description = "a description") Map<String, String> a; @Option(names = "-b", required = true, arity = "1..2", type = {Integer.class, Integer.class}, description = "b description") Map<Integer, Integer> b; @Option(names = "-c", required = true, arity = "1..3", type = {String.class, URL.class}, description = "c description") Map<String, URL> c; @Option(names = "-d", required = true, paramLabel = "K=URL", arity = "2..4", description = "d description") Map<String, URL> d; } String expected = String.format("" + "Usage: <main class> -a[=<String=String>] [-a[=<String=String>]]...%n" + " -b=<Integer=Integer> [<Integer=Integer>]%n" + " [-b=<Integer=Integer> [<Integer=Integer>]]...%n" + " -c=<String=URL> [<String=URL> [<String=URL>]]%n" + " [-c=<String=URL> [<String=URL> [<String=URL>]]]... -d=K=URL%n" + " K=URL [K=URL [K=URL]] [-d=K=URL K=URL [K=URL [K=URL]]]...%n" + " -a=[<String=String>] a description%n" + " -b=<Integer=Integer> [<Integer=Integer>]%n" + " b description%n" + " -c=<String=URL> [<String=URL> [<String=URL>]]%n" + " c description%n" + " -d=K=URL K=URL [K=URL [K=URL]]%n" + " d description%n"); //CommandLine.usage(new Args(), System.out); assertEquals(expected, usageString(new Args(), Help.Ansi.OFF)); } @Test public void testUsageRangeArityOptionMap() throws UnsupportedEncodingException { class Args { @Option(names = "-a", arity = "0..1"/*, type = {UUID.class, URL.class}*/, description = "a description") Map<UUID, URL> a; @Option(names = "-b", arity = "1..2", type = {Long.class, UUID.class}, description = "b description") Map<?, ?> b; @Option(names = "-c", arity = "1..3", type = {Long.class}, description = "c description") Map<?, ?> c; @Option(names = "-d", paramLabel = "K=V", arity = "2..4", description = "d description") Map<?, ?> d; } String expected = String.format("" + "Usage: <main class> [-a[=<UUID=URL>]]... [-b=<Long=UUID> [<Long=UUID>]]...%n" + " [-c=<String=String> [<String=String> [<String=String>]]]...%n" + " [-d=K=V K=V [K=V [K=V]]]...%n" + " -a=[<UUID=URL>] a description%n" + " -b=<Long=UUID> [<Long=UUID>]%n" + " b description%n" + " -c=<String=String> [<String=String> [<String=String>]]%n" + " c description%n" + " -d=K=V K=V [K=V [K=V]] d description%n"); //CommandLine.usage(new Args(), System.out); assertEquals(expected, usageString(new Args(), Help.Ansi.OFF)); } @Test public void testUsageFixedArityRequiredOptionMap() throws UnsupportedEncodingException { // if option is required at least once and can be specified multiple times: // -f=ARG [-f=ARG]... class Args { @Option(names = "-a", required = true, description = "a description") Map<Short, Field> a; @Option(names = "-b", required = true, paramLabel = "KEY=VAL", arity = "0", description = "b description") @SuppressWarnings("unchecked") Map<?, ?> b; @Option(names = "-c", required = true, arity = "1", type = {Long.class, File.class}, description = "c description") Map<Long, File> c; @Option(names = "-d", required = true, arity = "2", type = {URI.class, URL.class}, description = "d description") Map<URI, URL> d; } String expected = String.format("" + "Usage: <main class> -b [-b]... -a=<Short=Field> [-a=<Short=Field>]...%n" + " -c=<Long=File> [-c=<Long=File>]... -d=<URI=URL> <URI=URL>%n" + " [-d=<URI=URL> <URI=URL>]...%n" + " -a=<Short=Field> a description%n" + " -b b description%n" + " -c=<Long=File> c description%n" + " -d=<URI=URL> <URI=URL> d description%n"); //CommandLine.usage(new Args(), System.out); assertEquals(expected, usageString(new Args(), Help.Ansi.OFF)); } @Test public void testUsageFixedArityOptionMap() throws UnsupportedEncodingException { class Args { @Option(names = "-a", type = {Short.class, Field.class}, description = "a description") Map<Short, Field> a; @Option(names = "-b", arity = "0", type = {UUID.class, Long.class}, description = "b description") @SuppressWarnings("unchecked") Map<?, ?> b; @Option(names = "-c", arity = "1", description = "c description") Map<Long, File> c; @Option(names = "-d", arity = "2", type = {URI.class, URL.class}, description = "d description") Map<URI, URL> d; } String expected = String.format("" + "Usage: <main class> [-b]... [-a=<Short=Field>]... [-c=<Long=File>]...%n" + " [-d=<URI=URL> <URI=URL>]...%n" + " -a=<Short=Field> a description%n" + " -b b description%n" + " -c=<Long=File> c description%n" + " -d=<URI=URL> <URI=URL> d description%n"); //CommandLine.usage(new Args(), System.out); assertEquals(expected, usageString(new Args(), Help.Ansi.OFF)); } //-------------- @Test public void testUsageVariableArityParametersArray() throws UnsupportedEncodingException { // if option is required at least once and can be specified multiple times: // -f=ARG [-f=ARG]... class Args { @Parameters(paramLabel = "APARAM", description = "APARAM description") String[] a; @Parameters(arity = "0..*", description = "b description") List<String> b; @Parameters(arity = "1..*", description = "c description") String[] c; @Parameters(arity = "2..*", description = "d description") List<String> d; } String expected = String.format("" + "Usage: <main class> [APARAM...] [<b>...] <c>... <d> <d>...%n" + " [APARAM...] APARAM description%n" + " [<b>...] b description%n" + " <c>... c description%n" + " <d> <d>... d description%n"); //CommandLine.usage(new Args(), System.out); assertEquals(expected, usageString(new Args(), Help.Ansi.OFF)); } @Test public void testUsageRangeArityParameterArray() throws UnsupportedEncodingException { class Args { @Parameters(index = "0", paramLabel = "PARAMA", arity = "0..1", description = "PARAMA description") List<String> a; @Parameters(index = "0", paramLabel = "PARAMB", arity = "1..2", description = "PARAMB description") String[] b; @Parameters(index = "0", paramLabel = "PARAMC", arity = "1..3", description = "PARAMC description") String[] c; @Parameters(index = "0", paramLabel = "PARAMD", arity = "2..4", description = "PARAMD description") String[] d; } String expected = String.format("" + "Usage: <main class> [PARAMA] PARAMB [PARAMB] PARAMC [PARAMC [PARAMC]] PARAMD%n" + " PARAMD [PARAMD [PARAMD]]%n" + " [PARAMA] PARAMA description%n" + " PARAMB [PARAMB] PARAMB description%n" + " PARAMC [PARAMC [PARAMC]]%n" + " PARAMC description%n" + " PARAMD PARAMD [PARAMD [PARAMD]]%n" + " PARAMD description%n"); //CommandLine.usage(new Args(), System.out); assertEquals(expected, usageString(new Args(), Help.Ansi.OFF)); } @Test public void testUsageFixedArityParametersArray() throws UnsupportedEncodingException { class Args { @Parameters(description = "a description (default arity)") String[] a; @Parameters(index = "0", arity = "0", description = "b description (arity=0)") String[] b; @Parameters(index = "1", arity = "1", description = "b description (arity=1)") String[] c; @Parameters(index = "2", arity = "2", description = "b description (arity=2)") String[] d; } String expected = String.format("" + "Usage: <main class> [<a>...] <c> <d> <d>%n" + " b description (arity=0)%n" + " [<a>...] a description (default arity)%n" + " <c> b description (arity=1)%n" + " <d> <d> b description (arity=2)%n"); //CommandLine.usage(new Args(), System.out); assertEquals(expected, usageString(new Args(), Help.Ansi.OFF)); } @Test public void testUsageVariableArityParametersMap() throws UnsupportedEncodingException { class Args { @Parameters() Map<String, String> a; @Parameters(arity = "0..*", description = "a description (arity=0..*)") Map<Integer, Integer> b; @Parameters(paramLabel = "KEY=VALUE", arity = "1..*", type = {String.class, TimeUnit.class}) Map<String, TimeUnit> c; @Parameters(arity = "2..*", type = {String.class, URL.class}, description = "description") Map<String, URL> d; } String expected = String.format("" + "Usage: <main class> [<String=String>...] [<Integer=Integer>...] KEY=VALUE...%n" + " <String=URL> <String=URL>...%n" + " [<String=String>...]%n" + " [<Integer=Integer>...] a description (arity=0..*)%n" + " KEY=VALUE...%n" + " <String=URL> <String=URL>...%n" + " description%n"); //CommandLine.usage(new Args(), System.out); assertEquals(expected, usageString(new Args(), Help.Ansi.OFF)); } @Test public void testUsageRangeArityParametersMap() throws UnsupportedEncodingException { class Args { @Parameters(index = "0", arity = "0..1"/*, type = {UUID.class, URL.class}*/, description = "a description") Map<UUID, URL> a; @Parameters(index = "1", arity = "1..2", type = {Long.class, UUID.class}, description = "b description") Map<?, ?> b; @Parameters(index = "2", arity = "1..3", type = {Long.class}, description = "c description") Map<?, ?> c; @Parameters(index = "3", paramLabel = "K=V", arity = "2..4", description = "d description") Map<?, ?> d; } String expected = String.format("" + "Usage: <main class> [<UUID=URL>] <Long=UUID> [<Long=UUID>] <String=String>%n" + " [<String=String> [<String=String>]] K=V K=V [K=V [K=V]]%n" + " [<UUID=URL>] a description%n" + " <Long=UUID> [<Long=UUID>]%n" + " b description%n" + " <String=String> [<String=String> [<String=String>]]%n" + " c description%n" + " K=V K=V [K=V [K=V]] d description%n"); //CommandLine.usage(new Args(), System.out); assertEquals(expected, usageString(new Args(), Help.Ansi.OFF)); } @Test public void testUsageFixedArityParametersMap() throws UnsupportedEncodingException { class Args { @Parameters(type = {Short.class, Field.class}, description = "a description") Map<Short, Field> a; @Parameters(index = "0", arity = "0", type = {UUID.class, Long.class}, description = "b description (arity=0)") @SuppressWarnings("unchecked") Map<?, ?> b; @Parameters(index = "1", arity = "1", description = "c description") Map<Long, File> c; @Parameters(index = "2", arity = "2", type = {URI.class, URL.class}, description = "d description") Map<URI, URL> d; } String expected = String.format("" + "Usage: <main class> [<Short=Field>...] <Long=File> <URI=URL> <URI=URL>%n" + " b description (arity=0)%n" + " [<Short=Field>...] a description%n" + " <Long=File> c description%n" + " <URI=URL> <URI=URL> d description%n"); //CommandLine.usage(new Args(), System.out); assertEquals(expected, usageString(new Args(), Help.Ansi.OFF)); } //---------- @Test public void testShortestFirstComparator_sortsShortestFirst() { String[] values = {"12345", "12", "123", "123456", "1", "", "1234"}; Arrays.sort(values, new Help.ShortestFirst()); String[] expected = {"", "1", "12", "123", "1234", "12345", "123456"}; assertArrayEquals(expected, values); } @Test public void testShortestFirstComparator_sortsShortestFirst2() { String[] values = {"12345", "12", "123", "123456", "1", "", "1234"}; Arrays.sort(values, Help.shortestFirst()); String[] expected = {"", "1", "12", "123", "1234", "12345", "123456"}; assertArrayEquals(expected, values); } @Test public void testShortestFirstComparator_sortsDeclarationOrderIfEqualLength() { String[] values = {"-d", "-", "-a", "--alpha", "--b", "--a", "--beta"}; Arrays.sort(values, new Help.ShortestFirst()); String[] expected = {"-", "-d", "-a", "--b", "--a", "--beta", "--alpha"}; assertArrayEquals(expected, values); } @Test public void testSortByShortestOptionNameComparator() throws Exception { class App { @Option(names = {"-t", "--aaaa"}) boolean aaaa; @Option(names = {"--bbbb", "-k"}) boolean bbbb; @Option(names = {"-c", "--cccc"}) boolean cccc; } OptionSpec[] fields = options(new App(), "aaaa", "bbbb", "cccc"); // -tkc Arrays.sort(fields, new Help.SortByShortestOptionNameAlphabetically()); OptionSpec[] expected = options(new App(), "cccc", "bbbb", "aaaa"); // -ckt assertEquals(expected[0], fields[0]); assertEquals(expected[1], fields[1]); assertEquals(expected[2], fields[2]); assertArrayEquals(expected, fields); } @Test public void testSortByOptionArityAndNameComparator_sortsByMaxThenMinThenName() throws Exception { class App { @Option(names = {"-t", "--aaaa"} ) boolean tImplicitArity0; @Option(names = {"-e", "--EEE"}, arity = "1" ) boolean explicitArity1; @Option(names = {"--bbbb", "-k"} ) boolean kImplicitArity0; @Option(names = {"--AAAA", "-a"} ) int aImplicitArity1; @Option(names = {"--BBBB", "-z"} ) String[] zImplicitArity1; @Option(names = {"--ZZZZ", "-b"}, arity = "1..3") String[] bExplicitArity1_3; @Option(names = {"-f", "--ffff"} ) boolean fImplicitArity0; } OptionSpec[] fields = options(new App(), "tImplicitArity0", "explicitArity1", "kImplicitArity0", "aImplicitArity1", "zImplicitArity1", "bExplicitArity1_3", "fImplicitArity0"); Arrays.sort(fields, new Help.SortByOptionArityAndNameAlphabetically()); OptionSpec[] expected = options(new App(), "fImplicitArity0", "kImplicitArity0", "tImplicitArity0", "aImplicitArity1", "explicitArity1", "zImplicitArity1", "bExplicitArity1_3"); assertArrayEquals(expected, fields); } @Test public void testSortByShortestOptionNameAlphabetically_handlesNulls() throws Exception { Help.SortByShortestOptionNameAlphabetically sort = new Help.SortByShortestOptionNameAlphabetically(); OptionSpec a = OptionSpec.builder("-a").build(); OptionSpec b = OptionSpec.builder("-b").build(); assertEquals(1, sort.compare(null, a)); assertEquals(-1, sort.compare(a, null)); assertEquals(-1, sort.compare(a, b)); assertEquals(0, sort.compare(a, a)); assertEquals(1, sort.compare(b, a)); } @Test public void testSortByOptionOrder() throws Exception { class App { @Option(names = {"-a"}, order = 9) boolean a; @Option(names = {"-b"}, order = 8) boolean b; @Option(names = {"-c"}, order = 7) boolean c; @Option(names = {"-d"}, order = 6) int d; @Option(names = {"-e"}, order = 5) String[] e; @Option(names = {"-f"}, order = 4) String[] f; @Option(names = {"-g"}, order = 3) boolean g; } OptionSpec[] fields = options(new App(), "a", "b", "c", "d", "e", "f", "g"); Arrays.sort(fields, Help.createOrderComparator()); OptionSpec[] expected = options(new App(), "g", "f", "e", "d", "c", "b", "a"); assertArrayEquals(expected, fields); } @Test public void testSortByOptionOrderAllowsGaps() throws Exception { @Command(sortOptions = false) class App { @Option(names = {"-a"}, order = 9) boolean a; @Option(names = {"-b"}, order = 8) boolean b; @Option(names = {"-c"}, order = 7) boolean c; @Option(names = {"-d"}, order = 6) int d; @Option(names = {"-e"}, order = 3) String[] e; @Option(names = {"-f"}, order = 1) String[] f; @Option(names = {"-g"}, order = 0) boolean g; } OptionSpec[] fields = options(new App(), "a", "b", "c", "d", "e", "f", "g"); Arrays.sort(fields, Help.createOrderComparator()); OptionSpec[] expected = options(new App(), "g", "f", "e", "d", "c", "b", "a"); assertArrayEquals(expected, fields); String expectedUsage = String.format("" + "Usage: <main class> [-abcg] [-d=<d>] [-e=<e>]... [-f=<f>]...%n" + " -g%n" + " -f=<f>%n" + " -e=<e>%n" + " -d=<d>%n" + " -c%n" + " -b%n" + " -a%n"); assertEquals(expectedUsage, new CommandLine(new App()).getUsageMessage()); } @Test public void testSortByOptionOrderStableSortWhenEqualOrder() throws Exception { @Command(sortOptions = false) class App { @Option(names = {"-a"}, order = 9) boolean a; @Option(names = {"-b"}, order = 8) boolean b; @Option(names = {"-c"}, order = 7) boolean c; @Option(names = {"-d"}, order = 7) int d; @Option(names = {"-e"}, order = 7) String[] e; @Option(names = {"-f"}, order = 7) String[] f; @Option(names = {"-g"}, order = 0) boolean g; } OptionSpec[] fields = options(new App(), "a", "b", "c", "d", "e", "f", "g"); Arrays.sort(fields, Help.createOrderComparator()); OptionSpec[] expected = options(new App(), "g", "c", "d", "e", "f", "b", "a"); assertArrayEquals(expected, fields); String expectedUsage = String.format("" + "Usage: <main class> [-abcg] [-d=<d>] [-e=<e>]... [-f=<f>]...%n" + " -g%n" + " -c%n" + " -d=<d>%n" + " -e=<e>%n" + " -f=<f>%n" + " -b%n" + " -a%n"); assertEquals(expectedUsage, new CommandLine(new App()).getUsageMessage()); } @Test public void testSortDeclarationOrderWhenOrderAttributeOmitted() { @Command(sortOptions = false) class App { @Option(names = {"-a"}) boolean a; @Option(names = {"-b"}) boolean b; @Option(names = {"-c"}) boolean c; @Option(names = {"-d"}) int d; @Option(names = {"-e"}) String[] e; @Option(names = {"-f"}) String[] f; @Option(names = {"-g"}) boolean g; } String expectedUsage = String.format("" + "Usage: <main class> [-abcg] [-d=<d>] [-e=<e>]... [-f=<f>]...%n" + " -a%n" + " -b%n" + " -c%n" + " -d=<d>%n" + " -e=<e>%n" + " -f=<f>%n" + " -g%n"); assertEquals(expectedUsage, new CommandLine(new App()).getUsageMessage()); } @Test public void testCreateMinimalOptionRenderer_ReturnsMinimalOptionRenderer() { assertEquals(Help.MinimalOptionRenderer.class, Help.createMinimalOptionRenderer().getClass()); } @Test public void testMinimalOptionRenderer_rendersFirstDeclaredOptionNameAndDescription() { class Example { @Option(names = {"---long", "-L"}, description = "long description") String longField; @Option(names = {"-b", "-a", "--alpha"}, description = "other") String otherField; } Help.IOptionRenderer renderer = Help.createMinimalOptionRenderer(); Help help = new Help(new Example(), Help.Ansi.ON); Help.IParamLabelRenderer parameterRenderer = help.createDefaultParamLabelRenderer(); OptionSpec option = help.options().get(0); Text[][] row1 = renderer.render(option, parameterRenderer, Help.defaultColorScheme( help.ansi())); assertEquals(1, row1.length); //assertArrayEquals(new String[]{"---long=<longField>", "long description"}, row1[0]); assertArrayEquals(new Text[]{ help.ansi().new Text(format("%s---long%s=%s<longField>%s", "@|fg(yellow) ", "|@", "@|italic ", "|@")), help.ansi().new Text("long description")}, row1[0]); OptionSpec option2 = help.options().get(1); Text[][] row2 = renderer.render(option2, parameterRenderer, Help.defaultColorScheme( help.ansi())); assertEquals(1, row2.length); //assertArrayEquals(new String[]{"-b=<otherField>", "other"}, row2[0]); assertArrayEquals(new Text[]{ help.ansi().new Text(format("%s-b%s=%s<otherField>%s", "@|fg(yellow) ", "|@", "@|italic ", "|@")), help.ansi().new Text("other")}, row2[0]); } @Test public void testCreateDefaultOptionRenderer_ReturnsDefaultOptionRenderer() { assertEquals(Help.DefaultOptionRenderer.class, new Help(new UsageDemo()).createDefaultOptionRenderer().getClass()); } @Test public void testDefaultOptionRenderer_rendersShortestOptionNameThenOtherOptionNamesAndDescription() { @Command(showDefaultValues = true) class Example { @Option(names = {"---long", "-L"}, description = "long description") String longField; @Option(names = {"-b", "-a", "--alpha"}, description = "other") String otherField = "abc"; } Help help = new Help(new Example()); Help.IOptionRenderer renderer = help.createDefaultOptionRenderer(); Help.IParamLabelRenderer parameterRenderer = help.createDefaultParamLabelRenderer(); OptionSpec option = help.options().get(0); Text[][] row1 = renderer.render(option, parameterRenderer, help.colorScheme()); assertEquals(1, row1.length); assertArrayEquals(Arrays.toString(row1[0]), textArray(help, "", "-L", ",", "---long=<longField>", "long description"), row1[0]); //assertArrayEquals(Arrays.toString(row1[1]), textArray(help, "", "", "", "", " Default: null"), row1[1]); // #201 don't show null defaults option = help.options().get(1); Text[][] row2 = renderer.render(option, parameterRenderer, help.colorScheme()); assertEquals(2, row2.length); assertArrayEquals(Arrays.toString(row2[0]), textArray(help, "", "-b", ",", "-a, --alpha=<otherField>", "other"), row2[0]); assertArrayEquals(Arrays.toString(row2[1]), textArray(help, "", "", "", "", " Default: abc"), row2[1]); } @Test public void testDefaultOptionRenderer_rendersSpecifiedMarkerForRequiredOptionsWithDefault() { @Command(requiredOptionMarker = '*', showDefaultValues = true) class Example { @Option(names = {"-b", "-a", "--alpha"}, required = true, description = "other") String otherField ="abc"; } Help help = new Help(new Example()); Help.IOptionRenderer renderer = help.createDefaultOptionRenderer(); Help.IParamLabelRenderer parameterRenderer = help.createDefaultParamLabelRenderer(); OptionSpec option = help.options().get(0); Text[][] row = renderer.render(option, parameterRenderer, help.colorScheme()); assertEquals(2, row.length); assertArrayEquals(Arrays.toString(row[0]), textArray(help, "*", "-b", ",", "-a, --alpha=<otherField>", "other"), row[0]); assertArrayEquals(Arrays.toString(row[1]), textArray(help, "", "", "", "", " Default: abc"), row[1]); } @Test public void testDefaultOptionRenderer_rendersSpecifiedMarkerForRequiredOptionsWithoutDefault() { @Command(requiredOptionMarker = '*') class Example { @Option(names = {"-b", "-a", "--alpha"}, required = true, description = "other") String otherField ="abc"; } Help help = new Help(new Example()); Help.IOptionRenderer renderer = help.createDefaultOptionRenderer(); Help.IParamLabelRenderer parameterRenderer = help.createDefaultParamLabelRenderer(); OptionSpec option = help.options().get(0); Text[][] row = renderer.render(option, parameterRenderer, help.colorScheme()); assertEquals(1, row.length); assertArrayEquals(Arrays.toString(row[0]), textArray(help, "*", "-b", ",", "-a, --alpha=<otherField>", "other"), row[0]); } @Test public void testDefaultOptionRenderer_rendersSpacePrefixByDefaultForRequiredOptionsWithoutDefaultValue() { class Example { @Option(names = {"-b", "-a", "--alpha"}, required = true, description = "other") String otherField; } Help help = new Help(new Example()); Help.IOptionRenderer renderer = help.createDefaultOptionRenderer(); Help.IParamLabelRenderer parameterRenderer = help.createDefaultParamLabelRenderer(); OptionSpec option = help.options().get(0); Text[][] row = renderer.render(option, parameterRenderer, help.colorScheme()); assertEquals(1, row.length); assertArrayEquals(Arrays.toString(row[0]), textArray(help, " ", "-b", ",", "-a, --alpha=<otherField>", "other"), row[0]); } @Test public void testDefaultOptionRenderer_rendersSpacePrefixByDefaultForRequiredOptionsWithDefaultValue() { //@Command(showDefaultValues = true) // set programmatically class Example { @Option(names = {"-b", "-a", "--alpha"}, required = true, description = "other") String otherField; } Help help = new Help(new Example()); help.commandSpec().usageMessage().showDefaultValues(true); Help.IOptionRenderer renderer = help.createDefaultOptionRenderer(); Help.IParamLabelRenderer parameterRenderer = help.createDefaultParamLabelRenderer(); OptionSpec option = help.options().get(0); Text[][] row = renderer.render(option, parameterRenderer, help.colorScheme()); assertEquals(1, row.length); assertArrayEquals(Arrays.toString(row[0]), textArray(help, " ", "-b", ",", "-a, --alpha=<otherField>", "other"), row[0]); // assertArrayEquals(Arrays.toString(row[1]), textArray(help, "", "", "", "", " Default: null"), row[1]); // #201 don't show null defaults } @Test public void testDefaultParameterRenderer_rendersSpacePrefixByDefaultForParametersWithPositiveArity() { class Required { @Parameters(description = "required") String required; } Help help = new Help(new Required()); Help.IParameterRenderer renderer = help.createDefaultParameterRenderer(); Help.IParamLabelRenderer parameterRenderer = Help.createMinimalParamLabelRenderer(); PositionalParamSpec param = help.positionalParameters().get(0); Text[][] row1 = renderer.render(param, parameterRenderer, help.colorScheme()); assertEquals(1, row1.length); assertArrayEquals(Arrays.toString(row1[0]), textArray(help, " ", "", "", "<required>", "required"), row1[0]); } @Test public void testDefaultParameterRenderer_rendersSpecifiedMarkerForParametersWithPositiveArity() { @Command(requiredOptionMarker = '*') class Required { @Parameters(description = "required") String required; } Help help = new Help(new Required()); Help.IParameterRenderer renderer = help.createDefaultParameterRenderer(); Help.IParamLabelRenderer parameterRenderer = Help.createMinimalParamLabelRenderer(); PositionalParamSpec param = help.positionalParameters().get(0); Text[][] row1 = renderer.render(param, parameterRenderer, help.colorScheme()); assertEquals(1, row1.length); assertArrayEquals(Arrays.toString(row1[0]), textArray(help, "*", "", "", "<required>", "required"), row1[0]); } @Test public void testDefaultParameterRenderer_rendersSpacePrefixForParametersWithZeroArity() { @Command(requiredOptionMarker = '*') class Optional { @Parameters(arity = "0..1", description = "optional") String optional; } Help help = new Help(new Optional()); Help.IParameterRenderer renderer = help.createDefaultParameterRenderer(); Help.IParamLabelRenderer parameterRenderer = Help.createMinimalParamLabelRenderer(); PositionalParamSpec param = help.positionalParameters().get(0); Text[][] row1 = renderer.render(param, parameterRenderer, help.colorScheme()); assertEquals(1, row1.length); assertArrayEquals(Arrays.toString(row1[0]), textArray(help, "", "", "", "<optional>", "optional"), row1[0]); } @Test public void testDefaultOptionRenderer_rendersCommaOnlyIfBothShortAndLongOptionNamesExist() { class Example { @Option(names = {"-v"}, description = "shortBool") boolean shortBoolean; @Option(names = {"--verbose"}, description = "longBool") boolean longBoolean; @Option(names = {"-x", "--xeno"}, description = "combiBool") boolean combiBoolean; @Option(names = {"-s"}, description = "shortOnly") String shortOnlyField; @Option(names = {"--long"}, description = "longOnly") String longOnlyField; @Option(names = {"-b", "--beta"}, description = "combi") String combiField; } Help help = new Help(new Example()); help.commandSpec().usageMessage().showDefaultValues(false); // omit default values from description column Help.IOptionRenderer renderer = help.createDefaultOptionRenderer(); Help.IParamLabelRenderer parameterRenderer = help.createDefaultParamLabelRenderer(); String[][] expected = new String[][] { {"", "-v", "", "", "shortBool"}, {"", "", "", "--verbose", "longBool"}, {"", "-x", ",", "--xeno", "combiBool"}, {"", "-s", "=", "<shortOnlyField>", "shortOnly"}, {"", "", "", "--long=<longOnlyField>", "longOnly"}, {"", "-b", ",", "--beta=<combiField>", "combi"}, }; int i = -1; for (OptionSpec option : help.options()) { Text[][] row = renderer.render(option, parameterRenderer, help.colorScheme()); assertEquals(1, row.length); assertArrayEquals(Arrays.toString(row[0]), textArray(help, expected[++i]), row[0]); } } @Test public void testDefaultOptionRenderer_omitsDefaultValuesForBooleanFields() { @Command(showDefaultValues = true) class Example { @Option(names = {"-v"}, description = "shortBool") boolean shortBoolean; @Option(names = {"--verbose"}, description = "longBool") Boolean longBoolean; @Option(names = {"-s"}, description = "shortOnly") String shortOnlyField = "short"; @Option(names = {"--long"}, description = "longOnly") String longOnlyField = "long"; @Option(names = {"-b", "--beta"}, description = "combi") int combiField = 123; } Help help = new Help(new Example()); Help.IOptionRenderer renderer = help.createDefaultOptionRenderer(); Help.IParamLabelRenderer parameterRenderer = help.createDefaultParamLabelRenderer(); String[][] expected = new String[][] { {"", "-v", "", "", "shortBool"}, {"", "", "", "--verbose", "longBool"}, {"", "-s", "=", "<shortOnlyField>", "shortOnly"}, {"", "", "", "", "Default: short"}, {"", "", "", "--long=<longOnlyField>", "longOnly"}, {"", "", "", "", "Default: long"}, {"", "-b", ",", "--beta=<combiField>", "combi"}, {"", "", "", "", "Default: 123"}, }; int[] rowCount = {1, 1, 2, 2, 2}; int i = -1; int rowIndex = 0; for (OptionSpec option : help.options()) { Text[][] row = renderer.render(option, parameterRenderer, help.colorScheme()); assertEquals(rowCount[++i], row.length); assertArrayEquals(Arrays.toString(row[0]), textArray(help, expected[rowIndex]), row[0]); rowIndex += rowCount[i]; } } @Test public void testCreateDefaultParameterRenderer_ReturnsDefaultParameterRenderer() { assertEquals(Help.DefaultParamLabelRenderer.class, new Help(new UsageDemo()).createDefaultParamLabelRenderer().getClass()); } @Test public void testDefaultParameterRenderer_showsParamLabelIfPresentOrFieldNameOtherwise() { class Example { @Option(names = "--without" ) String longField; @Option(names = "--with", paramLabel = "LABEL") String otherField; } Help help = new Help(new Example()); Help.IParamLabelRenderer equalSeparatedParameterRenderer = help.createDefaultParamLabelRenderer(); Help help2 = new Help(new Example()); help2.commandSpec().parser().separator(" "); Help.IParamLabelRenderer spaceSeparatedParameterRenderer = help2.createDefaultParamLabelRenderer(); String[] expected = new String[] { "<longField>", "LABEL", }; int i = -1; for (OptionSpec option : help.options()) { i++; Text withSpace = spaceSeparatedParameterRenderer.renderParameterLabel(option, help.ansi(), Collections.<IStyle>emptyList()); assertEquals(withSpace.toString(), " " + expected[i], withSpace.toString()); Text withEquals = equalSeparatedParameterRenderer.renderParameterLabel(option, help.ansi(), Collections.<IStyle>emptyList()); assertEquals(withEquals.toString(), "=" + expected[i], withEquals.toString()); } } @Test public void testDefaultParameterRenderer_appliesToPositionalArgumentsIgnoresSeparator() { class WithLabel { @Parameters(paramLabel = "POSITIONAL_ARGS") String positional; } class WithoutLabel { @Parameters() String positional; } Help withLabel = new Help(new WithLabel()); Help.IParamLabelRenderer equals = withLabel.createDefaultParamLabelRenderer(); withLabel.commandSpec().parser().separator("="); Help.IParamLabelRenderer spaced = withLabel.createDefaultParamLabelRenderer(); Text withSpace = spaced.renderParameterLabel(withLabel.positionalParameters().get(0), withLabel.ansi(), Collections.<IStyle>emptyList()); assertEquals(withSpace.toString(), "POSITIONAL_ARGS", withSpace.toString()); Text withEquals = equals.renderParameterLabel(withLabel.positionalParameters().get(0), withLabel.ansi(), Collections.<IStyle>emptyList()); assertEquals(withEquals.toString(), "POSITIONAL_ARGS", withEquals.toString()); Help withoutLabel = new Help(new WithoutLabel()); withSpace = spaced.renderParameterLabel(withoutLabel.positionalParameters().get(0), withoutLabel.ansi(), Collections.<IStyle>emptyList()); assertEquals(withSpace.toString(), "<positional>", withSpace.toString()); withEquals = equals.renderParameterLabel(withoutLabel.positionalParameters().get(0), withoutLabel.ansi(), Collections.<IStyle>emptyList()); assertEquals(withEquals.toString(), "<positional>", withEquals.toString()); } @Test public void testUsageOptions_hideParamSyntax_on() { class App { @Option(names = "-x1") String single; @Option(names = "-s1", arity = "2") String[] multi; @Option(names = "-x2", hideParamSyntax = true) String singleHide; @Option(names = "-s2", hideParamSyntax = true, arity = "2") String[] multiHide; @Option(names = "-o3", hideParamSyntax = false, split = ",") String[] multiSplit; @Option(names = "-s3", hideParamSyntax = true, split = ",") String[] multiHideSplit; } String actual = new CommandLine(new App()).getUsageMessage(Help.Ansi.OFF); String expected = String.format("" + "Usage: <main class> [-x1=<single>] [-x2=<singleHide>] [-o3=<multiSplit>[,%n" + " <multiSplit>...]]... [-s3=<multiHideSplit>]... [-s1=<multi>%n" + " <multi>]... [-s2=<multiHide>]...%n" + " -o3=<multiSplit>[,<multiSplit>...]%n" + "%n" + " -s1=<multi> <multi>%n" + " -s2=<multiHide>%n" + " -s3=<multiHideSplit>%n" + " -x1=<single>%n" + " -x2=<singleHide>%n"); assertEquals(expected, actual); } @Test public void testUsageParameters_hideParamSyntax_on() { class App { @Parameters() String single; @Parameters(arity = "2") String[] multi; @Parameters(hideParamSyntax = true) String singleHide; @Parameters(hideParamSyntax = true, arity = "2") String[] multiHide; @Parameters(hideParamSyntax = false, split = ",") String[] multiSplit; @Parameters(hideParamSyntax = true, split = ",") String[] multiHideSplit; } String actual = new CommandLine(new App()).getUsageMessage(Help.Ansi.OFF); String expected = String.format("" + "Usage: <main class> [<multiSplit>[,<multiSplit>...]...] <multiHideSplit>%n" + " <single> <singleHide> (<multi> <multi>)... <multiHide>%n" + " [<multiSplit>[,<multiSplit>...]...]%n" + "%n" + " <multiHideSplit>%n" + " <single>%n" + " <singleHide>%n" + " (<multi> <multi>)...%n" + " <multiHide>%n"); assertEquals(expected, actual); } @Test public void testDefaultParameterRenderer_hideParamSyntax_on() { class App { @Parameters(index = "0") String single; @Parameters(index = "1", arity = "2") String[] multi; @Parameters(index = "2", hideParamSyntax = true) String singleHide; @Parameters(index = "3", hideParamSyntax = true, arity = "2") String[] multiHide; @Parameters(index = "4", hideParamSyntax = false, arity = "*", split = ",") String[] multiSplit; @Parameters(index = "5", hideParamSyntax = true, arity = "*", split = ",") String[] multiHideSplit; } Help withLabel = new Help(new App(), Help.Ansi.OFF); withLabel.commandSpec().parser().separator("="); Help.IParamLabelRenderer equals = withLabel.createDefaultParamLabelRenderer(); withLabel.commandSpec().parser().separator(" "); Help.IParamLabelRenderer spaced = withLabel.createDefaultParamLabelRenderer(); String[] expected = new String[] { "<single>", // "<multi> <multi>", // "<singleHide>", // "<multiHide>", // "[<multiSplit>[,<multiSplit>...]...]", // "<multiHideSplit>", // }; for (int i = 0; i < expected.length; i++) { Text withEquals = equals.renderParameterLabel(withLabel.positionalParameters().get(i), withLabel.ansi(), Collections.<IStyle>emptyList()); Text withSpace = spaced.renderParameterLabel(withLabel.positionalParameters().get(i), withLabel.ansi(), Collections.<IStyle>emptyList()); assertEquals(withEquals.toString(), expected[i], withEquals.toString()); assertEquals(withSpace.toString(), expected[i], withSpace.toString()); } } @Test public void testDefaultLayout_addsEachRowToTable() { final Text[][] values = { textArray(Help.Ansi.OFF, "a", "b", "c", "d"), textArray(Help.Ansi.OFF, "1", "2", "3", "4") }; final int[] count = {0}; TextTable tt = TextTable.forDefaultColumns(Help.Ansi.OFF, UsageMessageSpec.DEFAULT_USAGE_WIDTH); tt = new TextTable(Help.Ansi.OFF, tt.columns()) { @Override public void addRowValues(Text[] columnValues) { assertArrayEquals(values[count[0]], columnValues); count[0]++; } }; Help.Layout layout = new Help.Layout(Help.defaultColorScheme(Help.Ansi.OFF), tt); layout.layout(null, values); assertEquals(2, count[0]); } @Test public void testAbreviatedSynopsis_withoutParameters() { @Command(abbreviateSynopsis = true) class App { @Option(names = {"--verbose", "-v"}) boolean verbose; @Option(names = {"--count", "-c"}) int count; @Option(names = {"--help", "-h"}, hidden = true) boolean helpRequested; } Help help = new Help(new App(), Help.Ansi.OFF); assertEquals("<main class> [OPTIONS]" + LINESEP, help.synopsis(0)); } @Test public void testAbreviatedSynopsis_withoutParameters_ANSI() { @Command(abbreviateSynopsis = true) class App { @Option(names = {"--verbose", "-v"}) boolean verbose; @Option(names = {"--count", "-c"}) int count; @Option(names = {"--help", "-h"}, hidden = true) boolean helpRequested; } Help help = new Help(new App(), Help.Ansi.ON); assertEquals(Help.Ansi.ON.new Text("@|bold <main class>|@ [OPTIONS]" + LINESEP).toString(), help.synopsis(0)); } @Test public void testAbreviatedSynopsis_commandNameCustomizableDeclaratively() throws UnsupportedEncodingException { @Command(abbreviateSynopsis = true, name = "aprogram") class App { @Option(names = {"--verbose", "-v"}) boolean verbose; @Option(names = {"--count", "-c"}) int count; @Option(names = {"--help", "-h"}, hidden = true) boolean helpRequested; @Parameters File[] files; } String expected = "" + "Usage: aprogram [OPTIONS] [<files>...]%n" + " [<files>...]%n" + " -c, --count=<count>%n" + " -v, --verbose%n"; String actual = usageString(new CommandLine(new App()), Help.Ansi.OFF); assertEquals(String.format(expected), actual); } @Test public void testAbreviatedSynopsis_commandNameCustomizableProgrammatically() throws UnsupportedEncodingException { @Command(abbreviateSynopsis = true) class App { @Option(names = {"--verbose", "-v"}) boolean verbose; @Option(names = {"--count", "-c"}) int count; @Option(names = {"--help", "-h"}, hidden = true) boolean helpRequested; @Parameters File[] files; } String expected = "" + "Usage: anotherProgram [OPTIONS] [<files>...]%n" + " [<files>...]%n" + " -c, --count=<count>%n" + " -v, --verbose%n"; String actual = usageString(new CommandLine(new App()).setCommandName("anotherProgram"), Help.Ansi.OFF); assertEquals(String.format(expected), actual); } @Test public void testSynopsis_commandNameCustomizableDeclaratively() throws UnsupportedEncodingException { @Command(name = "aprogram") class App { @Option(names = {"--verbose", "-v"}) boolean verbose; @Option(names = {"--count", "-c"}) int count; @Option(names = {"--help", "-h"}, hidden = true) boolean helpRequested; @Parameters File[] files; } String expected = "" + "Usage: aprogram [-v] [-c=<count>] [<files>...]%n" + " [<files>...]%n" + " -c, --count=<count>%n" + " -v, --verbose%n"; String actual = usageString(new CommandLine(new App()), Help.Ansi.OFF); assertEquals(String.format(expected), actual); } @Test public void testSynopsis_commandNameCustomizableProgrammatically() throws UnsupportedEncodingException { class App { @Option(names = {"--verbose", "-v"}) boolean verbose; @Option(names = {"--count", "-c"}) int count; @Option(names = {"--help", "-h"}, hidden = true) boolean helpRequested; @Parameters File[] files; } String expected = "" + "Usage: anotherProgram [-v] [-c=<count>] [<files>...]%n" + " [<files>...]%n" + " -c, --count=<count>%n" + " -v, --verbose%n"; String actual = usageString(new CommandLine(new App()).setCommandName("anotherProgram"), Help.Ansi.OFF); assertEquals(String.format(expected), actual); } @Test public void testSynopsis_optionalOptionArity1_n_withDefaultSeparator() { @Command() class App { @Option(names = {"--verbose", "-v"}) boolean verbose; @Option(names = {"--count", "-c"}, arity = "1..*") int count; @Option(names = {"--help", "-h"}, hidden = true) boolean helpRequested; } Help help = new Help(new App(), Help.Ansi.OFF); assertEquals("<main class> [-v] [-c=<count>...]" + LINESEP, help.synopsis(0)); } @Test public void testSynopsis_optionalOptionArity1_n_withDefaultSeparator_ANSI() { @Command() class App { @Option(names = {"--verbose", "-v"}) boolean verbose; @Option(names = {"--count", "-c"}, arity = "1..*") int count; @Option(names = {"--help", "-h"}, hidden = true) boolean helpRequested; } Help help = new Help(new App(), Help.Ansi.ON); assertEquals(Help.Ansi.ON.new Text("@|bold <main class>|@ [@|yellow -v|@] [@|yellow -c|@=@|italic <count>|@...]" + LINESEP), help.synopsis(0)); } @Test public void testSynopsis_optionalOptionArity0_1_withSpaceSeparator() { @Command(separator = " ") class App { @Option(names = {"--verbose", "-v"}) boolean verbose; @Option(names = {"--count", "-c"}, arity = "0..1") int count; @Option(names = {"--help", "-h"}, hidden = true) boolean helpRequested; } Help help = new Help(new App(), Help.Ansi.OFF); assertEquals("<main class> [-v] [-c [<count>]]" + LINESEP, help.synopsis(0)); } @Test public void testSynopsis_optionalOptionArity0_1_withSpaceSeparator_ANSI() { @Command(separator = " ") class App { @Option(names = {"--verbose", "-v"}) boolean verbose; @Option(names = {"--count", "-c"}, arity = "0..1") int count; @Option(names = {"--help", "-h"}, hidden = true) boolean helpRequested; } Help help = new Help(new App(), Help.Ansi.ON); assertEquals(Help.Ansi.ON.new Text("@|bold <main class>|@ [@|yellow -v|@] [@|yellow -c|@ [@|italic <count>|@]]" + LINESEP), help.synopsis(0)); } @Test public void testSynopsis_requiredOptionWithSeparator() { @Command() class App { @Option(names = {"--verbose", "-v"}) boolean verbose; @Option(names = {"--count", "-c"}, required = true) int count; @Option(names = {"--help", "-h"}, hidden = true) boolean helpRequested; } Help help = new Help(new App(), Help.Ansi.OFF); assertEquals("<main class> [-v] -c=<count>" + LINESEP, help.synopsis(0)); } @Test public void testSynopsis_requiredOptionWithSeparator_ANSI() { @Command() class App { @Option(names = {"--verbose", "-v"}) boolean verbose; @Option(names = {"--count", "-c"}, required = true) int count; @Option(names = {"--help", "-h"}, hidden = true) boolean helpRequested; } Help help = new Help(new App(), Help.Ansi.ON); assertEquals(Help.Ansi.ON.new Text("@|bold <main class>|@ [@|yellow -v|@] @|yellow -c|@=@|italic <count>|@" + LINESEP), help.synopsis(0)); } @Test public void testSynopsis_optionalOption_withSpaceSeparator() { @Command(separator = " ") class App { @Option(names = {"--verbose", "-v"}) boolean verbose; @Option(names = {"--count", "-c"}) int count; @Option(names = {"--help", "-h"}, hidden = true) boolean helpRequested; } Help help = new Help(new App(), Help.Ansi.OFF); assertEquals("<main class> [-v] [-c <count>]" + LINESEP, help.synopsis(0)); } @Test public void testSynopsis_optionalOptionArity0_1__withSeparator() { class App { @Option(names = {"--verbose", "-v"}) boolean verbose; @Option(names = {"--count", "-c"}, arity = "0..1") int count; @Option(names = {"--help", "-h"}, hidden = true) boolean helpRequested; } Help help = new Help(new App(), Help.Ansi.OFF); assertEquals("<main class> [-v] [-c[=<count>]]" + LINESEP, help.synopsis(0)); } @Test public void testSynopsis_optionalOptionArity0_n__withSeparator() { @Command(separator = "=") class App { @Option(names = {"--verbose", "-v"}) boolean verbose; @Option(names = {"--count", "-c"}, arity = "0..*") int count; @Option(names = {"--help", "-h"}, hidden = true) boolean helpRequested; } Help help = new Help(new App(), Help.Ansi.OFF); // NOTE Expected :<main class> [-v] [-c[=<count>]...] but arity=0 for int field is weird anyway... assertEquals("<main class> [-v] [-c[=<count>...]]" + LINESEP, help.synopsis(0)); } @Test public void testSynopsis_optionalOptionArity1_n__withSeparator() { @Command(separator = "=") class App { @Option(names = {"--verbose", "-v"}) boolean verbose; @Option(names = {"--count", "-c"}, arity = "1..*") int count; @Option(names = {"--help", "-h"}, hidden = true) boolean helpRequested; } Help help = new Help(new App(), Help.Ansi.OFF); assertEquals("<main class> [-v] [-c=<count>...]" + LINESEP, help.synopsis(0)); } @Test public void testSynopsis_withProgrammaticallySetSeparator_withParameters() throws UnsupportedEncodingException { class App { @Option(names = {"--verbose", "-v"}) boolean verbose; @Option(names = {"--count", "-c"}) int count; @Option(names = {"--help", "-h"}, hidden = true) boolean helpRequested; @Parameters File[] files; } CommandLine commandLine = new CommandLine(new App()).setSeparator(":"); String actual = usageString(commandLine, Help.Ansi.OFF); String expected = "" + "Usage: <main class> [-v] [-c:<count>] [<files>...]%n" + " [<files>...]%n" + " -c, --count:<count>%n" + " -v, --verbose%n"; assertEquals(String.format(expected), actual); } @Test public void testSynopsis_clustersBooleanOptions() { @Command(separator = "=") class App { @Option(names = {"--verbose", "-v"}) boolean verbose; @Option(names = {"--aaaa", "-a"}) boolean aBoolean; @Option(names = {"--xxxx", "-x"}) Boolean xBoolean; @Option(names = {"--count", "-c"}, paramLabel = "COUNT") int count; } Help help = new Help(new App(), Help.Ansi.OFF); assertEquals("<main class> [-avx] [-c=COUNT]" + LINESEP, help.synopsis(0)); } @Test public void testSynopsis_clustersRequiredBooleanOptions() { @Command(separator = "=") class App { @Option(names = {"--verbose", "-v"}, required = true) boolean verbose; @Option(names = {"--aaaa", "-a"}, required = true) boolean aBoolean; @Option(names = {"--xxxx", "-x"}, required = true) Boolean xBoolean; @Option(names = {"--count", "-c"}, paramLabel = "COUNT") int count; } Help help = new Help(new App(), Help.Ansi.OFF); assertEquals("<main class> -avx [-c=COUNT]" + LINESEP, help.synopsis(0)); } @Test public void testCustomSynopsis() { @Command(customSynopsis = { "<the-app> --number=NUMBER --other-option=<aargh>", " --more=OTHER --and-other-option=<aargh>", "<the-app> --number=NUMBER --and-other-option=<aargh>", }) class App {@Option(names = "--ignored") boolean ignored;} Help help = new Help(new App(), Help.Ansi.OFF); assertEquals(String.format( "<the-app> --number=NUMBER --other-option=<aargh>%n" + " --more=OTHER --and-other-option=<aargh>%n" + "<the-app> --number=NUMBER --and-other-option=<aargh>%n"), help.synopsis(0)); } @Test public void testTextTable() { TextTable table = TextTable.forDefaultColumns(Help.Ansi.OFF, UsageMessageSpec.DEFAULT_USAGE_WIDTH); table.addRowValues(textArray(Help.Ansi.OFF, "", "-v", ",", "--verbose", "show what you're doing while you are doing it")); table.addRowValues(textArray(Help.Ansi.OFF, "", "-p", null, null, "the quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog.")); assertEquals(String.format( " -v, --verbose show what you're doing while you are doing it%n" + " -p the quick brown fox jumped over the lazy dog. The%n" + " quick brown fox jumped over the lazy dog.%n" ,""), table.toString(new StringBuilder()).toString()); } @Test(expected = IllegalArgumentException.class) public void testTextTableAddsNewRowWhenTooManyValuesSpecified() { TextTable table = TextTable.forDefaultColumns(Help.Ansi.OFF, UsageMessageSpec.DEFAULT_USAGE_WIDTH); table.addRowValues(textArray(Help.Ansi.OFF, "", "-c", ",", "--create", "description", "INVALID", "Row 3")); // assertEquals(String.format("" + // " -c, --create description %n" + // " INVALID %n" + // " Row 3 %n" // ,""), table.toString(new StringBuilder()).toString()); } @Test public void testTextTableAddsNewRowWhenAnyColumnTooLong() { TextTable table = TextTable.forDefaultColumns(Help.Ansi.OFF, UsageMessageSpec.DEFAULT_USAGE_WIDTH); table.addRowValues("*", "-c", ",", "--create, --create2, --create3, --create4, --create5, --create6, --create7, --create8", "description"); assertEquals(String.format("" + "* -c, --create, --create2, --create3, --create4, --create5, --create6,%n" + " --create7, --create8%n" + " description%n" ,""), table.toString(new StringBuilder()).toString()); table = TextTable.forDefaultColumns(Help.Ansi.OFF, UsageMessageSpec.DEFAULT_USAGE_WIDTH); table.addRowValues("", "-c", ",", "--create, --create2, --create3, --create4, --create5, --create6, --createAA7, --create8", "description"); assertEquals(String.format("" + " -c, --create, --create2, --create3, --create4, --create5, --create6,%n" + " --createAA7, --create8%n" + " description%n" ,""), table.toString(new StringBuilder()).toString()); } @Test public void testCatUsageFormat() { @Command(name = "cat", customSynopsis = "cat [OPTIONS] [FILE...]", description = "Concatenate FILE(s), or standard input, to standard output.", footer = "Copyright(c) 2017") class Cat { @Parameters(paramLabel = "FILE", hidden = true, description = "Files whose contents to display") List<File> files; @Option(names = "--help", help = true, description = "display this help and exit") boolean help; @Option(names = "--version", help = true, description = "output version information and exit") boolean version; @Option(names = "-u", description = "(ignored)") boolean u; @Option(names = "-t", description = "equivalent to -vT") boolean t; @Option(names = "-e", description = "equivalent to -vET") boolean e; @Option(names = {"-A", "--show-all"}, description = "equivalent to -vET") boolean showAll; @Option(names = {"-s", "--squeeze-blank"}, description = "suppress repeated empty output lines") boolean squeeze; @Option(names = {"-v", "--show-nonprinting"}, description = "use ^ and M- notation, except for LDF and TAB") boolean v; @Option(names = {"-b", "--number-nonblank"}, description = "number nonempty output lines, overrides -n") boolean b; @Option(names = {"-T", "--show-tabs"}, description = "display TAB characters as ^I") boolean T; @Option(names = {"-E", "--show-ends"}, description = "display $ at end of each line") boolean E; @Option(names = {"-n", "--number"}, description = "number all output lines") boolean n; } ByteArrayOutputStream baos = new ByteArrayOutputStream(); CommandLine.usage(new Cat(), new PrintStream(baos), Help.Ansi.OFF); String expected = String.format( "Usage: cat [OPTIONS] [FILE...]%n" + "Concatenate FILE(s), or standard input, to standard output.%n" + " -A, --show-all equivalent to -vET%n" + " -b, --number-nonblank number nonempty output lines, overrides -n%n" + " -e equivalent to -vET%n" + " -E, --show-ends display $ at end of each line%n" + " -n, --number number all output lines%n" + " -s, --squeeze-blank suppress repeated empty output lines%n" + " -t equivalent to -vT%n" + " -T, --show-tabs display TAB characters as ^I%n" + " -u (ignored)%n" + " -v, --show-nonprinting use ^ and M- notation, except for LDF and TAB%n" + " --help display this help and exit%n" + " --version output version information and exit%n" + "Copyright(c) 2017%n", ""); assertEquals(expected, baos.toString()); } @Test public void testZipUsageFormat() { String expected = String.format("" + "Copyright (c) 1990-2008 Info-ZIP - Type 'zip \"-L\"' for software license.%n" + "Zip 3.0 (July 5th 2008). Command:%n" + "zip [-options] [-b path] [-t mmddyyyy] [-n suffixes] [zipfile list] [-xi list]%n" + " The default action is to add or replace zipfile entries from list, which%n" + " can include the special name - to compress standard input.%n" + " If zipfile and list are omitted, zip compresses stdin to stdout.%n" + " -f freshen: only changed files -u update: only changed or new files%n" + " -d delete entries in zipfile -m move into zipfile (delete OS files)%n" + " -r recurse into directories -j junk (don't record) directory names%n" + " -0 store only -l convert LF to CR LF (-ll CR LF to LF)%n" + " -1 compress faster -9 compress better%n" + " -q quiet operation -v verbose operation/print version info%n" + " -c add one-line comments -z add zipfile comment%n" + " -@ read names from stdin -o make zipfile as old as latest entry%n" + " -x exclude the following names -i include only the following names%n" + " -F fix zipfile (-FF try harder) -D do not add directory entries%n" + " -A adjust self-extracting exe -J junk zipfile prefix (unzipsfx)%n" + " -T test zipfile integrity -X eXclude eXtra file attributes%n" + " -y store symbolic links as the link instead of the referenced file%n" + " -e encrypt -n don't compress these suffixes%n" + " -h2 show more help%n"); assertEquals(expected, CustomLayoutDemo.createZipUsageFormat(Help.Ansi.OFF)); } @Test public void testNetstatUsageFormat() { String expected = String.format("" + "Displays protocol statistics and current TCP/IP network connections.%n" + "%n" + "NETSTAT [-a] [-b] [-e] [-f] [-n] [-o] [-p proto] [-q] [-r] [-s] [-t] [-x] [-y]%n" + " [interval]%n" + "%n" + " -a Displays all connections and listening ports.%n" + " -b Displays the executable involved in creating each connection or%n" + " listening port. In some cases well-known executables host%n" + " multiple independent components, and in these cases the%n" + " sequence of components involved in creating the connection or%n" + " listening port is displayed. In this case the executable name%n" + " is in [] at the bottom, on top is the component it called, and%n" + " so forth until TCP/IP was reached. Note that this option can be%n" + " time-consuming and will fail unless you have sufficient%n" + " permissions.%n" + " -e Displays Ethernet statistics. This may be combined with the -s%n" + " option.%n" + " -f Displays Fully Qualified Domain Names (FQDN) for foreign%n" + " addresses.%n" + " -n Displays addresses and port numbers in numerical form.%n" + " -o Displays the owning process ID associated with each connection.%n" + " -p proto Shows connections for the protocol specified by proto; proto%n" + " may be any of: TCP, UDP, TCPv6, or UDPv6. If used with the -s%n" + " option to display per-protocol statistics, proto may be any of:%n" + " IP, IPv6, ICMP, ICMPv6, TCP, TCPv6, UDP, or UDPv6.%n" + " -q Displays all connections, listening ports, and bound%n" + " nonlistening TCP ports. Bound nonlistening ports may or may not%n" + " be associated with an active connection.%n" + " -r Displays the routing table.%n" + " -s Displays per-protocol statistics. By default, statistics are%n" + " shown for IP, IPv6, ICMP, ICMPv6, TCP, TCPv6, UDP, and UDPv6;%n" + " the -p option may be used to specify a subset of the default.%n" + " -t Displays the current connection offload state.%n" + " -x Displays NetworkDirect connections, listeners, and shared%n" + " endpoints.%n" + " -y Displays the TCP connection template for all connections.%n" + " Cannot be combined with the other options.%n" + " interval Redisplays selected statistics, pausing interval seconds%n" + " between each display. Press CTRL+C to stop redisplaying%n" + " statistics. If omitted, netstat will print the current%n" + " configuration information once.%n" , ""); assertEquals(expected, CustomLayoutDemo.createNetstatUsageFormat(Help.Ansi.OFF)); } @Test public void testUsageIndexedPositionalParameters() throws UnsupportedEncodingException { @Command() class App { @Parameters(index = "0", description = "source host") InetAddress host1; @Parameters(index = "1", description = "source port") int port1; @Parameters(index = "2", description = "destination host") InetAddress host2; @Parameters(index = "3", arity = "1..2", description = "destination port range") int[] port2range; @Parameters(index = "4..*", description = "files to transfer") String[] files; @Parameters(hidden = true) String[] all; } String actual = usageString(new App(), Help.Ansi.OFF); String expected = String.format( "Usage: <main class> <host1> <port1> <host2> <port2range> [<port2range>]%n" + " [<files>...]%n" + " <host1> source host%n" + " <port1> source port%n" + " <host2> destination host%n" + " <port2range> [<port2range>]%n" + " destination port range%n" + " [<files>...] files to transfer%n" ); assertEquals(expected, actual); } @Command(name = "base", abbreviateSynopsis = true, commandListHeading = "c o m m a n d s", customSynopsis = "cust", description = "base description", descriptionHeading = "base descr heading", footer = "base footer", footerHeading = "base footer heading", header = "base header", headerHeading = "base header heading", optionListHeading = "base option heading", parameterListHeading = "base param heading", requiredOptionMarker = '&', separator = ";", showDefaultValues = true, sortOptions = false, synopsisHeading = "abcd") class Base { } @Test public void testAttributesInheritedWhenSubclassingForReuse() throws UnsupportedEncodingException { @Command class EmptySub extends Base {} Help help = new Help(new EmptySub()); assertEquals("base", help.commandName()); assertEquals(String.format("cust%n"), help.synopsis(0)); assertEquals(String.format("cust%n"), help.customSynopsis()); assertEquals(String.format("base%n"), help.abbreviatedSynopsis()); assertEquals(String.format("base%n"), help.detailedSynopsis(0,null, true)); assertEquals("abcd", help.synopsisHeading()); assertEquals("", help.commandList()); assertEquals("", help.commandListHeading()); assertEquals("c o m m a n d s", help.commandSpec().usageMessage().commandListHeading()); assertEquals(String.format("base description%n"), help.description()); assertEquals("base descr heading", help.descriptionHeading()); assertEquals(String.format("base footer%n"), help.footer()); assertEquals("base footer heading", help.footerHeading()); assertEquals(String.format("base header%n"), help.header()); assertEquals("base header heading", help.headerHeading()); assertEquals("", help.optionList()); assertEquals("", help.optionListHeading()); assertEquals("base option heading", help.commandSpec().usageMessage().optionListHeading()); assertEquals("", help.parameterList()); assertEquals("", help.parameterListHeading()); assertEquals("base param heading", help.commandSpec().usageMessage().parameterListHeading()); assertEquals(";", help.commandSpec().parser().separator()); assertEquals('&', help.commandSpec().usageMessage().requiredOptionMarker()); assertTrue(help.commandSpec().usageMessage().abbreviateSynopsis()); assertTrue(help.commandSpec().usageMessage().showDefaultValues()); assertFalse(help.commandSpec().usageMessage().sortOptions()); } @Test public void testSubclassAttributesOverrideEmptySuper() { @Command class EmptyBase {} @Command(name = "base", abbreviateSynopsis = true, commandListHeading = "c o m m a n d s", customSynopsis = "cust", description = "base description", descriptionHeading = "base descr heading", footer = "base footer", footerHeading = "base footer heading", header = "base header", headerHeading = "base header heading", optionListHeading = "base option heading", parameterListHeading = "base param heading", requiredOptionMarker = '&', separator = ";", showDefaultValues = true, sortOptions = false, synopsisHeading = "abcd", subcommands = Sub.class) class FullBase extends EmptyBase{ } Help help = new Help(new FullBase()); assertEquals("base", help.commandName()); assertEquals(String.format("cust%n"), help.synopsis(0)); assertEquals(String.format("cust%n"), help.customSynopsis()); assertEquals(String.format("base [COMMAND]%n"), help.abbreviatedSynopsis()); assertEquals(String.format("base [COMMAND]%n"), help.detailedSynopsis(0, null, true)); assertEquals("abcd", help.synopsisHeading()); assertEquals(String.format(" sub This is a subcommand%n"), help.commandList()); assertEquals("c o m m a n d s", help.commandListHeading()); assertEquals(String.format("base description%n"), help.description()); assertEquals("base descr heading", help.descriptionHeading()); assertEquals(String.format("base footer%n"), help.footer()); assertEquals("base footer heading", help.footerHeading()); assertEquals(String.format("base header%n"), help.header()); assertEquals("base header heading", help.headerHeading()); assertEquals("", help.optionList()); assertEquals("base option heading", help.commandSpec().usageMessage().optionListHeading()); assertEquals("", help.optionListHeading()); // because no options assertEquals("", help.parameterList()); assertEquals("base param heading", help.commandSpec().usageMessage().parameterListHeading()); assertEquals("", help.parameterListHeading()); // because no parameters assertTrue(help.commandSpec().usageMessage().abbreviateSynopsis()); assertTrue(help.commandSpec().usageMessage().showDefaultValues()); assertFalse(help.commandSpec().usageMessage().sortOptions()); assertEquals(";", help.commandSpec().parser().separator()); assertEquals('&', help.commandSpec().usageMessage().requiredOptionMarker()); } @Test public void testSubclassAttributesOverrideSuperValues() { @Command(name = "sub", abbreviateSynopsis = false, commandListHeading = "subc o m m a n d s", customSynopsis = "subcust", description = "sub description", descriptionHeading = "sub descr heading", footer = "sub footer", footerHeading = "sub footer heading", header = "sub header", headerHeading = "sub header heading", optionListHeading = "sub option heading", parameterListHeading = "sub param heading", requiredOptionMarker = '%', separator = ":", showDefaultValues = false, sortOptions = true, synopsisHeading = "xyz") class FullSub extends Base{ } Help help = new Help(new FullSub()); assertEquals("sub", help.commandName()); assertEquals(String.format("subcust%n"), help.synopsis(0)); assertEquals(String.format("subcust%n"), help.customSynopsis()); assertEquals(String.format("sub%n"), help.abbreviatedSynopsis()); assertEquals(String.format("sub%n"), help.detailedSynopsis(0,null, true)); assertEquals("xyz", help.synopsisHeading()); assertEquals("", help.commandList()); assertEquals("", help.commandListHeading()); // empty: no commands assertEquals("subc o m m a n d s", help.commandSpec().usageMessage().commandListHeading()); assertEquals(String.format("sub description%n"), help.description()); assertEquals("sub descr heading", help.descriptionHeading()); assertEquals(String.format("sub footer%n"), help.footer()); assertEquals("sub footer heading", help.footerHeading()); assertEquals(String.format("sub header%n"), help.header()); assertEquals("sub header heading", help.headerHeading()); assertEquals("", help.optionList()); assertEquals("", help.optionListHeading()); assertEquals("sub option heading", help.commandSpec().usageMessage().optionListHeading()); assertEquals("", help.parameterList()); assertEquals("", help.parameterListHeading()); assertEquals("sub param heading", help.commandSpec().usageMessage().parameterListHeading()); assertTrue(help.commandSpec().usageMessage().abbreviateSynopsis()); assertTrue(help.commandSpec().usageMessage().showDefaultValues()); assertFalse(help.commandSpec().usageMessage().sortOptions()); assertEquals(":", help.commandSpec().parser().separator()); assertEquals('%', help.commandSpec().usageMessage().requiredOptionMarker()); } static class UsageDemo { @Option(names = "-a", description = "boolean option with short name only") boolean a; @Option(names = "-b", paramLabel = "INT", description = "short option with a parameter") int b; @Option(names = {"-c", "--c-option"}, description = "boolean option with short and long name") boolean c; @Option(names = {"-d", "--d-option"}, paramLabel = "FILE", description = "option with parameter and short and long name") File d; @Option(names = "--e-option", description = "boolean option with only a long name") boolean e; @Option(names = "--f-option", paramLabel = "STRING", description = "option with parameter and only a long name") String f; @Option(names = {"-g", "--g-option-with-a-name-so-long-that-it-runs-into-the-descriptions-column"}, description = "boolean option with short and long name") boolean g; @Parameters(index = "0", paramLabel = "0BLAH", description = "first parameter") String param0; @Parameters(index = "1", paramLabel = "1PARAMETER-with-a-name-so-long-that-it-runs-into-the-descriptions-column", description = "2nd parameter") String param1; @Parameters(index = "2..*", paramLabel = "remaining", description = "remaining parameters") String param2_n; @Parameters(index = "*", paramLabel = "all", description = "all parameters") String param_n; } @Test public void testSubclassedCommandHelp() { @Command(name = "parent", description = "parent description") class ParentOption { } @Command(name = "child", description = "child description") class ChildOption extends ParentOption { } String actual = usageString(new ChildOption(), Help.Ansi.OFF); assertEquals(String.format( "Usage: child%n" + "child description%n"), actual); } @Test public void testSynopsisOrderCorrectWhenParametersDeclaredOutOfOrder() { class WithParams { @Parameters(index = "1") String param1; @Parameters(index = "0") String param0; } Help help = new Help(new WithParams()); assertEquals(format("<main class> <param0> <param1>%n"), help.synopsis(0)); } @Test public void testSynopsisOrderCorrectWhenSubClassAddsParameters() { class BaseWithParams { @Parameters(index = "1") String param1; @Parameters(index = "0") String param0; } class SubWithParams extends BaseWithParams { @Parameters(index = "3") String param3; @Parameters(index = "2") String param2; } Help help = new Help(new SubWithParams()); assertEquals(format("<main class> <param0> <param1> <param2> <param3>%n"), help.synopsis(0)); } @Test public void testUsageNestedSubcommand() throws IOException { @Command(name = "main") class MainCommand { @Option(names = "-a") boolean a; @Option(names = "-h", help = true) boolean h;} @Command(name = "cmd1") class ChildCommand1 { @Option(names = "-b") boolean b; } @Command(name = "cmd2") class ChildCommand2 { @Option(names = "-c") boolean c; @Option(names = "-h", help = true) boolean h;} @Command(name = "sub11") class GrandChild1Command1 { @Option(names = "-d") boolean d; } @Command(name = "sub12") class GrandChild1Command2 { @Option(names = "-e") int e; } @Command(name = "sub21") class GrandChild2Command1 { @Option(names = "-h", help = true) boolean h; } @Command(name = "sub22") class GrandChild2Command2 { @Option(names = "-g") boolean g; } @Command(name = "sub22sub1") class GreatGrandChild2Command2_1 { @Option(names = "-h", help = true) boolean h; @Option(names = {"-t", "--type"}) String customType; } CommandLine commandLine = new CommandLine(new MainCommand()); commandLine .addSubcommand("cmd1", new CommandLine(new ChildCommand1()) .addSubcommand("sub11", new GrandChild1Command1()) .addSubcommand("sub12", new GrandChild1Command2()) ) .addSubcommand("cmd2", new CommandLine(new ChildCommand2()) .addSubcommand("sub21", new GrandChild2Command1()) .addSubcommand("sub22", new CommandLine(new GrandChild2Command2()) .addSubcommand("sub22sub1", new GreatGrandChild2Command2_1()) ) ); String main = usageString(commandLine, Help.Ansi.OFF); assertEquals(String.format("" + "Usage: main [-ah] [COMMAND]%n" + " -a%n" + " -h%n" + "Commands:%n" + " cmd1%n" + " cmd2%n"), main); String cmd2 = usageString(commandLine.getSubcommands().get("cmd2"), Help.Ansi.OFF); assertEquals(String.format("" + "Usage: main cmd2 [-ch] [COMMAND]%n" + " -c%n" + " -h%n" + "Commands:%n" + " sub21%n" + " sub22%n"), cmd2); String sub22 = usageString(commandLine.getSubcommands().get("cmd2").getSubcommands().get("sub22"), Help.Ansi.OFF); assertEquals(String.format("" + "Usage: main cmd2 sub22 [-g] [COMMAND]%n" + " -g%n" + "Commands:%n" + " sub22sub1%n"), sub22); } @Test public void testLayoutConstructorCreatesDefaultColumns() { ColorScheme colorScheme = new ColorScheme.Builder().build(); Help.Layout layout = new Help.Layout(colorScheme, 99); TextTable expected = TextTable.forDefaultColumns(Help.Ansi.OFF, 99); assertEquals(expected.columns().length, layout.table.columns().length); for (int i = 0; i < expected.columns().length; i++) { assertEquals(expected.columns()[i].indent, layout.table.columns()[i].indent); assertEquals(expected.columns()[i].width, layout.table.columns()[i].width); assertEquals(expected.columns()[i].overflow, layout.table.columns()[i].overflow); } } @Test public void testHelpCreateLayout_CreatesDefaultColumns() { Help help = new Help(CommandSpec.create(), new ColorScheme.Builder(Help.Ansi.OFF).build()); Help.Layout layout = help.createDefaultLayout(); int[] widthsForNoOptions = {2, 2, 1, 3, 72}; TextTable expected = TextTable.forDefaultColumns(Help.Ansi.OFF, 80); assertEquals(expected.columns().length, layout.table.columns().length); for (int i = 0; i < expected.columns().length; i++) { assertEquals(expected.columns()[i].indent, layout.table.columns()[i].indent); assertEquals(widthsForNoOptions[i], layout.table.columns()[i].width); assertEquals(expected.columns()[i].overflow, layout.table.columns()[i].overflow); } } @Test public void testMinimalParameterLabelRenderer() { Help.IParamLabelRenderer renderer = Help.createMinimalParamLabelRenderer(); assertEquals("", renderer.separator()); } @Test public void testMinimalOptionRenderer() { Help.MinimalOptionRenderer renderer = new Help.MinimalOptionRenderer(); Text[][] texts = renderer.render(OptionSpec.builder("-x").build(), Help.createMinimalParamLabelRenderer(), new ColorScheme.Builder().build()); assertEquals("", texts[0][1].plainString()); } @Test public void testMinimalParameterRenderer() { Help.MinimalParameterRenderer renderer = new Help.MinimalParameterRenderer(); Text[][] texts = renderer.render(PositionalParamSpec.builder().build(), Help.createMinimalParamLabelRenderer(), new ColorScheme.Builder().build()); assertEquals("", texts[0][1].plainString()); } @Test public void testTextTableConstructorRequiresAtLeastOneColumn() { try { new TextTable(Help.Ansi.OFF, new Help.Column[0]); } catch (IllegalArgumentException ex) { assertEquals("At least one column is required", ex.getMessage()); } } @Test public void testTextTablePutValue_DisallowsInvalidRowIndex() { TextTable tt = new TextTable(Help.Ansi.OFF, new Help.Column[] {new Help.Column(30, 2, Help.Column.Overflow.SPAN)}); try { tt.putValue(1, 0, Help.Ansi.OFF.text("abc")); } catch (IllegalArgumentException ex) { assertEquals("Cannot write to row 1: rowCount=0", ex.getMessage()); } } @Test public void testTextTablePutValue_NullOrEmpty() { TextTable tt = new TextTable(Help.Ansi.OFF, new Help.Column[] {new Help.Column(30, 2, Help.Column.Overflow.SPAN)}); tt.addEmptyRow(); TextTable.Cell cell00 = tt.putValue(0, 0, null); assertEquals(0, cell00.column); assertEquals(0, cell00.row); TextTable.Cell other00 = tt.putValue(0, 0, Help.Ansi.EMPTY_TEXT); assertEquals(0, other00.column); assertEquals(0, other00.row); } @Test public void testTextTableAddRowValues() { TextTable tt = new TextTable(Help.Ansi.OFF, new Help.Column[] {new Help.Column(30, 2, Help.Column.Overflow.SPAN)}); tt.addRowValues(new String[] {null}); assertEquals(Help.Ansi.EMPTY_TEXT, tt.textAt(0, 0)); } @SuppressWarnings("deprecation") @Test public void testTextTableCellAt() { TextTable tt = new TextTable(Help.Ansi.OFF, new Help.Column[] {new Help.Column(30, 2, Help.Column.Overflow.SPAN)}); tt.addRowValues(new String[] {null}); assertEquals(Help.Ansi.EMPTY_TEXT, tt.cellAt(0, 0)); } @Test public void testJoin() throws Exception { Method m = Help.class.getDeclaredMethod("join", String[].class, int.class, int.class, String.class); m.setAccessible(true); String result = (String) m.invoke(null, (String[]) null, 0, 0, "abc"); assertEquals("", result); } @Test public void testFormat() throws Exception { Method m = CommandLine.class.getDeclaredMethod("format", String.class, Object[].class); m.setAccessible(true); String result = (String) m.invoke(null, (String) null, new Object[]{"abc"}); assertEquals("", result); } @Test @Deprecated public void testJoin2Deprecated() { StringBuilder sb = Help.join(Help.Ansi.OFF, 80, null, new StringBuilder("abc")); assertEquals("abc", sb.toString()); } @Test public void testJoin2() { StringBuilder sb = Help.join(Help.Ansi.OFF, 80, true,null, new StringBuilder("abc")); assertEquals("abc", sb.toString()); } @Test public void testCountTrailingSpaces() throws Exception { Method m = Help.class.getDeclaredMethod("countTrailingSpaces", String.class); m.setAccessible(true); int result = (Integer) m.invoke(null, (String) null); assertEquals(0, result); } @Test public void testHeading() throws Exception { Method m = Help.class.getDeclaredMethod("heading", Help.Ansi.class, int.class, boolean.class, String.class, Object[].class); m.setAccessible(true); String result = (String) m.invoke(null, Help.Ansi.OFF, 80, true, "\r\n", new Object[0]); assertEquals(String.format("%n"), result); String result2 = (String) m.invoke(null, Help.Ansi.OFF, 80, false, "boom", new Object[0]); assertEquals(String.format("boom"), result2); String result3 = (String) m.invoke(null, Help.Ansi.OFF, 80, true, null, new Object[0]); assertEquals("", result3); } @Test public void trimTrailingLineSeparator() { assertEquals("abc", Help.trimLineSeparator("abc")); String lineSep = System.getProperty("line.separator"); assertEquals("abc", Help.trimLineSeparator("abc" + lineSep)); assertEquals("abc" + lineSep, Help.trimLineSeparator("abc" + lineSep + lineSep)); } @Test public void testHelpCreateDetailedSynopsisOptionsText() { Help help = new Help(CommandSpec.create().addOption(OptionSpec.builder("xx").build()), new ColorScheme.Builder(Help.Ansi.OFF).build()); Text text = help.createDetailedSynopsisOptionsText(new ArrayList<ArgSpec>(), null, true); assertEquals(" [xx]", text.toString()); } @Test public void testAddAllSubcommands() { Help help = new Help(CommandSpec.create(), new ColorScheme.Builder(Help.Ansi.OFF).build()); help.addAllSubcommands(null); assertTrue(help.subcommands().isEmpty()); } @SuppressWarnings("deprecation") @Test public void testDetailedSynopsis() { Help help = new Help(CommandSpec.create(), new ColorScheme.Builder(Help.Ansi.OFF).build()); String str = help.detailedSynopsis(new Help.SortByShortestOptionNameAlphabetically(), true); assertEquals(String.format("<main class>%n"), str); } @Test public void testCreateDescriptionFirstLines() throws Exception { Method m = Help.class.getDeclaredMethod("createDescriptionFirstLines", Help.ColorScheme.class, Model.ArgSpec.class, String[].class, boolean[].class); m.setAccessible(true); String[][] input = new String[][] { new String[0], new String[] {""}, new String[] {"a", "b", "c"} }; Help.Ansi.Text[][] expectedOutput = new Help.Ansi.Text[][] { new Help.Ansi.Text[] {Help.Ansi.OFF.text("")}, new Help.Ansi.Text[] {Help.Ansi.OFF.text("")}, new Help.Ansi.Text[] {Help.Ansi.OFF.text("a"), Help.Ansi.OFF.text("b"), Help.Ansi.OFF.text("c")} }; for (int i = 0; i < input.length; i++) { String[] description = input[i]; Help.Ansi.Text[] result = (Help.Ansi.Text[]) m.invoke(null, new ColorScheme.Builder(Help.Ansi.OFF).build(), null, description, new boolean[3]); Help.Ansi.Text[] expected = expectedOutput[i]; for (int j = 0; j < result.length; j++) { assertEquals(expected[j], result[j]); } } } @Test public void testAbbreviatedSynopsis() { CommandSpec spec = CommandSpec.create(); spec.addPositional(PositionalParamSpec.builder().paramLabel("a").hidden(true).build()); spec.addPositional(PositionalParamSpec.builder().paramLabel("b").build()); Help help = new Help(spec, new ColorScheme.Builder(Help.Ansi.OFF).build()); String actual = help.abbreviatedSynopsis(); assertEquals(String.format("<main class> b...%n"), actual); } @SuppressWarnings("deprecation") @Test public void testSynopsis() { Help help = new Help(CommandSpec.create(), new ColorScheme.Builder(Help.Ansi.OFF).build()); String actual = help.synopsis(); assertEquals(String.format("<main class>%n"), actual); } @SuppressWarnings("deprecation") @Test public void testAddSubcommand() { @Command(name = "app", mixinStandardHelpOptions = true) class App { } Help help = new Help(new CommandLine(CommandSpec.create()).getCommandSpec(), new ColorScheme.Builder(Help.Ansi.OFF).build()); help.addSubcommand("boo", new App()); assertEquals(1, help.subcommands().size()); assertEquals("app", help.subcommands().get("boo").commandSpec().name()); } @Test public void testEmbeddedNewLinesInUsageSections() throws UnsupportedEncodingException { @Command(description = "first line\nsecond line\nthird line", headerHeading = "headerHeading1\nheaderHeading2", header = "header1\nheader2", descriptionHeading = "descriptionHeading1\ndescriptionHeading2", footerHeading = "footerHeading1\nfooterHeading2", footer = "footer1\nfooter2") class App { @Option(names = {"-v", "--verbose"}, description = "optionDescription1\noptionDescription2") boolean v; @Parameters(description = "paramDescription1\nparamDescription2") String file; } String actual = usageString(new App(), Help.Ansi.OFF); String expected = String.format("" + "headerHeading1%n" + "headerHeading2header1%n" + "header2%n" + "Usage: <main class> [-v] <file>%n" + "descriptionHeading1%n" + "descriptionHeading2first line%n" + "second line%n" + "third line%n" + " <file> paramDescription1%n" + " paramDescription2%n" + " -v, --verbose optionDescription1%n" + " optionDescription2%n" + "footerHeading1%n" + "footerHeading2footer1%n" + "footer2%n"); assertEquals(expected, actual); } @Test public void testRepeatingGroup() { class App { @Parameters(arity = "2", description = "description") String[] twoArgs; } String actual = usageString(new App(), Help.Ansi.OFF); String expected = String.format("" + "Usage: <main class> (<twoArgs> <twoArgs>)...%n" + " (<twoArgs> <twoArgs>)...%n" + " description%n"); assertEquals(expected, actual); } @Test public void testMapFieldHelp_with_unlimitedSplit() { class App { @Parameters(arity = "2", split = "\\|", paramLabel = "FIXTAG=VALUE", description = "Repeating group of two lists of vertical bar '|'-separated FIXTAG=VALUE pairs.") Map<Integer,String> message; @Option(names = {"-P", "-map"}, split = ",", paramLabel = "TIMEUNIT=VALUE", description = "Any number of TIMEUNIT=VALUE pairs. These may be specified separately (-PTIMEUNIT=VALUE) or as a comma-separated list.") Map<TimeUnit, String> map; } String actual = usageString(new App(), Help.Ansi.OFF); String expected = String.format("" + "Usage: <main class> [-P=TIMEUNIT=VALUE[,TIMEUNIT=VALUE...]]... (FIXTAG=VALUE%n" + " [\\|FIXTAG=VALUE...] FIXTAG=VALUE[\\|FIXTAG=VALUE...])...%n" + " (FIXTAG=VALUE[\\|FIXTAG=VALUE...] FIXTAG=VALUE[\\|FIXTAG=VALUE...])...%n" + " Repeating group of two lists of vertical bar '|'-separated%n" + " FIXTAG=VALUE pairs.%n" + " -P, -map=TIMEUNIT=VALUE[,TIMEUNIT=VALUE...]%n" + " Any number of TIMEUNIT=VALUE pairs. These may be specified separately%n" + " (-PTIMEUNIT=VALUE) or as a comma-separated list.%n"); assertEquals(expected, actual); } @Test public void testMapFieldHelpSplit_with_limitSplit() { class App { @Parameters(arity = "2", split = "\\|", paramLabel = "FIXTAG=VALUE", description = "Exactly two lists of vertical bar '|'-separated FIXTAG=VALUE pairs.") Map<Integer,String> message; @Option(names = {"-P", "-map"}, split = ",", paramLabel = "TIMEUNIT=VALUE", description = "Any number of TIMEUNIT=VALUE pairs. These may be specified separately (-PTIMEUNIT=VALUE) or as a comma-separated list.") Map<TimeUnit, String> map; } CommandSpec spec = CommandSpec.forAnnotatedObject(new App()); spec.parser().limitSplit(true); String actual = usageString(new CommandLine(spec), Help.Ansi.OFF); String expected = String.format("" + "Usage: <main class> [-P=TIMEUNIT=VALUE[,TIMEUNIT=VALUE]...]...%n" + " (FIXTAG=VALUE\\|FIXTAG=VALUE)...%n" + " (FIXTAG=VALUE\\|FIXTAG=VALUE)...%n" + " Exactly two lists of vertical bar '|'-separated FIXTAG=VALUE pairs.%n" + " -P, -map=TIMEUNIT=VALUE[,TIMEUNIT=VALUE]...%n" + " Any number of TIMEUNIT=VALUE pairs. These may be specified separately%n" + " (-PTIMEUNIT=VALUE) or as a comma-separated list.%n"); assertEquals(expected, actual); } // def cli = new CliBuilder(name:'ant', // header:'Options:') // cli.help('print this message') // cli.logfile(type:File, argName:'file', 'use given file for log') // cli.D(type:Map, argName:'property=value', args: '+', 'use value for given property') // cli.lib(argName:'path', valueSeparator:',', args: '3', // 'comma-separated list of up to 3 paths to search for jars and classes') @Test public void testMultiValueCliBuilderCompatibility() { class App { @Option(names = "--help", description = "print this message") boolean help; @Option(names = "--logfile", description = "use given file for log") File file; @Option(names = "-P", arity = "0..*", paramLabel = "<key=ppp>", description = "use value for project key") Map projectMap; @Option(names = "-D", arity = "1..*", paramLabel = "<key=ddd>", description = "use value for given property") Map map; @Option(names = "-S", arity = "0..*", split = ",", paramLabel = "<key=sss>", description = "use value for project key") Map sss; @Option(names = "-T", arity = "1..*", split = ",", paramLabel = "<key=ttt>", description = "use value for given property") Map ttt; @Option(names = "--x", arity = "0..2", split = ",", description = "comma-separated list of up to 2 xxx's") String[] x; @Option(names = "--y", arity = "3", split = ",", description = "exactly 3 y's") String[] y; @Option(names = "--lib", arity = "1..3", split = ",", description = "comma-separated list of up to 3 paths to search for jars and classes") String[] path; } CommandSpec spec = CommandSpec.forAnnotatedObject(new App()); spec.parser().limitSplit(true); String actual = usageString(new CommandLine(spec), Help.Ansi.OFF); String expected = String.format("" + "Usage: <main class> [--help] [--logfile=<file>] [--x[=<x>[,<x>]]]...%n" + " [--lib=<path>[,<path>[,<path>]]]... [--y=<y>,<y>,<y>]... [-P%n" + " [=<key=ppp>...]]... [-S[=<key=sss>[,<key=sss>]...]]...%n" + " [-D=<key=ddd>...]... [-T=<key=ttt>[,<key=ttt>]...]...%n" + " -D=<key=ddd>... use value for given property%n" + " --help print this message%n" + " --lib=<path>[,<path>[,<path>]]%n" + " comma-separated list of up to 3 paths to search for%n" + " jars and classes%n" + " --logfile=<file> use given file for log%n" + " -P=[<key=ppp>...] use value for project key%n" + " -S=[<key=sss>[,<key=sss>]...]%n" + " use value for project key%n" + " -T=<key=ttt>[,<key=ttt>]...%n" + " use value for given property%n" + " --x[=<x>[,<x>]] comma-separated list of up to 2 xxx's%n" + " --y=<y>,<y>,<y> exactly 3 y's%n" ); assertEquals(expected, actual); } @Test public void testMapFieldTypeInference() throws UnsupportedEncodingException { class App { @Option(names = "-a") Map<Integer, URI> a; @Option(names = "-b") Map<TimeUnit, StringBuilder> b; @SuppressWarnings("unchecked") @Option(names = "-c") Map c; @Option(names = "-d") List<File> d; @Option(names = "-e") Map<? extends Integer, ? super Long> e; @Option(names = "-f", type = {Long.class, Float.class}) Map<? extends Number, ? super Number> f; @SuppressWarnings("unchecked") @Option(names = "-g", type = {TimeUnit.class, Float.class}) Map<?, ?> g; } String actual = usageString(new App(), Help.Ansi.OFF); String expected = String.format("" + "Usage: <main class> [-a=<Integer=URI>]... [-b=<TimeUnit=StringBuilder>]...%n" + " [-c=<String=String>]... [-d=<d>]... [-e=<Integer=Long>]...%n" + " [-f=<Long=Float>]... [-g=<TimeUnit=Float>]...%n" + " -a=<Integer=URI>%n" + " -b=<TimeUnit=StringBuilder>%n" + "%n" + " -c=<String=String>%n" + " -d=<d>%n" + " -e=<Integer=Long>%n" + " -f=<Long=Float>%n" + " -g=<TimeUnit=Float>%n"); assertEquals(expected, actual); } @Test public void test200NPEWithEmptyCommandName() throws UnsupportedEncodingException { @Command(name = "") class Args {} String actual = usageString(new Args(), Help.Ansi.OFF); String expected = String.format("" + "Usage: %n" + ""); assertEquals(expected, actual); } @SuppressWarnings("deprecation") @Test public void testPrintHelpIfRequested1ReturnsTrueForUsageHelp() throws IOException { class App { @Option(names = "-h", usageHelp = true) boolean usageRequested; } List<CommandLine> list = new CommandLine(new App()).parse("-h"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); final PrintStream out = new PrintStream(baos); assertTrue(CommandLine.printHelpIfRequested(list, out, Help.Ansi.OFF)); String expected = String.format("" + "Usage: <main class> [-h]%n" + " -h%n"); assertEquals(expected, baos.toString()); } @Test public void testPrintHelpIfRequestedWithParseResultReturnsTrueForUsageHelp() throws IOException { class App { @Option(names = "-h", usageHelp = true) boolean usageRequested; } ParseResult parseResult = new CommandLine(new App()).parseArgs("-h"); assertTrue(CommandLine.printHelpIfRequested(parseResult)); String expected = String.format("" + "Usage: <main class> [-h]%n" + " -h%n"); assertEquals(expected, systemOutRule.getLog()); } @SuppressWarnings("deprecation") @Test public void testPrintHelpIfRequested2ReturnsTrueForUsageHelp() throws IOException { class App { @Option(names = "-h", usageHelp = true) boolean usageRequested; } List<CommandLine> list = new CommandLine(new App()).parse("-h"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); final PrintStream out = new PrintStream(baos); assertTrue(CommandLine.printHelpIfRequested(list, out, out, Help.Ansi.OFF)); String expected = String.format("" + "Usage: <main class> [-h]%n" + " -h%n"); assertEquals(expected, baos.toString()); } @SuppressWarnings("deprecation") @Test public void testPrintHelpIfRequestedWithCustomColorScheme() { ColorScheme customColorScheme = new ColorScheme.Builder(Help.Ansi.ON) .optionParams(Style.fg_magenta) .commands(Style.bg_cyan) .options(Style.fg_green) .parameters(Style.bg_white).build(); @Command(mixinStandardHelpOptions = true) class App { @Option(names = { "-f" }, paramLabel = "ARCHIVE", description = "the archive file") File archive; @Parameters(paramLabel = "POSITIONAL", description = "positional arg") String arg; } List<CommandLine> list = new CommandLine(new App()).parse("--help"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); final PrintStream out = new PrintStream(baos); assertTrue(CommandLine.printHelpIfRequested(list, out, out, customColorScheme)); String expected = Help.Ansi.ON.string(String.format("" + "Usage: @|bg_cyan <main class>|@ [@|green -hV|@] [@|green -f|@=@|magenta ARCHIVE|@] @|bg_white POSITIONAL|@%n" + "@|bg_white |@ @|bg_white POSITIONAL|@ positional arg%n" + " @|green -f|@=@|magenta A|@@|magenta RCHIVE|@ the archive file%n" + " @|green -h|@, @|green --help|@ Show this help message and exit.%n" + " @|green -V|@, @|green --version|@ Print version information and exit.%n")); assertEquals(expected, baos.toString()); } @SuppressWarnings("deprecation") @Test public void testPrintHelpIfRequestedReturnsTrueForVersionHelp() throws IOException { @Command(version = "abc 1.2.3 myversion") class App { @Option(names = "-V", versionHelp = true) boolean versionRequested; } List<CommandLine> list = new CommandLine(new App()).parse("-V"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); final PrintStream out = new PrintStream(baos); assertTrue(CommandLine.printHelpIfRequested(list, out, out, Help.Ansi.OFF)); String expected = String.format("abc 1.2.3 myversion%n"); assertEquals(expected, baos.toString()); } @SuppressWarnings("deprecation") @Test public void testPrintHelpIfRequestedReturnsFalseForNoHelp() throws IOException { class App { @Option(names = "-v") boolean verbose; } List<CommandLine> list = new CommandLine(new App()).parse("-v"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); final PrintStream out = new PrintStream(baos); assertFalse(CommandLine.printHelpIfRequested(list, out, out, Help.Ansi.OFF)); String expected = ""; assertEquals(expected, baos.toString()); } @Test public void testPrintHelpIfRequestedForHelpCommandThatDoesNotImplementIHelpCommandInitializable() { @Command(name = "help", helpCommand = true) class MyHelp implements Runnable { public void run() { } } @Command(subcommands = MyHelp.class) class App implements Runnable { public void run() { } } CommandLine cmd = new CommandLine(new App(), new InnerClassFactory(this)); ParseResult result = cmd.parseArgs("help"); assertTrue(CommandLine.printHelpIfRequested(result)); } @Command(name = "top", subcommands = {Sub.class}) static class Top { @Option(names = "-o", required = true) String mandatory; @Option(names = "-h", usageHelp = true) boolean isUsageHelpRequested; } @Command(name = "sub", description = "This is a subcommand") static class Sub {} @SuppressWarnings("deprecation") @Test public void test244SubcommandsNotParsed() { List<CommandLine> list = new CommandLine(new Top()).parse("-h", "sub"); assertEquals(2, list.size()); assertTrue(list.get(0).getCommand() instanceof Top); assertTrue(list.get(1).getCommand() instanceof Sub); assertTrue(((Top) list.get(0).getCommand()).isUsageHelpRequested); } @Test public void testDemoUsage() { String expected = String.format("" + " .__ .__ .__%n" + "______ |__| ____ ____ ____ | | |__|%n" + "\\____ \\| |/ ___\\/ _ \\_/ ___\\| | | |%n" + "| |_> > \\ \\__( <_> ) \\___| |_| |%n" + "| __/|__|\\___ >____/ \\___ >____/__|%n" + "|__| \\/ \\/%n" + "%n" + "Usage: picocli.Demo [-123airtV] [--simple]%n" + "%n" + "Demonstrates picocli subcommands parsing and usage help.%n" + "%n" + "Options:%n" + " -a, --autocomplete Generate sample autocomplete script for git%n" + " -1, --showUsageForSubcommandGitCommit%n" + " Shows usage help for the git-commit subcommand%n" + " -2, --showUsageForMainCommand%n" + " Shows usage help for a command with subcommands%n" + " -3, --showUsageForSubcommandGitStatus%n" + " Shows usage help for the git-status subcommand%n" + " --simple Show help for the first simple Example in the manual%n" + " -i, --index Show 256 color palette index values%n" + " -r, --rgb Show 256 color palette RGB component values%n" + " -t, --tests Runs all tests in this class%n" + " -V, --version Show version information and exit%n" + "%n" + "VM Options:%n" + "Run with -ea to enable assertions used in the tests.%n" + "Run with -Dpicocli.ansi=true to force picocli to use ansi codes,%n" + " or with -Dpicocli.ansi=false to force picocli to NOT use ansi codes.%n" + "(By default picocli will use ansi codes if the platform supports it.)%n" + "%n" + "If you would like to contribute or report an issue%n" + "go to github: https://github.com/remkop/picocli%n" + "%n" + "If you like the project star it on github and follow me on twitter!%n" + "This project is created and maintained by Remko Popma (@remkopopma)%n" + "%n"); assertEquals(expected, usageString(new Demo(), Help.Ansi.OFF)); } @Test public void testHelpCannotBeAddedAsSubcommand() { @Command(subcommands = Help.class) class App{} try { new CommandLine(new App(), new InnerClassFactory(this)); } catch (InitializationException ex) { assertEquals("picocli.CommandLine$Help is not a valid subcommand. Did you mean picocli.CommandLine$HelpCommand?", ex.getMessage()); } } @SuppressWarnings("deprecation") @Test public void testAutoHelpMixinUsageHelpOption() { @Command(mixinStandardHelpOptions = true) class App {} String[] helpOptions = {"-h", "--help"}; for (String option : helpOptions) { List<CommandLine> list = new CommandLine(new App()).parse(option); assertTrue(list.get(0).isUsageHelpRequested()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); final PrintStream out = new PrintStream(baos); assertTrue(CommandLine.printHelpIfRequested(list, out, out, Help.Ansi.OFF)); String expected = String.format("" + "Usage: <main class> [-hV]%n" + " -h, --help Show this help message and exit.%n" + " -V, --version Print version information and exit.%n"); assertEquals(expected, baos.toString()); } } @SuppressWarnings("deprecation") @Test public void testAutoHelpMixinVersionHelpOption() { @Command(mixinStandardHelpOptions = true, version = "1.2.3") class App {} String[] versionOptions = {"-V", "--version"}; for (String option : versionOptions) { List<CommandLine> list = new CommandLine(new App()).parse(option); assertTrue(list.get(0).isVersionHelpRequested()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); final PrintStream out = new PrintStream(baos); assertTrue(CommandLine.printHelpIfRequested(list, out, out, Help.Ansi.OFF)); String expected = String.format("1.2.3%n"); assertEquals(expected, baos.toString()); } } @SuppressWarnings("deprecation") @Test public void testAutoHelpMixinUsageHelpSubcommandOnAppWithoutSubcommands() { @Command(mixinStandardHelpOptions = true, subcommands = HelpCommand.class) class App {} List<CommandLine> list = new CommandLine(new App()).parse("help"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); final PrintStream out = new PrintStream(baos); assertTrue(CommandLine.printHelpIfRequested(list, out, out, Help.Ansi.OFF)); String expected = String.format("" + "Usage: <main class> [-hV] [COMMAND]%n" + " -h, --help Show this help message and exit.%n" + " -V, --version Print version information and exit.%n" + "Commands:%n" + " help Displays help information about the specified command%n"); assertEquals(expected, baos.toString()); } @Test public void testAutoHelpMixinRunHelpSubcommandOnAppWithoutSubcommands() { @Command(mixinStandardHelpOptions = true, subcommands = HelpCommand.class) class App implements Runnable{ public void run(){}} StringWriter sw = new StringWriter(); new CommandLine(new App()) .setOut(new PrintWriter(sw)) .setColorScheme(Help.defaultColorScheme(Help.Ansi.OFF)) .execute("help"); String expected = String.format("" + "Usage: <main class> [-hV] [COMMAND]%n" + " -h, --help Show this help message and exit.%n" + " -V, --version Print version information and exit.%n" + "Commands:%n" + " help Displays help information about the specified command%n"); assertEquals(expected, sw.toString()); } @Test public void testHelpSubcommandWithValidCommand() { @Command(subcommands = {Sub.class, HelpCommand.class}) class App implements Runnable{ public void run(){}} StringWriter sw = new StringWriter(); new CommandLine(new App()) .setOut(new PrintWriter(sw)) .setColorScheme(Help.defaultColorScheme(Help.Ansi.OFF)) .execute("help", "sub"); String expected = String.format("" + "Usage: <main class> sub%n" + "This is a subcommand%n"); assertEquals(expected, sw.toString()); } @Test public void testHelpSubcommandWithInvalidCommand() { @Command(mixinStandardHelpOptions = true, subcommands = {Sub.class, HelpCommand.class}) class App implements Runnable{ public void run(){}} StringWriter sw = new StringWriter(); new CommandLine(new App()) .setErr(new PrintWriter(sw)) .setColorScheme(Help.defaultColorScheme(Help.Ansi.OFF)) .execute("help", "abcd"); String expected = String.format("" + "Unknown subcommand 'abcd'.%n" + "Usage: <main class> [-hV] [COMMAND]%n" + " -h, --help Show this help message and exit.%n" + " -V, --version Print version information and exit.%n" + "Commands:%n" + " sub This is a subcommand%n" + " help Displays help information about the specified command%n"); assertEquals(expected, sw.toString()); } @Test public void testHelpSubcommandWithHelpOption() { @Command(subcommands = {Sub.class, HelpCommand.class}) class App implements Runnable{ public void run(){}} StringWriter sw = new StringWriter(); new CommandLine(new App()) .setOut(new PrintWriter(sw)) .setColorScheme(Help.defaultColorScheme(Help.Ansi.OFF)) .execute("help", "-h"); String expected = String.format("" + "Displays help information about the specified command%n" + "%n" + "Usage: <main class> help [-h] [COMMAND...]%n" + "%n" + "When no COMMAND is given, the usage help for the main command is displayed.%n" + "If a COMMAND is specified, the help for that command is shown.%n" + "%n" + " [COMMAND...] The COMMAND to display the usage help message for.%n" + " -h, --help Show usage help for the help command and exit.%n"); assertEquals(expected, sw.toString()); sw = new StringWriter(); new CommandLine(new App()).getSubcommands().get("help").usage(new PrintWriter(sw)); assertEquals(expected, sw.toString()); } @Test public void testHelpSubcommandWithoutCommand() { @Command(mixinStandardHelpOptions = true, subcommands = {Sub.class, HelpCommand.class}) class App implements Runnable{ public void run(){}} StringWriter sw = new StringWriter(); new CommandLine(new App()) .setOut(new PrintWriter(sw)) .setColorScheme(Help.defaultColorScheme(Help.Ansi.OFF)) .execute("help"); String expected = String.format("" + "Usage: <main class> [-hV] [COMMAND]%n" + " -h, --help Show this help message and exit.%n" + " -V, --version Print version information and exit.%n" + "Commands:%n" + " sub This is a subcommand%n" + " help Displays help information about the specified command%n"); assertEquals(expected, sw.toString()); sw = new StringWriter(); new CommandLine(new App()).usage(new PrintWriter(sw), Help.Ansi.OFF); assertEquals(expected, sw.toString()); } @Test public void testHelpSubcommandRunDoesNothingIfParentNotSet() { HelpCommand cmd = new HelpCommand(); cmd.run(); assertEquals("", this.systemOutRule.getLog()); } @SuppressWarnings({"deprecation"}) @Test public void testHelpSubcommandRunPrintsParentUsageIfParentSet() { HelpCommand cmd = new HelpCommand(); CommandLine help = new CommandLine(cmd); CommandSpec spec = CommandSpec.create().name("parent"); spec.usageMessage().description("the parent command"); spec.addSubcommand("parent", help); new CommandLine(spec); // make sure parent spec has a CommandLine cmd.init(help, Help.Ansi.OFF, System.out, System.err); cmd.run(); String expected = String.format("" + "Usage: parent [COMMAND]%n" + "the parent command%n" + "Commands:%n" + " parent Displays help information about the specified command%n"); assertEquals(expected, this.systemOutRule.getLog()); } @Test public void testHelpSubcommand2RunPrintsParentUsageIfParentSet() { HelpCommand cmd = new HelpCommand(); CommandLine help = new CommandLine(cmd); CommandSpec spec = CommandSpec.create().name("parent"); spec.usageMessage().description("the parent command"); spec.addSubcommand("parent", help); new CommandLine(spec); // make sure parent spec has a CommandLine cmd.init(help, Help.defaultColorScheme(Help.Ansi.OFF), new PrintWriter(System.out), new PrintWriter(System.err)); cmd.run(); String expected = String.format("" + "Usage: parent [COMMAND]%n" + "the parent command%n" + "Commands:%n" + " parent Displays help information about the specified command%n"); assertEquals(expected, this.systemOutRule.getLog()); } @Test public void testUsageHelpForNestedSubcommands() { @Command(name = "subsub", mixinStandardHelpOptions = true) class SubSub { } @Command(name = "sub", subcommands = {SubSub.class}) class Sub { } @Command(name = "main", subcommands = {Sub.class}) class App { } CommandLine app = new CommandLine(new App(), new InnerClassFactory(this)); //ParseResult result = app.parseArgs("sub", "subsub", "--help"); //CommandLine.printHelpIfRequested(result); CommandLine subsub = app.getSubcommands().get("sub").getSubcommands().get("subsub"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); subsub.usage(new PrintStream(baos), Help.Ansi.OFF); String expected = String.format("" + "Usage: main sub subsub [-hV]%n" + " -h, --help Show this help message and exit.%n" + " -V, --version Print version information and exit.%n"); assertEquals(expected, baos.toString()); } @Test public void testUsageTextWithHiddenSubcommand() { @Command(name = "foo", description = "This is a visible subcommand") class Foo { } @Command(name = "bar", description = "This is a hidden subcommand", hidden = true) class Bar { } @Command(name = "app", subcommands = {Foo.class, Bar.class}) class App { } CommandLine app = new CommandLine(new App(), new InnerClassFactory(this)); ByteArrayOutputStream baos = new ByteArrayOutputStream(); app.usage(new PrintStream(baos)); String expected = format("" + "Usage: app [COMMAND]%n" + "Commands:%n" + " foo This is a visible subcommand%n"); assertEquals(expected, baos.toString()); } @Test public void testUsage_NoHeaderIfAllSubcommandHidden() { @Command(name = "foo", description = "This is a foo sub-command", hidden = true) class Foo { } @Command(name = "bar", description = "This is a foo sub-command", hidden = true) class Bar { } @Command(name = "app", abbreviateSynopsis = true) class App { } CommandLine app = new CommandLine(new App()) .addSubcommand("foo", new Foo()) .addSubcommand("bar", new Bar()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); app.usage(new PrintStream(baos)); String expected = format("" + "Usage: app [COMMAND]%n"); assertEquals(expected, baos.toString()); } @Test public void test282BrokenValidationWhenNoOptionsToCompareWith() { class App implements Runnable { @Parameters(paramLabel = "FILES", arity = "1..*", description = "List of files") private List<File> files = new ArrayList<File>(); public void run() { } } String[] args = new String[] {"-unknown"}; StringWriter sw = new StringWriter(); new CommandLine(new App()) .setErr(new PrintWriter(sw)) .setColorScheme(Help.defaultColorScheme(Help.Ansi.OFF)) .execute(args); String expected = format("" + "Missing required parameter: FILES%n" + "Usage: <main class> FILES...%n" + " FILES... List of files%n"); assertEquals(expected, sw.toString()); } @Test public void test282ValidationWorksWhenOptionToCompareWithExists() { class App implements Runnable { @Parameters(paramLabel = "FILES", arity = "1..*", description = "List of files") private List<File> files = new ArrayList<File>(); @CommandLine.Option(names = {"-v"}, description = "Print output") private boolean verbose; public void run() { } } String[] args = new String[] {"-unknown"}; StringWriter sw = new StringWriter(); new CommandLine(new App()) .setErr(new PrintWriter(sw)) .setColorScheme(Help.defaultColorScheme(Help.Ansi.OFF)) .execute(args); String expected = format("" + "Missing required parameter: FILES%n" + "Usage: <main class> [-v] FILES...%n" + " FILES... List of files%n" + " -v Print output%n"); assertEquals(expected, sw.toString()); } @Test public void testShouldGetUsageWidthFromSystemProperties() { int defaultWidth = new UsageMessageSpec().width(); assertEquals(80, defaultWidth); try { System.setProperty("picocli.usage.width", "123"); int width = new UsageMessageSpec().width(); assertEquals(123, width); } finally { System.setProperty("picocli.usage.width", String.valueOf(defaultWidth)); } } @Test public void testInvalidUsageWidthPropertyValue() throws UnsupportedEncodingException { PrintStream originalErr = System.err; ByteArrayOutputStream baos = new ByteArrayOutputStream(2500); System.setErr(new PrintStream(baos)); System.clearProperty("picocli.trace"); System.setProperty("picocli.usage.width", "INVALID"); int actual = new UsageMessageSpec().width(); System.setErr(originalErr); System.clearProperty("picocli.usage.width"); assertEquals(80, actual); assertEquals(format("[picocli WARN] Invalid picocli.usage.width value 'INVALID'. Using usage width 80.%n"), baos.toString("UTF-8")); } @Test public void testUsageWidthFromCommandAttribute() { @Command(usageHelpWidth = 60, description = "0123456789012345678901234567890123456789012345678901234567890123456789") class App {} CommandLine cmd = new CommandLine(new App()); assertEquals(60, cmd.getUsageHelpWidth()); assertEquals(60, cmd.getCommandSpec().usageMessage().width()); } @Test public void testUsageWidthFromSystemPropertyOverridesCommandAttribute() { @Command(usageHelpWidth = 60, description = "0123456789012345678901234567890123456789012345678901234567890123456789") class App {} System.setProperty("picocli.usage.width", "123"); try { CommandLine cmd = new CommandLine(new App()); assertEquals(123, cmd.getUsageHelpWidth()); assertEquals(123, cmd.getCommandSpec().usageMessage().width()); } finally { System.clearProperty("picocli.usage.width"); } } @Test public void testInvalidUsageWidthCommandAttribute() throws UnsupportedEncodingException { @Command(usageHelpWidth = 40) class App {} try { new CommandLine(new App()); fail("Expected exception"); } catch (InitializationException ex) { assertEquals("Invalid usage message width 40. Minimum value is 55", ex.getMessage()); }; } @Test public void testTooSmallUsageWidthPropertyValue() throws UnsupportedEncodingException { PrintStream originalErr = System.err; ByteArrayOutputStream baos = new ByteArrayOutputStream(2500); System.setErr(new PrintStream(baos)); System.clearProperty("picocli.trace"); System.setProperty("picocli.usage.width", "54"); int actual = new UsageMessageSpec().width(); System.setErr(originalErr); System.clearProperty("picocli.usage.width"); assertEquals(55, actual); assertEquals(format("[picocli WARN] Invalid picocli.usage.width value 54. Using minimum usage width 55.%n"), baos.toString("UTF-8")); } @Test public void testTextTableWithLargeWidth() { TextTable table = TextTable.forDefaultColumns(Help.Ansi.OFF, 200); table.addRowValues(textArray(Help.Ansi.OFF, "", "-v", ",", "--verbose", "show what you're doing while you are doing it")); table.addRowValues(textArray(Help.Ansi.OFF, "", "-p", null, null, "the quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy doooooooooooooooog.")); assertEquals(String.format( " -v, --verbose show what you're doing while you are doing it%n" + " -p the quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy doooooooooooooooog.%n" ), table.toString(new StringBuilder()).toString()); } @Test public void testLongMultiLineSynopsisIndentedWithLargeWidth() { System.setProperty("picocli.usage.width", "200"); try { @Command(name = "<best-app-ever>") class App { @Option(names = "--long-option-name", paramLabel = "<long-option-value>") int a; @Option(names = "--another-long-option-name", paramLabel = "<another-long-option-value>") int b; @Option(names = "--third-long-option-name", paramLabel = "<third-long-option-value>") int c; @Option(names = "--fourth-long-option-name", paramLabel = "<fourth-long-option-value>") int d; } Help help = new Help(new App(), Help.Ansi.OFF); assertEquals(String.format( "<best-app-ever> [--another-long-option-name=<another-long-option-value>] [--fourth-long-option-name=<fourth-long-option-value>] [--long-option-name=<long-option-value>]%n" + " [--third-long-option-name=<third-long-option-value>]%n"), help.synopsis(0)); } finally { System.setProperty("picocli.usage.width", String.valueOf(UsageMessageSpec.DEFAULT_USAGE_WIDTH)); } } @Command(description = "The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog.") static class WideDescriptionApp { @Option(names = "-s", description = "The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The a quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog.") String shortOption; @Option(names = "--very-very-very-looooooooooooooooong-option-name", description = "The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog.") String lengthyOption; static final String expected = format("Usage: <main class> [-s=<shortOption>] [--very-very-very-looooooooooooooooong-option-name=<lengthyOption>]%n" + "The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The quick brown fox jumped%n" + "over the lazy dog. The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The%n" + "quick brown fox jumped over the lazy dog.%n" + " -s=<shortOption> The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The a%n" + " quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog.%n" + " --very-very-very-looooooooooooooooong-option-name=<lengthyOption>%n" + " The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The%n" + " quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog.%n" ); } @Test public void testWideUsageViaSystemProperty() { System.setProperty("picocli.usage.width", String.valueOf(120)); try { String actual = usageString(new WideDescriptionApp(), Help.Ansi.OFF); assertEquals(WideDescriptionApp.expected, actual); } finally { System.setProperty("picocli.usage.width", String.valueOf(80)); } } @Test public void testWideUsage() { CommandLine cmd = new CommandLine(new WideDescriptionApp()); cmd.setUsageHelpWidth(120); String actual = usageString(cmd, Help.Ansi.OFF); assertEquals(WideDescriptionApp.expected, actual); } @Test public void testUsageHelpAutoWidthViaSystemProperty() { CommandLine cmd = new CommandLine(new WideDescriptionApp()); assertFalse(cmd.isUsageHelpAutoWidth()); assertFalse(cmd.getCommandSpec().usageMessage().autoWidth()); System.setProperty("picocli.usage.width", "AUTO"); assertTrue(cmd.isUsageHelpAutoWidth()); assertTrue(cmd.getCommandSpec().usageMessage().autoWidth()); System.setProperty("picocli.usage.width", "TERM"); assertTrue(cmd.isUsageHelpAutoWidth()); assertTrue(cmd.getCommandSpec().usageMessage().autoWidth()); System.setProperty("picocli.usage.width", "TERMINAL"); assertTrue(cmd.isUsageHelpAutoWidth()); assertTrue(cmd.getCommandSpec().usageMessage().autoWidth()); System.setProperty("picocli.usage.width", "X"); assertFalse(cmd.isUsageHelpAutoWidth()); assertFalse(cmd.getCommandSpec().usageMessage().autoWidth()); } @Test public void testGetTerminalWidthLinux() { String sttyResult = "speed 38400 baud; rows 50; columns 123; line = 0;\n" + "intr = ^C; quit = ^\\; erase = ^?; kill = ^U; eof = ^D; eol = <undef>; eol2 = <undef>; swtch = ^Z; start = ^Q; stop = ^S;\n" + "susp = ^Z; rprnt = ^R; werase = ^W; lnext = ^V; discard = ^O; min = 1; time = 0;\n" + "-parenb -parodd cs8 -hupcl -cstopb cread -clocal -crtscts\n" + "-ignbrk brkint -ignpar -parmrk -inpck -istrip -inlcr -igncr icrnl ixon -ixoff -iuclc ixany imaxbel iutf8\n" + "opost -olcuc -ocrnl onlcr -onocr -onlret -ofill -ofdel nl0 cr0 tab0 bs0 vt0 ff0\n" + "isig icanon iexten echo echoe echok -echonl -noflsh -tostop echoctl echoke -flusho\n"; Pattern pattern = Pattern.compile(".*olumns(:)?\\s+(\\d+)\\D.*", Pattern.DOTALL); Matcher matcher = pattern.matcher(sttyResult); assertTrue(matcher.matches()); assertEquals(123, Integer.parseInt(matcher.group(2))); } @Test public void testGetTerminalWidthWindows() { String sttyResult = "\n" + "Status for device CON:\n" + "----------------------\n" + " Lines: 9001\n" + " Columns: 113\n" + " Keyboard rate: 31\n" + " Keyboard delay: 1\n" + " Code page: 932\n" + "\n"; Pattern pattern = Pattern.compile(".*olumns(:)?\\s+(\\d+)\\D.*", Pattern.DOTALL); Matcher matcher = pattern.matcher(sttyResult); assertTrue(matcher.matches()); assertEquals(113, Integer.parseInt(matcher.group(2))); } @Test public void testAutoWidthDisabledBySystemProperty() { @Command(usageHelpAutoWidth = true) class App {} System.setProperty("picocli.usage.width", "123"); CommandLine cmd = new CommandLine(new App()); assertFalse(cmd.isUsageHelpAutoWidth()); assertFalse(cmd.getCommandSpec().usageMessage().autoWidth()); assertEquals(123, cmd.getCommandSpec().usageMessage().width()); } @Test public void testAutoWidthEnabledProgrammatically() { @Command(usageHelpAutoWidth = true) class App {} CommandLine cmd = new CommandLine(new App()); assertTrue(cmd.isUsageHelpAutoWidth()); assertTrue(cmd.getCommandSpec().usageMessage().autoWidth()); // the below may fail when this test is running on Cygwin or MINGW assertEquals(80, cmd.getCommandSpec().usageMessage().width()); } @Test public void testCliBuilderLsExample() { @Command(name="ls") class App { @Option(names = "-a", description = "display all files") boolean a; @Option(names = "-l", description = "use a long listing format") boolean l; @Option(names = "-t", description = "sort by modification time") boolean t; } String actual = usageString(new App(), Help.Ansi.OFF); assertEquals(String.format("" + "Usage: ls [-alt]%n" + " -a display all files%n" + " -l use a long listing format%n" + " -t sort by modification time%n"), actual); } @Test public void testAnsiText() { String markup = "@|bg(red),white,underline some text|@"; Help.Ansi.Text txt = Help.Ansi.ON.text(markup); Help.Ansi.Text txt2 = Help.Ansi.ON.new Text(markup); assertEquals(txt, txt2); } @Test public void testAnsiString() { String msg = "some text"; String markup = "@|bg(red),white,underline " + msg + "|@"; String ansiTxt = Help.Ansi.ON.string(markup); String ansiTxt2 = Help.Ansi.ON.new Text(markup).toString(); assertEquals(ansiTxt, ansiTxt2); } @Test public void testAnsiValueOf() { assertEquals("true=ON", Help.Ansi.ON, Help.Ansi.valueOf(true)); assertEquals("false=OFF", Help.Ansi.OFF, Help.Ansi.valueOf(false)); } @Test public void testIssue430NewlineInSubcommandDescriptionList() { // courtesy [Benny Bottema](https://github.com/bbottema) CommandSpec rootCmd = createCmd("newlines", "Displays subcommands, one of which contains description newlines"); rootCmd.addSubcommand("subA", createCmd("subA", "regular description for subA")); rootCmd.addSubcommand("subB", createCmd("subB", "very,\nspecial,\nChristopher Walken style,\ndescription.")); rootCmd.addSubcommand("subC", createCmd("subC", "not so,%nspecial,%nJon Voight style,%ndescription.")); rootCmd.addSubcommand("subD", createCmd("subD", "regular description for subD")); assertEquals(String.format("" + "Usage: newlines [-hV] [COMMAND]%n" + "Displays subcommands, one of which contains description newlines%n" + " -h, --help Show this help message and exit.%n" + " -V, --version Print version information and exit.%n" + "Commands:%n" + " subA regular description for subA%n" + " subB very,%n" + " special,%n" + " Christopher Walken style,%n" + " description.%n" + " subC not so,%n" + " special,%n" + " Jon Voight style,%n" + " description.%n" + " subD regular description for subD%n"), new CommandLine(rootCmd).getUsageMessage()); } @Test public void testMultiLineWrappedDescription() { CommandSpec rootCmd = createCmd("wrapDescriptions", "Displays sub commands, with extra long descriptions"); CommandSpec oneLineCmd = createCmd("oneLine", "The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog."); CommandSpec multiLineCmd = createCmd("multiLine", "The quick brown fox jumped over the lazy dog.%nThe quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog.%n%nThe quick brown fox jumped over the lazy dog."); rootCmd.addSubcommand("oneLine", oneLineCmd); rootCmd.addSubcommand("multiLine", multiLineCmd); assertEquals(String.format("" + "Usage: wrapDescriptions [-hV] [COMMAND]%n" + "Displays sub commands, with extra long descriptions%n" + " -h, --help Show this help message and exit.%n" + " -V, --version Print version information and exit.%n" + "Commands:%n" + " oneLine The quick brown fox jumped over the lazy dog. The quick brown fox%n" + " jumped over the lazy dog. The quick brown fox jumped over the%n" + " lazy dog. The quick brown fox jumped over the lazy dog. The%n" + " quick brown fox jumped over the lazy dog. The quick brown fox%n" + " jumped over the lazy dog.%n" + " multiLine The quick brown fox jumped over the lazy dog.%n" + " The quick brown fox jumped over the lazy dog. The quick brown fox%n" + " jumped over the lazy dog. The quick brown fox jumped over the%n" + " lazy dog. The quick brown fox jumped over the lazy dog.%n%n" + " The quick brown fox jumped over the lazy dog.%n"), new CommandLine(rootCmd).getUsageMessage()); assertEquals(String.format( "Usage: wrapDescriptions oneLine [-hV]%n" + "The quick brown fox jumped over the lazy dog. The quick brown fox jumped over%n" + "the lazy dog. The quick brown fox jumped over the lazy dog. The quick brown fox%n" + "jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The%n" + "quick brown fox jumped over the lazy dog.%n" + " -h, --help Show this help message and exit.%n" + " -V, --version Print version information and exit.%n"), new CommandLine(oneLineCmd).getUsageMessage()); assertEquals(String.format( "Usage: wrapDescriptions multiLine [-hV]%n" + "The quick brown fox jumped over the lazy dog.%n" + "The quick brown fox jumped over the lazy dog. The quick brown fox jumped over%n" + "the lazy dog. The quick brown fox jumped over the lazy dog. The quick brown fox%n" + "jumped over the lazy dog.%n%n" + "The quick brown fox jumped over the lazy dog.%n" + " -h, --help Show this help message and exit.%n" + " -V, --version Print version information and exit.%n"), new CommandLine(multiLineCmd).getUsageMessage()); } @Test public void testMultiLineWrappedDefaultValueWontRunIntoInfiniteLoop(){ class Args { @Parameters(arity = "1..*", description = "description", defaultValue = "/long/value/length/equals/columnValue/maxlength/and/non/null/offset/xxx", showDefaultValue = ALWAYS) String[] c; } String expected = String.format("" + "Usage: <main class> <c>...%n" + " <c>... description%n" + " Default:%n" + " /long/value/length/equals/columnValue/maxlength/and/non/null/of%n" + " fset/xxx%n"); assertEquals(expected, usageString(new Args(), Help.Ansi.OFF)); } private static CommandSpec createCmd(String name, String description) { CommandSpec cmd = CommandSpec.create().name(name).mixinStandardHelpOptions(true); cmd.usageMessage().description(description); return cmd; } @Test public void testHelpFactoryIsUsedWhenSet() { @Command() class TestCommand { } IHelpFactory helpFactoryWithOverridenHelpMethod = new IHelpFactory() { public Help create(CommandSpec commandSpec, ColorScheme colorScheme) { return new Help(commandSpec, colorScheme) { @Override public String detailedSynopsis(int synopsisHeadingLength, Comparator<OptionSpec> optionSort, boolean clusterBooleanOptions) { return "<custom detailed synopsis>"; } }; } }; CommandLine commandLineWithCustomHelpFactory = new CommandLine(new TestCommand()).setHelpFactory(helpFactoryWithOverridenHelpMethod); assertEquals("Usage: <custom detailed synopsis>", commandLineWithCustomHelpFactory.getUsageMessage(Help.Ansi.OFF)); ByteArrayOutputStream baos = new ByteArrayOutputStream(); commandLineWithCustomHelpFactory.usage(new PrintStream(baos, true)); assertEquals("Usage: <custom detailed synopsis>", baos.toString()); } @Test public void testCustomizableHelpSections() { @Command(header="<header> (%s)", description="<description>") class TestCommand { } CommandLine commandLineWithCustomHelpSections = new CommandLine(new TestCommand()); IHelpSectionRenderer renderer = new IHelpSectionRenderer() { public String render(Help help) { return help.header("<custom header param>"); } }; commandLineWithCustomHelpSections.getHelpSectionMap().put("customSectionExtendsHeader", renderer); commandLineWithCustomHelpSections.setHelpSectionKeys(Arrays.asList( UsageMessageSpec.SECTION_KEY_DESCRIPTION, UsageMessageSpec.SECTION_KEY_SYNOPSIS_HEADING, "customSectionExtendsHeader")); String expected = String.format("" + "<description>%n" + "Usage: <header> (<custom header param>)%n"); assertEquals(expected, commandLineWithCustomHelpSections.getUsageMessage(Help.Ansi.OFF)); } @Test public void testNullSectionRenderer() { CommandLine cmd = new CommandLine(new UsageDemo()); cmd.getHelpSectionMap().clear(); cmd.getHelpSectionMap().put(UsageMessageSpec.SECTION_KEY_HEADER, null); cmd.getHelpSectionMap().put(UsageMessageSpec.SECTION_KEY_DESCRIPTION, new IHelpSectionRenderer() { public String render(Help help) { return "abc"; } }); String actual = cmd.getUsageMessage(); String expected = "abc"; assertEquals(expected, actual); } @Test public void testBooleanOptionWithArity1() { @Command(mixinStandardHelpOptions = true) class ExampleCommand { @Option(names = { "-b" }, arity = "1") boolean booleanWithArity1; } String expected = String.format("" + "Usage: <main class> [-hV] [-b=<booleanWithArity1>]%n" + " -b=<booleanWithArity1>%n" + " -h, --help Show this help message and exit.%n" + " -V, --version Print version information and exit.%n"); assertEquals(expected, new CommandLine(new ExampleCommand()).getUsageMessage(Help.Ansi.OFF)); } @Test public void testIssue615DescriptionContainingPercentChar() { class App { @Option(names = {"--excludebase"}, arity="1..*", description = "exclude child files of cTree (only works with --ctree).%n" + "Currently must be explicit or with trailing % for truncated glob." ) public String[] excludeBase; } String expected = String.format("" + "Usage: <main class> [--excludebase=<excludeBase>...]...%n" + " --excludebase=<excludeBase>...%n" + " exclude child files of cTree (only works with --ctree).%%nCurrently%n" + " must be explicit or with trailing %% for truncated glob.%n"); String actual = new CommandLine(new App()).getUsageMessage(); assertEquals(expected, actual); assertTrue(systemErrRule.getLog().contains( "[picocli WARN] Could not format 'exclude child files of cTree (only works with --ctree).%n" + "Currently must be explicit or with trailing % for truncated glob.' " + "(Underlying error:")); assertTrue(systemErrRule.getLog().contains( "). " + "Using raw String: '%n' format strings have not been replaced with newlines. " + "Please ensure to escape '%' characters with another '%'.")); } @Test public void testDescriptionWithDefaultValueContainingPercentChar() { class App { @Option(names = {"-f"}, defaultValue = "%s - page %d of %d", description = "format string. Default: ${DEFAULT-VALUE}") public String formatString; } String expected = String.format("" + "Usage: <main class> [-f=<formatString>]%n" + " -f=<formatString> format string. Default: %%s - page %%d of %%d%n"); String actual = new CommandLine(new App()).getUsageMessage(); assertEquals(expected, actual); assertFalse(systemErrRule.getLog().contains( "[picocli WARN] Could not format 'format string. Default: %s - page %d of %d' " + "(Underlying error:")); assertFalse(systemErrRule.getLog().contains( "). " + "Using raw String: '%n' format strings have not been replaced with newlines. " + "Please ensure to escape '%' characters with another '%'.")); } @Test public void testDescriptionWithFallbackValueContainingPercentChar() { class App { @Option(names = {"-f"}, fallbackValue = "%s - page %d of %d", description = "format string. Fallback: ${FALLBACK-VALUE}") public String formatString; } String expected = String.format("" + "Usage: <main class> [-f=<formatString>]%n" + " -f=<formatString> format string. Fallback: %%s - page %%d of %%d%n"); String actual = new CommandLine(new App()).getUsageMessage(); assertEquals(expected, actual); assertFalse(systemErrRule.getLog().contains( "picocli WARN")); } @Test public void testCharCJKDoubleWidthTextByDefault() { @Command(name = "cjk", mixinStandardHelpOptions = true, description = { "12345678901234567890123456789012345678901234567890123456789012345678901234567890", "CUI\u306fGUI\u3068\u6bd4\u3079\u3066\u76f4\u611f\u7684\u306a\u64cd\u4f5c\u304c\u3067\u304d\u306a\u3044\u306a\u3069\u306e\u6b20\u70b9\u304c\u3042\u308b\u3082\u306e\u306e\u3001\u30e1\u30a4\u30f3\u30e1\u30e2\u30ea\u304a\u3088\u3073\u30d3\u30c7\u30aa\u30e1\u30e2\u30ea\u306a\u3069\u306e\u30b3\u30f3\u30d4\u30e5\u30fc\u30bf\u8cc7\u6e90\u306e\u6d88\u8cbb\u304c\u5c11\u306a\u3044\u3053\u3068\u304b\u3089\u3001" + "\u6027\u80fd\u306e\u4f4e\u3044\u521d\u671f\u306e\u30b3\u30f3\u30d4\u30e5\u30fc\u30bf\u3067\u306fCUI\u306b\u3088\u308b\u5bfe\u8a71\u74b0\u5883\u304c\u4e3b\u6d41\u3060\u3063\u305f\u3002\u305d\u306e\u5f8c\u3001\u30b3\u30f3\u30d4\u30e5\u30fc\u30bf\u306e\u6027\u80fd\u304c\u5411\u4e0a\u3057\u3001\u30de\u30a6\u30b9\u306a\u3069\u306e\u30dd\u30a4\u30f3\u30c6\u30a3\u30f3\u30b0\u30c7\u30d0\u30a4\u30b9\u306b\u3088\u3063\u3066" + "\u76f4\u611f\u7684\u306a\u64cd\u4f5c\u306e\u3067\u304d\u308bGUI\u74b0\u5883\u304cMacintosh\u3084Windows 95\u306a\u3069\u306b\u3088\u3063\u3066\u30aa\u30d5\u30a3\u30b9\u3084\u4e00\u822c\u5bb6\u5ead\u306b\u3082\u666e\u53ca\u3057\u3001" + "CUI\u306f\u65e2\u5b9a\u306e\u30a4\u30f3\u30bf\u30fc\u30d5\u30a7\u30a4\u30b9\u3067\u306f\u306a\u304f\u306a\u3063\u3066\u3044\u3063\u305f\u3002\u30d1\u30fc\u30bd\u30ca\u30eb\u30b3\u30f3\u30d4\u30e5\u30fc\u30bf (PC) \u5411\u3051\u3084\u30b5\u30fc\u30d0\u30fc\u5411\u3051\u306e\u30aa\u30da\u30ec\u30fc\u30c6\u30a3\u30f3\u30b0\u30b7\u30b9\u30c6\u30e0 (OS) " + "\u306b\u306f\u3001\u65e2\u5b9a\u306e\u30a4\u30f3\u30bf\u30fc\u30d5\u30a7\u30a4\u30b9\u304cGUI\u3067\u3042\u3063\u3066\u3082\u30b3\u30de\u30f3\u30c9\u30e9\u30a4\u30f3\u30bf\u30fc\u30df\u30ca\u30eb\u306a\u3069\u306eCUI\u74b0\u5883\u304c\u4f9d\u7136\u3068\u3057\u3066\u7528\u610f\u3055\u308c\u3066\u3044\u308b\u304c\u3001\u30b9\u30de\u30fc\u30c8\u30d5\u30a9\u30f3\u306a\u3069\u306e\u30e2\u30d0\u30a4\u30eb" + "\u7aef\u672b\u5411\u3051OS\u306b\u306f\u6a19\u6e96\u3067\u7528\u610f\u3055\u308c\u3066\u304a\u3089\u305a\u3001GUI\u304c\u4e3b\u6d41\u3068\u306a\u3063\u3066\u3044\u308b\u3002"}) class App { @Option(names = {"-x", "--long"}, description = "\u3057\u304b\u3057\u3001GUI\u74b0\u5883\u3067\u3042\u308c\u3070\u30dd\u30a4\u30f3\u30c6\u30a3\u30f3\u30b0\u30c7\u30d0\u30a4\u30b9\u306b\u3088\u308b\u64cd\u4f5c\u3092\u7e70\u308a\u8fd4\u3057\u884c\u308f\u306a\u3051\u308c\u3070\u306a\u3089\u306a\u3044\u3088\u3046\u306a\u7169\u96d1\u306a\u4f5c\u696d\u3092\u3001CUI\u74b0\u5883\u3067\u3042\u308c\u3070\u7c21\u5358\u306a\u30b3\u30de\u30f3\u30c9\u306e\u7d44\u307f\u5408\u308f\u305b\u3067\u5b9f\u884c\u3067\u304d\u308b\u5834\u5408\u3082\u3042\u308b\u306a\u3069\u3001CUI\u306b\u3082\u4f9d\u7136\u3068\u3057\u3066\u5229\u70b9\u306f\u3042\u308b\u3002\u7279\u306b\u30a8\u30f3\u30c9\u30e6\u30fc\u30b6\u30fc\u3060\u3051\u3067\u306a\u304f\u30cd\u30c3\u30c8\u30ef\u30fc\u30af\u7ba1\u7406\u8005\u3084\u30bd\u30d5\u30c8\u30a6\u30a7\u30a2\u958b\u767a\u8005\u3082\u5229\u7528\u3059\u308bPC\u3084\u30b5\u30fc\u30d0\u30fc\u306b\u304a\u3044\u3066\u306f\u3001GUI\u3068CUI\u306f\u7528\u9014\u306b\u3088\u3063\u3066\u4f4f\u307f\u5206\u3051\u3066\u4f75\u5b58\u3057\u3066\u3044\u308b\u3082\u306e\u3067\u3042\u308a\u3001CUI\u306f\u5b8c\u5168\u306b\u5ec3\u308c\u305f\u308f\u3051\u3067\u306f\u306a\u3044\u3002") int x; } String usageMessage = new CommandLine(new App()).getUsageMessage(); String expected = String.format("" + "Usage: cjk [-hV] [-x=<x>]%n" + "12345678901234567890123456789012345678901234567890123456789012345678901234567890%n" + "CUI\u306fGUI\u3068\u6bd4\u3079\u3066\u76f4\u611f\u7684\u306a\u64cd\u4f5c\u304c\u3067\u304d\u306a\u3044\u306a\u3069\u306e\u6b20\u70b9\u304c\u3042\u308b\u3082\u306e\u306e\u3001\u30e1\u30a4\u30f3\u30e1\u30e2\u30ea\u304a\u3088\u3073%n" + "\u30d3\u30c7\u30aa\u30e1\u30e2\u30ea\u306a\u3069\u306e\u30b3\u30f3\u30d4\u30e5\u30fc\u30bf\u8cc7\u6e90\u306e\u6d88\u8cbb\u304c\u5c11\u306a\u3044\u3053\u3068\u304b\u3089\u3001\u6027\u80fd\u306e\u4f4e\u3044\u521d\u671f\u306e\u30b3\u30f3%n" + "\u30d4\u30e5\u30fc\u30bf\u3067\u306fCUI\u306b\u3088\u308b\u5bfe\u8a71\u74b0\u5883\u304c\u4e3b\u6d41\u3060\u3063\u305f\u3002\u305d\u306e\u5f8c\u3001\u30b3\u30f3\u30d4\u30e5\u30fc\u30bf\u306e\u6027\u80fd\u304c\u5411\u4e0a\u3057\u3001%n" + "\u30de\u30a6\u30b9\u306a\u3069\u306e\u30dd\u30a4\u30f3\u30c6\u30a3\u30f3\u30b0\u30c7\u30d0\u30a4\u30b9\u306b\u3088\u3063\u3066\u76f4\u611f\u7684\u306a\u64cd\u4f5c\u306e\u3067\u304d\u308bGUI\u74b0\u5883\u304cMacintosh%n" + "\u3084Windows 95\u306a\u3069\u306b\u3088\u3063\u3066\u30aa\u30d5\u30a3\u30b9\u3084\u4e00\u822c\u5bb6\u5ead\u306b\u3082\u666e\u53ca\u3057\u3001CUI\u306f\u65e2\u5b9a\u306e\u30a4\u30f3\u30bf\u30fc\u30d5\u30a7\u30a4%n" + "\u30b9\u3067\u306f\u306a\u304f\u306a\u3063\u3066\u3044\u3063\u305f\u3002\u30d1\u30fc\u30bd\u30ca\u30eb\u30b3\u30f3\u30d4\u30e5\u30fc\u30bf (PC) \u5411\u3051\u3084\u30b5\u30fc\u30d0\u30fc\u5411\u3051\u306e\u30aa\u30da\u30ec\u30fc%n" + "\u30c6\u30a3\u30f3\u30b0\u30b7\u30b9\u30c6\u30e0 (OS) \u306b\u306f\u3001\u65e2\u5b9a\u306e\u30a4\u30f3\u30bf\u30fc\u30d5\u30a7\u30a4\u30b9\u304cGUI\u3067\u3042\u3063\u3066\u3082\u30b3\u30de\u30f3\u30c9\u30e9\u30a4\u30f3%n" + "\u30bf\u30fc\u30df\u30ca\u30eb\u306a\u3069\u306eCUI\u74b0\u5883\u304c\u4f9d\u7136\u3068\u3057\u3066\u7528\u610f\u3055\u308c\u3066\u3044\u308b\u304c\u3001\u30b9\u30de\u30fc\u30c8\u30d5\u30a9\u30f3\u306a\u3069\u306e\u30e2\u30d0\u30a4%n" + "\u30eb\u7aef\u672b\u5411\u3051OS\u306b\u306f\u6a19\u6e96\u3067\u7528\u610f\u3055\u308c\u3066\u304a\u3089\u305a\u3001GUI\u304c\u4e3b\u6d41\u3068\u306a\u3063\u3066\u3044\u308b\u3002%n" + " -h, --help Show this help message and exit.%n" + " -V, --version Print version information and exit.%n" + " -x, --long=<x> \u3057\u304b\u3057\u3001GUI\u74b0\u5883\u3067\u3042\u308c\u3070\u30dd\u30a4\u30f3\u30c6\u30a3\u30f3\u30b0\u30c7\u30d0\u30a4\u30b9\u306b\u3088\u308b\u64cd\u4f5c\u3092\u7e70\u308a%n" + " \u8fd4\u3057\u884c\u308f\u306a\u3051\u308c\u3070\u306a\u3089\u306a\u3044\u3088\u3046\u306a\u7169\u96d1\u306a\u4f5c\u696d\u3092\u3001CUI\u74b0\u5883\u3067\u3042\u308c\u3070%n" + " \u7c21\u5358\u306a\u30b3\u30de\u30f3\u30c9\u306e\u7d44\u307f\u5408\u308f\u305b\u3067\u5b9f\u884c\u3067\u304d\u308b\u5834\u5408\u3082\u3042\u308b\u306a\u3069\u3001CUI\u306b%n" + " \u3082\u4f9d\u7136\u3068\u3057\u3066\u5229\u70b9\u306f\u3042\u308b\u3002\u7279\u306b\u30a8\u30f3\u30c9\u30e6\u30fc\u30b6\u30fc\u3060\u3051\u3067\u306a\u304f\u30cd\u30c3\u30c8%n" + " \u30ef\u30fc\u30af\u7ba1\u7406\u8005\u3084\u30bd\u30d5\u30c8\u30a6\u30a7\u30a2\u958b\u767a\u8005\u3082\u5229\u7528\u3059\u308bPC\u3084\u30b5\u30fc\u30d0\u30fc\u306b\u304a%n" + " \u3044\u3066\u306f\u3001GUI\u3068CUI\u306f\u7528\u9014\u306b\u3088\u3063\u3066\u4f4f\u307f\u5206\u3051\u3066\u4f75\u5b58\u3057\u3066\u3044\u308b\u3082\u306e\u3067%n" + " \u3042\u308a\u3001CUI\u306f\u5b8c\u5168\u306b\u5ec3\u308c\u305f\u308f\u3051\u3067\u306f\u306a\u3044\u3002%n"); assertEquals(expected, usageMessage); } @Test public void testCharCJKDoubleWidthTextCanBeSwitchedOff() { @Command(name = "cjk", mixinStandardHelpOptions = true, description = { "12345678901234567890123456789012345678901234567890123456789012345678901234567890", "CUI\u306fGUI\u3068\u6bd4\u3079\u3066\u76f4\u611f\u7684\u306a\u64cd\u4f5c\u304c\u3067\u304d\u306a\u3044\u306a\u3069\u306e\u6b20\u70b9\u304c\u3042\u308b\u3082\u306e\u306e\u3001\u30e1\u30a4\u30f3\u30e1\u30e2\u30ea\u304a\u3088\u3073\u30d3\u30c7\u30aa\u30e1\u30e2\u30ea\u306a\u3069\u306e\u30b3\u30f3\u30d4\u30e5\u30fc\u30bf\u8cc7\u6e90\u306e\u6d88\u8cbb\u304c\u5c11\u306a\u3044\u3053\u3068\u304b\u3089\u3001" + "\u6027\u80fd\u306e\u4f4e\u3044\u521d\u671f\u306e\u30b3\u30f3\u30d4\u30e5\u30fc\u30bf\u3067\u306fCUI\u306b\u3088\u308b\u5bfe\u8a71\u74b0\u5883\u304c\u4e3b\u6d41\u3060\u3063\u305f\u3002\u305d\u306e\u5f8c\u3001\u30b3\u30f3\u30d4\u30e5\u30fc\u30bf\u306e\u6027\u80fd\u304c\u5411\u4e0a\u3057\u3001\u30de\u30a6\u30b9\u306a\u3069\u306e\u30dd\u30a4\u30f3\u30c6\u30a3\u30f3\u30b0\u30c7\u30d0\u30a4\u30b9\u306b\u3088\u3063\u3066" + "\u76f4\u611f\u7684\u306a\u64cd\u4f5c\u306e\u3067\u304d\u308bGUI\u74b0\u5883\u304cMacintosh\u3084Windows 95\u306a\u3069\u306b\u3088\u3063\u3066\u30aa\u30d5\u30a3\u30b9\u3084\u4e00\u822c\u5bb6\u5ead\u306b\u3082\u666e\u53ca\u3057\u3001" + "CUI\u306f\u65e2\u5b9a\u306e\u30a4\u30f3\u30bf\u30fc\u30d5\u30a7\u30a4\u30b9\u3067\u306f\u306a\u304f\u306a\u3063\u3066\u3044\u3063\u305f\u3002\u30d1\u30fc\u30bd\u30ca\u30eb\u30b3\u30f3\u30d4\u30e5\u30fc\u30bf (PC) \u5411\u3051\u3084\u30b5\u30fc\u30d0\u30fc\u5411\u3051\u306e\u30aa\u30da\u30ec\u30fc\u30c6\u30a3\u30f3\u30b0\u30b7\u30b9\u30c6\u30e0 (OS) " + "\u306b\u306f\u3001\u65e2\u5b9a\u306e\u30a4\u30f3\u30bf\u30fc\u30d5\u30a7\u30a4\u30b9\u304cGUI\u3067\u3042\u3063\u3066\u3082\u30b3\u30de\u30f3\u30c9\u30e9\u30a4\u30f3\u30bf\u30fc\u30df\u30ca\u30eb\u306a\u3069\u306eCUI\u74b0\u5883\u304c\u4f9d\u7136\u3068\u3057\u3066\u7528\u610f\u3055\u308c\u3066\u3044\u308b\u304c\u3001\u30b9\u30de\u30fc\u30c8\u30d5\u30a9\u30f3\u306a\u3069\u306e\u30e2\u30d0\u30a4\u30eb" + "\u7aef\u672b\u5411\u3051OS\u306b\u306f\u6a19\u6e96\u3067\u7528\u610f\u3055\u308c\u3066\u304a\u3089\u305a\u3001GUI\u304c\u4e3b\u6d41\u3068\u306a\u3063\u3066\u3044\u308b\u3002"}) class App { @Option(names = {"-x", "--long"}, description = "\u3057\u304b\u3057\u3001GUI\u74b0\u5883\u3067\u3042\u308c\u3070\u30dd\u30a4\u30f3\u30c6\u30a3\u30f3\u30b0\u30c7\u30d0\u30a4\u30b9\u306b\u3088\u308b\u64cd\u4f5c\u3092\u7e70\u308a\u8fd4\u3057\u884c\u308f\u306a\u3051\u308c\u3070\u306a\u3089\u306a\u3044\u3088\u3046\u306a\u7169\u96d1\u306a\u4f5c\u696d\u3092\u3001CUI\u74b0\u5883\u3067\u3042\u308c\u3070\u7c21\u5358\u306a\u30b3\u30de\u30f3\u30c9\u306e\u7d44\u307f\u5408\u308f\u305b\u3067\u5b9f\u884c\u3067\u304d\u308b\u5834\u5408\u3082\u3042\u308b\u306a\u3069\u3001CUI\u306b\u3082\u4f9d\u7136\u3068\u3057\u3066\u5229\u70b9\u306f\u3042\u308b\u3002\u7279\u306b\u30a8\u30f3\u30c9\u30e6\u30fc\u30b6\u30fc\u3060\u3051\u3067\u306a\u304f\u30cd\u30c3\u30c8\u30ef\u30fc\u30af\u7ba1\u7406\u8005\u3084\u30bd\u30d5\u30c8\u30a6\u30a7\u30a2\u958b\u767a\u8005\u3082\u5229\u7528\u3059\u308bPC\u3084\u30b5\u30fc\u30d0\u30fc\u306b\u304a\u3044\u3066\u306f\u3001GUI\u3068CUI\u306f\u7528\u9014\u306b\u3088\u3063\u3066\u4f4f\u307f\u5206\u3051\u3066\u4f75\u5b58\u3057\u3066\u3044\u308b\u3082\u306e\u3067\u3042\u308a\u3001CUI\u306f\u5b8c\u5168\u306b\u5ec3\u308c\u305f\u308f\u3051\u3067\u306f\u306a\u3044\u3002") int x; } String usageMessage = new CommandLine(new App()) .setAdjustLineBreaksForWideCJKCharacters(false) .getUsageMessage(); String expected = String.format("" + "Usage: cjk [-hV] [-x=<x>]%n" + "12345678901234567890123456789012345678901234567890123456789012345678901234567890%n" + "CUI\u306fGUI\u3068\u6bd4\u3079\u3066\u76f4\u611f\u7684\u306a\u64cd\u4f5c\u304c\u3067\u304d\u306a\u3044\u306a\u3069\u306e\u6b20\u70b9\u304c\u3042\u308b\u3082\u306e\u306e\u3001\u30e1\u30a4\u30f3\u30e1\u30e2\u30ea\u304a\u3088\u3073\u30d3\u30c7\u30aa\u30e1\u30e2\u30ea\u306a\u3069\u306e\u30b3\u30f3\u30d4\u30e5\u30fc\u30bf\u8cc7\u6e90\u306e\u6d88\u8cbb\u304c\u5c11\u306a\u3044\u3053\u3068\u304b\u3089\u3001\u6027\u80fd\u306e\u4f4e\u3044\u521d\u671f\u306e%n" + "\u30b3\u30f3\u30d4\u30e5\u30fc\u30bf\u3067\u306fCUI\u306b\u3088\u308b\u5bfe\u8a71\u74b0\u5883\u304c\u4e3b\u6d41\u3060\u3063\u305f\u3002\u305d\u306e\u5f8c\u3001\u30b3\u30f3\u30d4\u30e5\u30fc\u30bf\u306e\u6027\u80fd\u304c\u5411\u4e0a\u3057\u3001\u30de\u30a6\u30b9\u306a\u3069\u306e\u30dd\u30a4\u30f3\u30c6\u30a3\u30f3\u30b0\u30c7\u30d0\u30a4\u30b9\u306b\u3088\u3063\u3066\u76f4\u611f\u7684\u306a\u64cd\u4f5c\u306e\u3067\u304d\u308bGUI\u74b0\u5883\u304c%n" + "Macintosh\u3084Windows 95\u306a\u3069\u306b\u3088\u3063\u3066\u30aa\u30d5\u30a3\u30b9\u3084\u4e00\u822c\u5bb6\u5ead\u306b\u3082\u666e\u53ca\u3057\u3001CUI\u306f\u65e2\u5b9a\u306e\u30a4\u30f3\u30bf\u30fc\u30d5\u30a7\u30a4\u30b9\u3067\u306f\u306a\u304f\u306a\u3063\u3066\u3044\u3063\u305f\u3002\u30d1\u30fc\u30bd\u30ca\u30eb\u30b3\u30f3\u30d4\u30e5\u30fc\u30bf (%n" + "PC) \u5411\u3051\u3084\u30b5\u30fc\u30d0\u30fc\u5411\u3051\u306e\u30aa\u30da\u30ec\u30fc\u30c6\u30a3\u30f3\u30b0\u30b7\u30b9\u30c6\u30e0 (OS) \u306b\u306f\u3001\u65e2\u5b9a\u306e\u30a4\u30f3\u30bf\u30fc\u30d5\u30a7\u30a4\u30b9\u304cGUI\u3067\u3042\u3063\u3066\u3082\u30b3\u30de\u30f3\u30c9\u30e9\u30a4\u30f3\u30bf\u30fc\u30df\u30ca\u30eb\u306a\u3069\u306eCUI\u74b0\u5883\u304c\u4f9d\u7136\u3068\u3057%n" + "\u3066\u7528\u610f\u3055\u308c\u3066\u3044\u308b\u304c\u3001\u30b9\u30de\u30fc\u30c8\u30d5\u30a9\u30f3\u306a\u3069\u306e\u30e2\u30d0\u30a4\u30eb\u7aef\u672b\u5411\u3051OS\u306b\u306f\u6a19\u6e96\u3067\u7528\u610f\u3055\u308c\u3066\u304a\u3089\u305a\u3001GUI\u304c\u4e3b\u6d41\u3068\u306a\u3063\u3066\u3044\u308b\u3002%n" + " -h, --help Show this help message and exit.%n" + " -V, --version Print version information and exit.%n" + " -x, --long=<x> \u3057\u304b\u3057\u3001GUI\u74b0\u5883\u3067\u3042\u308c\u3070\u30dd\u30a4\u30f3\u30c6\u30a3\u30f3\u30b0\u30c7\u30d0\u30a4\u30b9\u306b\u3088\u308b\u64cd\u4f5c\u3092\u7e70\u308a\u8fd4\u3057\u884c\u308f\u306a\u3051\u308c\u3070\u306a\u3089\u306a\u3044\u3088\u3046\u306a\u7169\u96d1\u306a\u4f5c\u696d\u3092\u3001CUI\u74b0\u5883\u3067\u3042%n" + " \u308c\u3070\u7c21\u5358\u306a\u30b3\u30de\u30f3\u30c9\u306e\u7d44\u307f\u5408\u308f\u305b\u3067\u5b9f\u884c\u3067\u304d\u308b\u5834\u5408\u3082\u3042\u308b\u306a\u3069\u3001CUI\u306b\u3082\u4f9d\u7136\u3068\u3057\u3066\u5229\u70b9\u306f\u3042\u308b\u3002\u7279\u306b\u30a8\u30f3\u30c9\u30e6\u30fc\u30b6\u30fc\u3060\u3051\u3067\u306a\u304f%n" + " \u30cd\u30c3\u30c8\u30ef\u30fc\u30af\u7ba1\u7406\u8005\u3084\u30bd\u30d5\u30c8\u30a6\u30a7\u30a2\u958b\u767a\u8005\u3082\u5229\u7528\u3059\u308bPC\u3084\u30b5\u30fc\u30d0\u30fc\u306b\u304a\u3044\u3066\u306f\u3001GUI\u3068CUI\u306f\u7528\u9014\u306b\u3088\u3063\u3066\u4f4f\u307f\u5206\u3051\u3066\u4f75\u5b58\u3057%n" + " \u3066\u3044\u308b\u3082\u306e\u3067\u3042\u308a\u3001CUI\u306f\u5b8c\u5168\u306b\u5ec3\u308c\u305f\u308f\u3051\u3067\u306f\u306a\u3044\u3002%n"); assertEquals(expected, usageMessage); } @Test public void testTextTableAjustForWideCJKCharsByDefault() { assertTrue(TextTable.forDefaultColumns(Help.Ansi.OFF, 80).isAdjustLineBreaksForWideCJKCharacters()); assertTrue(TextTable.forColumnWidths(Help.Ansi.OFF, 3, 4, 6, 30).isAdjustLineBreaksForWideCJKCharacters()); assertTrue(TextTable.forDefaultColumns(Help.Ansi.OFF, 20, 80).isAdjustLineBreaksForWideCJKCharacters()); } @Test public void testTextTableAjustForWideCJKCharsByDefaultIsMutable() { TextTable textTable = TextTable.forDefaultColumns(Help.Ansi.OFF, 80); assertTrue(textTable.isAdjustLineBreaksForWideCJKCharacters()); textTable.setAdjustLineBreaksForWideCJKCharacters(false); assertFalse(textTable.isAdjustLineBreaksForWideCJKCharacters()); } @Command(name = "top", subcommands = { SubcommandWithStandardHelpOptions.class, CommandLine.HelpCommand.class }) static class ParentCommandWithRequiredOption implements Runnable { @Option(names = "--required", required = true) String required; public void run() { } } @Command(name = "sub", mixinStandardHelpOptions = true) static class SubcommandWithStandardHelpOptions implements Runnable { public void run() { } } @Ignore @Test // https://github.com/remkop/picocli/issues/743 public void testSubcommandHelpWhenParentCommandHasRequiredOption_743() { CommandLine cmd = new CommandLine(new ParentCommandWithRequiredOption()); cmd.execute("help", "sub"); String expected = String.format("" + "Usage: top sub [-hV]%n" + " -h, --help Show this help message and exit.%n" + " -V, --version Print version information and exit.%n"); assertEquals(expected, this.systemOutRule.getLog()); assertEquals("", this.systemErrRule.getLog()); systemErrRule.clearLog(); systemOutRule.clearLog(); cmd.execute("sub", "--help"); assertEquals("", this.systemErrRule.getLog()); assertEquals(expected, this.systemOutRule.getLog()); } @Test //https://github.com/remkop/picocli/issues/739 public void testIssue739CommandName72Chars() { @Command(name = "123456789012345678901234567890123456789012345678901234567890123456789012", mixinStandardHelpOptions = true) class App { @Option(names = "-a") String aaaaaa; @Option(names = "-b", arity = "2") String[] bbbbbbb; @Option(names = "-c", split = ",") String[] cccccccc; } String expected = String.format("" + "Usage: 123456789012345678901234567890123456789012345678901234567890123456789012%n" + " [-hV] [-a=<aaaaaa>] [-c=<cccccccc>[,<cccccccc>...]]... [-b=<bbbbbbb>%n" + " <bbbbbbb>]...%n" + " -a=<aaaaaa>%n" + " -b=<bbbbbbb> <bbbbbbb>%n" + " -c=<cccccccc>[,<cccccccc>...]%n" + "%n" + " -h, --help Show this help message and exit.%n" + " -V, --version Print version information and exit.%n"); String actual = new CommandLine(new App()).getUsageMessage(); assertEquals(expected, actual); } @Test //https://github.com/remkop/picocli/issues/739 public void testIssue739CommandName73Chars() { @Command(name = "1234567890123456789012345678901234567890123456789012345678901234567890123", mixinStandardHelpOptions = true) class App { @Option(names = "-a") String aaaaaa; @Option(names = "-b", arity = "2") String[] bbbbbbb; @Option(names = "-c", split = ",") String[] cccccccc; } String expected = String.format("" + "Usage: 1234567890123456789012345678901234567890123456789012345678901234567890123%n" + " [-hV] [-a=<aaaaaa>] [-c=<cccccccc>[,<cccccccc>...]]... [-b=<bbbbbbb>%n" + " <bbbbbbb>]...%n" + " -a=<aaaaaa>%n" + " -b=<bbbbbbb> <bbbbbbb>%n" + " -c=<cccccccc>[,<cccccccc>...]%n" + "%n" + " -h, --help Show this help message and exit.%n" + " -V, --version Print version information and exit.%n"); String actual = new CommandLine(new App()).getUsageMessage(); assertEquals(expected, actual); } @Test //https://github.com/remkop/picocli/issues/739 public void testIssue739CommandName80Chars() { @Command(name = "12345678901234567890123456789012345678901234567890123456789012345678901234567890", mixinStandardHelpOptions = true) class App { @Option(names = "-a") String aaaaaa; @Option(names = "-b", arity = "2") String[] bbbbbbb; @Option(names = "-c", split = ",") String[] cccccccc; } String expected = String.format("" + "Usage: 1234567890123456789012345678901234567890123456789012345678901234567890123%n" + " 4567890 [-hV] [-a=<aaaaaa>] [-c=<cccccccc>[,<cccccccc>...]]...%n" + " [-b=<bbbbbbb> <bbbbbbb>]...%n" + " -a=<aaaaaa>%n" + " -b=<bbbbbbb> <bbbbbbb>%n" + " -c=<cccccccc>[,<cccccccc>...]%n" + "%n" + " -h, --help Show this help message and exit.%n" + " -V, --version Print version information and exit.%n"); String actual = new CommandLine(new App()).getUsageMessage(); assertEquals(expected, actual); } @Test //https://github.com/remkop/picocli/issues/739 public void testIssue739CommandName40Chars_customSynopsisMaxIndent() { @Command(name = "1234567890123456789012345678901234567890", mixinStandardHelpOptions = true) class App { @Option(names = "-a") String aaaaaa; @Option(names = "-b", arity = "2") String[] bbbbbbb; @Option(names = "-c", split = ",") String[] cccccccc; } String expected = String.format("" + "Usage: 1234567890123456789012345678901234567890 [-hV] [-a=<aaaaaa>]%n" + " [-c=<cccccccc>[,<cccccccc>...]]...%n" + " [-b=<bbbbbbb> <bbbbbbb>]...%n" + " -a=<aaaaaa>%n" + " -b=<bbbbbbb> <bbbbbbb>%n" + " -c=<cccccccc>[,<cccccccc>...]%n" + "%n" + " -h, --help Show this help message and exit.%n" + " -V, --version Print version information and exit.%n"); CommandLine cmd = new CommandLine(new App()); cmd.getCommandSpec().usageMessage().synopsisAutoIndentThreshold(47.0 / 80); cmd.getCommandSpec().usageMessage().synopsisIndent(40); String actual = cmd.getUsageMessage(); assertEquals(expected, actual); cmd.getCommandSpec().usageMessage().synopsisIndent(20); assertEquals(String.format("" + "Usage: 1234567890123456789012345678901234567890 [-hV] [-a=<aaaaaa>]%n" + " [-c=<cccccccc>[,<cccccccc>...]]... [-b=<bbbbbbb>%n" + " <bbbbbbb>]...%n" + " -a=<aaaaaa>%n" + " -b=<bbbbbbb> <bbbbbbb>%n" + " -c=<cccccccc>[,<cccccccc>...]%n" + "%n" + " -h, --help Show this help message and exit.%n" + " -V, --version Print version information and exit.%n"), cmd.getUsageMessage()); cmd.getCommandSpec().usageMessage().synopsisIndent(-1); assertEquals(String.format("" + "Usage: 1234567890123456789012345678901234567890 [-hV] [-a=<aaaaaa>]%n" + " [-c=<cccccccc>[,<cccccccc>...]]... [-b=<bbbbbbb> <bbbbbbb>]...%n" + " -a=<aaaaaa>%n" + " -b=<bbbbbbb> <bbbbbbb>%n" + " -c=<cccccccc>[,<cccccccc>...]%n" + "%n" + " -h, --help Show this help message and exit.%n" + " -V, --version Print version information and exit.%n"), cmd.getUsageMessage()); } @Test public void testSynopsisAutoIndentThresholdDefault() { assertEquals(0.5, new UsageMessageSpec().synopsisAutoIndentThreshold(), 0.00001); } @Test public void testSynopsisAutoIndentThresholdDisallowsNegativeValue() { try { new UsageMessageSpec().synopsisAutoIndentThreshold(-0.1); fail("Expected exception"); } catch (IllegalArgumentException ex) { assertEquals("synopsisAutoIndentThreshold must be between 0.0 and 0.9 (inclusive), but was -0.1", ex.getMessage()); } } @Test public void testSynopsisAutoIndentThresholdDisallowsValueLargerThan0_9() { try { new UsageMessageSpec().synopsisAutoIndentThreshold(0.90001); fail("Expected exception"); } catch (IllegalArgumentException ex) { assertEquals("synopsisAutoIndentThreshold must be between 0.0 and 0.9 (inclusive), but was 0.90001", ex.getMessage()); } } @Test public void testSynopsisAutoIndentThresholdAcceptsValueZero() { assertEquals(0.0, new UsageMessageSpec().synopsisAutoIndentThreshold(0.0).synopsisAutoIndentThreshold(), 0.0001); } @Test public void testSynopsisAutoIndentThresholdAcceptsValue0_9() { assertEquals(0.9, new UsageMessageSpec().synopsisAutoIndentThreshold(0.9).synopsisAutoIndentThreshold(), 0.0001); } @Test public void testSynopsisIndentDefault() { assertEquals(-1, new UsageMessageSpec().synopsisIndent()); } @Test //https://github.com/remkop/picocli/issues/739 public void testIssue739CommandName32Chars() { @Command(name = "12345678901234567890123456789012", mixinStandardHelpOptions = true) class App { @Option(names = "-a") String aaaaaa; @Option(names = "-b", arity = "2") String[] bbbbbbb; @Option(names = "-c", split = ",") String[] cccccccc; } String expected = String.format("" + "Usage: 12345678901234567890123456789012 [-hV] [-a=<aaaaaa>] [-c=<cccccccc>[,%n" + " <cccccccc>...]]... [-b=<bbbbbbb>%n" + " <bbbbbbb>]...%n" + " -a=<aaaaaa>%n" + " -b=<bbbbbbb> <bbbbbbb>%n" + " -c=<cccccccc>[,<cccccccc>...]%n" + "%n" + " -h, --help Show this help message and exit.%n" + " -V, --version Print version information and exit.%n"); String actual = new CommandLine(new App()).getUsageMessage(); assertEquals(expected, actual); } @Command(name = "showenv", mixinStandardHelpOptions = true, version = "showenv 1.0", description = "Demonstrates a usage help message with " + "an additional section for environment variables.", exitCodeListHeading = "Exit Codes:%n", exitCodeList = { " 0:Successful program execution", "64:Usage error: user input for the command was incorrect, " + "e.g., the wrong number of arguments, a bad flag, " + "a bad syntax in a parameter, etc.", "70:Internal software error: an exception occurred when invoking " + "the business logic of this command." } ) public class EnvironmentVariablesSection { } @Test public void testCustomTabularSection() { String SECTION_KEY_ENV_HEADING = "environmentVariablesHeading"; String SECTION_KEY_ENV_DETAILS = "environmentVariables"; // the data to display final Map<String, String> env = new LinkedHashMap<String, String>(); env.put("FOO", "explanation of foo. If very long, then the line is wrapped and the wrapped line is indented with two spaces."); env.put("BAR", "explanation of bar"); env.put("XYZ", "xxxx yyyy zzz"); // register the custom section renderers CommandLine cmd = new CommandLine(new EnvironmentVariablesSection()); cmd.getHelpSectionMap().put(SECTION_KEY_ENV_HEADING, new IHelpSectionRenderer() { public String render(Help help) { return help.createHeading("Environment Variables:%n"); } }); cmd.getHelpSectionMap().put(SECTION_KEY_ENV_DETAILS, new IHelpSectionRenderer() { public String render(Help help) { return help.createTextTable(env).toString(); } }); // specify the location of the new sections List<String> keys = new ArrayList<String>(cmd.getHelpSectionKeys()); int index = keys.indexOf(CommandLine.Model.UsageMessageSpec.SECTION_KEY_FOOTER_HEADING); keys.add(index, SECTION_KEY_ENV_HEADING); keys.add(index + 1, SECTION_KEY_ENV_DETAILS); cmd.setHelpSectionKeys(keys); String expected = String.format("" + "Usage: showenv [-hV]%n" + "Demonstrates a usage help message with an additional section for environment%n" + "variables.%n" + " -h, --help Show this help message and exit.%n" + " -V, --version Print version information and exit.%n" + "Exit Codes:%n" + " 0 Successful program execution%n" + " 64 Usage error: user input for the command was incorrect, e.g., the wrong%n" + " number of arguments, a bad flag, a bad syntax in a parameter, etc.%n" + " 70 Internal software error: an exception occurred when invoking the%n" + " business logic of this command.%n" + "Environment Variables:%n" + " FOO explanation of foo. If very long, then the line is wrapped and the%n" + " wrapped line is indented with two spaces.%n" + " BAR explanation of bar%n" + " XYZ xxxx yyyy zzz%n"); assertEquals(expected, cmd.getUsageMessage(Help.Ansi.OFF)); } @Test public void testFullSynopsis() { Help help = new Help(CommandSpec.create(), CommandLine.Help.defaultColorScheme(Help.Ansi.OFF)); String syn1 = help.fullSynopsis(); assertEquals(syn1, new Help(CommandSpec.create(), CommandLine.Help.defaultColorScheme(Help.Ansi.OFF)).fullSynopsis()); } }
[#934] added test (incomplete)
src/test/java/picocli/HelpTest.java
[#934] added test (incomplete)
<ide><path>rc/test/java/picocli/HelpTest.java <ide> " description%n"); <ide> assertEquals(expected, actual); <ide> } <del> <add> <ide> @Test <ide> public void testMapFieldHelp_with_unlimitedSplit() { <ide> class App { <ide> ByteArrayOutputStream baos = new ByteArrayOutputStream(); <ide> final PrintStream out = new PrintStream(baos); <ide> assertTrue(CommandLine.printHelpIfRequested(list, out, Help.Ansi.OFF)); <del> <add> <ide> String expected = String.format("" + <ide> "Usage: <main class> [-h]%n" + <ide> " -h%n"); <ide> .commands(Style.bg_cyan) <ide> .options(Style.fg_green) <ide> .parameters(Style.bg_white).build(); <del> <add> <ide> @Command(mixinStandardHelpOptions = true) <ide> class App { <ide> @Option(names = { "-f" }, paramLabel = "ARCHIVE", description = "the archive file") File archive; <ide> ByteArrayOutputStream baos = new ByteArrayOutputStream(); <ide> final PrintStream out = new PrintStream(baos); <ide> assertTrue(CommandLine.printHelpIfRequested(list, out, out, customColorScheme)); <del> <add> <ide> String expected = Help.Ansi.ON.string(String.format("" + <ide> "Usage: @|bg_cyan <main class>|@ [@|green -hV|@] [@|green -f|@=@|magenta ARCHIVE|@] @|bg_white POSITIONAL|@%n" + <ide> "@|bg_white |@ @|bg_white POSITIONAL|@ positional arg%n" + <ide> String syn1 = help.fullSynopsis(); <ide> assertEquals(syn1, new Help(CommandSpec.create(), CommandLine.Help.defaultColorScheme(Help.Ansi.OFF)).fullSynopsis()); <ide> } <add> <add> @Ignore("#934") <add> @Test <add> public void testConfigurableLongOptionsColumnLength() { <add> @Command(name = "myapp", mixinStandardHelpOptions = true) <add> class MyApp { <add> @Option(names = {"-o", "--out"}, description = "Output location full path") <add> File outputFolder; <add> <add> //public static void main(String[] args) { <add> // new CommandLine(new MyApp()) <add> // .setUsageHelpLongOptionsMaxWidth(25) <add> // .execute(args); <add> //} <add> } <add> new CommandLine(new MyApp()).usage(System.out); <add> String expected = String.format("" + <add> "Usage: myapp [-hV] [-o=<outputFolder>]%n" + <add> " -h, --help Show this help message and exit.%n" + <add> " -o, --output=<outputFolder>%n" + <add> " Output location full path%n" + <add> " -V, --version Print version information and exit.%n"); <add> assertEquals("", this.systemOutRule.getLog()); <add> } <ide> }
Java
mit
1518b81841ce686854dd01b7cc67640f88d259de
0
SLIBIO/SLib,SLIBIO/SLib,SLIBIO/SLib,SLIBIO/SLib,SLIBIO/SLib
/* * Copyright (c) 2008-2018 SLIBIO <https://github.com/SLIBIO> * * 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 slib.platform.android; import android.util.Log; public class Logger { public static void exception(Throwable e) { Log.e("EXCEPTION", e.getMessage(), e); } public static void warning(String warning) { Log.w("WARNING", warning); } public static void info(String info) { Log.i("INFO", info); } public static void debug(String info) { Log.d("DEBUG", info); } public static void error(String error) { Log.e("ERROR", error); } }
java/android/slib/platform/android/Logger.java
/* * Copyright (c) 2008-2018 SLIBIO <https://github.com/SLIBIO> * * 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 slib.platform.android; import android.util.Log; public class Logger { public static void exception(Throwable e) { Log.e("Exception", e.getMessage(), e); } public static void warning(String warning) { Log.w("Warning", warning); } public static void info(String info) { Log.d("INFO", info); } public static void error(String error) { Log.e("Error", error); } }
minor update
java/android/slib/platform/android/Logger.java
minor update
<ide><path>ava/android/slib/platform/android/Logger.java <ide> public class Logger { <ide> <ide> public static void exception(Throwable e) { <del> Log.e("Exception", e.getMessage(), e); <add> Log.e("EXCEPTION", e.getMessage(), e); <ide> } <ide> <ide> public static void warning(String warning) { <del> Log.w("Warning", warning); <add> Log.w("WARNING", warning); <ide> } <ide> <ide> public static void info(String info) { <del> Log.d("INFO", info); <add> Log.i("INFO", info); <ide> } <del> <add> <add> public static void debug(String info) { <add> Log.d("DEBUG", info); <add> } <add> <ide> public static void error(String error) { <del> Log.e("Error", error); <add> Log.e("ERROR", error); <ide> } <ide> <ide> }
Java
apache-2.0
8a0dc768740cf7ae091514c994e9a859bcab7c1e
0
cinovo/cloudconductor-agent-redhat,cinovo/cloudconductor-agent-redhat
package de.cinovo.cloudconductor.agent.executors; /* * #%L * Node Agent for cloudconductor framework * %% * Copyright (C) 2013 - 2014 Cinovo AG * %% * 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. * #L% */ import de.cinovo.cloudconductor.agent.exceptions.ExecutionError; import de.cinovo.cloudconductor.agent.executors.helper.AbstractExecutor; import de.cinovo.cloudconductor.api.model.PackageVersion; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /** * Copyright 2013 Cinovo AG<br> * <br> * * @author psigloch */ public class InstalledPackages extends AbstractExecutor<List<PackageVersion>> { private static final String cmdYum = "yum list installed"; private static final String delimiter = ";"; private final Logger logger = LoggerFactory.getLogger(this.getClass()); private List<PackageVersion> result = new ArrayList<>(); @Override protected Process genProcess() throws IOException { return Runtime.getRuntime().exec(InstalledPackages.cmdYum); } @Override protected void analyzeStream(String[] dev, String[] error) throws ExecutionError { if(error.length > 0) { throw new ExecutionError("Error while collecting installed packages"); } this.logger.debug("Found installed packages: "); for(String str : dev) { str = str.replaceAll("\\s+", delimiter); String[] arr = str.split(InstalledPackages.delimiter); String pkg = arr[0].split("\\.")[0]; String version = arr[1].split(":")[arr[1].split(":").length - 1]; String repo = arr[2].replace("@", ""); PackageVersion packageVersion = new PackageVersion(pkg, version, null); Set<String> repos = new HashSet<>(); repos.add(repo); packageVersion.setRepos(repos); this.logger.debug(pkg + " - " + version + " - " + repo); this.result.add(packageVersion); } } @Override public List<PackageVersion> getResult() { return this.result; } }
src/main/java/de/cinovo/cloudconductor/agent/executors/InstalledPackages.java
package de.cinovo.cloudconductor.agent.executors; /* * #%L * Node Agent for cloudconductor framework * %% * Copyright (C) 2013 - 2014 Cinovo AG * %% * 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. * #L% */ import java.io.IOException; import java.util.ArrayList; import java.util.List; import de.cinovo.cloudconductor.agent.exceptions.ExecutionError; import de.cinovo.cloudconductor.agent.executors.helper.AbstractExecutor; import de.cinovo.cloudconductor.api.model.PackageVersion; /** * Copyright 2013 Cinovo AG<br> * <br> * * @author psigloch * */ public class InstalledPackages extends AbstractExecutor<List<PackageVersion>> { private static final String cmd = "rpm -qa --queryformat %{NAME};%{VERSION}-%{RELEASE}\\n"; private static final String delimiter = ";"; private List<PackageVersion> result = new ArrayList<>(); @Override protected Process genProcess() throws IOException { return Runtime.getRuntime().exec(InstalledPackages.cmd); } @Override protected void analyzeStream(String[] dev, String[] error) throws ExecutionError { if (error.length > 0) { throw new ExecutionError("Error while collecting installed packages"); } for (String str : dev) { String[] arr = str.split(InstalledPackages.delimiter); this.result.add(new PackageVersion(arr[0], arr[1], null)); } } @Override public List<PackageVersion> getResult() { return this.result; } }
adds better installed package discovery
src/main/java/de/cinovo/cloudconductor/agent/executors/InstalledPackages.java
adds better installed package discovery
<ide><path>rc/main/java/de/cinovo/cloudconductor/agent/executors/InstalledPackages.java <ide> * %% <ide> * Licensed under the Apache License, Version 2.0 (the <ide> * "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at <del> * <add> * <ide> * http://www.apache.org/licenses/LICENSE-2.0 <del> * <add> * <ide> * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, <ide> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions <ide> * and limitations under the License. <ide> * #L% <ide> */ <ide> <del>import java.io.IOException; <del>import java.util.ArrayList; <del>import java.util.List; <del> <ide> import de.cinovo.cloudconductor.agent.exceptions.ExecutionError; <ide> import de.cinovo.cloudconductor.agent.executors.helper.AbstractExecutor; <ide> import de.cinovo.cloudconductor.api.model.PackageVersion; <add>import org.slf4j.Logger; <add>import org.slf4j.LoggerFactory; <add> <add>import java.io.IOException; <add>import java.util.ArrayList; <add>import java.util.HashSet; <add>import java.util.List; <add>import java.util.Set; <ide> <ide> /** <ide> * Copyright 2013 Cinovo AG<br> <ide> * <br> <del> * <add> * <ide> * @author psigloch <del> * <ide> */ <ide> public class InstalledPackages extends AbstractExecutor<List<PackageVersion>> { <del> <del> private static final String cmd = "rpm -qa --queryformat %{NAME};%{VERSION}-%{RELEASE}\\n"; <add> private static final String cmdYum = "yum list installed"; <ide> private static final String delimiter = ";"; <add> <add> private final Logger logger = LoggerFactory.getLogger(this.getClass()); <add> <ide> private List<PackageVersion> result = new ArrayList<>(); <del> <del> <add> <add> <ide> @Override <ide> protected Process genProcess() throws IOException { <del> return Runtime.getRuntime().exec(InstalledPackages.cmd); <add> return Runtime.getRuntime().exec(InstalledPackages.cmdYum); <ide> } <del> <add> <ide> @Override <ide> protected void analyzeStream(String[] dev, String[] error) throws ExecutionError { <del> if (error.length > 0) { <add> if(error.length > 0) { <ide> throw new ExecutionError("Error while collecting installed packages"); <ide> } <del> for (String str : dev) { <add> this.logger.debug("Found installed packages: "); <add> for(String str : dev) { <add> str = str.replaceAll("\\s+", delimiter); <ide> String[] arr = str.split(InstalledPackages.delimiter); <del> this.result.add(new PackageVersion(arr[0], arr[1], null)); <add> String pkg = arr[0].split("\\.")[0]; <add> String version = arr[1].split(":")[arr[1].split(":").length - 1]; <add> String repo = arr[2].replace("@", ""); <add> PackageVersion packageVersion = new PackageVersion(pkg, version, null); <add> Set<String> repos = new HashSet<>(); <add> repos.add(repo); <add> packageVersion.setRepos(repos); <add> this.logger.debug(pkg + " - " + version + " - " + repo); <add> this.result.add(packageVersion); <ide> } <ide> } <del> <add> <ide> @Override <ide> public List<PackageVersion> getResult() { <ide> return this.result;
Java
apache-2.0
322246b7472d45c0a269bde908c766b1fdb8ce15
0
MichaelVose2/uPortal,ASU-Capstone/uPortal,GIP-RECIA/esup-uportal,apetro/uPortal,EsupPortail/esup-uportal,bjagg/uPortal,doodelicious/uPortal,stalele/uPortal,jl1955/uPortal5,groybal/uPortal,groybal/uPortal,andrewstuart/uPortal,GIP-RECIA/esco-portail,EdiaEducationTechnology/uPortal,jhelmer-unicon/uPortal,phillips1021/uPortal,stalele/uPortal,jameswennmacher/uPortal,GIP-RECIA/esup-uportal,vertein/uPortal,vbonamy/esup-uportal,andrewstuart/uPortal,EsupPortail/esup-uportal,Jasig/SSP-Platform,timlevett/uPortal,apetro/uPortal,joansmith/uPortal,Jasig/uPortal,EdiaEducationTechnology/uPortal,apetro/uPortal,ASU-Capstone/uPortal-Forked,doodelicious/uPortal,andrewstuart/uPortal,drewwills/uPortal,pspaude/uPortal,GIP-RECIA/esup-uportal,jhelmer-unicon/uPortal,cousquer/uPortal,Jasig/uPortal-start,andrewstuart/uPortal,joansmith/uPortal,Jasig/uPortal-start,vertein/uPortal,Jasig/SSP-Platform,drewwills/uPortal,stalele/uPortal,apetro/uPortal,mgillian/uPortal,jhelmer-unicon/uPortal,GIP-RECIA/esup-uportal,drewwills/uPortal,GIP-RECIA/esco-portail,ChristianMurphy/uPortal,MichaelVose2/uPortal,Mines-Albi/esup-uportal,phillips1021/uPortal,MichaelVose2/uPortal,chasegawa/uPortal,EsupPortail/esup-uportal,pspaude/uPortal,kole9273/uPortal,jl1955/uPortal5,ASU-Capstone/uPortal-Forked,kole9273/uPortal,chasegawa/uPortal,mgillian/uPortal,pspaude/uPortal,ChristianMurphy/uPortal,EdiaEducationTechnology/uPortal,bjagg/uPortal,timlevett/uPortal,ASU-Capstone/uPortal-Forked,jl1955/uPortal5,doodelicious/uPortal,vbonamy/esup-uportal,joansmith/uPortal,kole9273/uPortal,kole9273/uPortal,cousquer/uPortal,ASU-Capstone/uPortal,jonathanmtran/uPortal,GIP-RECIA/esup-uportal,vertein/uPortal,phillips1021/uPortal,stalele/uPortal,timlevett/uPortal,Jasig/SSP-Platform,cousquer/uPortal,ASU-Capstone/uPortal,ASU-Capstone/uPortal,pspaude/uPortal,mgillian/uPortal,jameswennmacher/uPortal,groybal/uPortal,phillips1021/uPortal,EdiaEducationTechnology/uPortal,groybal/uPortal,Mines-Albi/esup-uportal,stalele/uPortal,jameswennmacher/uPortal,jl1955/uPortal5,ASU-Capstone/uPortal-Forked,Jasig/SSP-Platform,doodelicious/uPortal,vertein/uPortal,joansmith/uPortal,jhelmer-unicon/uPortal,ASU-Capstone/uPortal-Forked,MichaelVose2/uPortal,jonathanmtran/uPortal,vbonamy/esup-uportal,Jasig/uPortal,GIP-RECIA/esco-portail,Mines-Albi/esup-uportal,EsupPortail/esup-uportal,jonathanmtran/uPortal,vbonamy/esup-uportal,timlevett/uPortal,joansmith/uPortal,kole9273/uPortal,Jasig/SSP-Platform,chasegawa/uPortal,doodelicious/uPortal,jameswennmacher/uPortal,groybal/uPortal,EsupPortail/esup-uportal,drewwills/uPortal,andrewstuart/uPortal,Mines-Albi/esup-uportal,chasegawa/uPortal,Jasig/uPortal,chasegawa/uPortal,MichaelVose2/uPortal,ASU-Capstone/uPortal,bjagg/uPortal,jhelmer-unicon/uPortal,phillips1021/uPortal,vbonamy/esup-uportal,jl1955/uPortal5,ChristianMurphy/uPortal,apetro/uPortal,Mines-Albi/esup-uportal,jameswennmacher/uPortal
/** * Copyright 2001 The JA-SIG Collaborative. 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. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the JA-SIG Collaborative * (http://www.jasig.org/)." * * THIS SOFTWARE IS PROVIDED BY THE JA-SIG COLLABORATIVE "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 JA-SIG COLLABORATIVE 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. * */ package org.jasig.portal.channels.groupsmanager; import org.jasig.portal.security.IAuthorizationPrincipal; import org.jasig.portal.security.IPerson; import org.w3c.dom.Document; /** * Session data that is a subset of CGroupsManagerSessionData. * * @author Don Fracapane * @version $Revision$ */ public class CGroupsManagerUnrestrictedSessionData implements GroupsManagerConstants { public Document model; public IPerson user; public boolean isAdminUser; public IGroupsManagerPermissions gmPermissions; public IAuthorizationPrincipal authPrincipal; /** * Creates new CGroupsManagerUnrestrictedSessionData */ public CGroupsManagerUnrestrictedSessionData () {} /** * Creates new CGroupsManagerUnrestrictedSessionData * @param model Document * @param user IPerson * @param isAdminUser boolean * @param gmPermissions IGroupsManagerPermissions * @param authPrincipal IAuthorizationPrincipal */ public CGroupsManagerUnrestrictedSessionData (Document model, IPerson user, boolean isAdminUser, IGroupsManagerPermissions gmPermissions, IAuthorizationPrincipal authPrincipal) { this.model = model; this.user = user; this.isAdminUser = isAdminUser; this.gmPermissions = gmPermissions; this.authPrincipal = authPrincipal; } }
source/org/jasig/portal/channels/groupsmanager/CGroupsManagerUnrestrictedSessionData.java
/** * Copyright 2001 The JA-SIG Collaborative. 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. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the JA-SIG Collaborative * (http://www.jasig.org/)." * * THIS SOFTWARE IS PROVIDED BY THE JA-SIG COLLABORATIVE "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 JA-SIG COLLABORATIVE 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. * */ package org.jasig.portal.channels.groupsmanager; import org.jasig.portal.security.IAuthorizationPrincipal; import org.jasig.portal.security.IPerson; import org.w3c.dom.Document; /** * Session data that is a subset of CGroupsManagerSessionData. * @author Don Fracapane * @version $Revision$ */ public class CGroupsManagerUnrestrictedSessionData implements GroupsManagerConstants { public Document model; public IPerson user; public boolean isAdminUser; public IGroupsManagerPermissions gmPermissions; public IAuthorizationPrincipal authPrincipal; /** Creates new CGroupsManagerUnrestrictedSessionData */ public CGroupsManagerUnrestrictedSessionData () {} /** Creates new CGroupsManagerUnrestrictedSessionData * @param model Document * @param user IPerson * @param isAdminUser boolean * @param gmPermissions IGroupsManagerPermissions * @param authPrincipal IAuthorizationPrincipal * @return an <code>CGroupsManagerUnrestrictedSessionData</code> object */ public CGroupsManagerUnrestrictedSessionData (Document model, IPerson user, boolean isAdminUser, IGroupsManagerPermissions gmPermissions, IAuthorizationPrincipal authPrincipal) { this.model = model; this.user = user; this.isAdminUser = isAdminUser; this.gmPermissions = gmPermissions; this.authPrincipal = authPrincipal; } }
javadoc clean up git-svn-id: 477788cc2a8229a747c5b8073e47c1d0f6ec0604@7304 f5dbab47-78f9-eb45-b975-e544023573eb
source/org/jasig/portal/channels/groupsmanager/CGroupsManagerUnrestrictedSessionData.java
javadoc clean up
<ide><path>ource/org/jasig/portal/channels/groupsmanager/CGroupsManagerUnrestrictedSessionData.java <ide> <ide> /** <ide> * Session data that is a subset of CGroupsManagerSessionData. <add> * <ide> * @author Don Fracapane <ide> * @version $Revision$ <ide> */ <ide> public IGroupsManagerPermissions gmPermissions; <ide> public IAuthorizationPrincipal authPrincipal; <ide> <del> /** Creates new CGroupsManagerUnrestrictedSessionData <add> /** <add> * Creates new CGroupsManagerUnrestrictedSessionData <ide> */ <ide> public CGroupsManagerUnrestrictedSessionData () {} <ide> <del> /** Creates new CGroupsManagerUnrestrictedSessionData <add> /** <add> * Creates new CGroupsManagerUnrestrictedSessionData <ide> * @param model Document <ide> * @param user IPerson <ide> * @param isAdminUser boolean <ide> * @param gmPermissions IGroupsManagerPermissions <ide> * @param authPrincipal IAuthorizationPrincipal <del> * @return an <code>CGroupsManagerUnrestrictedSessionData</code> object <ide> */ <ide> public CGroupsManagerUnrestrictedSessionData (Document model, IPerson user, boolean isAdminUser, <ide> IGroupsManagerPermissions gmPermissions, IAuthorizationPrincipal authPrincipal) {
Java
apache-2.0
241adf92dd4797b1223825068312ee728f615193
0
sepetnit/j-heuristic-search-framework,sepetnit/j-heuristic-search-framework
package org.cs4j.core.domains; import org.cs4j.core.collections.PairInt; import java.io.*; import java.util.ArrayList; import java.util.List; import java.util.Random; /** * This class contains general util functions that are required in more than a single domain * * All the functions in this class are defined as static * */ public class Utils { /** * Recursive implementation of factorial * * @param n Compute fact(n) * * @return Value of n! calculation */ public static int fact(int n) { if (n == 1) { return 1; } return n * fact(n -1); } /** * Returns an array of the given size which contains a number 0..max-1 (randomly shuffled) in each cell * * @param size The size of the required array * * @return The created array */ public static int[] getRandomIntegerListArray(int size, int max, Random rand) { if (rand == null) { rand = new Random(); } // For each box, determine the initial pile int[] toReturn = new int[size]; for (int i = 0; i < toReturn.length; ++i) { toReturn[i] = rand.nextInt(max); } return toReturn; } /** * Converts a given list that contains Integer objects, to an array of ints * * @param list The input list * * @return An array of integers (int) that contains all the elements in list */ public static int[] integerListToArray(List<Integer> list) { int[] toReturn = new int[list.size()]; int index = 0; for (int element : list) { toReturn[index++] = element; } return toReturn; } /** * Converts a given list that contains Double objects, to an array of doubles * * @param list The input list * * @return An array of doubles (double) that contains all the elements in list */ public static double[] doubleListToArray(List<Double> list) { double[] toReturn = new double[list.size()]; int index = 0; for (double element : list) { toReturn[index++] = element; } return toReturn; } /** * An opposite function of {@see integerListToArray} - converts an array of integers to a list * * @param array The array to convert * * @return The result list of integers */ public static List<Integer> intArrayToIntegerList(int[] array) { List<Integer> toReturn = new ArrayList<>(array.length); for (int current : array) { toReturn.add(current); } return toReturn; } /** * Calculates Manhattan distance between two locations * * @param xy The first location * @param ij The second location * * @return The calculated Manhattan distance */ public static int calcManhattanDistance(PairInt xy, PairInt ij) { // Calculate Manhattan distance to the location int xDistance = Math.abs(xy.first - ij.first); int yDistance = Math.abs(xy.second - ij.second); return xDistance + yDistance; } /** * Calculates the log2 value of the given number * * @param x The input number for the calculation * @return The calculated value */ public static double log2(int x) { return Math.log(x) / Math.log(2); } /** * Calculates the required number of bits in order to store a given number * * @param number The number to store * * @return The calculated bit count */ public static int bits(int number) { return (int) Math.ceil(Utils.log2(number)); } /** * An auxiliary function that computes the bitmask of the required number of bits * * @param bits The number of bits whose bit-mask should be computed * @return The calculated bit-mask */ public static long mask(int bits) { return ~((~0) << bits); } /** * An auxiliary function for throwing some fatal error and exit * * @param msg The message to print before exiting */ public static void fatal(String msg) { System.err.println(msg); System.exit(1); } /** * Reads the whole given file into a string * * @param file The file to read * @return The read bytes of the file * * @throws IOException If something wrong occurred */ public static String fileToString(File file) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file))); StringBuilder sb = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { sb.append(line).append("\n"); } reader.close(); return sb.toString(); } /** * Reads the whole given file into a string * * @param filename The file to read * @return The read bytes of the file * * @throws IOException If something wrong occurred */ public static String fileToString(String filename) throws IOException { return Utils.fileToString(new File(filename)); } }
src/main/java/org/cs4j/core/domains/Utils.java
package org.cs4j.core.domains; import org.cs4j.core.collections.PairInt; import java.io.*; import java.util.ArrayList; import java.util.List; import java.util.Random; /** * This class contains general util functions that are required in more than a single domain * * All the functions in this class are defined as static * */ public class Utils { /** * Recursive implementation of factorial * * @param n Compute fact(n) * * @return Value of n! calculation */ public static int fact(int n) { if (n == 1) { return 1; } return n * fact(n -1); } /** * Returns an array of the given size which contains a number 0..max-1 (randomly shuffled) in each cell * * @param size The size of the required array * * @return The created array */ public static int[] getRandomIntegerListArray(int size, int max, Random rand) { if (rand == null) { rand = new Random(); } // For each box, determine the initial pile int[] toReturn = new int[size]; for (int i = 0; i < toReturn.length; ++i) { toReturn[i] = rand.nextInt(max); } return toReturn; } /** * Converts a given list that contains Integer objects, to an array of ints * * @param list The input list * * @return An array of integers (int) that contains all the elements in list */ public static int[] integerListToArray(List<Integer> list) { int[] toReturn = new int[list.size()]; int index = 0; for (int element : list) { toReturn[index++] = element; } return toReturn; } /** * An opposite function of {@see integerListToArray} - converts an array of integers to a list * * @param array The array to convert * * @return The result list of integers */ public static List<Integer> intArrayToIntegerList(int[] array) { List<Integer> toReturn = new ArrayList<>(array.length); for (int current : array) { toReturn.add(current); } return toReturn; } /** * Calculates Manhattan distance between two locations * * @param xy The first location * @param ij The second location * * @return The calculated Manhattan distance */ public static int calcManhattanDistance(PairInt xy, PairInt ij) { // Calculate Manhattan distance to the location int xDistance = Math.abs(xy.first - ij.first); int yDistance = Math.abs(xy.second - ij.second); return xDistance + yDistance; } /** * Calculates the log2 value of the given number * * @param x The input number for the calculation * @return The calculated value */ public static double log2(int x) { return Math.log(x) / Math.log(2); } /** * Calculates the required number of bits in order to store a given number * * @param number The number to store * * @return The calculated bit count */ public static int bits(int number) { return (int) Math.ceil(Utils.log2(number)); } /** * An auxiliary function that computes the bitmask of the required number of bits * * @param bits The number of bits whose bit-mask should be computed * @return The calculated bit-mask */ public static long mask(int bits) { return ~((~0) << bits); } /** * An auxiliary function for throwing some fatal error and exit * * @param msg The message to print before exiting */ public static void fatal(String msg) { System.err.println(msg); System.exit(1); } /** * Reads the whole given file into a string * * @param file The file to read * @return The read bytes of the file * * @throws IOException If something wrong occurred */ public static String fileToString(File file) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file))); StringBuilder sb = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { sb.append(line).append("\n"); } reader.close(); return sb.toString(); } /** * Reads the whole given file into a string * * @param filename The file to read * @return The read bytes of the file * * @throws IOException If something wrong occurred */ public static String fileToString(String filename) throws IOException { return Utils.fileToString(new File(filename)); } }
Added doubleListToArray function
src/main/java/org/cs4j/core/domains/Utils.java
Added doubleListToArray function
<ide><path>rc/main/java/org/cs4j/core/domains/Utils.java <ide> int[] toReturn = new int[list.size()]; <ide> int index = 0; <ide> for (int element : list) { <add> toReturn[index++] = element; <add> } <add> return toReturn; <add> } <add> <add> /** <add> * Converts a given list that contains Double objects, to an array of doubles <add> * <add> * @param list The input list <add> * <add> * @return An array of doubles (double) that contains all the elements in list <add> */ <add> public static double[] doubleListToArray(List<Double> list) { <add> double[] toReturn = new double[list.size()]; <add> int index = 0; <add> for (double element : list) { <ide> toReturn[index++] = element; <ide> } <ide> return toReturn;
Java
apache-2.0
ddc8b77a1d27d0f8a911eb9f28a905ba461680a6
0
AndroidX/androidx,androidx/androidx,AndroidX/androidx,AndroidX/androidx,androidx/androidx,androidx/androidx,AndroidX/androidx,androidx/androidx,androidx/androidx,AndroidX/androidx,androidx/androidx,AndroidX/androidx,AndroidX/androidx,AndroidX/androidx,androidx/androidx,androidx/androidx,androidx/androidx,androidx/androidx,AndroidX/androidx,AndroidX/androidx
/* * Copyright 2018 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 androidx.loader.content; import android.content.Context; import android.os.AsyncTask; import android.os.Handler; import android.os.SystemClock; import android.text.format.DateUtils; import android.util.Log; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.core.os.OperationCanceledException; import java.io.FileDescriptor; import java.io.PrintWriter; import java.util.concurrent.Executor; import java.util.concurrent.TimeUnit; /** * Static library support version of the framework's {@link android.content.AsyncTaskLoader}. * Used to write apps that run on platforms prior to Android 3.0. When running * on Android 3.0 or above, this implementation is still used; it does not try * to switch to the framework's implementation. See the framework SDK * documentation for a class overview. */ public abstract class AsyncTaskLoader<D> extends Loader<D> { static final String TAG = "AsyncTaskLoader"; static final boolean DEBUG = false; final class LoadTask extends ModernAsyncTask<D> implements Runnable { // Set to true to indicate that the task has been posted to a handler for // execution at a later time. Used to throttle updates. boolean waiting; /* Runs on a worker thread */ @Override protected D doInBackground() { if (DEBUG) Log.v(TAG, this + " >>> doInBackground"); try { D data = AsyncTaskLoader.this.onLoadInBackground(); if (DEBUG) Log.v(TAG, this + " <<< doInBackground"); return data; } catch (OperationCanceledException ex) { if (!isCancelled()) { // onLoadInBackground threw a canceled exception spuriously. // This is problematic because it means that the LoaderManager did not // cancel the Loader itself and still expects to receive a result. // Additionally, the Loader's own state will not have been updated to // reflect the fact that the task was being canceled. // So we treat this case as an unhandled exception. throw ex; } if (DEBUG) Log.v(TAG, this + " <<< doInBackground (was canceled)", ex); return null; } } /* Runs on the UI thread */ @Override protected void onPostExecute(D data) { if (DEBUG) Log.v(TAG, this + " onPostExecute"); AsyncTaskLoader.this.dispatchOnLoadComplete(this, data); } /* Runs on the UI thread */ @Override protected void onCancelled(D data) { if (DEBUG) Log.v(TAG, this + " onCancelled"); AsyncTaskLoader.this.dispatchOnCancelled(this, data); } /* Runs on the UI thread, when the waiting task is posted to a handler. * This method is only executed when task execution was deferred (waiting was true). */ @Override public void run() { waiting = false; AsyncTaskLoader.this.executePendingTask(); } } private Executor mExecutor; volatile LoadTask mTask; volatile LoadTask mCancellingTask; long mUpdateThrottle; long mLastLoadCompleteTime = -10000; Handler mHandler; public AsyncTaskLoader(@NonNull Context context) { super(context); } /** * Set amount to throttle updates by. This is the minimum time from * when the last {@link #loadInBackground()} call has completed until * a new load is scheduled. * * @param delayMS Amount of delay, in milliseconds. */ public void setUpdateThrottle(long delayMS) { mUpdateThrottle = delayMS; if (delayMS != 0) { mHandler = new Handler(); } } @Override protected void onForceLoad() { super.onForceLoad(); cancelLoad(); mTask = new LoadTask(); if (DEBUG) Log.v(TAG, "Preparing load: mTask=" + mTask); executePendingTask(); } @Override protected boolean onCancelLoad() { if (DEBUG) Log.v(TAG, "onCancelLoad: mTask=" + mTask); if (mTask != null) { if (!mStarted) { mContentChanged = true; } if (mCancellingTask != null) { // There was a pending task already waiting for a previous // one being canceled; just drop it. if (DEBUG) Log.v(TAG, "cancelLoad: still waiting for cancelled task; dropping next"); if (mTask.waiting) { mTask.waiting = false; mHandler.removeCallbacks(mTask); } mTask = null; return false; } else if (mTask.waiting) { // There is a task, but it is waiting for the time it should // execute. We can just toss it. if (DEBUG) Log.v(TAG, "cancelLoad: task is waiting, dropping it"); mTask.waiting = false; mHandler.removeCallbacks(mTask); mTask = null; return false; } else { boolean cancelled = mTask.cancel(false); if (DEBUG) Log.v(TAG, "cancelLoad: cancelled=" + cancelled); if (cancelled) { mCancellingTask = mTask; cancelLoadInBackground(); } mTask = null; return cancelled; } } return false; } /** * Called if the task was canceled before it was completed. Gives the class a chance * to clean up post-cancellation and to properly dispose of the result. * * @param data The value that was returned by {@link #loadInBackground}, or null * if the task threw {@link OperationCanceledException}. */ public void onCanceled(@Nullable D data) { } void executePendingTask() { if (mCancellingTask == null && mTask != null) { if (mTask.waiting) { mTask.waiting = false; mHandler.removeCallbacks(mTask); } if (mUpdateThrottle > 0) { long now = SystemClock.uptimeMillis(); if (now < (mLastLoadCompleteTime+mUpdateThrottle)) { // Not yet time to do another load. if (DEBUG) Log.v(TAG, "Waiting until " + (mLastLoadCompleteTime+mUpdateThrottle) + " to execute: " + mTask); mTask.waiting = true; mHandler.postAtTime(mTask, mLastLoadCompleteTime+mUpdateThrottle); return; } } if (DEBUG) Log.v(TAG, "Executing: " + mTask); if (mExecutor == null) { mExecutor = getExecutor(); } mTask.executeOnExecutor(mExecutor); } } void dispatchOnCancelled(LoadTask task, D data) { onCanceled(data); if (mCancellingTask == task) { if (DEBUG) Log.v(TAG, "Cancelled task is now canceled!"); rollbackContentChanged(); mLastLoadCompleteTime = SystemClock.uptimeMillis(); mCancellingTask = null; if (DEBUG) Log.v(TAG, "Delivering cancellation"); deliverCancellation(); executePendingTask(); } } void dispatchOnLoadComplete(LoadTask task, D data) { if (mTask != task) { if (DEBUG) Log.v(TAG, "Load complete of old task, trying to cancel"); dispatchOnCancelled(task, data); } else { if (isAbandoned()) { // This cursor has been abandoned; just cancel the new data. onCanceled(data); } else { commitContentChanged(); mLastLoadCompleteTime = SystemClock.uptimeMillis(); mTask = null; if (DEBUG) Log.v(TAG, "Delivering result"); deliverResult(data); } } } /** * Called on a worker thread to perform the actual load and to return * the result of the load operation. * * Implementations should not deliver the result directly, but should return them * from this method, which will eventually end up calling {@link #deliverResult} on * the UI thread. If implementations need to process the results on the UI thread * they may override {@link #deliverResult} and do so there. * * To support cancellation, this method should periodically check the value of * {@link #isLoadInBackgroundCanceled} and terminate when it returns true. * Subclasses may also override {@link #cancelLoadInBackground} to interrupt the load * directly instead of polling {@link #isLoadInBackgroundCanceled}. * * When the load is canceled, this method may either return normally or throw * {@link OperationCanceledException}. In either case, the {@link Loader} will * call {@link #onCanceled} to perform post-cancellation cleanup and to dispose of the * result object, if any. * * @return The result of the load operation. * * @throws OperationCanceledException if the load is canceled during execution. * * @see #isLoadInBackgroundCanceled * @see #cancelLoadInBackground * @see #onCanceled */ @Nullable public abstract D loadInBackground(); /** * Calls {@link #loadInBackground()}. * * This method is reserved for use by the loader framework. * Subclasses should override {@link #loadInBackground} instead of this method. * * @return The result of the load operation. * * @throws OperationCanceledException if the load is canceled during execution. * * @see #loadInBackground */ @Nullable protected D onLoadInBackground() { return loadInBackground(); } /** * Called on the main thread to abort a load in progress. * * Override this method to abort the current invocation of {@link #loadInBackground} * that is running in the background on a worker thread. * * This method should do nothing if {@link #loadInBackground} has not started * running or if it has already finished. * * @see #loadInBackground */ public void cancelLoadInBackground() { } /** * Returns true if the current invocation of {@link #loadInBackground} is being canceled. * * @return True if the current invocation of {@link #loadInBackground} is being canceled. * * @see #loadInBackground */ public boolean isLoadInBackgroundCanceled() { return mCancellingTask != null; } /** * Returns the {@link Executor} to use for this {@link Loader}'s {@link AsyncTask}s. * By default {@link AsyncTask#THREAD_POOL_EXECUTOR} will be used. * * Override this method to return a custom executor. Note that this method will only be called * once before this {@link Loader}'s first {@link AsyncTask} is run. It is up to the * {@link Loader} to shut down the {@link Executor} at the appropriate place * (e.g. in {@link #onAbandon()}) if necessary. * * @return the {@link Executor} to use for this {@link Loader}'s {@link AsyncTask}s. */ @NonNull protected Executor getExecutor() { return AsyncTask.THREAD_POOL_EXECUTOR; } @Override @Deprecated public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) { super.dump(prefix, fd, writer, args); if (mTask != null) { writer.print(prefix); writer.print("mTask="); writer.print(mTask); writer.print(" waiting="); writer.println(mTask.waiting); } if (mCancellingTask != null) { writer.print(prefix); writer.print("mCancellingTask="); writer.print(mCancellingTask); writer.print(" waiting="); writer.println(mCancellingTask.waiting); } if (mUpdateThrottle != 0) { writer.print(prefix); writer.print("mUpdateThrottle="); writer.print(DateUtils.formatElapsedTime( TimeUnit.MILLISECONDS.toSeconds(mUpdateThrottle))); writer.print(" mLastLoadCompleteTime="); writer.print(mLastLoadCompleteTime == -10000 ? "--" : "-" + DateUtils.formatElapsedTime(TimeUnit.MILLISECONDS.toSeconds( SystemClock.uptimeMillis() - mLastLoadCompleteTime))); writer.println(); } } }
loader/src/main/java/androidx/loader/content/AsyncTaskLoader.java
/* * Copyright 2018 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 androidx.loader.content; import static androidx.annotation.RestrictTo.Scope.LIBRARY_GROUP; import android.content.Context; import android.os.AsyncTask; import android.os.Handler; import android.os.SystemClock; import android.text.format.DateUtils; import android.util.Log; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.RestrictTo; import androidx.core.os.OperationCanceledException; import java.io.FileDescriptor; import java.io.PrintWriter; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executor; import java.util.concurrent.TimeUnit; /** * Static library support version of the framework's {@link android.content.AsyncTaskLoader}. * Used to write apps that run on platforms prior to Android 3.0. When running * on Android 3.0 or above, this implementation is still used; it does not try * to switch to the framework's implementation. See the framework SDK * documentation for a class overview. */ public abstract class AsyncTaskLoader<D> extends Loader<D> { static final String TAG = "AsyncTaskLoader"; static final boolean DEBUG = false; final class LoadTask extends ModernAsyncTask<D> implements Runnable { private final CountDownLatch mDone = new CountDownLatch(1); // Set to true to indicate that the task has been posted to a handler for // execution at a later time. Used to throttle updates. boolean waiting; /* Runs on a worker thread */ @Override protected D doInBackground() { if (DEBUG) Log.v(TAG, this + " >>> doInBackground"); try { D data = AsyncTaskLoader.this.onLoadInBackground(); if (DEBUG) Log.v(TAG, this + " <<< doInBackground"); return data; } catch (OperationCanceledException ex) { if (!isCancelled()) { // onLoadInBackground threw a canceled exception spuriously. // This is problematic because it means that the LoaderManager did not // cancel the Loader itself and still expects to receive a result. // Additionally, the Loader's own state will not have been updated to // reflect the fact that the task was being canceled. // So we treat this case as an unhandled exception. throw ex; } if (DEBUG) Log.v(TAG, this + " <<< doInBackground (was canceled)", ex); return null; } } /* Runs on the UI thread */ @Override protected void onPostExecute(D data) { if (DEBUG) Log.v(TAG, this + " onPostExecute"); try { AsyncTaskLoader.this.dispatchOnLoadComplete(this, data); } finally { mDone.countDown(); } } /* Runs on the UI thread */ @Override protected void onCancelled(D data) { if (DEBUG) Log.v(TAG, this + " onCancelled"); try { AsyncTaskLoader.this.dispatchOnCancelled(this, data); } finally { mDone.countDown(); } } /* Runs on the UI thread, when the waiting task is posted to a handler. * This method is only executed when task execution was deferred (waiting was true). */ @Override public void run() { waiting = false; AsyncTaskLoader.this.executePendingTask(); } /* Used for testing purposes to wait for the task to complete. */ public void waitForLoader() { try { mDone.await(); } catch (InterruptedException e) { // Ignore } } } private Executor mExecutor; volatile LoadTask mTask; volatile LoadTask mCancellingTask; long mUpdateThrottle; long mLastLoadCompleteTime = -10000; Handler mHandler; public AsyncTaskLoader(@NonNull Context context) { super(context); } /** * Set amount to throttle updates by. This is the minimum time from * when the last {@link #loadInBackground()} call has completed until * a new load is scheduled. * * @param delayMS Amount of delay, in milliseconds. */ public void setUpdateThrottle(long delayMS) { mUpdateThrottle = delayMS; if (delayMS != 0) { mHandler = new Handler(); } } @Override protected void onForceLoad() { super.onForceLoad(); cancelLoad(); mTask = new LoadTask(); if (DEBUG) Log.v(TAG, "Preparing load: mTask=" + mTask); executePendingTask(); } @Override protected boolean onCancelLoad() { if (DEBUG) Log.v(TAG, "onCancelLoad: mTask=" + mTask); if (mTask != null) { if (!mStarted) { mContentChanged = true; } if (mCancellingTask != null) { // There was a pending task already waiting for a previous // one being canceled; just drop it. if (DEBUG) Log.v(TAG, "cancelLoad: still waiting for cancelled task; dropping next"); if (mTask.waiting) { mTask.waiting = false; mHandler.removeCallbacks(mTask); } mTask = null; return false; } else if (mTask.waiting) { // There is a task, but it is waiting for the time it should // execute. We can just toss it. if (DEBUG) Log.v(TAG, "cancelLoad: task is waiting, dropping it"); mTask.waiting = false; mHandler.removeCallbacks(mTask); mTask = null; return false; } else { boolean cancelled = mTask.cancel(false); if (DEBUG) Log.v(TAG, "cancelLoad: cancelled=" + cancelled); if (cancelled) { mCancellingTask = mTask; cancelLoadInBackground(); } mTask = null; return cancelled; } } return false; } /** * Called if the task was canceled before it was completed. Gives the class a chance * to clean up post-cancellation and to properly dispose of the result. * * @param data The value that was returned by {@link #loadInBackground}, or null * if the task threw {@link OperationCanceledException}. */ public void onCanceled(@Nullable D data) { } void executePendingTask() { if (mCancellingTask == null && mTask != null) { if (mTask.waiting) { mTask.waiting = false; mHandler.removeCallbacks(mTask); } if (mUpdateThrottle > 0) { long now = SystemClock.uptimeMillis(); if (now < (mLastLoadCompleteTime+mUpdateThrottle)) { // Not yet time to do another load. if (DEBUG) Log.v(TAG, "Waiting until " + (mLastLoadCompleteTime+mUpdateThrottle) + " to execute: " + mTask); mTask.waiting = true; mHandler.postAtTime(mTask, mLastLoadCompleteTime+mUpdateThrottle); return; } } if (DEBUG) Log.v(TAG, "Executing: " + mTask); if (mExecutor == null) { mExecutor = getExecutor(); } mTask.executeOnExecutor(mExecutor); } } void dispatchOnCancelled(LoadTask task, D data) { onCanceled(data); if (mCancellingTask == task) { if (DEBUG) Log.v(TAG, "Cancelled task is now canceled!"); rollbackContentChanged(); mLastLoadCompleteTime = SystemClock.uptimeMillis(); mCancellingTask = null; if (DEBUG) Log.v(TAG, "Delivering cancellation"); deliverCancellation(); executePendingTask(); } } void dispatchOnLoadComplete(LoadTask task, D data) { if (mTask != task) { if (DEBUG) Log.v(TAG, "Load complete of old task, trying to cancel"); dispatchOnCancelled(task, data); } else { if (isAbandoned()) { // This cursor has been abandoned; just cancel the new data. onCanceled(data); } else { commitContentChanged(); mLastLoadCompleteTime = SystemClock.uptimeMillis(); mTask = null; if (DEBUG) Log.v(TAG, "Delivering result"); deliverResult(data); } } } /** * Called on a worker thread to perform the actual load and to return * the result of the load operation. * * Implementations should not deliver the result directly, but should return them * from this method, which will eventually end up calling {@link #deliverResult} on * the UI thread. If implementations need to process the results on the UI thread * they may override {@link #deliverResult} and do so there. * * To support cancellation, this method should periodically check the value of * {@link #isLoadInBackgroundCanceled} and terminate when it returns true. * Subclasses may also override {@link #cancelLoadInBackground} to interrupt the load * directly instead of polling {@link #isLoadInBackgroundCanceled}. * * When the load is canceled, this method may either return normally or throw * {@link OperationCanceledException}. In either case, the {@link Loader} will * call {@link #onCanceled} to perform post-cancellation cleanup and to dispose of the * result object, if any. * * @return The result of the load operation. * * @throws OperationCanceledException if the load is canceled during execution. * * @see #isLoadInBackgroundCanceled * @see #cancelLoadInBackground * @see #onCanceled */ @Nullable public abstract D loadInBackground(); /** * Calls {@link #loadInBackground()}. * * This method is reserved for use by the loader framework. * Subclasses should override {@link #loadInBackground} instead of this method. * * @return The result of the load operation. * * @throws OperationCanceledException if the load is canceled during execution. * * @see #loadInBackground */ @Nullable protected D onLoadInBackground() { return loadInBackground(); } /** * Called on the main thread to abort a load in progress. * * Override this method to abort the current invocation of {@link #loadInBackground} * that is running in the background on a worker thread. * * This method should do nothing if {@link #loadInBackground} has not started * running or if it has already finished. * * @see #loadInBackground */ public void cancelLoadInBackground() { } /** * Returns true if the current invocation of {@link #loadInBackground} is being canceled. * * @return True if the current invocation of {@link #loadInBackground} is being canceled. * * @see #loadInBackground */ public boolean isLoadInBackgroundCanceled() { return mCancellingTask != null; } /** * Returns the {@link Executor} to use for this {@link Loader}'s {@link AsyncTask}s. * By default {@link AsyncTask#THREAD_POOL_EXECUTOR} will be used. * * Override this method to return a custom executor. Note that this method will only be called * once before this {@link Loader}'s first {@link AsyncTask} is run. It is up to the * {@link Loader} to shut down the {@link Executor} at the appropriate place * (e.g. in {@link #onAbandon()}) if necessary. * * @return the {@link Executor} to use for this {@link Loader}'s {@link AsyncTask}s. */ @NonNull protected Executor getExecutor() { return AsyncTask.THREAD_POOL_EXECUTOR; } /** * Locks the current thread until the loader completes the current load * operation. Returns immediately if there is no load operation running. * Should not be called from the UI thread: calling it from the UI * thread would cause a deadlock. * <p> * Use for testing only. <b>Never</b> call this from a UI thread. * * @hide */ @RestrictTo(LIBRARY_GROUP) public void waitForLoader() { LoadTask task = mTask; if (task != null) { task.waitForLoader(); } } @Override @Deprecated public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) { super.dump(prefix, fd, writer, args); if (mTask != null) { writer.print(prefix); writer.print("mTask="); writer.print(mTask); writer.print(" waiting="); writer.println(mTask.waiting); } if (mCancellingTask != null) { writer.print(prefix); writer.print("mCancellingTask="); writer.print(mCancellingTask); writer.print(" waiting="); writer.println(mCancellingTask.waiting); } if (mUpdateThrottle != 0) { writer.print(prefix); writer.print("mUpdateThrottle="); writer.print(DateUtils.formatElapsedTime( TimeUnit.MILLISECONDS.toSeconds(mUpdateThrottle))); writer.print(" mLastLoadCompleteTime="); writer.print(mLastLoadCompleteTime == -10000 ? "--" : "-" + DateUtils.formatElapsedTime(TimeUnit.MILLISECONDS.toSeconds( SystemClock.uptimeMillis() - mLastLoadCompleteTime))); writer.println(); } } }
Remove unused RestrictTo(LIBRARY_GROUP) APIs from Loaders This API was not used internally and was never available externally. Test: ./gradlew bOS Change-Id: I93863d722c260133ba79a7690483d78a07432e78
loader/src/main/java/androidx/loader/content/AsyncTaskLoader.java
Remove unused RestrictTo(LIBRARY_GROUP) APIs from Loaders
<ide><path>oader/src/main/java/androidx/loader/content/AsyncTaskLoader.java <ide> <ide> package androidx.loader.content; <ide> <del>import static androidx.annotation.RestrictTo.Scope.LIBRARY_GROUP; <del> <ide> import android.content.Context; <ide> import android.os.AsyncTask; <ide> import android.os.Handler; <ide> <ide> import androidx.annotation.NonNull; <ide> import androidx.annotation.Nullable; <del>import androidx.annotation.RestrictTo; <ide> import androidx.core.os.OperationCanceledException; <ide> <ide> import java.io.FileDescriptor; <ide> import java.io.PrintWriter; <del>import java.util.concurrent.CountDownLatch; <ide> import java.util.concurrent.Executor; <ide> import java.util.concurrent.TimeUnit; <ide> <ide> static final boolean DEBUG = false; <ide> <ide> final class LoadTask extends ModernAsyncTask<D> implements Runnable { <del> private final CountDownLatch mDone = new CountDownLatch(1); <del> <ide> // Set to true to indicate that the task has been posted to a handler for <ide> // execution at a later time. Used to throttle updates. <ide> boolean waiting; <ide> @Override <ide> protected void onPostExecute(D data) { <ide> if (DEBUG) Log.v(TAG, this + " onPostExecute"); <del> try { <del> AsyncTaskLoader.this.dispatchOnLoadComplete(this, data); <del> } finally { <del> mDone.countDown(); <del> } <add> AsyncTaskLoader.this.dispatchOnLoadComplete(this, data); <ide> } <ide> <ide> /* Runs on the UI thread */ <ide> @Override <ide> protected void onCancelled(D data) { <ide> if (DEBUG) Log.v(TAG, this + " onCancelled"); <del> try { <del> AsyncTaskLoader.this.dispatchOnCancelled(this, data); <del> } finally { <del> mDone.countDown(); <del> } <add> AsyncTaskLoader.this.dispatchOnCancelled(this, data); <ide> } <ide> <ide> /* Runs on the UI thread, when the waiting task is posted to a handler. <ide> public void run() { <ide> waiting = false; <ide> AsyncTaskLoader.this.executePendingTask(); <del> } <del> <del> /* Used for testing purposes to wait for the task to complete. */ <del> public void waitForLoader() { <del> try { <del> mDone.await(); <del> } catch (InterruptedException e) { <del> // Ignore <del> } <ide> } <ide> } <ide> <ide> return AsyncTask.THREAD_POOL_EXECUTOR; <ide> } <ide> <del> /** <del> * Locks the current thread until the loader completes the current load <del> * operation. Returns immediately if there is no load operation running. <del> * Should not be called from the UI thread: calling it from the UI <del> * thread would cause a deadlock. <del> * <p> <del> * Use for testing only. <b>Never</b> call this from a UI thread. <del> * <del> * @hide <del> */ <del> @RestrictTo(LIBRARY_GROUP) <del> public void waitForLoader() { <del> LoadTask task = mTask; <del> if (task != null) { <del> task.waitForLoader(); <del> } <del> } <del> <ide> @Override <ide> @Deprecated <ide> public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
Java
epl-1.0
0f62a2973cb7eac660bdfc6335a2d031065a3ece
0
amolenaar/fitnesse,rbevers/fitnesse,amolenaar/fitnesse,jdufner/fitnesse,amolenaar/fitnesse,hansjoachim/fitnesse,hansjoachim/fitnesse,rbevers/fitnesse,jdufner/fitnesse,jdufner/fitnesse,rbevers/fitnesse,hansjoachim/fitnesse
package fitnesse.wiki.fs; import java.io.File; import java.io.IOException; import java.util.List; import org.hamcrest.Matcher; import org.junit.Before; import org.junit.Test; import fitnesse.wiki.*; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.Matchers.hasSize; import static org.junit.Assert.*; public class WikiFilePageTest { private FileSystem fileSystem; private VersionsController versionsController; private WikiPage root; @Before public void setUp() throws Exception { fileSystem = new MemoryFileSystem(); versionsController = new SimpleFileVersionsController(fileSystem); root = new FileSystemPageFactory(fileSystem, versionsController).makePage(new File("root"), "root", null, new SystemVariableSource()); } @Test public void pagesShouldBeListedByOldStyleParentPage() throws IOException { File wikiPageFile = new File("root", "testPage.wiki"); fileSystem.makeFile(wikiPageFile, "page content"); final List<WikiPage> children = root.getChildren(); assertThat(children, hasSize(1)); assertThat(((WikiFilePage) children.get(0)).getFileSystemPath().getPath(), is("root" + File.separator + "testPage")); assertThat(children.get(0).getName(), is("testPage")); } @Test public void pagesWithSubPagesShouldNotBeListedTwice() throws IOException { File wikiPageFile = new File("root", "testPage.wiki"); File subWikiPageFile = new File("root", "testPage/subPage.wiki"); fileSystem.makeFile(wikiPageFile, "page content"); fileSystem.makeFile(subWikiPageFile, "page content"); final List<WikiPage> children = root.getChildren(); assertThat(children, hasSize(1)); assertThat(((WikiFilePage) children.get(0)).getFileSystemPath().getPath(), is("root" + File.separator + "testPage")); assertThat(children.get(0).getName(), is("testPage")); } @Test public void removePageWithoutSubPages() throws IOException { File wikiPageFile = new File("root", "testPage.wiki"); fileSystem.makeFile(wikiPageFile, "page content"); final WikiPage testPage = this.root.getChildPage("testPage"); testPage.remove(); assertFalse(fileSystem.exists(wikiPageFile)); } @Test public void removePageWithSubPages() throws IOException { File wikiPageFile = new File("root", "testPage.wiki"); File subWikiPageFile1 = new File("root", "testPage/sub1.wiki"); File subWikiPageFile2 = new File("root", "testPage/sub2.wiki"); fileSystem.makeFile(wikiPageFile, "page content"); fileSystem.makeFile(subWikiPageFile1, "page content"); fileSystem.makeFile(subWikiPageFile2, "page content"); final WikiPage testPage = this.root.getChildPage("testPage"); testPage.remove(); assertFalse(fileSystem.exists(wikiPageFile)); assertFalse(fileSystem.exists(subWikiPageFile1)); assertFalse(fileSystem.exists(subWikiPageFile2)); } @Test public void loadRootPageContent() throws IOException { fileSystem.makeDirectory(new File("root")); fileSystem.makeFile(new File("root", "_root.wiki"), "root page content"); root = new FileSystemPageFactory(fileSystem, versionsController).makePage(new File("root"), "root", null, new SystemVariableSource()); assertThat(root.getData().getContent(), is("root page content")); } @Test public void loadPageContent() throws IOException { fileSystem.makeFile(new File("root", "testPage.wiki"), "page content"); final WikiPage testPage = root.getChildPage("testPage"); assertThat(testPage.getData().getContent(), is("page content")); } @Test public void loadPageProperties() throws IOException { fileSystem.makeFile(new File("root", "testPage.wiki"), "page content"); final WikiPage testPage = root.getChildPage("testPage"); final WikiPageProperty properties = testPage.getData().getProperties(); assertThat(properties.getProperty(WikiPageProperty.EDIT), is(not(nullValue()))); } @Test public void loadPageWithFrontMatter() throws IOException { fileSystem.makeFile(new File("root", "testPage.wiki"), "---\n" + "Test\n" + "Help: text comes here\n" + "---\n" + "page content"); final WikiPage testPage = root.getChildPage("testPage"); String content = testPage.getData().getContent(); final WikiPageProperty properties = testPage.getData().getProperties(); assertThat(content, is("page content")); assertThat("Test", properties.get("Test"), isPresent()); assertThat("Help", properties.get("Help"), is("text comes here")); } @Test public void loadPageWithFrontMatterCanUnsetProperties() throws IOException { fileSystem.makeFile(new File("root", "testPage.wiki"), "---\n" + "Files: no\n" + "---\n" + "page content"); final WikiPage testPage = root.getChildPage("testPage"); String content = testPage.getData().getContent(); final WikiPageProperty properties = testPage.getData().getProperties(); assertThat(content, is("page content")); assertThat("Files", properties.get("Files"), isNotPresent()); } @Test public void loadPageWithFrontMatterWithSymbolicLinks() throws IOException { fileSystem.makeFile(new File("root", "testPage.wiki"), "---\n" + "SymbolicLinks:\n" + " Linked: SomePage\n" + "---\n" + "page content"); final WikiPage testPage = root.getChildPage("testPage"); String content = testPage.getData().getContent(); final WikiPageProperty properties = testPage.getData().getProperties(); assertThat(content, is("page content")); assertThat("SymbolicLinks", properties.getProperty("SymbolicLinks").get("Linked"), is("SomePage")); } @Test public void loadPageWithEmptyLineInFrontMatter() throws IOException { fileSystem.makeFile(new File("root", "testPage.wiki"), "---\n" + "\n" + "---\n" + "page content"); final WikiPage testPage = root.getChildPage("testPage"); String content = testPage.getData().getContent(); assertThat(content, is("page content")); } @Test public void loadPageWithFrontMatterAndDashesInContent() throws IOException { fileSystem.makeFile(new File("root", "testPage.wiki"), "---\n" + "\n" + "---\n" + "\n" + "---\n"); final WikiPage testPage = root.getChildPage("testPage"); String content = testPage.getData().getContent(); assertThat(content, is("\n---\n")); } @Test public void updateWikiFile() throws IOException { File wikiPageFile = new File("root", "testPage.wiki"); fileSystem.makeFile(wikiPageFile, "page content"); final WikiPage testPage = root.getChildPage("testPage"); PageData data = testPage.getData(); data.setContent("updated!"); testPage.commit(data); final String content = fileSystem.getContent(wikiPageFile); assertThat(content, is("updated!")); } @Test public void updateWikiFileWithPropertiesChanged() throws IOException { File wikiPageFile = new File("root", "testPage.wiki"); fileSystem.makeFile(wikiPageFile, "page content"); final WikiPage testPage = root.getChildPage("testPage"); PageData data = testPage.getData(); data.setContent("updated!"); data.getProperties().set("Test"); data.getProperties().set("Help", "foo"); data.getProperties().remove("Edit"); testPage.commit(data); final String content = fileSystem.getContent(wikiPageFile); assertThat(content, is( "---\n" + "Edit: no\n" + "Help: foo\n" + "Test\n" + "---\n" + "updated!")); } @Test public void updateWikiFileWithSymLinks() throws IOException { File wikiPageFile = new File("root", "testPage.wiki"); fileSystem.makeFile(wikiPageFile, "page content"); final WikiPage testPage = root.getChildPage("testPage"); PageData data = testPage.getData(); final WikiPageProperty symlinks = data.getProperties().set(SymbolicPage.PROPERTY_NAME); symlinks.set("PageOne", "RemotePage"); symlinks.set("PageTwo", "AnotherRemotePage"); testPage.commit(data); final String content = fileSystem.getContent(wikiPageFile); assertThat(content, is( "---\n" + "SymbolicLinks\n" + " PageOne: RemotePage\n" + " PageTwo: AnotherRemotePage\n" + "---\n" + "page content")); } @Test public void readWikiFileWithFrontMatterButNoContent() throws IOException { File wikiPageFile = new File("root", "testPage.wiki"); fileSystem.makeFile(wikiPageFile, "---\n" + "Test\n" + "---\n"); final WikiPage testPage = root.getChildPage("testPage"); PageData data = testPage.getData(); assertThat(data.getContent(), is("")); } @Test public void pageLoadShouldNotLoadRootPage() throws IOException { File rootWikiPageFile = new File("root", "_root.wiki"); File wikiPageFile = new File("root", "testPage.wiki"); fileSystem.makeFile(rootWikiPageFile, "test"); fileSystem.makeFile(wikiPageFile, "test"); final List<WikiPage> children = root.getChildren(); assertThat(children, hasSize(1)); assertThat(children.get(0).getName(), is("testPage")); } private Matcher<? super String> isPresent() { return is(not(nullValue())); } private Matcher<? super String> isNotPresent() { return is(nullValue()); } }
test/fitnesse/wiki/fs/WikiFilePageTest.java
package fitnesse.wiki.fs; import java.io.File; import java.io.IOException; import java.util.List; import org.hamcrest.Matcher; import org.junit.Before; import org.junit.Test; import fitnesse.wiki.*; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.Matchers.hasSize; import static org.junit.Assert.*; public class WikiFilePageTest { private FileSystem fileSystem; private VersionsController versionsController; private WikiPage root; @Before public void setUp() throws Exception { fileSystem = new MemoryFileSystem(); versionsController = new SimpleFileVersionsController(fileSystem); root = new FileSystemPageFactory(fileSystem, versionsController).makePage(new File("root"), "root", null, new SystemVariableSource()); } @Test public void pagesShouldBeListedByOldStyleParentPage() throws IOException { File wikiPageFile = new File("root", "testPage.wiki"); fileSystem.makeFile(wikiPageFile, "page content"); final List<WikiPage> children = root.getChildren(); assertThat(children, hasSize(1)); assertThat(((WikiFilePage) children.get(0)).getFileSystemPath().getPath(), is("root/testPage")); assertThat(children.get(0).getName(), is("testPage")); } @Test public void pagesWithSubPagesShouldNotBeListedTwice() throws IOException { File wikiPageFile = new File("root", "testPage.wiki"); File subWikiPageFile = new File("root", "testPage/subPage.wiki"); fileSystem.makeFile(wikiPageFile, "page content"); fileSystem.makeFile(subWikiPageFile, "page content"); final List<WikiPage> children = root.getChildren(); assertThat(children, hasSize(1)); assertThat(((WikiFilePage) children.get(0)).getFileSystemPath().getPath(), is("root/testPage")); assertThat(children.get(0).getName(), is("testPage")); } @Test public void removePageWithoutSubPages() throws IOException { File wikiPageFile = new File("root", "testPage.wiki"); fileSystem.makeFile(wikiPageFile, "page content"); final WikiPage testPage = this.root.getChildPage("testPage"); testPage.remove(); assertFalse(fileSystem.exists(wikiPageFile)); } @Test public void removePageWithSubPages() throws IOException { File wikiPageFile = new File("root", "testPage.wiki"); File subWikiPageFile1 = new File("root", "testPage/sub1.wiki"); File subWikiPageFile2 = new File("root", "testPage/sub2.wiki"); fileSystem.makeFile(wikiPageFile, "page content"); fileSystem.makeFile(subWikiPageFile1, "page content"); fileSystem.makeFile(subWikiPageFile2, "page content"); final WikiPage testPage = this.root.getChildPage("testPage"); testPage.remove(); assertFalse(fileSystem.exists(wikiPageFile)); assertFalse(fileSystem.exists(subWikiPageFile1)); assertFalse(fileSystem.exists(subWikiPageFile2)); } @Test public void loadRootPageContent() throws IOException { fileSystem.makeDirectory(new File("root")); fileSystem.makeFile(new File("root", "_root.wiki"), "root page content"); root = new FileSystemPageFactory(fileSystem, versionsController).makePage(new File("root"), "root", null, new SystemVariableSource()); assertThat(root.getData().getContent(), is("root page content")); } @Test public void loadPageContent() throws IOException { fileSystem.makeFile(new File("root", "testPage.wiki"), "page content"); final WikiPage testPage = root.getChildPage("testPage"); assertThat(testPage.getData().getContent(), is("page content")); } @Test public void loadPageProperties() throws IOException { fileSystem.makeFile(new File("root", "testPage.wiki"), "page content"); final WikiPage testPage = root.getChildPage("testPage"); final WikiPageProperty properties = testPage.getData().getProperties(); assertThat(properties.getProperty(WikiPageProperty.EDIT), is(not(nullValue()))); } @Test public void loadPageWithFrontMatter() throws IOException { fileSystem.makeFile(new File("root", "testPage.wiki"), "---\n" + "Test\n" + "Help: text comes here\n" + "---\n" + "page content"); final WikiPage testPage = root.getChildPage("testPage"); String content = testPage.getData().getContent(); final WikiPageProperty properties = testPage.getData().getProperties(); assertThat(content, is("page content")); assertThat("Test", properties.get("Test"), isPresent()); assertThat("Help", properties.get("Help"), is("text comes here")); } @Test public void loadPageWithFrontMatterCanUnsetProperties() throws IOException { fileSystem.makeFile(new File("root", "testPage.wiki"), "---\n" + "Files: no\n" + "---\n" + "page content"); final WikiPage testPage = root.getChildPage("testPage"); String content = testPage.getData().getContent(); final WikiPageProperty properties = testPage.getData().getProperties(); assertThat(content, is("page content")); assertThat("Files", properties.get("Files"), isNotPresent()); } @Test public void loadPageWithFrontMatterWithSymbolicLinks() throws IOException { fileSystem.makeFile(new File("root", "testPage.wiki"), "---\n" + "SymbolicLinks:\n" + " Linked: SomePage\n" + "---\n" + "page content"); final WikiPage testPage = root.getChildPage("testPage"); String content = testPage.getData().getContent(); final WikiPageProperty properties = testPage.getData().getProperties(); assertThat(content, is("page content")); assertThat("SymbolicLinks", properties.getProperty("SymbolicLinks").get("Linked"), is("SomePage")); } @Test public void loadPageWithEmptyLineInFrontMatter() throws IOException { fileSystem.makeFile(new File("root", "testPage.wiki"), "---\n" + "\n" + "---\n" + "page content"); final WikiPage testPage = root.getChildPage("testPage"); String content = testPage.getData().getContent(); assertThat(content, is("page content")); } @Test public void loadPageWithFrontMatterAndDashesInContent() throws IOException { fileSystem.makeFile(new File("root", "testPage.wiki"), "---\n" + "\n" + "---\n" + "\n" + "---\n"); final WikiPage testPage = root.getChildPage("testPage"); String content = testPage.getData().getContent(); assertThat(content, is("\n---\n")); } @Test public void updateWikiFile() throws IOException { File wikiPageFile = new File("root", "testPage.wiki"); fileSystem.makeFile(wikiPageFile, "page content"); final WikiPage testPage = root.getChildPage("testPage"); PageData data = testPage.getData(); data.setContent("updated!"); testPage.commit(data); final String content = fileSystem.getContent(wikiPageFile); assertThat(content, is("updated!")); } @Test public void updateWikiFileWithPropertiesChanged() throws IOException { File wikiPageFile = new File("root", "testPage.wiki"); fileSystem.makeFile(wikiPageFile, "page content"); final WikiPage testPage = root.getChildPage("testPage"); PageData data = testPage.getData(); data.setContent("updated!"); data.getProperties().set("Test"); data.getProperties().set("Help", "foo"); data.getProperties().remove("Edit"); testPage.commit(data); final String content = fileSystem.getContent(wikiPageFile); assertThat(content, is( "---\n" + "Edit: no\n" + "Help: foo\n" + "Test\n" + "---\n" + "updated!")); } @Test public void updateWikiFileWithSymLinks() throws IOException { File wikiPageFile = new File("root", "testPage.wiki"); fileSystem.makeFile(wikiPageFile, "page content"); final WikiPage testPage = root.getChildPage("testPage"); PageData data = testPage.getData(); final WikiPageProperty symlinks = data.getProperties().set(SymbolicPage.PROPERTY_NAME); symlinks.set("PageOne", "RemotePage"); symlinks.set("PageTwo", "AnotherRemotePage"); testPage.commit(data); final String content = fileSystem.getContent(wikiPageFile); assertThat(content, is( "---\n" + "SymbolicLinks\n" + " PageOne: RemotePage\n" + " PageTwo: AnotherRemotePage\n" + "---\n" + "page content")); } @Test public void readWikiFileWithFrontMatterButNoContent() throws IOException { File wikiPageFile = new File("root", "testPage.wiki"); fileSystem.makeFile(wikiPageFile, "---\n" + "Test\n" + "---\n"); final WikiPage testPage = root.getChildPage("testPage"); PageData data = testPage.getData(); assertThat(data.getContent(), is("")); } @Test public void pageLoadShouldNotLoadRootPage() throws IOException { File rootWikiPageFile = new File("root", "_root.wiki"); File wikiPageFile = new File("root", "testPage.wiki"); fileSystem.makeFile(rootWikiPageFile, "test"); fileSystem.makeFile(wikiPageFile, "test"); final List<WikiPage> children = root.getChildren(); assertThat(children, hasSize(1)); assertThat(children.get(0).getName(), is("testPage")); } private Matcher<? super String> isPresent() { return is(not(nullValue())); } private Matcher<? super String> isNotPresent() { return is(nullValue()); } }
Fix unit test under Windows
test/fitnesse/wiki/fs/WikiFilePageTest.java
Fix unit test under Windows
<ide><path>est/fitnesse/wiki/fs/WikiFilePageTest.java <ide> final List<WikiPage> children = root.getChildren(); <ide> <ide> assertThat(children, hasSize(1)); <del> assertThat(((WikiFilePage) children.get(0)).getFileSystemPath().getPath(), is("root/testPage")); <add> assertThat(((WikiFilePage) children.get(0)).getFileSystemPath().getPath(), <add> is("root" + File.separator + "testPage")); <ide> assertThat(children.get(0).getName(), is("testPage")); <ide> } <ide> <ide> final List<WikiPage> children = root.getChildren(); <ide> <ide> assertThat(children, hasSize(1)); <del> assertThat(((WikiFilePage) children.get(0)).getFileSystemPath().getPath(), is("root/testPage")); <add> assertThat(((WikiFilePage) children.get(0)).getFileSystemPath().getPath(), <add> is("root" + File.separator + "testPage")); <ide> assertThat(children.get(0).getName(), is("testPage")); <ide> } <ide>
Java
apache-2.0
b8b34b81cc16bc085016297cfe6346356a26dde2
0
alibaba/nacos,alibaba/nacos,alibaba/nacos,alibaba/nacos
/* * Copyright 1999-2021 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.nacos.client.auth.ram.injector; import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.exception.runtime.NacosRuntimeException; import com.alibaba.nacos.plugin.auth.api.LoginIdentityContext; import com.alibaba.nacos.client.auth.ram.RamContext; import com.alibaba.nacos.plugin.auth.api.RequestResource; import com.alibaba.nacos.client.config.impl.ConfigHttpClientManager; import com.alibaba.nacos.client.auth.ram.utils.SpasAdapter; import com.alibaba.nacos.client.auth.ram.identify.StsConfig; import com.alibaba.nacos.client.auth.ram.identify.StsCredential; import com.alibaba.nacos.client.utils.LogUtils; import com.alibaba.nacos.common.http.HttpRestResult; import com.alibaba.nacos.common.http.param.Header; import com.alibaba.nacos.common.http.param.Query; import com.alibaba.nacos.common.utils.JacksonUtils; import com.alibaba.nacos.common.utils.StringUtils; import com.fasterxml.jackson.core.type.TypeReference; import org.slf4j.Logger; import java.util.Map; /** * Resource Injector for naming module. * * @author xiweng.yy */ public class ConfigResourceInjector extends AbstractResourceInjector { private static final Logger LOGGER = LogUtils.logger(ConfigResourceInjector.class); private static final String SECURITY_TOKEN_HEADER = "Spas-SecurityToken"; private static final String ACCESS_KEY_HEADER = "Spas-AccessKey"; private static final String DEFAULT_RESOURCE = ""; private StsCredential stsCredential; @Override public void doInject(RequestResource resource, RamContext context, LoginIdentityContext result) { String accessKey = context.getAccessKey(); String secretKey = context.getSecretKey(); // STS 临时凭证鉴权的优先级高于 AK/SK 鉴权 if (StsConfig.getInstance().isStsOn()) { StsCredential stsCredential = getStsCredential(); accessKey = stsCredential.getAccessKeyId(); secretKey = stsCredential.getAccessKeySecret(); result.setParameter(SECURITY_TOKEN_HEADER, stsCredential.getSecurityToken()); } if (StringUtils.isNotEmpty(accessKey) && StringUtils.isNotBlank(secretKey)) { result.setParameter(ACCESS_KEY_HEADER, accessKey); } Map<String, String> signHeaders = SpasAdapter .getSignHeaders(getResource(resource.getNamespace(), resource.getGroup()), secretKey); result.setParameters(signHeaders); } private StsCredential getStsCredential() { boolean cacheSecurityCredentials = StsConfig.getInstance().isCacheSecurityCredentials(); if (cacheSecurityCredentials && stsCredential != null) { long currentTime = System.currentTimeMillis(); long expirationTime = stsCredential.getExpiration().getTime(); int timeToRefreshInMillisecond = StsConfig.getInstance().getTimeToRefreshInMillisecond(); if (expirationTime - currentTime > timeToRefreshInMillisecond) { return stsCredential; } } String stsResponse = getStsResponse(); stsCredential = JacksonUtils.toObj(stsResponse, new TypeReference<StsCredential>() { }); LOGGER.info("[getSTSCredential] code:{}, accessKeyId:{}, lastUpdated:{}, expiration:{}", stsCredential.getCode(), stsCredential.getAccessKeyId(), stsCredential.getLastUpdated(), stsCredential.getExpiration()); return stsCredential; } private static String getStsResponse() { String securityCredentials = StsConfig.getInstance().getSecurityCredentials(); if (securityCredentials != null) { return securityCredentials; } String securityCredentialsUrl = StsConfig.getInstance().getSecurityCredentialsUrl(); try { HttpRestResult<String> result = ConfigHttpClientManager.getInstance().getNacosRestTemplate() .get(securityCredentialsUrl, Header.EMPTY, Query.EMPTY, String.class); if (!result.ok()) { LOGGER.error( "can not get security credentials, securityCredentialsUrl: {}, responseCode: {}, response: {}", securityCredentialsUrl, result.getCode(), result.getMessage()); throw new NacosRuntimeException(NacosException.SERVER_ERROR, "can not get security credentials, responseCode: " + result.getCode() + ", response: " + result .getMessage()); } return result.getData(); } catch (Exception e) { LOGGER.error("can not get security credentials", e); throw new NacosRuntimeException(NacosException.SERVER_ERROR, e); } } private String getResource(String tenant, String group) { if (StringUtils.isNotBlank(tenant) && StringUtils.isNotBlank(group)) { return tenant + "+" + group; } if (StringUtils.isNotBlank(group)) { return group; } if (StringUtils.isNotBlank(tenant)) { return tenant; } return DEFAULT_RESOURCE; } }
client/src/main/java/com/alibaba/nacos/client/auth/ram/injector/ConfigResourceInjector.java
/* * Copyright 1999-2021 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.nacos.client.auth.ram.injector; import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.exception.runtime.NacosRuntimeException; import com.alibaba.nacos.plugin.auth.api.LoginIdentityContext; import com.alibaba.nacos.client.auth.ram.RamContext; import com.alibaba.nacos.plugin.auth.api.RequestResource; import com.alibaba.nacos.client.config.impl.ConfigHttpClientManager; import com.alibaba.nacos.client.auth.ram.utils.SpasAdapter; import com.alibaba.nacos.client.auth.ram.identify.StsConfig; import com.alibaba.nacos.client.auth.ram.identify.StsCredential; import com.alibaba.nacos.client.utils.LogUtils; import com.alibaba.nacos.common.http.HttpRestResult; import com.alibaba.nacos.common.http.param.Header; import com.alibaba.nacos.common.http.param.Query; import com.alibaba.nacos.common.utils.JacksonUtils; import com.alibaba.nacos.common.utils.StringUtils; import com.fasterxml.jackson.core.type.TypeReference; import org.slf4j.Logger; import java.util.Map; /** * Resource Injector for naming module. * * @author xiweng.yy */ public class ConfigResourceInjector extends AbstractResourceInjector { private static final Logger LOGGER = LogUtils.logger(ConfigResourceInjector.class); private static final String SECURITY_TOKEN_HEADER = "Spas-SecurityToken"; private static final String ACCESS_KEY_HEADER = "Spas-AccessKey"; private static final String DEFAULT_RESOURCE = ""; private StsCredential stsCredential; @Override public void doInject(RequestResource resource, RamContext context, LoginIdentityContext result) { String accessKey = context.getAccessKey(); String secretKey = context.getSecretKey(); // STS 临时凭证鉴权的优先级高于 AK/SK 鉴权 if (StsConfig.getInstance().isStsOn()) { StsCredential stsCredential = getStsCredential(); accessKey = stsCredential.getAccessKeyId(); secretKey = stsCredential.getAccessKeySecret(); result.setParameter(SECURITY_TOKEN_HEADER, stsCredential.getSecurityToken()); } if (StringUtils.isNotEmpty(accessKey) && StringUtils.isNotBlank(secretKey)) { result.setParameter(ACCESS_KEY_HEADER, accessKey); } Map<String, String> signHeaders = SpasAdapter .getSignHeaders(getResource(resource.getNamespace(), resource.getGroup()), secretKey); if (signHeaders != null && !signHeaders.isEmpty()) { result.setParameters(signHeaders); } } private StsCredential getStsCredential() { boolean cacheSecurityCredentials = StsConfig.getInstance().isCacheSecurityCredentials(); if (cacheSecurityCredentials && stsCredential != null) { long currentTime = System.currentTimeMillis(); long expirationTime = stsCredential.getExpiration().getTime(); int timeToRefreshInMillisecond = StsConfig.getInstance().getTimeToRefreshInMillisecond(); if (expirationTime - currentTime > timeToRefreshInMillisecond) { return stsCredential; } } String stsResponse = getStsResponse(); stsCredential = JacksonUtils.toObj(stsResponse, new TypeReference<StsCredential>() { }); LOGGER.info("[getSTSCredential] code:{}, accessKeyId:{}, lastUpdated:{}, expiration:{}", stsCredential.getCode(), stsCredential.getAccessKeyId(), stsCredential.getLastUpdated(), stsCredential.getExpiration()); return stsCredential; } private static String getStsResponse() { String securityCredentials = StsConfig.getInstance().getSecurityCredentials(); if (securityCredentials != null) { return securityCredentials; } String securityCredentialsUrl = StsConfig.getInstance().getSecurityCredentialsUrl(); try { HttpRestResult<String> result = ConfigHttpClientManager.getInstance().getNacosRestTemplate() .get(securityCredentialsUrl, Header.EMPTY, Query.EMPTY, String.class); if (!result.ok()) { LOGGER.error( "can not get security credentials, securityCredentialsUrl: {}, responseCode: {}, response: {}", securityCredentialsUrl, result.getCode(), result.getMessage()); throw new NacosRuntimeException(NacosException.SERVER_ERROR, "can not get security credentials, responseCode: " + result.getCode() + ", response: " + result .getMessage()); } return result.getData(); } catch (Exception e) { LOGGER.error("can not get security credentials", e); throw new NacosRuntimeException(NacosException.SERVER_ERROR, e); } } private String getResource(String tenant, String group) { if (StringUtils.isNotBlank(tenant) && StringUtils.isNotBlank(group)) { return tenant + "+" + group; } if (StringUtils.isNotBlank(group)) { return group; } if (StringUtils.isNotBlank(tenant)) { return tenant; } return DEFAULT_RESOURCE; } }
[ISSUE#8533] remove redundant signHeaders empty judgment (#8534)
client/src/main/java/com/alibaba/nacos/client/auth/ram/injector/ConfigResourceInjector.java
[ISSUE#8533] remove redundant signHeaders empty judgment (#8534)
<ide><path>lient/src/main/java/com/alibaba/nacos/client/auth/ram/injector/ConfigResourceInjector.java <ide> } <ide> Map<String, String> signHeaders = SpasAdapter <ide> .getSignHeaders(getResource(resource.getNamespace(), resource.getGroup()), secretKey); <del> if (signHeaders != null && !signHeaders.isEmpty()) { <del> result.setParameters(signHeaders); <del> } <add> result.setParameters(signHeaders); <ide> } <ide> <ide> private StsCredential getStsCredential() {
Java
apache-2.0
c53840e2ee7262b44ad408ab2dd5fb25333047c6
0
runigma/pft-16,runigma/pft-16
package com.example.tests; public class ContactData implements Comparable<ContactData> { public String firstname; public String lastname; public String address; public String homephone; public String mobilephone; public String workphone; public String firstemail; public String secondemail; public String day; public String month; public String year; public String groupname; public String secondaddress; public String secondphone; public ContactData() { } public ContactData(String firstname, String lastname, String address, String homephone, String mobilephone, String workphone, String firstemail, String secondemail, String day, String month, String year, String groupname, String secondaddress, String secondphone) { this.firstname = firstname; this.lastname = lastname; this.address = address; this.homephone = homephone; this.mobilephone = mobilephone; this.workphone = workphone; this.firstemail = firstemail; this.secondemail = secondemail; this.day = day; this.month = month; this.year = year; this.groupname = groupname; this.secondaddress = secondaddress; this.secondphone = secondphone; } @Override public String toString() { return "ContactData [firstname=" + firstname + ", lastname=" + lastname + "]"; } @Override public int hashCode() { //final int prime = 31; int result = 1; //result = prime * result + ((firstname == null) ? 0 : firstname.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ContactData other = (ContactData) obj; if (firstname == null) { if (other.firstname != null) return false; } else if (!firstname.equals(other.firstname)) return false; return true; } @Override public int compareTo(ContactData other) { int cmp; cmp = this.lastname.toLowerCase().compareTo(other.lastname.toLowerCase()); if (cmp==0){ cmp = this.firstname.toLowerCase().compareTo(other.firstname.toLowerCase()); } return cmp; } }
adressbook-selenium-tests/src/com/example/tests/ContactData.java
package com.example.tests; public class ContactData implements Comparable<ContactData> { public String firstname; public String lastname; public String address; public String homephone; public String mobilephone; public String workphone; public String firstemail; public String secondemail; public String day; public String month; public String year; public String groupname; public String secondaddress; public String secondphone; public ContactData() { } public ContactData(String firstname, String lastname, String address, String homephone, String mobilephone, String workphone, String firstemail, String secondemail, String day, String month, String year, String groupname, String secondaddress, String secondphone) { this.firstname = firstname; this.lastname = lastname; this.address = address; this.homephone = homephone; this.mobilephone = mobilephone; this.workphone = workphone; this.firstemail = firstemail; this.secondemail = secondemail; this.day = day; this.month = month; this.year = year; this.groupname = groupname; this.secondaddress = secondaddress; this.secondphone = secondphone; } @Override public String toString() { return "ContactData [firstname=" + firstname + ", lastname=" + lastname + "]"; } @Override public int hashCode() { //final int prime = 31; int result = 1; //result = prime * result + ((firstname == null) ? 0 : firstname.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ContactData other = (ContactData) obj; if (firstname == null) { if (other.firstname != null) return false; } else if (!firstname.equals(other.firstname)) return false; return true; } @Override public int compareTo(ContactData other) { return this.lastname.toLowerCase().compareTo(other.lastname.toLowerCase()); } }
Method for contacts comparison was modified. Method for contacts comparison was modified. Second checking was added.
adressbook-selenium-tests/src/com/example/tests/ContactData.java
Method for contacts comparison was modified.
<ide><path>dressbook-selenium-tests/src/com/example/tests/ContactData.java <ide> <ide> @Override <ide> public int compareTo(ContactData other) { <del> return this.lastname.toLowerCase().compareTo(other.lastname.toLowerCase()); <add> int cmp; <add> cmp = this.lastname.toLowerCase().compareTo(other.lastname.toLowerCase()); <add> if (cmp==0){ <add> cmp = this.firstname.toLowerCase().compareTo(other.firstname.toLowerCase()); <add> } <add> return cmp; <ide> } <ide> }
JavaScript
mit
450044e750cad26c50fe7b07fc005d4432ecd05e
0
TulevaEE/onboarding-client,TulevaEE/onboarding-client,TulevaEE/onboarding-client
import React, { Fragment } from 'react'; import { PropTypes as Types } from 'prop-types'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import { Message } from 'retranslate'; import { Link } from 'react-router'; import { Loader, ErrorMessage } from '../common'; import PensionFundTable from './../onboardingFlow/selectSources/pensionFundTable'; import PendingExchangesTable from './pendingExchangeTable'; import UpdateUserForm from './updateUserForm'; import { updateUser } from '../common/user/actions'; export const AccountPage = ({ currentBalanceFunds, loadingCurrentBalance, initialCapital, memberNumber, conversion, pendingExchanges, loadingPendingExchanges, saveUser, error, }) => ( <Fragment> <div className="mt-5"> {memberNumber ? ( <Message params={{ memberNumber }}>account.member.statement</Message> ) : ( <span> <Message>account.non.member.statement</Message>{' '} <a className="btn btn-link p-0 border-0" href="https://tuleva.ee/#inline-signup-anchor"> <Message>login.join.tuleva</Message> </a> </span> )}{' '} {initialCapital ? ( <Message params={{ initialCapital: initialCapital.amount }}> account.initial-capital.statement </Message> ) : ( '' )} <div> {currentBalanceFunds && currentBalanceFunds.length === 0 ? ( <Message>account.second.pillar.missing</Message> ) : ( '' )} </div> </div> {conversion && conversion.transfersComplete && conversion.selectionComplete ? ( <div className="mt-5"> <Message>account.converted.user.statement</Message> </div> ) : ( '' )} {error ? <ErrorMessage errors={error.body} /> : ''} <div className="row mt-5"> <div className="col-md-6"> <Message className="mb-4 lead">select.sources.current.status</Message> </div> {currentBalanceFunds && currentBalanceFunds.length > 0 && ( <div className="col-md-6 text-md-right"> <Link className="btn btn-primary mb-3" to="/steps/select-sources"> <Message>change.my.pension.fund</Message> </Link> </div> )} </div> {loadingCurrentBalance ? ( <Loader className="align-middle" /> ) : ( <PensionFundTable funds={currentBalanceFunds} /> )} <div className="mt-5"> <p className="mb-4 lead"> <Message>pending.exchanges.lead</Message> </p> {loadingPendingExchanges ? ( <Loader className="align-middle" /> ) : ( <PendingExchangesTable pendingExchanges={pendingExchanges} /> )} </div> <div className="mt-5"> <p className="mb-4 lead"> <Message>update.user.details.title</Message> </p> <UpdateUserForm onSubmit={saveUser} /> </div> </Fragment> ); const noop = () => null; AccountPage.defaultProps = { currentBalanceFunds: [], loadingCurrentBalance: false, pendingExchanges: [], loadingPendingExchanges: false, initialCapital: {}, memberNumber: null, conversion: {}, error: null, saveUser: noop, }; AccountPage.propTypes = { currentBalanceFunds: Types.arrayOf(Types.shape({})), loadingCurrentBalance: Types.bool, pendingExchanges: Types.arrayOf(Types.shape({})), loadingPendingExchanges: Types.bool, initialCapital: Types.shape({}), memberNumber: Types.number, conversion: Types.shape({}), saveUser: Types.func, error: Types.shape({}), }; const mapStateToProps = state => ({ currentBalanceFunds: state.exchange.sourceFunds !== null ? state.exchange.sourceFunds : [], loadingCurrentBalance: state.exchange.loadingSourceFunds, pendingExchanges: state.exchange.pendingExchanges, loadingPendingExchanges: state.exchange.loadingPendingExchanges, initialCapital: state.account.initialCapital, memberNumber: (state.login.user || {}).memberNumber, conversion: state.login.userConversion, error: state.exchange.error, }); const mapDispatchToProps = dispatch => bindActionCreators( { saveUser: updateUser, }, dispatch, ); const withRedux = connect( mapStateToProps, mapDispatchToProps, ); export default withRedux(AccountPage);
src/entries/components/account/AccountPage.js
import React from 'react'; import { PropTypes as Types } from 'prop-types'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import { Message } from 'retranslate'; import { Link } from 'react-router'; import { Loader, ErrorMessage } from '../common'; import PensionFundTable from './../onboardingFlow/selectSources/pensionFundTable'; import PendingExchangesTable from './pendingExchangeTable'; import UpdateUserForm from './updateUserForm'; import { updateUser } from '../common/user/actions'; export const AccountPage = ({ currentBalanceFunds, loadingCurrentBalance, initialCapital, memberNumber, conversion, pendingExchanges, loadingPendingExchanges, saveUser, error, }) => ( <div> <div className="row mt-5"> <div className="col"> {memberNumber ? ( <Message params={{ memberNumber }}>account.member.statement</Message> ) : ( <span> <Message>account.non.member.statement</Message>{' '} <a className="btn btn-link p-0 border-0" href="https://tuleva.ee/#inline-signup-anchor"> <Message>login.join.tuleva</Message> </a> </span> )}{' '} {initialCapital ? ( <Message params={{ initialCapital: initialCapital.amount }}> account.initial-capital.statement </Message> ) : ( '' )} <div> {currentBalanceFunds && currentBalanceFunds.length === 0 ? ( <Message>account.second.pillar.missing</Message> ) : ( '' )} </div> </div> </div> {conversion && conversion.transfersComplete && conversion.selectionComplete ? ( <div className="row mt-5"> <div className="col"> <Message>account.converted.user.statement</Message> </div> </div> ) : ( '' )} {error ? <ErrorMessage errors={error.body} /> : ''} <div className="row mt-5"> <div className="col-md-6"> <Message className="mb-4 lead">select.sources.current.status</Message> </div> {currentBalanceFunds && currentBalanceFunds.length > 0 && ( <div className="col-md-6 text-md-right"> <Link className="btn btn-primary mb-3" to="/steps/select-sources"> <Message>change.my.pension.fund</Message> </Link> </div> )} </div> <div className="row"> <div className="col"> {loadingCurrentBalance ? ( <Loader className="align-middle" /> ) : ( <PensionFundTable funds={currentBalanceFunds} /> )} </div> </div> <div className="row mt-5"> <div className="col"> <p className="mb-4 lead"> <Message>pending.exchanges.lead</Message> </p> {loadingPendingExchanges ? ( <Loader className="align-middle" /> ) : ( <PendingExchangesTable pendingExchanges={pendingExchanges} /> )} </div> </div> <div className="mt-5"> <p className="mb-4 lead"> <Message>update.user.details.title</Message> </p> <UpdateUserForm onSubmit={saveUser} /> </div> </div> ); const noop = () => null; AccountPage.defaultProps = { currentBalanceFunds: [], loadingCurrentBalance: false, pendingExchanges: [], loadingPendingExchanges: false, initialCapital: {}, memberNumber: null, conversion: {}, error: null, saveUser: noop, }; AccountPage.propTypes = { currentBalanceFunds: Types.arrayOf(Types.shape({})), loadingCurrentBalance: Types.bool, pendingExchanges: Types.arrayOf(Types.shape({})), loadingPendingExchanges: Types.bool, initialCapital: Types.shape({}), memberNumber: Types.number, conversion: Types.shape({}), saveUser: Types.func, error: Types.shape({}), }; const mapStateToProps = state => ({ currentBalanceFunds: state.exchange.sourceFunds !== null ? state.exchange.sourceFunds : [], loadingCurrentBalance: state.exchange.loadingSourceFunds, pendingExchanges: state.exchange.pendingExchanges, loadingPendingExchanges: state.exchange.loadingPendingExchanges, initialCapital: state.account.initialCapital, memberNumber: (state.login.user || {}).memberNumber, conversion: state.login.userConversion, error: state.exchange.error, }); const mapDispatchToProps = dispatch => bindActionCreators( { saveUser: updateUser, }, dispatch, ); const withRedux = connect( mapStateToProps, mapDispatchToProps, ); export default withRedux(AccountPage);
Remove unnecessary grid elements
src/entries/components/account/AccountPage.js
Remove unnecessary grid elements
<ide><path>rc/entries/components/account/AccountPage.js <del>import React from 'react'; <add>import React, { Fragment } from 'react'; <ide> import { PropTypes as Types } from 'prop-types'; <ide> import { bindActionCreators } from 'redux'; <ide> import { connect } from 'react-redux'; <ide> saveUser, <ide> error, <ide> }) => ( <del> <div> <del> <div className="row mt-5"> <del> <div className="col"> <del> {memberNumber ? ( <del> <Message params={{ memberNumber }}>account.member.statement</Message> <del> ) : ( <del> <span> <del> <Message>account.non.member.statement</Message>{' '} <del> <a className="btn btn-link p-0 border-0" href="https://tuleva.ee/#inline-signup-anchor"> <del> <Message>login.join.tuleva</Message> <del> </a> <del> </span> <del> )}{' '} <del> {initialCapital ? ( <del> <Message params={{ initialCapital: initialCapital.amount }}> <del> account.initial-capital.statement <del> </Message> <add> <Fragment> <add> <div className="mt-5"> <add> {memberNumber ? ( <add> <Message params={{ memberNumber }}>account.member.statement</Message> <add> ) : ( <add> <span> <add> <Message>account.non.member.statement</Message>{' '} <add> <a className="btn btn-link p-0 border-0" href="https://tuleva.ee/#inline-signup-anchor"> <add> <Message>login.join.tuleva</Message> <add> </a> <add> </span> <add> )}{' '} <add> {initialCapital ? ( <add> <Message params={{ initialCapital: initialCapital.amount }}> <add> account.initial-capital.statement <add> </Message> <add> ) : ( <add> '' <add> )} <add> <div> <add> {currentBalanceFunds && currentBalanceFunds.length === 0 ? ( <add> <Message>account.second.pillar.missing</Message> <ide> ) : ( <ide> '' <ide> )} <del> <div> <del> {currentBalanceFunds && currentBalanceFunds.length === 0 ? ( <del> <Message>account.second.pillar.missing</Message> <del> ) : ( <del> '' <del> )} <del> </div> <ide> </div> <ide> </div> <add> <ide> {conversion && conversion.transfersComplete && conversion.selectionComplete ? ( <del> <div className="row mt-5"> <del> <div className="col"> <del> <Message>account.converted.user.statement</Message> <del> </div> <add> <div className="mt-5"> <add> <Message>account.converted.user.statement</Message> <ide> </div> <ide> ) : ( <ide> '' <ide> )} <ide> {error ? <ErrorMessage errors={error.body} /> : ''} <add> <ide> <div className="row mt-5"> <ide> <div className="col-md-6"> <ide> <Message className="mb-4 lead">select.sources.current.status</Message> <ide> </div> <ide> )} <ide> </div> <del> <div className="row"> <del> <div className="col"> <del> {loadingCurrentBalance ? ( <del> <Loader className="align-middle" /> <del> ) : ( <del> <PensionFundTable funds={currentBalanceFunds} /> <del> )} <del> </div> <add> <add> {loadingCurrentBalance ? ( <add> <Loader className="align-middle" /> <add> ) : ( <add> <PensionFundTable funds={currentBalanceFunds} /> <add> )} <add> <add> <div className="mt-5"> <add> <p className="mb-4 lead"> <add> <Message>pending.exchanges.lead</Message> <add> </p> <add> {loadingPendingExchanges ? ( <add> <Loader className="align-middle" /> <add> ) : ( <add> <PendingExchangesTable pendingExchanges={pendingExchanges} /> <add> )} <ide> </div> <del> <div className="row mt-5"> <del> <div className="col"> <del> <p className="mb-4 lead"> <del> <Message>pending.exchanges.lead</Message> <del> </p> <del> {loadingPendingExchanges ? ( <del> <Loader className="align-middle" /> <del> ) : ( <del> <PendingExchangesTable pendingExchanges={pendingExchanges} /> <del> )} <del> </div> <del> </div> <add> <ide> <div className="mt-5"> <ide> <p className="mb-4 lead"> <ide> <Message>update.user.details.title</Message> <ide> </p> <ide> <UpdateUserForm onSubmit={saveUser} /> <ide> </div> <del> </div> <add> </Fragment> <ide> ); <ide> <ide> const noop = () => null;
Java
mit
5bc3d9da21cb01e5832e5e6d164075b5c9a30223
0
ihongs/HongsCORE.new,ihongs/HongsCORE.new,ihongs/HongsCORE.new,ihongs/HongsCORE.new,ihongs/HongsCORE.new
package app.hongs.util.sketch; import java.awt.Color; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.imageio.ImageIO; import net.coobird.thumbnailator.Thumbnails; import net.coobird.thumbnailator.Thumbnails.Builder; import net.coobird.thumbnailator.geometry.Position; import net.coobird.thumbnailator.geometry.Positions; /** * 缩略图工具 * @author Hongs */ public class Thumb { private BufferedImage src; private Position pos = Positions.CENTER; private Color col = new Color(0, 0, 0, 0); // 扩展名:宽*高, 扩展名可以为空串 private static final Pattern PAT = Pattern.compile("([\\w_]*):(\\d+)\\*(\\d+)"); // keep:R,G,B,A, 取值0~255, A可选 private static final Pattern PXT = Pattern.compile(";color:(\\d+(,\\d+){2,3})"); public Thumb(BufferedImage img) { this.src = img; } public Thumb( File src) throws IOException { this(ImageIO.read(src)); } public Thumb(String src) throws IOException { this(ImageIO.read(new File(src))); } public Thumb setColor(Color col) { this.col = col; return this; } public Thumb setPosition(Position pos) { this.pos = pos; return this; } /** * 按比例保留 * @param w * @param h * @return * @throws IOException */ public Builder keep(int w, int h) throws IOException { int xw = src.getWidth (null); int xh = src.getHeight(null); int zw = xh * w / h; if (zw < xw) { h = xw * h / w; w = xw; // 宽度优先 } else { w = zw; h = xh; // 高度优先 } BufferedImage img = draw(src, col, pos, w, h, xw, xh); return Thumbnails.of(img); } /** * 按比例截取 * @param w * @param h * @return */ public Builder pick(int w, int h) { int xw = src.getWidth (null); int xh = src.getHeight(null); int zw = xh * w / h; if (zw > xw) { h = xw * h / w; w = xw; // 宽度优先 } else { w = zw; h = xh; // 高度优先 } BufferedImage img = draw(src, col, pos, w, h, xw, xh); return Thumbnails.of(img); } /** * 按尺寸缩放 * @param w * @param h * @return */ public Builder zoom(int w, int h) { BufferedImage img = draw(src, col); return Thumbnails.of(img) .size(w,h); } /** * 转为构造器 * @return */ public Builder make() { BufferedImage img = draw(src, col); return Thumbnails.of(img); } private BufferedImage draw(BufferedImage img, Color col, Position pos, int w, int h, int xw, int xh) { int l , t; if (pos == Positions.TOP_LEFT) { l = 0; t = 0; } else if (pos == Positions.TOP_RIGHT) { l = (w - xw); t = 0; } else if (pos == Positions.BOTTOM_LEFT) { l = 0; t = (h - xh); } else if (pos == Positions.BOTTOM_RIGHT) { l = (w - xw); t = (h - xh); } else { l = (w - xw) / 2; t = (h - xh) / 2; } BufferedImage buf = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB); Graphics grp = buf.createGraphics(); grp.setColor (col); grp.fillRect (0,0, w,h); grp.drawImage (img, l,t, null); grp.dispose ( ); return buf; } private BufferedImage draw(BufferedImage img, Color col) { int w = img.getWidth( ); int h = img.getHeight(); BufferedImage buf = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB); Graphics grp = buf.createGraphics(); grp.setColor (col); grp.fillRect (0,0, w,h); grp.drawImage (img, 0,0, null); grp.dispose ( ); return buf; } /** * 生成缩略图 * @param pth 原始图片路径 * @param url 原始图片链接 * @param ext 规定输出格式 * @param rat 截取比例格式: 后缀:宽*高;keep#RGBA * @param map 缩放尺寸格式: 后缀:宽*高,后缀:宽*高... * @return 缩略图路径,链接 * @throws IOException */ public static String[][] toThumbs(String pth, String url, String ext, String rat, String map) throws IOException { if (url == null) url = ""; if (ext == null) ext = ""; if (rat == null) rat = ""; if (map == null) map = ""; if ("".equals(ext)) { int pos = pth.lastIndexOf('.'); if (pos > 0) { ext = pth.substring(pos+1); } else { throw new NullPointerException("Argument ext can not be empty"); } } if ("".equals(rat) && "".equals(map)) { throw new NullPointerException("Argument rat or map can not be empty"); } List<String> pts = new ArrayList(); List<String> urs = new ArrayList(); Thumb thb = new Thumb(pth ); Builder bld ; Matcher mat ; String pre , prl , suf ; int w, h; pth = new File( pth ).getAbsolutePath( ); pre = pth.replaceFirst("\\.[^\\.]+$",""); prl = url.replaceFirst("\\.[^\\.]+$",""); // 截取图 mat = PAT.matcher(rat); if ( mat.find( ) ) { suf = mat.group(1); w = Integer.parseInt(mat.group(2)); h = Integer.parseInt(mat.group(3)); // 提取背景颜色(RGBA) mat = PXT.matcher(rat); if (mat.find()) { String[] x = mat.group(1).split(","); int r = Integer.parseInt( x[0] ); int g = Integer.parseInt( x[1] ); int b = Integer.parseInt( x[2] ); int a = x.length == 3 ? 255 : Integer.parseInt( x[3] ); thb.setColor(new Color(r, g, b, a) ); } // 提取拼贴位置(TBLR) if (rat.contains(";bot-right")) { thb.setPosition(Positions.BOTTOM_RIGHT); } else if (rat.contains(";bot-left")) { thb.setPosition(Positions.BOTTOM_LEFT); } else if (rat.contains(";top-right")) { thb.setPosition(Positions.TOP_RIGHT); } else if (rat.contains(";top-left")) { thb.setPosition(Positions.TOP_LEFT); } else { thb.setPosition(Positions.CENTER); } bld = rat.contains(";keep") ? thb.keep(w,h) : thb.pick(w,h); if (! rat.contains(";temp")) { pth = pre + suf + "." + ext; url = prl + suf + "." + ext; bld.outputFormat(ext) .toFile(pth); pts.add(pth); urs.add(url); } } else { bld = Thumbnails.of (pth); if (rat.length() != 0) { pth = pre + rat + "." + ext; url = prl + rat + "." + ext; bld.outputFormat(ext) .toFile(pth); pts.add(pth); urs.add(url); } else { bld.outputFormat(ext) .toFile(pth); pts.add(pth); urs.add(url); } } // 以上面截取的图为蓝本进行缩放 thb = new Thumb(bld.asBufferedImage()); // 缩放图 mat = PAT.matcher(map); while (mat.find()) { suf = mat.group(1); w = Integer.parseInt(mat.group(2)); h = Integer.parseInt(mat.group(3)); pth = pre + suf + "." + ext; url = prl + suf + "." + ext; bld = thb.zoom (w,h); bld.outputFormat(ext) .toFile(pth); pts.add(pth); urs.add(url); } // 没截取或缩放则用指定格式路径 if (pts.isEmpty()) { pts.add(pre + "." + ext); urs.add(url + "." + ext); } return new String[][] { pts.toArray(new String[] {}), urs.toArray(new String[] {}) }; } }
hongs-serv/src/main/java/app/hongs/util/sketch/Thumb.java
package app.hongs.util.sketch; import java.awt.Color; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.imageio.ImageIO; import net.coobird.thumbnailator.Thumbnails; import net.coobird.thumbnailator.Thumbnails.Builder; import net.coobird.thumbnailator.geometry.Position; import net.coobird.thumbnailator.geometry.Positions; /** * 缩略图工具 * @author Hongs */ public class Thumb { private BufferedImage src; private Position pos = Positions.CENTER; private Color col = new Color(0, 0, 0, 0); // 扩展名:宽*高, 扩展名可以为空串 private static final Pattern PAT = Pattern.compile("([\\w_]*):(\\d+)\\*(\\d+)"); // keep:R,G,B,A, 取值0~255, A可选 private static final Pattern PXT = Pattern.compile(";color:(\\d+(,\\d+){2,3})"); public Thumb(BufferedImage img) { this.src = img; } public Thumb( File src) throws IOException { this(ImageIO.read(src)); } public Thumb(String src) throws IOException { this(ImageIO.read(new File(src))); } public Thumb setColor(Color col) { this.col = col; return this; } public Thumb setPosition(Position pos) { this.pos = pos; return this; } /** * 按比例保留 * @param w * @param h * @return * @throws IOException */ public Builder keep(int w, int h) throws IOException { int xw = src.getWidth (null); int xh = src.getHeight(null); int zw = xh * w / h; if (zw < xw) { h = xw * h / w; w = xw; // 宽度优先 } else { w = zw; h = xh; // 高度优先 } BufferedImage img = draw(src, col, pos, w, h, xw, xh); return Thumbnails.of(img); } /** * 按比例截取 * @param w * @param h * @return */ public Builder pick(int w, int h) { int xw = src.getWidth (null); int xh = src.getHeight(null); int zw = xh * w / h; if (zw > xw) { h = xw * h / w; w = xw; // 宽度优先 } else { w = zw; h = xh; // 高度优先 } BufferedImage img = draw(src, col, pos, w, h, xw, xh); return Thumbnails.of(img); } /** * 按尺寸缩放 * @param w * @param h * @return */ public Builder zoom(int w, int h) { BufferedImage img = draw(src, col); return Thumbnails.of(img) .size(w,h); } /** * 转为构造器 * @return */ public Builder make() { BufferedImage img = draw(src, col); return Thumbnails.of(img); } private BufferedImage draw(BufferedImage img, Color col, Position pos, int w, int h, int xw, int xh) { int l , t; if (pos == Positions.TOP_LEFT) { l = 0; t = 0; } else if (pos == Positions.TOP_RIGHT) { l = (w - xw); t = 0; } else if (pos == Positions.BOTTOM_LEFT) { l = 0; t = (h - xh); } else if (pos == Positions.BOTTOM_RIGHT) { l = (w - xw); t = (h - xh); } else { l = (w - xw) / 2; t = (h - xh) / 2; } BufferedImage buf = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB); Graphics grp = buf.createGraphics(); grp.setColor (col); grp.fillRect (0,0, w,h); grp.drawImage (img, l,t, null); grp.dispose ( ); return buf; } private BufferedImage draw(BufferedImage img, Color col) { int w = img.getWidth( ); int h = img.getHeight(); BufferedImage buf = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB); Graphics grp = buf.createGraphics(); grp.setColor (col); grp.fillRect (0,0, w,h); grp.drawImage (img, 0,0, null); grp.dispose ( ); return buf; } /** * 生成缩略图 * @param pth 原始图片路径 * @param url 原始图片链接 * @param ext 规定输出格式 * @param rat 截取比例格式: 后缀:宽*高;keep#RGBA * @param map 缩放尺寸格式: 后缀:宽*高,后缀:宽*高... * @return 缩略图路径,链接 * @throws IOException */ public static String[][] toThumbs(String pth, String url, String ext, String rat, String map) throws IOException { if (url == null) url = ""; if (ext == null) ext = ""; if (rat == null) rat = ""; if (map == null) map = ""; if ("".equals(ext)) { int pos = pth.lastIndexOf('.'); if (pos > 0) { ext = pth.substring(pos+1); } else { throw new NullPointerException("Argument ext can not be empty"); } } if ("".equals(rat) && "".equals(map)) { throw new NullPointerException("Argument rat or map can not be empty"); } List<String> pts = new ArrayList(); List<String> urs = new ArrayList(); Thumb thb = new Thumb(pth ); Builder bld; Matcher mat ; String pre , prl, suf ; File src ; int w, h; boolean tmp = false; pth = new File( pth ).getAbsolutePath( ); pre = pth.replaceFirst("\\.[^\\.]+$",""); prl = url.replaceFirst("\\.[^\\.]+$",""); // 截取图 mat = PAT.matcher(rat); if ( mat.find( ) ) { suf = mat.group(1); w = Integer.parseInt(mat.group(2)); h = Integer.parseInt(mat.group(3)); // 提取背景色(RGBA) mat = PXT.matcher(rat); if (mat.find()) { String[] x = mat.group(1).split(","); int r = Integer.parseInt( x[0] ); int g = Integer.parseInt( x[1] ); int b = Integer.parseInt( x[2] ); int a = x.length == 3 ? 255 : Integer.parseInt( x[3] ); thb.setColor(new Color(r, g, b, a) ); } // 提取位置 if (rat.contains(";bot-right")) { thb.setPosition(Positions.BOTTOM_RIGHT); } else if (rat.contains(";bot-left")) { thb.setPosition(Positions.BOTTOM_LEFT); } else if (rat.contains(";top-right")) { thb.setPosition(Positions.TOP_RIGHT); } else if (rat.contains(";top-left")) { thb.setPosition(Positions.TOP_LEFT); } else { thb.setPosition(Positions.CENTER); } bld = rat.contains(";keep") ? thb.keep(w,h) : thb.pick(w,h); if (! rat.contains(";temp")) { pth = pre + suf + "." + ext; url = prl + suf + "." + ext; bld.outputFormat(ext) .toFile(pth); pts.add(pth); urs.add(url); } } else { bld = Thumbnails.of (pth); if (rat.length() != 0) { pth = pre + rat + "." + ext; url = prl + rat + "." + ext; bld.outputFormat(ext) .toFile(pth); pts.add(pth); urs.add(url); } else { bld.outputFormat(ext) .toFile(pth); pts.add(pth); urs.add(url); } } // 以上面截取的图为蓝本进行缩放 thb = new Thumb(bld.asBufferedImage()); // 缩放图 mat = PAT.matcher(map); while (mat.find()) { suf = mat.group(1); w = Integer.parseInt(mat.group(2)); h = Integer.parseInt(mat.group(3)); pth = pre + suf + "." + ext; url = prl + suf + "." + ext; bld = thb.zoom (w,h); bld.outputFormat(ext) .toFile(pth); pts.add(pth); urs.add(url); } // 没截取或缩放则用指定格式路径 if (pts.isEmpty()) { pts.add(pre + "." + ext); urs.add(url + "." + ext); } return new String[][] { pts.toArray(new String[] {}), urs.toArray(new String[] {}) }; } }
重写缩略图类
hongs-serv/src/main/java/app/hongs/util/sketch/Thumb.java
重写缩略图类
<ide><path>ongs-serv/src/main/java/app/hongs/util/sketch/Thumb.java <ide> List<String> pts = new ArrayList(); <ide> List<String> urs = new ArrayList(); <ide> Thumb thb = new Thumb(pth ); <del> <del> Builder bld; <add> Builder bld ; <ide> Matcher mat ; <del> String pre , prl, suf ; <del> File src ; <add> String pre , prl , suf ; <ide> int w, h; <del> boolean tmp = false; <ide> <ide> pth = new File( pth ).getAbsolutePath( ); <ide> pre = pth.replaceFirst("\\.[^\\.]+$",""); <ide> w = Integer.parseInt(mat.group(2)); <ide> h = Integer.parseInt(mat.group(3)); <ide> <del> // 提取背景色(RGBA) <add> // 提取背景颜色(RGBA) <ide> mat = PXT.matcher(rat); <ide> if (mat.find()) { <ide> String[] x = mat.group(1).split(","); <ide> thb.setColor(new Color(r, g, b, a) ); <ide> } <ide> <del> // 提取位置 <add> // 提取拼贴位置(TBLR) <ide> if (rat.contains(";bot-right")) { <ide> thb.setPosition(Positions.BOTTOM_RIGHT); <ide> } else
JavaScript
bsd-3-clause
51edf3cece13b42b8419c7d2587a4e2beeb05fd9
0
antlr/antlr4,ericvergnaud/antlr4,parrt/antlr4,parrt/antlr4,antlr/antlr4,antlr/antlr4,ericvergnaud/antlr4,parrt/antlr4,antlr/antlr4,antlr/antlr4,parrt/antlr4,ericvergnaud/antlr4,parrt/antlr4,antlr/antlr4,ericvergnaud/antlr4,ericvergnaud/antlr4,parrt/antlr4,ericvergnaud/antlr4,antlr/antlr4,ericvergnaud/antlr4,ericvergnaud/antlr4,antlr/antlr4,parrt/antlr4,ericvergnaud/antlr4,antlr/antlr4,parrt/antlr4,parrt/antlr4,parrt/antlr4,antlr/antlr4,ericvergnaud/antlr4
// /* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. * Use of this file is governed by the BSD 3-clause license that * can be found in the LICENSE.txt file in the project root. */ // var Token = require('./Token').Token; require('./polyfills/codepointat'); require('./polyfills/fromcodepoint'); // Vacuum all input from a string and then treat it like a buffer. function _loadString(stream, decodeToUnicodeCodePoints) { stream._index = 0; stream.data = []; if (stream.decodeToUnicodeCodePoints) { for (var i = 0; i < stream.strdata.length; ) { var codePoint = stream.strdata.codePointAt(i); stream.data.push(codePoint); i += codePoint <= 0xFFFF ? 1 : 2; } } else { for (var i = 0; i < stream.strdata.length; i++) { var codeUnit = stream.strdata.charCodeAt(i); stream.data.push(codeUnit); } } stream._size = stream.data.length; } // If decodeToUnicodeCodePoints is true, the input is treated // as a series of Unicode code points. // // Otherwise, the input is treated as a series of 16-bit UTF-16 code // units. function InputStream(data, decodeToUnicodeCodePoints) { this.name = "<empty>"; this.strdata = data; this.decodeToUnicodeCodePoints = decodeToUnicodeCodePoints || false; _loadString(this); return this; } Object.defineProperty(InputStream.prototype, "index", { get : function() { return this._index; } }); Object.defineProperty(InputStream.prototype, "size", { get : function() { return this._size; } }); // Reset the stream so that it's in the same state it was // when the object was created *except* the data array is not // touched. // InputStream.prototype.reset = function() { this._index = 0; }; InputStream.prototype.consume = function() { if (this._index >= this._size) { // assert this.LA(1) == Token.EOF throw ("cannot consume EOF"); } this._index += 1; }; InputStream.prototype.LA = function(offset) { if (offset === 0) { return 0; // undefined } if (offset < 0) { offset += 1; // e.g., translate LA(-1) to use offset=0 } var pos = this._index + offset - 1; if (pos < 0 || pos >= this._size) { // invalid return Token.EOF; } return this.data[pos]; }; InputStream.prototype.LT = function(offset) { return this.LA(offset); }; // mark/release do nothing; we have entire buffer InputStream.prototype.mark = function() { return -1; }; InputStream.prototype.release = function(marker) { }; // consume() ahead until p==_index; can't just set p=_index as we must // update line and column. If we seek backwards, just set p // InputStream.prototype.seek = function(_index) { if (_index <= this._index) { this._index = _index; // just jump; don't update stream state (line, // ...) return; } // seek forward this._index = Math.min(_index, this._size); }; InputStream.prototype.getText = function(start, stop) { if (stop >= this._size) { stop = this._size - 1; } if (start >= this._size) { return ""; } else { if (this.decodeToUnicodeCodePoints) { var result = ""; for (var i = start; i <= stop; i++) { result += String.fromCodePoint(this.data[i]); } return result; } else { return this.strdata.slice(start, stop + 1); } } }; InputStream.prototype.toString = function() { return this.strdata; }; exports.InputStream = InputStream;
runtime/JavaScript/src/antlr4/InputStream.js
// /* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. * Use of this file is governed by the BSD 3-clause license that * can be found in the LICENSE.txt file in the project root. */ // var Token = require('./Token').Token; require('./polyfills/codepointat'); // Vacuum all input from a string and then treat it like a buffer. function _loadString(stream, decodeToUnicodeCodePoints) { stream._index = 0; stream.data = []; if (decodeToUnicodeCodePoints) { for (var i = 0; i < stream.strdata.length; ) { var codePoint = stream.strdata.codePointAt(i); stream.data.push(codePoint); i += codePoint <= 0xFFFF ? 1 : 2; } } else { for (var i = 0; i < stream.strdata.length; i++) { var codeUnit = stream.strdata.charCodeAt(i); stream.data.push(codeUnit); } } stream._size = stream.data.length; } // If decodeToUnicodeCodePoints is true, the input is treated // as a series of Unicode code points. // // Otherwise, the input is treated as a series of 16-bit UTF-16 code // units. function InputStream(data, decodeToUnicodeCodePoints) { this.name = "<empty>"; this.strdata = data; _loadString(this, decodeToUnicodeCodePoints || false); return this; } Object.defineProperty(InputStream.prototype, "index", { get : function() { return this._index; } }); Object.defineProperty(InputStream.prototype, "size", { get : function() { return this._size; } }); // Reset the stream so that it's in the same state it was // when the object was created *except* the data array is not // touched. // InputStream.prototype.reset = function() { this._index = 0; }; InputStream.prototype.consume = function() { if (this._index >= this._size) { // assert this.LA(1) == Token.EOF throw ("cannot consume EOF"); } this._index += 1; }; InputStream.prototype.LA = function(offset) { if (offset === 0) { return 0; // undefined } if (offset < 0) { offset += 1; // e.g., translate LA(-1) to use offset=0 } var pos = this._index + offset - 1; if (pos < 0 || pos >= this._size) { // invalid return Token.EOF; } return this.data[pos]; }; InputStream.prototype.LT = function(offset) { return this.LA(offset); }; // mark/release do nothing; we have entire buffer InputStream.prototype.mark = function() { return -1; }; InputStream.prototype.release = function(marker) { }; // consume() ahead until p==_index; can't just set p=_index as we must // update line and column. If we seek backwards, just set p // InputStream.prototype.seek = function(_index) { if (_index <= this._index) { this._index = _index; // just jump; don't update stream state (line, // ...) return; } // seek forward this._index = Math.min(_index, this._size); }; InputStream.prototype.getText = function(start, stop) { if (stop >= this._size) { stop = this._size - 1; } if (start >= this._size) { return ""; } else { return this.strdata.slice(start, stop + 1); } }; InputStream.prototype.toString = function() { return this.strdata; }; exports.InputStream = InputStream;
Fix InputStream.getText() when input contains Unicode values > U+FFFF
runtime/JavaScript/src/antlr4/InputStream.js
Fix InputStream.getText() when input contains Unicode values > U+FFFF
<ide><path>untime/JavaScript/src/antlr4/InputStream.js <ide> <ide> var Token = require('./Token').Token; <ide> require('./polyfills/codepointat'); <add>require('./polyfills/fromcodepoint'); <ide> <ide> // Vacuum all input from a string and then treat it like a buffer. <ide> <ide> function _loadString(stream, decodeToUnicodeCodePoints) { <ide> stream._index = 0; <ide> stream.data = []; <del> if (decodeToUnicodeCodePoints) { <add> if (stream.decodeToUnicodeCodePoints) { <ide> for (var i = 0; i < stream.strdata.length; ) { <ide> var codePoint = stream.strdata.codePointAt(i); <ide> stream.data.push(codePoint); <ide> function InputStream(data, decodeToUnicodeCodePoints) { <ide> this.name = "<empty>"; <ide> this.strdata = data; <del> _loadString(this, decodeToUnicodeCodePoints || false); <add> this.decodeToUnicodeCodePoints = decodeToUnicodeCodePoints || false; <add> _loadString(this); <ide> return this; <ide> } <ide> <ide> if (start >= this._size) { <ide> return ""; <ide> } else { <del> return this.strdata.slice(start, stop + 1); <add> if (this.decodeToUnicodeCodePoints) { <add> var result = ""; <add> for (var i = start; i <= stop; i++) { <add> result += String.fromCodePoint(this.data[i]); <add> } <add> return result; <add> } else { <add> return this.strdata.slice(start, stop + 1); <add> } <ide> } <ide> }; <ide>
Java
epl-1.0
d438c0e1293278d48915d031748e84cbffa8f749
0
GoClipse/goclipse,GoClipse/goclipse,GoClipse/goclipse
/******************************************************************************* * Copyright (c) 2014 Bruno Medeiros and other Contributors. * 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: * Bruno Medeiros - initial API and implementation *******************************************************************************/ package melnorme.lang.ide.core.operations; import static melnorme.utilbox.core.Assert.AssertNamespace.assertNotNull; import java.nio.file.Path; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import melnorme.lang.ide.core.ILangOperationsListener; import melnorme.lang.ide.core.LangCore; import melnorme.lang.ide.core.utils.EclipseUtils; import melnorme.lang.ide.core.utils.ResourceUtils; import melnorme.lang.ide.core.utils.operation.EclipseCancelMonitor; import melnorme.lang.ide.core.utils.process.AbstractRunProcessTask; import melnorme.lang.ide.core.utils.process.AbstractRunProcessTask.ProcessStartHelper; import melnorme.lang.tooling.data.IValidatedField; import melnorme.lang.tooling.data.StatusException; import melnorme.lang.tooling.data.StatusLevel; import melnorme.lang.tooling.ops.IOperationHelper; import melnorme.lang.tooling.ops.util.PathValidator; import melnorme.lang.utils.ProcessUtils; import melnorme.utilbox.concurrency.ICancelMonitor; import melnorme.utilbox.concurrency.OperationCancellation; import melnorme.utilbox.core.CommonException; import melnorme.utilbox.fields.EventSource; import melnorme.utilbox.misc.Location; import melnorme.utilbox.process.ExternalProcessHelper.ExternalProcessResult; /** * Abstract class for running external tools and notifying interested listeners (normally the UI only). */ public abstract class AbstractToolManager extends EventSource<ILangOperationsListener> { public AbstractToolManager() { } public void shutdownNow() { } /* ----------------- ----------------- */ public Path getSDKToolPath(IProject project) throws CommonException { return getSDKToolPathField(project).getValidatedField(); } private IValidatedField<Path> getSDKToolPathField(IProject project) { return new ValidatedSDKToolPath(project, getSDKToolPathValidator()); } public static class ValidatedSDKToolPath implements IValidatedField<Path> { protected final IProject project; protected final PathValidator pathValidator; public ValidatedSDKToolPath(IProject project, PathValidator pathValidator) { this.project = project; this.pathValidator = assertNotNull(pathValidator); } protected String getRawFieldValue2() { return ToolchainPreferences.SDK_PATH2.getEffectiveValue(project); } @Override public Path getValidatedField() throws StatusException { String pathString = getRawFieldValue2(); return getPathValidator().getValidatedPath(pathString); } protected PathValidator getPathValidator() { return pathValidator; } } protected abstract PathValidator getSDKToolPathValidator(); /* ----------------- ----------------- */ public ProcessBuilder createSDKProcessBuilder(IProject project, String... sdkOptions) throws CoreException, CommonException { Location projectLocation = ResourceUtils.getProjectLocation(project); Path sdkToolPath = getSDKToolPath(project); return createToolProcessBuilder(sdkToolPath, projectLocation, sdkOptions); } public ProcessBuilder createToolProcessBuilder(Path buildToolCmdPath, Location workingDir, String... arguments) { return ProcessUtils.createProcessBuilder(buildToolCmdPath, workingDir, true, arguments); } public static ProcessBuilder createProcessBuilder(IProject project, String... commands) { Path workingDir = project != null ? project.getLocation().toFile().toPath() : EclipseUtils.getWorkspaceRoot().getLocation().toFile().toPath(); return new ProcessBuilder(commands).directory(workingDir.toFile()); } /* ----------------- ----------------- */ public void notifyMessage(StatusLevel statusLevel, String title, String message) { for(ILangOperationsListener listener : getListeners()) { listener.notifyMessage(statusLevel, title, message); } } public void notifyOperationStarted(OperationInfo opInfo) { for(ILangOperationsListener processListener : getListeners()) { processListener.handleNewOperation(opInfo); } } public void notifyMessageEvent(MessageEventInfo messageInfo) { for(ILangOperationsListener processListener : getListeners()) { processListener.handleMessage(messageInfo); } } /* ----------------- ----------------- */ public OperationInfo startNewToolOperation() { OperationInfo opInfo = new OperationInfo(null); notifyOperationStarted(opInfo); opInfo.setStarted(true); return opInfo; } protected EclipseCancelMonitor cm(IProgressMonitor pm) { return new EclipseCancelMonitor(pm); } public RunProcessTask newRunToolOperation2(ProcessBuilder pb, IProgressMonitor pm) { OperationInfo opInfo = startNewToolOperation(); return newRunToolTask(opInfo, pb, cm(pm)); } public RunProcessTask newRunToolTask(OperationInfo opInfo, ProcessBuilder pb, IProgressMonitor pm) { return newRunToolTask(opInfo, pb, cm(pm)); } public RunProcessTask newRunToolTask(OperationInfo opInfo, ProcessBuilder pb, ICancelMonitor cm) { return new RunProcessTask(opInfo, pb, cm); } public class RunProcessTask extends AbstractRunProcessTask { protected final OperationInfo opInfo; public RunProcessTask(OperationInfo opInfo, ProcessBuilder pb, ICancelMonitor cancelMonitor) { super(pb, cancelMonitor); this.opInfo = opInfo; } @Override protected void handleProcessStartResult(ProcessStartHelper psh) { for(ILangOperationsListener processListener : getListeners()) { processListener.handleProcessStart(newProcessStartInfo(opInfo, pb, psh)); } } } protected ProcessStartInfo newProcessStartInfo(OperationInfo opInfo, ProcessBuilder pb, ProcessStartHelper psh) { return new ProcessStartInfo(opInfo, pb, ">> Running: ", psh); } /* ----------------- ----------------- */ public ExternalProcessResult runEngineTool(ProcessBuilder pb, String clientInput, IProgressMonitor pm) throws CoreException, OperationCancellation { return runEngineTool(pb, clientInput, cm(pm)); } public ExternalProcessResult runEngineTool(ProcessBuilder pb, String clientInput, ICancelMonitor cm) throws CoreException, OperationCancellation { try { return new RunEngineClientOperation(pb, cm).runProcess(clientInput); } catch(CommonException ce) { throw LangCore.createCoreException(ce); } } public class RunEngineClientOperation extends AbstractRunProcessTask { public RunEngineClientOperation(ProcessBuilder pb, ICancelMonitor cancelMonitor) { super(pb, cancelMonitor); } @Override protected void handleProcessStartResult(ProcessStartHelper psh) { for (ILangOperationsListener listener : AbstractToolManager.this.getListeners()) { listener.engineClientToolStart(pb, psh); } } } public class StartEngineDaemonOperation extends AbstractRunProcessTask { public StartEngineDaemonOperation(ProcessBuilder pb, ICancelMonitor cancelMonitor) { super(pb, cancelMonitor); } @Override protected void handleProcessStartResult(ProcessStartHelper psh) { for (ILangOperationsListener listener : getListeners()) { listener.engineDaemonStart(pb, psh); } } } /* ----------------- ----------------- */ /** * Helper to start engine client processes in the tool manager. */ public class ToolManagerEngineToolRunner implements IOperationHelper { protected final boolean throwOnNonZeroStatus; protected final EclipseCancelMonitor cm; public ToolManagerEngineToolRunner(IProgressMonitor monitor, boolean throwOnNonZeroStatus) { this.throwOnNonZeroStatus = throwOnNonZeroStatus; this.cm = new EclipseCancelMonitor(monitor); } @Override public ExternalProcessResult runProcess(ProcessBuilder pb, String input) throws CommonException, OperationCancellation { return new RunEngineClientOperation(pb, cm).runProcess(input, throwOnNonZeroStatus); } @Override public void logStatus(StatusException statusException) { LangCore.logStatusException(statusException); } } }
plugin_ide.core/src-lang/melnorme/lang/ide/core/operations/AbstractToolManager.java
/******************************************************************************* * Copyright (c) 2014 Bruno Medeiros and other Contributors. * 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: * Bruno Medeiros - initial API and implementation *******************************************************************************/ package melnorme.lang.ide.core.operations; import static melnorme.utilbox.core.Assert.AssertNamespace.assertNotNull; import java.nio.file.Path; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import melnorme.lang.ide.core.ILangOperationsListener; import melnorme.lang.ide.core.LangCore; import melnorme.lang.ide.core.utils.EclipseUtils; import melnorme.lang.ide.core.utils.ResourceUtils; import melnorme.lang.ide.core.utils.operation.EclipseCancelMonitor; import melnorme.lang.ide.core.utils.process.AbstractRunProcessTask; import melnorme.lang.ide.core.utils.process.AbstractRunProcessTask.ProcessStartHelper; import melnorme.lang.tooling.data.IValidatedField; import melnorme.lang.tooling.data.StatusException; import melnorme.lang.tooling.data.StatusLevel; import melnorme.lang.tooling.ops.IOperationHelper; import melnorme.lang.tooling.ops.util.PathValidator; import melnorme.lang.utils.ProcessUtils; import melnorme.utilbox.concurrency.ICancelMonitor; import melnorme.utilbox.concurrency.OperationCancellation; import melnorme.utilbox.core.CommonException; import melnorme.utilbox.fields.EventSource; import melnorme.utilbox.misc.Location; import melnorme.utilbox.process.ExternalProcessHelper.ExternalProcessResult; /** * Abstract class for running external tools and notifying interested listeners (normally the UI only). */ public abstract class AbstractToolManager extends EventSource<ILangOperationsListener> { public AbstractToolManager() { } public void shutdownNow() { } /* ----------------- ----------------- */ public Path getSDKToolPath(IProject project) throws CommonException { return getSDKToolPathField(project).getValidatedField(); } protected IValidatedField<Path> getSDKToolPathField(IProject project) { return new ValidatedSDKToolPath(project, getSDKToolPathValidator()); } public static class ValidatedSDKToolPath implements IValidatedField<Path> { protected final IProject project; protected final PathValidator pathValidator; public ValidatedSDKToolPath(IProject project, PathValidator pathValidator) { this.project = project; this.pathValidator = assertNotNull(pathValidator); } protected String getRawFieldValue2() { return ToolchainPreferences.SDK_PATH2.getEffectiveValue(project); } @Override public Path getValidatedField() throws StatusException { String pathString = getRawFieldValue2(); return getPathValidator().getValidatedPath(pathString); } protected PathValidator getPathValidator() { return pathValidator; } } protected abstract PathValidator getSDKToolPathValidator(); /* ----------------- ----------------- */ public ProcessBuilder createSDKProcessBuilder(IProject project, String... sdkOptions) throws CoreException, CommonException { Location projectLocation = ResourceUtils.getProjectLocation(project); Path sdkToolPath = getSDKToolPath(project); return createToolProcessBuilder(sdkToolPath, projectLocation, sdkOptions); } public ProcessBuilder createToolProcessBuilder(Path buildToolCmdPath, Location workingDir, String... arguments) { return ProcessUtils.createProcessBuilder(buildToolCmdPath, workingDir, true, arguments); } public static ProcessBuilder createProcessBuilder(IProject project, String... commands) { Path workingDir = project != null ? project.getLocation().toFile().toPath() : EclipseUtils.getWorkspaceRoot().getLocation().toFile().toPath(); return new ProcessBuilder(commands).directory(workingDir.toFile()); } /* ----------------- ----------------- */ public void notifyMessage(StatusLevel statusLevel, String title, String message) { for(ILangOperationsListener listener : getListeners()) { listener.notifyMessage(statusLevel, title, message); } } public void notifyOperationStarted(OperationInfo opInfo) { for(ILangOperationsListener processListener : getListeners()) { processListener.handleNewOperation(opInfo); } } public void notifyMessageEvent(MessageEventInfo messageInfo) { for(ILangOperationsListener processListener : getListeners()) { processListener.handleMessage(messageInfo); } } /* ----------------- ----------------- */ public OperationInfo startNewToolOperation() { OperationInfo opInfo = new OperationInfo(null); notifyOperationStarted(opInfo); opInfo.setStarted(true); return opInfo; } protected EclipseCancelMonitor cm(IProgressMonitor pm) { return new EclipseCancelMonitor(pm); } public RunProcessTask newRunToolOperation2(ProcessBuilder pb, IProgressMonitor pm) { OperationInfo opInfo = startNewToolOperation(); return newRunToolTask(opInfo, pb, cm(pm)); } public RunProcessTask newRunToolTask(OperationInfo opInfo, ProcessBuilder pb, IProgressMonitor pm) { return newRunToolTask(opInfo, pb, cm(pm)); } public RunProcessTask newRunToolTask(OperationInfo opInfo, ProcessBuilder pb, ICancelMonitor cm) { return new RunProcessTask(opInfo, pb, cm); } public class RunProcessTask extends AbstractRunProcessTask { protected final OperationInfo opInfo; public RunProcessTask(OperationInfo opInfo, ProcessBuilder pb, ICancelMonitor cancelMonitor) { super(pb, cancelMonitor); this.opInfo = opInfo; } @Override protected void handleProcessStartResult(ProcessStartHelper psh) { for(ILangOperationsListener processListener : getListeners()) { processListener.handleProcessStart(newProcessStartInfo(opInfo, pb, psh)); } } } protected ProcessStartInfo newProcessStartInfo(OperationInfo opInfo, ProcessBuilder pb, ProcessStartHelper psh) { return new ProcessStartInfo(opInfo, pb, ">> Running: ", psh); } /* ----------------- ----------------- */ public ExternalProcessResult runEngineTool(ProcessBuilder pb, String clientInput, IProgressMonitor pm) throws CoreException, OperationCancellation { return runEngineTool(pb, clientInput, cm(pm)); } public ExternalProcessResult runEngineTool(ProcessBuilder pb, String clientInput, ICancelMonitor cm) throws CoreException, OperationCancellation { try { return new RunEngineClientOperation(pb, cm).runProcess(clientInput); } catch(CommonException ce) { throw LangCore.createCoreException(ce); } } public class RunEngineClientOperation extends AbstractRunProcessTask { public RunEngineClientOperation(ProcessBuilder pb, ICancelMonitor cancelMonitor) { super(pb, cancelMonitor); } @Override protected void handleProcessStartResult(ProcessStartHelper psh) { for (ILangOperationsListener listener : AbstractToolManager.this.getListeners()) { listener.engineClientToolStart(pb, psh); } } } public class StartEngineDaemonOperation extends AbstractRunProcessTask { public StartEngineDaemonOperation(ProcessBuilder pb, ICancelMonitor cancelMonitor) { super(pb, cancelMonitor); } @Override protected void handleProcessStartResult(ProcessStartHelper psh) { for (ILangOperationsListener listener : getListeners()) { listener.engineDaemonStart(pb, psh); } } } /* ----------------- ----------------- */ /** * Helper to start engine client processes in the tool manager. */ public class ToolManagerEngineToolRunner implements IOperationHelper { protected final boolean throwOnNonZeroStatus; protected final EclipseCancelMonitor cm; public ToolManagerEngineToolRunner(IProgressMonitor monitor, boolean throwOnNonZeroStatus) { this.throwOnNonZeroStatus = throwOnNonZeroStatus; this.cm = new EclipseCancelMonitor(monitor); } @Override public ExternalProcessResult runProcess(ProcessBuilder pb, String input) throws CommonException, OperationCancellation { return new RunEngineClientOperation(pb, cm).runProcess(input, throwOnNonZeroStatus); } @Override public void logStatus(StatusException statusException) { LangCore.logStatusException(statusException); } } }
Merging [MelnormeLang]
plugin_ide.core/src-lang/melnorme/lang/ide/core/operations/AbstractToolManager.java
Merging [MelnormeLang]
<ide><path>lugin_ide.core/src-lang/melnorme/lang/ide/core/operations/AbstractToolManager.java <ide> return getSDKToolPathField(project).getValidatedField(); <ide> } <ide> <del> protected IValidatedField<Path> getSDKToolPathField(IProject project) { <add> private IValidatedField<Path> getSDKToolPathField(IProject project) { <ide> return new ValidatedSDKToolPath(project, getSDKToolPathValidator()); <ide> } <ide>
Java
apache-2.0
6e44b0d2c9a9d6d691b3352b50bcd34300a4b33d
0
lummyare/lummyare-test,zenefits/selenium,minhthuanit/selenium,lukeis/selenium,dbo/selenium,titusfortner/selenium,clavery/selenium,chrisblock/selenium,davehunt/selenium,quoideneuf/selenium,thanhpete/selenium,dcjohnson1989/selenium,minhthuanit/selenium,Jarob22/selenium,lrowe/selenium,bmannix/selenium,tkurnosova/selenium,eric-stanley/selenium,bayandin/selenium,aluedeke/chromedriver,alexec/selenium,alexec/selenium,misttechnologies/selenium,rrussell39/selenium,minhthuanit/selenium,denis-vilyuzhanin/selenium-fastview,jknguyen/josephknguyen-selenium,minhthuanit/selenium,lummyare/lummyare-lummy,jsakamoto/selenium,chrsmithdemos/selenium,thanhpete/selenium,Sravyaksr/selenium,mojwang/selenium,gorlemik/selenium,dcjohnson1989/selenium,lmtierney/selenium,kalyanjvn1/selenium,skurochkin/selenium,anshumanchatterji/selenium,orange-tv-blagnac/selenium,i17c/selenium,amikey/selenium,arunsingh/selenium,blueyed/selenium,TikhomirovSergey/selenium,soundcloud/selenium,RamaraoDonta/ramarao-clone,tbeadle/selenium,Dude-X/selenium,s2oBCN/selenium,Sravyaksr/selenium,onedox/selenium,markodolancic/selenium,clavery/selenium,rovner/selenium,jabbrwcky/selenium,xsyntrex/selenium,MeetMe/selenium,slongwang/selenium,tbeadle/selenium,misttechnologies/selenium,gotcha/selenium,xmhubj/selenium,krosenvold/selenium,dcjohnson1989/selenium,gorlemik/selenium,chrsmithdemos/selenium,jerome-jacob/selenium,oddui/selenium,denis-vilyuzhanin/selenium-fastview,lummyare/lummyare-lummy,alb-i986/selenium,anshumanchatterji/selenium,chrisblock/selenium,juangj/selenium,arunsingh/selenium,actmd/selenium,dibagga/selenium,bmannix/selenium,AutomatedTester/selenium,SouWilliams/selenium,MCGallaspy/selenium,alexec/selenium,dimacus/selenium,twalpole/selenium,valfirst/selenium,bartolkaruza/selenium,carsonmcdonald/selenium,sevaseva/selenium,blueyed/selenium,Ardesco/selenium,knorrium/selenium,rplevka/selenium,petruc/selenium,xsyntrex/selenium,kalyanjvn1/selenium,dkentw/selenium,SevInf/IEDriver,5hawnknight/selenium,Dude-X/selenium,BlackSmith/selenium,gabrielsimas/selenium,dibagga/selenium,i17c/selenium,knorrium/selenium,telefonicaid/selenium,dandv/selenium,Ardesco/selenium,krosenvold/selenium,bmannix/selenium,quoideneuf/selenium,amar-sharma/selenium,SevInf/IEDriver,petruc/selenium,joshmgrant/selenium,minhthuanit/selenium,asashour/selenium,mojwang/selenium,TikhomirovSergey/selenium,dcjohnson1989/selenium,sankha93/selenium,tarlabs/selenium,mach6/selenium,lummyare/lummyare-test,onedox/selenium,chrsmithdemos/selenium,vinay-qa/vinayit-android-server-apk,gabrielsimas/selenium,gorlemik/selenium,sebady/selenium,houchj/selenium,uchida/selenium,tarlabs/selenium,lummyare/lummyare-lummy,asolntsev/selenium,anshumanchatterji/selenium,soundcloud/selenium,titusfortner/selenium,livioc/selenium,orange-tv-blagnac/selenium,mojwang/selenium,jsarenik/jajomojo-selenium,jerome-jacob/selenium,wambat/selenium,lmtierney/selenium,joshbruning/selenium,DrMarcII/selenium,dandv/selenium,MCGallaspy/selenium,o-schneider/selenium,SeleniumHQ/selenium,aluedeke/chromedriver,stupidnetizen/selenium,p0deje/selenium,xmhubj/selenium,carlosroh/selenium,twalpole/selenium,JosephCastro/selenium,misttechnologies/selenium,p0deje/selenium,jknguyen/josephknguyen-selenium,bayandin/selenium,tarlabs/selenium,minhthuanit/selenium,HtmlUnit/selenium,dibagga/selenium,temyers/selenium,lummyare/lummyare-test,AutomatedTester/selenium,jerome-jacob/selenium,doungni/selenium,jabbrwcky/selenium,slongwang/selenium,Tom-Trumper/selenium,compstak/selenium,meksh/selenium,skurochkin/selenium,amar-sharma/selenium,wambat/selenium,yukaReal/selenium,krmahadevan/selenium,pulkitsinghal/selenium,sag-enorman/selenium,SevInf/IEDriver,tkurnosova/selenium,krosenvold/selenium-git-release-candidate,quoideneuf/selenium,knorrium/selenium,manuelpirez/selenium,lummyare/lummyare-test,TikhomirovSergey/selenium,oddui/selenium,Appdynamics/selenium,temyers/selenium,uchida/selenium,customcommander/selenium,BlackSmith/selenium,wambat/selenium,slongwang/selenium,p0deje/selenium,livioc/selenium,uchida/selenium,amikey/selenium,Jarob22/selenium,dkentw/selenium,zenefits/selenium,dbo/selenium,valfirst/selenium,pulkitsinghal/selenium,JosephCastro/selenium,SeleniumHQ/selenium,DrMarcII/selenium,dkentw/selenium,SouWilliams/selenium,temyers/selenium,skurochkin/selenium,Appdynamics/selenium,MCGallaspy/selenium,joshmgrant/selenium,lummyare/lummyare-lummy,manuelpirez/selenium,denis-vilyuzhanin/selenium-fastview,lilredindy/selenium,valfirst/selenium,lummyare/lummyare-test,valfirst/selenium,dimacus/selenium,actmd/selenium,arunsingh/selenium,sag-enorman/selenium,stupidnetizen/selenium,twalpole/selenium,vveliev/selenium,gotcha/selenium,s2oBCN/selenium,isaksky/selenium,gabrielsimas/selenium,jerome-jacob/selenium,aluedeke/chromedriver,alb-i986/selenium,minhthuanit/selenium,Jarob22/selenium,petruc/selenium,tkurnosova/selenium,denis-vilyuzhanin/selenium-fastview,jabbrwcky/selenium,wambat/selenium,Tom-Trumper/selenium,SeleniumHQ/selenium,davehunt/selenium,joshuaduffy/selenium,asolntsev/selenium,GorK-ChO/selenium,zenefits/selenium,sebady/selenium,anshumanchatterji/selenium,mestihudson/selenium,Appdynamics/selenium,joshmgrant/selenium,carlosroh/selenium,s2oBCN/selenium,doungni/selenium,asashour/selenium,juangj/selenium,skurochkin/selenium,SeleniumHQ/selenium,HtmlUnit/selenium,livioc/selenium,Herst/selenium,kalyanjvn1/selenium,gabrielsimas/selenium,SeleniumHQ/selenium,JosephCastro/selenium,customcommander/selenium,Appdynamics/selenium,titusfortner/selenium,SouWilliams/selenium,amikey/selenium,thanhpete/selenium,petruc/selenium,pulkitsinghal/selenium,denis-vilyuzhanin/selenium-fastview,MeetMe/selenium,misttechnologies/selenium,jknguyen/josephknguyen-selenium,stupidnetizen/selenium,Dude-X/selenium,Herst/selenium,blackboarddd/selenium,jknguyen/josephknguyen-selenium,freynaud/selenium,compstak/selenium,rplevka/selenium,TheBlackTuxCorp/selenium,jerome-jacob/selenium,AutomatedTester/selenium,chrsmithdemos/selenium,GorK-ChO/selenium,titusfortner/selenium,rrussell39/selenium,kalyanjvn1/selenium,Herst/selenium,twalpole/selenium,denis-vilyuzhanin/selenium-fastview,lrowe/selenium,sebady/selenium,kalyanjvn1/selenium,chrsmithdemos/selenium,orange-tv-blagnac/selenium,jsarenik/jajomojo-selenium,GorK-ChO/selenium,DrMarcII/selenium,alb-i986/selenium,wambat/selenium,meksh/selenium,DrMarcII/selenium,Sravyaksr/selenium,GorK-ChO/selenium,sebady/selenium,dbo/selenium,blueyed/selenium,eric-stanley/selenium,arunsingh/selenium,mestihudson/selenium,minhthuanit/selenium,mestihudson/selenium,amikey/selenium,lummyare/lummyare-lummy,lummyare/lummyare-lummy,manuelpirez/selenium,HtmlUnit/selenium,gabrielsimas/selenium,MeetMe/selenium,thanhpete/selenium,lmtierney/selenium,customcommander/selenium,onedox/selenium,isaksky/selenium,gregerrag/selenium,DrMarcII/selenium,o-schneider/selenium,amar-sharma/selenium,manuelpirez/selenium,tarlabs/selenium,gurayinan/selenium,Dude-X/selenium,Ardesco/selenium,titusfortner/selenium,jerome-jacob/selenium,isaksky/selenium,valfirst/selenium,SeleniumHQ/selenium,houchj/selenium,pulkitsinghal/selenium,bayandin/selenium,orange-tv-blagnac/selenium,alb-i986/selenium,customcommander/selenium,lilredindy/selenium,gregerrag/selenium,uchida/selenium,kalyanjvn1/selenium,Herst/selenium,rovner/selenium,krmahadevan/selenium,gemini-testing/selenium,telefonicaid/selenium,alb-i986/selenium,amar-sharma/selenium,gregerrag/selenium,gotcha/selenium,customcommander/selenium,jknguyen/josephknguyen-selenium,lukeis/selenium,lmtierney/selenium,pulkitsinghal/selenium,Appdynamics/selenium,dimacus/selenium,blueyed/selenium,actmd/selenium,chrisblock/selenium,DrMarcII/selenium,dbo/selenium,lummyare/lummyare-test,markodolancic/selenium,bartolkaruza/selenium,gorlemik/selenium,mach6/selenium,Sravyaksr/selenium,joshbruning/selenium,clavery/selenium,meksh/selenium,twalpole/selenium,zenefits/selenium,stupidnetizen/selenium,minhthuanit/selenium,asolntsev/selenium,gorlemik/selenium,HtmlUnit/selenium,tarlabs/selenium,sankha93/selenium,davehunt/selenium,rrussell39/selenium,dimacus/selenium,sri85/selenium,blueyed/selenium,lilredindy/selenium,carlosroh/selenium,lilredindy/selenium,tkurnosova/selenium,Jarob22/selenium,carsonmcdonald/selenium,vinay-qa/vinayit-android-server-apk,BlackSmith/selenium,aluedeke/chromedriver,sri85/selenium,krosenvold/selenium,mach6/selenium,rovner/selenium,sebady/selenium,krmahadevan/selenium,jsarenik/jajomojo-selenium,blueyed/selenium,BlackSmith/selenium,lmtierney/selenium,manuelpirez/selenium,titusfortner/selenium,Appdynamics/selenium,vveliev/selenium,sri85/selenium,davehunt/selenium,GorK-ChO/selenium,anshumanchatterji/selenium,onedox/selenium,krmahadevan/selenium,blackboarddd/selenium,sri85/selenium,kalyanjvn1/selenium,dbo/selenium,freynaud/selenium,jsakamoto/selenium,amikey/selenium,slongwang/selenium,i17c/selenium,dandv/selenium,bmannix/selenium,thanhpete/selenium,doungni/selenium,TheBlackTuxCorp/selenium,orange-tv-blagnac/selenium,anshumanchatterji/selenium,lrowe/selenium,chrisblock/selenium,gregerrag/selenium,thanhpete/selenium,xsyntrex/selenium,slongwang/selenium,oddui/selenium,SevInf/IEDriver,gregerrag/selenium,titusfortner/selenium,pulkitsinghal/selenium,dandv/selenium,misttechnologies/selenium,vinay-qa/vinayit-android-server-apk,arunsingh/selenium,uchida/selenium,slongwang/selenium,yukaReal/selenium,eric-stanley/selenium,Ardesco/selenium,krosenvold/selenium-git-release-candidate,dibagga/selenium,bayandin/selenium,gabrielsimas/selenium,TikhomirovSergey/selenium,krmahadevan/selenium,gorlemik/selenium,dibagga/selenium,markodolancic/selenium,telefonicaid/selenium,MeetMe/selenium,petruc/selenium,AutomatedTester/selenium,sankha93/selenium,SeleniumHQ/selenium,quoideneuf/selenium,DrMarcII/selenium,joshmgrant/selenium,thanhpete/selenium,tbeadle/selenium,joshuaduffy/selenium,knorrium/selenium,Tom-Trumper/selenium,MeetMe/selenium,sag-enorman/selenium,joshmgrant/selenium,dkentw/selenium,tarlabs/selenium,TikhomirovSergey/selenium,gurayinan/selenium,alexec/selenium,HtmlUnit/selenium,rrussell39/selenium,BlackSmith/selenium,soundcloud/selenium,p0deje/selenium,sag-enorman/selenium,krosenvold/selenium,bayandin/selenium,temyers/selenium,o-schneider/selenium,aluedeke/chromedriver,oddui/selenium,isaksky/selenium,mojwang/selenium,mach6/selenium,clavery/selenium,yukaReal/selenium,Tom-Trumper/selenium,5hawnknight/selenium,xmhubj/selenium,JosephCastro/selenium,xsyntrex/selenium,sebady/selenium,yukaReal/selenium,SouWilliams/selenium,krosenvold/selenium,aluedeke/chromedriver,joshuaduffy/selenium,denis-vilyuzhanin/selenium-fastview,houchj/selenium,lrowe/selenium,gabrielsimas/selenium,xmhubj/selenium,freynaud/selenium,stupidnetizen/selenium,krmahadevan/selenium,jsakamoto/selenium,Tom-Trumper/selenium,MCGallaspy/selenium,lilredindy/selenium,o-schneider/selenium,jabbrwcky/selenium,lmtierney/selenium,joshmgrant/selenium,Ardesco/selenium,jsarenik/jajomojo-selenium,chrsmithdemos/selenium,i17c/selenium,meksh/selenium,wambat/selenium,xsyntrex/selenium,jsarenik/jajomojo-selenium,MeetMe/selenium,Herst/selenium,s2oBCN/selenium,houchj/selenium,jknguyen/josephknguyen-selenium,kalyanjvn1/selenium,lrowe/selenium,Herst/selenium,mach6/selenium,isaksky/selenium,slongwang/selenium,Dude-X/selenium,dbo/selenium,rovner/selenium,Herst/selenium,sankha93/selenium,alb-i986/selenium,o-schneider/selenium,skurochkin/selenium,gurayinan/selenium,temyers/selenium,freynaud/selenium,JosephCastro/selenium,temyers/selenium,SouWilliams/selenium,bartolkaruza/selenium,krosenvold/selenium-git-release-candidate,onedox/selenium,Dude-X/selenium,rrussell39/selenium,gemini-testing/selenium,dimacus/selenium,vveliev/selenium,markodolancic/selenium,gemini-testing/selenium,customcommander/selenium,actmd/selenium,s2oBCN/selenium,joshuaduffy/selenium,actmd/selenium,SevInf/IEDriver,TheBlackTuxCorp/selenium,valfirst/selenium,krosenvold/selenium-git-release-candidate,krmahadevan/selenium,arunsingh/selenium,o-schneider/selenium,pulkitsinghal/selenium,joshbruning/selenium,chrisblock/selenium,gorlemik/selenium,quoideneuf/selenium,blackboarddd/selenium,meksh/selenium,jabbrwcky/selenium,TikhomirovSergey/selenium,telefonicaid/selenium,s2oBCN/selenium,TikhomirovSergey/selenium,jsakamoto/selenium,amikey/selenium,joshmgrant/selenium,isaksky/selenium,5hawnknight/selenium,knorrium/selenium,mach6/selenium,blackboarddd/selenium,rplevka/selenium,dimacus/selenium,soundcloud/selenium,zenefits/selenium,soundcloud/selenium,mestihudson/selenium,carsonmcdonald/selenium,arunsingh/selenium,p0deje/selenium,sebady/selenium,HtmlUnit/selenium,dkentw/selenium,MCGallaspy/selenium,Jarob22/selenium,eric-stanley/selenium,freynaud/selenium,asashour/selenium,oddui/selenium,actmd/selenium,bartolkaruza/selenium,Dude-X/selenium,asashour/selenium,quoideneuf/selenium,mach6/selenium,oddui/selenium,davehunt/selenium,wambat/selenium,tbeadle/selenium,dcjohnson1989/selenium,gurayinan/selenium,gotcha/selenium,dandv/selenium,HtmlUnit/selenium,lrowe/selenium,carlosroh/selenium,carsonmcdonald/selenium,i17c/selenium,tkurnosova/selenium,tbeadle/selenium,Ardesco/selenium,eric-stanley/selenium,gregerrag/selenium,gotcha/selenium,arunsingh/selenium,mestihudson/selenium,carsonmcdonald/selenium,markodolancic/selenium,lilredindy/selenium,blueyed/selenium,tbeadle/selenium,aluedeke/chromedriver,isaksky/selenium,twalpole/selenium,dandv/selenium,lmtierney/selenium,carlosroh/selenium,doungni/selenium,carlosroh/selenium,Tom-Trumper/selenium,manuelpirez/selenium,twalpole/selenium,mach6/selenium,pulkitsinghal/selenium,juangj/selenium,JosephCastro/selenium,krosenvold/selenium-git-release-candidate,rrussell39/selenium,chrisblock/selenium,sri85/selenium,Sravyaksr/selenium,vinay-qa/vinayit-android-server-apk,krmahadevan/selenium,tkurnosova/selenium,5hawnknight/selenium,gotcha/selenium,amar-sharma/selenium,p0deje/selenium,o-schneider/selenium,DrMarcII/selenium,TheBlackTuxCorp/selenium,petruc/selenium,Tom-Trumper/selenium,zenefits/selenium,bmannix/selenium,Sravyaksr/selenium,zenefits/selenium,lmtierney/selenium,gurayinan/selenium,p0deje/selenium,alb-i986/selenium,RamaraoDonta/ramarao-clone,isaksky/selenium,eric-stanley/selenium,sri85/selenium,blueyed/selenium,BlackSmith/selenium,davehunt/selenium,joshbruning/selenium,xsyntrex/selenium,Dude-X/selenium,customcommander/selenium,gotcha/selenium,petruc/selenium,juangj/selenium,houchj/selenium,amar-sharma/selenium,Dude-X/selenium,Sravyaksr/selenium,alexec/selenium,sevaseva/selenium,vveliev/selenium,jknguyen/josephknguyen-selenium,uchida/selenium,joshuaduffy/selenium,MeetMe/selenium,Appdynamics/selenium,mojwang/selenium,amikey/selenium,sankha93/selenium,jerome-jacob/selenium,HtmlUnit/selenium,tkurnosova/selenium,markodolancic/selenium,sevaseva/selenium,tkurnosova/selenium,manuelpirez/selenium,valfirst/selenium,wambat/selenium,SeleniumHQ/selenium,blackboarddd/selenium,yukaReal/selenium,Herst/selenium,skurochkin/selenium,dcjohnson1989/selenium,freynaud/selenium,dcjohnson1989/selenium,jabbrwcky/selenium,markodolancic/selenium,jsakamoto/selenium,soundcloud/selenium,uchida/selenium,lukeis/selenium,joshbruning/selenium,carsonmcdonald/selenium,uchida/selenium,p0deje/selenium,yukaReal/selenium,5hawnknight/selenium,HtmlUnit/selenium,mojwang/selenium,jknguyen/josephknguyen-selenium,davehunt/selenium,chrisblock/selenium,knorrium/selenium,jsakamoto/selenium,gurayinan/selenium,rplevka/selenium,lummyare/lummyare-test,blackboarddd/selenium,dimacus/selenium,rplevka/selenium,skurochkin/selenium,slongwang/selenium,joshmgrant/selenium,stupidnetizen/selenium,markodolancic/selenium,p0deje/selenium,gurayinan/selenium,doungni/selenium,compstak/selenium,mestihudson/selenium,tbeadle/selenium,rovner/selenium,Appdynamics/selenium,gotcha/selenium,dandv/selenium,eric-stanley/selenium,xsyntrex/selenium,houchj/selenium,compstak/selenium,SouWilliams/selenium,tarlabs/selenium,MeetMe/selenium,sevaseva/selenium,gurayinan/selenium,RamaraoDonta/ramarao-clone,gemini-testing/selenium,eric-stanley/selenium,gorlemik/selenium,dimacus/selenium,carlosroh/selenium,dandv/selenium,aluedeke/chromedriver,bayandin/selenium,bayandin/selenium,SeleniumHQ/selenium,lukeis/selenium,gregerrag/selenium,krosenvold/selenium-git-release-candidate,dibagga/selenium,actmd/selenium,jsakamoto/selenium,telefonicaid/selenium,doungni/selenium,SeleniumHQ/selenium,vinay-qa/vinayit-android-server-apk,lukeis/selenium,rovner/selenium,juangj/selenium,wambat/selenium,bmannix/selenium,Appdynamics/selenium,5hawnknight/selenium,mach6/selenium,joshbruning/selenium,rrussell39/selenium,asashour/selenium,krosenvold/selenium,alb-i986/selenium,sevaseva/selenium,temyers/selenium,tbeadle/selenium,compstak/selenium,bartolkaruza/selenium,vinay-qa/vinayit-android-server-apk,misttechnologies/selenium,HtmlUnit/selenium,anshumanchatterji/selenium,livioc/selenium,sevaseva/selenium,Jarob22/selenium,MCGallaspy/selenium,yukaReal/selenium,yukaReal/selenium,xsyntrex/selenium,Ardesco/selenium,customcommander/selenium,dibagga/selenium,gurayinan/selenium,gregerrag/selenium,bartolkaruza/selenium,skurochkin/selenium,valfirst/selenium,lmtierney/selenium,jsarenik/jajomojo-selenium,petruc/selenium,joshbruning/selenium,JosephCastro/selenium,sevaseva/selenium,lilredindy/selenium,onedox/selenium,tkurnosova/selenium,alexec/selenium,thanhpete/selenium,alexec/selenium,tarlabs/selenium,bayandin/selenium,AutomatedTester/selenium,asolntsev/selenium,lummyare/lummyare-test,orange-tv-blagnac/selenium,chrsmithdemos/selenium,customcommander/selenium,mestihudson/selenium,sag-enorman/selenium,quoideneuf/selenium,meksh/selenium,TheBlackTuxCorp/selenium,i17c/selenium,chrsmithdemos/selenium,soundcloud/selenium,manuelpirez/selenium,denis-vilyuzhanin/selenium-fastview,asolntsev/selenium,arunsingh/selenium,sebady/selenium,amikey/selenium,twalpole/selenium,krosenvold/selenium-git-release-candidate,misttechnologies/selenium,carlosroh/selenium,juangj/selenium,telefonicaid/selenium,clavery/selenium,TheBlackTuxCorp/selenium,valfirst/selenium,Tom-Trumper/selenium,Jarob22/selenium,sebady/selenium,compstak/selenium,clavery/selenium,valfirst/selenium,joshmgrant/selenium,i17c/selenium,sri85/selenium,oddui/selenium,krmahadevan/selenium,AutomatedTester/selenium,sag-enorman/selenium,compstak/selenium,blackboarddd/selenium,asolntsev/selenium,vveliev/selenium,xmhubj/selenium,jsarenik/jajomojo-selenium,joshuaduffy/selenium,vinay-qa/vinayit-android-server-apk,jsakamoto/selenium,gemini-testing/selenium,MCGallaspy/selenium,amar-sharma/selenium,misttechnologies/selenium,rrussell39/selenium,gemini-testing/selenium,Jarob22/selenium,RamaraoDonta/ramarao-clone,mestihudson/selenium,asashour/selenium,i17c/selenium,bmannix/selenium,telefonicaid/selenium,doungni/selenium,davehunt/selenium,joshuaduffy/selenium,sri85/selenium,blueyed/selenium,onedox/selenium,meksh/selenium,lukeis/selenium,jknguyen/josephknguyen-selenium,SevInf/IEDriver,Sravyaksr/selenium,TheBlackTuxCorp/selenium,lukeis/selenium,manuelpirez/selenium,RamaraoDonta/ramarao-clone,jabbrwcky/selenium,vinay-qa/vinayit-android-server-apk,valfirst/selenium,bmannix/selenium,TikhomirovSergey/selenium,joshmgrant/selenium,skurochkin/selenium,slongwang/selenium,tarlabs/selenium,gabrielsimas/selenium,AutomatedTester/selenium,blackboarddd/selenium,DrMarcII/selenium,GorK-ChO/selenium,petruc/selenium,mojwang/selenium,bartolkaruza/selenium,sevaseva/selenium,gemini-testing/selenium,vveliev/selenium,clavery/selenium,sag-enorman/selenium,xmhubj/selenium,joshbruning/selenium,compstak/selenium,rovner/selenium,asolntsev/selenium,JosephCastro/selenium,clavery/selenium,doungni/selenium,uchida/selenium,BlackSmith/selenium,denis-vilyuzhanin/selenium-fastview,doungni/selenium,5hawnknight/selenium,knorrium/selenium,telefonicaid/selenium,lummyare/lummyare-lummy,gemini-testing/selenium,o-schneider/selenium,mojwang/selenium,gabrielsimas/selenium,carlosroh/selenium,Sravyaksr/selenium,dibagga/selenium,isaksky/selenium,rovner/selenium,alexec/selenium,bartolkaruza/selenium,SevInf/IEDriver,rplevka/selenium,dimacus/selenium,Herst/selenium,bartolkaruza/selenium,TheBlackTuxCorp/selenium,stupidnetizen/selenium,kalyanjvn1/selenium,houchj/selenium,stupidnetizen/selenium,jabbrwcky/selenium,onedox/selenium,vveliev/selenium,tbeadle/selenium,joshmgrant/selenium,oddui/selenium,GorK-ChO/selenium,chrsmithdemos/selenium,TikhomirovSergey/selenium,lrowe/selenium,dibagga/selenium,jabbrwcky/selenium,jsarenik/jajomojo-selenium,5hawnknight/selenium,vinay-qa/vinayit-android-server-apk,dbo/selenium,MCGallaspy/selenium,asashour/selenium,yukaReal/selenium,houchj/selenium,lukeis/selenium,dbo/selenium,vveliev/selenium,gorlemik/selenium,dbo/selenium,actmd/selenium,amikey/selenium,jsakamoto/selenium,i17c/selenium,lukeis/selenium,sankha93/selenium,temyers/selenium,rovner/selenium,Ardesco/selenium,asolntsev/selenium,dandv/selenium,joshuaduffy/selenium,carsonmcdonald/selenium,krosenvold/selenium-git-release-candidate,soundcloud/selenium,JosephCastro/selenium,alb-i986/selenium,rrussell39/selenium,RamaraoDonta/ramarao-clone,asolntsev/selenium,s2oBCN/selenium,jsarenik/jajomojo-selenium,zenefits/selenium,rplevka/selenium,oddui/selenium,alexec/selenium,s2oBCN/selenium,dkentw/selenium,titusfortner/selenium,quoideneuf/selenium,amar-sharma/selenium,lilredindy/selenium,lummyare/lummyare-test,SevInf/IEDriver,onedox/selenium,davehunt/selenium,dkentw/selenium,gemini-testing/selenium,pulkitsinghal/selenium,titusfortner/selenium,quoideneuf/selenium,anshumanchatterji/selenium,soundcloud/selenium,SevInf/IEDriver,knorrium/selenium,SouWilliams/selenium,lrowe/selenium,s2oBCN/selenium,houchj/selenium,sag-enorman/selenium,livioc/selenium,temyers/selenium,Tom-Trumper/selenium,TheBlackTuxCorp/selenium,rplevka/selenium,joshbruning/selenium,juangj/selenium,sankha93/selenium,xsyntrex/selenium,anshumanchatterji/selenium,aluedeke/chromedriver,mojwang/selenium,rplevka/selenium,titusfortner/selenium,BlackSmith/selenium,sankha93/selenium,dkentw/selenium,freynaud/selenium,orange-tv-blagnac/selenium,BlackSmith/selenium,Jarob22/selenium,sri85/selenium,clavery/selenium,stupidnetizen/selenium,orange-tv-blagnac/selenium,joshuaduffy/selenium,titusfortner/selenium,dcjohnson1989/selenium,livioc/selenium,asashour/selenium,jerome-jacob/selenium,telefonicaid/selenium,livioc/selenium,asashour/selenium,Ardesco/selenium,RamaraoDonta/ramarao-clone,xmhubj/selenium,AutomatedTester/selenium,eric-stanley/selenium,o-schneider/selenium,gotcha/selenium,lilredindy/selenium,freynaud/selenium,SouWilliams/selenium,lrowe/selenium,SeleniumHQ/selenium,lummyare/lummyare-lummy,compstak/selenium,GorK-ChO/selenium,twalpole/selenium,lummyare/lummyare-lummy,juangj/selenium,gregerrag/selenium,sag-enorman/selenium,sankha93/selenium,chrisblock/selenium,meksh/selenium,jerome-jacob/selenium,carsonmcdonald/selenium,dkentw/selenium,bayandin/selenium,meksh/selenium,GorK-ChO/selenium,xmhubj/selenium,5hawnknight/selenium,freynaud/selenium,markodolancic/selenium,livioc/selenium,RamaraoDonta/ramarao-clone,actmd/selenium,SouWilliams/selenium,amar-sharma/selenium,carsonmcdonald/selenium,misttechnologies/selenium,mestihudson/selenium,orange-tv-blagnac/selenium,dcjohnson1989/selenium,knorrium/selenium,krosenvold/selenium,thanhpete/selenium,chrisblock/selenium,xmhubj/selenium,blackboarddd/selenium,livioc/selenium,bmannix/selenium,MeetMe/selenium,krosenvold/selenium,MCGallaspy/selenium,AutomatedTester/selenium,juangj/selenium,sevaseva/selenium,vveliev/selenium,RamaraoDonta/ramarao-clone,krosenvold/selenium,zenefits/selenium
/* * Copyright 2006 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.openqa.selenium.server; import java.util.LinkedList; /** * <p>Provides a synchronizing queue that holds a single entry * (eg a single Selenium Command).</p> * @author Paul Hammant * @version $Revision: 411 $ */ public class SingleEntryAsyncQueue { private LinkedList q = new LinkedList(); private boolean waitingThreadsShouldThrow = false; static private int timeout = SeleniumServer.DEFAULT_TIMEOUT; class OwnerAndDataPair extends Object { private Object owner; private Object data; public OwnerAndDataPair(Object ownerParm, Object dataParm) { owner = ownerParm; data = dataParm; } public Object getData() { return data; } public Object getOwner() { return owner; } public String toString() { return "" + data + " (from " + owner + ")"; } } public void clear() { this.waitingThreadsShouldThrow = true; if (q.isEmpty()) { q.add("dummy_to_wake_up_getting_thread____(if_there_is_one)"); } else { q.clear(); } synchronized(this) { this.notifyAll(); } } static public int getTimeout() { return SingleEntryAsyncQueue.timeout; } static public void setTimeout(int timeout) { SingleEntryAsyncQueue.timeout = timeout; } /** * <p>Retrieves the item from the queue.</p> * <p>If there's nothing in the queue right now, wait a period of time * for something to show up.</p> * @return the item in the queue * @throws SeleniumCommandTimedOutException if the timeout is exceeded. */ public synchronized Object get() { int retries = 0; while (q.isEmpty()) { if (q.isEmpty() & retries >= timeout) { throw new SeleniumCommandTimedOutException(); } try { wait(1000); } catch (InterruptedException e) { continue; } retries++; } verifyThisQueueWasNotHungAndThenCleared("get"); Object thing = ((OwnerAndDataPair) q.removeFirst()).getData(); notifyAll(); return thing; } private void verifyThisQueueWasNotHungAndThenCleared(String methodCalled) { if (waitingThreadsShouldThrow) { throw new RuntimeException("called queue." + methodCalled + "() when queue.clear() called"); } } public int size() { return q.size(); } public String toString() { return q.toString(); } /** * <p>Puts something in the queue.</p> * If there's already something available in the queue, wait * for that item to get picked up and removed from the queue. * @param obj - the thing to put in the queue */ public synchronized void put(Object thing) { verifyThisQueueWasNotHungAndThenCleared("put"); q.addLast(new OwnerAndDataPair("owner stub", thing)); notifyAll(); synchronized(this) { while (((OwnerAndDataPair) q.getFirst()).getData() != thing) { try { wait(); } catch (InterruptedException e) { } verifyThisQueueWasNotHungAndThenCleared("put"); } } } }
server/src/main/java/org/openqa/selenium/server/SingleEntryAsyncQueue.java
/* * Copyright 2006 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.openqa.selenium.server; import java.util.LinkedList; /** * <p>Provides a synchronizing queue that holds a single entry * (eg a single Selenium Command).</p> * @author Paul Hammant * @version $Revision: 411 $ */ public class SingleEntryAsyncQueue { private LinkedList q = new LinkedList(); private boolean waitingThreadsShouldThrow = false; static private int timeout = SeleniumServer.DEFAULT_TIMEOUT; class OwnerAndDataPair extends Object { private Object owner; private Object data; public OwnerAndDataPair(Object ownerParm, Object dataParm) { owner = ownerParm; data = dataParm; } public Object getData() { return data; } public Object getOwner() { return owner; } public String toString() { return "" + data + " (from " + owner + ")"; } } public void clear() { this.waitingThreadsShouldThrow = true; if (q.isEmpty()) { q.add("dummy_to_wake_up_getting_thread____(if_there_is_one)"); } else { q.clear(); } synchronized(this) { this.notifyAll(); } } static public int getTimeout() { return SingleEntryAsyncQueue.timeout; } static public void setTimeout(int timeout) { SingleEntryAsyncQueue.timeout = timeout; } /** * <p>Retrieves the item from the queue.</p> * <p>If there's nothing in the queue right now, wait a period of time * for something to show up.</p> * @return the item in the queue * @throws SeleniumCommandTimedOutException if the timeout is exceeded. */ public synchronized Object get() { int retries = 0; while (q.isEmpty()) { if (q.isEmpty() & retries >= timeout) { throw new SeleniumCommandTimedOutException(); } try { wait(1000); } catch (InterruptedException e) { continue; } retries++; } verifyThisQueueWasNotHungAndThenCleared("get"); Object thing = ((OwnerAndDataPair) q.removeFirst()).getData(); notifyAll(); return thing; } private void verifyThisQueueWasNotHungAndThenCleared(String methodCalled) { if (waitingThreadsShouldThrow) { throw new RuntimeException("called queue." + methodCalled + "() when queue.clear() called"); } } public int size() { return q.size(); } public String toString() { return q.toString(); } /** * <p>Puts something in the queue.</p> * If there's already something available in the queue, wait * for that item to get picked up and removed from the queue. * @param obj - the thing to put in the queue */ public synchronized void put(Object thing) { verifyThisQueueWasNotHungAndThenCleared("put"); q.addLast(new OwnerAndDataPair("owner stub", thing)); notifyAll(); synchronized(this) { while (((OwnerAndDataPair) q.getFirst()).getData() != thing) { try { wait(); } catch (InterruptedException e) { } verifyThisQueueWasNotHungAndThenCleared("put"); } } } }
reverting, whoops r2078
server/src/main/java/org/openqa/selenium/server/SingleEntryAsyncQueue.java
reverting, whoops
<ide><path>erver/src/main/java/org/openqa/selenium/server/SingleEntryAsyncQueue.java <ide> private LinkedList q = new LinkedList(); <ide> private boolean waitingThreadsShouldThrow = false; <ide> static private int timeout = SeleniumServer.DEFAULT_TIMEOUT; <del> <add> <ide> class OwnerAndDataPair extends Object { <ide> private Object owner; <ide> private Object data;
Java
lgpl-2.1
6ab14dd250cacc12dda03e6725f3a8cd87e4e651
0
cfallin/soot,anddann/soot,xph906/SootNew,mbenz89/soot,plast-lab/soot,plast-lab/soot,xph906/SootNew,mbenz89/soot,mbenz89/soot,xph906/SootNew,mbenz89/soot,cfallin/soot,plast-lab/soot,anddann/soot,anddann/soot,anddann/soot,cfallin/soot,cfallin/soot,xph906/SootNew
/* Soot - a J*va Optimization Framework * Copyright (C) 2003 Ondrej Lhotak * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ package soot.jimple.toolkits.callgraph; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import soot.ArrayType; import soot.Body; import soot.Context; import soot.EntryPoints; import soot.FastHierarchy; import soot.G; import soot.Kind; import soot.Local; import soot.MethodContext; import soot.MethodOrMethodContext; import soot.PackManager; import soot.PhaseOptions; import soot.RefType; import soot.Scene; import soot.SceneTransformer; import soot.SootClass; import soot.SootMethod; import soot.SootMethodRef; import soot.Transform; import soot.Type; import soot.Unit; import soot.Value; import soot.javaToJimple.LocalGenerator; import soot.jimple.AssignStmt; import soot.jimple.FieldRef; import soot.jimple.InstanceInvokeExpr; import soot.jimple.InvokeExpr; import soot.jimple.InvokeStmt; import soot.jimple.Jimple; import soot.jimple.NewArrayExpr; import soot.jimple.NewExpr; import soot.jimple.NewMultiArrayExpr; import soot.jimple.SpecialInvokeExpr; import soot.jimple.StaticFieldRef; import soot.jimple.StaticInvokeExpr; import soot.jimple.Stmt; import soot.jimple.StringConstant; import soot.jimple.VirtualInvokeExpr; import soot.options.CGOptions; import soot.tagkit.Host; import soot.tagkit.SourceLnPosTag; import soot.util.LargeNumberedMap; import soot.util.NumberedString; import soot.util.SmallNumberedMap; import soot.util.queue.ChunkedQueue; import soot.util.queue.QueueReader; /** Models the call graph. * @author Ondrej Lhotak */ public final class OnFlyCallGraphBuilder { public class DefaultReflectionModel implements ReflectionModel { protected CGOptions options = new CGOptions( PhaseOptions.v().getPhaseOptions("cg") ); protected HashSet<SootMethod> warnedAlready = new HashSet<SootMethod>(); public void classForName(SootMethod source, Stmt s) { List<Local> stringConstants = (List<Local>) methodToStringConstants.get(source); if( stringConstants == null ) methodToStringConstants.put(source, stringConstants = new ArrayList<Local>()); InvokeExpr ie = s.getInvokeExpr(); Value className = ie.getArg(0); if( className instanceof StringConstant ) { String cls = ((StringConstant) className ).value; constantForName( cls, source, s ); } else { Local constant = (Local) className; if( options.safe_forname() ) { for (SootMethod tgt : EntryPoints.v().clinits()) { addEdge( source, s, tgt, Kind.CLINIT ); } } else { for (SootClass cls : Scene.v().dynamicClasses()) { for (SootMethod clinit : EntryPoints.v().clinitsOf(cls)) { addEdge( source, s, clinit, Kind.CLINIT); } } VirtualCallSite site = new VirtualCallSite( s, source, null, null, Kind.CLINIT ); List<VirtualCallSite> sites = (List<VirtualCallSite>) stringConstToSites.get(constant); if (sites == null) { stringConstToSites.put(constant, sites = new ArrayList<VirtualCallSite>()); stringConstants.add(constant); } sites.add(site); } } } public void classNewInstance(SootMethod source, Stmt s) { if( options.safe_newinstance() ) { for (SootMethod tgt : EntryPoints.v().inits()) { addEdge( source, s, tgt, Kind.NEWINSTANCE ); } } else { for (SootClass cls : Scene.v().dynamicClasses()) { if( cls.declaresMethod(sigInit) ) { addEdge( source, s, cls.getMethod(sigInit), Kind.NEWINSTANCE ); } } if( options.verbose() ) { G.v().out.println( "Warning: Method "+source+ " is reachable, and calls Class.newInstance;"+ " graph will be incomplete!"+ " Use safe-newinstance option for a conservative result." ); } } } public void contructorNewInstance(SootMethod source, Stmt s) { if( options.safe_newinstance() ) { for (SootMethod tgt : EntryPoints.v().allInits()) { addEdge( source, s, tgt, Kind.NEWINSTANCE ); } } else { for (SootClass cls : Scene.v().dynamicClasses()) { for(SootMethod m: cls.getMethods()) { if(m.getName().equals("<init>")) { addEdge( source, s, m, Kind.NEWINSTANCE ); } } } if( options.verbose() ) { G.v().out.println( "Warning: Method "+source+ " is reachable, and calls Constructor.newInstance;"+ " graph will be incomplete!"+ " Use safe-newinstance option for a conservative result." ); } } } public void methodInvoke(SootMethod container, Stmt invokeStmt) { if( !warnedAlready(container) ) { if( options.verbose() ) { G.v().out.println( "Warning: call to "+ "java.lang.reflect.Method: invoke() from "+container+ "; graph will be incomplete!" ); } markWarned(container); } } private void markWarned(SootMethod m) { warnedAlready.add(m); } private boolean warnedAlready(SootMethod m) { return warnedAlready.contains(m); } } public class TraceBasedReflectionModel implements ReflectionModel { class Guard { public Guard(SootMethod container, Stmt stmt, String message) { this.container = container; this.stmt = stmt; this.message = message; } final SootMethod container; final Stmt stmt; final String message; } protected Map<SootMethod,Set<String>> classForNameReceivers; protected Map<SootMethod,Set<String>> classNewInstanceReceivers; protected Map<SootMethod,Set<String>> constructorNewInstanceReceivers; protected Map<SootMethod,Set<String>> methodInvokeReceivers; protected Set<Guard> guards; private boolean registeredTransformation = false; private TraceBasedReflectionModel() { classForNameReceivers = new HashMap<SootMethod, Set<String>>(); classNewInstanceReceivers = new HashMap<SootMethod, Set<String>>(); constructorNewInstanceReceivers = new HashMap<SootMethod, Set<String>>(); methodInvokeReceivers = new HashMap<SootMethod, Set<String>>(); guards = new HashSet<Guard>(); String logFile = options.reflection_log(); if(logFile==null) { throw new InternalError("Trace based refection model enabled but no trace file given!?"); } else { try { BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(logFile))); String line; int lines = 0; while((line=reader.readLine())!=null) { if(line.length()==0) continue; String[] portions = line.split(";"); String kind = portions[0]; String target = portions[1]; String source = portions[2]; Set<SootMethod> possibleSourceMethods = inferSource(source); for (SootMethod sourceMethod : possibleSourceMethods) { if(kind.equals("Class.forName")) { Set<String> receiverNames; if((receiverNames=classForNameReceivers.get(sourceMethod))==null) { classForNameReceivers.put(sourceMethod, receiverNames = new HashSet<String>()); } receiverNames.add(target); } else if(kind.equals("Class.newInstance")) { Set<String> receiverNames; if((receiverNames=classNewInstanceReceivers.get(sourceMethod))==null) { classNewInstanceReceivers.put(sourceMethod, receiverNames = new HashSet<String>()); } receiverNames.add(target); } else if(kind.equals("Method.invoke")) { if(!Scene.v().containsMethod(target)) { throw new RuntimeException("Unknown method for signature: "+target); } Set<String> receiverNames; if((receiverNames=methodInvokeReceivers.get(sourceMethod))==null) { methodInvokeReceivers.put(sourceMethod, receiverNames = new HashSet<String>()); } receiverNames.add(target); } else if (kind.equals("Constructor.newInstance")) { if(!Scene.v().containsMethod(target)) { throw new RuntimeException("Unknown method for signature: "+target); } Set<String> receiverNames; if((receiverNames=constructorNewInstanceReceivers.get(sourceMethod))==null) { constructorNewInstanceReceivers.put(sourceMethod, receiverNames = new HashSet<String>()); } receiverNames.add(target); } else throw new RuntimeException("Unknown entry kind: "+kind); } lines++; } if(options.verbose()) { G.v().out.println("Successfully read information about "+lines+" reflective call sites from trace file."); } } catch (FileNotFoundException e) { throw new RuntimeException("Trace file not found.",e); } catch (IOException e) { throw new RuntimeException(e); } } } private Set<SootMethod> inferSource(String source) { String classNameDotMethodName = source.substring(0,source.indexOf("(")); String className = classNameDotMethodName.substring(0,classNameDotMethodName.lastIndexOf(".")); String methodName = classNameDotMethodName.substring(classNameDotMethodName.lastIndexOf(".")+1); if(!Scene.v().containsClass(className)) { Scene.v().addBasicClass(className, SootClass.BODIES); Scene.v().loadBasicClasses(); if(!Scene.v().containsClass(className)) { throw new RuntimeException("Trace file refers to unknown class: "+className); } } SootClass sootClass = Scene.v().getSootClass(className); Set<SootMethod> methodsWithRightName = new HashSet<SootMethod>(); for (SootMethod m: sootClass.getMethods()) { if(m.getName().equals(methodName)) { methodsWithRightName.add(m); } } if(methodsWithRightName.isEmpty()) { throw new RuntimeException("Trace file refers to unknown method with name "+methodName+" in Class "+className); } else if(methodsWithRightName.size()==1) { return Collections.singleton(methodsWithRightName.iterator().next()); } else { int lineNumber = Integer.parseInt(source.substring(source.indexOf(":")+1, source.lastIndexOf(")"))); //more than one method with that name for (SootMethod sootMethod : methodsWithRightName) { if(coversLineNumber(lineNumber, sootMethod)) { return Collections.singleton(sootMethod); } if(sootMethod.hasActiveBody()) { Body body = sootMethod.getActiveBody(); if(coversLineNumber(lineNumber, body)) { return Collections.singleton(sootMethod); } for (Unit u : body.getUnits()) { if(coversLineNumber(lineNumber, u)) { return Collections.singleton(sootMethod); } } } } //if we get here then we found no method with the right line number information; //be conservative and return all method that we found return methodsWithRightName; } } private boolean coversLineNumber(int lineNumber, Host host) { SourceLnPosTag tag = (SourceLnPosTag) host.getTag("SourceLnPosTag"); if(tag!=null) { if(tag.startLn()<=lineNumber && tag.endLn()>=lineNumber) { return true; } } return false; } /** * Adds an edge to all class initializers of all possible receivers * of Class.forName() calls within source. */ public void classForName(SootMethod container, Stmt forNameInvokeStmt) { Set<String> classNames = classForNameReceivers.get(container); if(classNames==null || classNames.isEmpty()) { registerGuard(container, forNameInvokeStmt, "Class.forName()"); } else { for (String clsName : classNames) { constantForName( clsName, container, forNameInvokeStmt ); } } } public void classNewInstance(SootMethod container, Stmt newInstanceInvokeStmt) { Set<String> classNames = classNewInstanceReceivers.get(container); if(classNames==null || classNames.isEmpty()) { registerGuard(container, newInstanceInvokeStmt, "Class.newInstance()"); } else { for (String clsName : classNames) { SootClass cls = Scene.v().getSootClass(clsName); if( cls.declaresMethod(sigInit) ) { addEdge( container, newInstanceInvokeStmt, cls.getMethod(sigInit), Kind.NEWINSTANCE ); } } } } public void contructorNewInstance(SootMethod container, Stmt newInstanceInvokeStmt) { Set<String> constructorSignatures = constructorNewInstanceReceivers.get(container); if(constructorSignatures==null || constructorSignatures.isEmpty()) { registerGuard(container, newInstanceInvokeStmt, "Construtor.newInstance(..)"); } else { for (String constructorSignature : constructorSignatures) { SootMethod constructor = Scene.v().getMethod(constructorSignature); addEdge( container, newInstanceInvokeStmt, constructor, Kind.NEWINSTANCE ); } } } public void methodInvoke(SootMethod container, Stmt invokeStmt) { Set<String> methodSignatures = methodInvokeReceivers.get(container); if (methodSignatures == null || methodSignatures.isEmpty()) { registerGuard(container, invokeStmt, "Method.invoke(..)"); } else { for (String methodSignature : methodSignatures) { SootMethod method = Scene.v().getMethod(methodSignature); addEdge( container, invokeStmt, method, Kind.VIRTUAL ); } } } private void registerGuard(SootMethod container, Stmt stmt, String string) { guards.add(new Guard(container,stmt,string)); if(options.verbose()) { G.v().out.println("Incomplete trace file: Class.forName() is called in method '" + container+"' but trace contains no information about the receiver class of this call."); if(options.guards().equals("ignore")) { G.v().out.println("Guarding strategy is set to 'ignore'. Will ignore this problem."); } else if(options.guards().equals("print")) { G.v().out.println("Guarding strategy is set to 'print'. " + "Program will print a stack trace if this location is reached during execution."); } else if(options.guards().equals("throw")) { G.v().out.println("Guarding strategy is set to 'throw'. Program will throw an " + "Error if this location is reached during execution."); } else { throw new RuntimeException("Invalid value for phase option (guarding): "+options.guards()); } } if(!registeredTransformation) { registeredTransformation=true; PackManager.v().getPack("wjap").add(new Transform("wjap.guards",new SceneTransformer() { @Override protected void internalTransform(String phaseName, Map options) { for (Guard g : guards) { insertGuard(g); } } })); PhaseOptions.v().setPhaseOption("wjap.guards", "enabled"); } } private void insertGuard(Guard guard) { if(options.guards().equals("ignore")) return; SootMethod container = guard.container; Stmt insertionPoint = guard.stmt; if(!container.hasActiveBody()) { G.v().out.println("WARNING: Tried to insert guard into "+container+" but couldn't because method has no body."); } else { Body body = container.getActiveBody(); //exc = new Error RefType runtimeExceptionType = RefType.v("java.lang.Error"); NewExpr newExpr = Jimple.v().newNewExpr(runtimeExceptionType); LocalGenerator lg = new LocalGenerator(body); Local exceptionLocal = lg.generateLocal(runtimeExceptionType); AssignStmt assignStmt = Jimple.v().newAssignStmt(exceptionLocal, newExpr); body.getUnits().insertBefore(assignStmt, insertionPoint); //exc.<init>(message) SootMethodRef cref = runtimeExceptionType.getSootClass().getMethod("<init>", Collections.singletonList(RefType.v("java.lang.String"))).makeRef(); SpecialInvokeExpr constructorInvokeExpr = Jimple.v().newSpecialInvokeExpr(exceptionLocal, cref, StringConstant.v(guard.message)); InvokeStmt initStmt = Jimple.v().newInvokeStmt(constructorInvokeExpr); body.getUnits().insertAfter(initStmt, assignStmt); if(options.guards().equals("print")) { //exc.printStackTrace(); VirtualInvokeExpr printStackTraceExpr = Jimple.v().newVirtualInvokeExpr(exceptionLocal, Scene.v().getSootClass("java.lang.Throwable").getMethod("printStackTrace", Collections.emptyList()).makeRef()); InvokeStmt printStackTraceStmt = Jimple.v().newInvokeStmt(printStackTraceExpr); body.getUnits().insertAfter(printStackTraceStmt, initStmt); } else if(options.guards().equals("throw")) { body.getUnits().insertAfter(Jimple.v().newThrowStmt(exceptionLocal), initStmt); } else { throw new RuntimeException("Invalid value for phase option (guarding): "+options.guards()); } } } } /** context-insensitive stuff */ private final CallGraph cicg = new CallGraph(); private final HashSet<SootMethod> analyzedMethods = new HashSet<SootMethod>(); private final LargeNumberedMap receiverToSites = new LargeNumberedMap( Scene.v().getLocalNumberer() ); // Local -> List(VirtualCallSite) private final LargeNumberedMap methodToReceivers = new LargeNumberedMap( Scene.v().getMethodNumberer() ); // SootMethod -> List(Local) public LargeNumberedMap methodToReceivers() { return methodToReceivers; } private final SmallNumberedMap stringConstToSites = new SmallNumberedMap( Scene.v().getLocalNumberer() ); // Local -> List(VirtualCallSite) private final LargeNumberedMap methodToStringConstants = new LargeNumberedMap( Scene.v().getMethodNumberer() ); // SootMethod -> List(Local) public LargeNumberedMap methodToStringConstants() { return methodToStringConstants; } private CGOptions options; private boolean appOnly; /** context-sensitive stuff */ private ReachableMethods rm; private QueueReader worklist; private ContextManager cm; private final ChunkedQueue targetsQueue = new ChunkedQueue(); private final QueueReader targets = targetsQueue.reader(); public OnFlyCallGraphBuilder( ContextManager cm, ReachableMethods rm ) { this.cm = cm; this.rm = rm; worklist = rm.listener(); options = new CGOptions( PhaseOptions.v().getPhaseOptions("cg") ); if( !options.verbose() ) { G.v().out.println( "[Call Graph] For information on where the call graph may be incomplete, use the verbose option to the cg phase." ); } if(options.reflection_log()==null) { reflectionModel = new DefaultReflectionModel(); } else { reflectionModel = new TraceBasedReflectionModel(); } } public OnFlyCallGraphBuilder( ContextManager cm, ReachableMethods rm, boolean appOnly ) { this( cm, rm ); this.appOnly = appOnly; } public void processReachables() { while(true) { if( !worklist.hasNext() ) { rm.update(); if( !worklist.hasNext() ) break; } MethodOrMethodContext momc = (MethodOrMethodContext) worklist.next(); SootMethod m = momc.method(); if( appOnly && !m.getDeclaringClass().isApplicationClass() ) continue; if( analyzedMethods.add( m ) ) processNewMethod( m ); processNewMethodContext( momc ); } } public boolean wantTypes( Local receiver ) { return receiverToSites.get(receiver) != null; } public void addType( Local receiver, Context srcContext, Type type, Context typeContext ) { FastHierarchy fh = Scene.v().getOrMakeFastHierarchy(); for( Iterator siteIt = ((Collection) receiverToSites.get( receiver )).iterator(); siteIt.hasNext(); ) { final VirtualCallSite site = (VirtualCallSite) siteIt.next(); InstanceInvokeExpr iie = site.iie(); if( site.kind() == Kind.THREAD && !fh.canStoreType( type, clRunnable ) ) continue; if( site.iie() instanceof SpecialInvokeExpr ) { targetsQueue.add( VirtualCalls.v().resolveSpecial( (SpecialInvokeExpr) site.iie(), site.subSig(), site.container() ) ); } else { VirtualCalls.v().resolve( type, receiver.getType(), site.subSig(), site.container(), targetsQueue ); } while(targets.hasNext()) { SootMethod target = (SootMethod) targets.next(); cm.addVirtualEdge( MethodContext.v( site.container(), srcContext ), site.stmt(), target, site.kind(), typeContext ); } } } public boolean wantStringConstants( Local stringConst ) { return stringConstToSites.get(stringConst) != null; } public void addStringConstant( Local l, Context srcContext, String constant ) { for( Iterator siteIt = ((Collection) stringConstToSites.get( l )).iterator(); siteIt.hasNext(); ) { final VirtualCallSite site = (VirtualCallSite) siteIt.next(); if( constant == null ) { if( options.verbose() ) { G.v().out.println( "Warning: Method "+site.container()+ " is reachable, and calls Class.forName on a"+ " non-constant String; graph will be incomplete!"+ " Use safe-forname option for a conservative result." ); } } else { if( constant.length() > 0 && constant.charAt(0) == '[' ) { if( constant.length() > 1 && constant.charAt(1) == 'L' && constant.charAt(constant.length()-1) == ';' ) { constant = constant.substring(2,constant.length()-1); } else continue; } if( !Scene.v().containsClass( constant ) ) { if( options.verbose() ) { G.v().out.println( "Warning: Class "+constant+" is"+ " a dynamic class, and you did not specify"+ " it as such; graph will be incomplete!" ); } } else { SootClass sootcls = Scene.v().getSootClass( constant ); if( !sootcls.isApplicationClass() ) { sootcls.setLibraryClass(); } for (SootMethod clinit : EntryPoints.v().clinitsOf(sootcls)) { cm.addStaticEdge( MethodContext.v( site.container(), srcContext ), site.stmt(), clinit, Kind.CLINIT ); } } } } } /* End of public methods. */ private void addVirtualCallSite( Stmt s, SootMethod m, Local receiver, InstanceInvokeExpr iie, NumberedString subSig, Kind kind ) { List<VirtualCallSite> sites = (List<VirtualCallSite>) receiverToSites.get(receiver); if (sites == null) { receiverToSites.put(receiver, sites = new ArrayList<VirtualCallSite>()); List<Local> receivers = (List<Local>) methodToReceivers.get(m); if( receivers == null ) methodToReceivers.put(m, receivers = new ArrayList<Local>()); receivers.add(receiver); } sites.add(new VirtualCallSite(s, m, iie, subSig, kind)); } private void processNewMethod( SootMethod m ) { if( m.isNative() || m.isPhantom() ) { return; } Body b = m.retrieveActiveBody(); getImplicitTargets( m ); findReceivers(m, b); } private void findReceivers(SootMethod m, Body b) { for( Iterator sIt = b.getUnits().iterator(); sIt.hasNext(); ) { final Stmt s = (Stmt) sIt.next(); if (s.containsInvokeExpr()) { InvokeExpr ie = s.getInvokeExpr(); if (ie instanceof InstanceInvokeExpr) { InstanceInvokeExpr iie = (InstanceInvokeExpr) ie; Local receiver = (Local) iie.getBase(); NumberedString subSig = iie.getMethodRef().getSubSignature(); addVirtualCallSite( s, m, receiver, iie, subSig, Edge.ieToKind(iie) ); if( subSig == sigStart ) { addVirtualCallSite( s, m, receiver, iie, sigRun, Kind.THREAD ); } } else { SootMethod tgt = ((StaticInvokeExpr) ie).getMethod(); addEdge(m, s, tgt); if( tgt.getSignature().equals( "<java.security.AccessController: java.lang.Object doPrivileged(java.security.PrivilegedAction)>" ) || tgt.getSignature().equals( "<java.security.AccessController: java.lang.Object doPrivileged(java.security.PrivilegedExceptionAction)>" ) || tgt.getSignature().equals( "<java.security.AccessController: java.lang.Object doPrivileged(java.security.PrivilegedAction,java.security.AccessControlContext)>" ) || tgt.getSignature().equals( "<java.security.AccessController: java.lang.Object doPrivileged(java.security.PrivilegedExceptionAction,java.security.AccessControlContext)>" ) ) { Local receiver = (Local) ie.getArg(0); addVirtualCallSite( s, m, receiver, null, sigObjRun, Kind.PRIVILEGED ); } } } } } ReflectionModel reflectionModel; private void getImplicitTargets( SootMethod source ) { final SootClass scl = source.getDeclaringClass(); if( source.isNative() || source.isPhantom() ) return; if( source.getSubSignature().indexOf( "<init>" ) >= 0 ) { handleInit(source, scl); } Body b = source.retrieveActiveBody(); for( Iterator sIt = b.getUnits().iterator(); sIt.hasNext(); ) { final Stmt s = (Stmt) sIt.next(); if( s.containsInvokeExpr() ) { InvokeExpr ie = s.getInvokeExpr(); if( ie.getMethod().getSignature().equals( "<java.lang.reflect.Method: java.lang.Object invoke(java.lang.Object,java.lang.Object[])>" ) ) { reflectionModel.methodInvoke(source,s); } if( ie.getMethod().getSignature().equals( "<java.lang.Class: java.lang.Object newInstance()>" ) ) { reflectionModel.classNewInstance(source,s); } if( ie.getMethod().getSignature().equals( "<java.lang.reflect.Constructor: java.lang.Object newInstance(java.lang.Object[])>" ) ) { reflectionModel.contructorNewInstance(source, s); } if( ie.getMethodRef().getSubSignature() == sigForName ) { reflectionModel.classForName(source,s); } if( ie instanceof StaticInvokeExpr ) { SootClass cl = ie.getMethodRef().declaringClass(); for (SootMethod clinit : EntryPoints.v().clinitsOf(cl)) { addEdge( source, s, clinit, Kind.CLINIT ); } } } if( s.containsFieldRef() ) { FieldRef fr = s.getFieldRef(); if( fr instanceof StaticFieldRef ) { SootClass cl = fr.getFieldRef().declaringClass(); for (SootMethod clinit : EntryPoints.v().clinitsOf(cl)) { addEdge( source, s, clinit, Kind.CLINIT ); } } } if( s instanceof AssignStmt ) { Value rhs = ((AssignStmt)s).getRightOp(); if( rhs instanceof NewExpr ) { NewExpr r = (NewExpr) rhs; SootClass cl = r.getBaseType().getSootClass(); for (SootMethod clinit : EntryPoints.v().clinitsOf(cl)) { addEdge( source, s, clinit, Kind.CLINIT ); } } else if( rhs instanceof NewArrayExpr || rhs instanceof NewMultiArrayExpr ) { Type t = rhs.getType(); if( t instanceof ArrayType ) t = ((ArrayType)t).baseType; if( t instanceof RefType ) { SootClass cl = ((RefType) t).getSootClass(); for (SootMethod clinit : EntryPoints.v().clinitsOf(cl)) { addEdge( source, s, clinit, Kind.CLINIT ); } } } } } } private void processNewMethodContext( MethodOrMethodContext momc ) { SootMethod m = momc.method(); Object ctxt = momc.context(); Iterator it = cicg.edgesOutOf(m); while( it.hasNext() ) { Edge e = (Edge) it.next(); cm.addStaticEdge( momc, e.srcUnit(), e.tgt(), e.kind() ); } } private void handleInit(SootMethod source, final SootClass scl) { addEdge( source, null, scl, sigFinalize, Kind.FINALIZE ); FastHierarchy fh = Scene.v().getOrMakeFastHierarchy(); } private void constantForName( String cls, SootMethod src, Stmt srcUnit ) { if( cls.length() > 0 && cls.charAt(0) == '[' ) { if( cls.length() > 1 && cls.charAt(1) == 'L' && cls.charAt(cls.length()-1) == ';' ) { cls = cls.substring(2,cls.length()-1); constantForName( cls, src, srcUnit ); } } else { if( !Scene.v().containsClass( cls ) ) { if( options.verbose() ) { G.v().out.println( "Warning: Class "+cls+" is"+ " a dynamic class, and you did not specify"+ " it as such; graph will be incomplete!" ); } } else { SootClass sootcls = Scene.v().getSootClass( cls ); if( !sootcls.isApplicationClass() ) { sootcls.setLibraryClass(); } for (SootMethod clinit : EntryPoints.v().clinitsOf(sootcls)) { addEdge( src, srcUnit, clinit, Kind.CLINIT ); } } } } private void addEdge( SootMethod src, Stmt stmt, SootMethod tgt, Kind kind ) { cicg.addEdge( new Edge( src, stmt, tgt, kind ) ); } private void addEdge( SootMethod src, Stmt stmt, SootClass cls, NumberedString methodSubSig, Kind kind ) { if( cls.declaresMethod( methodSubSig ) ) { addEdge( src, stmt, cls.getMethod( methodSubSig ), kind ); } } private void addEdge( SootMethod src, Stmt stmt, SootMethod tgt ) { InvokeExpr ie = stmt.getInvokeExpr(); addEdge( src, stmt, tgt, Edge.ieToKind(ie) ); } protected final NumberedString sigFinalize = Scene.v().getSubSigNumberer(). findOrAdd( "void finalize()" ); protected final NumberedString sigInit = Scene.v().getSubSigNumberer(). findOrAdd( "void <init>()" ); protected final NumberedString sigStart = Scene.v().getSubSigNumberer(). findOrAdd( "void start()" ); protected final NumberedString sigRun = Scene.v().getSubSigNumberer(). findOrAdd( "void run()" ); protected final NumberedString sigObjRun = Scene.v().getSubSigNumberer(). findOrAdd( "java.lang.Object run()" ); protected final NumberedString sigForName = Scene.v().getSubSigNumberer(). findOrAdd( "java.lang.Class forName(java.lang.String)" ); protected final RefType clRunnable = RefType.v("java.lang.Runnable"); }
src/soot/jimple/toolkits/callgraph/OnFlyCallGraphBuilder.java
/* Soot - a J*va Optimization Framework * Copyright (C) 2003 Ondrej Lhotak * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ package soot.jimple.toolkits.callgraph; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import soot.ArrayType; import soot.Body; import soot.Context; import soot.EntryPoints; import soot.FastHierarchy; import soot.G; import soot.Kind; import soot.Local; import soot.MethodContext; import soot.MethodOrMethodContext; import soot.PackManager; import soot.PhaseOptions; import soot.RefType; import soot.Scene; import soot.SceneTransformer; import soot.SootClass; import soot.SootMethod; import soot.SootMethodRef; import soot.Transform; import soot.Type; import soot.Unit; import soot.Value; import soot.javaToJimple.LocalGenerator; import soot.jimple.AssignStmt; import soot.jimple.FieldRef; import soot.jimple.InstanceInvokeExpr; import soot.jimple.InvokeExpr; import soot.jimple.InvokeStmt; import soot.jimple.Jimple; import soot.jimple.NewArrayExpr; import soot.jimple.NewExpr; import soot.jimple.NewMultiArrayExpr; import soot.jimple.SpecialInvokeExpr; import soot.jimple.StaticFieldRef; import soot.jimple.StaticInvokeExpr; import soot.jimple.Stmt; import soot.jimple.StringConstant; import soot.jimple.VirtualInvokeExpr; import soot.options.CGOptions; import soot.tagkit.Host; import soot.tagkit.SourceLnPosTag; import soot.util.LargeNumberedMap; import soot.util.NumberedString; import soot.util.SmallNumberedMap; import soot.util.queue.ChunkedQueue; import soot.util.queue.QueueReader; /** Models the call graph. * @author Ondrej Lhotak */ public final class OnFlyCallGraphBuilder { public class DefaultReflectionModel implements ReflectionModel { protected CGOptions options = new CGOptions( PhaseOptions.v().getPhaseOptions("cg") ); protected HashSet<SootMethod> warnedAlready = new HashSet<SootMethod>(); public void classForName(SootMethod source, Stmt s) { List<Local> stringConstants = (List<Local>) methodToStringConstants.get(source); if( stringConstants == null ) methodToStringConstants.put(source, stringConstants = new ArrayList<Local>()); InvokeExpr ie = s.getInvokeExpr(); Value className = ie.getArg(0); if( className instanceof StringConstant ) { String cls = ((StringConstant) className ).value; constantForName( cls, source, s ); } else { Local constant = (Local) className; if( options.safe_forname() ) { for (SootMethod tgt : EntryPoints.v().clinits()) { addEdge( source, s, tgt, Kind.CLINIT ); } } else { for (SootClass cls : Scene.v().dynamicClasses()) { for (SootMethod clinit : EntryPoints.v().clinitsOf(cls)) { addEdge( source, s, clinit, Kind.CLINIT); } } VirtualCallSite site = new VirtualCallSite( s, source, null, null, Kind.CLINIT ); List<VirtualCallSite> sites = (List<VirtualCallSite>) stringConstToSites.get(constant); if (sites == null) { stringConstToSites.put(constant, sites = new ArrayList<VirtualCallSite>()); stringConstants.add(constant); } sites.add(site); } } } public void classNewInstance(SootMethod source, Stmt s) { if( options.safe_newinstance() ) { for (SootMethod tgt : EntryPoints.v().inits()) { addEdge( source, s, tgt, Kind.NEWINSTANCE ); } } else { for (SootClass cls : Scene.v().dynamicClasses()) { if( cls.declaresMethod(sigInit) ) { addEdge( source, s, cls.getMethod(sigInit), Kind.NEWINSTANCE ); } } if( options.verbose() ) { G.v().out.println( "Warning: Method "+source+ " is reachable, and calls Class.newInstance;"+ " graph will be incomplete!"+ " Use safe-newinstance option for a conservative result." ); } } } public void contructorNewInstance(SootMethod source, Stmt s) { if( options.safe_newinstance() ) { for (SootMethod tgt : EntryPoints.v().allInits()) { addEdge( source, s, tgt, Kind.NEWINSTANCE ); } } else { for (SootClass cls : Scene.v().dynamicClasses()) { for(SootMethod m: cls.getMethods()) { if(m.getName().equals("<init>")) { addEdge( source, s, m, Kind.NEWINSTANCE ); } } } if( options.verbose() ) { G.v().out.println( "Warning: Method "+source+ " is reachable, and calls Constructor.newInstance;"+ " graph will be incomplete!"+ " Use safe-newinstance option for a conservative result." ); } } } public void methodInvoke(SootMethod container, Stmt invokeStmt) { if( !warnedAlready(container) ) { if( options.verbose() ) { G.v().out.println( "Warning: call to "+ "java.lang.reflect.Method: invoke() from "+container+ "; graph will be incomplete!" ); } markWarned(container); } } private void markWarned(SootMethod m) { warnedAlready.add(m); } private boolean warnedAlready(SootMethod m) { return warnedAlready.contains(m); } } public class TraceBasedReflectionModel implements ReflectionModel { class Guard { public Guard(SootMethod container, Stmt stmt, String message) { this.container = container; this.stmt = stmt; this.message = message; } final SootMethod container; final Stmt stmt; final String message; } protected Map<SootMethod,Set<String>> classForNameReceivers; protected Map<SootMethod,Set<String>> classNewInstanceReceivers; protected Map<SootMethod,Set<String>> constructorNewInstanceReceivers; protected Map<SootMethod,Set<String>> methodInvokeReceivers; protected Set<Guard> guards; private boolean registeredTransformation = false; private TraceBasedReflectionModel() { classForNameReceivers = new HashMap<SootMethod, Set<String>>(); classNewInstanceReceivers = new HashMap<SootMethod, Set<String>>(); constructorNewInstanceReceivers = new HashMap<SootMethod, Set<String>>(); methodInvokeReceivers = new HashMap<SootMethod, Set<String>>(); guards = new HashSet<Guard>(); String logFile = options.reflection_log(); if(logFile==null) { throw new InternalError("Trace based refection model enabled but no trace file given!?"); } else { try { BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(logFile))); String line; int lines = 0; while((line=reader.readLine())!=null) { if(line.length()==0) continue; String[] portions = line.split(";"); String kind = portions[0]; String target = portions[1]; String source = portions[2]; Set<SootMethod> possibleSourceMethods = inferSource(source); for (SootMethod sourceMethod : possibleSourceMethods) { if(kind.equals("Class.forName")) { Set<String> receiverNames; if((receiverNames=classForNameReceivers.get(sourceMethod))==null) { classForNameReceivers.put(sourceMethod, receiverNames = new HashSet<String>()); } receiverNames.add(target); } else if(kind.equals("Class.newInstance")) { Set<String> receiverNames; if((receiverNames=classNewInstanceReceivers.get(sourceMethod))==null) { classNewInstanceReceivers.put(sourceMethod, receiverNames = new HashSet<String>()); } receiverNames.add(target); } else if(kind.equals("Method.invoke")) { if(!Scene.v().containsMethod(target)) { G.v().out.println("Warning: Unknown method for signature: "+target); } Set<String> receiverNames; if((receiverNames=methodInvokeReceivers.get(sourceMethod))==null) { methodInvokeReceivers.put(sourceMethod, receiverNames = new HashSet<String>()); } receiverNames.add(target); } else if (kind.equals("Constructor.newInstance")) { if(!Scene.v().containsMethod(target)) { throw new RuntimeException("Unknown method for signature: "+target); } Set<String> receiverNames; if((receiverNames=constructorNewInstanceReceivers.get(sourceMethod))==null) { constructorNewInstanceReceivers.put(sourceMethod, receiverNames = new HashSet<String>()); } receiverNames.add(target); } else throw new RuntimeException("Unknown entry kind: "+kind); } lines++; } if(options.verbose()) { G.v().out.println("Successfully read information about "+lines+" reflective call sites from trace file."); } } catch (FileNotFoundException e) { throw new RuntimeException("Trace file not found.",e); } catch (IOException e) { throw new RuntimeException(e); } } } private Set<SootMethod> inferSource(String source) { String classNameDotMethodName = source.substring(0,source.indexOf("(")); String className = classNameDotMethodName.substring(0,classNameDotMethodName.lastIndexOf(".")); String methodName = classNameDotMethodName.substring(classNameDotMethodName.lastIndexOf(".")+1); if(!Scene.v().containsClass(className)) { Scene.v().addBasicClass(className, SootClass.BODIES); Scene.v().loadBasicClasses(); if(!Scene.v().containsClass(className)) { throw new RuntimeException("Trace file refers to unknown class: "+className); } } SootClass sootClass = Scene.v().getSootClass(className); Set<SootMethod> methodsWithRightName = new HashSet<SootMethod>(); for (SootMethod m: sootClass.getMethods()) { if(m.getName().equals(methodName)) { methodsWithRightName.add(m); } } if(methodsWithRightName.isEmpty()) { throw new RuntimeException("Trace file refers to unknown method with name "+methodName+" in Class "+className); } else if(methodsWithRightName.size()==1) { return Collections.singleton(methodsWithRightName.iterator().next()); } else { int lineNumber = Integer.parseInt(source.substring(source.indexOf(":")+1, source.lastIndexOf(")"))); //more than one method with that name for (SootMethod sootMethod : methodsWithRightName) { if(coversLineNumber(lineNumber, sootMethod)) { return Collections.singleton(sootMethod); } if(sootMethod.hasActiveBody()) { Body body = sootMethod.getActiveBody(); if(coversLineNumber(lineNumber, body)) { return Collections.singleton(sootMethod); } for (Unit u : body.getUnits()) { if(coversLineNumber(lineNumber, u)) { return Collections.singleton(sootMethod); } } } } //if we get here then we found no method with the right line number information; //be conservative and return all method that we found return methodsWithRightName; } } private boolean coversLineNumber(int lineNumber, Host host) { SourceLnPosTag tag = (SourceLnPosTag) host.getTag("SourceLnPosTag"); if(tag!=null) { if(tag.startLn()<=lineNumber && tag.endLn()>=lineNumber) { return true; } } return false; } /** * Adds an edge to all class initializers of all possible receivers * of Class.forName() calls within source. */ public void classForName(SootMethod container, Stmt forNameInvokeStmt) { Set<String> classNames = classForNameReceivers.get(container); if(classNames==null || classNames.isEmpty()) { registerGuard(container, forNameInvokeStmt, "Class.forName()"); } else { for (String clsName : classNames) { constantForName( clsName, container, forNameInvokeStmt ); } } } public void classNewInstance(SootMethod container, Stmt newInstanceInvokeStmt) { Set<String> classNames = classNewInstanceReceivers.get(container); if(classNames==null || classNames.isEmpty()) { registerGuard(container, newInstanceInvokeStmt, "Class.newInstance()"); } else { for (String clsName : classNames) { SootClass cls = Scene.v().getSootClass(clsName); if( cls.declaresMethod(sigInit) ) { addEdge( container, newInstanceInvokeStmt, cls.getMethod(sigInit), Kind.NEWINSTANCE ); } } } } public void contructorNewInstance(SootMethod container, Stmt newInstanceInvokeStmt) { Set<String> constructorSignatures = constructorNewInstanceReceivers.get(container); if(constructorSignatures==null || constructorSignatures.isEmpty()) { registerGuard(container, newInstanceInvokeStmt, "Construtor.newInstance(..)"); } else { for (String constructorSignature : constructorSignatures) { SootMethod constructor = Scene.v().getMethod(constructorSignature); addEdge( container, newInstanceInvokeStmt, constructor, Kind.NEWINSTANCE ); } } } public void methodInvoke(SootMethod container, Stmt invokeStmt) { Set<String> methodSignatures = methodInvokeReceivers.get(container); if (methodSignatures == null || methodSignatures.isEmpty()) { registerGuard(container, invokeStmt, "Method.invoke(..)"); } else { for (String methodSignature : methodSignatures) { SootMethod method = Scene.v().getMethod(methodSignature); addEdge( container, invokeStmt, method, Kind.VIRTUAL ); } } } private void registerGuard(SootMethod container, Stmt stmt, String string) { guards.add(new Guard(container,stmt,string)); if(options.verbose()) { G.v().out.println("Incomplete trace file: Class.forName() is called in method '" + container+"' but trace contains no information about the receiver class of this call."); if(options.guards().equals("ignore")) { G.v().out.println("Guarding strategy is set to 'ignore'. Will ignore this problem."); } else if(options.guards().equals("print")) { G.v().out.println("Guarding strategy is set to 'print'. " + "Program will print a stack trace if this location is reached during execution."); } else if(options.guards().equals("throw")) { G.v().out.println("Guarding strategy is set to 'throw'. Program will throw an " + "Error if this location is reached during execution."); } else { throw new RuntimeException("Invalid value for phase option (guarding): "+options.guards()); } } if(!registeredTransformation) { registeredTransformation=true; PackManager.v().getPack("wjap").add(new Transform("wjap.guards",new SceneTransformer() { @Override protected void internalTransform(String phaseName, Map options) { for (Guard g : guards) { insertGuard(g); } } })); PhaseOptions.v().setPhaseOption("wjap.guards", "enabled"); } } private void insertGuard(Guard guard) { if(options.guards().equals("ignore")) return; SootMethod container = guard.container; Stmt insertionPoint = guard.stmt; if(!container.hasActiveBody()) { G.v().out.println("WARNING: Tried to insert guard into "+container+" but couldn't because method has no body."); } else { Body body = container.getActiveBody(); //exc = new Error RefType runtimeExceptionType = RefType.v("java.lang.Error"); NewExpr newExpr = Jimple.v().newNewExpr(runtimeExceptionType); LocalGenerator lg = new LocalGenerator(body); Local exceptionLocal = lg.generateLocal(runtimeExceptionType); AssignStmt assignStmt = Jimple.v().newAssignStmt(exceptionLocal, newExpr); body.getUnits().insertBefore(assignStmt, insertionPoint); //exc.<init>(message) SootMethodRef cref = runtimeExceptionType.getSootClass().getMethod("<init>", Collections.singletonList(RefType.v("java.lang.String"))).makeRef(); SpecialInvokeExpr constructorInvokeExpr = Jimple.v().newSpecialInvokeExpr(exceptionLocal, cref, StringConstant.v(guard.message)); InvokeStmt initStmt = Jimple.v().newInvokeStmt(constructorInvokeExpr); body.getUnits().insertAfter(initStmt, assignStmt); if(options.guards().equals("print")) { //exc.printStackTrace(); VirtualInvokeExpr printStackTraceExpr = Jimple.v().newVirtualInvokeExpr(exceptionLocal, Scene.v().getSootClass("java.lang.Throwable").getMethod("printStackTrace", Collections.emptyList()).makeRef()); InvokeStmt printStackTraceStmt = Jimple.v().newInvokeStmt(printStackTraceExpr); body.getUnits().insertAfter(printStackTraceStmt, initStmt); } else if(options.guards().equals("throw")) { body.getUnits().insertAfter(Jimple.v().newThrowStmt(exceptionLocal), initStmt); } else { throw new RuntimeException("Invalid value for phase option (guarding): "+options.guards()); } } } } /** context-insensitive stuff */ private final CallGraph cicg = new CallGraph(); private final HashSet<SootMethod> analyzedMethods = new HashSet<SootMethod>(); private final LargeNumberedMap receiverToSites = new LargeNumberedMap( Scene.v().getLocalNumberer() ); // Local -> List(VirtualCallSite) private final LargeNumberedMap methodToReceivers = new LargeNumberedMap( Scene.v().getMethodNumberer() ); // SootMethod -> List(Local) public LargeNumberedMap methodToReceivers() { return methodToReceivers; } private final SmallNumberedMap stringConstToSites = new SmallNumberedMap( Scene.v().getLocalNumberer() ); // Local -> List(VirtualCallSite) private final LargeNumberedMap methodToStringConstants = new LargeNumberedMap( Scene.v().getMethodNumberer() ); // SootMethod -> List(Local) public LargeNumberedMap methodToStringConstants() { return methodToStringConstants; } private CGOptions options; private boolean appOnly; /** context-sensitive stuff */ private ReachableMethods rm; private QueueReader worklist; private ContextManager cm; private final ChunkedQueue targetsQueue = new ChunkedQueue(); private final QueueReader targets = targetsQueue.reader(); public OnFlyCallGraphBuilder( ContextManager cm, ReachableMethods rm ) { this.cm = cm; this.rm = rm; worklist = rm.listener(); options = new CGOptions( PhaseOptions.v().getPhaseOptions("cg") ); if( !options.verbose() ) { G.v().out.println( "[Call Graph] For information on where the call graph may be incomplete, use the verbose option to the cg phase." ); } if(options.reflection_log()==null) { reflectionModel = new DefaultReflectionModel(); } else { reflectionModel = new TraceBasedReflectionModel(); } } public OnFlyCallGraphBuilder( ContextManager cm, ReachableMethods rm, boolean appOnly ) { this( cm, rm ); this.appOnly = appOnly; } public void processReachables() { while(true) { if( !worklist.hasNext() ) { rm.update(); if( !worklist.hasNext() ) break; } MethodOrMethodContext momc = (MethodOrMethodContext) worklist.next(); SootMethod m = momc.method(); if( appOnly && !m.getDeclaringClass().isApplicationClass() ) continue; if( analyzedMethods.add( m ) ) processNewMethod( m ); processNewMethodContext( momc ); } } public boolean wantTypes( Local receiver ) { return receiverToSites.get(receiver) != null; } public void addType( Local receiver, Context srcContext, Type type, Context typeContext ) { FastHierarchy fh = Scene.v().getOrMakeFastHierarchy(); for( Iterator siteIt = ((Collection) receiverToSites.get( receiver )).iterator(); siteIt.hasNext(); ) { final VirtualCallSite site = (VirtualCallSite) siteIt.next(); InstanceInvokeExpr iie = site.iie(); if( site.kind() == Kind.THREAD && !fh.canStoreType( type, clRunnable ) ) continue; if( site.iie() instanceof SpecialInvokeExpr ) { targetsQueue.add( VirtualCalls.v().resolveSpecial( (SpecialInvokeExpr) site.iie(), site.subSig(), site.container() ) ); } else { VirtualCalls.v().resolve( type, receiver.getType(), site.subSig(), site.container(), targetsQueue ); } while(targets.hasNext()) { SootMethod target = (SootMethod) targets.next(); cm.addVirtualEdge( MethodContext.v( site.container(), srcContext ), site.stmt(), target, site.kind(), typeContext ); } } } public boolean wantStringConstants( Local stringConst ) { return stringConstToSites.get(stringConst) != null; } public void addStringConstant( Local l, Context srcContext, String constant ) { for( Iterator siteIt = ((Collection) stringConstToSites.get( l )).iterator(); siteIt.hasNext(); ) { final VirtualCallSite site = (VirtualCallSite) siteIt.next(); if( constant == null ) { if( options.verbose() ) { G.v().out.println( "Warning: Method "+site.container()+ " is reachable, and calls Class.forName on a"+ " non-constant String; graph will be incomplete!"+ " Use safe-forname option for a conservative result." ); } } else { if( constant.length() > 0 && constant.charAt(0) == '[' ) { if( constant.length() > 1 && constant.charAt(1) == 'L' && constant.charAt(constant.length()-1) == ';' ) { constant = constant.substring(2,constant.length()-1); } else continue; } if( !Scene.v().containsClass( constant ) ) { if( options.verbose() ) { G.v().out.println( "Warning: Class "+constant+" is"+ " a dynamic class, and you did not specify"+ " it as such; graph will be incomplete!" ); } } else { SootClass sootcls = Scene.v().getSootClass( constant ); if( !sootcls.isApplicationClass() ) { sootcls.setLibraryClass(); } for (SootMethod clinit : EntryPoints.v().clinitsOf(sootcls)) { cm.addStaticEdge( MethodContext.v( site.container(), srcContext ), site.stmt(), clinit, Kind.CLINIT ); } } } } } /* End of public methods. */ private void addVirtualCallSite( Stmt s, SootMethod m, Local receiver, InstanceInvokeExpr iie, NumberedString subSig, Kind kind ) { List<VirtualCallSite> sites = (List<VirtualCallSite>) receiverToSites.get(receiver); if (sites == null) { receiverToSites.put(receiver, sites = new ArrayList<VirtualCallSite>()); List<Local> receivers = (List<Local>) methodToReceivers.get(m); if( receivers == null ) methodToReceivers.put(m, receivers = new ArrayList<Local>()); receivers.add(receiver); } sites.add(new VirtualCallSite(s, m, iie, subSig, kind)); } private void processNewMethod( SootMethod m ) { if( m.isNative() || m.isPhantom() ) { return; } Body b = m.retrieveActiveBody(); getImplicitTargets( m ); findReceivers(m, b); } private void findReceivers(SootMethod m, Body b) { for( Iterator sIt = b.getUnits().iterator(); sIt.hasNext(); ) { final Stmt s = (Stmt) sIt.next(); if (s.containsInvokeExpr()) { InvokeExpr ie = s.getInvokeExpr(); if (ie instanceof InstanceInvokeExpr) { InstanceInvokeExpr iie = (InstanceInvokeExpr) ie; Local receiver = (Local) iie.getBase(); NumberedString subSig = iie.getMethodRef().getSubSignature(); addVirtualCallSite( s, m, receiver, iie, subSig, Edge.ieToKind(iie) ); if( subSig == sigStart ) { addVirtualCallSite( s, m, receiver, iie, sigRun, Kind.THREAD ); } } else { SootMethod tgt = ((StaticInvokeExpr) ie).getMethod(); addEdge(m, s, tgt); if( tgt.getSignature().equals( "<java.security.AccessController: java.lang.Object doPrivileged(java.security.PrivilegedAction)>" ) || tgt.getSignature().equals( "<java.security.AccessController: java.lang.Object doPrivileged(java.security.PrivilegedExceptionAction)>" ) || tgt.getSignature().equals( "<java.security.AccessController: java.lang.Object doPrivileged(java.security.PrivilegedAction,java.security.AccessControlContext)>" ) || tgt.getSignature().equals( "<java.security.AccessController: java.lang.Object doPrivileged(java.security.PrivilegedExceptionAction,java.security.AccessControlContext)>" ) ) { Local receiver = (Local) ie.getArg(0); addVirtualCallSite( s, m, receiver, null, sigObjRun, Kind.PRIVILEGED ); } } } } } ReflectionModel reflectionModel; private void getImplicitTargets( SootMethod source ) { final SootClass scl = source.getDeclaringClass(); if( source.isNative() || source.isPhantom() ) return; if( source.getSubSignature().indexOf( "<init>" ) >= 0 ) { handleInit(source, scl); } Body b = source.retrieveActiveBody(); for( Iterator sIt = b.getUnits().iterator(); sIt.hasNext(); ) { final Stmt s = (Stmt) sIt.next(); if( s.containsInvokeExpr() ) { InvokeExpr ie = s.getInvokeExpr(); if( ie.getMethod().getSignature().equals( "<java.lang.reflect.Method: java.lang.Object invoke(java.lang.Object,java.lang.Object[])>" ) ) { reflectionModel.methodInvoke(source,s); } if( ie.getMethod().getSignature().equals( "<java.lang.Class: java.lang.Object newInstance()>" ) ) { reflectionModel.classNewInstance(source,s); } if( ie.getMethod().getSignature().equals( "<java.lang.reflect.Constructor: java.lang.Object newInstance(java.lang.Object[])>" ) ) { reflectionModel.contructorNewInstance(source, s); } if( ie.getMethodRef().getSubSignature() == sigForName ) { reflectionModel.classForName(source,s); } if( ie instanceof StaticInvokeExpr ) { SootClass cl = ie.getMethodRef().declaringClass(); for (SootMethod clinit : EntryPoints.v().clinitsOf(cl)) { addEdge( source, s, clinit, Kind.CLINIT ); } } } if( s.containsFieldRef() ) { FieldRef fr = s.getFieldRef(); if( fr instanceof StaticFieldRef ) { SootClass cl = fr.getFieldRef().declaringClass(); for (SootMethod clinit : EntryPoints.v().clinitsOf(cl)) { addEdge( source, s, clinit, Kind.CLINIT ); } } } if( s instanceof AssignStmt ) { Value rhs = ((AssignStmt)s).getRightOp(); if( rhs instanceof NewExpr ) { NewExpr r = (NewExpr) rhs; SootClass cl = r.getBaseType().getSootClass(); for (SootMethod clinit : EntryPoints.v().clinitsOf(cl)) { addEdge( source, s, clinit, Kind.CLINIT ); } } else if( rhs instanceof NewArrayExpr || rhs instanceof NewMultiArrayExpr ) { Type t = rhs.getType(); if( t instanceof ArrayType ) t = ((ArrayType)t).baseType; if( t instanceof RefType ) { SootClass cl = ((RefType) t).getSootClass(); for (SootMethod clinit : EntryPoints.v().clinitsOf(cl)) { addEdge( source, s, clinit, Kind.CLINIT ); } } } } } } private void processNewMethodContext( MethodOrMethodContext momc ) { SootMethod m = momc.method(); Object ctxt = momc.context(); Iterator it = cicg.edgesOutOf(m); while( it.hasNext() ) { Edge e = (Edge) it.next(); cm.addStaticEdge( momc, e.srcUnit(), e.tgt(), e.kind() ); } } private void handleInit(SootMethod source, final SootClass scl) { addEdge( source, null, scl, sigFinalize, Kind.FINALIZE ); FastHierarchy fh = Scene.v().getOrMakeFastHierarchy(); } private void constantForName( String cls, SootMethod src, Stmt srcUnit ) { if( cls.length() > 0 && cls.charAt(0) == '[' ) { if( cls.length() > 1 && cls.charAt(1) == 'L' && cls.charAt(cls.length()-1) == ';' ) { cls = cls.substring(2,cls.length()-1); constantForName( cls, src, srcUnit ); } } else { if( !Scene.v().containsClass( cls ) ) { if( options.verbose() ) { G.v().out.println( "Warning: Class "+cls+" is"+ " a dynamic class, and you did not specify"+ " it as such; graph will be incomplete!" ); } } else { SootClass sootcls = Scene.v().getSootClass( cls ); if( !sootcls.isApplicationClass() ) { sootcls.setLibraryClass(); } for (SootMethod clinit : EntryPoints.v().clinitsOf(sootcls)) { addEdge( src, srcUnit, clinit, Kind.CLINIT ); } } } } private void addEdge( SootMethod src, Stmt stmt, SootMethod tgt, Kind kind ) { cicg.addEdge( new Edge( src, stmt, tgt, kind ) ); } private void addEdge( SootMethod src, Stmt stmt, SootClass cls, NumberedString methodSubSig, Kind kind ) { if( cls.declaresMethod( methodSubSig ) ) { addEdge( src, stmt, cls.getMethod( methodSubSig ), kind ); } } private void addEdge( SootMethod src, Stmt stmt, SootMethod tgt ) { InvokeExpr ie = stmt.getInvokeExpr(); addEdge( src, stmt, tgt, Edge.ieToKind(ie) ); } protected final NumberedString sigFinalize = Scene.v().getSubSigNumberer(). findOrAdd( "void finalize()" ); protected final NumberedString sigInit = Scene.v().getSubSigNumberer(). findOrAdd( "void <init>()" ); protected final NumberedString sigStart = Scene.v().getSubSigNumberer(). findOrAdd( "void start()" ); protected final NumberedString sigRun = Scene.v().getSubSigNumberer(). findOrAdd( "void run()" ); protected final NumberedString sigObjRun = Scene.v().getSubSigNumberer(). findOrAdd( "java.lang.Object run()" ); protected final NumberedString sigForName = Scene.v().getSubSigNumberer(). findOrAdd( "java.lang.Class forName(java.lang.String)" ); protected final RefType clRunnable = RefType.v("java.lang.Runnable"); }
better throw exception than just printing a warning
src/soot/jimple/toolkits/callgraph/OnFlyCallGraphBuilder.java
better throw exception than just printing a warning
<ide><path>rc/soot/jimple/toolkits/callgraph/OnFlyCallGraphBuilder.java <ide> receiverNames.add(target); <ide> } else if(kind.equals("Method.invoke")) { <ide> if(!Scene.v().containsMethod(target)) { <del> G.v().out.println("Warning: Unknown method for signature: "+target); <add> throw new RuntimeException("Unknown method for signature: "+target); <ide> } <ide> <ide> Set<String> receiverNames;
Java
apache-2.0
error: pathspec 'src/main/java/kfs/kfsGenDbi/generator.java' did not match any file(s) known to git
02e50128a6cc8a5b770e790fcbe1aff697c6aa0f
1
k0fis/kfsWfl
package kfs.kfsGenDbi; import java.math.BigDecimal; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import kfs.kfsDbi.kfsNames; import kfs.kfsDbi.kfsSb; /** * * @author pavedrim */ public class generator { public static String getJavaName(String name) { return new kfsNames().add(name, "_").getJavoizeName(); } enum dbt { num, str, date, nil, numAi; public static dbt getDbt(String typeName) { if ("VARCHAR2".equals(typeName) || "varchar".equals(typeName)) { return str; } else if ("int identity".equals(typeName)) { return numAi; } else if ("NUMBER".equals(typeName) || "tinyint".equals(typeName) || "unsigned bigint".equals(typeName) || "unsigned int".equals(typeName) || "smallint".equals(typeName) || "int".equals(typeName) ) { return num; } else if ("DATE".equals(typeName) || "TIMESTAMP".equals(typeName) || "datetime".equals(typeName)) { return date; } System.err.println("getDbt: "+typeName); return nil; } public static dbt getDbt2(String typeName) { if (String.class.getName().equals(typeName)) { return str; } else if (BigDecimal.class.getName().equals(typeName) || Long.class.getName().equals(typeName)) { return num; } else if (java.sql.Timestamp.class.getName().equals(typeName) || "oracle.sql.TIMESTAMP".equals(typeName)) { return date; } else if (Integer.class.getName().equals(typeName)) { return num; } System.err.println("getDbt2: " +typeName); //throw new RuntimeException(typeName); return nil; } } public static String getKfsType(String typeName) { switch (dbt.getDbt(typeName)) { case numAi: return "kfsIntAutoInc"; case num: return "kfsLong"; case str: return "kfsString"; case date: return "kfsDate"; } return "kfs" + typeName; } private static PreparedStatement pps = null; public static String getColumnLabel(Connection con, String owner, String table, String columnName, String retLab) throws SQLException { try { if (pps == null) { pps = con.prepareStatement("select comments from all_col_comments where owner = ? and table_name = ? and column_name = ?"); } pps.setString(1, owner); pps.setString(2, table); pps.setString(3, columnName); ResultSet rs = pps.executeQuery(); String r = ""; if (rs.next()) { r = rs.getString(1); } rs.close(); if (r == null) { return ""; } if (r.length() > 0) { return r; } return retLab; } catch (SQLException ex) { return columnName; } } public static String getClassString(Connection con, String owner, String table, ResultSetMetaData rsm, String pkg, String objName, String tblName) throws SQLException { kfsSb s = new kfsSb(""); s// .anl("package", " ", pkg, ";")// .nl()// .anl("import java.util.Date;")// .anl("import kfs.kfsDbi.*;")// .nl()// .anl("public class ", objName, " extends kfsDbObject {")// .nl(); for (int i = 0; i < rsm.getColumnCount(); i++) { s.anl(" private final ", getKfsType(rsm.getColumnTypeName(i + 1)), " ", getJavaName(rsm.getColumnName(i + 1)), "; //" + rsm.getColumnClassName(i+1)); } s// .anl(" public ", objName, "(kfsDbServerType dbType) {")// .anl(" super(dbType, \"", tblName, "\");")// .anl(" int pos = 0;"); for (int i = 0; i < rsm.getColumnCount(); i++) { s// .a(" ", getJavaName(rsm.getColumnName(i + 1)), " = new ")// .a(getKfsType(rsm.getColumnTypeName(i + 1)), "(");// String colName = rsm.getColumnName(i + 1); String label = getColumnLabel(con, owner, table, colName, rsm.getColumnLabel(i + 1)); switch (dbt.getDbt2(rsm.getColumnClassName(i + 1))) { case date: s.a("\"", colName, "\", \"", label, "\", pos++"); break; case str: s.a("\"", colName, "\", \"", label, "\", ", rsm.getPrecision(i + 1), ", pos++"); break; case num: s.a("\"", colName, "\", \"", label, "\", ", rsm.getPrecision(i + 1), ", pos++, ", rsm.isNullable(i + 1) == ResultSetMetaData.columnNullable); break; } s// .anl(");"); } s// .anl(" super.setColumns(new kfsDbiColumn[]{"); for (int i = 0; i < rsm.getColumnCount(); i++) { s.anl(" ", getJavaName(rsm.getColumnName(i + 1)), ","); } s// .anl(" });")// .anl(" super.setIdsColumns(new kfsDbiColumn[0]);")// .anl(" }"); s// .anl(" public kfsRowData copy(", objName, " src, kfsRowData f) {")// .anl(" kfsRowData r = new kfsRowData(this);"); for (int i = 0; i < rsm.getColumnCount(); i++) { String name = getJavaName(rsm.getColumnName(i + 1)); s.anl(" ", name, ".setData(src.", name, ".getData(f), r);"); } s// .anl(" return r;")// .anl(" }"); s// .anl(" public kfsRowData create() {")// .anl(" kfsRowData r = new kfsRowData(this);")// .anl(" return r;")// .anl(" }"); s// .nl()// .anl("}"); return s.toString(); } static Connection getConCorprd(String schema) throws Exception { Connection con; Class.forName("oracle.jdbc.OracleDriver"); con = DriverManager.getConnection("jdbc:oracle:thin:@(DESCRIPTION = " + "(ADDRESS = (PROTOCOL = TCP) (HOST = l5race23)(PORT = 1545)) " + "(ADDRESS = (PROTOCOL = TCP) (HOST = l5race22)(PORT = 1545)) " + "(ADDRESS = (PROTOCOL = TCP) (HOST = l5race21)(PORT = 1545)) " + "(CONNECT_DATA = (SERVER = DEDICATED)" + " (SERVICE_NAME = CORPRD_TAF.CESKYMOBIL.CZ)))", schema, schema + "123"); con.setAutoCommit(false); return con; } /* public static void main(String[] aa) throws Exception { Connection con = kfs.kfsUtils.kfsDbTools.getConnCorTp(); / * Statement ps = con.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); ResultSet rs = ps.executeQuery("select * from stat_table_name"); ResultSetMetaData rsm = rs.getMetaData(); for (int i = 0; i < rsm.getColumnCount(); i++) { System.out.print(rsm.getColumnName(i+1)+", "); } System.out.println(); while (rs.next()) { for (int i = 0; i < rsm.getColumnCount(); i++) { System.out.print(rs.getObject(i+1)+", "); } System.out.println(); } * / String tn = "vfcz_handset_provisioning"; ResultSet rs = con.createStatement().executeQuery("SELECT * FROM " + tn); System.out.print(getClassString(con, "TOUCHPOINT_OWN", tn, rs.getMetaData(), "kfs.kfsAllot.base.db", "dbHandsetDoc", tn)); rs.close(); con.close(); } */ }
src/main/java/kfs/kfsGenDbi/generator.java
Add Class Generator
src/main/java/kfs/kfsGenDbi/generator.java
Add Class Generator
<ide><path>rc/main/java/kfs/kfsGenDbi/generator.java <add>package kfs.kfsGenDbi; <add> <add>import java.math.BigDecimal; <add>import java.sql.Connection; <add>import java.sql.DriverManager; <add>import java.sql.PreparedStatement; <add>import java.sql.ResultSet; <add>import java.sql.ResultSetMetaData; <add>import java.sql.SQLException; <add>import kfs.kfsDbi.kfsNames; <add>import kfs.kfsDbi.kfsSb; <add> <add>/** <add> * <add> * @author pavedrim <add> */ <add>public class generator { <add> public static String getJavaName(String name) { <add> return new kfsNames().add(name, "_").getJavoizeName(); <add> } <add> <add> enum dbt { <add> <add> num, str, date, nil, numAi; <add> <add> public static dbt getDbt(String typeName) { <add> if ("VARCHAR2".equals(typeName) || "varchar".equals(typeName)) { <add> return str; <add> } else if ("int identity".equals(typeName)) { <add> return numAi; <add> } else if ("NUMBER".equals(typeName) || "tinyint".equals(typeName) || "unsigned bigint".equals(typeName) || "unsigned int".equals(typeName) || "smallint".equals(typeName) || "int".equals(typeName) ) { <add> return num; <add> } else if ("DATE".equals(typeName) || "TIMESTAMP".equals(typeName) || "datetime".equals(typeName)) { <add> return date; <add> } <add> System.err.println("getDbt: "+typeName); <add> return nil; <add> } <add> <add> public static dbt getDbt2(String typeName) { <add> if (String.class.getName().equals(typeName)) { <add> return str; <add> } else if (BigDecimal.class.getName().equals(typeName) || Long.class.getName().equals(typeName)) { <add> return num; <add> } else if (java.sql.Timestamp.class.getName().equals(typeName) || "oracle.sql.TIMESTAMP".equals(typeName)) { <add> return date; <add> } else if (Integer.class.getName().equals(typeName)) { <add> return num; <add> } <add> System.err.println("getDbt2: " +typeName); <add> //throw new RuntimeException(typeName); <add> return nil; <add> } <add> } <add> <add> public static String getKfsType(String typeName) { <add> switch (dbt.getDbt(typeName)) { <add> case numAi: <add> return "kfsIntAutoInc"; <add> case num: <add> return "kfsLong"; <add> case str: <add> return "kfsString"; <add> case date: <add> return "kfsDate"; <add> } <add> return "kfs" + typeName; <add> } <add> private static PreparedStatement pps = null; <add> <add> public static String getColumnLabel(Connection con, String owner, String table, String columnName, String retLab) throws SQLException { <add> try { <add> if (pps == null) { <add> pps = con.prepareStatement("select comments from all_col_comments where owner = ? and table_name = ? and column_name = ?"); <add> } <add> pps.setString(1, owner); <add> pps.setString(2, table); <add> pps.setString(3, columnName); <add> ResultSet rs = pps.executeQuery(); <add> String r = ""; <add> if (rs.next()) { <add> r = rs.getString(1); <add> } <add> rs.close(); <add> if (r == null) { <add> return ""; <add> } <add> if (r.length() > 0) { <add> return r; <add> } <add> return retLab; <add> } catch (SQLException ex) { <add> return columnName; <add> } <add> } <add> <add> public static String getClassString(Connection con, String owner, String table, ResultSetMetaData rsm, String pkg, String objName, String tblName) throws SQLException { <add> kfsSb s = new kfsSb(""); <add> s// <add> .anl("package", " ", pkg, ";")// <add> .nl()// <add> .anl("import java.util.Date;")// <add> .anl("import kfs.kfsDbi.*;")// <add> .nl()// <add> .anl("public class ", objName, " extends kfsDbObject {")// <add> .nl(); <add> for (int i = 0; i < rsm.getColumnCount(); i++) { <add> s.anl(" private final ", getKfsType(rsm.getColumnTypeName(i + 1)), " ", getJavaName(rsm.getColumnName(i + 1)), "; //" + rsm.getColumnClassName(i+1)); <add> } <add> s// <add> .anl(" public ", objName, "(kfsDbServerType dbType) {")// <add> .anl(" super(dbType, \"", tblName, "\");")// <add> .anl(" int pos = 0;"); <add> for (int i = 0; i < rsm.getColumnCount(); i++) { <add> s// <add> .a(" ", getJavaName(rsm.getColumnName(i + 1)), " = new ")// <add> .a(getKfsType(rsm.getColumnTypeName(i + 1)), "(");// <add> String colName = rsm.getColumnName(i + 1); <add> String label = getColumnLabel(con, owner, table, colName, rsm.getColumnLabel(i + 1)); <add> switch (dbt.getDbt2(rsm.getColumnClassName(i + 1))) { <add> case date: <add> s.a("\"", colName, "\", \"", label, "\", pos++"); <add> break; <add> case str: <add> s.a("\"", colName, "\", \"", label, "\", ", rsm.getPrecision(i + 1), ", pos++"); <add> break; <add> case num: <add> s.a("\"", colName, "\", \"", label, "\", ", rsm.getPrecision(i + 1), ", pos++, ", rsm.isNullable(i + 1) == ResultSetMetaData.columnNullable); <add> break; <add> } <add> s// <add> .anl(");"); <add> } <add> s// <add> .anl(" super.setColumns(new kfsDbiColumn[]{"); <add> for (int i = 0; i < rsm.getColumnCount(); i++) { <add> s.anl(" ", getJavaName(rsm.getColumnName(i + 1)), ","); <add> } <add> s// <add> .anl(" });")// <add> .anl(" super.setIdsColumns(new kfsDbiColumn[0]);")// <add> .anl(" }"); <add> <add> s// <add> .anl(" public kfsRowData copy(", objName, " src, kfsRowData f) {")// <add> .anl(" kfsRowData r = new kfsRowData(this);"); <add> for (int i = 0; i < rsm.getColumnCount(); i++) { <add> String name = getJavaName(rsm.getColumnName(i + 1)); <add> s.anl(" ", name, ".setData(src.", name, ".getData(f), r);"); <add> } <add> s// <add> .anl(" return r;")// <add> .anl(" }"); <add> <add> s// <add> .anl(" public kfsRowData create() {")// <add> .anl(" kfsRowData r = new kfsRowData(this);")// <add> .anl(" return r;")// <add> .anl(" }"); <add> <add> s// <add> .nl()// <add> .anl("}"); <add> return s.toString(); <add> } <add> <add> static Connection getConCorprd(String schema) throws Exception { <add> Connection con; <add> Class.forName("oracle.jdbc.OracleDriver"); <add> con = DriverManager.getConnection("jdbc:oracle:thin:@(DESCRIPTION = " <add> + "(ADDRESS = (PROTOCOL = TCP) (HOST = l5race23)(PORT = 1545)) " <add> + "(ADDRESS = (PROTOCOL = TCP) (HOST = l5race22)(PORT = 1545)) " <add> + "(ADDRESS = (PROTOCOL = TCP) (HOST = l5race21)(PORT = 1545)) " <add> + "(CONNECT_DATA = (SERVER = DEDICATED)" <add> + " (SERVICE_NAME = CORPRD_TAF.CESKYMOBIL.CZ)))", <add> schema, schema + "123"); <add> con.setAutoCommit(false); <add> return con; <add> } <add>/* <add> public static void main(String[] aa) throws Exception { <add> Connection con = kfs.kfsUtils.kfsDbTools.getConnCorTp(); <add> / * <add> Statement ps = con.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); <add> ResultSet rs = ps.executeQuery("select * from stat_table_name"); <add> ResultSetMetaData rsm = rs.getMetaData(); <add> for (int i = 0; i < rsm.getColumnCount(); i++) { <add> System.out.print(rsm.getColumnName(i+1)+", "); <add> } <add> System.out.println(); <add> while (rs.next()) { <add> for (int i = 0; i < rsm.getColumnCount(); i++) { <add> System.out.print(rs.getObject(i+1)+", "); <add> } <add> System.out.println(); <add> } <add> * / <add> String tn = "vfcz_handset_provisioning"; <add> ResultSet rs = con.createStatement().executeQuery("SELECT * FROM " + tn); <add> System.out.print(getClassString(con, "TOUCHPOINT_OWN", tn, rs.getMetaData(), <add> "kfs.kfsAllot.base.db", "dbHandsetDoc", <add> tn)); <add> rs.close(); <add> con.close(); <add> } <add> */ <add>}
JavaScript
mit
a3ef96f0007ddf506469809390d4b0cbad7ec7c4
0
cvan/fastHAR-api,cvan/fastHAR-api
var spawn = require('child_process').spawn; var db = require('./db'); var server = require('./server'); function phantomHAR(url, cb) { var output = ''; var error = ''; var args = [ __dirname + '/node_modules/phantomhar/phantomhar.js', url ]; var job = spawn('phantomjs', args); job.stdout.on('data', function(data) { output += data; }); job.stderr.on('data', function(data) { error += data; }); job.on('exit', function(code) { if (code !== 0) { if (error) { error = 'stderr: ' + error; } else { error = 'phantomjs ' + args[0] + ' exited: ' + code; } } cb(error, output); }); } // Sample usage: // % curl 'http://localhost:5000/har/fetch?url=http://thephantomoftheopera.com' // % curl -X POST 'http://localhost:5000/har/fetch' -d 'ref=badc0ffee&url=http://thephantomoftheopera.com' var fetchViewOptions = { url: '/har/fetch', swagger: { nickname: 'fetch', notes: 'Fetch site', summary: 'Fetch site' }, validation: { url: { description: 'Site URL', isRequired: true, isUrl: true }, name: { description: 'Name', isRequired: false }, ref: { description: 'Ref (unique identifier)', isRequired: false } } }; function fetchView(req, res) { var DATA = req.params; var url = encodeURIComponent(DATA.url); var ref = DATA.ref || new Date().toISOString(); phantomHAR(DATA.url, function(err, data) { if (err) { return res.error(400, {error: err}); } // TODO: Allow only one ref. data = JSON.parse(data); data.log._ref = ref; db.push(url, {har: data}, function(err) { if (err) { return res.error(400, {error: err}); } }); console.log(JSON.stringify(data, null, 4)); }); res.json({success: true}); } // Sample usage: // % curl 'http://localhost:5000/har/history?url=http://thephantomoftheopera.com' // % curl 'http://localhost:5000/har/history?ref=badc0ffee&url=http://thephantomoftheopera.com' var historyViewOptions = { url: '/har/history', swagger: { nickname: 'history', notes: 'History of network traffic for a site', summary: 'Site history' }, validation: { url: { description: 'Site URL', isRequired: true, isUrl: true }, ref: { description: 'Ref (unique identifier)', isRequired: false } } }; function historyView(req, res) { var DATA = req.params; var url = encodeURIComponent(DATA.url); var ref = DATA.ref; db.get(url, function(err, data) { if (err) { console.error(err); return res.json(ref ? {} : []); } var singleOutput = null; var output = []; (data || []).some(function(entry, idx) { if (ref && ref === entry.har.log._ref) { // Return HAR for a single ref. singleOutput = entry.har; } output.push(entry.har); }); if (ref) { output = singleOutput || {}; } res.json(output); }); } // Sample usage: // % curl 'http://localhost:5000/stats/history?url=http://thephantomoftheopera.com' // % curl 'http://localhost:5000/stats/history?ref=badc0ffee&url=http://thephantomoftheopera.com' var statsViewOptions = { url: '/stats/history', swagger: { nickname: 'stats', notes: 'Statistics data of historical network traffic for a site', summary: 'Statistics data' }, validation: { url: { description: 'Site URL', isRequired: true, isUrl: true }, ref: { description: 'Ref (unique identifier)', isRequired: false } } }; var resourceTypes = [ 'audio', 'css', 'cssimage', 'doc', 'flash', 'font', 'inlinecssimage', 'inlineimage', 'js', 'json', 'other', 'total', 'video' ]; function getStats(har) { var data = {sizes: {}, times: {}, totals: {}}; resourceTypes.forEach(function(type) { data.sizes[type] = data.times[type] = data.totals[type] = 0; }); var size; var time; var type; har.log.entries.forEach(function(entry) { if (!entry.response || !entry.response.content) { return; } type = entry.response.content._type; if (!type || resourceTypes.indexOf(type) === -1) { type = 'other'; } size = entry.response.bodySize; time = entry.timings.wait + entry.timings.receive; data.sizes[type] += size; data.times[type] += time; data.totals[type]++; data.sizes['total'] += size; data.times['total'] += time; data.totals['total']++; }); return data; } function statsView(req, res, cb) { var DATA = req.params; var url = encodeURIComponent(DATA.url); var ref = DATA.ref; db.get(url, function(err, data) { if (err) { console.error(err); data = ref ? {} : []; if (res) { return res.json(data); } else { return cb(err); } } var singleOutput = null; var output = []; var stats; (data || []).forEach(function(entry) { stats = getStats(entry.har); stats.ref = entry.har.log._ref; if (ref && ref === entry.har.log._ref) { // Return stats for a single ref. singleOutput = stats; } output.push(stats); }); if (ref) { output = singleOutput || {}; } if (res) { res.json(output); } else { cb(null, output); } }); } // Sample usage: // % curl 'http://localhost:5000/charts/sizes?url=http://thephantomoftheopera.com' // % curl 'http://localhost:5000/charts/times?url=http://thephantomoftheopera.com' // % curl 'http://localhost:5000/charts/totals?url=http://thephantomoftheopera.com' // % curl 'http://localhost:5000/charts/totals?resource=css&ref=badc0ffee&url=http://thephantomoftheopera.com' var chartsViewOptions = { url: '/charts/:stat', swagger: { nickname: 'charts', notes: 'Charts data of historical network traffic for a site ' + '(normalised for JS frontend)', summary: 'Charts data' }, validation: { url: { description: 'Site URL', isRequired: true, isUrl: true }, ref: { description: 'Ref (unique identifier)', isRequired: false }, resource: { description: 'Resource type to filter by', isRequired: false, isIn: resourceTypes }, stat: { description: 'Statistic type', isRequired: true, isIn: ['sizes', 'times', 'totals'], scope: 'path' }, exclude: { description: 'Resource type to exclude', isRequired: false, isIn: resourceTypes } } }; function chartsView(req, res) { var DATA = req.params; var stat = DATA.stat; var resourceType = DATA.resource; var exclude = DATA.exclude; var types = resourceTypes.slice(0); if (resourceType) { types = [resourceType]; } statsView(req, null, function(err, data) { if (err) { console.error(err); return res.json({}); } var output = { // One label per ref. labels: [], // One dataset entry per resource type. datasets: [] }; // Tally each resource type (so we know which keys to omit later). var resourceTotals = {}; types.forEach(function(type, idx) { // One data entry per ref. output.datasets[idx] = [type]; // Set counter for each resource type. resourceTotals[type] = 0; }); var whichDataset; data.forEach(function(entry) { output.labels.push(entry.ref); Object.keys(entry.totals).forEach(function(k) { resourceTotals[k] += entry.totals[k]; }); Object.keys(entry[stat]).forEach(function(k) { if (resourceType && k !== resourceType) { return; } // Look up the dataset for this resource type. whichDataset = output.datasets[types.indexOf(k)]; // Push the value onto the array for aforementioned dataset. whichDataset.push(entry[stat][k]); }); }); // Omit a particular resource type if no requests of that type were // ever made throughout the entire history recorded for this site. output.datasets = output.datasets.filter(function(dataset) { if (exclude && dataset[0] === exclude) { return false; } return resourceTotals[dataset[0]]; }); res.json(output); }); } server.get(fetchViewOptions, fetchView); server.post(fetchViewOptions, fetchView); server.get(historyViewOptions, historyView); server.get(statsViewOptions, statsView); server.get(chartsViewOptions, chartsView); server.listen(process.env.PORT || 5000, function() { console.log('%s listening at %s', server.name, server.url); });
app.js
var spawn = require('child_process').spawn; var db = require('./db'); var server = require('./server'); function phantomHAR(url, cb) { var output = ''; var error = ''; var args = [ __dirname + '/node_modules/phantomhar/phantomhar.js', url ]; var job = spawn('phantomjs', args); job.stdout.on('data', function(data) { output += data; }); job.stderr.on('data', function(data) { error += data; }); job.on('exit', function(code) { if (code !== 0) { if (error) { error = 'stderr: ' + error; } else { error = 'phantomjs ' + args[0] + ' exited: ' + code; } } cb(error, output); }); } // Sample usage: // % curl 'http://localhost:5000/har/fetch?url=http://thephantomoftheopera.com' // % curl -X POST 'http://localhost:5000/har/fetch' -d 'ref=badc0ffee&url=http://thephantomoftheopera.com' var fetchViewOptions = { url: '/har/fetch', swagger: { nickname: 'fetch', notes: 'Fetch site', summary: 'Fetch site' }, validation: { url: { description: 'Site URL', isRequired: true, isUrl: true }, name: { description: 'Name', isRequired: false }, ref: { description: 'Ref (unique identifier)', isRequired: false } } }; function fetchView(req, res) { var DATA = req.params; var url = encodeURIComponent(DATA.url); var ref = DATA.ref || new Date().toISOString(); phantomHAR(DATA.url, function(err, data) { if (err) { return res.error(400, {error: err}); } // TODO: Allow only one ref. data = JSON.parse(data); data.log._ref = ref; db.push(url, {har: data}, function(err) { if (err) { return res.error(400, {error: err}); } }); console.log(data); }); res.json({success: true}); } // Sample usage: // % curl 'http://localhost:5000/har/history?url=http://thephantomoftheopera.com' // % curl 'http://localhost:5000/har/history?ref=badc0ffee&url=http://thephantomoftheopera.com' var historyViewOptions = { url: '/har/history', swagger: { nickname: 'history', notes: 'History of network traffic for a site', summary: 'Site history' }, validation: { url: { description: 'Site URL', isRequired: true, isUrl: true }, ref: { description: 'Ref (unique identifier)', isRequired: false } } }; function historyView(req, res) { var DATA = req.params; var url = encodeURIComponent(DATA.url); var ref = DATA.ref; db.get(url, function(err, data) { if (err) { console.error(err); return res.json(ref ? {} : []); } var singleOutput = null; var output = []; (data || []).some(function(entry, idx) { if (ref && ref === entry.har.log._ref) { // Return HAR for a single ref. singleOutput = entry.har; } output.push(entry.har); }); if (ref) { output = singleOutput || {}; } res.json(output); }); } // Sample usage: // % curl 'http://localhost:5000/stats/history?url=http://thephantomoftheopera.com' // % curl 'http://localhost:5000/stats/history?ref=badc0ffee&url=http://thephantomoftheopera.com' var statsViewOptions = { url: '/stats/history', swagger: { nickname: 'stats', notes: 'Statistics data of historical network traffic for a site', summary: 'Statistics data' }, validation: { url: { description: 'Site URL', isRequired: true, isUrl: true }, ref: { description: 'Ref (unique identifier)', isRequired: false } } }; var resourceTypes = [ 'audio', 'css', 'cssimage', 'doc', 'flash', 'font', 'inlinecssimage', 'inlineimage', 'js', 'json', 'other', 'total', 'video' ]; function getStats(har) { var data = {sizes: {}, times: {}, totals: {}}; resourceTypes.forEach(function(type) { data.sizes[type] = data.times[type] = data.totals[type] = 0; }); var size; var time; var type; har.log.entries.forEach(function(entry) { if (!entry.response || !entry.response.content) { return; } type = entry.response.content._type; if (!type || resourceTypes.indexOf(type) === -1) { type = 'other'; } size = entry.response.bodySize; time = entry.timings.wait + entry.timings.receive; data.sizes[type] += size; data.times[type] += time; data.totals[type]++; data.sizes['total'] += size; data.times['total'] += time; data.totals['total']++; }); return data; } function statsView(req, res, cb) { var DATA = req.params; var url = encodeURIComponent(DATA.url); var ref = DATA.ref; db.get(url, function(err, data) { if (err) { console.error(err); data = ref ? {} : []; if (res) { return res.json(data); } else { return cb(err); } } var singleOutput = null; var output = []; var stats; (data || []).forEach(function(entry) { stats = getStats(entry.har); stats.ref = entry.har.log._ref; if (ref && ref === entry.har.log._ref) { // Return stats for a single ref. singleOutput = stats; } output.push(stats); }); if (ref) { output = singleOutput || {}; } if (res) { res.json(output); } else { cb(null, output); } }); } // Sample usage: // % curl 'http://localhost:5000/charts/sizes?url=http://thephantomoftheopera.com' // % curl 'http://localhost:5000/charts/times?url=http://thephantomoftheopera.com' // % curl 'http://localhost:5000/charts/totals?url=http://thephantomoftheopera.com' // % curl 'http://localhost:5000/charts/totals?resource=css&ref=badc0ffee&url=http://thephantomoftheopera.com' var chartsViewOptions = { url: '/charts/:stat', swagger: { nickname: 'charts', notes: 'Charts data of historical network traffic for a site ' + '(normalised for JS frontend)', summary: 'Charts data' }, validation: { url: { description: 'Site URL', isRequired: true, isUrl: true }, ref: { description: 'Ref (unique identifier)', isRequired: false }, resource: { description: 'Resource type to filter by', isRequired: false, isIn: resourceTypes }, stat: { description: 'Statistic type', isRequired: true, isIn: ['sizes', 'times', 'totals'], scope: 'path' }, exclude: { description: 'Resource type to exclude', isRequired: false, isIn: resourceTypes } } }; function chartsView(req, res) { var DATA = req.params; var stat = DATA.stat; var resourceType = DATA.resource; var exclude = DATA.exclude; var types = resourceTypes.slice(0); if (resourceType) { types = [resourceType]; } statsView(req, null, function(err, data) { if (err) { console.error(err); return res.json({}); } var output = { // One label per ref. labels: [], // One dataset entry per resource type. datasets: [] }; // Tally each resource type (so we know which keys to omit later). var resourceTotals = {}; types.forEach(function(type, idx) { // One data entry per ref. output.datasets[idx] = [type]; // Set counter for each resource type. resourceTotals[type] = 0; }); var whichDataset; data.forEach(function(entry) { output.labels.push(entry.ref); Object.keys(entry.totals).forEach(function(k) { resourceTotals[k] += entry.totals[k]; }); Object.keys(entry[stat]).forEach(function(k) { if (resourceType && k !== resourceType) { return; } // Look up the dataset for this resource type. whichDataset = output.datasets[types.indexOf(k)]; // Push the value onto the array for aforementioned dataset. whichDataset.push(entry[stat][k]); }); }); // Omit a particular resource type if no requests of that type were // ever made throughout the entire history recorded for this site. output.datasets = output.datasets.filter(function(dataset) { if (exclude && dataset[0] === exclude) { return false; } return resourceTotals[dataset[0]]; }); res.json(output); }); } server.get(fetchViewOptions, fetchView); server.post(fetchViewOptions, fetchView); server.get(historyViewOptions, historyView); server.get(statsViewOptions, statsView); server.get(chartsViewOptions, chartsView); server.listen(process.env.PORT || 5000, function() { console.log('%s listening at %s', server.name, server.url); });
JSON.stringify phantomHAR output
app.js
JSON.stringify phantomHAR output
<ide><path>pp.js <ide> return res.error(400, {error: err}); <ide> } <ide> }); <del> console.log(data); <add> console.log(JSON.stringify(data, null, 4)); <ide> }); <ide> <ide> res.json({success: true});
Java
apache-2.0
b18fa319c36f6a03bb7263025b742b638e36e3db
0
kantega/Flyt-cms,kantega/Flyt-cms,kantega/Flyt-cms
/* * Copyright 2009 Kantega AS * * 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 no.kantega.publishing.common; import com.google.gdata.util.common.base.Pair; import no.kantega.commons.exception.SystemException; import no.kantega.commons.log.Log; import no.kantega.commons.util.StringHelper; import no.kantega.publishing.api.cache.SiteCache; import no.kantega.publishing.api.content.ContentIdentifier; import no.kantega.publishing.api.content.ContentIdentifierDao; import no.kantega.publishing.api.content.Language; import no.kantega.publishing.api.model.Site; import no.kantega.publishing.common.ao.ContentAO; import no.kantega.publishing.common.data.Association; import no.kantega.publishing.common.data.Content; import no.kantega.publishing.common.data.ContentQuery; import no.kantega.publishing.common.data.SortOrder; import no.kantega.publishing.common.data.enums.AssociationType; import no.kantega.publishing.common.data.enums.ContentProperty; import no.kantega.publishing.common.exception.ContentNotFoundException; import no.kantega.publishing.common.util.database.dbConnectionFactory; import no.kantega.publishing.spring.RootContext; import org.apache.commons.lang3.StringUtils; import org.springframework.web.bind.ServletRequestBindingException; import org.springframework.web.bind.ServletRequestUtils; import javax.servlet.http.HttpServletRequest; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import static org.apache.commons.lang3.StringUtils.removeEnd; public class ContentIdHelper { private static final String SOURCE = "aksess.ContentIdHelper"; private static final int defaultContentID = -1; private static final int defaultSiteId = -1; private static final int defaultContextId = -1; private static final int defaultVersion = -1; private static SiteCache siteCache; /** * Find the ContentIdentifer for a Content, relative to the context-Content and expr. * @param context - The current Content-contect * @param expr - Path, e.g. "../", "../../" or "/" * @return - ContentIdentifier * @throws SystemException * @throws ContentNotFoundException */ public static ContentIdentifier findRelativeContentIdentifier(Content context, String expr) throws SystemException, ContentNotFoundException { if (context == null || expr == null) { return null; } if (expr.contains("..")) { // Hent fra N nivåer lengre opp if (expr.charAt(expr.length() - 1) != '/') { expr += "/"; } Association association = context.getAssociation(); String path = association.getPath(); if (path == null || path.length() == 0) { // Finn path'en int parentId = association.getParentAssociationId(); path = AssociationHelper.getPathForId(parentId); } int[] pathElements = StringHelper.getInts(path, "/"); String[] exprPathElements = expr.split("\\.\\."); int exprLength = exprPathElements.length - 1; if (exprLength > pathElements.length) { throw new ContentNotFoundException(SOURCE, expr); } ContentIdentifier cid = ContentIdentifier.fromAssociationId(pathElements[pathElements.length - exprLength]); assureContentIdAndAssociationIdSet(cid); cid.setLanguage(context.getLanguage()); return cid; } else if (expr.equalsIgnoreCase(".")) { // Hent fra denne siden ContentIdentifier cid = ContentIdentifier.fromAssociationId(context.getAssociation().getAssociationId()); cid.setLanguage(context.getLanguage()); assureContentIdAndAssociationIdSet(cid); return cid; } else if (expr.equalsIgnoreCase("group")) { // Hent fra group ContentIdentifier cid = ContentIdentifier.fromContentId(context.getGroupId()); cid.setLanguage(context.getLanguage()); assureContentIdAndAssociationIdSet(cid); return cid; } else if (expr.startsWith("/+")) { // Hent fra root + nivå n int level = Integer.parseInt(expr.substring("/+".length(), expr.length())); String path = context.getAssociation().getPath() + context.getAssociation().getId() + "/"; int[] pathElements = StringHelper.getInts(path, "/"); if (level > pathElements.length) { level = pathElements.length; } ContentIdentifier contentIdentifier = ContentIdentifier.fromAssociationId(pathElements[level]); assureContentIdAndAssociationIdSet(contentIdentifier); return contentIdentifier; } else if (expr.equalsIgnoreCase("next") || expr.equalsIgnoreCase("previous")){ boolean next = expr.equalsIgnoreCase("next"); Association association = context.getAssociation(); ContentIdentifier parent = ContentIdentifier.fromAssociationId(association.getParentAssociationId()); ContentQuery query = new ContentQuery(); query.setAssociatedId(parent); query.setAssociationCategory(association.getCategory()); List<Content> children = ContentAO.getContentList(query, -1, new SortOrder(ContentProperty.PRIORITY, false), false); for (int i = 0; i < children.size(); i++) { Content c = children.get(i); if (c.getAssociation().getId() == context.getAssociation().getId()) { if (next){ if (i < children.size() -1){ return children.get(i + 1).getContentIdentifier(); } else { return null; } } else { if (i > 0) { return children.get(i -1).getContentIdentifier(); } else { return null; } } } } return null; } else { return findContentIdentifier(context.getAssociation().getSiteId(), expr); } } /** * @param siteId - Site * @param url - Url/alias, e.g. /nyheter/ * @return ContentIdentifier for the given site and url. * @throws ContentNotFoundException * @throws SystemException */ public static ContentIdentifier findContentIdentifier(int siteId, String url) throws ContentNotFoundException, SystemException { int contentId = -1; int associationId = -1; int version = -1; int language = Language.NORWEGIAN_BO; if (url == null) { throw new ContentNotFoundException("", SOURCE); } if (url.indexOf('#') > 0) { url = url.substring(0, url.indexOf("#")); } url = getPath(url); associationId = getAssociationIdFromPrettyUrl(url, associationId); associationId = getAssociationIdFromThisId(url, associationId); contentId = getContentIdFromParameter(url, contentId, associationId); language = getLanguage(url, language); version = getVersion(url, version); // Hvis contentId ikke finnes i URL, slå opp i basen if (contentId != -1 || associationId != -1) { ContentIdentifier cid; if (associationId != -1) { cid = ContentIdentifier.fromAssociationId(associationId); } else { cid = ContentIdentifier.fromContentId(contentId); cid.setSiteId(siteId); } cid.setVersion(version); cid.setLanguage(language); assureContentIdAndAssociationIdSet(cid); return cid; } else { int end = url.indexOf('?'); if (end != -1) { url = url.substring(0, end); } end = url.lastIndexOf(Aksess.CONTENT_REQUEST_HANDLER); if (end != -1) { url = url.substring(0, end); } else { end = url.lastIndexOf(Aksess.getStartPage()); if (end != -1) { url = url.substring(0, end); } } setSiteCacheIfNull(); if (siteId != -1) { if ("/".equalsIgnoreCase(url)) { Site site = siteCache.getSiteById(siteId); if (site != null) { url = site.getAlias(); } } } else if ("/".equalsIgnoreCase(url)) { Site defaultSite = siteCache.getDefaultSite(); if (defaultSite != null) { siteId = defaultSite.getId(); url = defaultSite.getAlias(); } else { siteId = 1; url = siteCache.getSiteById(1).getAlias(); } } else { List<Site> sites = siteCache.getSites(); for (Site site : sites){ String siteAliasWithoutTrailingSlash = removeEnd(site.getAlias(), "/"); if(url.startsWith(siteAliasWithoutTrailingSlash)){ url = StringUtils.remove(url, siteAliasWithoutTrailingSlash); siteId = site.getId(); } } } return getContentIdentifier(siteId, url); } } private static int getVersion(String url, int version) { String versionToken = "version="; int versionPos = url.indexOf(versionToken); if (versionPos != -1) { String versionStr = url.substring(versionPos + versionToken.length(), url.length()); int end = versionStr.indexOf('&'); if (end != -1) { versionStr = versionStr.substring(0, end); } try { version = Integer.parseInt(versionStr); } catch (NumberFormatException e) { // Siste versjon } } return version; } private static int getContentIdFromParameter(String url, int contentId, int associationId) { if (associationId == -1) { String idToken = "contentid="; int idPos = url.indexOf(idToken); if (idPos != -1) { String idStr = url.substring(idPos + idToken.length(), url.length()); int end = idStr.indexOf('&'); if (end != -1) { idStr = idStr.substring(0, end); } try { contentId = Integer.parseInt(idStr); } catch (NumberFormatException e) { // Gjør ingenting } } } return contentId; } private static int getAssociationIdFromThisId(String url, int associationId) { String aIdToken = "thisid="; int aIdPos = url.indexOf(aIdToken); if (aIdPos != -1) { String idStr = url.substring(aIdPos + aIdToken.length(), url.length()); int end = idStr.indexOf('&'); if (end != -1) { idStr = idStr.substring(0, end); } try { associationId = Integer.parseInt(idStr); } catch (NumberFormatException e) { // Gjør ingenting } } return associationId; } /* Looks for /content/ID/name */ private static int getAssociationIdFromPrettyUrl(String url, int associationId) { int contentPos = url.indexOf(Aksess.CONTENT_URL_PREFIX); if (contentPos != -1 && url.length() > Aksess.CONTENT_URL_PREFIX.length() + 1) { String idStr = url.substring(contentPos + Aksess.CONTENT_URL_PREFIX.length() + 1, url.length()); int end = idStr.indexOf("/"); if (end != -1) { idStr = idStr.substring(0, end); } try { associationId = Integer.parseInt(idStr); } catch (NumberFormatException e) { // Do nothing } } return associationId; } /* Removes protocol and servername. */ private static String getPath(String url) { url = url.toLowerCase(); if (url.startsWith("http://") || url.startsWith("https://")) { url = url.substring(url.indexOf("://") + 3, url.length()); if (url.indexOf('/') != -1) { url = url.substring(url.indexOf('/'), url.length()); } String contextPath = Aksess.getContextPath().toLowerCase(); if (url.length() > contextPath.length()) { url = url.substring(contextPath.length(), url.length()); } if (url.length() == 0) { url = "/"; } } return url; } private static int getLanguage(String url, int language) { String languageToken = "language="; int languagePos = url.indexOf(languageToken); if (languagePos != -1) { String languageStr = url.substring(languagePos + languageToken.length(), url.length()); int end = languageStr.indexOf('&'); if (end != -1) { languageStr = languageStr.substring(0, end); } try { language = Integer.parseInt(languageStr); } catch (NumberFormatException e) { // Standard språk } } return language; } private static ContentIdentifier getContentIdentifier(int siteId, String url) throws ContentNotFoundException { ContentIdentifierDao contentIdentifierDao = RootContext.getInstance().getBean(ContentIdentifierDao.class); ContentIdentifier cid = null; if (siteId > 0) { cid = contentIdentifierDao.getContentIdentifierBySiteIdAndAlias(siteId, url); } else { // we are likely in development, where no sites are configured. List<ContentIdentifier> contentIdentifiersByAlias = contentIdentifierDao.getContentIdentifiersByAlias(url); if(!contentIdentifiersByAlias.isEmpty()){ cid = contentIdentifiersByAlias.get(0); } } if (cid == null) { throw new ContentNotFoundException(url, SOURCE); } return cid; } private static int findAssociationIdFromContentId(int contentId, int siteId, int contextId) throws SystemException { int associationId = -1; try (Connection c = dbConnectionFactory.getConnection()){ PreparedStatement st; ResultSet rs; if (contextId != -1) { // Først prøver vi å finne siden under der lenka kom fra st = c.prepareStatement("SELECT AssociationId FROM associations WHERE ContentId = ? AND Path like ? AND (IsDeleted IS NULL OR IsDeleted = 0)"); st.setInt(1, contentId); st.setString(2, "%/" + contextId + "/%"); rs = st.executeQuery(); if(rs.next()) { associationId = rs.getInt("AssociationId"); } rs.close(); st.close(); // Så i samme nettsted som lenka kom fra if (associationId == -1) { st = c.prepareStatement("SELECT SiteId FROM associations WHERE AssociationId = ? AND (IsDeleted IS NULL OR IsDeleted = 0)"); st.setInt(1, contextId); rs = st.executeQuery(); if(rs.next()) { siteId = rs.getInt("SiteId"); } rs.close(); st.close(); } } if (associationId == -1) { st = c.prepareStatement("SELECT AssociationId, SiteId FROM associations WHERE ContentId = ? AND Type = ? AND (IsDeleted IS NULL OR IsDeleted = 0)"); st.setInt(1, contentId); st.setInt(2, AssociationType.DEFAULT_POSTING_FOR_SITE); rs = st.executeQuery(); while(rs.next()) { int tmp = rs.getInt("AssociationId"); int tmpSiteId = rs.getInt("SiteId"); if (associationId == -1 || tmpSiteId == siteId) { associationId = tmp; } } rs.close(); st.close(); } } catch (SQLException e) { throw new SystemException("Feil ved SQL kall", SOURCE, e); } return associationId; } private static int findContentIdFromAssociationId(int associationId) throws SystemException { int contentId = -1; try (Connection c = dbConnectionFactory.getConnection()){ PreparedStatement st = c.prepareStatement("select ContentId from associations where AssociationId = ?"); st.setInt(1, associationId); ResultSet rs = st.executeQuery(); while(rs.next()) { contentId = rs.getInt("ContentId"); } rs.close(); st.close(); } catch (SQLException e) { throw new SystemException("Feil ved SQL kall", SOURCE, e); } return contentId; } private static int getSiteIdFromRequest(HttpServletRequest request) throws SystemException { return getSiteIdFromRequest(request, null).first; } /** * @return pair containing found siteId and the alias tried found. * If url is siteId/alias, url is adjusted to /alias */ private static Pair<Integer, String> getSiteIdFromRequest(HttpServletRequest request, String url) throws SystemException { int siteId = -1; String adjustedUrl = url; if (request.getParameter("siteId") != null) { try { siteId = Integer.parseInt(request.getParameter("siteId")); } catch (NumberFormatException e) { } } if (siteId == -1) { Content content = (Content)request.getAttribute("aksess_this"); if (content != null) { siteId = content.getAssociation().getSiteId(); } } if (siteId == -1 && url != null) { int siteIdPos = url.indexOf("siteId="); if (siteIdPos != -1) { String siteIdStr = url.substring(siteIdPos + "siteId=".length(), url.length()); int siteIdEndPos = siteIdStr.indexOf("&"); if (siteIdEndPos != -1) { siteIdStr = siteIdStr.substring(0, siteIdEndPos); } try { siteId = Integer.parseInt(siteIdStr); } catch (NumberFormatException e) { } } } setSiteCacheIfNull(); if (siteId == -1) { Site site = siteCache.getSiteByHostname(request.getServerName()); if(url != null) { List<Site> sites = siteCache.getSites(); for (Site s : sites){ String siteAliasWithoutTrailingSlash = removeEnd(s.getAlias(), "/"); if(url.startsWith(siteAliasWithoutTrailingSlash)){ adjustedUrl = StringUtils.remove(url, siteAliasWithoutTrailingSlash); siteId = s.getId(); break; } } } else if (site != null) { siteId = site.getId(); } } if(siteId == -1){ siteId = siteCache.getDefaultSite().getId(); } return new Pair<>(siteId, adjustedUrl); } /** * * @param request - The current request * @return ContentIdentifier for the given request. * @throws ContentNotFoundException */ public static ContentIdentifier fromRequest(HttpServletRequest request) throws ContentNotFoundException { ContentIdentifier contentIdentifier = null; String url = request.getServletPath(); String path = request.getPathInfo(); Content current = (Content)request.getAttribute("aksess_this"); if (current != null) { contentIdentifier = ContentIdentifier.fromAssociationId(current.getAssociation().getId()); contentIdentifier.setLanguage(current.getLanguage()); contentIdentifier.setVersion(current.getVersion()); } else if (request.getParameter("contentId") != null || request.getParameter("thisId") != null) { if (request.getParameter("contentId") != null) { contentIdentifier = ContentIdentifier.fromContentId(ServletRequestUtils.getIntParameter(request, "contentId", defaultContentID)); contentIdentifier.setSiteId(ServletRequestUtils.getIntParameter(request, "siteId", defaultSiteId)); contentIdentifier.setContextId(ServletRequestUtils.getIntParameter(request, "contextId", defaultContextId)); } else { try { contentIdentifier = ContentIdentifier.fromAssociationId(ServletRequestUtils.getIntParameter(request, "thisId")); } catch (ServletRequestBindingException e) { throw new ContentNotFoundException(request.getParameter("thisId"), SOURCE); } } contentIdentifier.setLanguage(ServletRequestUtils.getIntParameter(request, "language", Language.NORWEGIAN_BO)); } else if (url.startsWith(Aksess.CONTENT_URL_PREFIX) && path != null && path.indexOf("/") == 0) { try { int slashIndex = path.indexOf("/", 1); if (slashIndex != -1) { contentIdentifier = ContentIdentifier.fromAssociationId(Integer.parseInt(path.substring(1, slashIndex))); } } catch (NumberFormatException e) { throw new ContentNotFoundException(path, SOURCE); } } else { String queryString = request.getQueryString(); if (queryString != null && queryString.length() > 0) { url = url + "?" + queryString; } int siteId = ContentIdHelper.getSiteIdFromRequest(request); contentIdentifier = ContentIdHelper.findContentIdentifier(siteId, url); } if (contentIdentifier != null) { contentIdentifier.setVersion(ServletRequestUtils.getIntParameter(request, "version", defaultVersion)); } return contentIdentifier; } /** * @param request - The current request * @param url - The url of ContentIdentifier is desired for. * @return ContentIdentifier for url. * @throws ContentNotFoundException * @throws SystemException */ public static ContentIdentifier fromRequestAndUrl(HttpServletRequest request, String url) throws ContentNotFoundException, SystemException { Pair<Integer, String> siteId = ContentIdHelper.getSiteIdFromRequest(request, url); return ContentIdHelper.findContentIdentifier(siteId.first, siteId.second); } /** * * @param siteId - id of the site we want ContentIdentifier for. * @param url we want ContentIdentifier for. * @return ContentIdentifier for url on site with siteId * @throws SystemException * @throws ContentNotFoundException */ public static ContentIdentifier fromSiteIdAndUrl(int siteId, String url) throws SystemException, ContentNotFoundException { return ContentIdHelper.findContentIdentifier(siteId, url); } /** * @param url - e.g. "/" * @return ContentIdentifier for url. * @throws ContentNotFoundException * @throws SystemException */ public static ContentIdentifier fromUrl(String url) throws ContentNotFoundException, SystemException { return ContentIdHelper.findContentIdentifier(-1, url); } /** * Make sure the given ContentIdentifier has both contentId and associationId set. * @param contentIdentifier assure both are set on. */ public static void assureContentIdAndAssociationIdSet(ContentIdentifier contentIdentifier){ if (contentIdentifier != null) { int associationId = contentIdentifier.getAssociationId(); int contentId = contentIdentifier.getContentId(); if (contentId != -1 && associationId == -1) { try { associationId = ContentIdHelper.findAssociationIdFromContentId(contentId, contentIdentifier.getSiteId(), contentIdentifier.getContextId()); contentIdentifier.setAssociationId(associationId); } catch (SystemException e) { Log.error(SOURCE, e, null, null); } } else if (contentId == -1 && associationId != -1) { try { contentId = ContentIdHelper.findContentIdFromAssociationId(associationId); contentIdentifier.setContentId(contentId); } catch (SystemException e) { Log.error(SOURCE, e, null, null); } } } } private static void setSiteCacheIfNull() { if(siteCache == null){ siteCache = RootContext.getInstance().getBean(SiteCache.class); } } }
modules/core/src/java/no/kantega/publishing/common/ContentIdHelper.java
/* * Copyright 2009 Kantega AS * * 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 no.kantega.publishing.common; import no.kantega.commons.exception.SystemException; import no.kantega.commons.log.Log; import no.kantega.commons.util.StringHelper; import no.kantega.publishing.api.cache.SiteCache; import no.kantega.publishing.api.content.ContentIdentifier; import no.kantega.publishing.api.content.ContentIdentifierDao; import no.kantega.publishing.api.content.Language; import no.kantega.publishing.api.model.Site; import no.kantega.publishing.common.ao.ContentAO; import no.kantega.publishing.common.data.Association; import no.kantega.publishing.common.data.Content; import no.kantega.publishing.common.data.ContentQuery; import no.kantega.publishing.common.data.SortOrder; import no.kantega.publishing.common.data.enums.AssociationType; import no.kantega.publishing.common.data.enums.ContentProperty; import no.kantega.publishing.common.exception.ContentNotFoundException; import no.kantega.publishing.common.util.database.dbConnectionFactory; import no.kantega.publishing.spring.RootContext; import org.apache.commons.lang3.StringUtils; import org.springframework.web.bind.ServletRequestBindingException; import org.springframework.web.bind.ServletRequestUtils; import javax.servlet.http.HttpServletRequest; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import static org.apache.commons.lang3.StringUtils.removeEnd; public class ContentIdHelper { private static final String SOURCE = "aksess.ContentIdHelper"; private static final int defaultContentID = -1; private static final int defaultSiteId = -1; private static final int defaultContextId = -1; private static final int defaultVersion = -1; private static SiteCache siteCache; /** * Find the ContentIdentifer for a Content, relative to the context-Content and expr. * @param context - The current Content-contect * @param expr - Path, e.g. "../", "../../" or "/" * @return - ContentIdentifier * @throws SystemException * @throws ContentNotFoundException */ public static ContentIdentifier findRelativeContentIdentifier(Content context, String expr) throws SystemException, ContentNotFoundException { if (context == null || expr == null) { return null; } if (expr.contains("..")) { // Hent fra N nivåer lengre opp if (expr.charAt(expr.length() - 1) != '/') { expr += "/"; } Association association = context.getAssociation(); String path = association.getPath(); if (path == null || path.length() == 0) { // Finn path'en int parentId = association.getParentAssociationId(); path = AssociationHelper.getPathForId(parentId); } int[] pathElements = StringHelper.getInts(path, "/"); String[] exprPathElements = expr.split("\\.\\."); int exprLength = exprPathElements.length - 1; if (exprLength > pathElements.length) { throw new ContentNotFoundException(SOURCE, expr); } ContentIdentifier cid = ContentIdentifier.fromAssociationId(pathElements[pathElements.length - exprLength]); assureContentIdAndAssociationIdSet(cid); cid.setLanguage(context.getLanguage()); return cid; } else if (expr.equalsIgnoreCase(".")) { // Hent fra denne siden ContentIdentifier cid = ContentIdentifier.fromAssociationId(context.getAssociation().getAssociationId()); cid.setLanguage(context.getLanguage()); assureContentIdAndAssociationIdSet(cid); return cid; } else if (expr.equalsIgnoreCase("group")) { // Hent fra group ContentIdentifier cid = ContentIdentifier.fromContentId(context.getGroupId()); cid.setLanguage(context.getLanguage()); assureContentIdAndAssociationIdSet(cid); return cid; } else if (expr.startsWith("/+")) { // Hent fra root + nivå n int level = Integer.parseInt(expr.substring("/+".length(), expr.length())); String path = context.getAssociation().getPath() + context.getAssociation().getId() + "/"; int[] pathElements = StringHelper.getInts(path, "/"); if (level > pathElements.length) { level = pathElements.length; } ContentIdentifier contentIdentifier = ContentIdentifier.fromAssociationId(pathElements[level]); assureContentIdAndAssociationIdSet(contentIdentifier); return contentIdentifier; } else if (expr.equalsIgnoreCase("next") || expr.equalsIgnoreCase("previous")){ boolean next = expr.equalsIgnoreCase("next"); Association association = context.getAssociation(); ContentIdentifier parent = ContentIdentifier.fromAssociationId(association.getParentAssociationId()); ContentQuery query = new ContentQuery(); query.setAssociatedId(parent); query.setAssociationCategory(association.getCategory()); List<Content> children = ContentAO.getContentList(query, -1, new SortOrder(ContentProperty.PRIORITY, false), false); for (int i = 0; i < children.size(); i++) { Content c = children.get(i); if (c.getAssociation().getId() == context.getAssociation().getId()) { if (next){ if (i < children.size() -1){ return children.get(i + 1).getContentIdentifier(); } else { return null; } } else { if (i > 0) { return children.get(i -1).getContentIdentifier(); } else { return null; } } } } return null; } else { return findContentIdentifier(context.getAssociation().getSiteId(), expr); } } /** * @param siteId - Site * @param url - Url/alias, e.g. /nyheter/ * @return ContentIdentifier for the given site and url. * @throws ContentNotFoundException * @throws SystemException */ public static ContentIdentifier findContentIdentifier(int siteId, String url) throws ContentNotFoundException, SystemException { int contentId = -1; int associationId = -1; int version = -1; int language = Language.NORWEGIAN_BO; if (url == null) { throw new ContentNotFoundException("", SOURCE); } if (url.indexOf('#') > 0) { url = url.substring(0, url.indexOf("#")); } url = getPath(url); associationId = getAssociationIdFromPrettyUrl(url, associationId); associationId = getAssociationIdFromThisId(url, associationId); contentId = getContentIdFromParameter(url, contentId, associationId); language = getLanguage(url, language); version = getVersion(url, version); // Hvis contentId ikke finnes i URL, slå opp i basen if (contentId != -1 || associationId != -1) { ContentIdentifier cid; if (associationId != -1) { cid = ContentIdentifier.fromAssociationId(associationId); } else { cid = ContentIdentifier.fromContentId(contentId); cid.setSiteId(siteId); } cid.setVersion(version); cid.setLanguage(language); assureContentIdAndAssociationIdSet(cid); return cid; } else { int end = url.indexOf('?'); if (end != -1) { url = url.substring(0, end); } end = url.lastIndexOf(Aksess.CONTENT_REQUEST_HANDLER); if (end != -1) { url = url.substring(0, end); } else { end = url.lastIndexOf(Aksess.getStartPage()); if (end != -1) { url = url.substring(0, end); } } setSiteCacheIfNull(); if (siteId != -1) { if ("/".equalsIgnoreCase(url)) { Site site = siteCache.getSiteById(siteId); if (site != null) { url = site.getAlias(); } } } else if ("/".equalsIgnoreCase(url)) { Site defaultSite = siteCache.getDefaultSite(); if (defaultSite != null) { siteId = defaultSite.getId(); url = defaultSite.getAlias(); } else { siteId = 1; url = siteCache.getSiteById(1).getAlias(); } } else { List<Site> sites = siteCache.getSites(); for (Site site : sites){ String siteAliasWithoutTrailingSlash = removeEnd(site.getAlias(), "/"); if(url.startsWith(siteAliasWithoutTrailingSlash)){ url = StringUtils.remove(url, siteAliasWithoutTrailingSlash); siteId = site.getId(); } } } return getContentIdentifier(siteId, url); } } private static int getVersion(String url, int version) { String versionToken = "version="; int versionPos = url.indexOf(versionToken); if (versionPos != -1) { String versionStr = url.substring(versionPos + versionToken.length(), url.length()); int end = versionStr.indexOf('&'); if (end != -1) { versionStr = versionStr.substring(0, end); } try { version = Integer.parseInt(versionStr); } catch (NumberFormatException e) { // Siste versjon } } return version; } private static int getContentIdFromParameter(String url, int contentId, int associationId) { if (associationId == -1) { String idToken = "contentid="; int idPos = url.indexOf(idToken); if (idPos != -1) { String idStr = url.substring(idPos + idToken.length(), url.length()); int end = idStr.indexOf('&'); if (end != -1) { idStr = idStr.substring(0, end); } try { contentId = Integer.parseInt(idStr); } catch (NumberFormatException e) { // Gjør ingenting } } } return contentId; } private static int getAssociationIdFromThisId(String url, int associationId) { String aIdToken = "thisid="; int aIdPos = url.indexOf(aIdToken); if (aIdPos != -1) { String idStr = url.substring(aIdPos + aIdToken.length(), url.length()); int end = idStr.indexOf('&'); if (end != -1) { idStr = idStr.substring(0, end); } try { associationId = Integer.parseInt(idStr); } catch (NumberFormatException e) { // Gjør ingenting } } return associationId; } /* Looks for /content/ID/name */ private static int getAssociationIdFromPrettyUrl(String url, int associationId) { int contentPos = url.indexOf(Aksess.CONTENT_URL_PREFIX); if (contentPos != -1 && url.length() > Aksess.CONTENT_URL_PREFIX.length() + 1) { String idStr = url.substring(contentPos + Aksess.CONTENT_URL_PREFIX.length() + 1, url.length()); int end = idStr.indexOf("/"); if (end != -1) { idStr = idStr.substring(0, end); } try { associationId = Integer.parseInt(idStr); } catch (NumberFormatException e) { // Do nothing } } return associationId; } /* Removes protocol and servername. */ private static String getPath(String url) { url = url.toLowerCase(); if (url.startsWith("http://") || url.startsWith("https://")) { url = url.substring(url.indexOf("://") + 3, url.length()); if (url.indexOf('/') != -1) { url = url.substring(url.indexOf('/'), url.length()); } String contextPath = Aksess.getContextPath().toLowerCase(); if (url.length() > contextPath.length()) { url = url.substring(contextPath.length(), url.length()); } if (url.length() == 0) { url = "/"; } } return url; } private static int getLanguage(String url, int language) { String languageToken = "language="; int languagePos = url.indexOf(languageToken); if (languagePos != -1) { String languageStr = url.substring(languagePos + languageToken.length(), url.length()); int end = languageStr.indexOf('&'); if (end != -1) { languageStr = languageStr.substring(0, end); } try { language = Integer.parseInt(languageStr); } catch (NumberFormatException e) { // Standard språk } } return language; } private static ContentIdentifier getContentIdentifier(int siteId, String url) throws ContentNotFoundException { ContentIdentifierDao contentIdentifierDao = RootContext.getInstance().getBean(ContentIdentifierDao.class); ContentIdentifier cid = null; if (siteId > 0) { cid = contentIdentifierDao.getContentIdentifierBySiteIdAndAlias(siteId, url); } else { // we are likely in development, where no sites are configured. List<ContentIdentifier> contentIdentifiersByAlias = contentIdentifierDao.getContentIdentifiersByAlias(url); if(!contentIdentifiersByAlias.isEmpty()){ cid = contentIdentifiersByAlias.get(0); } } if (cid == null) { throw new ContentNotFoundException(url, SOURCE); } return cid; } private static int findAssociationIdFromContentId(int contentId, int siteId, int contextId) throws SystemException { int associationId = -1; try (Connection c = dbConnectionFactory.getConnection()){ PreparedStatement st; ResultSet rs; if (contextId != -1) { // Først prøver vi å finne siden under der lenka kom fra st = c.prepareStatement("SELECT AssociationId FROM associations WHERE ContentId = ? AND Path like ? AND (IsDeleted IS NULL OR IsDeleted = 0)"); st.setInt(1, contentId); st.setString(2, "%/" + contextId + "/%"); rs = st.executeQuery(); if(rs.next()) { associationId = rs.getInt("AssociationId"); } rs.close(); st.close(); // Så i samme nettsted som lenka kom fra if (associationId == -1) { st = c.prepareStatement("SELECT SiteId FROM associations WHERE AssociationId = ? AND (IsDeleted IS NULL OR IsDeleted = 0)"); st.setInt(1, contextId); rs = st.executeQuery(); if(rs.next()) { siteId = rs.getInt("SiteId"); } rs.close(); st.close(); } } if (associationId == -1) { st = c.prepareStatement("SELECT AssociationId, SiteId FROM associations WHERE ContentId = ? AND Type = ? AND (IsDeleted IS NULL OR IsDeleted = 0)"); st.setInt(1, contentId); st.setInt(2, AssociationType.DEFAULT_POSTING_FOR_SITE); rs = st.executeQuery(); while(rs.next()) { int tmp = rs.getInt("AssociationId"); int tmpSiteId = rs.getInt("SiteId"); if (associationId == -1 || tmpSiteId == siteId) { associationId = tmp; } } rs.close(); st.close(); } } catch (SQLException e) { throw new SystemException("Feil ved SQL kall", SOURCE, e); } return associationId; } private static int findContentIdFromAssociationId(int associationId) throws SystemException { int contentId = -1; try (Connection c = dbConnectionFactory.getConnection()){ PreparedStatement st = c.prepareStatement("select ContentId from associations where AssociationId = ?"); st.setInt(1, associationId); ResultSet rs = st.executeQuery(); while(rs.next()) { contentId = rs.getInt("ContentId"); } rs.close(); st.close(); } catch (SQLException e) { throw new SystemException("Feil ved SQL kall", SOURCE, e); } return contentId; } private static int getSiteIdFromRequest(HttpServletRequest request) throws SystemException { return getSiteIdFromRequest(request, null); } private static int getSiteIdFromRequest(HttpServletRequest request, String url) throws SystemException { int siteId = -1; if (request.getParameter("siteId") != null) { try { siteId = Integer.parseInt(request.getParameter("siteId")); } catch (NumberFormatException e) { } } if (siteId == -1) { Content content = (Content)request.getAttribute("aksess_this"); if (content != null) { siteId = content.getAssociation().getSiteId(); } } if (siteId == -1 && url != null) { int siteIdPos = url.indexOf("siteId="); if (siteIdPos != -1) { String siteIdStr = url.substring(siteIdPos + "siteId=".length(), url.length()); int siteIdEndPos = siteIdStr.indexOf("&"); if (siteIdEndPos != -1) { siteIdStr = siteIdStr.substring(0, siteIdEndPos); } try { siteId = Integer.parseInt(siteIdStr); } catch (NumberFormatException e) { } } } setSiteCacheIfNull(); if (siteId == -1) { Site site = siteCache.getSiteByHostname(request.getServerName()); if(url != null) { List<Site> sites = siteCache.getSites(); for (Site s : sites){ String siteAliasWithoutTrailingSlash = removeEnd(s.getAlias(), "/"); if(url.startsWith(siteAliasWithoutTrailingSlash)){ url = StringUtils.remove(url, siteAliasWithoutTrailingSlash); siteId = s.getId(); } } } else if (site != null) { siteId = site.getId(); } } if(siteId == -1){ siteId = siteCache.getDefaultSite().getId(); } return siteId; } /** * * @param request - The current request * @return ContentIdentifier for the given request. * @throws ContentNotFoundException */ public static ContentIdentifier fromRequest(HttpServletRequest request) throws ContentNotFoundException { ContentIdentifier contentIdentifier = null; String url = request.getServletPath(); String path = request.getPathInfo(); Content current = (Content)request.getAttribute("aksess_this"); if (current != null) { contentIdentifier = ContentIdentifier.fromAssociationId(current.getAssociation().getId()); contentIdentifier.setLanguage(current.getLanguage()); contentIdentifier.setVersion(current.getVersion()); } else if (request.getParameter("contentId") != null || request.getParameter("thisId") != null) { if (request.getParameter("contentId") != null) { contentIdentifier = ContentIdentifier.fromContentId(ServletRequestUtils.getIntParameter(request, "contentId", defaultContentID)); contentIdentifier.setSiteId(ServletRequestUtils.getIntParameter(request, "siteId", defaultSiteId)); contentIdentifier.setContextId(ServletRequestUtils.getIntParameter(request, "contextId", defaultContextId)); } else { try { contentIdentifier = ContentIdentifier.fromAssociationId(ServletRequestUtils.getIntParameter(request, "thisId")); } catch (ServletRequestBindingException e) { throw new ContentNotFoundException(request.getParameter("thisId"), SOURCE); } } contentIdentifier.setLanguage(ServletRequestUtils.getIntParameter(request, "language", Language.NORWEGIAN_BO)); } else if (url.startsWith(Aksess.CONTENT_URL_PREFIX) && path != null && path.indexOf("/") == 0) { try { int slashIndex = path.indexOf("/", 1); if (slashIndex != -1) { contentIdentifier = ContentIdentifier.fromAssociationId(Integer.parseInt(path.substring(1, slashIndex))); } } catch (NumberFormatException e) { throw new ContentNotFoundException(path, SOURCE); } } else { String queryString = request.getQueryString(); if (queryString != null && queryString.length() > 0) { url = url + "?" + queryString; } int siteId = ContentIdHelper.getSiteIdFromRequest(request); contentIdentifier = ContentIdHelper.findContentIdentifier(siteId, url); } if (contentIdentifier != null) { contentIdentifier.setVersion(ServletRequestUtils.getIntParameter(request, "version", defaultVersion)); } return contentIdentifier; } /** * @param request - The current request * @param url - The url of ContentIdentifier is desired for. * @return ContentIdentifier for url. * @throws ContentNotFoundException * @throws SystemException */ public static ContentIdentifier fromRequestAndUrl(HttpServletRequest request, String url) throws ContentNotFoundException, SystemException { int siteId = ContentIdHelper.getSiteIdFromRequest(request, url); return ContentIdHelper.findContentIdentifier(siteId, url); } /** * * @param siteId - id of the site we want ContentIdentifier for. * @param url we want ContentIdentifier for. * @return ContentIdentifier for url on site with siteId * @throws SystemException * @throws ContentNotFoundException */ public static ContentIdentifier fromSiteIdAndUrl(int siteId, String url) throws SystemException, ContentNotFoundException { return ContentIdHelper.findContentIdentifier(siteId, url); } /** * @param url - e.g. "/" * @return ContentIdentifier for url. * @throws ContentNotFoundException * @throws SystemException */ public static ContentIdentifier fromUrl(String url) throws ContentNotFoundException, SystemException { return ContentIdHelper.findContentIdentifier(-1, url); } /** * Make sure the given ContentIdentifier has both contentId and associationId set. * @param contentIdentifier assure both are set on. */ public static void assureContentIdAndAssociationIdSet(ContentIdentifier contentIdentifier){ if (contentIdentifier != null) { int associationId = contentIdentifier.getAssociationId(); int contentId = contentIdentifier.getContentId(); if (contentId != -1 && associationId == -1) { try { associationId = ContentIdHelper.findAssociationIdFromContentId(contentId, contentIdentifier.getSiteId(), contentIdentifier.getContextId()); contentIdentifier.setAssociationId(associationId); } catch (SystemException e) { Log.error(SOURCE, e, null, null); } } else if (contentId == -1 && associationId != -1) { try { contentId = ContentIdHelper.findContentIdFromAssociationId(associationId); contentIdentifier.setContentId(contentId); } catch (SystemException e) { Log.error(SOURCE, e, null, null); } } } } private static void setSiteCacheIfNull() { if(siteCache == null){ siteCache = RootContext.getInstance().getBean(SiteCache.class); } } }
AP-1549 - Page on site with alias does not work git-svn-id: a93d0315e7e7eeba024b3856a238bc20f6e6a60a@4173 fd808399-8219-4f14-9d4c-37719d9ec93d
modules/core/src/java/no/kantega/publishing/common/ContentIdHelper.java
AP-1549 - Page on site with alias does not work
<ide><path>odules/core/src/java/no/kantega/publishing/common/ContentIdHelper.java <ide> <ide> package no.kantega.publishing.common; <ide> <add>import com.google.gdata.util.common.base.Pair; <ide> import no.kantega.commons.exception.SystemException; <ide> import no.kantega.commons.log.Log; <ide> import no.kantega.commons.util.StringHelper; <ide> } <ide> <ide> private static int getSiteIdFromRequest(HttpServletRequest request) throws SystemException { <del> return getSiteIdFromRequest(request, null); <del> } <del> <del> private static int getSiteIdFromRequest(HttpServletRequest request, String url) throws SystemException { <add> return getSiteIdFromRequest(request, null).first; <add> } <add> <add> /** <add> * @return pair containing found siteId and the alias tried found. <add> * If url is siteId/alias, url is adjusted to /alias <add> */ <add> private static Pair<Integer, String> getSiteIdFromRequest(HttpServletRequest request, String url) throws SystemException { <ide> int siteId = -1; <add> String adjustedUrl = url; <ide> if (request.getParameter("siteId") != null) { <ide> try { <ide> siteId = Integer.parseInt(request.getParameter("siteId")); <ide> for (Site s : sites){ <ide> String siteAliasWithoutTrailingSlash = removeEnd(s.getAlias(), "/"); <ide> if(url.startsWith(siteAliasWithoutTrailingSlash)){ <del> url = StringUtils.remove(url, siteAliasWithoutTrailingSlash); <add> adjustedUrl = StringUtils.remove(url, siteAliasWithoutTrailingSlash); <ide> siteId = s.getId(); <add> break; <ide> } <ide> } <ide> } else if (site != null) { <ide> siteId = siteCache.getDefaultSite().getId(); <ide> } <ide> <del> return siteId; <add> return new Pair<>(siteId, adjustedUrl); <ide> } <ide> <ide> /** <ide> * @throws SystemException <ide> */ <ide> public static ContentIdentifier fromRequestAndUrl(HttpServletRequest request, String url) throws ContentNotFoundException, SystemException { <del> int siteId = ContentIdHelper.getSiteIdFromRequest(request, url); <del> return ContentIdHelper.findContentIdentifier(siteId, url); <add> Pair<Integer, String> siteId = ContentIdHelper.getSiteIdFromRequest(request, url); <add> return ContentIdHelper.findContentIdentifier(siteId.first, siteId.second); <ide> } <ide> <ide> /**
Java
apache-2.0
6d4d3fc93f1620e6c9df09ee1bbceee0e0da081c
0
jtablesaw/tablesaw,jtablesaw/tablesaw,jtablesaw/tablesaw
package tech.tablesaw.joining; import com.google.common.collect.Streams; import com.google.common.primitives.Ints; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; import tech.tablesaw.api.BooleanColumn; import tech.tablesaw.api.ColumnType; import tech.tablesaw.api.DateColumn; import tech.tablesaw.api.DateTimeColumn; import tech.tablesaw.api.DoubleColumn; import tech.tablesaw.api.FloatColumn; import tech.tablesaw.api.InstantColumn; import tech.tablesaw.api.IntColumn; import tech.tablesaw.api.LongColumn; import tech.tablesaw.api.Row; import tech.tablesaw.api.ShortColumn; import tech.tablesaw.api.StringColumn; import tech.tablesaw.api.Table; import tech.tablesaw.api.TimeColumn; import tech.tablesaw.columns.Column; import tech.tablesaw.columns.booleans.BooleanColumnType; import tech.tablesaw.columns.dates.DateColumnType; import tech.tablesaw.columns.datetimes.DateTimeColumnType; import tech.tablesaw.columns.instant.InstantColumnType; import tech.tablesaw.columns.numbers.DoubleColumnType; import tech.tablesaw.columns.numbers.FloatColumnType; import tech.tablesaw.columns.numbers.IntColumnType; import tech.tablesaw.columns.numbers.LongColumnType; import tech.tablesaw.columns.numbers.ShortColumnType; import tech.tablesaw.columns.strings.StringColumnType; import tech.tablesaw.columns.strings.TextColumnType; import tech.tablesaw.columns.times.TimeColumnType; import tech.tablesaw.index.ByteIndex; import tech.tablesaw.index.DoubleIndex; import tech.tablesaw.index.FloatIndex; import tech.tablesaw.index.Index; import tech.tablesaw.index.IntIndex; import tech.tablesaw.index.LongIndex; import tech.tablesaw.index.ShortIndex; import tech.tablesaw.index.StringIndex; import tech.tablesaw.selection.Selection; public class DataFrameJoiner { private enum JoinType { INNER, LEFT_OUTER, RIGHT_OUTER, FULL_OUTER } private static final String TABLE_ALIAS = "T"; private final Table table; private final String[] joinColumnNames; private final List<Integer> joinColumnIndexes; private final AtomicInteger joinTableId = new AtomicInteger(2); /** * Constructor. * @param table The table to join on. * @param joinColumnNames The join column names to join on. */ public DataFrameJoiner(Table table, String... joinColumnNames) { this.table = table; this.joinColumnNames = joinColumnNames; this.joinColumnIndexes = getJoinIndexes(table, joinColumnNames); } /** * Finds the index of the columns corresponding to the columnNames. * E.G. The column named "ID" is located at index 5 in table. * @param table the table that contains the columns. * @param columnNames the column names to find indexes of. * @return a list of column indexes within the table. */ private List<Integer> getJoinIndexes(Table table, String[] columnNames) { return Arrays.stream(columnNames).map(table::columnIndex).collect(Collectors.toList()); } /** * Joins to the given tables assuming that they have a column of the name we're joining on * * @param tables The tables to join with */ public Table inner(Table... tables) { return inner(false, tables); } /** * Joins to the given tables assuming that they have a column of the name we're joining on * * @param allowDuplicateColumnNames if {@code false} the join will fail if any columns other than the join column * have the same name if {@code true} the join will succeed and duplicate columns are renamed* * @param tables The tables to join with */ public Table inner(boolean allowDuplicateColumnNames, Table... tables) { Table joined = table; for (Table currT : tables) { joined = joinInternal(joined, currT, JoinType.INNER, allowDuplicateColumnNames, joinColumnNames); } return joined; } /** * Joins the joiner to the table2, using the given column for the second table and returns the resulting table * * @param table2 The table to join with * @param col2Name The column to join on. If col2Name refers to a double column, the join is performed after * rounding to integers. * @return The resulting table */ public Table inner(Table table2, String col2Name) { return inner(table2, false, col2Name); } /** * Joins the joiner to the table2, using the given columns for the second table and returns the resulting table * * @param table2 The table to join with * @param col2Names The columns to join on. If a name refers to a double column, the join is performed after * rounding to integers. * @return The resulting table */ public Table inner(Table table2, String[] col2Names) { return inner(table2, false, col2Names); } /** * Joins the joiner to the table2, using the given column for the second table and returns the resulting table * * @param table2 The table to join with * @param col2Name The column to join on. If col2Name refers to a double column, the join is performed after * rounding to integers. * @param allowDuplicateColumnNames if {@code false} the join will fail if any columns other than the join column * have the same name if {@code true} the join will succeed and duplicate columns are renamed* * @return The resulting table */ public Table inner(Table table2, String col2Name, boolean allowDuplicateColumnNames) { return inner(table2, allowDuplicateColumnNames, col2Name); } /** * Joins the joiner to the table2, using the given columns for the second table and returns the resulting table * * @param table2 The table to join with * @param allowDuplicateColumnNames if {@code false} the join will fail if any columns other than the join column * have the same name if {@code true} the join will succeed and duplicate columns are renamed* * @param col2Names The columns to join on. If a name refers to a double column, the join is performed after * rounding to integers. * @return The resulting table */ public Table inner(Table table2, boolean allowDuplicateColumnNames, String... col2Names) { Table joinedTable; joinedTable = joinInternal(table, table2, JoinType.INNER, allowDuplicateColumnNames, col2Names); return joinedTable; } /** * Joins the joiner to the table2, using the given columns for the second table and returns the resulting table * * @param table2 The table to join with * @param outer True if this join is actually an outer join, left or right or full, otherwise false. * @param allowDuplicateColumnNames if {@code false} the join will fail if any columns other than the join column * have the same name if {@code true} the join will succeed and duplicate columns are renamed* * @param col2Names The columns to join on. If a name refers to a double column, the join is performed after * rounding to integers. * @return The resulting table */ @Deprecated public Table inner(Table table2, boolean outer, boolean allowDuplicateColumnNames, String... col2Names) { JoinType joinType = JoinType.INNER; if (outer) { joinType = JoinType.LEFT_OUTER; } Table joinedTable; joinedTable = joinInternal(table, table2, joinType, allowDuplicateColumnNames, col2Names); return joinedTable; } /** * Joins two tables. * * @param table1 the table on the left side of the join. * @param table2 the table on the right side of the join. * @param joinType the type of join. * @param allowDuplicates if {@code false} the join will fail if any columns other than the join column have the * same name if {@code true} the join will succeed and duplicate columns are renamed * @param table2JoinColumnNames The names of the columns in table2 to join on. */ private Table joinInternal(Table table1, Table table2, JoinType joinType, boolean allowDuplicates, String... table2JoinColumnNames) { List<Integer> table2JoinColumnIndexes = getJoinIndexes(table2, table2JoinColumnNames); Table result = Table.create(table1.name()); // A set of column indexes in the result table that can be ignored. They are duplicate join keys. Set<Integer> resultIgnoreColIndexes = emptyTableFromColumns(result, table1, table2, joinType, allowDuplicates, table2JoinColumnIndexes); List<Index> table1Indexes = buildIndexesForJoinColumns(joinColumnIndexes, table1); List<Index> table2Indexes = buildIndexesForJoinColumns(table2JoinColumnIndexes, table2); Selection table1DoneRows = Selection.with(); Selection table2DoneRows = Selection.with(); for (Row row : table1) { int ri = row.getRowNumber(); if (table1DoneRows.contains(ri)) { // Already processed a selection of table1 that contained this row. continue; } Selection table1Rows = createMultiColSelection(table1, ri, table1Indexes, table1.rowCount()); Selection table2Rows = createMultiColSelection(table1, ri, table2Indexes, table2.rowCount()); if ((joinType == JoinType.LEFT_OUTER || joinType == JoinType.FULL_OUTER) && table2Rows.isEmpty()) { withMissingLeftJoin(result, table1, table1Rows, resultIgnoreColIndexes); } else { crossProduct(result, table1, table2, table1Rows, table2Rows, resultIgnoreColIndexes); } table1DoneRows = table1DoneRows.or(table1Rows); if (joinType == JoinType.FULL_OUTER || joinType == JoinType.RIGHT_OUTER) { // Update done rows in table2 for full Outer. table2DoneRows = table2DoneRows.or(table2Rows); } else if (table1DoneRows.size() == table1.rowCount()) { // Processed all the rows in table1 exit early. result.removeColumns(Ints.toArray(resultIgnoreColIndexes)); return result; } } // Add all rows from table2 that were not handled already. Selection table2Rows = table2DoneRows.flip(0, table2.rowCount()); withMissingRight(result, table1.columnCount(), table2, table2Rows, joinType, table2JoinColumnIndexes, resultIgnoreColIndexes); result.removeColumns(Ints.toArray(resultIgnoreColIndexes)); return result; } /** * Build a reverse index for every join column in the table. */ private List<Index> buildIndexesForJoinColumns(List<Integer> joinColumnIndexes, Table table) { return joinColumnIndexes.stream().map(c -> indexFor(table, c)).collect(Collectors.toList()); } /** * Create a reverse index for a given column. */ private Index indexFor(Table table, int colIndex) { ColumnType type = table.column(colIndex).type(); if (type instanceof DateColumnType) { return new IntIndex(table.dateColumn(colIndex)); } else if (type instanceof DateTimeColumnType) { return new LongIndex(table.dateTimeColumn(colIndex)); } else if (type instanceof InstantColumnType) { return new LongIndex(table.instantColumn(colIndex)); } else if (type instanceof TimeColumnType) { return new IntIndex(table.timeColumn(colIndex)); } else if (type instanceof StringColumnType || type instanceof TextColumnType) { return new StringIndex(table.stringColumn(colIndex)); } else if (type instanceof IntColumnType) { return new IntIndex(table.intColumn(colIndex)); } else if (type instanceof LongColumnType) { return new LongIndex(table.longColumn(colIndex)); } else if (type instanceof ShortColumnType) { return new ShortIndex(table.shortColumn(colIndex)); } else if (type instanceof BooleanColumnType) { return new ByteIndex(table.booleanColumn(colIndex)); } else if (type instanceof DoubleColumnType) { return new DoubleIndex(table.doubleColumn(colIndex)); } else if (type instanceof FloatColumnType) { return new FloatIndex(table.floatColumn(colIndex)); } throw new IllegalArgumentException( "Joining attempted on unsupported column type " + type); } /** * Given a reverse index find a selection of rows that have the same * value as the supplied column does in the given row index. */ private Selection selectionForColumn( Column<?> valueColumn, int rowIndex, Index rawIndex) { ColumnType type = valueColumn.type(); Selection selection = Selection.with(); if (type instanceof DateColumnType) { IntIndex index = (IntIndex) rawIndex; DateColumn typedValueColumn = (DateColumn) valueColumn; int value = typedValueColumn.getIntInternal(rowIndex); selection = index.get(value); } else if (type instanceof TimeColumnType) { IntIndex index = (IntIndex) rawIndex; TimeColumn typedValueColumn = (TimeColumn) valueColumn; int value = typedValueColumn.getIntInternal(rowIndex); selection = index.get(value); } else if (type instanceof DateTimeColumnType) { LongIndex index = (LongIndex) rawIndex; DateTimeColumn typedValueColumn = (DateTimeColumn) valueColumn; long value = typedValueColumn.getLongInternal(rowIndex); selection = index.get(value); } else if (type instanceof InstantColumnType) { LongIndex index = (LongIndex) rawIndex; InstantColumn typedValueColumn = (InstantColumn) valueColumn; long value = typedValueColumn.getLongInternal(rowIndex); selection = index.get(value); } else if (type instanceof StringColumnType || type instanceof TextColumnType) { StringIndex index = (StringIndex) rawIndex; StringColumn typedValueColumn = (StringColumn) valueColumn; String value = typedValueColumn.get(rowIndex); selection = index.get(value); } else if (type instanceof IntColumnType) { IntIndex index = (IntIndex) rawIndex; IntColumn typedValueColumn = (IntColumn) valueColumn; int value = typedValueColumn.getInt(rowIndex); selection = index.get(value); } else if (type instanceof LongColumnType) { LongIndex index = (LongIndex) rawIndex; LongColumn typedValueColumn = (LongColumn) valueColumn; long value = typedValueColumn.getLong(rowIndex); selection = index.get(value); } else if (type instanceof ShortColumnType) { ShortIndex index = (ShortIndex) rawIndex; ShortColumn typedValueColumn = (ShortColumn) valueColumn; short value = typedValueColumn.getShort(rowIndex); selection = index.get(value); } else if (type instanceof BooleanColumnType) { ByteIndex index = (ByteIndex) rawIndex; BooleanColumn typedValueColumn = (BooleanColumn) valueColumn; byte value = typedValueColumn.getByte(rowIndex); selection = index.get(value); } else if (type instanceof DoubleColumnType) { DoubleIndex index = (DoubleIndex) rawIndex; DoubleColumn typedValueColumn = (DoubleColumn) valueColumn; double value = typedValueColumn.getDouble(rowIndex); selection = index.get(value); } else if (type instanceof FloatColumnType) { FloatIndex index = (FloatIndex) rawIndex; FloatColumn typedValueColumn = (FloatColumn) valueColumn; float value = typedValueColumn.getFloat(rowIndex); selection = index.get(value); } else { throw new IllegalArgumentException( "Joining is supported on numeric, string, and date-like columns. Column " + valueColumn.name() + " is of type " + valueColumn.type()); } return selection; } /** * Create a big multicolumn selection for all join columns in the given table. */ private Selection createMultiColSelection(Table table1, int ri, List<Index> indexes, int selectionSize) { Selection multiColSelection = Selection.withRange(0, selectionSize); int i = 0; for (Integer joinColumnIndex : joinColumnIndexes) { Column<?> col = table1.column(joinColumnIndex); Selection oneColSelection = selectionForColumn(col, ri, indexes.get(i)); // and the selections. multiColSelection = multiColSelection.and(oneColSelection); i++; } return multiColSelection; } private String newName(String table2Alias, String columnName) { return table2Alias + "." + columnName; } /** * Full outer join to the given tables assuming that they have a column of the name we're joining on * * @param tables The tables to join with * @return The resulting table */ public Table fullOuter(Table... tables) { return fullOuter(false, tables); } /** * Full outer join to the given tables assuming that they have a column of the name we're joining on * * @param allowDuplicateColumnNames if {@code false} the join will fail if any columns other than the join column * have the same name if {@code true} the join will succeed and duplicate columns are renamed* * @param tables The tables to join with * @return The resulting table */ public Table fullOuter(boolean allowDuplicateColumnNames, Table... tables) { Table joined = table; for (Table currT : tables) { joined = joinInternal(joined, currT, JoinType.FULL_OUTER, allowDuplicateColumnNames, joinColumnNames); } return joined; } /** * Full outer join the joiner to the table2, using the given column for the second table and returns the resulting * table * * @param table2 The table to join with * @param col2Name The column to join on. If col2Name refers to a double column, the join is performed after * rounding to integers. * @return The resulting table */ public Table fullOuter(Table table2, String col2Name) { return joinInternal(table, table2, JoinType.FULL_OUTER, false, col2Name); } /** * Joins to the given tables assuming that they have a column of the name we're joining on * * @param tables The tables to join with * @return The resulting table */ public Table leftOuter(Table... tables) { return leftOuter(false, tables); } /** * Joins to the given tables assuming that they have a column of the name we're joining on * * @param allowDuplicateColumnNames if {@code false} the join will fail if any columns other than the join column * have the same name if {@code true} the join will succeed and duplicate columns are renamed* * @param tables The tables to join with * @return The resulting table */ public Table leftOuter(boolean allowDuplicateColumnNames, Table... tables) { Table joined = table; for (Table table2 : tables) { joined = leftOuter(table2, allowDuplicateColumnNames, joinColumnNames); } return joined; } /** * Joins the joiner to the table2, using the given columns for the second table and returns the resulting table * * @param table2 The table to join with * @param col2Names The columns to join on. If a name refers to a double column, the join is performed after * rounding to integers. * @return The resulting table */ public Table leftOuter(Table table2, String[] col2Names) { return leftOuter(table2, false, col2Names); } /** * Joins the joiner to the table2, using the given column for the second table and returns the resulting table * * @param table2 The table to join with * @param col2Name The column to join on. If col2Name refers to a double column, the join is performed after * rounding to integers. * @return The resulting table */ public Table leftOuter(Table table2, String col2Name) { return leftOuter(table2, false, col2Name); } /** * Joins the joiner to the table2, using the given columns for the second table and returns the resulting table * * @param table2 The table to join with * @param allowDuplicateColumnNames if {@code false} the join will fail if any columns other than the join column * have the same name if {@code true} the join will succeed and duplicate columns are renamed * @param col2Names The columns to join on. If a name refers to a double column, the join is performed after * rounding to integers. * @return The resulting table */ public Table leftOuter(Table table2, boolean allowDuplicateColumnNames, String... col2Names) { return joinInternal(table, table2, JoinType.LEFT_OUTER, allowDuplicateColumnNames, col2Names); } /** * Joins to the given tables assuming that they have a column of the name we're joining on * * @param tables The tables to join with * @return The resulting table */ public Table rightOuter(Table... tables) { return rightOuter(false, tables); } /** * Joins to the given tables assuming that they have a column of the name we're joining on * * @param allowDuplicateColumnNames if {@code false} the join will fail if any columns other than the join column * have the same name if {@code true} the join will succeed and duplicate columns are renamed * @param tables The tables to join with * @return The resulting table */ public Table rightOuter(boolean allowDuplicateColumnNames, Table... tables) { Table joined = table; for (Table table2 : tables) { joined = rightOuter(table2, allowDuplicateColumnNames, joinColumnNames); } return joined; } /** * Joins the joiner to the table2, using the given column for the second table and returns the resulting table * * @param table2 The table to join with * @param col2Name The column to join on. If col2Name refers to a double column, the join is performed after * rounding to integers. * @return The resulting table */ public Table rightOuter(Table table2, String col2Name) { return rightOuter(table2, false, col2Name); } /** * Joins the joiner to the table2, using the given columns for the second table and returns the resulting table * * @param table2 The table to join with * @param col2Names The columns to join on. If a name refers to a double column, the join is performed after * rounding to integers. * @return The resulting table */ public Table rightOuter(Table table2, String[] col2Names) { return rightOuter(table2, false, col2Names); } /** * Joins the joiner to the table2, using the given columns for the second table and returns the resulting table * * @param table2 The table to join with * @param allowDuplicateColumnNames if {@code false} the join will fail if any columns other than the join column * have the same name if {@code true} the join will succeed and duplicate columns are renamed * @param col2Names The columns to join on. If a name refers to a double column, the join is performed after * rounding to integers. * @return The resulting table */ public Table rightOuter(Table table2, boolean allowDuplicateColumnNames, String... col2Names) { return joinInternal(table, table2, JoinType.RIGHT_OUTER, allowDuplicateColumnNames, col2Names); } /** * Adds empty columns to the destination table with the same type as columns in table1 and table2. * * For inner, left and full outer join types the join columns in table2 are not needed and will be marked as * placeholders. The indexes of those columns will be returned. The downstream logic is easier if we wait to remove * the redundant columns until the last step. * * @param destination the table to fill up with columns. Will be mutated in place. * @param table1 the table on left side of the join. * @param table2 the table on the right side of the join. * @param joinType the type of join. * @param allowDuplicates whether to allow duplicates. If yes rename columns in table2 that have the same name as * columns in table1 with the exception of join columns in table2 when performing a right join. * @param table2JoinColumnIndexes the index locations of the table2 join columns. * @return A */ private Set<Integer> emptyTableFromColumns(Table destination, Table table1, Table table2, JoinType joinType, boolean allowDuplicates, List<Integer> table2JoinColumnIndexes) { Column<?>[] cols = Streams.concat(table1.columns().stream(), table2.columns().stream()) .map(Column::emptyCopy).toArray(Column[]::new); // For inner join, left join and full outer join mark the join columns in table2 as placeholders. // For right join mark the join columns in table1 as placeholders. // Keep track of which join columns are placeholders so they can be ignored. Set<Integer> ignoreColumns = new HashSet<>(); for (int c = 0; c < cols.length; c++) { if (joinType == JoinType.RIGHT_OUTER) { if (c < table1.columnCount() && joinColumnIndexes.contains(c)) { cols[c].setName("Placeholder_" + ignoreColumns.size()); ignoreColumns.add(c); } } else { int table2Index = c - table1.columnCount(); if (c >= table1.columnCount() && table2JoinColumnIndexes.contains(table2Index)) { cols[c].setName("Placeholder_" + ignoreColumns.size()); ignoreColumns.add(c); } } } // Rename duplicate columns in second table if (allowDuplicates) { Set<String> table1ColNames = Arrays.stream(cols).map(Column::name) .map(String::toLowerCase).limit(table1.columnCount()).collect(Collectors.toSet()); String table2Alias = TABLE_ALIAS + joinTableId.getAndIncrement(); for (int c = table1.columnCount(); c < cols.length; c++) { String columnName = cols[c].name(); if (table1ColNames.contains(columnName.toLowerCase())) { cols[c].setName(newName(table2Alias, columnName)); } } } destination.addColumns(cols); return ignoreColumns; } /** * Creates cross product for the selection of two tables. * * @param destination the destination table. * @param table1 the table on left of join. * @param table2 the table on right of join. * @param table1Rows the selection of rows in table1. * @param table2Rows the selection of rows in table2. * @param ignoreColumns a set of column indexes in the result to ignore. They are redundant join columns. */ @SuppressWarnings({"rawtypes", "unchecked"}) private void crossProduct(Table destination, Table table1, Table table2, Selection table1Rows, Selection table2Rows, Set<Integer> ignoreColumns) { for (int c = 0; c < table1.columnCount() + table2.columnCount(); c++) { if (ignoreColumns.contains(c)) { continue; } int table2Index = c - table1.columnCount(); for (int r1 : table1Rows) { for (int r2 : table2Rows) { if (c < table1.columnCount()) { Column t1Col = table1.column(c); destination.column(c).append(t1Col, r1); } else { Column t2Col = table2.column(table2Index); destination.column(c).append(t2Col, r2); } } } } } /** * Adds rows to destination for each row in table1 with the columns from table2 added as missing values. */ @SuppressWarnings({"rawtypes", "unchecked"}) private void withMissingLeftJoin(Table destination, Table table1, Selection table1Rows, Set<Integer> ignoreColumns) { for (int c = 0; c < destination.columnCount(); c++) { if (ignoreColumns.contains(c)) { continue; } if (c < table1.columnCount()) { Column t1Col = table1.column(c); for (int index : table1Rows) { destination.column(c).append(t1Col, index); } } else { for (int r1 = 0; r1 < table1Rows.size(); r1++) { destination.column(c).appendMissing(); } } } } /** * Adds rows to destination for each row in table2 with the columns from table1 added as missing values. */ @SuppressWarnings({"rawtypes", "unchecked"}) private void withMissingRight(Table destination, int table1ColCount, Table table2, Selection table2Rows, JoinType joinType, List<Integer> col2Indexes, Set<Integer> ignoreColumns) { // Add index data from table2 into join column positions in table one. if (joinType == JoinType.FULL_OUTER) { for (int i = 0; i < col2Indexes.size(); i++) { Column t2Col = table2.column(col2Indexes.get(i)); for (int index : table2Rows) { destination.column(joinColumnIndexes.get(i)).append(t2Col, index); } } } for (int c = 0; c < destination.columnCount(); c++) { if (ignoreColumns.contains(c) || joinColumnIndexes.contains(c)) { continue; } if (c < table1ColCount) { for (int r1 = 0; r1 < table2Rows.size(); r1++) { destination.column(c).appendMissing(); } } else { Column t2Col = table2.column(c - table1ColCount); for (int index : table2Rows) { destination.column(c).append(t2Col, index); } } } } }
core/src/main/java/tech/tablesaw/joining/DataFrameJoiner.java
package tech.tablesaw.joining; import com.google.common.collect.Streams; import com.google.common.primitives.Ints; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; import tech.tablesaw.api.BooleanColumn; import tech.tablesaw.api.ColumnType; import tech.tablesaw.api.DateColumn; import tech.tablesaw.api.DateTimeColumn; import tech.tablesaw.api.DoubleColumn; import tech.tablesaw.api.FloatColumn; import tech.tablesaw.api.InstantColumn; import tech.tablesaw.api.IntColumn; import tech.tablesaw.api.LongColumn; import tech.tablesaw.api.Row; import tech.tablesaw.api.ShortColumn; import tech.tablesaw.api.StringColumn; import tech.tablesaw.api.Table; import tech.tablesaw.api.TimeColumn; import tech.tablesaw.columns.Column; import tech.tablesaw.columns.booleans.BooleanColumnType; import tech.tablesaw.columns.dates.DateColumnType; import tech.tablesaw.columns.datetimes.DateTimeColumnType; import tech.tablesaw.columns.instant.InstantColumnType; import tech.tablesaw.columns.numbers.DoubleColumnType; import tech.tablesaw.columns.numbers.FloatColumnType; import tech.tablesaw.columns.numbers.IntColumnType; import tech.tablesaw.columns.numbers.LongColumnType; import tech.tablesaw.columns.numbers.ShortColumnType; import tech.tablesaw.columns.strings.StringColumnType; import tech.tablesaw.columns.strings.TextColumnType; import tech.tablesaw.columns.times.TimeColumnType; import tech.tablesaw.index.ByteIndex; import tech.tablesaw.index.DoubleIndex; import tech.tablesaw.index.FloatIndex; import tech.tablesaw.index.Index; import tech.tablesaw.index.IntIndex; import tech.tablesaw.index.LongIndex; import tech.tablesaw.index.ShortIndex; import tech.tablesaw.index.StringIndex; import tech.tablesaw.selection.Selection; public class DataFrameJoiner { private enum JoinType { INNER, LEFT_OUTER, RIGHT_OUTER, FULL_OUTER } private static final String TABLE_ALIAS = "T"; private final Table table; private final String[] joinColumnNames; private final List<Integer> joinColumnIndexes; private final AtomicInteger joinTableId = new AtomicInteger(2); /** * Constructor. * @param table The table to join on. * @param joinColumnNames The join column names to join on. */ public DataFrameJoiner(Table table, String... joinColumnNames) { this.table = table; this.joinColumnNames = joinColumnNames; this.joinColumnIndexes = getJoinIndexes(table, joinColumnNames); } /** * Finds the index of the columns corresponding to the columnNames. * E.G. The column named "ID" is located at index 5 in table. * @param table the table that contains the columns. * @param columnNames the column names to find indexes of. * @return a list of column indexes within the table. */ private List<Integer> getJoinIndexes(Table table, String[] columnNames) { return Arrays.stream(columnNames).map(table::columnIndex).collect(Collectors.toList()); } /** * Joins to the given tables assuming that they have a column of the name we're joining on * * @param tables The tables to join with */ public Table inner(Table... tables) { return inner(false, tables); } /** * Joins to the given tables assuming that they have a column of the name we're joining on * * @param allowDuplicateColumnNames if {@code false} the join will fail if any columns other than the join column * have the same name if {@code true} the join will succeed and duplicate columns are renamed* * @param tables The tables to join with */ public Table inner(boolean allowDuplicateColumnNames, Table... tables) { Table joined = table; for (Table currT : tables) { joined = joinInternal(joined, currT, JoinType.INNER, allowDuplicateColumnNames, joinColumnNames); } return joined; } /** * Joins the joiner to the table2, using the given column for the second table and returns the resulting table * * @param table2 The table to join with * @param col2Name The column to join on. If col2Name refers to a double column, the join is performed after * rounding to integers. * @return The resulting table */ public Table inner(Table table2, String col2Name) { return inner(table2, false, col2Name); } /** * Joins the joiner to the table2, using the given columns for the second table and returns the resulting table * * @param table2 The table to join with * @param col2Names The columns to join on. If a name refers to a double column, the join is performed after * rounding to integers. * @return The resulting table */ public Table inner(Table table2, String[] col2Names) { return inner(table2, false, col2Names); } /** * Joins the joiner to the table2, using the given column for the second table and returns the resulting table * * @param table2 The table to join with * @param col2Name The column to join on. If col2Name refers to a double column, the join is performed after * rounding to integers. * @param allowDuplicateColumnNames if {@code false} the join will fail if any columns other than the join column * have the same name if {@code true} the join will succeed and duplicate columns are renamed* * @return The resulting table */ public Table inner(Table table2, String col2Name, boolean allowDuplicateColumnNames) { return inner(table2, allowDuplicateColumnNames, col2Name); } /** * Joins the joiner to the table2, using the given columns for the second table and returns the resulting table * * @param table2 The table to join with * @param allowDuplicateColumnNames if {@code false} the join will fail if any columns other than the join column * have the same name if {@code true} the join will succeed and duplicate columns are renamed* * @param col2Names The columns to join on. If a name refers to a double column, the join is performed after * rounding to integers. * @return The resulting table */ public Table inner(Table table2, boolean allowDuplicateColumnNames, String... col2Names) { Table joinedTable; joinedTable = joinInternal(table, table2, JoinType.INNER, allowDuplicateColumnNames, col2Names); return joinedTable; } /** * Joins the joiner to the table2, using the given columns for the second table and returns the resulting table * * @param table2 The table to join with * @param outer True if this join is actually an outer join, left or right or full, otherwise false. * @param allowDuplicateColumnNames if {@code false} the join will fail if any columns other than the join column * have the same name if {@code true} the join will succeed and duplicate columns are renamed* * @param col2Names The columns to join on. If a name refers to a double column, the join is performed after * rounding to integers. * @return The resulting table */ @Deprecated public Table inner(Table table2, boolean outer, boolean allowDuplicateColumnNames, String... col2Names) { JoinType joinType = JoinType.INNER; if (outer) { joinType = JoinType.LEFT_OUTER; } Table joinedTable; joinedTable = joinInternal(table, table2, joinType, allowDuplicateColumnNames, col2Names); return joinedTable; } /** * Joins two tables. * * @param table1 the table on the left side of the join. * @param table2 the table on the right side of the join. * @param joinType the type of join. * @param allowDuplicates if {@code false} the join will fail if any columns other than the join column have the * same name if {@code true} the join will succeed and duplicate columns are renamed * @param table2JoinColumnNames The names of the columns in table2 to join on. */ private Table joinInternal(Table table1, Table table2, JoinType joinType, boolean allowDuplicates, String... table2JoinColumnNames) { List<Integer> table2JoinColumnIndexes = getJoinIndexes(table2, table2JoinColumnNames); Table result = Table.create(table1.name()); // A set of column indexes in the result table that can be ignored. They are duplicate join keys. Set<Integer> resultIgnoreColIndexes = emptyTableFromColumns(result, table1, table2, joinType, allowDuplicates, table2JoinColumnIndexes); List<Index> table1Indexes = buildIndexesForJoinColumns(joinColumnIndexes, table1); List<Index> table2Indexes = buildIndexesForJoinColumns(table2JoinColumnIndexes, table2); Selection table1DoneRows = Selection.with(); Selection table2DoneRows = Selection.with(); for (Row row : table1) { int ri = row.getRowNumber(); if (table1DoneRows.contains(ri)) { // Already processed a selection of table1 that contained this row. continue; } Selection table1Rows = createMultiColSelection(table1, ri, table1Indexes, table1.rowCount()); Selection table2Rows = createMultiColSelection(table1, ri, table2Indexes, table2.rowCount()); if ((joinType == JoinType.LEFT_OUTER || joinType == JoinType.FULL_OUTER) && table2Rows.isEmpty()) { withMissingLeftJoin(result, table1, table1Rows, resultIgnoreColIndexes); } else { crossProduct(result, table1, table2, table1Rows, table2Rows, resultIgnoreColIndexes); } table1DoneRows = table1DoneRows.or(table1Rows); if (joinType == JoinType.FULL_OUTER || joinType == JoinType.RIGHT_OUTER) { // Update done rows in table2 for full Outer. table2DoneRows = table2DoneRows.or(table2Rows); } else if (table1DoneRows.size() == table1.rowCount()) { // Processed all the rows in table1 exit early. result.removeColumns(Ints.toArray(resultIgnoreColIndexes)); return result; } } // Add all rows from table2 that were not handled already. Selection table2Rows = table2DoneRows.flip(0, table2.rowCount()); withMissingRight(result, table1.columnCount(), table2, table2Rows, joinType, table2JoinColumnIndexes, resultIgnoreColIndexes); result.removeColumns(Ints.toArray(resultIgnoreColIndexes)); return result; } /** * Build a reverse index for every join column in the table. */ private List<Index> buildIndexesForJoinColumns(List<Integer> joinColumnIndexes, Table table) { return joinColumnIndexes.stream().map(c -> indexFor(table, c)).collect(Collectors.toList()); } /** Create a reverse index for a given column. */ private Index indexFor(Table table, int colIndex) { ColumnType type = table.column(colIndex).type(); if (type instanceof DateColumnType) { return new IntIndex(table.dateColumn(colIndex)); } else if (type instanceof DateTimeColumnType) { return new LongIndex(table.dateTimeColumn(colIndex)); } else if (type instanceof InstantColumnType) { return new LongIndex(table.instantColumn(colIndex)); } else if (type instanceof TimeColumnType) { return new IntIndex(table.timeColumn(colIndex)); } else if (type instanceof StringColumnType || type instanceof TextColumnType) { return new StringIndex(table.stringColumn(colIndex)); } else if (type instanceof IntColumnType) { return new IntIndex(table.intColumn(colIndex)); } else if (type instanceof LongColumnType) { return new LongIndex(table.longColumn(colIndex)); } else if (type instanceof ShortColumnType) { return new ShortIndex(table.shortColumn(colIndex)); } else if (type instanceof BooleanColumnType) { return new ByteIndex(table.booleanColumn(colIndex)); } else if (type instanceof DoubleColumnType) { return new DoubleIndex(table.doubleColumn(colIndex)); } else if (type instanceof FloatColumnType) { return new FloatIndex(table.floatColumn(colIndex)); } throw new IllegalArgumentException( "Joining attempted on unsupported column type " + type); } /** Given a reverse index find a selection of rows that have the same value as the supplied column does in the given row index. */ private Selection selectionForColumn( Column<?> valueColumn, int rowIndex, Index rawIndex) { ColumnType type = valueColumn.type(); Selection selection = Selection.with(); if (type instanceof DateColumnType) { IntIndex index = (IntIndex) rawIndex; DateColumn typedValueColumn = (DateColumn) valueColumn; int value = typedValueColumn.getIntInternal(rowIndex); selection = index.get(value); } else if (type instanceof TimeColumnType) { IntIndex index = (IntIndex) rawIndex; TimeColumn typedValueColumn = (TimeColumn) valueColumn; int value = typedValueColumn.getIntInternal(rowIndex); selection = index.get(value); } else if (type instanceof DateTimeColumnType) { LongIndex index = (LongIndex) rawIndex; DateTimeColumn typedValueColumn = (DateTimeColumn) valueColumn; long value = typedValueColumn.getLongInternal(rowIndex); selection = index.get(value); } else if (type instanceof InstantColumnType) { LongIndex index = (LongIndex) rawIndex; InstantColumn typedValueColumn = (InstantColumn) valueColumn; long value = typedValueColumn.getLongInternal(rowIndex); selection = index.get(value); } else if (type instanceof StringColumnType || type instanceof TextColumnType) { StringIndex index = (StringIndex) rawIndex; StringColumn typedValueColumn = (StringColumn) valueColumn; String value = typedValueColumn.get(rowIndex); selection = index.get(value); } else if (type instanceof IntColumnType) { IntIndex index = (IntIndex) rawIndex; IntColumn typedValueColumn = (IntColumn) valueColumn; int value = typedValueColumn.getInt(rowIndex); selection = index.get(value); } else if (type instanceof LongColumnType) { LongIndex index = (LongIndex) rawIndex; LongColumn typedValueColumn = (LongColumn) valueColumn; long value = typedValueColumn.getLong(rowIndex); selection = index.get(value); } else if (type instanceof ShortColumnType) { ShortIndex index = (ShortIndex) rawIndex; ShortColumn typedValueColumn = (ShortColumn) valueColumn; short value = typedValueColumn.getShort(rowIndex); selection = index.get(value); } else if (type instanceof BooleanColumnType) { ByteIndex index = (ByteIndex) rawIndex; BooleanColumn typedValueColumn = (BooleanColumn) valueColumn; byte value = typedValueColumn.getByte(rowIndex); selection = index.get(value); } else if (type instanceof DoubleColumnType) { DoubleIndex index = (DoubleIndex) rawIndex; DoubleColumn typedValueColumn = (DoubleColumn) valueColumn; double value = typedValueColumn.getDouble(rowIndex); selection = index.get(value); } else if (type instanceof FloatColumnType) { FloatIndex index = (FloatIndex) rawIndex; FloatColumn typedValueColumn = (FloatColumn) valueColumn; float value = typedValueColumn.getFloat(rowIndex); selection = index.get(value); } else { throw new IllegalArgumentException( "Joining is supported on numeric, string, and date-like columns. Column " + valueColumn.name() + " is of type " + valueColumn.type()); } return selection; } /** Create a big multicolumn selection for all join columns in the given table. */ private Selection createMultiColSelection(Table table1, int ri, List<Index> indexes, int selectionSize) { Selection multiColSelection = Selection.withRange(0, selectionSize); int i = 0; for (Integer joinColumnIndex : joinColumnIndexes) { Column<?> col = table1.column(joinColumnIndex); Selection oneColSelection = selectionForColumn(col, ri, indexes.get(i)); // and the selections. multiColSelection = multiColSelection.and(oneColSelection); i++; } return multiColSelection; } private String newName(String table2Alias, String columnName) { return table2Alias + "." + columnName; } /** * Full outer join to the given tables assuming that they have a column of the name we're joining on * * @param tables The tables to join with * @return The resulting table */ public Table fullOuter(Table... tables) { return fullOuter(false, tables); } /** * Full outer join to the given tables assuming that they have a column of the name we're joining on * * @param allowDuplicateColumnNames if {@code false} the join will fail if any columns other than the join column * have the same name if {@code true} the join will succeed and duplicate columns are renamed* * @param tables The tables to join with * @return The resulting table */ public Table fullOuter(boolean allowDuplicateColumnNames, Table... tables) { Table joined = table; for (Table currT : tables) { joined = joinInternal(joined, currT, JoinType.FULL_OUTER, allowDuplicateColumnNames, joinColumnNames); } return joined; } /** * Full outer join the joiner to the table2, using the given column for the second table and returns the resulting * table * * @param table2 The table to join with * @param col2Name The column to join on. If col2Name refers to a double column, the join is performed after * rounding to integers. * @return The resulting table */ public Table fullOuter(Table table2, String col2Name) { return joinInternal(table, table2, JoinType.FULL_OUTER, false, col2Name); } /** * Joins to the given tables assuming that they have a column of the name we're joining on * * @param tables The tables to join with * @return The resulting table */ public Table leftOuter(Table... tables) { return leftOuter(false, tables); } /** * Joins to the given tables assuming that they have a column of the name we're joining on * * @param allowDuplicateColumnNames if {@code false} the join will fail if any columns other than the join column * have the same name if {@code true} the join will succeed and duplicate columns are renamed* * @param tables The tables to join with * @return The resulting table */ public Table leftOuter(boolean allowDuplicateColumnNames, Table... tables) { Table joined = table; for (Table table2 : tables) { joined = leftOuter(table2, allowDuplicateColumnNames, joinColumnNames); } return joined; } /** * Joins the joiner to the table2, using the given columns for the second table and returns the resulting table * * @param table2 The table to join with * @param col2Names The columns to join on. If a name refers to a double column, the join is performed after * rounding to integers. * @return The resulting table */ public Table leftOuter(Table table2, String[] col2Names) { return leftOuter(table2, false, col2Names); } /** * Joins the joiner to the table2, using the given column for the second table and returns the resulting table * * @param table2 The table to join with * @param col2Name The column to join on. If col2Name refers to a double column, the join is performed after * rounding to integers. * @return The resulting table */ public Table leftOuter(Table table2, String col2Name) { return leftOuter(table2, false, col2Name); } /** * Joins the joiner to the table2, using the given columns for the second table and returns the resulting table * * @param table2 The table to join with * @param allowDuplicateColumnNames if {@code false} the join will fail if any columns other than the join column * have the same name if {@code true} the join will succeed and duplicate columns are renamed * @param col2Names The columns to join on. If a name refers to a double column, the join is performed after * rounding to integers. * @return The resulting table */ public Table leftOuter(Table table2, boolean allowDuplicateColumnNames, String... col2Names) { return joinInternal(table, table2, JoinType.LEFT_OUTER, allowDuplicateColumnNames, col2Names); } /** * Joins to the given tables assuming that they have a column of the name we're joining on * * @param tables The tables to join with * @return The resulting table */ public Table rightOuter(Table... tables) { return rightOuter(false, tables); } /** * Joins to the given tables assuming that they have a column of the name we're joining on * * @param allowDuplicateColumnNames if {@code false} the join will fail if any columns other than the join column * have the same name if {@code true} the join will succeed and duplicate columns are renamed * @param tables The tables to join with * @return The resulting table */ public Table rightOuter(boolean allowDuplicateColumnNames, Table... tables) { Table joined = table; for (Table table2 : tables) { joined = rightOuter(table2, allowDuplicateColumnNames, joinColumnNames); } return joined; } /** * Joins the joiner to the table2, using the given column for the second table and returns the resulting table * * @param table2 The table to join with * @param col2Name The column to join on. If col2Name refers to a double column, the join is performed after * rounding to integers. * @return The resulting table */ public Table rightOuter(Table table2, String col2Name) { return rightOuter(table2, false, col2Name); } /** * Joins the joiner to the table2, using the given columns for the second table and returns the resulting table * * @param table2 The table to join with * @param col2Names The columns to join on. If a name refers to a double column, the join is performed after * rounding to integers. * @return The resulting table */ public Table rightOuter(Table table2, String[] col2Names) { return rightOuter(table2, false, col2Names); } /** * Joins the joiner to the table2, using the given columns for the second table and returns the resulting table * * @param table2 The table to join with * @param allowDuplicateColumnNames if {@code false} the join will fail if any columns other than the join column * have the same name if {@code true} the join will succeed and duplicate columns are renamed * @param col2Names The columns to join on. If a name refers to a double column, the join is performed after * rounding to integers. * @return The resulting table */ public Table rightOuter(Table table2, boolean allowDuplicateColumnNames, String... col2Names) { return joinInternal(table, table2, JoinType.RIGHT_OUTER, allowDuplicateColumnNames, col2Names); } /** * Adds empty columns to the destination table with the same type as columns in table1 and table2. * * For inner, left and full outer join types the join columns in table2 are not needed and will be marked as * placeholders. The indexes of those columns will be returned. The downstream logic is easier if we wait to remove * the redundant columns until the last step. * * @param destination the table to fill up with columns. Will be mutated in place. * @param table1 the table on left side of the join. * @param table2 the table on the right side of the join. * @param joinType the type of join. * @param allowDuplicates whether to allow duplicates. If yes rename columns in table2 that have the same name as * columns in table1 with the exception of join columns in table2 when performing a right join. * @param table2JoinColumnIndexes the index locations of the table2 join columns. * @return A */ private Set<Integer> emptyTableFromColumns(Table destination, Table table1, Table table2, JoinType joinType, boolean allowDuplicates, List<Integer> table2JoinColumnIndexes) { Column<?>[] cols = Streams.concat(table1.columns().stream(), table2.columns().stream()) .map(Column::emptyCopy).toArray(Column[]::new); // For inner join, left join and full outer join mark the join columns in table2 as placeholders. // For right join mark the join columns in table1 as placeholders. // Keep track of which join columns are placeholders so they can be ignored. Set<Integer> ignoreColumns = new HashSet<>(); for (int c = 0; c < cols.length; c++) { if (joinType == JoinType.RIGHT_OUTER) { if (c < table1.columnCount() && joinColumnIndexes.contains(c)) { cols[c].setName("Placeholder_" + ignoreColumns.size()); ignoreColumns.add(c); } } else { int table2Index = c - table1.columnCount(); if (c >= table1.columnCount() && table2JoinColumnIndexes.contains(table2Index)) { cols[c].setName("Placeholder_" + ignoreColumns.size()); ignoreColumns.add(c); } } } // Rename duplicate columns in second table if (allowDuplicates) { Set<String> table1ColNames = Arrays.stream(cols).map(Column::name) .map(String::toLowerCase).limit(table1.columnCount()).collect(Collectors.toSet()); String table2Alias = TABLE_ALIAS + joinTableId.getAndIncrement(); for (int c = table1.columnCount(); c < cols.length; c++) { String columnName = cols[c].name(); if (table1ColNames.contains(columnName.toLowerCase())) { cols[c].setName(newName(table2Alias, columnName)); } } } destination.addColumns(cols); return ignoreColumns; } /** * Creates cross product for the selection of two tables. * * @param destination the destination table. * @param table1 the table on left of join. * @param table2 the table on right of join. * @param table1Rows the selection of rows in table1. * @param table2Rows the selection of rows in table2. * @param ignoreColumns a set of column indexes in the result to ignore. They are redundant join columns. */ @SuppressWarnings({"rawtypes", "unchecked"}) private void crossProduct(Table destination, Table table1, Table table2, Selection table1Rows, Selection table2Rows, Set<Integer> ignoreColumns) { for (int c = 0; c < table1.columnCount() + table2.columnCount(); c++) { if (ignoreColumns.contains(c)) { continue; } int table2Index = c - table1.columnCount(); for (int r1 : table1Rows) { for (int r2 : table2Rows) { if (c < table1.columnCount()) { Column t1Col = table1.column(c); destination.column(c).append(t1Col, r1); } else { Column t2Col = table2.column(table2Index); destination.column(c).append(t2Col, r2); } } } } } /** * Adds rows to destination for each row in table1 with the columns from table2 added as missing values. */ @SuppressWarnings({"rawtypes", "unchecked"}) private void withMissingLeftJoin(Table destination, Table table1, Selection table1Rows, Set<Integer> ignoreColumns) { for (int c = 0; c < destination.columnCount(); c++) { if (ignoreColumns.contains(c)) { continue; } if (c < table1.columnCount()) { Column t1Col = table1.column(c); for (int index : table1Rows) { destination.column(c).append(t1Col, index); } } else { for (int r1 = 0; r1 < table1Rows.size(); r1++) { destination.column(c).appendMissing(); } } } } /** * Adds rows to destination for each row in table2 with the columns from table1 added as missing values. */ @SuppressWarnings({"rawtypes", "unchecked"}) private void withMissingRight(Table destination, int table1ColCount, Table table2, Selection table2Rows, JoinType joinType, List<Integer> col2Indexes, Set<Integer> ignoreColumns) { // Add index data from table2 into join column positions in table one. if (joinType == JoinType.FULL_OUTER) { for (int i = 0; i < col2Indexes.size(); i++) { Column t2Col = table2.column(col2Indexes.get(i)); for (int index : table2Rows) { destination.column(joinColumnIndexes.get(i)).append(t2Col, index); } } } for (int c = 0; c < destination.columnCount(); c++) { if (ignoreColumns.contains(c) || joinColumnIndexes.contains(c)) { continue; } if (c < table1ColCount) { for (int r1 = 0; r1 < table2Rows.size(); r1++) { destination.column(c).appendMissing(); } } else { Column t2Col = table2.column(c - table1ColCount); for (int index : table2Rows) { destination.column(c).append(t2Col, index); } } } } }
Fix comment formatting
core/src/main/java/tech/tablesaw/joining/DataFrameJoiner.java
Fix comment formatting
<ide><path>ore/src/main/java/tech/tablesaw/joining/DataFrameJoiner.java <ide> } <ide> <ide> /** <del> Create a reverse index for a given column. <add> * Create a reverse index for a given column. <ide> */ <ide> private Index indexFor(Table table, int colIndex) { <ide> ColumnType type = table.column(colIndex).type(); <ide> } <ide> <ide> /** <del> Given a reverse index find a selection of rows that have the same <del> value as the supplied column does in the given row index. <add> * Given a reverse index find a selection of rows that have the same <add> * value as the supplied column does in the given row index. <ide> */ <ide> private Selection selectionForColumn( <ide> Column<?> valueColumn, <ide> } <ide> <ide> /** <del> Create a big multicolumn selection for all join columns in the given table. <add> * Create a big multicolumn selection for all join columns in the given table. <ide> */ <ide> private Selection createMultiColSelection(Table table1, int ri, List<Index> indexes, int selectionSize) { <ide> Selection multiColSelection = Selection.withRange(0, selectionSize);
Java
agpl-3.0
ffbcb834a6df0f5fd3acd59261126f19d4779e70
0
echinopsii/net.echinopsii.ariane.community.core.directory,echinopsii/net.echinopsii.ariane.community.core.directory,echinopsii/net.echinopsii.ariane.community.core.directory
/** * Directory wat * Application REST endpoint * Copyright (C) 2013 Mathilde Ffrench * * 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 net.echinopsii.ariane.community.core.directory.wat.rest.organisational; import net.echinopsii.ariane.community.core.directory.base.model.organisational.Company; import net.echinopsii.ariane.community.core.directory.base.model.organisational.Team; import net.echinopsii.ariane.community.core.directory.base.model.technical.system.OSInstance; import net.echinopsii.ariane.community.core.directory.base.json.ToolBox; import net.echinopsii.ariane.community.core.directory.base.json.ds.organisational.ApplicationJSON; import net.echinopsii.ariane.community.core.directory.wat.plugin.DirectoryJPAProviderConsumer; import net.echinopsii.ariane.community.core.directory.base.model.organisational.Application; import net.echinopsii.ariane.community.core.directory.wat.rest.CommonRestResponse; import net.echinopsii.ariane.community.core.directory.wat.rest.technical.system.OSInstanceEndpoint; import org.apache.shiro.SecurityUtils; import org.apache.shiro.subject.Subject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.persistence.EntityManager; import javax.persistence.NoResultException; import javax.persistence.TypedQuery; import javax.ws.rs.*; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.HashSet; import static net.echinopsii.ariane.community.core.directory.base.json.ds.organisational.ApplicationJSON.JSONFriendlyApplication; /** * */ @Path("directories/common/organisation/applications") public class ApplicationEndpoint { private static final Logger log = LoggerFactory.getLogger(ApplicationEndpoint.class); private EntityManager em; public static Response applicationToJSON(Application application) { Response ret = null; String result; ByteArrayOutputStream outStream = new ByteArrayOutputStream(); try { ApplicationJSON.oneApplication2JSON(application, outStream); result = ToolBox.getOuputStreamContent(outStream, "UTF-8"); ret = Response.status(Status.OK).entity(result).build(); } catch (Exception e) { log.error(e.getMessage()); e.printStackTrace(); result = e.getMessage(); ret = Response.status(Status.INTERNAL_SERVER_ERROR).entity(result).build(); } return ret; } public static Application findApplicationById(EntityManager em, long id) { TypedQuery<Application> findByIdQuery = em.createQuery("SELECT DISTINCT a FROM Application a LEFT JOIN FETCH a.osInstances LEFT JOIN FETCH a.company WHERE a.id = :entityId ORDER BY a.id", Application.class); findByIdQuery.setParameter("entityId", id); Application entity; try { entity = findByIdQuery.getSingleResult(); } catch (NoResultException nre) { entity = null; } return entity; } public static Application findApplicationByName(EntityManager em, String name) { TypedQuery<Application> findByNameQuery = em.createQuery("SELECT DISTINCT a FROM Application a LEFT JOIN FETCH a.osInstances LEFT JOIN FETCH a.company WHERE a.name = :entityName ORDER BY a.name", Application.class); findByNameQuery.setParameter("entityName", name); Application entity; try { entity = findByNameQuery.getSingleResult(); } catch (NoResultException nre) { entity = null; } return entity; } public static CommonRestResponse jsonFriendlyToHibernateFriendly(EntityManager em, JSONFriendlyApplication jsonFriendlyApplication) { Application entity = null; CommonRestResponse commonRestResponse = new CommonRestResponse(); if(jsonFriendlyApplication.getApplicationID() !=0) entity = findApplicationById(em, jsonFriendlyApplication.getApplicationID()); if(entity == null){ if(jsonFriendlyApplication.getApplicationName() != null){ entity = findApplicationByName(em, jsonFriendlyApplication.getApplicationName()); } } if(entity != null) { if (jsonFriendlyApplication.getApplicationName() !=null) { entity.setName(jsonFriendlyApplication.getApplicationName()); } if (jsonFriendlyApplication.getApplicationShortName() != null) { entity.setShortName(jsonFriendlyApplication.getApplicationShortName()); } if (jsonFriendlyApplication.getApplicationColorCode() != null) { entity.setColorCode(jsonFriendlyApplication.getApplicationColorCode()); } if (jsonFriendlyApplication.getApplicationDescription() != null) { entity.setDescription(jsonFriendlyApplication.getApplicationDescription()); } if (jsonFriendlyApplication.getApplicationCompanyID() != 0) { Company company = CompanyEndpoint.findCompanyById(em, jsonFriendlyApplication.getApplicationCompanyID()); if (company != null) { if (entity.getCompany() != null) entity.getCompany().getApplications().remove(entity); entity.setCompany(company); company.getApplications().add(entity); } } if (jsonFriendlyApplication.getApplicationTeamID() != 0) { Team team = TeamEndpoint.findTeamById(em, jsonFriendlyApplication.getApplicationTeamID()); if (team != null) { if (entity.getTeam() != null) entity.getTeam().getApplications().remove(entity); entity.setTeam(team); team.getApplications().add(entity); } } if(jsonFriendlyApplication.getApplicationOSInstancesID() != null) { if (!jsonFriendlyApplication.getApplicationOSInstancesID().isEmpty()) { for (OSInstance osInstance : entity.getOsInstances()) { if (!jsonFriendlyApplication.getApplicationOSInstancesID().contains(osInstance.getId())) { entity.getOsInstances().remove(osInstance); osInstance.getApplications().remove(entity); } } for (Long osiId : jsonFriendlyApplication.getApplicationOSInstancesID()) { OSInstance osInstance = OSInstanceEndpoint.findOSInstanceById(em, osiId); if (osInstance != null) { if (!entity.getOsInstances().contains(osInstance)) { entity.getOsInstances().add(osInstance); osInstance.getApplications().add(entity); } } else { commonRestResponse.setErrorMessage("Fail to update Application. Reason : provided OS Instance ID " + osiId +" was not found."); return commonRestResponse; } } } else { for (OSInstance osInstance: entity.getOsInstances()) { entity.getOsInstances().remove(osInstance); osInstance.getApplications().remove(entity); } } } commonRestResponse.setDeserialiedObject(entity); } else { entity = new Application(); entity.setNameR(jsonFriendlyApplication.getApplicationName()).setShortNameR(jsonFriendlyApplication.getApplicationShortName()) .setColorCodeR(jsonFriendlyApplication.getApplicationColorCode()).setDescription(jsonFriendlyApplication.getApplicationDescription()); if (jsonFriendlyApplication.getApplicationCompanyID() != 0) { Company company = CompanyEndpoint.findCompanyById(em, jsonFriendlyApplication.getApplicationCompanyID()); if (company != null) { if (entity.getCompany() != null) entity.getCompany().getApplications().remove(entity); entity.setCompany(company); company.getApplications().add(entity); } else { commonRestResponse.setErrorMessage("Fail to create Application. Reason : provided Company ID " + jsonFriendlyApplication.getApplicationCompanyID() +" was not found."); return commonRestResponse; } } if (jsonFriendlyApplication.getApplicationTeamID() != 0) { Team team = TeamEndpoint.findTeamById(em, jsonFriendlyApplication.getApplicationTeamID()); if (team != null) { if (entity.getTeam() != null) entity.getTeam().getApplications().remove(entity); entity.setTeam(team); team.getApplications().add(entity); } else { commonRestResponse.setErrorMessage("Fail to create Application. Reason : provided Team ID " + jsonFriendlyApplication.getApplicationTeamID() +" was not found."); return commonRestResponse; } } if(jsonFriendlyApplication.getApplicationOSInstancesID() != null) { if (!jsonFriendlyApplication.getApplicationOSInstancesID().isEmpty()) { for (Long osiId : jsonFriendlyApplication.getApplicationOSInstancesID()) { OSInstance osInstance = OSInstanceEndpoint.findOSInstanceById(em, osiId); if (osInstance != null) { if (!entity.getOsInstances().contains(osInstance)) { entity.getOsInstances().add(osInstance); osInstance.getApplications().add(entity); } } else { commonRestResponse.setErrorMessage("Fail to update Application. Reason : provided OS Instance ID " + osiId + " was not found."); return commonRestResponse; } } } } commonRestResponse.setDeserialiedObject(entity); } return commonRestResponse; } @GET @Path("/{id:[0-9][0-9]*}") public Response displayApplication(@PathParam("id") Long id) { Subject subject = SecurityUtils.getSubject(); log.debug("[{}-{}] get application : {}", new Object[]{Thread.currentThread().getId(), subject.getPrincipal(), id}); if (subject.hasRole("orgadmin") || subject.hasRole("orgreviewer") || subject.isPermitted("dirComOrgApp:display") || subject.hasRole("Jedi") || subject.isPermitted("universe:zeone")) { em = DirectoryJPAProviderConsumer.getInstance().getDirectoryJpaProvider().createEM(); Application entity = findApplicationById(em, id); if (entity == null) { em.close(); return Response.status(Status.NOT_FOUND).build(); } Response ret = applicationToJSON(entity); em.close(); return ret; } else { return Response.status(Status.UNAUTHORIZED).entity("You're not authorized to display applications. Contact your administrator.").build(); } } @GET public Response displayAllApplications() { Subject subject = SecurityUtils.getSubject(); log.debug("[{}-{}] get applications", new Object[]{Thread.currentThread().getId(), subject.getPrincipal()}); if (subject.hasRole("orgadmin") || subject.hasRole("orgreviewer") || subject.isPermitted("dirComOrgApp:display") || subject.hasRole("Jedi") || subject.isPermitted("universe:zeone")) { em = DirectoryJPAProviderConsumer.getInstance().getDirectoryJpaProvider().createEM(); final HashSet<Application> results = new HashSet(em.createQuery("SELECT DISTINCT a FROM Application a LEFT JOIN FETCH a.osInstances LEFT JOIN FETCH a.company ORDER BY a.id", Application.class).getResultList()); String result; ByteArrayOutputStream outStream = new ByteArrayOutputStream(); Response ret = null; try { ApplicationJSON.manyApplications2JSON(results, outStream); result = ToolBox.getOuputStreamContent(outStream, "UTF-8"); ret = Response.status(Status.OK).entity(result).build(); } catch (Exception e) { log.error(e.getMessage()); e.printStackTrace(); result = e.getMessage(); ret = Response.status(Status.INTERNAL_SERVER_ERROR).entity(result).build(); } finally { em.close(); return ret; } } else { return Response.status(Status.UNAUTHORIZED).entity("You're not authorized to display applications. Contact your administrator.").build(); } } @GET @Path("/get") public Response getApplication(@QueryParam("name") String name, @QueryParam("id") long id) { if (id != 0) { return displayApplication(id); } else if (name != null) { Subject subject = SecurityUtils.getSubject(); log.debug("[{}-{}] get application : {}", new Object[]{Thread.currentThread().getId(), subject.getPrincipal(), name}); if (subject.hasRole("orgadmin") || subject.hasRole("orgreviewer") || subject.isPermitted("dirComOrgApp:display") || subject.hasRole("Jedi") || subject.isPermitted("universe:zeone")) { em = DirectoryJPAProviderConsumer.getInstance().getDirectoryJpaProvider().createEM(); Application entity = findApplicationByName(em, name); if (entity == null) { em.close(); return Response.status(Status.NOT_FOUND).build(); } Response ret = applicationToJSON(entity); em.close(); return ret; } else { return Response.status(Status.UNAUTHORIZED).entity("You're not authorized to display applications. Contact your administrator.").build(); } } else { return Response.status(Status.INTERNAL_SERVER_ERROR).entity("Request error: id and name are not defined. You must define one of these parameters.").build(); } } @GET @Path("/create") public Response createApplication(@QueryParam("name") String name, @QueryParam("shortName") String shortName, @QueryParam("description") String description, @QueryParam("colorCode") String colorCode) { if (name != null && shortName != null && colorCode != null) { Subject subject = SecurityUtils.getSubject(); log.debug("[{}-{}] create application : ({},{},{},{})", new Object[]{Thread.currentThread().getId(), subject.getPrincipal(), name, shortName, description, colorCode}); if (subject.hasRole("orgadmin") || subject.isPermitted("dirComOrgApp:create") || subject.hasRole("Jedi") || subject.isPermitted("universe:zeone")) { em = DirectoryJPAProviderConsumer.getInstance().getDirectoryJpaProvider().createEM(); Application entity = findApplicationByName(em, name); if (entity == null) { entity = new Application(); entity.setNameR(name).setShortNameR(shortName).setColorCodeR(colorCode).setDescription(description); try { em.getTransaction().begin(); em.persist(entity); em.flush(); em.getTransaction().commit(); } catch (Throwable t) { if (em.getTransaction().isActive()) em.getTransaction().rollback(); em.close(); return Response.status(Status.INTERNAL_SERVER_ERROR).entity("Throwable raised while creating application " + entity.getName() + " : " + t.getMessage()).build(); } } Response ret = applicationToJSON(entity); em.close(); return ret; } else { return Response.status(Status.UNAUTHORIZED).entity("You're not authorized to create applications. Contact your administrator.").build(); } } else { return Response.status(Status.INTERNAL_SERVER_ERROR).entity("Request error: name and/or short name and/or color code are not defined. You must define these parameters.").build(); } } @POST public Response postApplication(@QueryParam("payload") String payload) throws IOException { Subject subject = SecurityUtils.getSubject(); log.debug("[{}-{}] create/update application : ({})", new Object[]{Thread.currentThread().getId(), subject.getPrincipal(), payload}); if (subject.hasRole("orgadmin") || subject.isPermitted("dirComOrgApp:create") || subject.hasRole("Jedi") || subject.isPermitted("universe:zeone")) { em = DirectoryJPAProviderConsumer.getInstance().getDirectoryJpaProvider().createEM(); JSONFriendlyApplication jsonFriendlyApplication = ApplicationJSON.JSON2Application(payload); CommonRestResponse commonRestResponse = jsonFriendlyToHibernateFriendly(em, jsonFriendlyApplication); Application entity = (Application) commonRestResponse.getDeserialiedObject(); if (entity != null) { try { em.getTransaction().begin(); if (entity.getId() == null){ em.persist(entity); em.flush(); em.getTransaction().commit(); } else { em.merge(entity); em.flush(); em.getTransaction().commit(); } Response ret = applicationToJSON(entity); em.close(); return ret; } catch (Throwable t) { if (em.getTransaction().isActive()) em.getTransaction().rollback(); em.close(); return Response.status(Status.INTERNAL_SERVER_ERROR).entity("Throwable raised while creating application " + payload + " : " + t.getMessage()).build(); } } else{ return Response.status(Status.INTERNAL_SERVER_ERROR).entity(commonRestResponse.getErrorMessage()).build(); } } else { return Response.status(Status.UNAUTHORIZED).entity("You're not authorized to create applications. Contact your administrator.").build(); } } @GET @Path("/delete") public Response deleteApplication(@QueryParam("id")Long id) { if (id!=0) { Subject subject = SecurityUtils.getSubject(); log.debug("[{}-{}] delete application : {}", new Object[]{Thread.currentThread().getId(), subject.getPrincipal(), id}); if (subject.hasRole("orgadmin") || subject.isPermitted("dirComOrgApp:delete") || subject.hasRole("Jedi") || subject.isPermitted("universe:zeone")) { em = DirectoryJPAProviderConsumer.getInstance().getDirectoryJpaProvider().createEM(); Application entity = findApplicationById(em, id); if (entity != null) { try { em.getTransaction().begin(); for (OSInstance osInstance : entity.getOsInstances()) osInstance.getApplications().remove(entity); if (entity.getCompany()!=null) entity.getCompany().getApplications().remove(entity); if (entity.getTeam()!=null) entity.getTeam().getApplications().remove(entity); em.remove(entity); em.flush(); em.getTransaction().commit(); return Response.status(Status.OK).entity("Application " + id + " has been successfully deleted").build(); } catch (Throwable t) { if(em.getTransaction().isActive()) em.getTransaction().rollback(); em.close(); return Response.status(Status.INTERNAL_SERVER_ERROR).entity("Throwable raised while deleting application " + entity.getName() + " : " + t.getMessage()).build(); } } else { em.close(); return Response.status(Status.NOT_FOUND).build(); } } else { return Response.status(Status.UNAUTHORIZED).entity("You're not authorized to delete applications. Contact your administrator.").build(); } } else { return Response.status(Status.INTERNAL_SERVER_ERROR).entity("Request error: id is not defined. You must define this parameter.").build(); } } @GET @Path("/update/name") public Response updateApplicationName(@QueryParam("id")Long id, @QueryParam("name")String name) { if (id!=0 && name!=null) { Subject subject = SecurityUtils.getSubject(); log.debug("[{}-{}] update application {} name : {}", new Object[]{Thread.currentThread().getId(), subject.getPrincipal(), id, name}); if (subject.hasRole("orgadmin") || subject.isPermitted("dirComOrgApp:update") || subject.hasRole("Jedi") || subject.isPermitted("universe:zeone")) { em = DirectoryJPAProviderConsumer.getInstance().getDirectoryJpaProvider().createEM(); Application entity = findApplicationById(em, id); if (entity != null) { try { em.getTransaction().begin(); entity.setName(name); em.flush(); em.getTransaction().commit(); em.close(); return Response.status(Status.OK).entity("Application " + id + " has been successfully updated with name " + name).build(); } catch (Throwable t) { if(em.getTransaction().isActive()) em.getTransaction().rollback(); em.close(); return Response.status(Status.INTERNAL_SERVER_ERROR).entity("Throwable raised while updating application " + entity.getName() + " : " + t.getMessage()).build(); } } else { return Response.status(Status.NOT_FOUND).build(); } } else { return Response.status(Status.UNAUTHORIZED).entity("You're not authorized to update applications. Contact your administrator.").build(); } } else { return Response.status(Status.INTERNAL_SERVER_ERROR).entity("Request error: id and/or name are not defined. You must define these parameters.").build(); } } @GET @Path("/update/shortName") public Response updateApplicationShortName(@QueryParam("id")Long id, @QueryParam("shortName")String shortName) { if (id!=0 && shortName!=null) { Subject subject = SecurityUtils.getSubject(); log.debug("[{}-{}] update application {} short name : {}", new Object[]{Thread.currentThread().getId(), subject.getPrincipal(), id, shortName}); if (subject.hasRole("orgadmin") || subject.isPermitted("dirComOrgApp:update") || subject.hasRole("Jedi") || subject.isPermitted("universe:zeone")) { em = DirectoryJPAProviderConsumer.getInstance().getDirectoryJpaProvider().createEM(); Application entity = findApplicationById(em, id); if (entity != null) { try { em.getTransaction().begin(); entity.setShortName(shortName); em.flush(); em.getTransaction().commit(); em.close(); return Response.status(Status.OK).entity("Application " + id + " has been successfully updated with short name " + shortName).build(); } catch (Throwable t) { if(em.getTransaction().isActive()) em.getTransaction().rollback(); em.close(); return Response.status(Status.INTERNAL_SERVER_ERROR).entity("Throwable raised while updating application " + entity.getName() + " : " + t.getMessage()).build(); } } else { return Response.status(Status.NOT_FOUND).build(); } } else { return Response.status(Status.UNAUTHORIZED).entity("You're not authorized to update applications. Contact your administrator.").build(); } } else { return Response.status(Status.INTERNAL_SERVER_ERROR).entity("Request error: id and/or shortName are not defined. You must define these parameters.").build(); } } @GET @Path("/update/description") public Response updateApplicationDescription(@QueryParam("id")Long id, @QueryParam("description")String description) { if (id!=0 && description!=null) { Subject subject = SecurityUtils.getSubject(); log.debug("[{}-{}] update application {} description : {}", new Object[]{Thread.currentThread().getId(), subject.getPrincipal(), id, description}); if (subject.hasRole("orgadmin") || subject.isPermitted("dirComOrgApp:update") || subject.hasRole("Jedi") || subject.isPermitted("universe:zeone")) { em = DirectoryJPAProviderConsumer.getInstance().getDirectoryJpaProvider().createEM(); Application entity = findApplicationById(em, id); if (entity != null) { try { em.getTransaction().begin(); entity.setDescription(description); em.flush(); em.getTransaction().commit(); em.close(); return Response.status(Status.OK).entity("Application " + id + " has been successfully updated with description " + description).build(); } catch (Throwable t) { if(em.getTransaction().isActive()) em.getTransaction().rollback(); em.close(); return Response.status(Status.INTERNAL_SERVER_ERROR).entity("Throwable raised while updating application " + entity.getName() + " : " + t.getMessage()).build(); } } else { return Response.status(Status.NOT_FOUND).build(); } } else { return Response.status(Status.UNAUTHORIZED).entity("You're not authorized to update applications. Contact your administrator.").build(); } } else { return Response.status(Status.INTERNAL_SERVER_ERROR).entity("Request error: id and/or description are not defined. You must define these parameters.").build(); } } @GET @Path("/update/colorCode") public Response updateApplicationColorCode(@QueryParam("id")Long id, @QueryParam("colorCode")String colorCode) { if (id!=0 && colorCode!=null) { Subject subject = SecurityUtils.getSubject(); log.debug("[{}-{}] update application {} color code : {}", new Object[]{Thread.currentThread().getId(), subject.getPrincipal(), id, colorCode}); if (subject.hasRole("orgadmin") || subject.isPermitted("dirComOrgApp:update") || subject.hasRole("Jedi") || subject.isPermitted("universe:zeone")) { em = DirectoryJPAProviderConsumer.getInstance().getDirectoryJpaProvider().createEM(); Application entity = findApplicationById(em, id); if (entity != null) { try { em.getTransaction().begin(); entity.setColorCode(colorCode); em.flush(); em.getTransaction().commit(); em.close(); return Response.status(Status.OK).entity("Application " + id + " has been successfully updated with color code " + colorCode).build(); } catch (Throwable t) { if(em.getTransaction().isActive()) em.getTransaction().rollback(); em.close(); return Response.status(Status.INTERNAL_SERVER_ERROR).entity("Throwable raised while updating application " + entity.getName() + " : " + t.getMessage()).build(); } } else { return Response.status(Status.NOT_FOUND).build(); } } else { return Response.status(Status.UNAUTHORIZED).entity("You're not authorized to update applications. Contact your administrator.").build(); } } else { return Response.status(Status.INTERNAL_SERVER_ERROR).entity("Request error: id and/or colorCode are not defined. You must define these parameters.").build(); } } @GET @Path("/update/company") public Response updateApplicationCompany(@QueryParam("id")Long id, @QueryParam("companyID")Long companyID) { if (id!=0 && companyID!=null) { Subject subject = SecurityUtils.getSubject(); log.debug("[{}-{}] update application {} company : {}", new Object[]{Thread.currentThread().getId(), subject.getPrincipal(), id, companyID}); if (subject.hasRole("orgadmin") || subject.isPermitted("dirComOrgApp:update") || subject.hasRole("Jedi") || subject.isPermitted("universe:zeone")) { em = DirectoryJPAProviderConsumer.getInstance().getDirectoryJpaProvider().createEM(); Application entity = findApplicationById(em, id); if (entity != null) { Company company = CompanyEndpoint.findCompanyById(em, companyID); if (company != null) { try { em.getTransaction().begin(); if (entity.getCompany()!=null) entity.getCompany().getApplications().remove(entity); entity.setCompany(company); company.getApplications().add(entity); em.flush(); em.getTransaction().commit(); em.close(); return Response.status(Status.OK).entity("Application " + id + " has been successfully updated with company " + companyID).build(); } catch (Throwable t) { if(em.getTransaction().isActive()) em.getTransaction().rollback(); em.close(); return Response.status(Status.INTERNAL_SERVER_ERROR).entity("Throwable raised while updating application " + entity.getName() + " : " + t.getMessage()).build(); } } else { return Response.status(Status.NOT_FOUND).entity("Company " + companyID + " not found.").build(); } } else { return Response.status(Status.NOT_FOUND).entity("Application " + id + " not found.").build(); } } else { return Response.status(Status.UNAUTHORIZED).entity("You're not authorized to update applications. Contact your administrator.").build(); } } else { return Response.status(Status.INTERNAL_SERVER_ERROR).entity("Request error: id and/or companyID are not defined. You must define these parameters.").build(); } } @GET @Path("/update/team") public Response updateApplicationTeam(@QueryParam("id")Long id, @QueryParam("teamID")Long teamID) { if (id!=0 && teamID!=null) { Subject subject = SecurityUtils.getSubject(); log.debug("[{}-{}] update application {} team : {}", new Object[]{Thread.currentThread().getId(), subject.getPrincipal(), id, teamID}); if (subject.hasRole("orgadmin") || subject.isPermitted("dirComOrgApp:update") || subject.hasRole("Jedi") || subject.isPermitted("universe:zeone")) { em = DirectoryJPAProviderConsumer.getInstance().getDirectoryJpaProvider().createEM(); Application entity = findApplicationById(em, id); if (entity != null) { Team team = TeamEndpoint.findTeamById(em, teamID); if (team != null) { try { em.getTransaction().begin(); entity.getTeam().getApplications().remove(entity); entity.setTeam(team); team.getApplications().add(entity); em.flush(); em.getTransaction().commit(); em.close(); return Response.status(Status.OK).entity("Application " + id + " has been successfully updated with team " + teamID).build(); } catch (Throwable t) { if(em.getTransaction().isActive()) em.getTransaction().rollback(); em.close(); return Response.status(Status.INTERNAL_SERVER_ERROR).entity("Throwable raised while updating application " + entity.getName() + " : " + t.getMessage()).build(); } } else { return Response.status(Status.NOT_FOUND).entity("Team " + teamID + " not found.").build(); } } else { return Response.status(Status.NOT_FOUND).entity("Application " + id + " not found.").build(); } } else { return Response.status(Status.UNAUTHORIZED).entity("You're not authorized to update applications. Contact your administrator.").build(); } } else { return Response.status(Status.INTERNAL_SERVER_ERROR).entity("Request error: id and/or teamID are not defined. You must define these parameters.").build(); } } @GET @Path("/update/osinstances/add") public Response updateApplicationAddOSInstance(@QueryParam("id")Long id, @QueryParam("osiID")Long osiID) { if (id!=0 && osiID!=null) { Subject subject = SecurityUtils.getSubject(); log.debug("[{}-{}] update application {} by adding os instance : {}", new Object[]{Thread.currentThread().getId(), subject.getPrincipal(), id, osiID}); if (subject.hasRole("orgadmin") || subject.isPermitted("dirComOrgApp:update") || subject.hasRole("Jedi") || subject.isPermitted("universe:zeone")) { em = DirectoryJPAProviderConsumer.getInstance().getDirectoryJpaProvider().createEM(); Application entity = findApplicationById(em, id); if (entity != null) { OSInstance osInstance = OSInstanceEndpoint.findOSInstanceById(em, osiID); if (osInstance != null) { try { em.getTransaction().begin(); entity.getOsInstances().add(osInstance); osInstance.getApplications().add(entity); em.flush(); em.getTransaction().commit(); em.close(); return Response.status(Status.OK).entity("Application " + id + " has been suessfully updated by adding os instance " + osiID).build(); } catch (Throwable t) { if(em.getTransaction().isActive()) em.getTransaction().rollback(); em.close(); return Response.status(Status.INTERNAL_SERVER_ERROR).entity("Throwable raised while updating application " + entity.getName() + " : " + t.getMessage()).build(); } } else { return Response.status(Status.NOT_FOUND).entity("OS Instance " + osiID + " not found.").build(); } } else { return Response.status(Status.NOT_FOUND).entity("Application " + id + " not found.").build(); } } else { return Response.status(Status.UNAUTHORIZED).entity("You're not authorized to update applications. Contact your administrator.").build(); } } else { return Response.status(Status.INTERNAL_SERVER_ERROR).entity("Request error: id and/or teamID are not defined. You must define these parameters.").build(); } } @GET @Path("/update/osinstances/delete") public Response updateApplicationDeleteOSInstance(@QueryParam("id")Long id, @QueryParam("osiID")Long osiID) { if (id!=0 && osiID!=null) { Subject subject = SecurityUtils.getSubject(); log.debug("[{}-{}] update application {} by adding os instance : {}", new Object[]{Thread.currentThread().getId(), subject.getPrincipal(), id, osiID}); if (subject.hasRole("orgadmin") || subject.isPermitted("dirComOrgApp:update") || subject.hasRole("Jedi") || subject.isPermitted("universe:zeone")) { em = DirectoryJPAProviderConsumer.getInstance().getDirectoryJpaProvider().createEM(); Application entity = findApplicationById(em, id); if (entity != null) { OSInstance osInstance = OSInstanceEndpoint.findOSInstanceById(em, osiID); if (osInstance != null) { try { em.getTransaction().begin(); entity.getOsInstances().remove(osInstance); osInstance.getApplications().remove(entity); em.flush(); em.getTransaction().commit(); em.close(); return Response.status(Status.OK).entity("Application " + id + " has been suessfully updated by adding os instance " + osiID).build(); } catch (Throwable t) { if(em.getTransaction().isActive()) em.getTransaction().rollback(); em.close(); return Response.status(Status.INTERNAL_SERVER_ERROR).entity("Throwable raised while updating application " + entity.getName() + " : " + t.getMessage()).build(); } } else { return Response.status(Status.NOT_FOUND).entity("OS Instance " + osiID + " not found.").build(); } } else { return Response.status(Status.NOT_FOUND).entity("Application " + id + " not found.").build(); } } else { return Response.status(Status.UNAUTHORIZED).entity("You're not authorized to update applications. Contact your administrator.").build(); } } else { return Response.status(Status.INTERNAL_SERVER_ERROR).entity("Request error: id and/or teamID are not defined. You must define these parameters.").build(); } } }
wat/src/main/java/net/echinopsii/ariane/community/core/directory/wat/rest/organisational/ApplicationEndpoint.java
/** * Directory wat * Application REST endpoint * Copyright (C) 2013 Mathilde Ffrench * * 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 net.echinopsii.ariane.community.core.directory.wat.rest.organisational; import net.echinopsii.ariane.community.core.directory.base.model.organisational.Company; import net.echinopsii.ariane.community.core.directory.base.model.organisational.Team; import net.echinopsii.ariane.community.core.directory.base.model.technical.system.OSInstance; import net.echinopsii.ariane.community.core.directory.base.json.ToolBox; import net.echinopsii.ariane.community.core.directory.base.json.ds.organisational.ApplicationJSON; import net.echinopsii.ariane.community.core.directory.wat.plugin.DirectoryJPAProviderConsumer; import net.echinopsii.ariane.community.core.directory.base.model.organisational.Application; import net.echinopsii.ariane.community.core.directory.wat.rest.technical.system.OSInstanceEndpoint; import org.apache.shiro.SecurityUtils; import org.apache.shiro.subject.Subject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.persistence.EntityManager; import javax.persistence.NoResultException; import javax.persistence.TypedQuery; import javax.ws.rs.*; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.HashSet; import static net.echinopsii.ariane.community.core.directory.base.json.ds.organisational.ApplicationJSON.JSONFriendlyApplication; /** * */ @Path("directories/common/organisation/applications") public class ApplicationEndpoint { private static final Logger log = LoggerFactory.getLogger(ApplicationEndpoint.class); private EntityManager em; public static Response applicationToJSON(Application application) { Response ret = null; String result; ByteArrayOutputStream outStream = new ByteArrayOutputStream(); try { ApplicationJSON.oneApplication2JSON(application, outStream); result = ToolBox.getOuputStreamContent(outStream, "UTF-8"); ret = Response.status(Status.OK).entity(result).build(); } catch (Exception e) { log.error(e.getMessage()); e.printStackTrace(); result = e.getMessage(); ret = Response.status(Status.INTERNAL_SERVER_ERROR).entity(result).build(); } return ret; } public static Application findApplicationById(EntityManager em, long id) { TypedQuery<Application> findByIdQuery = em.createQuery("SELECT DISTINCT a FROM Application a LEFT JOIN FETCH a.osInstances LEFT JOIN FETCH a.company WHERE a.id = :entityId ORDER BY a.id", Application.class); findByIdQuery.setParameter("entityId", id); Application entity; try { entity = findByIdQuery.getSingleResult(); } catch (NoResultException nre) { entity = null; } return entity; } public static Application findApplicationByName(EntityManager em, String name) { TypedQuery<Application> findByNameQuery = em.createQuery("SELECT DISTINCT a FROM Application a LEFT JOIN FETCH a.osInstances LEFT JOIN FETCH a.company WHERE a.name = :entityName ORDER BY a.name", Application.class); findByNameQuery.setParameter("entityName", name); Application entity; try { entity = findByNameQuery.getSingleResult(); } catch (NoResultException nre) { entity = null; } return entity; } public static Application jsonFriendlyToHibernateFriendly(EntityManager em, JSONFriendlyApplication jsonFriendlyApplication) { Application entity = null; if(jsonFriendlyApplication.getApplicationID() != 0) { entity = findApplicationById(em, jsonFriendlyApplication.getApplicationID()); if(entity != null) { if (jsonFriendlyApplication.getApplicationName() !=null) { entity.setName(jsonFriendlyApplication.getApplicationName()); } if (jsonFriendlyApplication.getApplicationShortName() != null) { entity.setShortName(jsonFriendlyApplication.getApplicationShortName()); } if (jsonFriendlyApplication.getApplicationColorCode() != null) { entity.setColorCode(jsonFriendlyApplication.getApplicationColorCode()); } if (jsonFriendlyApplication.getApplicationDescription() != null) { entity.setDescription(jsonFriendlyApplication.getApplicationDescription()); } if (jsonFriendlyApplication.getApplicationCompanyID() != 0) { Company company = CompanyEndpoint.findCompanyById(em, jsonFriendlyApplication.getApplicationCompanyID()); if (company != null) { if (entity.getCompany() != null) entity.getCompany().getApplications().remove(entity); entity.setCompany(company); company.getApplications().add(entity); } } if (jsonFriendlyApplication.getApplicationTeamID() != 0) { Team team = TeamEndpoint.findTeamById(em, jsonFriendlyApplication.getApplicationTeamID()); if (team != null) { if (entity.getTeam() != null) entity.getTeam().getApplications().remove(entity); entity.setTeam(team); team.getApplications().add(entity); } } if(jsonFriendlyApplication.getApplicationOSInstancesID() != null) { if (!jsonFriendlyApplication.getApplicationOSInstancesID().isEmpty()) { for (OSInstance osInstance : entity.getOsInstances()) { if (!jsonFriendlyApplication.getApplicationOSInstancesID().contains(osInstance.getId())) { entity.getOsInstances().remove(osInstance); osInstance.getApplications().remove(entity); } } for (Long osiId : jsonFriendlyApplication.getApplicationOSInstancesID()) { OSInstance osInstance = OSInstanceEndpoint.findOSInstanceById(em, osiId); if (osInstance != null) { if (!entity.getOsInstances().contains(osInstance)) { entity.getOsInstances().add(osInstance); osInstance.getApplications().add(entity); } } } } } } else { log.error("Request error: Failed to update Application, unable to lookup provided Application Id."); } } else { entity = findApplicationByName(em, jsonFriendlyApplication.getApplicationName()); if(jsonFriendlyApplication.getApplicationName()!=null && jsonFriendlyApplication.getApplicationShortName()!=null && jsonFriendlyApplication.getApplicationColorCode()!=null){ if(entity == null) { entity = new Application(); entity.setNameR(jsonFriendlyApplication.getApplicationName()).setShortNameR(jsonFriendlyApplication.getApplicationShortName()) .setColorCodeR(jsonFriendlyApplication.getApplicationColorCode()).setDescription(jsonFriendlyApplication.getApplicationDescription()); } } else { log.error("Request error: name and/or short name and/or color code are not defined. You must define these parameters."); } } return entity; } @GET @Path("/{id:[0-9][0-9]*}") public Response displayApplication(@PathParam("id") Long id) { Subject subject = SecurityUtils.getSubject(); log.debug("[{}-{}] get application : {}", new Object[]{Thread.currentThread().getId(), subject.getPrincipal(), id}); if (subject.hasRole("orgadmin") || subject.hasRole("orgreviewer") || subject.isPermitted("dirComOrgApp:display") || subject.hasRole("Jedi") || subject.isPermitted("universe:zeone")) { em = DirectoryJPAProviderConsumer.getInstance().getDirectoryJpaProvider().createEM(); Application entity = findApplicationById(em, id); if (entity == null) { em.close(); return Response.status(Status.NOT_FOUND).build(); } Response ret = applicationToJSON(entity); em.close(); return ret; } else { return Response.status(Status.UNAUTHORIZED).entity("You're not authorized to display applications. Contact your administrator.").build(); } } @GET public Response displayAllApplications() { Subject subject = SecurityUtils.getSubject(); log.debug("[{}-{}] get applications", new Object[]{Thread.currentThread().getId(), subject.getPrincipal()}); if (subject.hasRole("orgadmin") || subject.hasRole("orgreviewer") || subject.isPermitted("dirComOrgApp:display") || subject.hasRole("Jedi") || subject.isPermitted("universe:zeone")) { em = DirectoryJPAProviderConsumer.getInstance().getDirectoryJpaProvider().createEM(); final HashSet<Application> results = new HashSet(em.createQuery("SELECT DISTINCT a FROM Application a LEFT JOIN FETCH a.osInstances LEFT JOIN FETCH a.company ORDER BY a.id", Application.class).getResultList()); String result; ByteArrayOutputStream outStream = new ByteArrayOutputStream(); Response ret = null; try { ApplicationJSON.manyApplications2JSON(results, outStream); result = ToolBox.getOuputStreamContent(outStream, "UTF-8"); ret = Response.status(Status.OK).entity(result).build(); } catch (Exception e) { log.error(e.getMessage()); e.printStackTrace(); result = e.getMessage(); ret = Response.status(Status.INTERNAL_SERVER_ERROR).entity(result).build(); } finally { em.close(); return ret; } } else { return Response.status(Status.UNAUTHORIZED).entity("You're not authorized to display applications. Contact your administrator.").build(); } } @GET @Path("/get") public Response getApplication(@QueryParam("name") String name, @QueryParam("id") long id) { if (id != 0) { return displayApplication(id); } else if (name != null) { Subject subject = SecurityUtils.getSubject(); log.debug("[{}-{}] get application : {}", new Object[]{Thread.currentThread().getId(), subject.getPrincipal(), name}); if (subject.hasRole("orgadmin") || subject.hasRole("orgreviewer") || subject.isPermitted("dirComOrgApp:display") || subject.hasRole("Jedi") || subject.isPermitted("universe:zeone")) { em = DirectoryJPAProviderConsumer.getInstance().getDirectoryJpaProvider().createEM(); Application entity = findApplicationByName(em, name); if (entity == null) { em.close(); return Response.status(Status.NOT_FOUND).build(); } Response ret = applicationToJSON(entity); em.close(); return ret; } else { return Response.status(Status.UNAUTHORIZED).entity("You're not authorized to display applications. Contact your administrator.").build(); } } else { return Response.status(Status.INTERNAL_SERVER_ERROR).entity("Request error: id and name are not defined. You must define one of these parameters.").build(); } } @GET @Path("/create") public Response createApplication(@QueryParam("name") String name, @QueryParam("shortName") String shortName, @QueryParam("description") String description, @QueryParam("colorCode") String colorCode) { if (name != null && shortName != null && colorCode != null) { Subject subject = SecurityUtils.getSubject(); log.debug("[{}-{}] create application : ({},{},{},{})", new Object[]{Thread.currentThread().getId(), subject.getPrincipal(), name, shortName, description, colorCode}); if (subject.hasRole("orgadmin") || subject.isPermitted("dirComOrgApp:create") || subject.hasRole("Jedi") || subject.isPermitted("universe:zeone")) { em = DirectoryJPAProviderConsumer.getInstance().getDirectoryJpaProvider().createEM(); Application entity = findApplicationByName(em, name); if (entity == null) { entity = new Application(); entity.setNameR(name).setShortNameR(shortName).setColorCodeR(colorCode).setDescription(description); try { em.getTransaction().begin(); em.persist(entity); em.flush(); em.getTransaction().commit(); } catch (Throwable t) { if (em.getTransaction().isActive()) em.getTransaction().rollback(); em.close(); return Response.status(Status.INTERNAL_SERVER_ERROR).entity("Throwable raised while creating application " + entity.getName() + " : " + t.getMessage()).build(); } } Response ret = applicationToJSON(entity); em.close(); return ret; } else { return Response.status(Status.UNAUTHORIZED).entity("You're not authorized to create applications. Contact your administrator.").build(); } } else { return Response.status(Status.INTERNAL_SERVER_ERROR).entity("Request error: name and/or short name and/or color code are not defined. You must define these parameters.").build(); } } @POST public Response postApplication(@QueryParam("payload") String payload) throws IOException { Subject subject = SecurityUtils.getSubject(); log.debug("[{}-{}] create/update application : ({})", new Object[]{Thread.currentThread().getId(), subject.getPrincipal(), payload}); if (subject.hasRole("orgadmin") || subject.isPermitted("dirComOrgApp:create") || subject.hasRole("Jedi") || subject.isPermitted("universe:zeone")) { em = DirectoryJPAProviderConsumer.getInstance().getDirectoryJpaProvider().createEM(); JSONFriendlyApplication jsonFriendlyApplication = ApplicationJSON.JSON2Application(payload); Application entity = jsonFriendlyToHibernateFriendly(em, jsonFriendlyApplication); if (entity != null) { try { em.getTransaction().begin(); if (entity.getId() == null){ em.persist(entity); em.flush(); em.getTransaction().commit(); } else { em.merge(entity); em.flush(); em.getTransaction().commit(); } Response ret = applicationToJSON(entity); em.close(); return ret; } catch (Throwable t) { if (em.getTransaction().isActive()) em.getTransaction().rollback(); em.close(); return Response.status(Status.INTERNAL_SERVER_ERROR).entity("Throwable raised while creating application " + payload + " : " + t.getMessage()).build(); } } else{ return Response.status(Status.INTERNAL_SERVER_ERROR).entity("Check server logs to know more.").build(); } } else { return Response.status(Status.UNAUTHORIZED).entity("You're not authorized to create applications. Contact your administrator.").build(); } } @GET @Path("/delete") public Response deleteApplication(@QueryParam("id")Long id) { if (id!=0) { Subject subject = SecurityUtils.getSubject(); log.debug("[{}-{}] delete application : {}", new Object[]{Thread.currentThread().getId(), subject.getPrincipal(), id}); if (subject.hasRole("orgadmin") || subject.isPermitted("dirComOrgApp:delete") || subject.hasRole("Jedi") || subject.isPermitted("universe:zeone")) { em = DirectoryJPAProviderConsumer.getInstance().getDirectoryJpaProvider().createEM(); Application entity = findApplicationById(em, id); if (entity != null) { try { em.getTransaction().begin(); for (OSInstance osInstance : entity.getOsInstances()) osInstance.getApplications().remove(entity); if (entity.getCompany()!=null) entity.getCompany().getApplications().remove(entity); if (entity.getTeam()!=null) entity.getTeam().getApplications().remove(entity); em.remove(entity); em.flush(); em.getTransaction().commit(); return Response.status(Status.OK).entity("Application " + id + " has been successfully deleted").build(); } catch (Throwable t) { if(em.getTransaction().isActive()) em.getTransaction().rollback(); em.close(); return Response.status(Status.INTERNAL_SERVER_ERROR).entity("Throwable raised while deleting application " + entity.getName() + " : " + t.getMessage()).build(); } } else { em.close(); return Response.status(Status.NOT_FOUND).build(); } } else { return Response.status(Status.UNAUTHORIZED).entity("You're not authorized to delete applications. Contact your administrator.").build(); } } else { return Response.status(Status.INTERNAL_SERVER_ERROR).entity("Request error: id is not defined. You must define this parameter.").build(); } } @GET @Path("/update/name") public Response updateApplicationName(@QueryParam("id")Long id, @QueryParam("name")String name) { if (id!=0 && name!=null) { Subject subject = SecurityUtils.getSubject(); log.debug("[{}-{}] update application {} name : {}", new Object[]{Thread.currentThread().getId(), subject.getPrincipal(), id, name}); if (subject.hasRole("orgadmin") || subject.isPermitted("dirComOrgApp:update") || subject.hasRole("Jedi") || subject.isPermitted("universe:zeone")) { em = DirectoryJPAProviderConsumer.getInstance().getDirectoryJpaProvider().createEM(); Application entity = findApplicationById(em, id); if (entity != null) { try { em.getTransaction().begin(); entity.setName(name); em.flush(); em.getTransaction().commit(); em.close(); return Response.status(Status.OK).entity("Application " + id + " has been successfully updated with name " + name).build(); } catch (Throwable t) { if(em.getTransaction().isActive()) em.getTransaction().rollback(); em.close(); return Response.status(Status.INTERNAL_SERVER_ERROR).entity("Throwable raised while updating application " + entity.getName() + " : " + t.getMessage()).build(); } } else { return Response.status(Status.NOT_FOUND).build(); } } else { return Response.status(Status.UNAUTHORIZED).entity("You're not authorized to update applications. Contact your administrator.").build(); } } else { return Response.status(Status.INTERNAL_SERVER_ERROR).entity("Request error: id and/or name are not defined. You must define these parameters.").build(); } } @GET @Path("/update/shortName") public Response updateApplicationShortName(@QueryParam("id")Long id, @QueryParam("shortName")String shortName) { if (id!=0 && shortName!=null) { Subject subject = SecurityUtils.getSubject(); log.debug("[{}-{}] update application {} short name : {}", new Object[]{Thread.currentThread().getId(), subject.getPrincipal(), id, shortName}); if (subject.hasRole("orgadmin") || subject.isPermitted("dirComOrgApp:update") || subject.hasRole("Jedi") || subject.isPermitted("universe:zeone")) { em = DirectoryJPAProviderConsumer.getInstance().getDirectoryJpaProvider().createEM(); Application entity = findApplicationById(em, id); if (entity != null) { try { em.getTransaction().begin(); entity.setShortName(shortName); em.flush(); em.getTransaction().commit(); em.close(); return Response.status(Status.OK).entity("Application " + id + " has been successfully updated with short name " + shortName).build(); } catch (Throwable t) { if(em.getTransaction().isActive()) em.getTransaction().rollback(); em.close(); return Response.status(Status.INTERNAL_SERVER_ERROR).entity("Throwable raised while updating application " + entity.getName() + " : " + t.getMessage()).build(); } } else { return Response.status(Status.NOT_FOUND).build(); } } else { return Response.status(Status.UNAUTHORIZED).entity("You're not authorized to update applications. Contact your administrator.").build(); } } else { return Response.status(Status.INTERNAL_SERVER_ERROR).entity("Request error: id and/or shortName are not defined. You must define these parameters.").build(); } } @GET @Path("/update/description") public Response updateApplicationDescription(@QueryParam("id")Long id, @QueryParam("description")String description) { if (id!=0 && description!=null) { Subject subject = SecurityUtils.getSubject(); log.debug("[{}-{}] update application {} description : {}", new Object[]{Thread.currentThread().getId(), subject.getPrincipal(), id, description}); if (subject.hasRole("orgadmin") || subject.isPermitted("dirComOrgApp:update") || subject.hasRole("Jedi") || subject.isPermitted("universe:zeone")) { em = DirectoryJPAProviderConsumer.getInstance().getDirectoryJpaProvider().createEM(); Application entity = findApplicationById(em, id); if (entity != null) { try { em.getTransaction().begin(); entity.setDescription(description); em.flush(); em.getTransaction().commit(); em.close(); return Response.status(Status.OK).entity("Application " + id + " has been successfully updated with description " + description).build(); } catch (Throwable t) { if(em.getTransaction().isActive()) em.getTransaction().rollback(); em.close(); return Response.status(Status.INTERNAL_SERVER_ERROR).entity("Throwable raised while updating application " + entity.getName() + " : " + t.getMessage()).build(); } } else { return Response.status(Status.NOT_FOUND).build(); } } else { return Response.status(Status.UNAUTHORIZED).entity("You're not authorized to update applications. Contact your administrator.").build(); } } else { return Response.status(Status.INTERNAL_SERVER_ERROR).entity("Request error: id and/or description are not defined. You must define these parameters.").build(); } } @GET @Path("/update/colorCode") public Response updateApplicationColorCode(@QueryParam("id")Long id, @QueryParam("colorCode")String colorCode) { if (id!=0 && colorCode!=null) { Subject subject = SecurityUtils.getSubject(); log.debug("[{}-{}] update application {} color code : {}", new Object[]{Thread.currentThread().getId(), subject.getPrincipal(), id, colorCode}); if (subject.hasRole("orgadmin") || subject.isPermitted("dirComOrgApp:update") || subject.hasRole("Jedi") || subject.isPermitted("universe:zeone")) { em = DirectoryJPAProviderConsumer.getInstance().getDirectoryJpaProvider().createEM(); Application entity = findApplicationById(em, id); if (entity != null) { try { em.getTransaction().begin(); entity.setColorCode(colorCode); em.flush(); em.getTransaction().commit(); em.close(); return Response.status(Status.OK).entity("Application " + id + " has been successfully updated with color code " + colorCode).build(); } catch (Throwable t) { if(em.getTransaction().isActive()) em.getTransaction().rollback(); em.close(); return Response.status(Status.INTERNAL_SERVER_ERROR).entity("Throwable raised while updating application " + entity.getName() + " : " + t.getMessage()).build(); } } else { return Response.status(Status.NOT_FOUND).build(); } } else { return Response.status(Status.UNAUTHORIZED).entity("You're not authorized to update applications. Contact your administrator.").build(); } } else { return Response.status(Status.INTERNAL_SERVER_ERROR).entity("Request error: id and/or colorCode are not defined. You must define these parameters.").build(); } } @GET @Path("/update/company") public Response updateApplicationCompany(@QueryParam("id")Long id, @QueryParam("companyID")Long companyID) { if (id!=0 && companyID!=null) { Subject subject = SecurityUtils.getSubject(); log.debug("[{}-{}] update application {} company : {}", new Object[]{Thread.currentThread().getId(), subject.getPrincipal(), id, companyID}); if (subject.hasRole("orgadmin") || subject.isPermitted("dirComOrgApp:update") || subject.hasRole("Jedi") || subject.isPermitted("universe:zeone")) { em = DirectoryJPAProviderConsumer.getInstance().getDirectoryJpaProvider().createEM(); Application entity = findApplicationById(em, id); if (entity != null) { Company company = CompanyEndpoint.findCompanyById(em, companyID); if (company != null) { try { em.getTransaction().begin(); if (entity.getCompany()!=null) entity.getCompany().getApplications().remove(entity); entity.setCompany(company); company.getApplications().add(entity); em.flush(); em.getTransaction().commit(); em.close(); return Response.status(Status.OK).entity("Application " + id + " has been successfully updated with company " + companyID).build(); } catch (Throwable t) { if(em.getTransaction().isActive()) em.getTransaction().rollback(); em.close(); return Response.status(Status.INTERNAL_SERVER_ERROR).entity("Throwable raised while updating application " + entity.getName() + " : " + t.getMessage()).build(); } } else { return Response.status(Status.NOT_FOUND).entity("Company " + companyID + " not found.").build(); } } else { return Response.status(Status.NOT_FOUND).entity("Application " + id + " not found.").build(); } } else { return Response.status(Status.UNAUTHORIZED).entity("You're not authorized to update applications. Contact your administrator.").build(); } } else { return Response.status(Status.INTERNAL_SERVER_ERROR).entity("Request error: id and/or companyID are not defined. You must define these parameters.").build(); } } @GET @Path("/update/team") public Response updateApplicationTeam(@QueryParam("id")Long id, @QueryParam("teamID")Long teamID) { if (id!=0 && teamID!=null) { Subject subject = SecurityUtils.getSubject(); log.debug("[{}-{}] update application {} team : {}", new Object[]{Thread.currentThread().getId(), subject.getPrincipal(), id, teamID}); if (subject.hasRole("orgadmin") || subject.isPermitted("dirComOrgApp:update") || subject.hasRole("Jedi") || subject.isPermitted("universe:zeone")) { em = DirectoryJPAProviderConsumer.getInstance().getDirectoryJpaProvider().createEM(); Application entity = findApplicationById(em, id); if (entity != null) { Team team = TeamEndpoint.findTeamById(em, teamID); if (team != null) { try { em.getTransaction().begin(); entity.getTeam().getApplications().remove(entity); entity.setTeam(team); team.getApplications().add(entity); em.flush(); em.getTransaction().commit(); em.close(); return Response.status(Status.OK).entity("Application " + id + " has been successfully updated with team " + teamID).build(); } catch (Throwable t) { if(em.getTransaction().isActive()) em.getTransaction().rollback(); em.close(); return Response.status(Status.INTERNAL_SERVER_ERROR).entity("Throwable raised while updating application " + entity.getName() + " : " + t.getMessage()).build(); } } else { return Response.status(Status.NOT_FOUND).entity("Team " + teamID + " not found.").build(); } } else { return Response.status(Status.NOT_FOUND).entity("Application " + id + " not found.").build(); } } else { return Response.status(Status.UNAUTHORIZED).entity("You're not authorized to update applications. Contact your administrator.").build(); } } else { return Response.status(Status.INTERNAL_SERVER_ERROR).entity("Request error: id and/or teamID are not defined. You must define these parameters.").build(); } } @GET @Path("/update/osinstances/add") public Response updateApplicationAddOSInstance(@QueryParam("id")Long id, @QueryParam("osiID")Long osiID) { if (id!=0 && osiID!=null) { Subject subject = SecurityUtils.getSubject(); log.debug("[{}-{}] update application {} by adding os instance : {}", new Object[]{Thread.currentThread().getId(), subject.getPrincipal(), id, osiID}); if (subject.hasRole("orgadmin") || subject.isPermitted("dirComOrgApp:update") || subject.hasRole("Jedi") || subject.isPermitted("universe:zeone")) { em = DirectoryJPAProviderConsumer.getInstance().getDirectoryJpaProvider().createEM(); Application entity = findApplicationById(em, id); if (entity != null) { OSInstance osInstance = OSInstanceEndpoint.findOSInstanceById(em, osiID); if (osInstance != null) { try { em.getTransaction().begin(); entity.getOsInstances().add(osInstance); osInstance.getApplications().add(entity); em.flush(); em.getTransaction().commit(); em.close(); return Response.status(Status.OK).entity("Application " + id + " has been suessfully updated by adding os instance " + osiID).build(); } catch (Throwable t) { if(em.getTransaction().isActive()) em.getTransaction().rollback(); em.close(); return Response.status(Status.INTERNAL_SERVER_ERROR).entity("Throwable raised while updating application " + entity.getName() + " : " + t.getMessage()).build(); } } else { return Response.status(Status.NOT_FOUND).entity("OS Instance " + osiID + " not found.").build(); } } else { return Response.status(Status.NOT_FOUND).entity("Application " + id + " not found.").build(); } } else { return Response.status(Status.UNAUTHORIZED).entity("You're not authorized to update applications. Contact your administrator.").build(); } } else { return Response.status(Status.INTERNAL_SERVER_ERROR).entity("Request error: id and/or teamID are not defined. You must define these parameters.").build(); } } @GET @Path("/update/osinstances/delete") public Response updateApplicationDeleteOSInstance(@QueryParam("id")Long id, @QueryParam("osiID")Long osiID) { if (id!=0 && osiID!=null) { Subject subject = SecurityUtils.getSubject(); log.debug("[{}-{}] update application {} by adding os instance : {}", new Object[]{Thread.currentThread().getId(), subject.getPrincipal(), id, osiID}); if (subject.hasRole("orgadmin") || subject.isPermitted("dirComOrgApp:update") || subject.hasRole("Jedi") || subject.isPermitted("universe:zeone")) { em = DirectoryJPAProviderConsumer.getInstance().getDirectoryJpaProvider().createEM(); Application entity = findApplicationById(em, id); if (entity != null) { OSInstance osInstance = OSInstanceEndpoint.findOSInstanceById(em, osiID); if (osInstance != null) { try { em.getTransaction().begin(); entity.getOsInstances().remove(osInstance); osInstance.getApplications().remove(entity); em.flush(); em.getTransaction().commit(); em.close(); return Response.status(Status.OK).entity("Application " + id + " has been suessfully updated by adding os instance " + osiID).build(); } catch (Throwable t) { if(em.getTransaction().isActive()) em.getTransaction().rollback(); em.close(); return Response.status(Status.INTERNAL_SERVER_ERROR).entity("Throwable raised while updating application " + entity.getName() + " : " + t.getMessage()).build(); } } else { return Response.status(Status.NOT_FOUND).entity("OS Instance " + osiID + " not found.").build(); } } else { return Response.status(Status.NOT_FOUND).entity("Application " + id + " not found.").build(); } } else { return Response.status(Status.UNAUTHORIZED).entity("You're not authorized to update applications. Contact your administrator.").build(); } } else { return Response.status(Status.INTERNAL_SERVER_ERROR).entity("Request error: id and/or teamID are not defined. You must define these parameters.").build(); } } }
[ACC-200] improve application post
wat/src/main/java/net/echinopsii/ariane/community/core/directory/wat/rest/organisational/ApplicationEndpoint.java
[ACC-200] improve application post
<ide><path>at/src/main/java/net/echinopsii/ariane/community/core/directory/wat/rest/organisational/ApplicationEndpoint.java <ide> import net.echinopsii.ariane.community.core.directory.base.json.ds.organisational.ApplicationJSON; <ide> import net.echinopsii.ariane.community.core.directory.wat.plugin.DirectoryJPAProviderConsumer; <ide> import net.echinopsii.ariane.community.core.directory.base.model.organisational.Application; <add>import net.echinopsii.ariane.community.core.directory.wat.rest.CommonRestResponse; <ide> import net.echinopsii.ariane.community.core.directory.wat.rest.technical.system.OSInstanceEndpoint; <ide> import org.apache.shiro.SecurityUtils; <ide> import org.apache.shiro.subject.Subject; <ide> return entity; <ide> } <ide> <del> public static Application jsonFriendlyToHibernateFriendly(EntityManager em, JSONFriendlyApplication jsonFriendlyApplication) { <add> public static CommonRestResponse jsonFriendlyToHibernateFriendly(EntityManager em, JSONFriendlyApplication jsonFriendlyApplication) { <ide> Application entity = null; <del> <del> if(jsonFriendlyApplication.getApplicationID() != 0) { <add> CommonRestResponse commonRestResponse = new CommonRestResponse(); <add> <add> if(jsonFriendlyApplication.getApplicationID() !=0) <ide> entity = findApplicationById(em, jsonFriendlyApplication.getApplicationID()); <del> if(entity != null) { <del> if (jsonFriendlyApplication.getApplicationName() !=null) { <del> entity.setName(jsonFriendlyApplication.getApplicationName()); <del> } <del> if (jsonFriendlyApplication.getApplicationShortName() != null) { <del> entity.setShortName(jsonFriendlyApplication.getApplicationShortName()); <del> } <del> if (jsonFriendlyApplication.getApplicationColorCode() != null) { <del> entity.setColorCode(jsonFriendlyApplication.getApplicationColorCode()); <del> } <del> if (jsonFriendlyApplication.getApplicationDescription() != null) { <del> entity.setDescription(jsonFriendlyApplication.getApplicationDescription()); <del> } <del> if (jsonFriendlyApplication.getApplicationCompanyID() != 0) { <del> Company company = CompanyEndpoint.findCompanyById(em, jsonFriendlyApplication.getApplicationCompanyID()); <del> if (company != null) { <del> if (entity.getCompany() != null) <del> entity.getCompany().getApplications().remove(entity); <del> entity.setCompany(company); <del> company.getApplications().add(entity); <del> } <del> } <del> if (jsonFriendlyApplication.getApplicationTeamID() != 0) { <del> Team team = TeamEndpoint.findTeamById(em, jsonFriendlyApplication.getApplicationTeamID()); <del> if (team != null) { <del> if (entity.getTeam() != null) <del> entity.getTeam().getApplications().remove(entity); <del> entity.setTeam(team); <del> team.getApplications().add(entity); <del> } <del> } <del> if(jsonFriendlyApplication.getApplicationOSInstancesID() != null) { <del> if (!jsonFriendlyApplication.getApplicationOSInstancesID().isEmpty()) { <del> for (OSInstance osInstance : entity.getOsInstances()) { <del> if (!jsonFriendlyApplication.getApplicationOSInstancesID().contains(osInstance.getId())) { <del> entity.getOsInstances().remove(osInstance); <del> osInstance.getApplications().remove(entity); <add> if(entity == null){ <add> if(jsonFriendlyApplication.getApplicationName() != null){ <add> entity = findApplicationByName(em, jsonFriendlyApplication.getApplicationName()); <add> } <add> } <add> if(entity != null) { <add> if (jsonFriendlyApplication.getApplicationName() !=null) { <add> entity.setName(jsonFriendlyApplication.getApplicationName()); <add> } <add> if (jsonFriendlyApplication.getApplicationShortName() != null) { <add> entity.setShortName(jsonFriendlyApplication.getApplicationShortName()); <add> } <add> if (jsonFriendlyApplication.getApplicationColorCode() != null) { <add> entity.setColorCode(jsonFriendlyApplication.getApplicationColorCode()); <add> } <add> if (jsonFriendlyApplication.getApplicationDescription() != null) { <add> entity.setDescription(jsonFriendlyApplication.getApplicationDescription()); <add> } <add> if (jsonFriendlyApplication.getApplicationCompanyID() != 0) { <add> Company company = CompanyEndpoint.findCompanyById(em, jsonFriendlyApplication.getApplicationCompanyID()); <add> if (company != null) { <add> if (entity.getCompany() != null) <add> entity.getCompany().getApplications().remove(entity); <add> entity.setCompany(company); <add> company.getApplications().add(entity); <add> } <add> } <add> if (jsonFriendlyApplication.getApplicationTeamID() != 0) { <add> Team team = TeamEndpoint.findTeamById(em, jsonFriendlyApplication.getApplicationTeamID()); <add> if (team != null) { <add> if (entity.getTeam() != null) <add> entity.getTeam().getApplications().remove(entity); <add> entity.setTeam(team); <add> team.getApplications().add(entity); <add> } <add> } <add> if(jsonFriendlyApplication.getApplicationOSInstancesID() != null) { <add> if (!jsonFriendlyApplication.getApplicationOSInstancesID().isEmpty()) { <add> for (OSInstance osInstance : entity.getOsInstances()) { <add> if (!jsonFriendlyApplication.getApplicationOSInstancesID().contains(osInstance.getId())) { <add> entity.getOsInstances().remove(osInstance); <add> osInstance.getApplications().remove(entity); <add> } <add> } <add> for (Long osiId : jsonFriendlyApplication.getApplicationOSInstancesID()) { <add> OSInstance osInstance = OSInstanceEndpoint.findOSInstanceById(em, osiId); <add> if (osInstance != null) { <add> if (!entity.getOsInstances().contains(osInstance)) { <add> entity.getOsInstances().add(osInstance); <add> osInstance.getApplications().add(entity); <ide> } <add> } else { <add> commonRestResponse.setErrorMessage("Fail to update Application. Reason : provided OS Instance ID " + osiId +" was not found."); <add> return commonRestResponse; <ide> } <del> for (Long osiId : jsonFriendlyApplication.getApplicationOSInstancesID()) { <del> OSInstance osInstance = OSInstanceEndpoint.findOSInstanceById(em, osiId); <del> if (osInstance != null) { <del> if (!entity.getOsInstances().contains(osInstance)) { <del> entity.getOsInstances().add(osInstance); <del> osInstance.getApplications().add(entity); <del> } <add> } <add> } else { <add> for (OSInstance osInstance: entity.getOsInstances()) { <add> entity.getOsInstances().remove(osInstance); <add> osInstance.getApplications().remove(entity); <add> } <add> } <add> } <add> commonRestResponse.setDeserialiedObject(entity); <add> } else { <add> entity = new Application(); <add> entity.setNameR(jsonFriendlyApplication.getApplicationName()).setShortNameR(jsonFriendlyApplication.getApplicationShortName()) <add> .setColorCodeR(jsonFriendlyApplication.getApplicationColorCode()).setDescription(jsonFriendlyApplication.getApplicationDescription()); <add> if (jsonFriendlyApplication.getApplicationCompanyID() != 0) { <add> Company company = CompanyEndpoint.findCompanyById(em, jsonFriendlyApplication.getApplicationCompanyID()); <add> if (company != null) { <add> if (entity.getCompany() != null) <add> entity.getCompany().getApplications().remove(entity); <add> entity.setCompany(company); <add> company.getApplications().add(entity); <add> } else { <add> commonRestResponse.setErrorMessage("Fail to create Application. Reason : provided Company ID " + jsonFriendlyApplication.getApplicationCompanyID() +" was not found."); <add> return commonRestResponse; <add> } <add> } <add> <add> if (jsonFriendlyApplication.getApplicationTeamID() != 0) { <add> Team team = TeamEndpoint.findTeamById(em, jsonFriendlyApplication.getApplicationTeamID()); <add> if (team != null) { <add> if (entity.getTeam() != null) <add> entity.getTeam().getApplications().remove(entity); <add> entity.setTeam(team); <add> team.getApplications().add(entity); <add> } else { <add> commonRestResponse.setErrorMessage("Fail to create Application. Reason : provided Team ID " + jsonFriendlyApplication.getApplicationTeamID() +" was not found."); <add> return commonRestResponse; <add> } <add> } <add> <add> if(jsonFriendlyApplication.getApplicationOSInstancesID() != null) { <add> if (!jsonFriendlyApplication.getApplicationOSInstancesID().isEmpty()) { <add> for (Long osiId : jsonFriendlyApplication.getApplicationOSInstancesID()) { <add> OSInstance osInstance = OSInstanceEndpoint.findOSInstanceById(em, osiId); <add> if (osInstance != null) { <add> if (!entity.getOsInstances().contains(osInstance)) { <add> entity.getOsInstances().add(osInstance); <add> osInstance.getApplications().add(entity); <ide> } <add> } else { <add> commonRestResponse.setErrorMessage("Fail to update Application. Reason : provided OS Instance ID " + osiId + " was not found."); <add> return commonRestResponse; <ide> } <ide> } <ide> } <del> } else { <del> log.error("Request error: Failed to update Application, unable to lookup provided Application Id."); <del> } <del> } else { <del> entity = findApplicationByName(em, jsonFriendlyApplication.getApplicationName()); <del> if(jsonFriendlyApplication.getApplicationName()!=null && jsonFriendlyApplication.getApplicationShortName()!=null <del> && jsonFriendlyApplication.getApplicationColorCode()!=null){ <del> if(entity == null) { <del> entity = new Application(); <del> entity.setNameR(jsonFriendlyApplication.getApplicationName()).setShortNameR(jsonFriendlyApplication.getApplicationShortName()) <del> .setColorCodeR(jsonFriendlyApplication.getApplicationColorCode()).setDescription(jsonFriendlyApplication.getApplicationDescription()); <del> } <del> } else { <del> log.error("Request error: name and/or short name and/or color code are not defined. You must define these parameters."); <del> } <del> } <del> return entity; <add> } <add> commonRestResponse.setDeserialiedObject(entity); <add> } <add> return commonRestResponse; <ide> } <ide> <ide> @GET <ide> subject.hasRole("Jedi") || subject.isPermitted("universe:zeone")) { <ide> em = DirectoryJPAProviderConsumer.getInstance().getDirectoryJpaProvider().createEM(); <ide> JSONFriendlyApplication jsonFriendlyApplication = ApplicationJSON.JSON2Application(payload); <del> Application entity = jsonFriendlyToHibernateFriendly(em, jsonFriendlyApplication); <add> CommonRestResponse commonRestResponse = jsonFriendlyToHibernateFriendly(em, jsonFriendlyApplication); <add> Application entity = (Application) commonRestResponse.getDeserialiedObject(); <ide> if (entity != null) { <ide> try { <ide> em.getTransaction().begin(); <ide> return Response.status(Status.INTERNAL_SERVER_ERROR).entity("Throwable raised while creating application " + payload + " : " + t.getMessage()).build(); <ide> } <ide> } else{ <del> return Response.status(Status.INTERNAL_SERVER_ERROR).entity("Check server logs to know more.").build(); <add> return Response.status(Status.INTERNAL_SERVER_ERROR).entity(commonRestResponse.getErrorMessage()).build(); <ide> } <ide> } else { <ide> return Response.status(Status.UNAUTHORIZED).entity("You're not authorized to create applications. Contact your administrator.").build();
Java
apache-2.0
0c733e14256715e64003a47aa75083c47c781208
0
cnoldtree/netty,tbrooks8/netty,louxiu/netty,luyiisme/netty,mx657649013/netty,carl-mastrangelo/netty,gerdriesselmann/netty,ejona86/netty,zer0se7en/netty,NiteshKant/netty,artgon/netty,Techcable/netty,johnou/netty,blucas/netty,Apache9/netty,idelpivnitskiy/netty,jongyeol/netty,netty/netty,mx657649013/netty,blucas/netty,ichaki5748/netty,doom369/netty,mx657649013/netty,Apache9/netty,skyao/netty,netty/netty,joansmith/netty,cnoldtree/netty,Scottmitch/netty,mcobrien/netty,golovnin/netty,blucas/netty,Scottmitch/netty,NiteshKant/netty,skyao/netty,idelpivnitskiy/netty,ichaki5748/netty,johnou/netty,kiril-me/netty,zer0se7en/netty,doom369/netty,ngocdaothanh/netty,fenik17/netty,Spikhalskiy/netty,joansmith/netty,jongyeol/netty,andsel/netty,skyao/netty,jchambers/netty,netty/netty,fenik17/netty,jchambers/netty,idelpivnitskiy/netty,KatsuraKKKK/netty,mikkokar/netty,Squarespace/netty,ichaki5748/netty,yrcourage/netty,netty/netty,Scottmitch/netty,ngocdaothanh/netty,jchambers/netty,SinaTadayon/netty,NiteshKant/netty,KatsuraKKKK/netty,skyao/netty,kiril-me/netty,s-gheldd/netty,carl-mastrangelo/netty,ichaki5748/netty,andsel/netty,NiteshKant/netty,golovnin/netty,KatsuraKKKK/netty,carl-mastrangelo/netty,luyiisme/netty,luyiisme/netty,johnou/netty,ngocdaothanh/netty,fengjiachun/netty,artgon/netty,mcobrien/netty,ejona86/netty,tbrooks8/netty,mx657649013/netty,fenik17/netty,fengjiachun/netty,jongyeol/netty,jongyeol/netty,Apache9/netty,joansmith/netty,luyiisme/netty,louxiu/netty,louxiu/netty,fengjiachun/netty,Scottmitch/netty,Apache9/netty,cnoldtree/netty,s-gheldd/netty,doom369/netty,golovnin/netty,carl-mastrangelo/netty,s-gheldd/netty,zer0se7en/netty,ngocdaothanh/netty,golovnin/netty,mcobrien/netty,bryce-anderson/netty,Spikhalskiy/netty,maliqq/netty,johnou/netty,tbrooks8/netty,mcobrien/netty,Spikhalskiy/netty,gerdriesselmann/netty,KatsuraKKKK/netty,maliqq/netty,KatsuraKKKK/netty,SinaTadayon/netty,bryce-anderson/netty,yrcourage/netty,artgon/netty,yrcourage/netty,zer0se7en/netty,fenik17/netty,tbrooks8/netty,doom369/netty,windie/netty,ejona86/netty,Squarespace/netty,golovnin/netty,Techcable/netty,mcobrien/netty,jchambers/netty,bryce-anderson/netty,ngocdaothanh/netty,ejona86/netty,blucas/netty,zer0se7en/netty,jongyeol/netty,Squarespace/netty,bryce-anderson/netty,cnoldtree/netty,s-gheldd/netty,mikkokar/netty,Apache9/netty,kiril-me/netty,SinaTadayon/netty,s-gheldd/netty,netty/netty,mikkokar/netty,carl-mastrangelo/netty,fengjiachun/netty,windie/netty,Techcable/netty,maliqq/netty,windie/netty,gerdriesselmann/netty,windie/netty,artgon/netty,Spikhalskiy/netty,johnou/netty,kiril-me/netty,kiril-me/netty,louxiu/netty,louxiu/netty,andsel/netty,fengjiachun/netty,tbrooks8/netty,mx657649013/netty,andsel/netty,idelpivnitskiy/netty,SinaTadayon/netty,andsel/netty,mikkokar/netty,maliqq/netty,fenik17/netty,Spikhalskiy/netty,Squarespace/netty,yrcourage/netty,Scottmitch/netty,luyiisme/netty,mikkokar/netty,bryce-anderson/netty,gerdriesselmann/netty,joansmith/netty,yrcourage/netty,doom369/netty,Techcable/netty,ichaki5748/netty,idelpivnitskiy/netty,cnoldtree/netty,blucas/netty,Techcable/netty,joansmith/netty,windie/netty,ejona86/netty,artgon/netty,gerdriesselmann/netty,NiteshKant/netty,skyao/netty,SinaTadayon/netty,maliqq/netty,Squarespace/netty,jchambers/netty
/* * Copyright 2012 The Netty Project * * The Netty Project 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 io.netty.channel.nio; import io.netty.channel.Channel; import io.netty.channel.ChannelException; import io.netty.channel.EventLoopException; import io.netty.channel.SingleThreadEventLoop; import io.netty.util.internal.PlatformDependent; import io.netty.util.internal.SystemPropertyUtil; import io.netty.util.internal.logging.InternalLogger; import io.netty.util.internal.logging.InternalLoggerFactory; import java.io.IOException; import java.lang.reflect.Field; import java.nio.channels.CancelledKeyException; import java.nio.channels.SelectableChannel; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.spi.SelectorProvider; import java.util.ArrayList; import java.util.Collection; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.Queue; import java.util.Set; import java.util.concurrent.Executor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; /** * {@link SingleThreadEventLoop} implementation which register the {@link Channel}'s to a * {@link Selector} and so does the multi-plexing of these in the event loop. * */ public final class NioEventLoop extends SingleThreadEventLoop { private static final InternalLogger logger = InternalLoggerFactory.getInstance(NioEventLoop.class); private static final int CLEANUP_INTERVAL = 256; // XXX Hard-coded value, but won't need customization. private static final boolean DISABLE_KEYSET_OPTIMIZATION = SystemPropertyUtil.getBoolean("io.netty.noKeySetOptimization", false); private static final int MIN_PREMATURE_SELECTOR_RETURNS = 3; private static final int SELECTOR_AUTO_REBUILD_THRESHOLD; // Workaround for JDK NIO bug. // // See: // - http://bugs.sun.com/view_bug.do?bug_id=6427854 // - https://github.com/netty/netty/issues/203 static { String key = "sun.nio.ch.bugLevel"; try { String buglevel = SystemPropertyUtil.get(key); if (buglevel == null) { System.setProperty(key, ""); } } catch (SecurityException e) { if (logger.isDebugEnabled()) { logger.debug("Unable to get/set System Property: {}", key, e); } } int selectorAutoRebuildThreshold = SystemPropertyUtil.getInt("io.netty.selectorAutoRebuildThreshold", 512); if (selectorAutoRebuildThreshold < MIN_PREMATURE_SELECTOR_RETURNS) { selectorAutoRebuildThreshold = 0; } SELECTOR_AUTO_REBUILD_THRESHOLD = selectorAutoRebuildThreshold; if (logger.isDebugEnabled()) { logger.debug("-Dio.netty.noKeySetOptimization: {}", DISABLE_KEYSET_OPTIMIZATION); logger.debug("-Dio.netty.selectorAutoRebuildThreshold: {}", SELECTOR_AUTO_REBUILD_THRESHOLD); } } /** * The NIO {@link Selector}. */ Selector selector; private SelectedSelectionKeySet selectedKeys; private final SelectorProvider provider; /** * Boolean that controls determines if a blocked Selector.select should * break out of its selection process. In our case we use a timeout for * the select method and the select method will block for that time unless * waken up. */ private final AtomicBoolean wakenUp = new AtomicBoolean(); private volatile int ioRatio = 50; private int cancelledKeys; private boolean needsToSelectAgain; NioEventLoop(NioEventLoopGroup parent, Executor executor, SelectorProvider selectorProvider) { super(parent, executor, false); if (selectorProvider == null) { throw new NullPointerException("selectorProvider"); } provider = selectorProvider; selector = openSelector(); } private Selector openSelector() { final Selector selector; try { selector = provider.openSelector(); } catch (IOException e) { throw new ChannelException("failed to open a new selector", e); } if (DISABLE_KEYSET_OPTIMIZATION) { return selector; } try { SelectedSelectionKeySet selectedKeySet = new SelectedSelectionKeySet(); Class<?> selectorImplClass = Class.forName("sun.nio.ch.SelectorImpl", false, PlatformDependent.getSystemClassLoader()); // Ensure the current selector implementation is what we can instrument. if (!selectorImplClass.isAssignableFrom(selector.getClass())) { return selector; } Field selectedKeysField = selectorImplClass.getDeclaredField("selectedKeys"); Field publicSelectedKeysField = selectorImplClass.getDeclaredField("publicSelectedKeys"); selectedKeysField.setAccessible(true); publicSelectedKeysField.setAccessible(true); selectedKeysField.set(selector, selectedKeySet); publicSelectedKeysField.set(selector, selectedKeySet); selectedKeys = selectedKeySet; logger.trace("Instrumented an optimized java.util.Set into: {}", selector); } catch (Throwable t) { selectedKeys = null; logger.trace("Failed to instrument an optimized java.util.Set into: {}", selector, t); } return selector; } @Override protected Queue<Runnable> newTaskQueue() { // This event loop never calls takeTask() return PlatformDependent.newMpscQueue(); } /** * Registers an arbitrary {@link SelectableChannel}, not necessarily created by Netty, to the {@link Selector} * of this event loop. Once the specified {@link SelectableChannel} is registered, the specified {@code task} will * be executed by this event loop when the {@link SelectableChannel} is ready. */ public void register(final SelectableChannel ch, final int interestOps, final NioTask<?> task) { if (ch == null) { throw new NullPointerException("ch"); } if (interestOps == 0) { throw new IllegalArgumentException("interestOps must be non-zero."); } if ((interestOps & ~ch.validOps()) != 0) { throw new IllegalArgumentException( "invalid interestOps: " + interestOps + "(validOps: " + ch.validOps() + ')'); } if (task == null) { throw new NullPointerException("task"); } if (isShutdown()) { throw new IllegalStateException("event loop shut down"); } try { ch.register(selector, interestOps, task); } catch (Exception e) { throw new EventLoopException("failed to register a channel", e); } } /** * Returns the percentage of the desired amount of time spent for I/O in the event loop. */ public int getIoRatio() { return ioRatio; } /** * Sets the percentage of the desired amount of time spent for I/O in the event loop. The default value is * {@code 50}, which means the event loop will try to spend the same amount of time for I/O as for non-I/O tasks. */ public void setIoRatio(int ioRatio) { if (ioRatio <= 0 || ioRatio > 100) { throw new IllegalArgumentException("ioRatio: " + ioRatio + " (expected: 0 < ioRatio <= 100)"); } this.ioRatio = ioRatio; } /** * Replaces the current {@link Selector} of this event loop with newly created {@link Selector}s to work * around the infamous epoll 100% CPU bug. */ public void rebuildSelector() { if (!inEventLoop()) { execute(new Runnable() { @Override public void run() { rebuildSelector(); } }); return; } final Selector oldSelector = selector; final Selector newSelector; if (oldSelector == null) { return; } try { newSelector = openSelector(); } catch (Exception e) { logger.warn("Failed to create a new Selector.", e); return; } // Register all channels to the new Selector. int nChannels = 0; for (;;) { try { for (SelectionKey key: oldSelector.keys()) { Object a = key.attachment(); try { if (!key.isValid() || key.channel().keyFor(newSelector) != null) { continue; } int interestOps = key.interestOps(); key.cancel(); SelectionKey newKey = key.channel().register(newSelector, interestOps, a); if (a instanceof AbstractNioChannel) { // Update SelectionKey ((AbstractNioChannel) a).selectionKey = newKey; } nChannels ++; } catch (Exception e) { logger.warn("Failed to re-register a Channel to the new Selector.", e); if (a instanceof AbstractNioChannel) { AbstractNioChannel ch = (AbstractNioChannel) a; ch.unsafe().close(ch.unsafe().voidPromise()); } else { @SuppressWarnings("unchecked") NioTask<SelectableChannel> task = (NioTask<SelectableChannel>) a; invokeChannelUnregistered(task, key, e); } } } } catch (ConcurrentModificationException e) { // Probably due to concurrent modification of the key set. continue; } break; } selector = newSelector; try { // time to close the old selector as everything else is registered to the new one oldSelector.close(); } catch (Throwable t) { if (logger.isWarnEnabled()) { logger.warn("Failed to close the old Selector.", t); } } logger.info("Migrated " + nChannels + " channel(s) to the new Selector."); } @Override protected void run() { for (;;) { boolean oldWakenUp = wakenUp.getAndSet(false); try { if (hasTasks()) { selectNow(); } else { select(oldWakenUp); // 'wakenUp.compareAndSet(false, true)' is always evaluated // before calling 'selector.wakeup()' to reduce the wake-up // overhead. (Selector.wakeup() is an expensive operation.) // // However, there is a race condition in this approach. // The race condition is triggered when 'wakenUp' is set to // true too early. // // 'wakenUp' is set to true too early if: // 1) Selector is waken up between 'wakenUp.set(false)' and // 'selector.select(...)'. (BAD) // 2) Selector is waken up between 'selector.select(...)' and // 'if (wakenUp.get()) { ... }'. (OK) // // In the first case, 'wakenUp' is set to true and the // following 'selector.select(...)' will wake up immediately. // Until 'wakenUp' is set to false again in the next round, // 'wakenUp.compareAndSet(false, true)' will fail, and therefore // any attempt to wake up the Selector will fail, too, causing // the following 'selector.select(...)' call to block // unnecessarily. // // To fix this problem, we wake up the selector again if wakenUp // is true immediately after selector.select(...). // It is inefficient in that it wakes up the selector for both // the first case (BAD - wake-up required) and the second case // (OK - no wake-up required). if (wakenUp.get()) { selector.wakeup(); } } cancelledKeys = 0; needsToSelectAgain = false; final int ioRatio = this.ioRatio; if (ioRatio == 100) { processSelectedKeys(); runAllTasks(); } else { final long ioStartTime = System.nanoTime(); processSelectedKeys(); final long ioTime = System.nanoTime() - ioStartTime; runAllTasks(ioTime * (100 - ioRatio) / ioRatio); } if (isShuttingDown()) { closeAll(); if (confirmShutdown()) { break; } } } catch (Throwable t) { logger.warn("Unexpected exception in the selector loop.", t); // Prevent possible consecutive immediate failures that lead to // excessive CPU consumption. try { Thread.sleep(1000); } catch (InterruptedException e) { // Ignore. } } } } private void processSelectedKeys() { if (selectedKeys != null) { processSelectedKeysOptimized(selectedKeys.flip()); } else { processSelectedKeysPlain(selector.selectedKeys()); } } @Override protected void cleanup() { try { selector.close(); } catch (IOException e) { logger.warn("Failed to close a selector.", e); } } void cancel(SelectionKey key) { key.cancel(); cancelledKeys ++; if (cancelledKeys >= CLEANUP_INTERVAL) { cancelledKeys = 0; needsToSelectAgain = true; } } @Override protected Runnable pollTask() { Runnable task = super.pollTask(); if (needsToSelectAgain) { selectAgain(); } return task; } private void processSelectedKeysPlain(Set<SelectionKey> selectedKeys) { // check if the set is empty and if so just return to not create garbage by // creating a new Iterator every time even if there is nothing to process. // See https://github.com/netty/netty/issues/597 if (selectedKeys.isEmpty()) { return; } Iterator<SelectionKey> i = selectedKeys.iterator(); for (;;) { final SelectionKey k = i.next(); final Object a = k.attachment(); i.remove(); if (a instanceof AbstractNioChannel) { processSelectedKey(k, (AbstractNioChannel) a); } else { @SuppressWarnings("unchecked") NioTask<SelectableChannel> task = (NioTask<SelectableChannel>) a; processSelectedKey(k, task); } if (!i.hasNext()) { break; } if (needsToSelectAgain) { selectAgain(); selectedKeys = selector.selectedKeys(); // Create the iterator again to avoid ConcurrentModificationException if (selectedKeys.isEmpty()) { break; } else { i = selectedKeys.iterator(); } } } } private void processSelectedKeysOptimized(SelectionKey[] selectedKeys) { for (int i = 0;; i ++) { final SelectionKey k = selectedKeys[i]; if (k == null) { break; } // null out entry in the array to allow to have it GC'ed once the Channel close // See https://github.com/netty/netty/issues/2363 selectedKeys[i] = null; final Object a = k.attachment(); if (a instanceof AbstractNioChannel) { processSelectedKey(k, (AbstractNioChannel) a); } else { @SuppressWarnings("unchecked") NioTask<SelectableChannel> task = (NioTask<SelectableChannel>) a; processSelectedKey(k, task); } if (needsToSelectAgain) { // null out entries in the array to allow to have it GC'ed once the Channel close // See https://github.com/netty/netty/issues/2363 for (;;) { i++; if (selectedKeys[i] == null) { break; } selectedKeys[i] = null; } selectAgain(); // Need to flip the optimized selectedKeys to get the right reference to the array // and reset the index to -1 which will then set to 0 on the for loop // to start over again. // // See https://github.com/netty/netty/issues/1523 selectedKeys = this.selectedKeys.flip(); i = -1; } } } private static void processSelectedKey(SelectionKey k, AbstractNioChannel ch) { final AbstractNioChannel.NioUnsafe unsafe = ch.unsafe(); if (!k.isValid()) { // close the channel if the key is not valid anymore unsafe.close(unsafe.voidPromise()); return; } try { int readyOps = k.readyOps(); // Also check for readOps of 0 to workaround possible JDK bug which may otherwise lead // to a spin loop if ((readyOps & (SelectionKey.OP_READ | SelectionKey.OP_ACCEPT)) != 0 || readyOps == 0) { unsafe.read(); if (!ch.isOpen()) { // Connection already closed - no need to handle write. return; } } if ((readyOps & SelectionKey.OP_WRITE) != 0) { // Call forceFlush which will also take care of clear the OP_WRITE once there is nothing left to write ch.unsafe().forceFlush(); } if ((readyOps & SelectionKey.OP_CONNECT) != 0) { // remove OP_CONNECT as otherwise Selector.select(..) will always return without blocking // See https://github.com/netty/netty/issues/924 int ops = k.interestOps(); ops &= ~SelectionKey.OP_CONNECT; k.interestOps(ops); unsafe.finishConnect(); } } catch (CancelledKeyException ignored) { unsafe.close(unsafe.voidPromise()); } } private static void processSelectedKey(SelectionKey k, NioTask<SelectableChannel> task) { int state = 0; try { task.channelReady(k.channel(), k); state = 1; } catch (Exception e) { k.cancel(); invokeChannelUnregistered(task, k, e); state = 2; } finally { switch (state) { case 0: k.cancel(); invokeChannelUnregistered(task, k, null); break; case 1: if (!k.isValid()) { // Cancelled by channelReady() invokeChannelUnregistered(task, k, null); } break; } } } private void closeAll() { selectAgain(); Set<SelectionKey> keys = selector.keys(); Collection<AbstractNioChannel> channels = new ArrayList<AbstractNioChannel>(keys.size()); for (SelectionKey k: keys) { Object a = k.attachment(); if (a instanceof AbstractNioChannel) { channels.add((AbstractNioChannel) a); } else { k.cancel(); @SuppressWarnings("unchecked") NioTask<SelectableChannel> task = (NioTask<SelectableChannel>) a; invokeChannelUnregistered(task, k, null); } } for (AbstractNioChannel ch: channels) { ch.unsafe().close(ch.unsafe().voidPromise()); } } private static void invokeChannelUnregistered(NioTask<SelectableChannel> task, SelectionKey k, Throwable cause) { try { task.channelUnregistered(k.channel(), cause); } catch (Exception e) { logger.warn("Unexpected exception while running NioTask.channelUnregistered()", e); } } @Override protected void wakeup(boolean inEventLoop) { if (!inEventLoop && wakenUp.compareAndSet(false, true)) { selector.wakeup(); } } void selectNow() throws IOException { try { selector.selectNow(); } finally { // restore wakup state if needed if (wakenUp.get()) { selector.wakeup(); } } } private void select(boolean oldWakenUp) throws IOException { Selector selector = this.selector; try { int selectCnt = 0; long currentTimeNanos = System.nanoTime(); long selectDeadLineNanos = currentTimeNanos + delayNanos(currentTimeNanos); for (;;) { long timeoutMillis = (selectDeadLineNanos - currentTimeNanos + 500000L) / 1000000L; if (timeoutMillis <= 0) { if (selectCnt == 0) { selector.selectNow(); selectCnt = 1; } break; } int selectedKeys = selector.select(timeoutMillis); selectCnt ++; if (selectedKeys != 0 || oldWakenUp || wakenUp.get() || hasTasks() || hasScheduledTasks()) { // - Selected something, // - waken up by user, or // - the task queue has a pending task. // - a scheduled task is ready for processing break; } if (Thread.interrupted()) { // Thread was interrupted so reset selected keys and break so we not run into a busy loop. // As this is most likely a bug in the handler of the user or it's client library we will // also log it. // // See https://github.com/netty/netty/issues/2426 if (logger.isDebugEnabled()) { logger.debug("Selector.select() returned prematurely because " + "Thread.currentThread().interrupt() was called. Use " + "NioEventLoop.shutdownGracefully() to shutdown the NioEventLoop."); } selectCnt = 1; break; } long time = System.nanoTime(); if (time - TimeUnit.MILLISECONDS.toNanos(timeoutMillis) >= currentTimeNanos) { // timeoutMillis elapsed without anything selected. selectCnt = 1; } else if (SELECTOR_AUTO_REBUILD_THRESHOLD > 0 && selectCnt >= SELECTOR_AUTO_REBUILD_THRESHOLD) { // The selector returned prematurely many times in a row. // Rebuild the selector to work around the problem. logger.warn( "Selector.select() returned prematurely {} times in a row; rebuilding selector.", selectCnt); rebuildSelector(); selector = this.selector; // Select again to populate selectedKeys. selector.selectNow(); selectCnt = 1; break; } currentTimeNanos = time; } if (selectCnt > MIN_PREMATURE_SELECTOR_RETURNS) { if (logger.isDebugEnabled()) { logger.debug("Selector.select() returned prematurely {} times in a row.", selectCnt - 1); } } } catch (CancelledKeyException e) { if (logger.isDebugEnabled()) { logger.debug(CancelledKeyException.class.getSimpleName() + " raised by a Selector - JDK bug?", e); } // Harmless exception - log anyway } } private void selectAgain() { needsToSelectAgain = false; try { selector.selectNow(); } catch (Throwable t) { logger.warn("Failed to update SelectionKeys.", t); } } }
transport/src/main/java/io/netty/channel/nio/NioEventLoop.java
/* * Copyright 2012 The Netty Project * * The Netty Project 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 io.netty.channel.nio; import io.netty.channel.Channel; import io.netty.channel.ChannelException; import io.netty.channel.EventLoopException; import io.netty.channel.SingleThreadEventLoop; import io.netty.util.internal.PlatformDependent; import io.netty.util.internal.SystemPropertyUtil; import io.netty.util.internal.logging.InternalLogger; import io.netty.util.internal.logging.InternalLoggerFactory; import java.io.IOException; import java.lang.reflect.Field; import java.nio.channels.CancelledKeyException; import java.nio.channels.SelectableChannel; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.spi.SelectorProvider; import java.util.ArrayList; import java.util.Collection; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.Queue; import java.util.Set; import java.util.concurrent.Executor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; /** * {@link SingleThreadEventLoop} implementation which register the {@link Channel}'s to a * {@link Selector} and so does the multi-plexing of these in the event loop. * */ public final class NioEventLoop extends SingleThreadEventLoop { private static final InternalLogger logger = InternalLoggerFactory.getInstance(NioEventLoop.class); private static final int CLEANUP_INTERVAL = 256; // XXX Hard-coded value, but won't need customization. private static final boolean DISABLE_KEYSET_OPTIMIZATION = SystemPropertyUtil.getBoolean("io.netty.noKeySetOptimization", false); private static final int MIN_PREMATURE_SELECTOR_RETURNS = 3; private static final int SELECTOR_AUTO_REBUILD_THRESHOLD; // Workaround for JDK NIO bug. // // See: // - http://bugs.sun.com/view_bug.do?bug_id=6427854 // - https://github.com/netty/netty/issues/203 static { String key = "sun.nio.ch.bugLevel"; try { String buglevel = SystemPropertyUtil.get(key); if (buglevel == null) { System.setProperty(key, ""); } } catch (SecurityException e) { if (logger.isDebugEnabled()) { logger.debug("Unable to get/set System Property: {}", key, e); } } int selectorAutoRebuildThreshold = SystemPropertyUtil.getInt("io.netty.selectorAutoRebuildThreshold", 512); if (selectorAutoRebuildThreshold < MIN_PREMATURE_SELECTOR_RETURNS) { selectorAutoRebuildThreshold = 0; } SELECTOR_AUTO_REBUILD_THRESHOLD = selectorAutoRebuildThreshold; if (logger.isDebugEnabled()) { logger.debug("-Dio.netty.noKeySetOptimization: {}", DISABLE_KEYSET_OPTIMIZATION); logger.debug("-Dio.netty.selectorAutoRebuildThreshold: {}", SELECTOR_AUTO_REBUILD_THRESHOLD); } } /** * The NIO {@link Selector}. */ Selector selector; private SelectedSelectionKeySet selectedKeys; private final SelectorProvider provider; /** * Boolean that controls determines if a blocked Selector.select should * break out of its selection process. In our case we use a timeout for * the select method and the select method will block for that time unless * waken up. */ private final AtomicBoolean wakenUp = new AtomicBoolean(); private volatile int ioRatio = 50; private int cancelledKeys; private boolean needsToSelectAgain; NioEventLoop(NioEventLoopGroup parent, Executor executor, SelectorProvider selectorProvider) { super(parent, executor, false); if (selectorProvider == null) { throw new NullPointerException("selectorProvider"); } provider = selectorProvider; selector = openSelector(); } private Selector openSelector() { final Selector selector; try { selector = provider.openSelector(); } catch (IOException e) { throw new ChannelException("failed to open a new selector", e); } if (DISABLE_KEYSET_OPTIMIZATION) { return selector; } try { SelectedSelectionKeySet selectedKeySet = new SelectedSelectionKeySet(); Class<?> selectorImplClass = Class.forName("sun.nio.ch.SelectorImpl", false, PlatformDependent.getSystemClassLoader()); // Ensure the current selector implementation is what we can instrument. if (!selectorImplClass.isAssignableFrom(selector.getClass())) { return selector; } Field selectedKeysField = selectorImplClass.getDeclaredField("selectedKeys"); Field publicSelectedKeysField = selectorImplClass.getDeclaredField("publicSelectedKeys"); selectedKeysField.setAccessible(true); publicSelectedKeysField.setAccessible(true); selectedKeysField.set(selector, selectedKeySet); publicSelectedKeysField.set(selector, selectedKeySet); selectedKeys = selectedKeySet; logger.trace("Instrumented an optimized java.util.Set into: {}", selector); } catch (Throwable t) { selectedKeys = null; logger.trace("Failed to instrument an optimized java.util.Set into: {}", selector, t); } return selector; } @Override protected Queue<Runnable> newTaskQueue() { // This event loop never calls takeTask() return PlatformDependent.newMpscQueue(); } /** * Registers an arbitrary {@link SelectableChannel}, not necessarily created by Netty, to the {@link Selector} * of this event loop. Once the specified {@link SelectableChannel} is registered, the specified {@code task} will * be executed by this event loop when the {@link SelectableChannel} is ready. */ public void register(final SelectableChannel ch, final int interestOps, final NioTask<?> task) { if (ch == null) { throw new NullPointerException("ch"); } if (interestOps == 0) { throw new IllegalArgumentException("interestOps must be non-zero."); } if ((interestOps & ~ch.validOps()) != 0) { throw new IllegalArgumentException( "invalid interestOps: " + interestOps + "(validOps: " + ch.validOps() + ')'); } if (task == null) { throw new NullPointerException("task"); } if (isShutdown()) { throw new IllegalStateException("event loop shut down"); } try { ch.register(selector, interestOps, task); } catch (Exception e) { throw new EventLoopException("failed to register a channel", e); } } /** * Returns the percentage of the desired amount of time spent for I/O in the event loop. */ public int getIoRatio() { return ioRatio; } /** * Sets the percentage of the desired amount of time spent for I/O in the event loop. The default value is * {@code 50}, which means the event loop will try to spend the same amount of time for I/O as for non-I/O tasks. */ public void setIoRatio(int ioRatio) { if (ioRatio <= 0 || ioRatio > 100) { throw new IllegalArgumentException("ioRatio: " + ioRatio + " (expected: 0 < ioRatio <= 100)"); } this.ioRatio = ioRatio; } /** * Replaces the current {@link Selector} of this event loop with newly created {@link Selector}s to work * around the infamous epoll 100% CPU bug. */ public void rebuildSelector() { if (!inEventLoop()) { execute(new Runnable() { @Override public void run() { rebuildSelector(); } }); return; } final Selector oldSelector = selector; final Selector newSelector; if (oldSelector == null) { return; } try { newSelector = openSelector(); } catch (Exception e) { logger.warn("Failed to create a new Selector.", e); return; } // Register all channels to the new Selector. int nChannels = 0; for (;;) { try { for (SelectionKey key: oldSelector.keys()) { Object a = key.attachment(); try { if (!key.isValid() || key.channel().keyFor(newSelector) != null) { continue; } int interestOps = key.interestOps(); key.cancel(); SelectionKey newKey = key.channel().register(newSelector, interestOps, a); if (a instanceof AbstractNioChannel) { // Update SelectionKey ((AbstractNioChannel) a).selectionKey = newKey; } nChannels ++; } catch (Exception e) { logger.warn("Failed to re-register a Channel to the new Selector.", e); if (a instanceof AbstractNioChannel) { AbstractNioChannel ch = (AbstractNioChannel) a; ch.unsafe().close(ch.unsafe().voidPromise()); } else { @SuppressWarnings("unchecked") NioTask<SelectableChannel> task = (NioTask<SelectableChannel>) a; invokeChannelUnregistered(task, key, e); } } } } catch (ConcurrentModificationException e) { // Probably due to concurrent modification of the key set. continue; } break; } selector = newSelector; try { // time to close the old selector as everything else is registered to the new one oldSelector.close(); } catch (Throwable t) { if (logger.isWarnEnabled()) { logger.warn("Failed to close the old Selector.", t); } } logger.info("Migrated " + nChannels + " channel(s) to the new Selector."); } @Override protected void run() { for (;;) { boolean oldWakenUp = wakenUp.getAndSet(false); try { if (hasTasks()) { selectNow(); } else { select(oldWakenUp); // 'wakenUp.compareAndSet(false, true)' is always evaluated // before calling 'selector.wakeup()' to reduce the wake-up // overhead. (Selector.wakeup() is an expensive operation.) // // However, there is a race condition in this approach. // The race condition is triggered when 'wakenUp' is set to // true too early. // // 'wakenUp' is set to true too early if: // 1) Selector is waken up between 'wakenUp.set(false)' and // 'selector.select(...)'. (BAD) // 2) Selector is waken up between 'selector.select(...)' and // 'if (wakenUp.get()) { ... }'. (OK) // // In the first case, 'wakenUp' is set to true and the // following 'selector.select(...)' will wake up immediately. // Until 'wakenUp' is set to false again in the next round, // 'wakenUp.compareAndSet(false, true)' will fail, and therefore // any attempt to wake up the Selector will fail, too, causing // the following 'selector.select(...)' call to block // unnecessarily. // // To fix this problem, we wake up the selector again if wakenUp // is true immediately after selector.select(...). // It is inefficient in that it wakes up the selector for both // the first case (BAD - wake-up required) and the second case // (OK - no wake-up required). if (wakenUp.get()) { selector.wakeup(); } } cancelledKeys = 0; needsToSelectAgain = false; final int ioRatio = this.ioRatio; if (ioRatio == 100) { processSelectedKeys(); runAllTasks(); } else { final long ioStartTime = System.nanoTime(); processSelectedKeys(); final long ioTime = System.nanoTime() - ioStartTime; runAllTasks(ioTime * (100 - ioRatio) / ioRatio); } if (isShuttingDown()) { closeAll(); if (confirmShutdown()) { break; } } } catch (Throwable t) { logger.warn("Unexpected exception in the selector loop.", t); // Prevent possible consecutive immediate failures that lead to // excessive CPU consumption. try { Thread.sleep(1000); } catch (InterruptedException e) { // Ignore. } } } } private void processSelectedKeys() { if (selectedKeys != null) { processSelectedKeysOptimized(selectedKeys.flip()); } else { processSelectedKeysPlain(selector.selectedKeys()); } } @Override protected void cleanup() { try { selector.close(); } catch (IOException e) { logger.warn("Failed to close a selector.", e); } } void cancel(SelectionKey key) { key.cancel(); cancelledKeys ++; if (cancelledKeys >= CLEANUP_INTERVAL) { cancelledKeys = 0; needsToSelectAgain = true; } } @Override protected Runnable pollTask() { Runnable task = super.pollTask(); if (needsToSelectAgain) { selectAgain(); } return task; } private void processSelectedKeysPlain(Set<SelectionKey> selectedKeys) { // check if the set is empty and if so just return to not create garbage by // creating a new Iterator every time even if there is nothing to process. // See https://github.com/netty/netty/issues/597 if (selectedKeys.isEmpty()) { return; } Iterator<SelectionKey> i = selectedKeys.iterator(); for (;;) { final SelectionKey k = i.next(); final Object a = k.attachment(); i.remove(); if (a instanceof AbstractNioChannel) { processSelectedKey(k, (AbstractNioChannel) a); } else { @SuppressWarnings("unchecked") NioTask<SelectableChannel> task = (NioTask<SelectableChannel>) a; processSelectedKey(k, task); } if (!i.hasNext()) { break; } if (needsToSelectAgain) { selectAgain(); selectedKeys = selector.selectedKeys(); // Create the iterator again to avoid ConcurrentModificationException if (selectedKeys.isEmpty()) { break; } else { i = selectedKeys.iterator(); } } } } private void processSelectedKeysOptimized(SelectionKey[] selectedKeys) { for (int i = 0;; i ++) { final SelectionKey k = selectedKeys[i]; if (k == null) { break; } // null out entry in the array to allow to have it GC'ed once the Channel close // See https://github.com/netty/netty/issues/2363 selectedKeys[i] = null; final Object a = k.attachment(); if (a instanceof AbstractNioChannel) { processSelectedKey(k, (AbstractNioChannel) a); } else { @SuppressWarnings("unchecked") NioTask<SelectableChannel> task = (NioTask<SelectableChannel>) a; processSelectedKey(k, task); } if (needsToSelectAgain) { // null out entries in the array to allow to have it GC'ed once the Channel close // See https://github.com/netty/netty/issues/2363 for (;;) { if (selectedKeys[i] == null) { break; } selectedKeys[i] = null; i++; } selectAgain(); // Need to flip the optimized selectedKeys to get the right reference to the array // and reset the index to -1 which will then set to 0 on the for loop // to start over again. // // See https://github.com/netty/netty/issues/1523 selectedKeys = this.selectedKeys.flip(); i = -1; } } } private static void processSelectedKey(SelectionKey k, AbstractNioChannel ch) { final AbstractNioChannel.NioUnsafe unsafe = ch.unsafe(); if (!k.isValid()) { // close the channel if the key is not valid anymore unsafe.close(unsafe.voidPromise()); return; } try { int readyOps = k.readyOps(); // Also check for readOps of 0 to workaround possible JDK bug which may otherwise lead // to a spin loop if ((readyOps & (SelectionKey.OP_READ | SelectionKey.OP_ACCEPT)) != 0 || readyOps == 0) { unsafe.read(); if (!ch.isOpen()) { // Connection already closed - no need to handle write. return; } } if ((readyOps & SelectionKey.OP_WRITE) != 0) { // Call forceFlush which will also take care of clear the OP_WRITE once there is nothing left to write ch.unsafe().forceFlush(); } if ((readyOps & SelectionKey.OP_CONNECT) != 0) { // remove OP_CONNECT as otherwise Selector.select(..) will always return without blocking // See https://github.com/netty/netty/issues/924 int ops = k.interestOps(); ops &= ~SelectionKey.OP_CONNECT; k.interestOps(ops); unsafe.finishConnect(); } } catch (CancelledKeyException ignored) { unsafe.close(unsafe.voidPromise()); } } private static void processSelectedKey(SelectionKey k, NioTask<SelectableChannel> task) { int state = 0; try { task.channelReady(k.channel(), k); state = 1; } catch (Exception e) { k.cancel(); invokeChannelUnregistered(task, k, e); state = 2; } finally { switch (state) { case 0: k.cancel(); invokeChannelUnregistered(task, k, null); break; case 1: if (!k.isValid()) { // Cancelled by channelReady() invokeChannelUnregistered(task, k, null); } break; } } } private void closeAll() { selectAgain(); Set<SelectionKey> keys = selector.keys(); Collection<AbstractNioChannel> channels = new ArrayList<AbstractNioChannel>(keys.size()); for (SelectionKey k: keys) { Object a = k.attachment(); if (a instanceof AbstractNioChannel) { channels.add((AbstractNioChannel) a); } else { k.cancel(); @SuppressWarnings("unchecked") NioTask<SelectableChannel> task = (NioTask<SelectableChannel>) a; invokeChannelUnregistered(task, k, null); } } for (AbstractNioChannel ch: channels) { ch.unsafe().close(ch.unsafe().voidPromise()); } } private static void invokeChannelUnregistered(NioTask<SelectableChannel> task, SelectionKey k, Throwable cause) { try { task.channelUnregistered(k.channel(), cause); } catch (Exception e) { logger.warn("Unexpected exception while running NioTask.channelUnregistered()", e); } } @Override protected void wakeup(boolean inEventLoop) { if (!inEventLoop && wakenUp.compareAndSet(false, true)) { selector.wakeup(); } } void selectNow() throws IOException { try { selector.selectNow(); } finally { // restore wakup state if needed if (wakenUp.get()) { selector.wakeup(); } } } private void select(boolean oldWakenUp) throws IOException { Selector selector = this.selector; try { int selectCnt = 0; long currentTimeNanos = System.nanoTime(); long selectDeadLineNanos = currentTimeNanos + delayNanos(currentTimeNanos); for (;;) { long timeoutMillis = (selectDeadLineNanos - currentTimeNanos + 500000L) / 1000000L; if (timeoutMillis <= 0) { if (selectCnt == 0) { selector.selectNow(); selectCnt = 1; } break; } int selectedKeys = selector.select(timeoutMillis); selectCnt ++; if (selectedKeys != 0 || oldWakenUp || wakenUp.get() || hasTasks() || hasScheduledTasks()) { // - Selected something, // - waken up by user, or // - the task queue has a pending task. // - a scheduled task is ready for processing break; } if (Thread.interrupted()) { // Thread was interrupted so reset selected keys and break so we not run into a busy loop. // As this is most likely a bug in the handler of the user or it's client library we will // also log it. // // See https://github.com/netty/netty/issues/2426 if (logger.isDebugEnabled()) { logger.debug("Selector.select() returned prematurely because " + "Thread.currentThread().interrupt() was called. Use " + "NioEventLoop.shutdownGracefully() to shutdown the NioEventLoop."); } selectCnt = 1; break; } long time = System.nanoTime(); if (time - TimeUnit.MILLISECONDS.toNanos(timeoutMillis) >= currentTimeNanos) { // timeoutMillis elapsed without anything selected. selectCnt = 1; } else if (SELECTOR_AUTO_REBUILD_THRESHOLD > 0 && selectCnt >= SELECTOR_AUTO_REBUILD_THRESHOLD) { // The selector returned prematurely many times in a row. // Rebuild the selector to work around the problem. logger.warn( "Selector.select() returned prematurely {} times in a row; rebuilding selector.", selectCnt); rebuildSelector(); selector = this.selector; // Select again to populate selectedKeys. selector.selectNow(); selectCnt = 1; break; } currentTimeNanos = time; } if (selectCnt > MIN_PREMATURE_SELECTOR_RETURNS) { if (logger.isDebugEnabled()) { logger.debug("Selector.select() returned prematurely {} times in a row.", selectCnt - 1); } } } catch (CancelledKeyException e) { if (logger.isDebugEnabled()) { logger.debug(CancelledKeyException.class.getSimpleName() + " raised by a Selector - JDK bug?", e); } // Harmless exception - log anyway } } private void selectAgain() { needsToSelectAgain = false; try { selector.selectNow(); } catch (Throwable t) { logger.warn("Failed to update SelectionKeys.", t); } } }
[#2363] Correctly null out SelectionKey[] when selectAgain Motivation: The prefix fix of #2363 did not correctly handle the case when selectAgain is true and so missed to null out entries. Modifications: Move the i++ from end of loop to beginning of loop Result: Entries in the array will be null out so allow to have these GC'ed once the Channel close
transport/src/main/java/io/netty/channel/nio/NioEventLoop.java
[#2363] Correctly null out SelectionKey[] when selectAgain
<ide><path>ransport/src/main/java/io/netty/channel/nio/NioEventLoop.java <ide> // null out entries in the array to allow to have it GC'ed once the Channel close <ide> // See https://github.com/netty/netty/issues/2363 <ide> for (;;) { <add> i++; <ide> if (selectedKeys[i] == null) { <ide> break; <ide> } <ide> selectedKeys[i] = null; <del> i++; <ide> } <ide> <ide> selectAgain();