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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
JavaScript | mit | ec95bc14bcad420725150f05620892955350bc42 | 0 | jjhampton/cross-pollinate,jjhampton/cross-pollinate | import Ember from 'ember';
export default Ember.Route.extend({
model: function() {
return this.store.findAll('problem');
},
actions: {
getResults: function() {
var query;
function escapeRegExp(string) {
return string.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}
query = escapeRegExp($('.index-search-input').val());
// this.store.findAll('problem').then(function(response) {
// return response.map(function(problem) {
// return [problem.get('id'), problem.get('name'), problem.get('tags'), problem.get('city'), problem.get('state'), problem.get('country')];
// });
// }).then(function(response){
// console.log("Problem searchables are", response);
// console.log("search query was", query);
// var matched = _.filter(response, function(problem){
// return _.contains(problem, query);
// });
// console.log(matched);
// });
this.store.findQuery('problem', {
where: {
$or: [
{name: {$regex: query}},
// {tags: {$regex: query}},
{city: {$regex: query}},
{state: {$regex: query}},
{country: {$regex: query}},
]
}
}).then(function(response) {
console.log(response.content);
response.content.forEach(function(element) {
console.log(element._data.name);
});
});
}
}
});
| app/routes/index.js | import Ember from 'ember';
export default Ember.Route.extend({
model: function() {
return this.store.findAll('problem');
},
actions: {
getResults: function() {
var query;
function escapeRegExp(string) {
return string.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}
query = escapeRegExp($('.index-search-input').val());
// this.store.findAll('problem').then(function(response) {
// return response.map(function(problem) {
// return [problem.get('id'), problem.get('name'), problem.get('tags'), problem.get('city'), problem.get('state'), problem.get('country')];
// });
// }).then(function(response){
// console.log("Problem searchables are", response);
// console.log("search query was", query);
// var matched = _.filter(response, function(problem){
// return _.contains(problem, query);
// });
// console.log(matched);
// });
this.store.findQuery('problem', {
where: {
$or: [
{name: {$regex: query}},
// {tags: {$regex: query}},
{city: {$regex: query}},
{state: {$regex: query}},
{country: {$regex: query}},
]
}
}).then(function(response) {
console.log(response.content);
response.content.forEach(function(element) {
console.log(element.id);
});
});
}
}
});
| Log names to console of problems that match a keyword query
| app/routes/index.js | Log names to console of problems that match a keyword query | <ide><path>pp/routes/index.js
<ide> }).then(function(response) {
<ide> console.log(response.content);
<ide> response.content.forEach(function(element) {
<del> console.log(element.id);
<add> console.log(element._data.name);
<ide> });
<ide> });
<del>
<ide> }
<ide> }
<ide> }); |
|
Java | agpl-3.0 | 8e90ef1e69833e7a41133539e58bd975735752f8 | 0 | TheLanguageArchive/YAMS,TheLanguageArchive/YAMS,TheLanguageArchive/YAMS | /**
* Copyright (C) 2013 The Language Archive, Max Planck Institute for
* Psycholinguistics
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package nl.mpi.yams.cs.connector;
import java.net.URI;
import nl.mpi.archiving.corpusstructure.core.CorpusNode;
import nl.mpi.archiving.corpusstructure.provider.AccessInfoProvider;
import nl.mpi.archiving.corpusstructure.provider.CorpusStructureProvider;
import nl.mpi.flap.model.DataNodePermissions;
import nl.mpi.flap.model.DataNodeType;
import nl.mpi.flap.model.ModelException;
import nl.mpi.flap.model.SerialisableDataNode;
/**
* @since Apr 22, 2014 3:51:30 PM (creation date)
* @author Peter Withers <[email protected]>
*/
public class CorpusNodeWrapper extends SerialisableDataNode {
private final CorpusNode archiveObject;
private final AccessInfoProvider accessInfoProvider;
private final CorpusStructureProvider corpusStructureProvider;
private final String userId;
public CorpusNodeWrapper(CorpusStructureProvider corpusStructureProvider, AccessInfoProvider accessInfoProvider, CorpusNode archiveObject, final String userId) {
this.corpusStructureProvider = corpusStructureProvider;
this.accessInfoProvider = accessInfoProvider;
this.archiveObject = archiveObject;
this.userId = (userId == null) ? "anonymous" : userId;
}
@Override
public String getLabel() {
return archiveObject.getName();
}
@Override
public String getArchiveHandle() {
final URI pid = archiveObject.getPID();
if (pid == null) {
// for some reason archive objects do not always have persistent identifiers, even foreign archive nodes should have some sort of PID so this is possibly an issue in Corpus Structure
return null;
}
return pid.toString();
}
@Override
public String getURI() throws ModelException {
return archiveObject.getNodeURI().toString();
}
@Override
public DataNodeType getType() {
final DataNodeType dataNodeType = new DataNodeType();
switch (archiveObject.getType()) {
case COLLECTION:
dataNodeType.setFormat(DataNodeType.FormatType.cmdi);
break;
case IMDICATALOGUE:
dataNodeType.setFormat(DataNodeType.FormatType.imdi_catalogue);
break;
case IMDIINFO:
dataNodeType.setFormat(DataNodeType.FormatType.imdi_info);
break;
case METADATA:
dataNodeType.setFormat(DataNodeType.FormatType.cmdi);
break;
case RESOURCE_ANNOTATION:
dataNodeType.setFormat(DataNodeType.FormatType.resource_annotation);
break;
case RESOURCE_AUDIO:
dataNodeType.setFormat(DataNodeType.FormatType.resource_audio);
break;
case RESOURCE_LEXICAL:
dataNodeType.setFormat(DataNodeType.FormatType.resource_lexical);
break;
case RESOURCE_OTHER:
dataNodeType.setFormat(DataNodeType.FormatType.resource_other);
break;
case RESOURCE_VIDEO:
dataNodeType.setFormat(DataNodeType.FormatType.resource_video);
break;
}
dataNodeType.setMimeType(archiveObject.getFormat());
return dataNodeType;
}
@Override
public DataNodePermissions getPermissions() {
final DataNodePermissions permissions = new DataNodePermissions();
switch (accessInfoProvider.getAccessLevel(archiveObject.getNodeURI())) {
case ACCESS_LEVEL_CLOSED:
permissions.setAccessLevel(DataNodePermissions.AccessLevel.closed);
break;
case ACCESS_LEVEL_EXTERNAL:
permissions.setAccessLevel(DataNodePermissions.AccessLevel.external);
break;
case ACCESS_LEVEL_OPEN_EVERYBODY:
permissions.setAccessLevel(DataNodePermissions.AccessLevel.open_everybody);
break;
case ACCESS_LEVEL_OPEN_REGISTERED_USERS:
permissions.setAccessLevel(DataNodePermissions.AccessLevel.open_registered_users);
break;
case ACCESS_LEVEL_PERMISSION_NEEDED:
permissions.setAccessLevel(DataNodePermissions.AccessLevel.permission_needed);
break;
case ACCESS_LEVEL_UNKNOWN:
permissions.setAccessLevel(DataNodePermissions.AccessLevel.unknown);
break;
}
return permissions;
}
@Override
public Integer getLinkCount() {
// todo: it would be nice if corpus structure provides us with a child link count but instead we get a list
// corpusStructureProvider.
// archiveObject.getFileInfo().
// archiveObject.getLastUpdate()
// archiveObject.getProfile()
// CorpusStructDB.
// archiveObject.isOnSite()
return corpusStructureProvider.getChildNodeURIs(archiveObject.getNodeURI()).size();
}
}
| yams-cs-connector/src/main/java/nl/mpi/yams/cs/connector/CorpusNodeWrapper.java | /**
* Copyright (C) 2013 The Language Archive, Max Planck Institute for
* Psycholinguistics
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package nl.mpi.yams.cs.connector;
import nl.mpi.archiving.corpusstructure.core.CorpusNode;
import nl.mpi.archiving.corpusstructure.provider.AccessInfoProvider;
import nl.mpi.archiving.corpusstructure.provider.CorpusStructureProvider;
import nl.mpi.flap.model.DataNodePermissions;
import nl.mpi.flap.model.DataNodeType;
import nl.mpi.flap.model.ModelException;
import nl.mpi.flap.model.SerialisableDataNode;
/**
* @since Apr 22, 2014 3:51:30 PM (creation date)
* @author Peter Withers <[email protected]>
*/
public class CorpusNodeWrapper extends SerialisableDataNode {
private final CorpusNode archiveObject;
private final AccessInfoProvider accessInfoProvider;
private final CorpusStructureProvider corpusStructureProvider;
private final String userId;
public CorpusNodeWrapper(CorpusStructureProvider corpusStructureProvider, AccessInfoProvider accessInfoProvider, CorpusNode archiveObject, final String userId) {
this.corpusStructureProvider = corpusStructureProvider;
this.accessInfoProvider = accessInfoProvider;
this.archiveObject = archiveObject;
this.userId = (userId == null) ? "anonymous" : userId;
}
@Override
public String getLabel() {
return archiveObject.getName();
}
@Override
public String getArchiveHandle() {
return archiveObject.getPID().toString();
}
@Override
public String getURI() throws ModelException {
return archiveObject.getNodeURI().toString();
}
@Override
public DataNodeType getType() {
final DataNodeType dataNodeType = new DataNodeType();
switch (archiveObject.getType()) {
case COLLECTION:
dataNodeType.setFormat(DataNodeType.FormatType.cmdi);
break;
case IMDICATALOGUE:
dataNodeType.setFormat(DataNodeType.FormatType.imdi_catalogue);
break;
case IMDIINFO:
dataNodeType.setFormat(DataNodeType.FormatType.imdi_info);
break;
case METADATA:
dataNodeType.setFormat(DataNodeType.FormatType.cmdi);
break;
case RESOURCE_ANNOTATION:
dataNodeType.setFormat(DataNodeType.FormatType.resource_annotation);
break;
case RESOURCE_AUDIO:
dataNodeType.setFormat(DataNodeType.FormatType.resource_audio);
break;
case RESOURCE_LEXICAL:
dataNodeType.setFormat(DataNodeType.FormatType.resource_lexical);
break;
case RESOURCE_OTHER:
dataNodeType.setFormat(DataNodeType.FormatType.resource_other);
break;
case RESOURCE_VIDEO:
dataNodeType.setFormat(DataNodeType.FormatType.resource_video);
break;
}
dataNodeType.setMimeType(archiveObject.getFormat());
return dataNodeType;
}
@Override
public DataNodePermissions getPermissions() {
final DataNodePermissions permissions = new DataNodePermissions();
switch (accessInfoProvider.getAccessLevel(archiveObject.getNodeURI())) {
case ACCESS_LEVEL_CLOSED:
permissions.setAccessLevel(DataNodePermissions.AccessLevel.closed);
break;
case ACCESS_LEVEL_EXTERNAL:
permissions.setAccessLevel(DataNodePermissions.AccessLevel.external);
break;
case ACCESS_LEVEL_OPEN_EVERYBODY:
permissions.setAccessLevel(DataNodePermissions.AccessLevel.open_everybody);
break;
case ACCESS_LEVEL_OPEN_REGISTERED_USERS:
permissions.setAccessLevel(DataNodePermissions.AccessLevel.open_registered_users);
break;
case ACCESS_LEVEL_PERMISSION_NEEDED:
permissions.setAccessLevel(DataNodePermissions.AccessLevel.permission_needed);
break;
case ACCESS_LEVEL_UNKNOWN:
permissions.setAccessLevel(DataNodePermissions.AccessLevel.unknown);
break;
}
return permissions;
}
@Override
public Integer getLinkCount() {
// todo: it would be nice if corpus structure provides us with a child link count but instead we get a list
// corpusStructureProvider.
// archiveObject.getFileInfo().
// archiveObject.getLastUpdate()
// archiveObject.getProfile()
// CorpusStructDB.
// archiveObject.isOnSite()
return corpusStructureProvider.getChildNodeURIs(archiveObject.getNodeURI()).size();
}
}
| Added graceful handling of archive objects without persistent identifiers.
| yams-cs-connector/src/main/java/nl/mpi/yams/cs/connector/CorpusNodeWrapper.java | Added graceful handling of archive objects without persistent identifiers. | <ide><path>ams-cs-connector/src/main/java/nl/mpi/yams/cs/connector/CorpusNodeWrapper.java
<ide> */
<ide> package nl.mpi.yams.cs.connector;
<ide>
<add>import java.net.URI;
<ide> import nl.mpi.archiving.corpusstructure.core.CorpusNode;
<ide> import nl.mpi.archiving.corpusstructure.provider.AccessInfoProvider;
<ide> import nl.mpi.archiving.corpusstructure.provider.CorpusStructureProvider;
<ide>
<ide> @Override
<ide> public String getArchiveHandle() {
<del> return archiveObject.getPID().toString();
<add> final URI pid = archiveObject.getPID();
<add> if (pid == null) {
<add> // for some reason archive objects do not always have persistent identifiers, even foreign archive nodes should have some sort of PID so this is possibly an issue in Corpus Structure
<add> return null;
<add> }
<add> return pid.toString();
<ide> }
<ide>
<ide> @Override |
|
Java | apache-2.0 | 1c5d882a848960659b3f30ed6c8fa44196b71a98 | 0 | rwl/requestfactory-addon | package org.springframework.roo.classpath.converters;
import static org.springframework.roo.project.ContextualPath.MODULE_PATH_SEPARATOR;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Service;
import org.springframework.roo.classpath.PhysicalTypeIdentifier;
import org.springframework.roo.classpath.TypeLocationService;
import org.springframework.roo.model.JavaPackage;
import org.springframework.roo.model.JavaType;
import org.springframework.roo.process.manager.FileManager;
import org.springframework.roo.project.ProjectOperations;
import org.springframework.roo.project.maven.Pom;
import org.springframework.roo.shell.Completion;
import org.springframework.roo.shell.Converter;
import org.springframework.roo.shell.MethodTarget;
import org.springframework.roo.support.util.AnsiEscapeCode;
import org.springframework.roo.support.util.StringUtils;
/**
* Provides conversion to and from {@link JavaType}, with full support for using "~" as denoting the user's top-level package.
*
* @author Ben Alex
* @since 1.0
*/
@Component
@Service
public class JavaTypeConverter implements Converter<JavaType> {
private static final List<String> NUMBER_PRIMITIVES = Arrays.asList("byte", "short", "int", "long", "float", "double");
// Fields
@Reference protected LastUsed lastUsed;
@Reference protected FileManager fileManager;
@Reference protected ProjectOperations projectOperations;
@Reference private TypeLocationService typeLocationService;
public JavaType convertFromText(String value, final Class<?> requiredType, final String optionContext) {
if (value == null || "".equals(value)) {
return null;
}
// Check for number primitives
if (NUMBER_PRIMITIVES.contains(value)) {
return getNumberPrimitiveType(value);
}
if ("*".equals(value)) {
JavaType result = lastUsed.getJavaType();
if (result == null) {
throw new IllegalStateException("Unknown type; please indicate the type as a command option (ie --xxxx)");
}
return result;
}
String topLevelPath;
Pom module = projectOperations.getFocusedModule();
if (value.contains(MODULE_PATH_SEPARATOR)) {
String moduleName = value.substring(0, value.indexOf(MODULE_PATH_SEPARATOR));
module = projectOperations.getPomManagementService().getPomFromModuleName(moduleName);
topLevelPath = typeLocationService.getTopLevelPackageForModule(module);
value = value.substring(value.indexOf(MODULE_PATH_SEPARATOR) + 1, value.length()).trim();
if (optionContext.contains("update")) {
projectOperations.getPomManagementService().setFocusedModule(module);
}
} else {
topLevelPath = typeLocationService.getTopLevelPackageForModule(projectOperations.getFocusedModule());
}
if (value.equals(topLevelPath)) {
return null;
}
String newValue = locateExisting(value, topLevelPath);
if (newValue == null) {
newValue = locateNew(value, topLevelPath);
}
if (StringUtils.hasText(newValue)) {
String physicalTypeIdentifier = typeLocationService.getPhysicalTypeIdentifier(new JavaType(newValue));
if (StringUtils.hasText(physicalTypeIdentifier)) {
module = projectOperations.getPomManagementService().getPomFromModuleName(PhysicalTypeIdentifier.getPath(physicalTypeIdentifier).getModule());
}
}
// If the user did not provide a java type name containing a dot, it's taken as relative to the current package directory
if (!newValue.contains(".")) {
newValue = (lastUsed.getJavaPackage() == null ? lastUsed.getTopLevelPackage().getFullyQualifiedPackageName() : lastUsed.getJavaPackage().getFullyQualifiedPackageName()) + "." + newValue;
}
// Automatically capitalize the first letter of the last name segment (ie capitalize the type name, but not the package)
int index = newValue.lastIndexOf(".");
if (index > -1 && !newValue.endsWith(".")) {
String typeName = newValue.substring(index + 1);
typeName = StringUtils.capitalize(typeName);
newValue = newValue.substring(0, index).toLowerCase() + "." + typeName;
}
JavaType result = new JavaType(newValue);
if (optionContext.contains("update")) {
lastUsed.setType(result, module);
}
return result;
}
private String locateNew(final String value, final String topLevelPath) {
String newValue = value;
if (value.startsWith("~")) {
if (value.length() > 1) {
newValue = (value.charAt(1) == '.' ? topLevelPath : topLevelPath + ".") + value.substring(1);
} else {
newValue = topLevelPath + ".";
}
}
lastUsed.setTopLevelPackage(new JavaPackage(topLevelPath));
return newValue;
}
private String locateExisting(final String value, String topLevelPath) {
String newValue = value;
if (value.startsWith("~")) {
boolean found = false;
while (!found) {
if (value.length() > 1) {
newValue = (value.charAt(1) == '.' ? topLevelPath : topLevelPath + ".") + value.substring(1);
} else {
newValue = topLevelPath + ".";
}
String physicalTypeIdentifier = typeLocationService.getPhysicalTypeIdentifier(new JavaType(newValue));
if (physicalTypeIdentifier != null) {
topLevelPath = typeLocationService.getTopLevelPackageForModule(projectOperations.getPomFromModuleName(PhysicalTypeIdentifier.getPath(physicalTypeIdentifier).getModule()));
found = true;
} else {
int index = topLevelPath.lastIndexOf('.');
if (index == -1) {
break;
}
topLevelPath = topLevelPath.substring(0, topLevelPath.lastIndexOf('.'));
}
}
if (found) {
lastUsed.setTopLevelPackage(new JavaPackage(topLevelPath));
} else {
return null;
}
}
return newValue;
}
public boolean supports(final Class<?> requiredType, final String optionContext) {
return JavaType.class.isAssignableFrom(requiredType);
}
public boolean getAllPossibleValues(final List<Completion> completions, final Class<?> requiredType, String existingData, final String optionContext, final MethodTarget target) {
if (existingData == null) {
existingData = "";
}
if (optionContext == null || "".equals(optionContext) || optionContext.contains("project")) {
completeProjectSpecificPaths(completions, existingData);
}
if (optionContext != null && optionContext.contains("java")) {
completeJavaSpecificPaths(completions, existingData, optionContext);
}
return false;
}
/**
* Adds common "java." types to the completions. For now we just provide them statically.
*/
private void completeJavaSpecificPaths(final List<Completion> completions, final String existingData, String optionContext) {
SortedSet<String> types = new TreeSet<String>();
if (optionContext == null || "".equals(optionContext)) {
optionContext = "java-all";
}
if (optionContext.contains("java-all") || optionContext.contains("java-lang")) {
// lang - other
types.add(Boolean.class.getName());
types.add(String.class.getName());
}
if (optionContext.contains("java-all") || optionContext.contains("java-lang") || optionContext.contains("java-number")) {
// lang - numeric
types.add(Number.class.getName());
types.add(Short.class.getName());
types.add(Byte.class.getName());
types.add(Integer.class.getName());
types.add(Long.class.getName());
types.add(Float.class.getName());
types.add(Double.class.getName());
types.add(Byte.TYPE.getName());
types.add(Short.TYPE.getName());
types.add(Integer.TYPE.getName());
types.add(Long.TYPE.getName());
types.add(Float.TYPE.getName());
types.add(Double.TYPE.getName());
}
if (optionContext.contains("java-all") || optionContext.contains("java-number")) {
// misc
types.add(BigDecimal.class.getName());
types.add(BigInteger.class.getName());
}
if (optionContext.contains("java-all") || optionContext.contains("java-util") || optionContext.contains("java-collections")) {
// util
types.add(Collection.class.getName());
types.add(List.class.getName());
types.add(Queue.class.getName());
types.add(Set.class.getName());
types.add(SortedSet.class.getName());
types.add(Map.class.getName());
}
if (optionContext.contains("java-all") || optionContext.contains("java-util") || optionContext.contains("java-date")) {
// util
types.add(Date.class.getName());
types.add(Calendar.class.getName());
}
for (String type : types) {
if (type.startsWith(existingData) || existingData.startsWith(type)) {
completions.add(new Completion(type));
}
}
}
private void completeProjectSpecificPaths(final List<Completion> completions, String existingData) {
String topLevelPath = "";
if (!projectOperations.isFocusedProjectAvailable()) {
return;
}
topLevelPath = typeLocationService.getTopLevelPackageForModule(projectOperations.getFocusedModule());
Pom focusedModule = projectOperations.getFocusedModule();
String focusedModulePath = projectOperations.getFocusedModule().getPath();
String focusedModuleName = focusedModule.getModuleName();
boolean intraModule = false;
if (existingData.contains(MODULE_PATH_SEPARATOR)) {
focusedModuleName = existingData.substring(0, existingData.indexOf(MODULE_PATH_SEPARATOR));
focusedModule = projectOperations.getPomFromModuleName(focusedModuleName);
focusedModulePath = focusedModule.getPath();
existingData = existingData.substring(existingData.indexOf(MODULE_PATH_SEPARATOR) + 1, existingData.length());
topLevelPath = typeLocationService.getTopLevelPackageForModule(focusedModule);
intraModule = true;
}
String newValue = existingData;
if (existingData.startsWith("~")) {
if (existingData.length() > 1) {
newValue = (existingData.charAt(1) == '.' ? topLevelPath : topLevelPath + ".") + existingData.substring(1);
} else {
newValue = topLevelPath + ".";
}
}
String prefix = "";
String formattedPrefix = "";
if (!focusedModulePath.equals(projectOperations.getFocusedModule().getPath())) {
prefix = focusedModuleName + MODULE_PATH_SEPARATOR;
formattedPrefix = AnsiEscapeCode.decorate(focusedModuleName + MODULE_PATH_SEPARATOR, AnsiEscapeCode.FG_CYAN);
}
for (String moduleName : projectOperations.getPomManagementService().getModuleNames()) {
if (!moduleName.equals(focusedModuleName)) {
Completion completion = new Completion(moduleName + MODULE_PATH_SEPARATOR, AnsiEscapeCode.decorate(moduleName + MODULE_PATH_SEPARATOR, AnsiEscapeCode.FG_CYAN), "Modules", 0);
completions.add(completion);
}
}
String heading = "";
if (!intraModule) {
heading = focusedModuleName;
}
if (typeLocationService.getTypesForModule(focusedModulePath).isEmpty()) {
completions.add(new Completion(prefix + focusedModule.getGroupId(), formattedPrefix + focusedModule.getGroupId(), heading, 1));
return;
} else {
completions.add(new Completion(prefix + topLevelPath, formattedPrefix + topLevelPath, heading, 1));
}
for (String type : typeLocationService.getTypesForModule(focusedModulePath)) {
if (type.startsWith(newValue)) {
type = StringUtils.replaceFirst(type, topLevelPath, "~");
completions.add(new Completion(prefix + type, formattedPrefix + type, heading, 1));
}
}
}
private JavaType getNumberPrimitiveType(final String value) {
if ("byte".equals(value)) {
return JavaType.BYTE_PRIMITIVE;
} else if ("short".equals(value)) {
return JavaType.SHORT_PRIMITIVE;
} else if ("int".equals(value)) {
return JavaType.INT_PRIMITIVE;
} else if ("long".equals(value)) {
return JavaType.LONG_PRIMITIVE;
} else if ("float".equals(value)) {
return JavaType.FLOAT_PRIMITIVE;
} else if ("double".equals(value)) {
return JavaType.DOUBLE_PRIMITIVE;
} else {
return null;
}
}
}
| classpath/src/main/java/org/springframework/roo/classpath/converters/JavaTypeConverter.java | package org.springframework.roo.classpath.converters;
import static org.springframework.roo.project.ContextualPath.MODULE_PATH_SEPARATOR;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Service;
import org.springframework.roo.classpath.PhysicalTypeIdentifier;
import org.springframework.roo.classpath.TypeLocationService;
import org.springframework.roo.model.JavaPackage;
import org.springframework.roo.model.JavaType;
import org.springframework.roo.process.manager.FileManager;
import org.springframework.roo.project.ProjectOperations;
import org.springframework.roo.project.maven.Pom;
import org.springframework.roo.shell.Completion;
import org.springframework.roo.shell.Converter;
import org.springframework.roo.shell.MethodTarget;
import org.springframework.roo.support.util.AnsiEscapeCode;
import org.springframework.roo.support.util.StringUtils;
/**
* Provides conversion to and from {@link JavaType}, with full support for using "~" as denoting the user's top-level package.
*
* @author Ben Alex
* @since 1.0
*/
@Component
@Service
public class JavaTypeConverter implements Converter<JavaType> {
private static final List<String> NUMBER_PRIMITIVES = Arrays.asList("byte", "short", "int", "long", "float", "double");
// Fields
@Reference protected LastUsed lastUsed;
@Reference protected FileManager fileManager;
@Reference protected ProjectOperations projectOperations;
@Reference private TypeLocationService typeLocationService;
public JavaType convertFromText(String value, final Class<?> requiredType, final String optionContext) {
if (value == null || "".equals(value)) {
return null;
}
// Check for number primitives
if (NUMBER_PRIMITIVES.contains(value)) {
return getNumberPrimitiveType(value);
}
if ("*".equals(value)) {
JavaType result = lastUsed.getJavaType();
if (result == null) {
throw new IllegalStateException("Unknown type; please indicate the type as a command option (ie --xxxx)");
}
return result;
}
String topLevelPath;
Pom module = projectOperations.getFocusedModule();
if (value.contains(MODULE_PATH_SEPARATOR)) {
String moduleName = value.substring(0, value.indexOf(MODULE_PATH_SEPARATOR));
module = projectOperations.getPomManagementService().getPomFromModuleName(moduleName);
topLevelPath = typeLocationService.getTopLevelPackageForModule(module);
value = value.substring(value.indexOf(MODULE_PATH_SEPARATOR) + 1, value.length()).trim();
projectOperations.getPomManagementService().setFocusedModule(module);
} else {
topLevelPath = typeLocationService.getTopLevelPackageForModule(projectOperations.getFocusedModule());
}
if (value.equals(topLevelPath)) {
return null;
}
String newValue = locateExisting(value, topLevelPath);
if (newValue == null) {
newValue = locateNew(value, topLevelPath);
}
if (StringUtils.hasText(newValue)) {
String physicalTypeIdentifier = typeLocationService.getPhysicalTypeIdentifier(new JavaType(newValue));
if (StringUtils.hasText(physicalTypeIdentifier)) {
module = projectOperations.getPomManagementService().getPomFromModuleName(PhysicalTypeIdentifier.getPath(physicalTypeIdentifier).getModule());
}
}
// If the user did not provide a java type name containing a dot, it's taken as relative to the current package directory
if (!newValue.contains(".")) {
newValue = (lastUsed.getJavaPackage() == null ? lastUsed.getTopLevelPackage().getFullyQualifiedPackageName() : lastUsed.getJavaPackage().getFullyQualifiedPackageName()) + "." + newValue;
}
// Automatically capitalize the first letter of the last name segment (ie capitalize the type name, but not the package)
int index = newValue.lastIndexOf(".");
if (index > -1 && !newValue.endsWith(".")) {
String typeName = newValue.substring(index + 1);
typeName = StringUtils.capitalize(typeName);
newValue = newValue.substring(0, index).toLowerCase() + "." + typeName;
}
JavaType result = new JavaType(newValue);
if (optionContext.contains("update")) {
lastUsed.setType(result, module);
}
return result;
}
private String locateNew(final String value, final String topLevelPath) {
String newValue = value;
if (value.startsWith("~")) {
if (value.length() > 1) {
newValue = (value.charAt(1) == '.' ? topLevelPath : topLevelPath + ".") + value.substring(1);
} else {
newValue = topLevelPath + ".";
}
}
lastUsed.setTopLevelPackage(new JavaPackage(topLevelPath));
return newValue;
}
private String locateExisting(final String value, String topLevelPath) {
String newValue = value;
if (value.startsWith("~")) {
boolean found = false;
while (!found) {
if (value.length() > 1) {
newValue = (value.charAt(1) == '.' ? topLevelPath : topLevelPath + ".") + value.substring(1);
} else {
newValue = topLevelPath + ".";
}
String physicalTypeIdentifier = typeLocationService.getPhysicalTypeIdentifier(new JavaType(newValue));
if (physicalTypeIdentifier != null) {
topLevelPath = typeLocationService.getTopLevelPackageForModule(projectOperations.getPomFromModuleName(PhysicalTypeIdentifier.getPath(physicalTypeIdentifier).getModule()));
found = true;
} else {
int index = topLevelPath.lastIndexOf('.');
if (index == -1) {
break;
}
topLevelPath = topLevelPath.substring(0, topLevelPath.lastIndexOf('.'));
}
}
if (found) {
lastUsed.setTopLevelPackage(new JavaPackage(topLevelPath));
} else {
return null;
}
}
return newValue;
}
public boolean supports(final Class<?> requiredType, final String optionContext) {
return JavaType.class.isAssignableFrom(requiredType);
}
public boolean getAllPossibleValues(final List<Completion> completions, final Class<?> requiredType, String existingData, final String optionContext, final MethodTarget target) {
if (existingData == null) {
existingData = "";
}
if (optionContext == null || "".equals(optionContext) || optionContext.contains("project")) {
completeProjectSpecificPaths(completions, existingData);
}
if (optionContext != null && optionContext.contains("java")) {
completeJavaSpecificPaths(completions, existingData, optionContext);
}
return false;
}
/**
* Adds common "java." types to the completions. For now we just provide them statically.
*/
private void completeJavaSpecificPaths(final List<Completion> completions, final String existingData, String optionContext) {
SortedSet<String> types = new TreeSet<String>();
if (optionContext == null || "".equals(optionContext)) {
optionContext = "java-all";
}
if (optionContext.contains("java-all") || optionContext.contains("java-lang")) {
// lang - other
types.add(Boolean.class.getName());
types.add(String.class.getName());
}
if (optionContext.contains("java-all") || optionContext.contains("java-lang") || optionContext.contains("java-number")) {
// lang - numeric
types.add(Number.class.getName());
types.add(Short.class.getName());
types.add(Byte.class.getName());
types.add(Integer.class.getName());
types.add(Long.class.getName());
types.add(Float.class.getName());
types.add(Double.class.getName());
types.add(Byte.TYPE.getName());
types.add(Short.TYPE.getName());
types.add(Integer.TYPE.getName());
types.add(Long.TYPE.getName());
types.add(Float.TYPE.getName());
types.add(Double.TYPE.getName());
}
if (optionContext.contains("java-all") || optionContext.contains("java-number")) {
// misc
types.add(BigDecimal.class.getName());
types.add(BigInteger.class.getName());
}
if (optionContext.contains("java-all") || optionContext.contains("java-util") || optionContext.contains("java-collections")) {
// util
types.add(Collection.class.getName());
types.add(List.class.getName());
types.add(Queue.class.getName());
types.add(Set.class.getName());
types.add(SortedSet.class.getName());
types.add(Map.class.getName());
}
if (optionContext.contains("java-all") || optionContext.contains("java-util") || optionContext.contains("java-date")) {
// util
types.add(Date.class.getName());
types.add(Calendar.class.getName());
}
for (String type : types) {
if (type.startsWith(existingData) || existingData.startsWith(type)) {
completions.add(new Completion(type));
}
}
}
private void completeProjectSpecificPaths(final List<Completion> completions, String existingData) {
String topLevelPath = "";
if (!projectOperations.isFocusedProjectAvailable()) {
return;
}
topLevelPath = typeLocationService.getTopLevelPackageForModule(projectOperations.getFocusedModule());
Pom focusedModule = projectOperations.getFocusedModule();
String focusedModulePath = projectOperations.getFocusedModule().getPath();
String focusedModuleName = focusedModule.getModuleName();
boolean intraModule = false;
if (existingData.contains(MODULE_PATH_SEPARATOR)) {
focusedModuleName = existingData.substring(0, existingData.indexOf(MODULE_PATH_SEPARATOR));
focusedModule = projectOperations.getPomFromModuleName(focusedModuleName);
focusedModulePath = focusedModule.getPath();
existingData = existingData.substring(existingData.indexOf(MODULE_PATH_SEPARATOR) + 1, existingData.length());
topLevelPath = typeLocationService.getTopLevelPackageForModule(focusedModule);
intraModule = true;
}
String newValue = existingData;
if (existingData.startsWith("~")) {
if (existingData.length() > 1) {
newValue = (existingData.charAt(1) == '.' ? topLevelPath : topLevelPath + ".") + existingData.substring(1);
} else {
newValue = topLevelPath + ".";
}
}
String prefix = "";
String formattedPrefix = "";
if (!focusedModulePath.equals(projectOperations.getFocusedModule().getPath())) {
prefix = focusedModuleName + MODULE_PATH_SEPARATOR;
formattedPrefix = AnsiEscapeCode.decorate(focusedModuleName + MODULE_PATH_SEPARATOR, AnsiEscapeCode.FG_CYAN);
}
for (String moduleName : projectOperations.getPomManagementService().getModuleNames()) {
if (!moduleName.equals(focusedModuleName)) {
Completion completion = new Completion(moduleName + MODULE_PATH_SEPARATOR, AnsiEscapeCode.decorate(moduleName + MODULE_PATH_SEPARATOR, AnsiEscapeCode.FG_CYAN), "Modules", 0);
completions.add(completion);
}
}
String heading = "";
if (!intraModule) {
heading = focusedModuleName;
}
if (typeLocationService.getTypesForModule(focusedModulePath).isEmpty()) {
completions.add(new Completion(prefix + focusedModule.getGroupId(), formattedPrefix + focusedModule.getGroupId(), heading, 1));
return;
} else {
completions.add(new Completion(prefix + topLevelPath, formattedPrefix + topLevelPath, heading, 1));
}
for (String type : typeLocationService.getTypesForModule(focusedModulePath)) {
if (type.startsWith(newValue)) {
type = StringUtils.replaceFirst(type, topLevelPath, "~");
completions.add(new Completion(prefix + type, formattedPrefix + type, heading, 1));
}
}
}
private JavaType getNumberPrimitiveType(final String value) {
if ("byte".equals(value)) {
return JavaType.BYTE_PRIMITIVE;
} else if ("short".equals(value)) {
return JavaType.SHORT_PRIMITIVE;
} else if ("int".equals(value)) {
return JavaType.INT_PRIMITIVE;
} else if ("long".equals(value)) {
return JavaType.LONG_PRIMITIVE;
} else if ("float".equals(value)) {
return JavaType.FLOAT_PRIMITIVE;
} else if ("double".equals(value)) {
return JavaType.DOUBLE_PRIMITIVE;
} else {
return null;
}
}
}
| ROO-120: Support multi module Maven projects - JavaTypeConverter now only focusses the converted type's module if the optionContext contains "update"
| classpath/src/main/java/org/springframework/roo/classpath/converters/JavaTypeConverter.java | ROO-120: Support multi module Maven projects - JavaTypeConverter now only focusses the converted type's module if the optionContext contains "update" | <ide><path>lasspath/src/main/java/org/springframework/roo/classpath/converters/JavaTypeConverter.java
<ide> module = projectOperations.getPomManagementService().getPomFromModuleName(moduleName);
<ide> topLevelPath = typeLocationService.getTopLevelPackageForModule(module);
<ide> value = value.substring(value.indexOf(MODULE_PATH_SEPARATOR) + 1, value.length()).trim();
<del> projectOperations.getPomManagementService().setFocusedModule(module);
<add> if (optionContext.contains("update")) {
<add> projectOperations.getPomManagementService().setFocusedModule(module);
<add> }
<ide> } else {
<ide> topLevelPath = typeLocationService.getTopLevelPackageForModule(projectOperations.getFocusedModule());
<ide> } |
|
Java | lgpl-2.1 | 11412c960233114f24c2da13edbd4ff9a6f6ca3a | 0 | threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya | //
// $Id$
//
// Narya library - tools for developing networked games
// Copyright (C) 2002-2004 Three Rings Design, Inc., All Rights Reserved
// http://www.threerings.net/code/narya/
//
// 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 com.threerings.crowd.chat.client;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.samskivert.util.Collections;
import com.samskivert.util.HashIntMap;
import com.samskivert.util.ObserverList;
import com.samskivert.util.ResultListener;
import com.samskivert.util.StringUtil;
import com.threerings.presents.client.BasicDirector;
import com.threerings.presents.client.Client;
import com.threerings.presents.data.ClientObject;
import com.threerings.presents.dobj.DObject;
import com.threerings.presents.dobj.MessageEvent;
import com.threerings.presents.dobj.MessageListener;
import com.threerings.util.MessageBundle;
import com.threerings.util.MessageManager;
import com.threerings.util.Name;
import com.threerings.util.TimeUtil;
import com.threerings.crowd.Log;
import com.threerings.crowd.client.LocationObserver;
import com.threerings.crowd.data.BodyObject;
import com.threerings.crowd.data.PlaceObject;
import com.threerings.crowd.util.CrowdContext;
import com.threerings.crowd.chat.data.ChatCodes;
import com.threerings.crowd.chat.data.ChatMessage;
import com.threerings.crowd.chat.data.SystemMessage;
import com.threerings.crowd.chat.data.TellFeedbackMessage;
import com.threerings.crowd.chat.data.UserMessage;
import com.threerings.crowd.chat.data.UserSystemMessage;
/**
* The chat director is the client side coordinator of all chat related
* services. It handles both place constrained chat as well as direct
* messaging.
*/
public class ChatDirector extends BasicDirector
implements ChatCodes, LocationObserver, MessageListener
{
/**
* An interface to receive information about the {@link #MAX_CHATTERS}
* most recent users that we've been chatting with.
*/
public static interface ChatterObserver
{
/**
* Called when the list of chatters has been changed.
*/
public void chattersUpdated (Iterator chatternames);
}
/**
* An interface for those who would like to validate whether usernames
* may be added to the chatter list.
*/
public static interface ChatterValidator
{
/**
* Returns whether the username may be added to the chatters list.
*/
public boolean isChatterValid (Name username);
}
/**
* Used to implement a slash command (e.g. <code>/who</code>).
*/
public static abstract class CommandHandler
{
/**
* Handles the specified chat command.
*
* @param speakSvc an optional SpeakService object representing
* the object to send the chat message on.
* @param command the slash command that was used to invoke this
* handler (e.g. <code>/tell</code>).
* @param args the arguments provided along with the command (e.g.
* <code>Bob hello</code>) or <code>null</code> if no arguments
* were supplied.
* @param history an in/out parameter that allows the command to
* modify the text that will be appended to the chat history. If
* this is set to null, nothing will be appended.
*
* @return an untranslated string that will be reported to the
* chat box to convey an error response to the user, or {@link
* ChatCodes#SUCCESS}.
*/
public abstract String handleCommand (
SpeakService speakSvc, String command, String args,
String[] history);
/**
* Returns true if this user should have access to this chat
* command.
*/
public boolean checkAccess (BodyObject user)
{
return true;
}
}
/**
* Creates a chat director and initializes it with the supplied
* context. The chat director will register itself as a location
* observer so that it can automatically process place constrained
* chat.
*
* @param msgmgr the message manager via which we do our translations.
* @param bundle the message bundle from which we obtain our
* chat-related translation strings.
*/
public ChatDirector (CrowdContext ctx, MessageManager msgmgr, String bundle)
{
super(ctx);
// keep the context around
_ctx = ctx;
_msgmgr = msgmgr;
_bundle = bundle;
// register ourselves as a location observer
_ctx.getLocationDirector().addLocationObserver(this);
// register our default chat handlers
if (_bundle == null || _msgmgr == null) {
Log.warning("Null bundle or message manager given to ChatDirector");
return;
}
MessageBundle msg = _msgmgr.getBundle(_bundle);
registerCommandHandler(msg, "help", new HelpHandler());
registerCommandHandler(msg, "clear", new ClearHandler());
registerCommandHandler(msg, "speak", new SpeakHandler());
registerCommandHandler(msg, "emote", new EmoteHandler());
registerCommandHandler(msg, "think", new ThinkHandler());
}
/**
* Adds the supplied chat display to the chat display list. It will
* subsequently be notified of incoming chat messages as well as tell
* responses.
*/
public void addChatDisplay (ChatDisplay display)
{
_displays.add(display);
}
/**
* Removes the specified chat display from the chat display list. The
* display will no longer receive chat related notifications.
*/
public void removeChatDisplay (ChatDisplay display)
{
_displays.remove(display);
}
/**
* Adds the specified chat filter to the list of filters. All
* chat requests and receipts will be filtered with all filters
* before they being sent or dispatched locally.
*/
public void addChatFilter (ChatFilter filter)
{
_filters.add(filter);
}
/**
* Removes the specified chat validator from the list of chat validators.
*/
public void removeChatFilter (ChatFilter filter)
{
_filters.remove(filter);
}
/**
* Adds an observer that watches the chatters list, and updates it
* immediately.
*/
public void addChatterObserver (ChatterObserver co)
{
_chatterObservers.add(co);
co.chattersUpdated(_chatters.listIterator());
}
/**
* Removes an observer from the list of chatter observers.
*/
public void removeChatterObserver (ChatterObserver co)
{
_chatterObservers.remove(co);
}
/**
* Sets the validator that decides if a username is valid to be
* added to the chatter list, or null if no such filtering is desired.
*/
public void setChatterValidator (ChatterValidator validator)
{
_chatterValidator = validator;
}
/**
* Registers a chat command handler.
*
* @param msg the message bundle via which the slash command will be
* translated (as <code>c.</code><i>command</i>). If no translation
* exists the command will be <code>/</code><i>command</i>.
* @param command the name of the command that will be used to invoke
* this handler (e.g. <code>tell</code> if the command will be invoked
* as <code>/tell</code>).
* @param handler the chat command handler itself.
*/
public void registerCommandHandler (
MessageBundle msg, String command, CommandHandler handler)
{
String key = "c." + command;
if (msg.exists(key)) {
StringTokenizer st = new StringTokenizer(msg.get(key));
while (st.hasMoreTokens()) {
_handlers.put(st.nextToken(), handler);
}
} else {
// fall back to just using the English command
_handlers.put(command, handler);
}
}
/**
* Return the current size of the history.
*/
public int getCommandHistorySize ()
{
return _history.size();
}
/**
* Get the chat history entry at the specified index,
* with 0 being the oldest.
*/
public String getCommandHistory (int index)
{
return _history.get(index);
}
/**
* Clear the chat command history.
*/
public void clearCommandHistory ()
{
_history.clear();
}
/**
* Requests that all chat displays clear their contents.
*/
public void clearDisplays ()
{
_displays.apply(new ObserverList.ObserverOp<ChatDisplay>() {
public boolean apply (ChatDisplay observer) {
observer.clear();
return true;
}
});
}
/**
* Display a system INFO message as if it had come from the server.
* The localtype of the message will be PLACE_CHAT_TYPE.
*
* Info messages are sent when something happens that was neither
* directly triggered by the user, nor requires direct action.
*/
public void displayInfo (String bundle, String message)
{
displaySystem(bundle, message, SystemMessage.INFO, PLACE_CHAT_TYPE);
}
/**
* Display a system INFO message as if it had come from the server.
*
* Info messages are sent when something happens that was neither
* directly triggered by the user, nor requires direct action.
*/
public void displayInfo (String bundle, String message, String localtype)
{
displaySystem(bundle, message, SystemMessage.INFO, localtype);
}
/**
* Display a system FEEDBACK message as if it had come from the server.
* The localtype of the message will be PLACE_CHAT_TYPE.
*
* Feedback messages are sent in direct response to a user action,
* usually to indicate success or failure of the user's action.
*/
public void displayFeedback (String bundle, String message)
{
displaySystem(
bundle, message, SystemMessage.FEEDBACK, PLACE_CHAT_TYPE);
}
/**
* Display a system ATTENTION message as if it had come from the server.
* The localtype of the message will be PLACE_CHAT_TYPE.
*
* Attention messages are sent when something requires user action
* that did not result from direct action by the user.
*/
public void displayAttention (String bundle, String message)
{
displaySystem(
bundle, message, SystemMessage.ATTENTION, PLACE_CHAT_TYPE);
}
/**
* Dispatches the provided message to our chat displays.
*/
public void dispatchMessage (ChatMessage message)
{
_displayMessageOp.setMessage(message);
_displays.apply(_displayMessageOp);
}
/**
* Parses and delivers the supplied chat message. Slash command
* processing and mogrification are performed and the message is added
* to the chat history if appropriate.
*
* @param speakSvc the SpeakService representing the target dobj of
* the speak or null if we should speak in the "default" way.
* @param text the text to be parsed and sent.
* @param record if text is a command, should it be added to the history?
*
* @return <code>ChatCodes#SUCCESS</code> if the message was parsed
* and sent correctly, a translatable error string if there was some
* problem.
*/
public String requestChat (
SpeakService speakSvc, String text, boolean record)
{
if (text.startsWith("/")) {
// split the text up into a command and arguments
String command = text.substring(1).toLowerCase();
String[] hist = new String[1];
String args = "";
int sidx = text.indexOf(" ");
if (sidx != -1) {
command = text.substring(1, sidx).toLowerCase();
args = text.substring(sidx+1).trim();
}
HashMap<String,CommandHandler> possibleCommands =
getCommandHandlers(command);
switch (possibleCommands.size()) {
case 0:
StringTokenizer tok = new StringTokenizer(text);
return MessageBundle.tcompose(
"m.unknown_command", tok.nextToken());
case 1:
Map.Entry<String,CommandHandler> entry =
possibleCommands.entrySet().iterator().next();
String cmdName = entry.getKey();
CommandHandler cmd = entry.getValue();
String result = cmd.handleCommand(
speakSvc, cmdName, args, hist);
if (!result.equals(ChatCodes.SUCCESS)) {
return result;
}
if (record) {
// get the final history-ready command string
hist[0] = "/" + ((hist[0] == null) ? command : hist[0]);
// remove from history if it was present and
// add it to the end
addToHistory(hist[0]);
}
return result;
default:
String alternativeCommands = "";
Iterator<String> itr = Collections.getSortedIterator(
possibleCommands.keySet());
while (itr.hasNext()) {
alternativeCommands += " /" + itr.next();
}
return MessageBundle.tcompose(
"m.unspecific_command", alternativeCommands);
}
}
// if not a command then just speak
String message = text.trim();
if (StringUtil.isBlank(message)) {
// report silent failure for now
return ChatCodes.SUCCESS;
}
return deliverChat(speakSvc, message, ChatCodes.DEFAULT_MODE);
}
/**
* Requests that a speak message with the specified mode be generated
* and delivered via the supplied speak service instance (which will
* be associated with a particular "speak object"). The message will
* first be validated by all registered {@link ChatFilter}s (and
* possibly vetoed) before being dispatched.
*
* @param speakService the speak service to use when generating the
* speak request or null if we should speak in the current "place".
* @param message the contents of the speak message.
* @param mode a speech mode that will be interpreted by the {@link
* ChatDisplay} implementations that eventually display this speak
* message.
*/
public void requestSpeak (
SpeakService speakService, String message, byte mode)
{
if (speakService == null) {
if (_place == null) {
return;
}
speakService = _place.speakService;
}
// make sure they can say what they want to say
message = filter(message, null, true);
if (message == null) {
return;
}
// dispatch a speak request using the supplied speak service
speakService.speak(_ctx.getClient(), message, mode);
}
/**
* Requests to send a site-wide broadcast message.
*
* @param message the contents of the message.
*/
public void requestBroadcast (String message)
{
message = filter(message, null, true);
if (message == null) {
displayFeedback(_bundle,
MessageBundle.compose("m.broadcast_failed", "m.filtered"));
return;
}
_cservice.broadcast(
_ctx.getClient(), message, new ChatService.InvocationListener() {
public void requestFailed (String reason) {
reason = MessageBundle.compose(
"m.broadcast_failed", reason);
displayFeedback(_bundle, reason);
}
});
}
/**
* Requests that a tell message be delivered to the specified target
* user.
*
* @param target the username of the user to which the tell message
* should be delivered.
* @param msg the contents of the tell message.
* @param rl an optional result listener if you'd like to be notified
* of success or failure.
*/
public void requestTell (final Name target, String msg,
final ResultListener rl)
{
// make sure they can say what they want to say
final String message = filter(msg, target, true);
if (message == null) {
if (rl != null) {
rl.requestFailed(null);
}
return;
}
// create a listener that will report success or failure
ChatService.TellListener listener = new ChatService.TellListener() {
public void tellSucceeded (long idletime, String awayMessage) {
success(xlate(_bundle, MessageBundle.tcompose(
"m.told_format", target, message)));
// if they have an away message, report that
if (awayMessage != null) {
awayMessage = filter(awayMessage, target, false);
if (awayMessage != null) {
String msg = MessageBundle.tcompose(
"m.recipient_afk", target, awayMessage);
displayFeedback(_bundle, msg);
}
}
// if they are idle, report that
if (idletime > 0L) {
// adjust by the time it took them to become idle
idletime += _ctx.getConfig().getValue(
IDLE_TIME_KEY, DEFAULT_IDLE_TIME);
String msg = MessageBundle.compose(
"m.recipient_idle", MessageBundle.taint(target),
TimeUtil.getTimeOrderString(idletime, TimeUtil.MINUTE));
displayFeedback(_bundle, msg);
}
}
protected void success (String feedback) {
dispatchMessage(new TellFeedbackMessage(feedback));
addChatter(target);
if (rl != null) {
rl.requestCompleted(target);
}
}
public void requestFailed (String reason) {
String msg = MessageBundle.compose(
"m.tell_failed", MessageBundle.taint(target), reason);
displayFeedback(_bundle, msg);
if (rl != null) {
rl.requestFailed(null);
}
}
};
_cservice.tell(_ctx.getClient(), target, message, listener);
}
/**
* Configures a message that will be automatically reported to anyone
* that sends a tell message to this client to indicate that we are
* busy or away from the keyboard.
*/
public void setAwayMessage (String message)
{
if (message != null) {
message = filter(message, null, true);
if (message == null) {
// they filtered away their own away message..
// change it to something
message = "...";
}
}
// pass the buck right on along
_cservice.away(_ctx.getClient(), message);
}
/**
* Adds an additional object via which chat messages may arrive. The
* chat director assumes the caller will be managing the subscription
* to this object and will remain subscribed to it for as long as it
* remains in effect as an auxiliary chat source.
*
* @param localtype a type to be associated with all chat messages
* that arrive on the specified DObject.
*/
public void addAuxiliarySource (DObject source, String localtype)
{
source.addListener(this);
_auxes.put(source.getOid(), localtype);
}
/**
* Removes a previously added auxiliary chat source.
*/
public void removeAuxiliarySource (DObject source)
{
source.removeListener(this);
_auxes.remove(source.getOid());
}
/**
* Run a message through all the currently registered filters.
*/
public String filter (String msg, Name otherUser, boolean outgoing)
{
_filterMessageOp.setMessage(msg, otherUser, outgoing);
_filters.apply(_filterMessageOp);
return _filterMessageOp.getMessage();
}
/**
* Runs the supplied message through the various chat mogrifications.
*/
public String mogrifyChat (String text)
{
return mogrifyChat(text, false, true);
}
// documentation inherited
public boolean locationMayChange (int placeId)
{
// we accept all location change requests
return true;
}
// documentation inherited
public void locationDidChange (PlaceObject place)
{
if (_place != null) {
// unlisten to our old object
_place.removeListener(this);
}
// listen to the new object
_place = place;
if (_place != null) {
_place.addListener(this);
}
}
// documentation inherited
public void locationChangeFailed (int placeId, String reason)
{
// nothing we care about
}
// documentation inherited
public void messageReceived (MessageEvent event)
{
if (CHAT_NOTIFICATION.equals(event.getName())) {
ChatMessage msg = (ChatMessage) event.getArgs()[0];
String localtype = getLocalType(event.getTargetOid());
String message = msg.message;
String autoResponse = null;
Name speaker = null;
byte mode = (byte) -1;
// figure out if the message was triggered by another user
if (msg instanceof UserMessage) {
UserMessage umsg = (UserMessage)msg;
speaker = umsg.speaker;
mode = umsg.mode;
} else if (msg instanceof UserSystemMessage) {
speaker = ((UserSystemMessage) msg).speaker;
}
// if there was an originating speaker, see if we want to hear it
if (speaker != null) {
if ((message = filter(message, speaker, false)) == null) {
return;
}
if (USER_CHAT_TYPE.equals(localtype) &&
mode == ChatCodes.DEFAULT_MODE) {
// if it was a tell, add the speaker as a chatter
addChatter(speaker);
// note whether or not we have an auto-response
BodyObject self = (BodyObject)
_ctx.getClient().getClientObject();
if (!StringUtil.isBlank(self.awayMessage)) {
autoResponse = self.awayMessage;
}
}
}
// initialize the client-specific fields of the message
msg.setClientInfo(xlate(msg.bundle, message), localtype);
// and send it off!
dispatchMessage(msg);
// if we auto-responded, report as much
if (autoResponse != null) {
String amsg = MessageBundle.tcompose(
"m.auto_responded", speaker, autoResponse);
displayFeedback(_bundle, amsg);
}
}
}
// documentation inherited
public void clientDidLogon (Client client)
{
super.clientDidLogon(client);
// listen on the client object for tells
addAuxiliarySource(_clobj = client.getClientObject(), USER_CHAT_TYPE);
}
// documentation inherited
public void clientObjectDidChange (Client client)
{
super.clientObjectDidChange(client);
// change what we're listening to for tells
removeAuxiliarySource(_clobj);
addAuxiliarySource(_clobj = client.getClientObject(), USER_CHAT_TYPE);
clearDisplays();
}
// documentation inherited
public void clientDidLogoff (Client client)
{
super.clientDidLogoff(client);
// stop listening to it for tells
if (_clobj != null) {
removeAuxiliarySource(_clobj);
_clobj = null;
}
// in fact, clear out all auxiliary sources
_auxes.clear();
clearDisplays();
// clear out the list of people we've chatted with
_chatters.clear();
notifyChatterObservers();
// clear the _place
locationDidChange(null);
// clear our service
_cservice = null;
}
/**
* Called to determine whether we are permitted to post the supplied
* chat message. Derived classes may wish to throttle chat or restrict
* certain types in certain circumstances for whatever reason.
*
* @return null if the chat is permitted, SUCCESS if the chat is permitted
* and has already been dealt with, or a translatable string
* indicating the reason for rejection if not.
*/
protected String checkCanChat (
SpeakService speakSvc, String message, byte mode)
{
return null;
}
/**
* Delivers a plain chat message (not a slash command) on the
* specified speak service in the specified mode. The message will be
* mogrified and filtered prior to delivery.
*
* @return {@link ChatCodes#SUCCESS} if the message was delivered or a
* string indicating why it failed.
*/
protected String deliverChat (
SpeakService speakSvc, String message, byte mode)
{
// run the message through our mogrification process
message = mogrifyChat(message, true, mode != ChatCodes.EMOTE_MODE);
// mogrification may result in something being turned into a slash
// command, in which case we have to run everything through again
// from the start
if (message.startsWith("/")) {
return requestChat(speakSvc, message, false);
}
// make sure this client is not restricted from performing this
// chat message for some reason or other
String errmsg = checkCanChat(speakSvc, message, mode);
if (errmsg != null) {
return errmsg;
}
// speak on the specified service
requestSpeak(speakSvc, message, mode);
return ChatCodes.SUCCESS;
}
/**
* Add the specified command to the history.
*/
protected void addToHistory (String cmd)
{
// remove any previous instance of this command
_history.remove(cmd);
// append it to the end
_history.add(cmd);
// prune the history once it extends beyond max size
if (_history.size() > MAX_COMMAND_HISTORY) {
_history.remove(0);
}
}
/**
* Mogrify common literary crutches into more appealing chat or
* commands.
*
* @param transformsAllowed if true, the chat may transformed into a
* different mode. (lol -> /emote laughs)
* @param capFirst if true, the first letter of the text is
* capitalized. This is not desired if the chat is already an emote.
*/
protected String mogrifyChat (
String text, boolean transformsAllowed, boolean capFirst)
{
int tlen = text.length();
if (tlen == 0) {
return text;
// check to make sure there aren't too many caps
} else if (tlen > 7) {
// count caps
int caps = 0;
for (int ii=0; ii < tlen; ii++) {
if (Character.isUpperCase(text.charAt(ii))) {
caps++;
if (caps > (tlen / 2)) {
// lowercase the whole string if there are
text = text.toLowerCase();
break;
}
}
}
}
StringBuffer buf = new StringBuffer(text);
buf = mogrifyChat(buf, transformsAllowed, capFirst);
return buf.toString();
}
/** Helper function for {@link #mogrifyChat}. */
protected StringBuffer mogrifyChat (
StringBuffer buf, boolean transformsAllowed, boolean capFirst)
{
// do the generic mogrifications and translations
buf = translatedReplacements("x.mogrifies", buf);
// perform themed expansions and transformations
if (transformsAllowed) {
buf = translatedReplacements("x.transforms", buf);
}
/*
// capitalize the first letter
if (capFirst) {
buf.setCharAt(0, Character.toUpperCase(buf.charAt(0)));
}
// and capitalize any letters after a sentence-ending punctuation
Pattern p = Pattern.compile("([^\\.][\\.\\?\\!](\\s)+\\p{Ll})");
Matcher m = p.matcher(buf);
if (m.find()) {
buf = new StringBuffer();
m.appendReplacement(buf, m.group().toUpperCase());
while (m.find()) {
m.appendReplacement(buf, m.group().toUpperCase());
}
m.appendTail(buf);
}
*/
return buf;
}
/**
* Do all the replacements (mogrifications) specified in the
* translation string specified by the key.
*/
protected StringBuffer translatedReplacements (String key, StringBuffer buf)
{
MessageBundle bundle = _msgmgr.getBundle(_bundle);
if (!bundle.exists(key)) {
return buf;
}
StringTokenizer st = new StringTokenizer(bundle.get(key), "#");
// apply the replacements to each mogrification that matches
while (st.hasMoreTokens()) {
String pattern = st.nextToken();
String replace = st.nextToken();
Matcher m = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE).
matcher(buf);
if (m.find()) {
buf = new StringBuffer();
m.appendReplacement(buf, replace);
// they may match more than once
while (m.find()) {
m.appendReplacement(buf, replace);
}
m.appendTail(buf);
}
}
return buf;
}
/**
* Returns a hashmap containing all command handlers that match the
* specified command (i.e. the specified command is a prefix of their
* registered command string).
*/
protected HashMap<String,CommandHandler> getCommandHandlers (String command)
{
HashMap<String,CommandHandler> matches =
new HashMap<String,CommandHandler>();
BodyObject user = (BodyObject)_ctx.getClient().getClientObject();
for (Map.Entry<String,CommandHandler> entry : _handlers.entrySet()) {
String cmd = entry.getKey();
if (!cmd.startsWith(command)) {
continue;
}
CommandHandler handler = entry.getValue();
if (!handler.checkAccess(user)) {
continue;
}
matches.put(cmd, handler);
}
return matches;
}
/**
* Adds a chatter to our list of recent chatters.
*/
protected void addChatter (Name name)
{
// check to see if the chatter validator approves..
if ((_chatterValidator != null) &&
(!_chatterValidator.isChatterValid(name))) {
return;
}
boolean wasthere = _chatters.remove(name);
_chatters.addFirst(name);
if (!wasthere) {
if (_chatters.size() > MAX_CHATTERS) {
_chatters.removeLast();
}
notifyChatterObservers();
}
}
/**
* Notifies all registered {@link ChatterObserver}s that the list of
* chatters has changed.
*/
protected void notifyChatterObservers ()
{
_chatterObservers.apply(new ObserverList.ObserverOp<ChatterObserver>() {
public boolean apply (ChatterObserver observer) {
observer.chattersUpdated(_chatters.listIterator());
return true;
}
});
}
/**
* Translates the specified message using the specified bundle.
*/
protected String xlate (String bundle, String message)
{
if (bundle != null && _msgmgr != null) {
MessageBundle msgb = _msgmgr.getBundle(bundle);
if (msgb == null) {
Log.warning(
"No message bundle available to translate message " +
"[bundle=" + bundle + ", message=" + message + "].");
} else {
message = msgb.xlate(message);
}
}
return message;
}
/**
* Display the specified system message as if it had come from the server.
*/
protected void displaySystem (
String bundle, String message, byte attLevel, String localtype)
{
// nothing should be untranslated, so pass the default bundle if need
// be.
if (bundle == null) {
bundle = _bundle;
}
SystemMessage msg = new SystemMessage();
msg.attentionLevel = attLevel;
msg.setClientInfo(xlate(bundle, message), localtype);
dispatchMessage(msg);
}
/**
* Looks up and returns the message type associated with the specified
* oid.
*/
protected String getLocalType (int oid)
{
String type = _auxes.get(oid);
return (type == null) ? PLACE_CHAT_TYPE : type;
}
// documentation inherited from interface
protected void fetchServices (Client client)
{
// get a handle on our chat service
_cservice = (ChatService)client.requireService(ChatService.class);
}
/**
* An operation that checks with all chat filters to properly filter
* a message prior to sending to the server or displaying.
*/
protected static class FilterMessageOp
implements ObserverList.ObserverOp<ChatFilter>
{
public void setMessage (String msg, Name otherUser, boolean outgoing)
{
_msg = msg;
_otherUser = otherUser;
_out = outgoing;
}
public boolean apply (ChatFilter observer)
{
if (_msg != null) {
_msg = observer.filter(_msg, _otherUser, _out);
}
return true;
}
public String getMessage ()
{
return _msg;
}
protected Name _otherUser;
protected String _msg;
protected boolean _out;
}
/**
* An observer op used to dispatch ChatMessages on the client.
*/
protected static class DisplayMessageOp
implements ObserverList.ObserverOp<ChatDisplay>
{
public void setMessage (ChatMessage message)
{
_message = message;
}
public boolean apply (ChatDisplay observer)
{
observer.displayMessage(_message);
return true;
}
protected ChatMessage _message;
}
/** Implements <code>/help</code>. */
protected class HelpHandler extends CommandHandler
{
public String handleCommand (SpeakService speakSvc, String command,
String args, String[] history)
{
String hcmd = "";
// grab the command they want help on
if (!StringUtil.isBlank(args)) {
hcmd = args;
int sidx = args.indexOf(" ");
if (sidx != -1) {
hcmd = args.substring(0, sidx);
}
}
// let the user give commands with or with the /
if (hcmd.startsWith("/")) {
hcmd = hcmd.substring(1);
}
// handle "/help help" and "/help someboguscommand"
HashMap<String,CommandHandler> possibleCommands =
getCommandHandlers(hcmd);
if (hcmd.equals("help") || possibleCommands.isEmpty()) {
possibleCommands = getCommandHandlers("");
possibleCommands.remove("help"); // remove help from the list
}
// if there is only one possible command display its usage
switch (possibleCommands.size()) {
case 1:
Iterator<String> itr = possibleCommands.keySet().iterator();
// this is a little funny, but we display the feeback
// message by hand and return SUCCESS so that the chat
// entry field doesn't think that we've failed and
// preserve our command text
displayFeedback(null, "m.usage_" + itr.next());
return ChatCodes.SUCCESS;
default:
Object[] commands = possibleCommands.keySet().toArray();
Arrays.sort(commands);
String commandList = "";
for (int ii = 0; ii < commands.length; ii++) {
commandList += " /" + commands[ii];
}
return MessageBundle.tcompose("m.usage_help", commandList);
}
}
}
/** Implements <code>/clear</code>. */
protected class ClearHandler extends CommandHandler
{
public String handleCommand (SpeakService speakSvc, String command,
String args, String[] history)
{
clearDisplays();
return ChatCodes.SUCCESS;
}
}
/** Implements <code>/speak</code>. */
protected class SpeakHandler extends CommandHandler
{
public String handleCommand (SpeakService speakSvc, String command,
String args, String[] history)
{
if (StringUtil.isBlank(args)) {
return "m.usage_speak";
}
// note the command to be stored in the history
history[0] = command + " ";
return requestChat(null, args, true);
}
}
/** Implements <code>/emote</code>. */
protected class EmoteHandler extends CommandHandler
{
public String handleCommand (SpeakService speakSvc, String command,
String args, String[] history)
{
if (StringUtil.isBlank(args)) {
return "m.usage_emote";
}
// note the command to be stored in the history
history[0] = command + " ";
return deliverChat(speakSvc, args, ChatCodes.EMOTE_MODE);
}
}
/** Implements <code>/think</code>. */
protected class ThinkHandler extends CommandHandler
{
public String handleCommand (SpeakService speakSvc, String command,
String args, String[] history)
{
if (StringUtil.isBlank(args)) {
return "m.usage_think";
}
// note the command to be stored in the history
history[0] = command + " ";
return deliverChat(speakSvc, args, ChatCodes.THINK_MODE);
}
}
/** Implements <code>/tell</code>. */
protected class TellHandler extends CommandHandler
{
public String handleCommand (
SpeakService speakSvc, final String command, String args,
String[] history)
{
// there should be at least two arg tokens: '/tell target word'
StringTokenizer tok = new StringTokenizer(args);
if (tok.countTokens() < 2) {
return "m.usage_tell";
}
// if the handle starts with a quote, keep tacking on words until
// we find the end quote
String handle = tok.nextToken();
if (handle.startsWith("\"")) {
while (!handle.endsWith("\"") && tok.hasMoreTokens()) {
handle = handle + " " + tok.nextToken();
}
}
if (!handle.endsWith("\"")) {
return "m.usage_tell";
}
// now strip off everything after the handle for the message
int uidx = args.indexOf(handle);
String message = args.substring(uidx + handle.length()).trim();
if (StringUtil.isBlank(message)) {
return "m.usage_tell";
}
// strip the quotes off of the handle
if (handle.startsWith("\"")) {
handle = handle.substring(1, handle.length()-1);
}
// make sure we're not trying to tell something to ourselves
BodyObject self = (BodyObject)_ctx.getClient().getClientObject();
if (handle.equalsIgnoreCase(self.getVisibleName().toString())) {
return "m.talk_self";
}
// clear out from the history any tells that are mistypes
for (Iterator iter = _history.iterator(); iter.hasNext(); ) {
String hist = (String) iter.next();
if (hist.startsWith("/" + command) &&
(new StringTokenizer(hist).countTokens() > 2)) {
iter.remove();
}
}
// mogrify the chat
message = mogrifyChat(message);
// store the full command in the history, even if it was mistyped
final String histEntry = command + " \"" + handle + "\" " + message;
history[0] = histEntry;
// request to send this text as a tell message
requestTell(new Name(handle), message, new ResultListener() {
public void requestCompleted (Object result) {
// replace the full one in the history with just:
// /tell "<handle>"
String newEntry = "/" + command + " \"" + result + "\" ";
_history.remove(newEntry);
int dex = _history.lastIndexOf("/" + histEntry);
if (dex >= 0) {
_history.set(dex, newEntry);
} else {
_history.add(newEntry);
}
}
public void requestFailed (Exception cause) {
// do nothing
}
});
return ChatCodes.SUCCESS;
}
}
/** Our active chat context. */
protected CrowdContext _ctx;
/** Provides access to chat-related server-side services. */
protected ChatService _cservice;
/** The message manager. */
protected MessageManager _msgmgr;
/** The bundle to use for our own internal messages. */
protected String _bundle;
/** The place object that we currently occupy. */
protected PlaceObject _place;
/** The client object that we're listening to for tells. */
protected ClientObject _clobj;
/** A list of registered chat displays. */
protected ObserverList<ChatDisplay> _displays =
new ObserverList<ChatDisplay>(ObserverList.FAST_UNSAFE_NOTIFY);
/** A list of registered chat filters. */
protected ObserverList<ChatFilter> _filters =
new ObserverList<ChatFilter>(ObserverList.FAST_UNSAFE_NOTIFY);
/** A mapping from auxiliary chat objects to the types under which
* they are registered. */
protected HashIntMap<String> _auxes = new HashIntMap<String>();
/** Validator of who may be added to the chatters list. */
protected ChatterValidator _chatterValidator;
/** Usernames of users we've recently chatted with. */
protected LinkedList<Name> _chatters = new LinkedList<Name>();
/** Observers that are watching our chatters list. */
protected ObserverList<ChatterObserver> _chatterObservers =
new ObserverList<ChatterObserver>(ObserverList.FAST_UNSAFE_NOTIFY);
/** Registered chat command handlers. */
protected static HashMap<String,CommandHandler> _handlers =
new HashMap<String,CommandHandler>();
/** A history of chat commands. */
protected static ArrayList<String> _history = new ArrayList<String>();
/** Operation used to filter chat messages. */
protected FilterMessageOp _filterMessageOp = new FilterMessageOp();
/** Operation used to display chat messages. */
protected DisplayMessageOp _displayMessageOp = new DisplayMessageOp();
/** The maximum number of chatter usernames to track. */
protected static final int MAX_CHATTERS = 6;
/** The maximum number of commands to keep in the chat history. */
protected static final int MAX_COMMAND_HISTORY = 10;
}
| src/java/com/threerings/crowd/chat/client/ChatDirector.java | //
// $Id$
//
// Narya library - tools for developing networked games
// Copyright (C) 2002-2004 Three Rings Design, Inc., All Rights Reserved
// http://www.threerings.net/code/narya/
//
// 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 com.threerings.crowd.chat.client;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.samskivert.util.Collections;
import com.samskivert.util.HashIntMap;
import com.samskivert.util.ObserverList;
import com.samskivert.util.ResultListener;
import com.samskivert.util.StringUtil;
import com.threerings.presents.client.BasicDirector;
import com.threerings.presents.client.Client;
import com.threerings.presents.data.ClientObject;
import com.threerings.presents.dobj.DObject;
import com.threerings.presents.dobj.MessageEvent;
import com.threerings.presents.dobj.MessageListener;
import com.threerings.util.MessageBundle;
import com.threerings.util.MessageManager;
import com.threerings.util.Name;
import com.threerings.util.TimeUtil;
import com.threerings.crowd.Log;
import com.threerings.crowd.client.LocationObserver;
import com.threerings.crowd.data.BodyObject;
import com.threerings.crowd.data.PlaceObject;
import com.threerings.crowd.util.CrowdContext;
import com.threerings.crowd.chat.data.ChatCodes;
import com.threerings.crowd.chat.data.ChatMessage;
import com.threerings.crowd.chat.data.SystemMessage;
import com.threerings.crowd.chat.data.TellFeedbackMessage;
import com.threerings.crowd.chat.data.UserMessage;
import com.threerings.crowd.chat.data.UserSystemMessage;
/**
* The chat director is the client side coordinator of all chat related
* services. It handles both place constrained chat as well as direct
* messaging.
*/
public class ChatDirector extends BasicDirector
implements ChatCodes, LocationObserver, MessageListener
{
/**
* An interface to receive information about the {@link #MAX_CHATTERS}
* most recent users that we've been chatting with.
*/
public static interface ChatterObserver
{
/**
* Called when the list of chatters has been changed.
*/
public void chattersUpdated (Iterator chatternames);
}
/**
* An interface for those who would like to validate whether usernames
* may be added to the chatter list.
*/
public static interface ChatterValidator
{
/**
* Returns whether the username may be added to the chatters list.
*/
public boolean isChatterValid (Name username);
}
/**
* Used to implement a slash command (e.g. <code>/who</code>).
*/
public static abstract class CommandHandler
{
/**
* Handles the specified chat command.
*
* @param speakSvc an optional SpeakService object representing
* the object to send the chat message on.
* @param command the slash command that was used to invoke this
* handler (e.g. <code>/tell</code>).
* @param args the arguments provided along with the command (e.g.
* <code>Bob hello</code>) or <code>null</code> if no arguments
* were supplied.
* @param history an in/out parameter that allows the command to
* modify the text that will be appended to the chat history. If
* this is set to null, nothing will be appended.
*
* @return an untranslated string that will be reported to the
* chat box to convey an error response to the user, or {@link
* ChatCodes#SUCCESS}.
*/
public abstract String handleCommand (
SpeakService speakSvc, String command, String args,
String[] history);
/**
* Returns true if this user should have access to this chat
* command.
*/
public boolean checkAccess (BodyObject user)
{
return true;
}
}
/**
* Creates a chat director and initializes it with the supplied
* context. The chat director will register itself as a location
* observer so that it can automatically process place constrained
* chat.
*
* @param msgmgr the message manager via which we do our translations.
* @param bundle the message bundle from which we obtain our
* chat-related translation strings.
*/
public ChatDirector (CrowdContext ctx, MessageManager msgmgr, String bundle)
{
super(ctx);
// keep the context around
_ctx = ctx;
_msgmgr = msgmgr;
_bundle = bundle;
// register ourselves as a location observer
_ctx.getLocationDirector().addLocationObserver(this);
// register our default chat handlers
if (_bundle == null || _msgmgr == null) {
Log.warning("Null bundle or message manager given to ChatDirector");
return;
}
MessageBundle msg = _msgmgr.getBundle(_bundle);
registerCommandHandler(msg, "help", new HelpHandler());
registerCommandHandler(msg, "clear", new ClearHandler());
registerCommandHandler(msg, "speak", new SpeakHandler());
registerCommandHandler(msg, "emote", new EmoteHandler());
registerCommandHandler(msg, "think", new ThinkHandler());
}
/**
* Adds the supplied chat display to the chat display list. It will
* subsequently be notified of incoming chat messages as well as tell
* responses.
*/
public void addChatDisplay (ChatDisplay display)
{
_displays.add(display);
}
/**
* Removes the specified chat display from the chat display list. The
* display will no longer receive chat related notifications.
*/
public void removeChatDisplay (ChatDisplay display)
{
_displays.remove(display);
}
/**
* Adds the specified chat filter to the list of filters. All
* chat requests and receipts will be filtered with all filters
* before they being sent or dispatched locally.
*/
public void addChatFilter (ChatFilter filter)
{
_filters.add(filter);
}
/**
* Removes the specified chat validator from the list of chat validators.
*/
public void removeChatFilter (ChatFilter filter)
{
_filters.remove(filter);
}
/**
* Adds an observer that watches the chatters list, and updates it
* immediately.
*/
public void addChatterObserver (ChatterObserver co)
{
_chatterObservers.add(co);
co.chattersUpdated(_chatters.listIterator());
}
/**
* Removes an observer from the list of chatter observers.
*/
public void removeChatterObserver (ChatterObserver co)
{
_chatterObservers.remove(co);
}
/**
* Sets the validator that decides if a username is valid to be
* added to the chatter list, or null if no such filtering is desired.
*/
public void setChatterValidator (ChatterValidator validator)
{
_chatterValidator = validator;
}
/**
* Registers a chat command handler.
*
* @param msg the message bundle via which the slash command will be
* translated (as <code>c.</code><i>command</i>). If no translation
* exists the command will be <code>/</code><i>command</i>.
* @param command the name of the command that will be used to invoke
* this handler (e.g. <code>tell</code> if the command will be invoked
* as <code>/tell</code>).
* @param handler the chat command handler itself.
*/
public void registerCommandHandler (
MessageBundle msg, String command, CommandHandler handler)
{
String key = "c." + command;
if (msg.exists(key)) {
StringTokenizer st = new StringTokenizer(msg.get(key));
while (st.hasMoreTokens()) {
_handlers.put(st.nextToken(), handler);
}
} else {
// fall back to just using the English command
_handlers.put(command, handler);
}
}
/**
* Return the current size of the history.
*/
public int getCommandHistorySize ()
{
return _history.size();
}
/**
* Get the chat history entry at the specified index,
* with 0 being the oldest.
*/
public String getCommandHistory (int index)
{
return _history.get(index);
}
/**
* Clear the chat command history.
*/
public void clearCommandHistory ()
{
_history.clear();
}
/**
* Requests that all chat displays clear their contents.
*/
public void clearDisplays ()
{
_displays.apply(new ObserverList.ObserverOp<ChatDisplay>() {
public boolean apply (ChatDisplay observer) {
observer.clear();
return true;
}
});
}
/**
* Display a system INFO message as if it had come from the server.
* The localtype of the message will be PLACE_CHAT_TYPE.
*
* Info messages are sent when something happens that was neither
* directly triggered by the user, nor requires direct action.
*/
public void displayInfo (String bundle, String message)
{
displaySystem(bundle, message, SystemMessage.INFO, PLACE_CHAT_TYPE);
}
/**
* Display a system INFO message as if it had come from the server.
*
* Info messages are sent when something happens that was neither
* directly triggered by the user, nor requires direct action.
*/
public void displayInfo (String bundle, String message, String localtype)
{
displaySystem(bundle, message, SystemMessage.INFO, localtype);
}
/**
* Display a system FEEDBACK message as if it had come from the server.
* The localtype of the message will be PLACE_CHAT_TYPE.
*
* Feedback messages are sent in direct response to a user action,
* usually to indicate success or failure of the user's action.
*/
public void displayFeedback (String bundle, String message)
{
displaySystem(
bundle, message, SystemMessage.FEEDBACK, PLACE_CHAT_TYPE);
}
/**
* Display a system ATTENTION message as if it had come from the server.
* The localtype of the message will be PLACE_CHAT_TYPE.
*
* Attention messages are sent when something requires user action
* that did not result from direct action by the user.
*/
public void displayAttention (String bundle, String message)
{
displaySystem(
bundle, message, SystemMessage.ATTENTION, PLACE_CHAT_TYPE);
}
/**
* Dispatches the provided message to our chat displays.
*/
public void dispatchMessage (ChatMessage message)
{
_displayMessageOp.setMessage(message);
_displays.apply(_displayMessageOp);
}
/**
* Parses and delivers the supplied chat message. Slash command
* processing and mogrification are performed and the message is added
* to the chat history if appropriate.
*
* @param speakSvc the SpeakService representing the target dobj of
* the speak or null if we should speak in the "default" way.
* @param text the text to be parsed and sent.
* @param record if text is a command, should it be added to the history?
*
* @return <code>ChatCodes#SUCCESS</code> if the message was parsed
* and sent correctly, a translatable error string if there was some
* problem.
*/
public String requestChat (
SpeakService speakSvc, String text, boolean record)
{
if (text.startsWith("/")) {
// split the text up into a command and arguments
String command = text.substring(1).toLowerCase();
String[] hist = new String[1];
String args = "";
int sidx = text.indexOf(" ");
if (sidx != -1) {
command = text.substring(1, sidx).toLowerCase();
args = text.substring(sidx+1).trim();
}
HashMap<String,CommandHandler> possibleCommands =
getCommandHandlers(command);
switch (possibleCommands.size()) {
case 0:
StringTokenizer tok = new StringTokenizer(text);
return MessageBundle.tcompose(
"m.unknown_command", tok.nextToken());
case 1:
Map.Entry<String,CommandHandler> entry =
possibleCommands.entrySet().iterator().next();
String cmdName = entry.getKey();
CommandHandler cmd = entry.getValue();
String result = cmd.handleCommand(
speakSvc, cmdName, args, hist);
if (!result.equals(ChatCodes.SUCCESS)) {
return result;
}
if (record) {
// get the final history-ready command string
hist[0] = "/" + ((hist[0] == null) ? command : hist[0]);
// remove from history if it was present and
// add it to the end
addToHistory(hist[0]);
}
return result;
default:
String alternativeCommands = "";
Iterator<String> itr = Collections.getSortedIterator(
possibleCommands.keySet());
while (itr.hasNext()) {
alternativeCommands += " /" + itr.next();
}
return MessageBundle.tcompose(
"m.unspecific_command", alternativeCommands);
}
}
// if not a command then just speak
String message = text.trim();
if (StringUtil.isBlank(message)) {
// report silent failure for now
return ChatCodes.SUCCESS;
}
return deliverChat(speakSvc, message, ChatCodes.DEFAULT_MODE);
}
/**
* Requests that a speak message with the specified mode be generated
* and delivered via the supplied speak service instance (which will
* be associated with a particular "speak object"). The message will
* first be validated by all registered {@link ChatFilter}s (and
* possibly vetoed) before being dispatched.
*
* @param speakService the speak service to use when generating the
* speak request or null if we should speak in the current "place".
* @param message the contents of the speak message.
* @param mode a speech mode that will be interpreted by the {@link
* ChatDisplay} implementations that eventually display this speak
* message.
*/
public void requestSpeak (
SpeakService speakService, String message, byte mode)
{
if (speakService == null) {
if (_place == null) {
return;
}
speakService = _place.speakService;
}
// make sure they can say what they want to say
message = filter(message, null, true);
if (message == null) {
return;
}
// dispatch a speak request using the supplied speak service
speakService.speak(_ctx.getClient(), message, mode);
}
/**
* Requests to send a site-wide broadcast message.
*
* @param message the contents of the message.
*/
public void requestBroadcast (String message)
{
message = filter(message, null, true);
if (message == null) {
displayFeedback(_bundle,
MessageBundle.compose("m.broadcast_failed", "m.filtered"));
return;
}
_cservice.broadcast(
_ctx.getClient(), message, new ChatService.InvocationListener() {
public void requestFailed (String reason) {
reason = MessageBundle.compose(
"m.broadcast_failed", reason);
displayFeedback(_bundle, reason);
}
});
}
/**
* Requests that a tell message be delivered to the specified target
* user.
*
* @param target the username of the user to which the tell message
* should be delivered.
* @param msg the contents of the tell message.
* @param rl an optional result listener if you'd like to be notified
* of success or failure.
*/
public void requestTell (final Name target, String msg,
final ResultListener rl)
{
// make sure they can say what they want to say
final String message = filter(msg, target, true);
if (message == null) {
if (rl != null) {
rl.requestFailed(null);
}
return;
}
// create a listener that will report success or failure
ChatService.TellListener listener = new ChatService.TellListener() {
public void tellSucceeded (long idletime, String awayMessage) {
success(xlate(_bundle, MessageBundle.tcompose(
"m.told_format", target, message)));
// if they have an away message, report that
if (awayMessage != null) {
awayMessage = filter(awayMessage, target, false);
if (awayMessage != null) {
String msg = MessageBundle.tcompose(
"m.recipient_afk", target, awayMessage);
displayFeedback(_bundle, msg);
}
}
// if they are idle, report that
if (idletime > 0L) {
// adjust by the time it took them to become idle
idletime += _ctx.getConfig().getValue(
IDLE_TIME_KEY, DEFAULT_IDLE_TIME);
String msg = MessageBundle.compose(
"m.recipient_idle", MessageBundle.taint(target),
TimeUtil.getTimeOrderString(idletime, TimeUtil.MINUTE));
displayFeedback(_bundle, msg);
}
}
protected void success (String feedback) {
dispatchMessage(new TellFeedbackMessage(feedback));
addChatter(target);
if (rl != null) {
rl.requestCompleted(target);
}
}
public void requestFailed (String reason) {
String msg = MessageBundle.compose(
"m.tell_failed", MessageBundle.taint(target), reason);
displayFeedback(_bundle, msg);
if (rl != null) {
rl.requestFailed(null);
}
}
};
_cservice.tell(_ctx.getClient(), target, message, listener);
}
/**
* Configures a message that will be automatically reported to anyone
* that sends a tell message to this client to indicate that we are
* busy or away from the keyboard.
*/
public void setAwayMessage (String message)
{
if (message != null) {
message = filter(message, null, true);
if (message == null) {
// they filtered away their own away message..
// change it to something
message = "...";
}
}
// pass the buck right on along
_cservice.away(_ctx.getClient(), message);
}
/**
* Adds an additional object via which chat messages may arrive. The
* chat director assumes the caller will be managing the subscription
* to this object and will remain subscribed to it for as long as it
* remains in effect as an auxiliary chat source.
*
* @param localtype a type to be associated with all chat messages
* that arrive on the specified DObject.
*/
public void addAuxiliarySource (DObject source, String localtype)
{
source.addListener(this);
_auxes.put(source.getOid(), localtype);
}
/**
* Removes a previously added auxiliary chat source.
*/
public void removeAuxiliarySource (DObject source)
{
source.removeListener(this);
_auxes.remove(source.getOid());
}
/**
* Run a message through all the currently registered filters.
*/
public String filter (String msg, Name otherUser, boolean outgoing)
{
_filterMessageOp.setMessage(msg, otherUser, outgoing);
_filters.apply(_filterMessageOp);
return _filterMessageOp.getMessage();
}
/**
* Runs the supplied message through the various chat mogrifications.
*/
public String mogrifyChat (String text)
{
return mogrifyChat(text, false, true);
}
// documentation inherited
public boolean locationMayChange (int placeId)
{
// we accept all location change requests
return true;
}
// documentation inherited
public void locationDidChange (PlaceObject place)
{
if (_place != null) {
// unlisten to our old object
_place.removeListener(this);
}
// listen to the new object
_place = place;
if (_place != null) {
_place.addListener(this);
}
}
// documentation inherited
public void locationChangeFailed (int placeId, String reason)
{
// nothing we care about
}
// documentation inherited
public void messageReceived (MessageEvent event)
{
if (CHAT_NOTIFICATION.equals(event.getName())) {
ChatMessage msg = (ChatMessage) event.getArgs()[0];
String localtype = getLocalType(event.getTargetOid());
String message = msg.message;
String autoResponse = null;
Name speaker = null;
byte mode = (byte) -1;
// figure out if the message was triggered by another user
if (msg instanceof UserMessage) {
UserMessage umsg = (UserMessage)msg;
speaker = umsg.speaker;
mode = umsg.mode;
} else if (msg instanceof UserSystemMessage) {
speaker = ((UserSystemMessage) msg).speaker;
}
// if there was an originating speaker, see if we want to hear it
if (speaker != null) {
if ((message = filter(message, speaker, false)) == null) {
return;
}
if (USER_CHAT_TYPE.equals(localtype) &&
mode == ChatCodes.DEFAULT_MODE) {
// if it was a tell, add the speaker as a chatter
addChatter(speaker);
// note whether or not we have an auto-response
BodyObject self = (BodyObject)
_ctx.getClient().getClientObject();
if (!StringUtil.isBlank(self.awayMessage)) {
autoResponse = self.awayMessage;
}
}
}
// initialize the client-specific fields of the message
msg.setClientInfo(xlate(msg.bundle, message), localtype);
// and send it off!
dispatchMessage(msg);
// if we auto-responded, report as much
if (autoResponse != null) {
String amsg = MessageBundle.tcompose(
"m.auto_responded", speaker, autoResponse);
displayFeedback(_bundle, amsg);
}
}
}
// documentation inherited
public void clientDidLogon (Client client)
{
super.clientDidLogon(client);
// listen on the client object for tells
addAuxiliarySource(_clobj = client.getClientObject(), USER_CHAT_TYPE);
}
// documentation inherited
public void clientObjectDidChange (Client client)
{
super.clientObjectDidChange(client);
// change what we're listening to for tells
removeAuxiliarySource(_clobj);
addAuxiliarySource(_clobj = client.getClientObject(), USER_CHAT_TYPE);
clearDisplays();
}
// documentation inherited
public void clientDidLogoff (Client client)
{
super.clientDidLogoff(client);
// stop listening to it for tells
if (_clobj != null) {
removeAuxiliarySource(_clobj);
_clobj = null;
}
// in fact, clear out all auxiliary sources
_auxes.clear();
clearDisplays();
// clear out the list of people we've chatted with
_chatters.clear();
notifyChatterObservers();
// clear the _place
locationDidChange(null);
// clear our service
_cservice = null;
}
/**
* Called to determine whether we are permitted to post the supplied
* chat message. Derived classes may wish to throttle chat or restrict
* certain types in certain circumstances for whatever reason.
*
* @return null if the chat is permitted, SUCCESS if the chat is permitted
* and has already been dealt with, or a translatable string
* indicating the reason for rejection if not.
*/
protected String checkCanChat (
SpeakService speakSvc, String message, byte mode)
{
return null;
}
/**
* Delivers a plain chat message (not a slash command) on the
* specified speak service in the specified mode. The message will be
* mogrified and filtered prior to delivery.
*
* @return {@link ChatCodes#SUCCESS} if the message was delivered or a
* string indicating why it failed.
*/
protected String deliverChat (
SpeakService speakSvc, String message, byte mode)
{
// run the message through our mogrification process
message = mogrifyChat(message, true, mode != ChatCodes.EMOTE_MODE);
// mogrification may result in something being turned into a slash
// command, in which case we have to run everything through again
// from the start
if (message.startsWith("/")) {
return requestChat(speakSvc, message, false);
}
// make sure this client is not restricted from performing this
// chat message for some reason or other
String errmsg = checkCanChat(speakSvc, message, mode);
if (errmsg != null) {
return errmsg;
}
// speak on the specified service
requestSpeak(speakSvc, message, mode);
return ChatCodes.SUCCESS;
}
/**
* Add the specified command to the history.
*/
protected void addToHistory (String cmd)
{
// remove any previous instance of this command
_history.remove(cmd);
// append it to the end
_history.add(cmd);
// prune the history once it extends beyond max size
if (_history.size() > MAX_COMMAND_HISTORY) {
_history.remove(0);
}
}
/**
* Mogrify common literary crutches into more appealing chat or
* commands.
*
* @param transformsAllowed if true, the chat may transformed into a
* different mode. (lol -> /emote laughs)
* @param capFirst if true, the first letter of the text is
* capitalized. This is not desired if the chat is already an emote.
*/
protected String mogrifyChat (
String text, boolean transformsAllowed, boolean capFirst)
{
int tlen = text.length();
if (tlen == 0) {
return text;
// check to make sure there aren't too many caps
} else if (tlen > 7) {
// count caps
int caps = 0;
for (int ii=0; ii < tlen; ii++) {
if (Character.isUpperCase(text.charAt(ii))) {
caps++;
if (caps > (tlen / 2)) {
// lowercase the whole string if there are
text = text.toLowerCase();
break;
}
}
}
}
StringBuffer buf = new StringBuffer(text);
buf = mogrifyChat(buf, transformsAllowed, capFirst);
return buf.toString();
}
/** Helper function for {@link #mogrifyChat}. */
protected StringBuffer mogrifyChat (
StringBuffer buf, boolean transformsAllowed, boolean capFirst)
{
// do the generic mogrifications and translations
buf = translatedReplacements("x.mogrifies", buf);
// perform themed expansions and transformations
if (transformsAllowed) {
buf = translatedReplacements("x.transforms", buf);
}
/*
// capitalize the first letter
if (capFirst) {
buf.setCharAt(0, Character.toUpperCase(buf.charAt(0)));
}
// and capitalize any letters after a sentence-ending punctuation
Pattern p = Pattern.compile("([^\\.][\\.\\?\\!](\\s)+\\p{Ll})");
Matcher m = p.matcher(buf);
if (m.find()) {
buf = new StringBuffer();
m.appendReplacement(buf, m.group().toUpperCase());
while (m.find()) {
m.appendReplacement(buf, m.group().toUpperCase());
}
m.appendTail(buf);
}
*/
return buf;
}
/**
* Do all the replacements (mogrifications) specified in the
* translation string specified by the key.
*/
protected StringBuffer translatedReplacements (String key, StringBuffer buf)
{
MessageBundle bundle = _msgmgr.getBundle(_bundle);
if (!bundle.exists(key)) {
return buf;
}
StringTokenizer st = new StringTokenizer(bundle.get(key), "#");
// apply the replacements to each mogrification that matches
while (st.hasMoreTokens()) {
String pattern = st.nextToken();
String replace = st.nextToken();
Matcher m = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE).
matcher(buf);
if (m.find()) {
buf = new StringBuffer();
m.appendReplacement(buf, replace);
// they may match more than once
while (m.find()) {
m.appendReplacement(buf, replace);
}
m.appendTail(buf);
}
}
return buf;
}
/**
* Returns a hashmap containing all command handlers that match the
* specified command (i.e. the specified command is a prefix of their
* registered command string).
*/
protected HashMap<String,CommandHandler> getCommandHandlers (String command)
{
HashMap<String,CommandHandler> matches =
new HashMap<String,CommandHandler>();
BodyObject user = (BodyObject)_ctx.getClient().getClientObject();
for (Map.Entry<String,CommandHandler> entry : _handlers.entrySet()) {
String cmd = entry.getKey();
if (!cmd.startsWith(command)) {
continue;
}
CommandHandler handler = entry.getValue();
if (!handler.checkAccess(user)) {
continue;
}
matches.put(cmd, handler);
}
return matches;
}
/**
* Adds a chatter to our list of recent chatters.
*/
protected void addChatter (Name name)
{
// check to see if the chatter validator approves..
if ((_chatterValidator != null) &&
(!_chatterValidator.isChatterValid(name))) {
return;
}
boolean wasthere = _chatters.remove(name);
_chatters.addFirst(name);
if (!wasthere) {
if (_chatters.size() > MAX_CHATTERS) {
_chatters.removeLast();
}
notifyChatterObservers();
}
}
/**
* Notifies all registered {@link ChatterObserver}s that the list of
* chatters has changed.
*/
protected void notifyChatterObservers ()
{
_chatterObservers.apply(new ObserverList.ObserverOp<ChatterObserver>() {
public boolean apply (ChatterObserver observer) {
observer.chattersUpdated(_chatters.listIterator());
return true;
}
});
}
/**
* Translates the specified message using the specified bundle.
*/
protected String xlate (String bundle, String message)
{
if (bundle != null && _msgmgr != null) {
MessageBundle msgb = _msgmgr.getBundle(bundle);
if (msgb == null) {
Log.warning(
"No message bundle available to translate message " +
"[bundle=" + bundle + ", message=" + message + "].");
} else {
message = msgb.xlate(message);
}
}
return message;
}
/**
* Display the specified system message as if it had come from the server.
*/
protected void displaySystem (
String bundle, String message, byte attLevel, String localtype)
{
// nothing should be untranslated, so pass the default bundle if need
// be.
if (bundle == null) {
bundle = _bundle;
}
SystemMessage msg = new SystemMessage();
msg.attentionLevel = attLevel;
msg.setClientInfo(xlate(bundle, message), localtype);
dispatchMessage(msg);
}
/**
* Looks up and returns the message type associated with the specified
* oid.
*/
protected String getLocalType (int oid)
{
String type = _auxes.get(oid);
return (type == null) ? PLACE_CHAT_TYPE : type;
}
// documentation inherited from interface
protected void fetchServices (Client client)
{
// get a handle on our chat service
_cservice = (ChatService)client.requireService(ChatService.class);
}
/**
* An operation that checks with all chat filters to properly filter
* a message prior to sending to the server or displaying.
*/
protected static class FilterMessageOp
implements ObserverList.ObserverOp<ChatFilter>
{
public void setMessage (String msg, Name otherUser, boolean outgoing)
{
_msg = msg;
_otherUser = otherUser;
_out = outgoing;
}
public boolean apply (ChatFilter observer)
{
if (_msg != null) {
_msg = observer.filter(_msg, _otherUser, _out);
}
return true;
}
public String getMessage ()
{
return _msg;
}
protected Name _otherUser;
protected String _msg;
protected boolean _out;
}
/**
* An observer op used to dispatch ChatMessages on the client.
*/
protected static class DisplayMessageOp
implements ObserverList.ObserverOp<ChatDisplay>
{
public void setMessage (ChatMessage message)
{
_message = message;
}
public boolean apply (ChatDisplay observer)
{
observer.displayMessage(_message);
return true;
}
protected ChatMessage _message;
}
/** Implements <code>/help</code>. */
protected class HelpHandler extends CommandHandler
{
public String handleCommand (SpeakService speakSvc, String command,
String args, String[] history)
{
String hcmd = "";
// grab the command they want help on
if (!StringUtil.isBlank(args)) {
hcmd = args;
int sidx = args.indexOf(" ");
if (sidx != -1) {
hcmd = args.substring(0, sidx);
}
}
// let the user give commands with or with the /
if (hcmd.startsWith("/")) {
hcmd = hcmd.substring(1);
}
// handle "/help help" and "/help someboguscommand"
HashMap<String,CommandHandler> possibleCommands =
getCommandHandlers(hcmd);
if (hcmd.equals("help") || possibleCommands.isEmpty()) {
possibleCommands = getCommandHandlers("");
possibleCommands.remove("help"); // remove help from the list
}
// if there is only one possible command display its usage
switch (possibleCommands.size()) {
case 1:
Iterator<String> itr = possibleCommands.keySet().iterator();
// this is a little funny, but we display the feeback
// message by hand and return SUCCESS so that the chat
// entry field doesn't think that we've failed and
// preserve our command text
displayFeedback(null, "m.usage_" + itr.next());
return ChatCodes.SUCCESS;
default:
Object[] commands = possibleCommands.keySet().toArray();
Arrays.sort(commands);
String commandList = "";
for (int ii = 0; ii < commands.length; ii++) {
commandList += " /" + commands[ii];
}
return MessageBundle.tcompose("m.usage_help", commandList);
}
}
}
/** Implements <code>/clear</code>. */
protected class ClearHandler extends CommandHandler
{
public String handleCommand (SpeakService speakSvc, String command,
String args, String[] history)
{
clearDisplays();
return ChatCodes.SUCCESS;
}
}
/** Implements <code>/speak</code>. */
protected class SpeakHandler extends CommandHandler
{
public String handleCommand (SpeakService speakSvc, String command,
String args, String[] history)
{
if (StringUtil.isBlank(args)) {
return "m.usage_speak";
}
// note the command to be stored in the history
history[0] = command + " ";
return requestChat(null, args, true);
}
}
/** Implements <code>/emote</code>. */
protected class EmoteHandler extends CommandHandler
{
public String handleCommand (SpeakService speakSvc, String command,
String args, String[] history)
{
if (StringUtil.isBlank(args)) {
return "m.usage_emote";
}
// note the command to be stored in the history
history[0] = command + " ";
return deliverChat(speakSvc, args, ChatCodes.EMOTE_MODE);
}
}
/** Implements <code>/think</code>. */
protected class ThinkHandler extends CommandHandler
{
public String handleCommand (SpeakService speakSvc, String command,
String args, String[] history)
{
if (StringUtil.isBlank(args)) {
return "m.usage_think";
}
// note the command to be stored in the history
history[0] = command + " ";
return deliverChat(speakSvc, args, ChatCodes.THINK_MODE);
}
}
/** Our active chat context. */
protected CrowdContext _ctx;
/** Provides access to chat-related server-side services. */
protected ChatService _cservice;
/** The message manager. */
protected MessageManager _msgmgr;
/** The bundle to use for our own internal messages. */
protected String _bundle;
/** The place object that we currently occupy. */
protected PlaceObject _place;
/** The client object that we're listening to for tells. */
protected ClientObject _clobj;
/** A list of registered chat displays. */
protected ObserverList<ChatDisplay> _displays =
new ObserverList<ChatDisplay>(ObserverList.FAST_UNSAFE_NOTIFY);
/** A list of registered chat filters. */
protected ObserverList<ChatFilter> _filters =
new ObserverList<ChatFilter>(ObserverList.FAST_UNSAFE_NOTIFY);
/** A mapping from auxiliary chat objects to the types under which
* they are registered. */
protected HashIntMap<String> _auxes = new HashIntMap<String>();
/** Validator of who may be added to the chatters list. */
protected ChatterValidator _chatterValidator;
/** Usernames of users we've recently chatted with. */
protected LinkedList<Name> _chatters = new LinkedList<Name>();
/** Observers that are watching our chatters list. */
protected ObserverList<ChatterObserver> _chatterObservers =
new ObserverList<ChatterObserver>(ObserverList.FAST_UNSAFE_NOTIFY);
/** Registered chat command handlers. */
protected static HashMap<String,CommandHandler> _handlers =
new HashMap<String,CommandHandler>();
/** A history of chat commands. */
protected static ArrayList<String> _history = new ArrayList<String>();
/** Operation used to filter chat messages. */
protected FilterMessageOp _filterMessageOp = new FilterMessageOp();
/** Operation used to display chat messages. */
protected DisplayMessageOp _displayMessageOp = new DisplayMessageOp();
/** The maximum number of chatter usernames to track. */
protected static final int MAX_CHATTERS = 6;
/** The maximum number of commands to keep in the chat history. */
protected static final int MAX_COMMAND_HISTORY = 10;
}
| Implemented a standard /tell handler.
git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@4040 542714f4-19e9-0310-aa3c-eee0fc999fb1
| src/java/com/threerings/crowd/chat/client/ChatDirector.java | Implemented a standard /tell handler. | <ide><path>rc/java/com/threerings/crowd/chat/client/ChatDirector.java
<ide> }
<ide> }
<ide>
<add> /** Implements <code>/tell</code>. */
<add> protected class TellHandler extends CommandHandler
<add> {
<add> public String handleCommand (
<add> SpeakService speakSvc, final String command, String args,
<add> String[] history)
<add> {
<add> // there should be at least two arg tokens: '/tell target word'
<add> StringTokenizer tok = new StringTokenizer(args);
<add> if (tok.countTokens() < 2) {
<add> return "m.usage_tell";
<add> }
<add>
<add> // if the handle starts with a quote, keep tacking on words until
<add> // we find the end quote
<add> String handle = tok.nextToken();
<add> if (handle.startsWith("\"")) {
<add> while (!handle.endsWith("\"") && tok.hasMoreTokens()) {
<add> handle = handle + " " + tok.nextToken();
<add> }
<add> }
<add> if (!handle.endsWith("\"")) {
<add> return "m.usage_tell";
<add> }
<add>
<add> // now strip off everything after the handle for the message
<add> int uidx = args.indexOf(handle);
<add> String message = args.substring(uidx + handle.length()).trim();
<add> if (StringUtil.isBlank(message)) {
<add> return "m.usage_tell";
<add> }
<add>
<add> // strip the quotes off of the handle
<add> if (handle.startsWith("\"")) {
<add> handle = handle.substring(1, handle.length()-1);
<add> }
<add>
<add> // make sure we're not trying to tell something to ourselves
<add> BodyObject self = (BodyObject)_ctx.getClient().getClientObject();
<add> if (handle.equalsIgnoreCase(self.getVisibleName().toString())) {
<add> return "m.talk_self";
<add> }
<add>
<add> // clear out from the history any tells that are mistypes
<add> for (Iterator iter = _history.iterator(); iter.hasNext(); ) {
<add> String hist = (String) iter.next();
<add> if (hist.startsWith("/" + command) &&
<add> (new StringTokenizer(hist).countTokens() > 2)) {
<add> iter.remove();
<add> }
<add> }
<add>
<add> // mogrify the chat
<add> message = mogrifyChat(message);
<add>
<add> // store the full command in the history, even if it was mistyped
<add> final String histEntry = command + " \"" + handle + "\" " + message;
<add> history[0] = histEntry;
<add>
<add> // request to send this text as a tell message
<add> requestTell(new Name(handle), message, new ResultListener() {
<add> public void requestCompleted (Object result) {
<add> // replace the full one in the history with just:
<add> // /tell "<handle>"
<add> String newEntry = "/" + command + " \"" + result + "\" ";
<add> _history.remove(newEntry);
<add> int dex = _history.lastIndexOf("/" + histEntry);
<add> if (dex >= 0) {
<add> _history.set(dex, newEntry);
<add> } else {
<add> _history.add(newEntry);
<add> }
<add> }
<add> public void requestFailed (Exception cause) {
<add> // do nothing
<add> }
<add> });
<add>
<add> return ChatCodes.SUCCESS;
<add> }
<add> }
<add>
<ide> /** Our active chat context. */
<ide> protected CrowdContext _ctx;
<ide> |
|
Java | apache-2.0 | 5b4fef3eda3928c5a5a4bd8a63aafc560c7abf4a | 0 | kalaspuffar/pdfbox,kalaspuffar/pdfbox,apache/pdfbox,apache/pdfbox | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.pdfbox.pdmodel;
import java.awt.Point;
import java.awt.image.DataBuffer;
import java.awt.image.Raster;
import java.awt.image.WritableRaster;
import java.io.BufferedOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.fontbox.ttf.TrueTypeFont;
import org.apache.pdfbox.cos.COSArray;
import org.apache.pdfbox.cos.COSBase;
import org.apache.pdfbox.cos.COSDictionary;
import org.apache.pdfbox.cos.COSDocument;
import org.apache.pdfbox.cos.COSInteger;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.cos.COSObject;
import org.apache.pdfbox.io.IOUtils;
import org.apache.pdfbox.io.MemoryUsageSetting;
import org.apache.pdfbox.io.RandomAccessBuffer;
import org.apache.pdfbox.io.RandomAccessBufferedFileInputStream;
import org.apache.pdfbox.io.RandomAccessRead;
import org.apache.pdfbox.io.ScratchFile;
import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.pdfwriter.COSWriter;
import org.apache.pdfbox.pdmodel.common.COSArrayList;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.common.PDStream;
import org.apache.pdfbox.pdmodel.encryption.AccessPermission;
import org.apache.pdfbox.pdmodel.encryption.InvalidPasswordException;
import org.apache.pdfbox.pdmodel.encryption.PDEncryption;
import org.apache.pdfbox.pdmodel.encryption.ProtectionPolicy;
import org.apache.pdfbox.pdmodel.encryption.SecurityHandler;
import org.apache.pdfbox.pdmodel.encryption.SecurityHandlerFactory;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.graphics.color.PDDeviceRGB;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationWidget;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAppearanceDictionary;
import org.apache.pdfbox.pdmodel.interactive.digitalsignature.ExternalSigningSupport;
import org.apache.pdfbox.pdmodel.interactive.digitalsignature.PDSignature;
import org.apache.pdfbox.pdmodel.interactive.digitalsignature.SignatureInterface;
import org.apache.pdfbox.pdmodel.interactive.digitalsignature.SignatureOptions;
import org.apache.pdfbox.pdmodel.interactive.digitalsignature.SigningSupport;
import org.apache.pdfbox.pdmodel.interactive.form.PDAcroForm;
import org.apache.pdfbox.pdmodel.interactive.form.PDField;
import org.apache.pdfbox.pdmodel.interactive.form.PDSignatureField;
/**
* This is the in-memory representation of the PDF document.
* The #close() method must be called once the document is no longer needed.
*
* @author Ben Litchfield
*/
public class PDDocument implements Closeable
{
/**
* For signing: large reserve byte range used as placeholder in the saved PDF until the actual
* length of the PDF is known. You'll need to fetch (with
* {@link PDSignature#getByteRange()} ) and reassign this yourself (with
* {@link PDSignature#setByteRange(int[])} ) only if you call
* {@link #saveIncrementalForExternalSigning(java.io.OutputStream) saveIncrementalForExternalSigning()}
* twice.
*/
private static final int[] RESERVE_BYTE_RANGE = new int[] { 0, 1000000000, 1000000000, 1000000000 };
private static final Log LOG = LogFactory.getLog(PDDocument.class);
/**
* avoid concurrency issues with PDDeviceRGB
*/
static
{
try
{
WritableRaster raster = Raster.createBandedRaster(DataBuffer.TYPE_BYTE, 1, 1, 3, new Point(0, 0));
PDDeviceRGB.INSTANCE.toRGBImage(raster);
}
catch (IOException ex)
{
LOG.debug("voodoo error", ex);
}
}
private final COSDocument document;
// cached values
private PDDocumentInformation documentInformation;
private PDDocumentCatalog documentCatalog;
// the encryption will be cached here. When the document is decrypted then
// the COSDocument will not have an "Encrypt" dictionary anymore and this object must be used
private PDEncryption encryption;
// holds a flag which tells us if we should remove all security from this documents.
private boolean allSecurityToBeRemoved;
// keep tracking customized documentId for the trailer. If null, a new id will be generated
// this ID doesn't represent the actual documentId from the trailer
private Long documentId;
// the pdf to be read
private final RandomAccessRead pdfSource;
// the access permissions of the document
private AccessPermission accessPermission;
// fonts to subset before saving
private final Set<PDFont> fontsToSubset = new HashSet<>();
// fonts to close when closing document
private final Set<TrueTypeFont> fontsToClose = new HashSet<>();
// Signature interface
private SignatureInterface signInterface;
// helper class used to create external signature
private SigningSupport signingSupport;
// document-wide cached resources
private ResourceCache resourceCache = new DefaultResourceCache();
// to make sure only one signature is added
private boolean signatureAdded = false;
/**
* Creates an empty PDF document.
* You need to add at least one page for the document to be valid.
*/
public PDDocument()
{
this(MemoryUsageSetting.setupMainMemoryOnly());
}
/**
* Creates an empty PDF document.
* You need to add at least one page for the document to be valid.
*
* @param memUsageSetting defines how memory is used for buffering PDF streams
*/
public PDDocument(MemoryUsageSetting memUsageSetting)
{
ScratchFile scratchFile = null;
try
{
scratchFile = new ScratchFile(memUsageSetting);
}
catch (IOException ioe)
{
LOG.warn("Error initializing scratch file: " + ioe.getMessage() +
". Fall back to main memory usage only.", ioe);
scratchFile = ScratchFile.getMainMemoryOnlyInstance();
}
document = new COSDocument(scratchFile);
pdfSource = null;
// First we need a trailer
COSDictionary trailer = new COSDictionary();
document.setTrailer(trailer);
// Next we need the root dictionary.
COSDictionary rootDictionary = new COSDictionary();
trailer.setItem(COSName.ROOT, rootDictionary);
rootDictionary.setItem(COSName.TYPE, COSName.CATALOG);
rootDictionary.setItem(COSName.VERSION, COSName.getPDFName("1.4"));
// next we need the pages tree structure
COSDictionary pages = new COSDictionary();
rootDictionary.setItem(COSName.PAGES, pages);
pages.setItem(COSName.TYPE, COSName.PAGES);
COSArray kidsArray = new COSArray();
pages.setItem(COSName.KIDS, kidsArray);
pages.setItem(COSName.COUNT, COSInteger.ZERO);
}
/**
* This will add a page to the document. This is a convenience method, that will add the page to the root of the
* hierarchy and set the parent of the page to the root.
*
* @param page The page to add to the document.
*/
public void addPage(PDPage page)
{
getPages().add(page);
}
/**
* Add parameters of signature to be created externally using default signature options. See
* {@link #saveIncrementalForExternalSigning(OutputStream)} method description on external
* signature creation scenario details.
* <p>
* Only one signature may be added in a document. To sign several times,
* load document, add signature, save incremental and close again.
*
* @param sigObject is the PDSignatureField model
* @throws IOException if there is an error creating required fields
* @throws IllegalStateException if one attempts to add several signature
* fields.
*/
public void addSignature(PDSignature sigObject) throws IOException
{
addSignature(sigObject, new SignatureOptions());
}
/**
* Add parameters of signature to be created externally. See
* {@link #saveIncrementalForExternalSigning(OutputStream)} method description on external
* signature creation scenario details.
* <p>
* Only one signature may be added in a document. To sign several times,
* load document, add signature, save incremental and close again.
*
* @param sigObject is the PDSignatureField model
* @param options signature options
* @throws IOException if there is an error creating required fields
* @throws IllegalStateException if one attempts to add several signature
* fields.
*/
public void addSignature(PDSignature sigObject, SignatureOptions options) throws IOException
{
addSignature(sigObject, null, options);
}
/**
* Add a signature to be created using the instance of given interface.
* <p>
* Only one signature may be added in a document. To sign several times,
* load document, add signature, save incremental and close again.
*
* @param sigObject is the PDSignatureField model
* @param signatureInterface is an interface whose implementation provides
* signing capabilities. Can be null if external signing if used.
* @throws IOException if there is an error creating required fields
* @throws IllegalStateException if one attempts to add several signature
* fields.
*/
public void addSignature(PDSignature sigObject, SignatureInterface signatureInterface) throws IOException
{
addSignature(sigObject, signatureInterface, new SignatureOptions());
}
/**
* This will add a signature to the document. If the 0-based page number in the options
* parameter is smaller than 0 or larger than max, the nearest valid page number will be used
* (i.e. 0 or max) and no exception will be thrown.
* <p>
* Only one signature may be added in a document. To sign several times,
* load document, add signature, save incremental and close again.
*
* @param sigObject is the PDSignatureField model
* @param signatureInterface is an interface whose implementation provides
* signing capabilities. Can be null if external signing if used.
* @param options signature options
* @throws IOException if there is an error creating required fields
* @throws IllegalStateException if one attempts to add several signature
* fields.
*/
public void addSignature(PDSignature sigObject, SignatureInterface signatureInterface,
SignatureOptions options) throws IOException
{
if (signatureAdded)
{
throw new IllegalStateException("Only one signature may be added in a document");
}
signatureAdded = true;
// Reserve content
// We need to reserve some space for the signature. Some signatures including
// big certificate chain and we need enough space to store it.
int preferredSignatureSize = options.getPreferredSignatureSize();
if (preferredSignatureSize > 0)
{
sigObject.setContents(new byte[preferredSignatureSize]);
}
else
{
sigObject.setContents(new byte[SignatureOptions.DEFAULT_SIGNATURE_SIZE]);
}
// Reserve ByteRange, will be overwritten in COSWriter
sigObject.setByteRange(RESERVE_BYTE_RANGE);
signInterface = signatureInterface;
// Create SignatureForm for signature and append it to the document
// Get the first valid page
int pageCount = getNumberOfPages();
if (pageCount == 0)
{
throw new IllegalStateException("Cannot sign an empty document");
}
int startIndex = Math.min(Math.max(options.getPage(), 0), pageCount - 1);
PDPage page = getPage(startIndex);
// Get the AcroForm from the Root-Dictionary and append the annotation
PDDocumentCatalog catalog = getDocumentCatalog();
PDAcroForm acroForm = catalog.getAcroForm();
catalog.getCOSObject().setNeedToBeUpdated(true);
if (acroForm == null)
{
acroForm = new PDAcroForm(this);
catalog.setAcroForm(acroForm);
}
else
{
acroForm.getCOSObject().setNeedToBeUpdated(true);
}
PDSignatureField signatureField = null;
if (!(acroForm.getCOSObject().getDictionaryObject(COSName.FIELDS) instanceof COSArray))
{
acroForm.getCOSObject().setItem(COSName.FIELDS, new COSArray());
}
else
{
COSArray fieldArray = (COSArray) acroForm.getCOSObject().getDictionaryObject(COSName.FIELDS);
fieldArray.setNeedToBeUpdated(true);
signatureField = findSignatureField(acroForm.getFieldIterator(), sigObject);
}
if (signatureField == null)
{
signatureField = new PDSignatureField(acroForm);
// append the signature object
signatureField.setValue(sigObject);
// backward linking
signatureField.getWidgets().get(0).setPage(page);
}
else
{
sigObject.getCOSObject().setNeedToBeUpdated(true);
}
// TODO This "overwrites" the settings of the original signature field which might not be intended by the user
// better make it configurable (not all users need/want PDF/A but their own setting):
// to conform PDF/A-1 requirement:
// The /F key's Print flag bit shall be set to 1 and
// its Hidden, Invisible and NoView flag bits shall be set to 0
signatureField.getWidgets().get(0).setPrinted(true);
// Set the AcroForm Fields
List<PDField> acroFormFields = acroForm.getFields();
acroForm.getCOSObject().setDirect(true);
acroForm.setSignaturesExist(true);
acroForm.setAppendOnly(true);
boolean checkFields = checkSignatureField(acroForm.getFieldIterator(), signatureField);
if (checkFields)
{
signatureField.getCOSObject().setNeedToBeUpdated(true);
}
else
{
acroFormFields.add(signatureField);
}
// Get the object from the visual signature
COSDocument visualSignature = options.getVisualSignature();
// Distinction of case for visual and non-visual signature
if (visualSignature == null)
{
prepareNonVisibleSignature(signatureField);
return;
}
prepareVisibleSignature(signatureField, acroForm, visualSignature);
// Create Annotation / Field for signature
List<PDAnnotation> annotations = page.getAnnotations();
// Make /Annots a direct object to avoid problem if it is an existing indirect object:
// it would not be updated in incremental save, and if we'd set the /Annots array "to be updated"
// while keeping it indirect, Adobe Reader would claim that the document had been modified.
page.setAnnotations(annotations);
// Get the annotations of the page and append the signature-annotation to it
// take care that page and acroforms do not share the same array (if so, we don't need to add it twice)
if (!(annotations instanceof COSArrayList &&
acroFormFields instanceof COSArrayList &&
((COSArrayList<?>) annotations).toList().equals(((COSArrayList<?>) acroFormFields).toList()) &&
checkFields))
{
PDAnnotationWidget widget = signatureField.getWidgets().get(0);
// use check to prevent the annotation widget from appearing twice
if (checkSignatureAnnotation(annotations, widget))
{
widget.getCOSObject().setNeedToBeUpdated(true);
}
else
{
annotations.add(widget);
}
}
page.getCOSObject().setNeedToBeUpdated(true);
}
/**
* Search acroform fields for signature field with specific signature dictionary.
*
* @param fieldIterator iterator on all fields.
* @param sigObject signature object (the /V part).
* @return a signature field if found, or null if none was found.
*/
private PDSignatureField findSignatureField(Iterator<PDField> fieldIterator, PDSignature sigObject)
{
PDSignatureField signatureField = null;
while (fieldIterator.hasNext())
{
PDField pdField = fieldIterator.next();
if (pdField instanceof PDSignatureField)
{
PDSignature signature = ((PDSignatureField) pdField).getSignature();
if (signature != null && signature.getCOSObject().equals(sigObject.getCOSObject()))
{
signatureField = (PDSignatureField) pdField;
}
}
}
return signatureField;
}
/**
* Check if the field already exists in the field list.
*
* @param fieldIterator iterator on all fields.
* @param signatureField the signature field.
* @return true if the field already existed in the field list, false if not.
*/
private boolean checkSignatureField(Iterator<PDField> fieldIterator, PDSignatureField signatureField)
{
while (fieldIterator.hasNext())
{
PDField field = fieldIterator.next();
if (field instanceof PDSignatureField
&& field.getCOSObject().equals(signatureField.getCOSObject()))
{
return true;
}
}
return false;
}
/**
* Check if the widget already exists in the annotation list
*
* @param acroFormFields the list of AcroForm fields.
* @param signatureField the signature field.
* @return true if the widget already existed in the annotation list, false if not.
*/
private boolean checkSignatureAnnotation(List<PDAnnotation> annotations, PDAnnotationWidget widget)
{
for (PDAnnotation annotation : annotations)
{
if (annotation.getCOSObject().equals(widget.getCOSObject()))
{
return true;
}
}
return false;
}
private void prepareVisibleSignature(PDSignatureField signatureField, PDAcroForm acroForm,
COSDocument visualSignature)
{
// Obtain visual signature object
boolean annotNotFound = true;
boolean sigFieldNotFound = true;
for (COSObject cosObject : visualSignature.getObjects())
{
if (!annotNotFound && !sigFieldNotFound)
{
break;
}
COSBase base = cosObject.getObject();
if (base instanceof COSDictionary)
{
COSDictionary cosBaseDict = (COSDictionary) base;
// Search for signature annotation
COSBase type = cosBaseDict.getDictionaryObject(COSName.TYPE);
if (annotNotFound && COSName.ANNOT.equals(type))
{
assignSignatureRectangle(signatureField, cosBaseDict);
annotNotFound = false;
}
// Search for signature field
COSBase fieldType = cosBaseDict.getDictionaryObject(COSName.FT);
COSBase apDict = cosBaseDict.getDictionaryObject(COSName.AP);
if (sigFieldNotFound && COSName.SIG.equals(fieldType) && apDict instanceof COSDictionary)
{
assignAppearanceDictionary(signatureField, (COSDictionary) apDict);
assignAcroFormDefaultResource(acroForm, cosBaseDict);
sigFieldNotFound = false;
}
}
}
if (annotNotFound || sigFieldNotFound)
{
throw new IllegalArgumentException("Template is missing required objects");
}
}
private void assignSignatureRectangle(PDSignatureField signatureField, COSDictionary annotDict)
{
// Read and set the rectangle for visual signature
COSArray rectArray = (COSArray) annotDict.getDictionaryObject(COSName.RECT);
PDRectangle rect = new PDRectangle(rectArray);
PDRectangle existingRectangle = signatureField.getWidgets().get(0).getRectangle();
//in case of an existing field keep the original rect
if (existingRectangle == null || existingRectangle.getCOSArray().size() != 4)
{
signatureField.getWidgets().get(0).setRectangle(rect);
}
}
private void assignAppearanceDictionary(PDSignatureField signatureField, COSDictionary apDict)
{
// read and set Appearance Dictionary
PDAppearanceDictionary ap = new PDAppearanceDictionary(apDict);
apDict.setDirect(true);
signatureField.getWidgets().get(0).setAppearance(ap);
}
private void assignAcroFormDefaultResource(PDAcroForm acroForm, COSDictionary newDict)
{
// read and set/update AcroForm default resource dictionary /DR if available
COSBase newBase = newDict.getDictionaryObject(COSName.DR);
if (newBase instanceof COSDictionary)
{
COSDictionary newDR = (COSDictionary) newBase;
PDResources defaultResources = acroForm.getDefaultResources();
if (defaultResources == null)
{
acroForm.getCOSObject().setItem(COSName.DR, newDR);
newDR.setDirect(true);
newDR.setNeedToBeUpdated(true);
}
else
{
COSDictionary oldDR = defaultResources.getCOSObject();
COSBase newXObjectBase = newDR.getItem(COSName.XOBJECT);
COSBase oldXObjectBase = oldDR.getItem(COSName.XOBJECT);
if (newXObjectBase instanceof COSDictionary &&
oldXObjectBase instanceof COSDictionary)
{
((COSDictionary) oldXObjectBase).addAll((COSDictionary) newXObjectBase);
oldDR.setNeedToBeUpdated(true);
}
}
}
}
private void prepareNonVisibleSignature(PDSignatureField signatureField)
{
// "Signature fields that are not intended to be visible shall
// have an annotation rectangle that has zero height and width."
// Set rectangle for non-visual signature to rectangle array [ 0 0 0 0 ]
signatureField.getWidgets().get(0).setRectangle(new PDRectangle());
}
/**
* Remove the page from the document.
*
* @param page The page to remove from the document.
*/
public void removePage(PDPage page)
{
getPages().remove(page);
}
/**
* Remove the page from the document.
*
* @param pageNumber 0 based index to page number.
*/
public void removePage(int pageNumber)
{
getPages().remove(pageNumber);
}
/**
* This will import and copy the contents from another location. Currently the content stream is stored in a scratch
* file. The scratch file is associated with the document. If you are adding a page to this document from another
* document and want to copy the contents to this
* document's scratch file then use this method otherwise just use the {@link #addPage addPage}
* method.
* <p>
* Unlike {@link #addPage addPage}, this method creates a new PDPage object. If your page has
* annotations, and if these link to pages not in the target document, then the target document
* might become huge. What you need to do is to delete page references of such annotations. See
* <a href="http://stackoverflow.com/a/35477351/535646">here</a> for how to do this.
* <p>
* Inherited (global) resources are ignored. If you need them, call
* <code>importedPage.setRotation(page.getRotation());</code>
*
* @param page The page to import.
* @return The page that was imported.
*
* @throws IOException If there is an error copying the page.
*/
public PDPage importPage(PDPage page) throws IOException
{
PDPage importedPage = new PDPage(new COSDictionary(page.getCOSObject()), resourceCache);
PDStream dest = new PDStream(this, page.getContents(), COSName.FLATE_DECODE);
importedPage.setContents(dest);
addPage(importedPage);
importedPage.setCropBox(page.getCropBox());
importedPage.setMediaBox(page.getMediaBox());
importedPage.setRotation(page.getRotation());
if (page.getResources() != null && !page.getCOSObject().containsKey(COSName.RESOURCES))
{
LOG.warn("inherited resources of source document are not imported to destination page");
LOG.warn("call importedPage.setResources(page.getResources()) to do this");
}
return importedPage;
}
/**
* Constructor that uses an existing document. The COSDocument that is passed in must be valid.
*
* @param doc The COSDocument that this document wraps.
*/
public PDDocument(COSDocument doc)
{
this(doc, null);
}
/**
* Constructor that uses an existing document. The COSDocument that is passed in must be valid.
*
* @param doc The COSDocument that this document wraps.
* @param source the parser which is used to read the pdf
*/
public PDDocument(COSDocument doc, RandomAccessRead source)
{
this(doc, source, null);
}
/**
* Constructor that uses an existing document. The COSDocument that is passed in must be valid.
*
* @param doc The COSDocument that this document wraps.
* @param source the parser which is used to read the pdf
* @param permission he access permissions of the pdf
*
*/
public PDDocument(COSDocument doc, RandomAccessRead source, AccessPermission permission)
{
document = doc;
pdfSource = source;
accessPermission = permission;
}
/**
* This will get the low level document.
*
* @return The document that this layer sits on top of.
*/
public COSDocument getDocument()
{
return document;
}
/**
* This will get the document info dictionary. This is guaranteed to not return null.
*
* @return The documents /Info dictionary
*/
public PDDocumentInformation getDocumentInformation()
{
if (documentInformation == null)
{
COSDictionary trailer = document.getTrailer();
COSDictionary infoDic = (COSDictionary) trailer.getDictionaryObject(COSName.INFO);
if (infoDic == null)
{
infoDic = new COSDictionary();
trailer.setItem(COSName.INFO, infoDic);
}
documentInformation = new PDDocumentInformation(infoDic);
}
return documentInformation;
}
/**
* This will set the document information for this document.
*
* @param info The updated document information.
*/
public void setDocumentInformation(PDDocumentInformation info)
{
documentInformation = info;
document.getTrailer().setItem(COSName.INFO, info.getCOSObject());
}
/**
* This will get the document CATALOG. This is guaranteed to not return null.
*
* @return The documents /Root dictionary
*/
public PDDocumentCatalog getDocumentCatalog()
{
if (documentCatalog == null)
{
COSDictionary trailer = document.getTrailer();
COSBase dictionary = trailer.getDictionaryObject(COSName.ROOT);
if (dictionary instanceof COSDictionary)
{
documentCatalog = new PDDocumentCatalog(this, (COSDictionary) dictionary);
}
else
{
documentCatalog = new PDDocumentCatalog(this);
}
}
return documentCatalog;
}
/**
* This will tell if this document is encrypted or not.
*
* @return true If this document is encrypted.
*/
public boolean isEncrypted()
{
return document.isEncrypted();
}
/**
* This will get the encryption dictionary for this document. This will still return the parameters if the document
* was decrypted. As the encryption architecture in PDF documents is plugable this returns an abstract class,
* but the only supported subclass at this time is a
* PDStandardEncryption object.
*
* @return The encryption dictionary(most likely a PDStandardEncryption object)
*/
public PDEncryption getEncryption()
{
if (encryption == null && isEncrypted())
{
encryption = new PDEncryption(document.getEncryptionDictionary());
}
return encryption;
}
/**
* This will set the encryption dictionary for this document.
*
* @param encryption The encryption dictionary(most likely a PDStandardEncryption object)
*/
public void setEncryptionDictionary(PDEncryption encryption)
{
this.encryption = encryption;
}
/**
* This will return the last signature from the field tree. Note that this may not be the
* last in time when empty signature fields are created first but signed after other fields.
*
* @return the last signature as <code>PDSignatureField</code>.
*/
public PDSignature getLastSignatureDictionary()
{
List<PDSignature> signatureDictionaries = getSignatureDictionaries();
int size = signatureDictionaries.size();
if (size > 0)
{
return signatureDictionaries.get(size - 1);
}
return null;
}
/**
* Retrieve all signature fields from the document.
*
* @return a <code>List</code> of <code>PDSignatureField</code>s
*/
public List<PDSignatureField> getSignatureFields()
{
List<PDSignatureField> fields = new ArrayList<>();
PDAcroForm acroForm = getDocumentCatalog().getAcroForm();
if (acroForm != null)
{
for (PDField field : acroForm.getFieldTree())
{
if (field instanceof PDSignatureField)
{
fields.add((PDSignatureField)field);
}
}
}
return fields;
}
/**
* Retrieve all signature dictionaries from the document.
*
* @return a <code>List</code> of <code>PDSignatureField</code>s
*/
public List<PDSignature> getSignatureDictionaries()
{
List<PDSignature> signatures = new ArrayList<>();
for (PDSignatureField field : getSignatureFields())
{
COSBase value = field.getCOSObject().getDictionaryObject(COSName.V);
if (value instanceof COSDictionary)
{
signatures.add(new PDSignature((COSDictionary)value));
}
}
return signatures;
}
/**
* For internal PDFBox use when creating PDF documents: register a TrueTypeFont to make sure it
* is closed when the PDDocument is closed to avoid memory leaks. Users don't have to call this
* method, it is done by the appropriate PDFont classes.
*
* @param ttf
*/
public void registerTrueTypeFontForClosing(TrueTypeFont ttf)
{
fontsToClose.add(ttf);
}
/**
* Returns the list of fonts which will be subset before the document is saved.
*/
Set<PDFont> getFontsToSubset()
{
return fontsToSubset;
}
/**
* Parses a PDF. Unrestricted main memory will be used for buffering PDF streams.
*
* @param file file to be loaded
*
* @return loaded document
*
* @throws InvalidPasswordException If the file required a non-empty password.
* @throws IOException in case of a file reading or parsing error
*/
public static PDDocument load(File file) throws InvalidPasswordException, IOException
{
return load(file, "", MemoryUsageSetting.setupMainMemoryOnly());
}
/**
* Parses a PDF.
*
* @param file file to be loaded
* @param memUsageSetting defines how memory is used for buffering PDF streams
*
* @return loaded document
*
* @throws InvalidPasswordException If the file required a non-empty password.
* @throws IOException in case of a file reading or parsing error
*/
public static PDDocument load(File file, MemoryUsageSetting memUsageSetting)
throws InvalidPasswordException, IOException
{
return load(file, "", null, null, memUsageSetting);
}
/**
* Parses a PDF. Unrestricted main memory will be used for buffering PDF streams.
*
* @param file file to be loaded
* @param password password to be used for decryption
*
* @return loaded document
*
* @throws InvalidPasswordException If the password is incorrect.
* @throws IOException in case of a file reading or parsing error
*/
public static PDDocument load(File file, String password)
throws InvalidPasswordException, IOException
{
return load(file, password, null, null, MemoryUsageSetting.setupMainMemoryOnly());
}
/**
* Parses a PDF.
*
* @param file file to be loaded
* @param password password to be used for decryption
* @param memUsageSetting defines how memory is used for buffering PDF streams
*
* @return loaded document
*
* @throws InvalidPasswordException If the password is incorrect.
* @throws IOException in case of a file reading or parsing error
*/
public static PDDocument load(File file, String password, MemoryUsageSetting memUsageSetting)
throws InvalidPasswordException, IOException
{
return load(file, password, null, null, memUsageSetting);
}
/**
* Parses a PDF. Unrestricted main memory will be used for buffering PDF streams.
*
* @param file file to be loaded
* @param password password to be used for decryption
* @param keyStore key store to be used for decryption when using public key security
* @param alias alias to be used for decryption when using public key security
*
* @return loaded document
*
* @throws IOException in case of a file reading or parsing error
*/
public static PDDocument load(File file, String password, InputStream keyStore, String alias)
throws IOException
{
return load(file, password, keyStore, alias, MemoryUsageSetting.setupMainMemoryOnly());
}
/**
* Parses a PDF.
*
* @param file file to be loaded
* @param password password to be used for decryption
* @param keyStore key store to be used for decryption when using public key security
* @param alias alias to be used for decryption when using public key security
* @param memUsageSetting defines how memory is used for buffering PDF streams
*
* @return loaded document
*
* @throws IOException in case of a file reading or parsing error
*/
public static PDDocument load(File file, String password, InputStream keyStore, String alias,
MemoryUsageSetting memUsageSetting) throws IOException
{
RandomAccessBufferedFileInputStream raFile = new RandomAccessBufferedFileInputStream(file);
try
{
ScratchFile scratchFile = new ScratchFile(memUsageSetting);
try
{
PDFParser parser = new PDFParser(raFile, password, keyStore, alias, scratchFile);
parser.parse();
return parser.getPDDocument();
}
catch (IOException ioe)
{
IOUtils.closeQuietly(scratchFile);
throw ioe;
}
}
catch (IOException ioe)
{
IOUtils.closeQuietly(raFile);
throw ioe;
}
}
/**
* Parses a PDF. The given input stream is copied to the memory to enable random access to the pdf.
* Unrestricted main memory will be used for buffering PDF streams.
*
* @param input stream that contains the document.
*
* @return loaded document
*
* @throws InvalidPasswordException If the PDF required a non-empty password.
* @throws IOException In case of a reading or parsing error.
*/
public static PDDocument load(InputStream input) throws InvalidPasswordException, IOException
{
return load(input, "", null, null, MemoryUsageSetting.setupMainMemoryOnly());
}
/**
* Parses a PDF. Depending on the memory settings parameter the given input
* stream is either copied to main memory or to a temporary file to enable
* random access to the pdf.
*
* @param input stream that contains the document.
* @param memUsageSetting defines how memory is used for buffering input stream and PDF streams
*
* @return loaded document
*
* @throws InvalidPasswordException If the PDF required a non-empty password.
* @throws IOException In case of a reading or parsing error.
*/
public static PDDocument load(InputStream input, MemoryUsageSetting memUsageSetting)
throws InvalidPasswordException, IOException
{
return load(input, "", null, null, memUsageSetting);
}
/**
* Parses a PDF. The given input stream is copied to the memory to enable random access to the pdf.
* Unrestricted main memory will be used for buffering PDF streams.
*
* @param input stream that contains the document.
* @param password password to be used for decryption
*
* @return loaded document
*
* @throws InvalidPasswordException If the password is incorrect.
* @throws IOException In case of a reading or parsing error.
*/
public static PDDocument load(InputStream input, String password)
throws InvalidPasswordException, IOException
{
return load(input, password, null, null, MemoryUsageSetting.setupMainMemoryOnly());
}
/**
* Parses a PDF. The given input stream is copied to the memory to enable random access to the pdf.
* Unrestricted main memory will be used for buffering PDF streams.
*
* @param input stream that contains the document.
* @param password password to be used for decryption
* @param keyStore key store to be used for decryption when using public key security
* @param alias alias to be used for decryption when using public key security
*
* @return loaded document
*
* @throws IOException In case of a reading or parsing error.
*/
public static PDDocument load(InputStream input, String password, InputStream keyStore, String alias)
throws IOException
{
return load(input, password, keyStore, alias, MemoryUsageSetting.setupMainMemoryOnly());
}
/**
* Parses a PDF. Depending on the memory settings parameter the given input
* stream is either copied to main memory or to a temporary file to enable
* random access to the pdf.
*
* @param input stream that contains the document.
* @param password password to be used for decryption
* @param memUsageSetting defines how memory is used for buffering input stream and PDF streams
*
* @return loaded document
*
* @throws InvalidPasswordException If the password is incorrect.
* @throws IOException In case of a reading or parsing error.
*/
public static PDDocument load(InputStream input, String password, MemoryUsageSetting memUsageSetting)
throws InvalidPasswordException, IOException
{
return load(input, password, null, null, memUsageSetting);
}
/**
* Parses a PDF. Depending on the memory settings parameter the given input
* stream is either copied to memory or to a temporary file to enable
* random access to the pdf.
*
* @param input stream that contains the document.
* @param password password to be used for decryption
* @param keyStore key store to be used for decryption when using public key security
* @param alias alias to be used for decryption when using public key security
* @param memUsageSetting defines how memory is used for buffering input stream and PDF streams
*
* @return loaded document
*
* @throws InvalidPasswordException If the password is incorrect.
* @throws IOException In case of a reading or parsing error.
*/
public static PDDocument load(InputStream input, String password, InputStream keyStore,
String alias, MemoryUsageSetting memUsageSetting) throws IOException
{
ScratchFile scratchFile = new ScratchFile(memUsageSetting);
try
{
RandomAccessRead source = scratchFile.createBuffer(input);
PDFParser parser = new PDFParser(source, password, keyStore, alias, scratchFile);
parser.parse();
return parser.getPDDocument();
}
catch (IOException ioe)
{
IOUtils.closeQuietly(scratchFile);
throw ioe;
}
}
/**
* Parses a PDF. Unrestricted main memory will be used for buffering PDF streams.
*
* @param input byte array that contains the document.
*
* @return loaded document
*
* @throws InvalidPasswordException If the PDF required a non-empty password.
* @throws IOException In case of a reading or parsing error.
*/
public static PDDocument load(byte[] input) throws InvalidPasswordException, IOException
{
return load(input, "");
}
/**
* Parses a PDF. Unrestricted main memory will be used for buffering PDF streams.
*
* @param input byte array that contains the document.
* @param password password to be used for decryption
*
* @return loaded document
*
* @throws InvalidPasswordException If the password is incorrect.
* @throws IOException In case of a reading or parsing error.
*/
public static PDDocument load(byte[] input, String password)
throws InvalidPasswordException, IOException
{
return load(input, password, null, null);
}
/**
* Parses a PDF. Unrestricted main memory will be used for buffering PDF streams.
*
* @param input byte array that contains the document.
* @param password password to be used for decryption
* @param keyStore key store to be used for decryption when using public key security
* @param alias alias to be used for decryption when using public key security
*
* @return loaded document
*
* @throws InvalidPasswordException If the password is incorrect.
* @throws IOException In case of a reading or parsing error.
*/
public static PDDocument load(byte[] input, String password, InputStream keyStore,
String alias) throws IOException
{
return load(input, password, keyStore, alias, MemoryUsageSetting.setupMainMemoryOnly());
}
/**
* Parses a PDF.
*
* @param input byte array that contains the document.
* @param password password to be used for decryption
* @param keyStore key store to be used for decryption when using public key security
* @param alias alias to be used for decryption when using public key security
* @param memUsageSetting defines how memory is used for buffering input stream and PDF streams
*
* @return loaded document
*
* @throws InvalidPasswordException If the password is incorrect.
* @throws IOException In case of a reading or parsing error.
*/
public static PDDocument load(byte[] input, String password, InputStream keyStore,
String alias, MemoryUsageSetting memUsageSetting) throws IOException
{
ScratchFile scratchFile = new ScratchFile(memUsageSetting);
RandomAccessRead source = new RandomAccessBuffer(input);
PDFParser parser = new PDFParser(source, password, keyStore, alias, scratchFile);
parser.parse();
return parser.getPDDocument();
}
/**
* Save the document to a file.
*
* @param fileName The file to save as.
*
* @throws IOException if the output could not be written
*/
public void save(String fileName) throws IOException
{
save(new File(fileName));
}
/**
* Save the document to a file.
*
* @param file The file to save as.
*
* @throws IOException if the output could not be written
*/
public void save(File file) throws IOException
{
save(new BufferedOutputStream(new FileOutputStream(file)));
}
/**
* This will save the document to an output stream.
*
* @param output The stream to write to. It will be closed when done. It is recommended to wrap
* it in a {@link java.io.BufferedOutputStream}, unless it is already buffered.
*
* @throws IOException if the output could not be written
*/
public void save(OutputStream output) throws IOException
{
if (document.isClosed())
{
throw new IOException("Cannot save a document which has been closed");
}
// subset designated fonts
for (PDFont font : fontsToSubset)
{
font.subset();
}
fontsToSubset.clear();
// save PDF
try (COSWriter writer = new COSWriter(output))
{
writer.write(this);
}
}
/**
* Save the PDF as an incremental update. This is only possible if the PDF was loaded from a
* file or a stream, not if the document was created in PDFBox itself.
*
* @param output stream to write to. It will be closed when done. It
* <i><b>must never</b></i> point to the source file or that one will be
* harmed!
* @throws IOException if the output could not be written
* @throws IllegalStateException if the document was not loaded from a file or a stream.
*/
public void saveIncremental(OutputStream output) throws IOException
{
if (pdfSource == null)
{
throw new IllegalStateException("document was not loaded from a file or a stream");
}
try (COSWriter writer = new COSWriter(output, pdfSource))
{
writer.write(this, signInterface);
}
}
/**
* Save PDF incrementally without closing for external signature creation scenario. The general
* sequence is:
* <pre>
* PDDocument pdDocument = ...;
* OutputStream outputStream = ...;
* SignatureOptions signatureOptions = ...; // options to specify fine tuned signature options or null for defaults
* PDSignature pdSignature = ...;
*
* // add signature parameters to be used when creating signature dictionary
* pdDocument.addSignature(pdSignature, signatureOptions);
* // prepare PDF for signing and obtain helper class to be used
* ExternalSigningSupport externalSigningSupport = pdDocument.saveIncrementalForExternalSigning(outputStream);
* // get data to be signed
* InputStream dataToBeSigned = externalSigningSupport.getContent();
* // invoke signature service
* byte[] signature = sign(dataToBeSigned);
* // set resulted CMS signature
* externalSigningSupport.setSignature(signature);
*
* // last step is to close the document
* pdDocument.close();
* </pre>
* <p>
* Note that after calling this method, only {@code close()} method may invoked for
* {@code PDDocument} instance and only AFTER {@link ExternalSigningSupport} instance is used.
* </p>
*
* @param output stream to write the final PDF. It will be closed when the
* document is closed. It <i><b>must never</b></i> point to the source file
* or that one will be harmed!
* @return instance to be used for external signing and setting CMS signature
* @throws IOException if the output could not be written
* @throws IllegalStateException if the document was not loaded from a file or a stream or
* signature options were not set.
*/
public ExternalSigningSupport saveIncrementalForExternalSigning(OutputStream output) throws IOException
{
if (pdfSource == null)
{
throw new IllegalStateException("document was not loaded from a file or a stream");
}
// PDFBOX-3978: getLastSignatureDictionary() not helpful if signing into a template
// that is not the last signature. So give higher priority to signature with update flag.
PDSignature foundSignature = null;
for (PDSignature sig : getSignatureDictionaries())
{
foundSignature = sig;
if (sig.getCOSObject().isNeedToBeUpdated())
{
break;
}
}
if (foundSignature == null)
{
throw new IllegalStateException("document does not contain signature fields");
}
int[] byteRange = foundSignature.getByteRange();
if (!Arrays.equals(byteRange, RESERVE_BYTE_RANGE))
{
throw new IllegalStateException("signature reserve byte range has been changed "
+ "after addSignature(), please set the byte range that existed after addSignature()");
}
COSWriter writer = new COSWriter(output, pdfSource);
writer.write(this);
signingSupport = new SigningSupport(writer);
return signingSupport;
}
/**
* Returns the page at the given 0-based index.
* <p>
* This method is too slow to get all the pages from a large PDF document
* (1000 pages or more). For such documents, use the iterator of
* {@link PDDocument#getPages()} instead.
*
* @param pageIndex the 0-based page index
* @return the page at the given index.
*/
public PDPage getPage(int pageIndex) // todo: REPLACE most calls to this method with BELOW method
{
return getDocumentCatalog().getPages().get(pageIndex);
}
/**
* Returns the page tree.
*
* @return the page tree
*/
public PDPageTree getPages()
{
return getDocumentCatalog().getPages();
}
/**
* This will return the total page count of the PDF document.
*
* @return The total number of pages in the PDF document.
*/
public int getNumberOfPages()
{
return getDocumentCatalog().getPages().getCount();
}
/**
* This will close the underlying COSDocument object.
*
* @throws IOException If there is an error releasing resources.
*/
@Override
public void close() throws IOException
{
if (!document.isClosed())
{
// Make sure that:
// - first Exception is kept
// - all IO resources are closed
// - there's a way to see which errors occured
IOException firstException = null;
// close resources and COSWriter
if (signingSupport != null)
{
firstException = IOUtils.closeAndLogException(signingSupport, LOG, "SigningSupport", firstException);
}
// close all intermediate I/O streams
firstException = IOUtils.closeAndLogException(document, LOG, "COSDocument", firstException);
// close the source PDF stream, if we read from one
if (pdfSource != null)
{
firstException = IOUtils.closeAndLogException(pdfSource, LOG, "RandomAccessRead pdfSource", firstException);
}
// close fonts
for (TrueTypeFont ttf : fontsToClose)
{
firstException = IOUtils.closeAndLogException(ttf, LOG, "TrueTypeFont", firstException);
}
// rethrow first exception to keep method contract
if (firstException != null)
{
throw firstException;
}
}
}
/**
* Protects the document with a protection policy. The document content will be really
* encrypted when it will be saved. This method only marks the document for encryption. It also
* calls {@link #setAllSecurityToBeRemoved(boolean)} with a false argument if it was set to true
* previously and logs a warning.
*
* @see org.apache.pdfbox.pdmodel.encryption.StandardProtectionPolicy
* @see org.apache.pdfbox.pdmodel.encryption.PublicKeyProtectionPolicy
*
* @param policy The protection policy.
* @throws IOException if there isn't any suitable security handler.
*/
public void protect(ProtectionPolicy policy) throws IOException
{
if (isAllSecurityToBeRemoved())
{
LOG.warn("do not call setAllSecurityToBeRemoved(true) before calling protect(), "
+ "as protect() implies setAllSecurityToBeRemoved(false)");
setAllSecurityToBeRemoved(false);
}
if (!isEncrypted())
{
encryption = new PDEncryption();
}
SecurityHandler securityHandler = SecurityHandlerFactory.INSTANCE.newSecurityHandlerForPolicy(policy);
if (securityHandler == null)
{
throw new IOException("No security handler for policy " + policy);
}
getEncryption().setSecurityHandler(securityHandler);
}
/**
* Returns the access permissions granted when the document was decrypted. If the document was not decrypted this
* method returns the access permission for a document owner (ie can do everything). The returned object is in read
* only mode so that permissions cannot be changed. Methods providing access to content should rely on this object
* to verify if the current user is allowed to proceed.
*
* @return the access permissions for the current user on the document.
*/
public AccessPermission getCurrentAccessPermission()
{
if (accessPermission == null)
{
accessPermission = AccessPermission.getOwnerAccessPermission();
}
return accessPermission;
}
/**
* Indicates if all security is removed or not when writing the pdf.
*
* @return returns true if all security shall be removed otherwise false
*/
public boolean isAllSecurityToBeRemoved()
{
return allSecurityToBeRemoved;
}
/**
* Activates/Deactivates the removal of all security when writing the pdf.
*
* @param removeAllSecurity remove all security if set to true
*/
public void setAllSecurityToBeRemoved(boolean removeAllSecurity)
{
allSecurityToBeRemoved = removeAllSecurity;
}
/**
* Provides the document ID.
*
* @return the dcoument ID
*/
public Long getDocumentId()
{
return documentId;
}
/**
* Sets the document ID to the given value.
*
* @param docId the new document ID
*/
public void setDocumentId(Long docId)
{
documentId = docId;
}
/**
* Returns the PDF specification version this document conforms to.
*
* @return the PDF version (e.g. 1.4f)
*/
public float getVersion()
{
float headerVersionFloat = getDocument().getVersion();
// there may be a second version information in the document catalog starting with 1.4
if (headerVersionFloat >= 1.4f)
{
String catalogVersion = getDocumentCatalog().getVersion();
float catalogVersionFloat = -1;
if (catalogVersion != null)
{
try
{
catalogVersionFloat = Float.parseFloat(catalogVersion);
}
catch(NumberFormatException exception)
{
LOG.error("Can't extract the version number of the document catalog.", exception);
}
}
// the most recent version is the correct one
return Math.max(catalogVersionFloat, headerVersionFloat);
}
else
{
return headerVersionFloat;
}
}
/**
* Sets the PDF specification version for this document.
*
* @param newVersion the new PDF version (e.g. 1.4f)
*
*/
public void setVersion(float newVersion)
{
float currentVersion = getVersion();
// nothing to do?
if (Float.compare(newVersion,currentVersion) == 0)
{
return;
}
// the version can't be downgraded
if (newVersion < currentVersion)
{
LOG.error("It's not allowed to downgrade the version of a pdf.");
return;
}
// update the catalog version if the document version is >= 1.4
if (getDocument().getVersion() >= 1.4f)
{
getDocumentCatalog().setVersion(Float.toString(newVersion));
}
else
{
// versions < 1.4f have a version header only
getDocument().setVersion(newVersion);
}
}
/**
* Returns the resource cache associated with this document, or null if there is none.
*/
public ResourceCache getResourceCache()
{
return resourceCache;
}
/**
* Sets the resource cache associated with this document.
*
* @param resourceCache A resource cache, or null.
*/
public void setResourceCache(ResourceCache resourceCache)
{
this.resourceCache = resourceCache;
}
}
| pdfbox/src/main/java/org/apache/pdfbox/pdmodel/PDDocument.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.pdfbox.pdmodel;
import java.awt.Point;
import java.awt.image.DataBuffer;
import java.awt.image.Raster;
import java.awt.image.WritableRaster;
import java.io.BufferedOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.fontbox.ttf.TrueTypeFont;
import org.apache.pdfbox.cos.COSArray;
import org.apache.pdfbox.cos.COSBase;
import org.apache.pdfbox.cos.COSDictionary;
import org.apache.pdfbox.cos.COSDocument;
import org.apache.pdfbox.cos.COSInteger;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.cos.COSObject;
import org.apache.pdfbox.io.IOUtils;
import org.apache.pdfbox.io.MemoryUsageSetting;
import org.apache.pdfbox.io.RandomAccessBuffer;
import org.apache.pdfbox.io.RandomAccessBufferedFileInputStream;
import org.apache.pdfbox.io.RandomAccessRead;
import org.apache.pdfbox.io.ScratchFile;
import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.pdfwriter.COSWriter;
import org.apache.pdfbox.pdmodel.common.COSArrayList;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.common.PDStream;
import org.apache.pdfbox.pdmodel.encryption.AccessPermission;
import org.apache.pdfbox.pdmodel.encryption.InvalidPasswordException;
import org.apache.pdfbox.pdmodel.encryption.PDEncryption;
import org.apache.pdfbox.pdmodel.encryption.ProtectionPolicy;
import org.apache.pdfbox.pdmodel.encryption.SecurityHandler;
import org.apache.pdfbox.pdmodel.encryption.SecurityHandlerFactory;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.graphics.color.PDDeviceRGB;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationWidget;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAppearanceDictionary;
import org.apache.pdfbox.pdmodel.interactive.digitalsignature.ExternalSigningSupport;
import org.apache.pdfbox.pdmodel.interactive.digitalsignature.PDSignature;
import org.apache.pdfbox.pdmodel.interactive.digitalsignature.SignatureInterface;
import org.apache.pdfbox.pdmodel.interactive.digitalsignature.SignatureOptions;
import org.apache.pdfbox.pdmodel.interactive.digitalsignature.SigningSupport;
import org.apache.pdfbox.pdmodel.interactive.form.PDAcroForm;
import org.apache.pdfbox.pdmodel.interactive.form.PDField;
import org.apache.pdfbox.pdmodel.interactive.form.PDSignatureField;
/**
* This is the in-memory representation of the PDF document.
* The #close() method must be called once the document is no longer needed.
*
* @author Ben Litchfield
*/
public class PDDocument implements Closeable
{
/**
* For signing: large reserve byte range used as placeholder in the saved PDF until the actual
* length of the PDF is known. You'll need to fetch (with
* {@link PDSignature#getByteRange()} ) and reassign this yourself (with
* {@link PDSignature#setByteRange(int[])} ) only if you call
* {@link #saveIncrementalForExternalSigning(java.io.OutputStream) saveIncrementalForExternalSigning()}
* twice.
*/
private static final int[] RESERVE_BYTE_RANGE = new int[] { 0, 1000000000, 1000000000, 1000000000 };
private static final Log LOG = LogFactory.getLog(PDDocument.class);
/**
* avoid concurrency issues with PDDeviceRGB
*/
static
{
try
{
WritableRaster raster = Raster.createBandedRaster(DataBuffer.TYPE_BYTE, 1, 1, 3, new Point(0, 0));
PDDeviceRGB.INSTANCE.toRGBImage(raster);
}
catch (IOException ex)
{
LOG.debug("voodoo error", ex);
}
}
private final COSDocument document;
// cached values
private PDDocumentInformation documentInformation;
private PDDocumentCatalog documentCatalog;
// the encryption will be cached here. When the document is decrypted then
// the COSDocument will not have an "Encrypt" dictionary anymore and this object must be used
private PDEncryption encryption;
// holds a flag which tells us if we should remove all security from this documents.
private boolean allSecurityToBeRemoved;
// keep tracking customized documentId for the trailer. If null, a new id will be generated
// this ID doesn't represent the actual documentId from the trailer
private Long documentId;
// the pdf to be read
private final RandomAccessRead pdfSource;
// the access permissions of the document
private AccessPermission accessPermission;
// fonts to subset before saving
private final Set<PDFont> fontsToSubset = new HashSet<>();
// fonts to close when closing document
private final Set<TrueTypeFont> fontsToClose = new HashSet<>();
// Signature interface
private SignatureInterface signInterface;
// helper class used to create external signature
private SigningSupport signingSupport;
// document-wide cached resources
private ResourceCache resourceCache = new DefaultResourceCache();
// to make sure only one signature is added
private boolean signatureAdded = false;
/**
* Creates an empty PDF document.
* You need to add at least one page for the document to be valid.
*/
public PDDocument()
{
this(MemoryUsageSetting.setupMainMemoryOnly());
}
/**
* Creates an empty PDF document.
* You need to add at least one page for the document to be valid.
*
* @param memUsageSetting defines how memory is used for buffering PDF streams
*/
public PDDocument(MemoryUsageSetting memUsageSetting)
{
ScratchFile scratchFile = null;
try
{
scratchFile = new ScratchFile(memUsageSetting);
}
catch (IOException ioe)
{
LOG.warn("Error initializing scratch file: " + ioe.getMessage() +
". Fall back to main memory usage only.", ioe);
scratchFile = ScratchFile.getMainMemoryOnlyInstance();
}
document = new COSDocument(scratchFile);
pdfSource = null;
// First we need a trailer
COSDictionary trailer = new COSDictionary();
document.setTrailer(trailer);
// Next we need the root dictionary.
COSDictionary rootDictionary = new COSDictionary();
trailer.setItem(COSName.ROOT, rootDictionary);
rootDictionary.setItem(COSName.TYPE, COSName.CATALOG);
rootDictionary.setItem(COSName.VERSION, COSName.getPDFName("1.4"));
// next we need the pages tree structure
COSDictionary pages = new COSDictionary();
rootDictionary.setItem(COSName.PAGES, pages);
pages.setItem(COSName.TYPE, COSName.PAGES);
COSArray kidsArray = new COSArray();
pages.setItem(COSName.KIDS, kidsArray);
pages.setItem(COSName.COUNT, COSInteger.ZERO);
}
/**
* This will add a page to the document. This is a convenience method, that will add the page to the root of the
* hierarchy and set the parent of the page to the root.
*
* @param page The page to add to the document.
*/
public void addPage(PDPage page)
{
getPages().add(page);
}
/**
* Add parameters of signature to be created externally using default signature options. See
* {@link #saveIncrementalForExternalSigning(OutputStream)} method description on external
* signature creation scenario details.
* <p>
* Only one signature may be added in a document. To sign several times,
* load document, add signature, save incremental and close again.
*
* @param sigObject is the PDSignatureField model
* @throws IOException if there is an error creating required fields
* @throws IllegalStateException if one attempts to add several signature
* fields.
*/
public void addSignature(PDSignature sigObject) throws IOException
{
addSignature(sigObject, new SignatureOptions());
}
/**
* Add parameters of signature to be created externally. See
* {@link #saveIncrementalForExternalSigning(OutputStream)} method description on external
* signature creation scenario details.
* <p>
* Only one signature may be added in a document. To sign several times,
* load document, add signature, save incremental and close again.
*
* @param sigObject is the PDSignatureField model
* @param options signature options
* @throws IOException if there is an error creating required fields
* @throws IllegalStateException if one attempts to add several signature
* fields.
*/
public void addSignature(PDSignature sigObject, SignatureOptions options) throws IOException
{
addSignature(sigObject, null, options);
}
/**
* Add a signature to be created using the instance of given interface.
* <p>
* Only one signature may be added in a document. To sign several times,
* load document, add signature, save incremental and close again.
*
* @param sigObject is the PDSignatureField model
* @param signatureInterface is an interface whose implementation provides
* signing capabilities. Can be null if external signing if used.
* @throws IOException if there is an error creating required fields
* @throws IllegalStateException if one attempts to add several signature
* fields.
*/
public void addSignature(PDSignature sigObject, SignatureInterface signatureInterface) throws IOException
{
addSignature(sigObject, signatureInterface, new SignatureOptions());
}
/**
* This will add a signature to the document. If the 0-based page number in the options
* parameter is smaller than 0 or larger than max, the nearest valid page number will be used
* (i.e. 0 or max) and no exception will be thrown.
* <p>
* Only one signature may be added in a document. To sign several times,
* load document, add signature, save incremental and close again.
*
* @param sigObject is the PDSignatureField model
* @param signatureInterface is an interface whose implementation provides
* signing capabilities. Can be null if external signing if used.
* @param options signature options
* @throws IOException if there is an error creating required fields
* @throws IllegalStateException if one attempts to add several signature
* fields.
*/
public void addSignature(PDSignature sigObject, SignatureInterface signatureInterface,
SignatureOptions options) throws IOException
{
if (signatureAdded)
{
throw new IllegalStateException("Only one signature may be added in a document");
}
signatureAdded = true;
// Reserve content
// We need to reserve some space for the signature. Some signatures including
// big certificate chain and we need enough space to store it.
int preferredSignatureSize = options.getPreferredSignatureSize();
if (preferredSignatureSize > 0)
{
sigObject.setContents(new byte[preferredSignatureSize]);
}
else
{
sigObject.setContents(new byte[SignatureOptions.DEFAULT_SIGNATURE_SIZE]);
}
// Reserve ByteRange, will be overwritten in COSWriter
sigObject.setByteRange(RESERVE_BYTE_RANGE);
signInterface = signatureInterface;
// Create SignatureForm for signature and append it to the document
// Get the first valid page
int pageCount = getNumberOfPages();
if (pageCount == 0)
{
throw new IllegalStateException("Cannot sign an empty document");
}
int startIndex = Math.min(Math.max(options.getPage(), 0), pageCount - 1);
PDPage page = getPage(startIndex);
// Get the AcroForm from the Root-Dictionary and append the annotation
PDDocumentCatalog catalog = getDocumentCatalog();
PDAcroForm acroForm = catalog.getAcroForm();
catalog.getCOSObject().setNeedToBeUpdated(true);
if (acroForm == null)
{
acroForm = new PDAcroForm(this);
catalog.setAcroForm(acroForm);
}
else
{
acroForm.getCOSObject().setNeedToBeUpdated(true);
}
PDSignatureField signatureField = null;
if (!(acroForm.getCOSObject().getDictionaryObject(COSName.FIELDS) instanceof COSArray))
{
acroForm.getCOSObject().setItem(COSName.FIELDS, new COSArray());
}
else
{
COSArray fieldArray = (COSArray) acroForm.getCOSObject().getDictionaryObject(COSName.FIELDS);
fieldArray.setNeedToBeUpdated(true);
signatureField = findSignatureField(acroForm.getFieldIterator(), sigObject);
}
if (signatureField == null)
{
signatureField = new PDSignatureField(acroForm);
// append the signature object
signatureField.setValue(sigObject);
// backward linking
signatureField.getWidgets().get(0).setPage(page);
}
else
{
sigObject.getCOSObject().setNeedToBeUpdated(true);
}
// TODO This "overwrites" the settings of the original signature field which might not be intended by the user
// better make it configurable (not all users need/want PDF/A but their own setting):
// to conform PDF/A-1 requirement:
// The /F key's Print flag bit shall be set to 1 and
// its Hidden, Invisible and NoView flag bits shall be set to 0
signatureField.getWidgets().get(0).setPrinted(true);
// Set the AcroForm Fields
List<PDField> acroFormFields = acroForm.getFields();
acroForm.getCOSObject().setDirect(true);
acroForm.setSignaturesExist(true);
acroForm.setAppendOnly(true);
boolean checkFields = checkSignatureField(acroForm.getFieldIterator(), signatureField);
if (checkFields)
{
signatureField.getCOSObject().setNeedToBeUpdated(true);
}
else
{
acroFormFields.add(signatureField);
}
// Get the object from the visual signature
COSDocument visualSignature = options.getVisualSignature();
// Distinction of case for visual and non-visual signature
if (visualSignature == null)
{
prepareNonVisibleSignature(signatureField);
return;
}
prepareVisibleSignature(signatureField, acroForm, visualSignature);
// Create Annotation / Field for signature
List<PDAnnotation> annotations = page.getAnnotations();
// Make /Annots a direct object to avoid problem if it is an existing indirect object:
// it would not be updated in incremental save, and if we'd set the /Annots array "to be updated"
// while keeping it indirect, Adobe Reader would claim that the document had been modified.
page.setAnnotations(annotations);
// Get the annotations of the page and append the signature-annotation to it
// take care that page and acroforms do not share the same array (if so, we don't need to add it twice)
if (!(annotations instanceof COSArrayList &&
acroFormFields instanceof COSArrayList &&
((COSArrayList<?>) annotations).toList().equals(((COSArrayList<?>) acroFormFields).toList()) &&
checkFields))
{
PDAnnotationWidget widget = signatureField.getWidgets().get(0);
// use check to prevent the annotation widget from appearing twice
if (checkSignatureAnnotation(annotations, widget))
{
widget.getCOSObject().setNeedToBeUpdated(true);
}
else
{
annotations.add(widget);
}
}
page.getCOSObject().setNeedToBeUpdated(true);
}
/**
* Search acroform fields for signature field with specific signature dictionary.
*
* @param fieldIterator iterator on all fields.
* @param sigObject signature object (the /V part).
* @return a signature field if found, or null if none was found.
*/
private PDSignatureField findSignatureField(Iterator<PDField> fieldIterator, PDSignature sigObject)
{
PDSignatureField signatureField = null;
while (fieldIterator.hasNext())
{
PDField pdField = fieldIterator.next();
if (pdField instanceof PDSignatureField)
{
PDSignature signature = ((PDSignatureField) pdField).getSignature();
if (signature != null && signature.getCOSObject().equals(sigObject.getCOSObject()))
{
signatureField = (PDSignatureField) pdField;
}
}
}
return signatureField;
}
/**
* Check if the field already exists in the field list.
*
* @param fieldIterator iterator on all fields.
* @param signatureField the signature field.
* @return true if the field already existed in the field list, false if not.
*/
private boolean checkSignatureField(Iterator<PDField> fieldIterator, PDSignatureField signatureField)
{
while (fieldIterator.hasNext())
{
PDField field = fieldIterator.next();
if (field instanceof PDSignatureField
&& field.getCOSObject().equals(signatureField.getCOSObject()))
{
return true;
}
}
return false;
}
/**
* Check if the widget already exists in the annotation list
*
* @param acroFormFields the list of AcroForm fields.
* @param signatureField the signature field.
* @return true if the widget already existed in the annotation list, false if not.
*/
private boolean checkSignatureAnnotation(List<PDAnnotation> annotations, PDAnnotationWidget widget)
{
for (PDAnnotation annotation : annotations)
{
if (annotation.getCOSObject().equals(widget.getCOSObject()))
{
return true;
}
}
return false;
}
private void prepareVisibleSignature(PDSignatureField signatureField, PDAcroForm acroForm,
COSDocument visualSignature)
{
// Obtain visual signature object
boolean annotNotFound = true;
boolean sigFieldNotFound = true;
for (COSObject cosObject : visualSignature.getObjects())
{
if (!annotNotFound && !sigFieldNotFound)
{
break;
}
COSBase base = cosObject.getObject();
if (base instanceof COSDictionary)
{
COSDictionary cosBaseDict = (COSDictionary) base;
// Search for signature annotation
COSBase type = cosBaseDict.getDictionaryObject(COSName.TYPE);
if (annotNotFound && COSName.ANNOT.equals(type))
{
assignSignatureRectangle(signatureField, cosBaseDict);
annotNotFound = false;
}
// Search for signature field
COSBase fieldType = cosBaseDict.getDictionaryObject(COSName.FT);
COSBase apDict = cosBaseDict.getDictionaryObject(COSName.AP);
if (sigFieldNotFound && COSName.SIG.equals(fieldType) && apDict instanceof COSDictionary)
{
assignAppearanceDictionary(signatureField, (COSDictionary) apDict);
assignAcroFormDefaultResource(acroForm, cosBaseDict);
sigFieldNotFound = false;
}
}
}
if (annotNotFound || sigFieldNotFound)
{
throw new IllegalArgumentException("Template is missing required objects");
}
}
private void assignSignatureRectangle(PDSignatureField signatureField, COSDictionary annotDict)
{
// Read and set the rectangle for visual signature
COSArray rectArray = (COSArray) annotDict.getDictionaryObject(COSName.RECT);
PDRectangle rect = new PDRectangle(rectArray);
PDRectangle existingRectangle = signatureField.getWidgets().get(0).getRectangle();
//in case of an existing field keep the original rect
if (existingRectangle == null || existingRectangle.getCOSArray().size() != 4)
{
signatureField.getWidgets().get(0).setRectangle(rect);
}
}
private void assignAppearanceDictionary(PDSignatureField signatureField, COSDictionary apDict)
{
// read and set Appearance Dictionary
PDAppearanceDictionary ap = new PDAppearanceDictionary(apDict);
apDict.setDirect(true);
signatureField.getWidgets().get(0).setAppearance(ap);
}
private void assignAcroFormDefaultResource(PDAcroForm acroForm, COSDictionary newDict)
{
// read and set/update AcroForm default resource dictionary /DR if available
COSBase newBase = newDict.getDictionaryObject(COSName.DR);
if (newBase instanceof COSDictionary)
{
COSDictionary newDR = (COSDictionary) newBase;
PDResources defaultResources = acroForm.getDefaultResources();
if (defaultResources == null)
{
acroForm.getCOSObject().setItem(COSName.DR, newDR);
newDR.setDirect(true);
newDR.setNeedToBeUpdated(true);
}
else
{
COSDictionary oldDR = defaultResources.getCOSObject();
COSBase newXObjectBase = newDR.getItem(COSName.XOBJECT);
COSBase oldXObjectBase = oldDR.getItem(COSName.XOBJECT);
if (newXObjectBase instanceof COSDictionary &&
oldXObjectBase instanceof COSDictionary)
{
((COSDictionary) oldXObjectBase).addAll((COSDictionary) newXObjectBase);
oldDR.setNeedToBeUpdated(true);
}
}
}
}
private void prepareNonVisibleSignature(PDSignatureField signatureField)
{
// "Signature fields that are not intended to be visible shall
// have an annotation rectangle that has zero height and width."
// Set rectangle for non-visual signature to rectangle array [ 0 0 0 0 ]
signatureField.getWidgets().get(0).setRectangle(new PDRectangle());
}
/**
* Remove the page from the document.
*
* @param page The page to remove from the document.
*/
public void removePage(PDPage page)
{
getPages().remove(page);
}
/**
* Remove the page from the document.
*
* @param pageNumber 0 based index to page number.
*/
public void removePage(int pageNumber)
{
getPages().remove(pageNumber);
}
/**
* This will import and copy the contents from another location. Currently the content stream is stored in a scratch
* file. The scratch file is associated with the document. If you are adding a page to this document from another
* document and want to copy the contents to this
* document's scratch file then use this method otherwise just use the {@link #addPage addPage}
* method.
* <p>
* Unlike {@link #addPage addPage}, this method creates a new PDPage object. If your page has
* annotations, and if these link to pages not in the target document, then the target document
* might become huge. What you need to do is to delete page references of such annotations. See
* <a href="http://stackoverflow.com/a/35477351/535646">here</a> for how to do this.
* <p>
* Inherited (global) resources are ignored. If you need them, call
* <code>importedPage.setRotation(page.getRotation());</code>
*
* @param page The page to import.
* @return The page that was imported.
*
* @throws IOException If there is an error copying the page.
*/
public PDPage importPage(PDPage page) throws IOException
{
PDPage importedPage = new PDPage(new COSDictionary(page.getCOSObject()), resourceCache);
PDStream dest = new PDStream(this, page.getContents(), COSName.FLATE_DECODE);
importedPage.setContents(dest);
addPage(importedPage);
importedPage.setCropBox(page.getCropBox());
importedPage.setMediaBox(page.getMediaBox());
importedPage.setRotation(page.getRotation());
if (page.getResources() != null && !page.getCOSObject().containsKey(COSName.RESOURCES))
{
LOG.warn("inherited resources of source document are not imported to destination page");
LOG.warn("call importedPage.setResources(page.getResources()) to do this");
}
return importedPage;
}
/**
* Constructor that uses an existing document. The COSDocument that is passed in must be valid.
*
* @param doc The COSDocument that this document wraps.
*/
public PDDocument(COSDocument doc)
{
this(doc, null);
}
/**
* Constructor that uses an existing document. The COSDocument that is passed in must be valid.
*
* @param doc The COSDocument that this document wraps.
* @param source the parser which is used to read the pdf
*/
public PDDocument(COSDocument doc, RandomAccessRead source)
{
this(doc, source, null);
}
/**
* Constructor that uses an existing document. The COSDocument that is passed in must be valid.
*
* @param doc The COSDocument that this document wraps.
* @param source the parser which is used to read the pdf
* @param permission he access permissions of the pdf
*
*/
public PDDocument(COSDocument doc, RandomAccessRead source, AccessPermission permission)
{
document = doc;
pdfSource = source;
accessPermission = permission;
}
/**
* This will get the low level document.
*
* @return The document that this layer sits on top of.
*/
public COSDocument getDocument()
{
return document;
}
/**
* This will get the document info dictionary. This is guaranteed to not return null.
*
* @return The documents /Info dictionary
*/
public PDDocumentInformation getDocumentInformation()
{
if (documentInformation == null)
{
COSDictionary trailer = document.getTrailer();
COSDictionary infoDic = (COSDictionary) trailer.getDictionaryObject(COSName.INFO);
if (infoDic == null)
{
infoDic = new COSDictionary();
trailer.setItem(COSName.INFO, infoDic);
}
documentInformation = new PDDocumentInformation(infoDic);
}
return documentInformation;
}
/**
* This will set the document information for this document.
*
* @param info The updated document information.
*/
public void setDocumentInformation(PDDocumentInformation info)
{
documentInformation = info;
document.getTrailer().setItem(COSName.INFO, info.getCOSObject());
}
/**
* This will get the document CATALOG. This is guaranteed to not return null.
*
* @return The documents /Root dictionary
*/
public PDDocumentCatalog getDocumentCatalog()
{
if (documentCatalog == null)
{
COSDictionary trailer = document.getTrailer();
COSBase dictionary = trailer.getDictionaryObject(COSName.ROOT);
if (dictionary instanceof COSDictionary)
{
documentCatalog = new PDDocumentCatalog(this, (COSDictionary) dictionary);
}
else
{
documentCatalog = new PDDocumentCatalog(this);
}
}
return documentCatalog;
}
/**
* This will tell if this document is encrypted or not.
*
* @return true If this document is encrypted.
*/
public boolean isEncrypted()
{
return document.isEncrypted();
}
/**
* This will get the encryption dictionary for this document. This will still return the parameters if the document
* was decrypted. As the encryption architecture in PDF documents is plugable this returns an abstract class,
* but the only supported subclass at this time is a
* PDStandardEncryption object.
*
* @return The encryption dictionary(most likely a PDStandardEncryption object)
*/
public PDEncryption getEncryption()
{
if (encryption == null && isEncrypted())
{
encryption = new PDEncryption(document.getEncryptionDictionary());
}
return encryption;
}
/**
* This will set the encryption dictionary for this document.
*
* @param encryption The encryption dictionary(most likely a PDStandardEncryption object)
*/
public void setEncryptionDictionary(PDEncryption encryption)
{
this.encryption = encryption;
}
/**
* This will return the last signature from the field tree. Note that this may not be the
* last in time when empty signature fields are created first but signed after other fields.
*
* @return the last signature as <code>PDSignatureField</code>.
*/
public PDSignature getLastSignatureDictionary()
{
List<PDSignature> signatureDictionaries = getSignatureDictionaries();
int size = signatureDictionaries.size();
if (size > 0)
{
return signatureDictionaries.get(size - 1);
}
return null;
}
/**
* Retrieve all signature fields from the document.
*
* @return a <code>List</code> of <code>PDSignatureField</code>s
*/
public List<PDSignatureField> getSignatureFields()
{
List<PDSignatureField> fields = new ArrayList<>();
PDAcroForm acroForm = getDocumentCatalog().getAcroForm();
if (acroForm != null)
{
for (PDField field : acroForm.getFieldTree())
{
if (field instanceof PDSignatureField)
{
fields.add((PDSignatureField)field);
}
}
}
return fields;
}
/**
* Retrieve all signature dictionaries from the document.
*
* @return a <code>List</code> of <code>PDSignatureField</code>s
*/
public List<PDSignature> getSignatureDictionaries()
{
List<PDSignature> signatures = new ArrayList<>();
for (PDSignatureField field : getSignatureFields())
{
COSBase value = field.getCOSObject().getDictionaryObject(COSName.V);
if (value instanceof COSDictionary)
{
signatures.add(new PDSignature((COSDictionary)value));
}
}
return signatures;
}
/**
* For internal PDFBox use when creating PDF documents: register a TrueTypeFont to make sure it
* is closed when the PDDocument is closed to avoid memory leaks. Users don't have to call this
* method, it is done by the appropriate PDFont classes.
*
* @param ttf
*/
public void registerTrueTypeFontForClosing(TrueTypeFont ttf)
{
fontsToClose.add(ttf);
}
/**
* Returns the list of fonts which will be subset before the document is saved.
*/
Set<PDFont> getFontsToSubset()
{
return fontsToSubset;
}
/**
* Parses a PDF. Unrestricted main memory will be used for buffering PDF streams.
*
* @param file file to be loaded
*
* @return loaded document
*
* @throws InvalidPasswordException If the file required a non-empty password.
* @throws IOException in case of a file reading or parsing error
*/
public static PDDocument load(File file) throws InvalidPasswordException, IOException
{
return load(file, "", MemoryUsageSetting.setupMainMemoryOnly());
}
/**
* Parses a PDF.
*
* @param file file to be loaded
* @param memUsageSetting defines how memory is used for buffering PDF streams
*
* @return loaded document
*
* @throws InvalidPasswordException If the file required a non-empty password.
* @throws IOException in case of a file reading or parsing error
*/
public static PDDocument load(File file, MemoryUsageSetting memUsageSetting)
throws InvalidPasswordException, IOException
{
return load(file, "", null, null, memUsageSetting);
}
/**
* Parses a PDF. Unrestricted main memory will be used for buffering PDF streams.
*
* @param file file to be loaded
* @param password password to be used for decryption
*
* @return loaded document
*
* @throws InvalidPasswordException If the password is incorrect.
* @throws IOException in case of a file reading or parsing error
*/
public static PDDocument load(File file, String password)
throws InvalidPasswordException, IOException
{
return load(file, password, null, null, MemoryUsageSetting.setupMainMemoryOnly());
}
/**
* Parses a PDF.
*
* @param file file to be loaded
* @param password password to be used for decryption
* @param memUsageSetting defines how memory is used for buffering PDF streams
*
* @return loaded document
*
* @throws InvalidPasswordException If the password is incorrect.
* @throws IOException in case of a file reading or parsing error
*/
public static PDDocument load(File file, String password, MemoryUsageSetting memUsageSetting)
throws InvalidPasswordException, IOException
{
return load(file, password, null, null, memUsageSetting);
}
/**
* Parses a PDF. Unrestricted main memory will be used for buffering PDF streams.
*
* @param file file to be loaded
* @param password password to be used for decryption
* @param keyStore key store to be used for decryption when using public key security
* @param alias alias to be used for decryption when using public key security
*
* @return loaded document
*
* @throws IOException in case of a file reading or parsing error
*/
public static PDDocument load(File file, String password, InputStream keyStore, String alias)
throws IOException
{
return load(file, password, keyStore, alias, MemoryUsageSetting.setupMainMemoryOnly());
}
/**
* Parses a PDF.
*
* @param file file to be loaded
* @param password password to be used for decryption
* @param keyStore key store to be used for decryption when using public key security
* @param alias alias to be used for decryption when using public key security
* @param memUsageSetting defines how memory is used for buffering PDF streams
*
* @return loaded document
*
* @throws IOException in case of a file reading or parsing error
*/
public static PDDocument load(File file, String password, InputStream keyStore, String alias,
MemoryUsageSetting memUsageSetting) throws IOException
{
RandomAccessBufferedFileInputStream raFile = new RandomAccessBufferedFileInputStream(file);
try
{
ScratchFile scratchFile = new ScratchFile(memUsageSetting);
try
{
PDFParser parser = new PDFParser(raFile, password, keyStore, alias, scratchFile);
parser.parse();
return parser.getPDDocument();
}
catch (IOException ioe)
{
IOUtils.closeQuietly(scratchFile);
throw ioe;
}
}
catch (IOException ioe)
{
IOUtils.closeQuietly(raFile);
throw ioe;
}
}
/**
* Parses a PDF. The given input stream is copied to the memory to enable random access to the pdf.
* Unrestricted main memory will be used for buffering PDF streams.
*
* @param input stream that contains the document.
*
* @return loaded document
*
* @throws InvalidPasswordException If the PDF required a non-empty password.
* @throws IOException In case of a reading or parsing error.
*/
public static PDDocument load(InputStream input) throws InvalidPasswordException, IOException
{
return load(input, "", null, null, MemoryUsageSetting.setupMainMemoryOnly());
}
/**
* Parses a PDF. Depending on the memory settings parameter the given input
* stream is either copied to main memory or to a temporary file to enable
* random access to the pdf.
*
* @param input stream that contains the document.
* @param memUsageSetting defines how memory is used for buffering input stream and PDF streams
*
* @return loaded document
*
* @throws InvalidPasswordException If the PDF required a non-empty password.
* @throws IOException In case of a reading or parsing error.
*/
public static PDDocument load(InputStream input, MemoryUsageSetting memUsageSetting)
throws InvalidPasswordException, IOException
{
return load(input, "", null, null, memUsageSetting);
}
/**
* Parses a PDF. The given input stream is copied to the memory to enable random access to the pdf.
* Unrestricted main memory will be used for buffering PDF streams.
*
* @param input stream that contains the document.
* @param password password to be used for decryption
*
* @return loaded document
*
* @throws InvalidPasswordException If the password is incorrect.
* @throws IOException In case of a reading or parsing error.
*/
public static PDDocument load(InputStream input, String password)
throws InvalidPasswordException, IOException
{
return load(input, password, null, null, MemoryUsageSetting.setupMainMemoryOnly());
}
/**
* Parses a PDF. The given input stream is copied to the memory to enable random access to the pdf.
* Unrestricted main memory will be used for buffering PDF streams.
*
* @param input stream that contains the document.
* @param password password to be used for decryption
* @param keyStore key store to be used for decryption when using public key security
* @param alias alias to be used for decryption when using public key security
*
* @return loaded document
*
* @throws IOException In case of a reading or parsing error.
*/
public static PDDocument load(InputStream input, String password, InputStream keyStore, String alias)
throws IOException
{
return load(input, password, keyStore, alias, MemoryUsageSetting.setupMainMemoryOnly());
}
/**
* Parses a PDF. Depending on the memory settings parameter the given input
* stream is either copied to main memory or to a temporary file to enable
* random access to the pdf.
*
* @param input stream that contains the document.
* @param password password to be used for decryption
* @param memUsageSetting defines how memory is used for buffering input stream and PDF streams
*
* @return loaded document
*
* @throws InvalidPasswordException If the password is incorrect.
* @throws IOException In case of a reading or parsing error.
*/
public static PDDocument load(InputStream input, String password, MemoryUsageSetting memUsageSetting)
throws InvalidPasswordException, IOException
{
return load(input, password, null, null, memUsageSetting);
}
/**
* Parses a PDF. Depending on the memory settings parameter the given input
* stream is either copied to memory or to a temporary file to enable
* random access to the pdf.
*
* @param input stream that contains the document.
* @param password password to be used for decryption
* @param keyStore key store to be used for decryption when using public key security
* @param alias alias to be used for decryption when using public key security
* @param memUsageSetting defines how memory is used for buffering input stream and PDF streams
*
* @return loaded document
*
* @throws InvalidPasswordException If the password is incorrect.
* @throws IOException In case of a reading or parsing error.
*/
public static PDDocument load(InputStream input, String password, InputStream keyStore,
String alias, MemoryUsageSetting memUsageSetting) throws IOException
{
ScratchFile scratchFile = new ScratchFile(memUsageSetting);
try
{
RandomAccessRead source = scratchFile.createBuffer(input);
PDFParser parser = new PDFParser(source, password, keyStore, alias, scratchFile);
parser.parse();
return parser.getPDDocument();
}
catch (IOException ioe)
{
IOUtils.closeQuietly(scratchFile);
throw ioe;
}
}
/**
* Parses a PDF. Unrestricted main memory will be used for buffering PDF streams.
*
* @param input byte array that contains the document.
*
* @return loaded document
*
* @throws InvalidPasswordException If the PDF required a non-empty password.
* @throws IOException In case of a reading or parsing error.
*/
public static PDDocument load(byte[] input) throws InvalidPasswordException, IOException
{
return load(input, "");
}
/**
* Parses a PDF. Unrestricted main memory will be used for buffering PDF streams.
*
* @param input byte array that contains the document.
* @param password password to be used for decryption
*
* @return loaded document
*
* @throws InvalidPasswordException If the password is incorrect.
* @throws IOException In case of a reading or parsing error.
*/
public static PDDocument load(byte[] input, String password)
throws InvalidPasswordException, IOException
{
return load(input, password, null, null);
}
/**
* Parses a PDF. Unrestricted main memory will be used for buffering PDF streams.
*
* @param input byte array that contains the document.
* @param password password to be used for decryption
* @param keyStore key store to be used for decryption when using public key security
* @param alias alias to be used for decryption when using public key security
*
* @return loaded document
*
* @throws InvalidPasswordException If the password is incorrect.
* @throws IOException In case of a reading or parsing error.
*/
public static PDDocument load(byte[] input, String password, InputStream keyStore,
String alias) throws IOException
{
return load(input, password, keyStore, alias, MemoryUsageSetting.setupMainMemoryOnly());
}
/**
* Parses a PDF.
*
* @param input byte array that contains the document.
* @param password password to be used for decryption
* @param keyStore key store to be used for decryption when using public key security
* @param alias alias to be used for decryption when using public key security
* @param memUsageSetting defines how memory is used for buffering input stream and PDF streams
*
* @return loaded document
*
* @throws InvalidPasswordException If the password is incorrect.
* @throws IOException In case of a reading or parsing error.
*/
public static PDDocument load(byte[] input, String password, InputStream keyStore,
String alias, MemoryUsageSetting memUsageSetting) throws IOException
{
ScratchFile scratchFile = new ScratchFile(memUsageSetting);
RandomAccessRead source = new RandomAccessBuffer(input);
PDFParser parser = new PDFParser(source, password, keyStore, alias, scratchFile);
parser.parse();
return parser.getPDDocument();
}
/**
* Save the document to a file.
*
* @param fileName The file to save as.
*
* @throws IOException if the output could not be written
*/
public void save(String fileName) throws IOException
{
save(new File(fileName));
}
/**
* Save the document to a file.
*
* @param file The file to save as.
*
* @throws IOException if the output could not be written
*/
public void save(File file) throws IOException
{
save(new BufferedOutputStream(new FileOutputStream(file)));
}
/**
* This will save the document to an output stream.
*
* @param output The stream to write to. It will be closed when done. It is recommended to wrap
* it in a {@link java.io.BufferedOutputStream}, unless it is already buffered.
*
* @throws IOException if the output could not be written
*/
public void save(OutputStream output) throws IOException
{
if (document.isClosed())
{
throw new IOException("Cannot save a document which has been closed");
}
// subset designated fonts
for (PDFont font : fontsToSubset)
{
font.subset();
}
fontsToSubset.clear();
// save PDF
try (COSWriter writer = new COSWriter(output))
{
writer.write(this);
}
}
/**
* Save the PDF as an incremental update. This is only possible if the PDF was loaded from a
* file or a stream, not if the document was created in PDFBox itself.
*
* @param output stream to write to. It will be closed when done. It should <i><b>not</b></i>
* point to the source file.
* @throws IOException if the output could not be written
* @throws IllegalStateException if the document was not loaded from a file or a stream.
*/
public void saveIncremental(OutputStream output) throws IOException
{
if (pdfSource == null)
{
throw new IllegalStateException("document was not loaded from a file or a stream");
}
try (COSWriter writer = new COSWriter(output, pdfSource))
{
writer.write(this, signInterface);
}
}
/**
* Save PDF incrementally without closing for external signature creation scenario. The general
* sequence is:
* <pre>
* PDDocument pdDocument = ...;
* OutputStream outputStream = ...;
* SignatureOptions signatureOptions = ...; // options to specify fine tuned signature options or null for defaults
* PDSignature pdSignature = ...;
*
* // add signature parameters to be used when creating signature dictionary
* pdDocument.addSignature(pdSignature, signatureOptions);
* // prepare PDF for signing and obtain helper class to be used
* ExternalSigningSupport externalSigningSupport = pdDocument.saveIncrementalForExternalSigning(outputStream);
* // get data to be signed
* InputStream dataToBeSigned = externalSigningSupport.getContent();
* // invoke signature service
* byte[] signature = sign(dataToBeSigned);
* // set resulted CMS signature
* externalSigningSupport.setSignature(signature);
*
* // last step is to close the document
* pdDocument.close();
* </pre>
* <p>
* Note that after calling this method, only {@code close()} method may invoked for
* {@code PDDocument} instance and only AFTER {@link ExternalSigningSupport} instance is used.
* </p>
*
* @param output stream to write the final PDF. It should <i><b>not</b></i> point to the source
* file. It will be closed when the document is closed.
* @return instance to be used for external signing and setting CMS signature
* @throws IOException if the output could not be written
* @throws IllegalStateException if the document was not loaded from a file or a stream or
* signature options were not set.
*/
public ExternalSigningSupport saveIncrementalForExternalSigning(OutputStream output) throws IOException
{
if (pdfSource == null)
{
throw new IllegalStateException("document was not loaded from a file or a stream");
}
// PDFBOX-3978: getLastSignatureDictionary() not helpful if signing into a template
// that is not the last signature. So give higher priority to signature with update flag.
PDSignature foundSignature = null;
for (PDSignature sig : getSignatureDictionaries())
{
foundSignature = sig;
if (sig.getCOSObject().isNeedToBeUpdated())
{
break;
}
}
if (foundSignature == null)
{
throw new IllegalStateException("document does not contain signature fields");
}
int[] byteRange = foundSignature.getByteRange();
if (!Arrays.equals(byteRange, RESERVE_BYTE_RANGE))
{
throw new IllegalStateException("signature reserve byte range has been changed "
+ "after addSignature(), please set the byte range that existed after addSignature()");
}
COSWriter writer = new COSWriter(output, pdfSource);
writer.write(this);
signingSupport = new SigningSupport(writer);
return signingSupport;
}
/**
* Returns the page at the given 0-based index.
* <p>
* This method is too slow to get all the pages from a large PDF document
* (1000 pages or more). For such documents, use the iterator of
* {@link PDDocument#getPages()} instead.
*
* @param pageIndex the 0-based page index
* @return the page at the given index.
*/
public PDPage getPage(int pageIndex) // todo: REPLACE most calls to this method with BELOW method
{
return getDocumentCatalog().getPages().get(pageIndex);
}
/**
* Returns the page tree.
*
* @return the page tree
*/
public PDPageTree getPages()
{
return getDocumentCatalog().getPages();
}
/**
* This will return the total page count of the PDF document.
*
* @return The total number of pages in the PDF document.
*/
public int getNumberOfPages()
{
return getDocumentCatalog().getPages().getCount();
}
/**
* This will close the underlying COSDocument object.
*
* @throws IOException If there is an error releasing resources.
*/
@Override
public void close() throws IOException
{
if (!document.isClosed())
{
// Make sure that:
// - first Exception is kept
// - all IO resources are closed
// - there's a way to see which errors occured
IOException firstException = null;
// close resources and COSWriter
if (signingSupport != null)
{
firstException = IOUtils.closeAndLogException(signingSupport, LOG, "SigningSupport", firstException);
}
// close all intermediate I/O streams
firstException = IOUtils.closeAndLogException(document, LOG, "COSDocument", firstException);
// close the source PDF stream, if we read from one
if (pdfSource != null)
{
firstException = IOUtils.closeAndLogException(pdfSource, LOG, "RandomAccessRead pdfSource", firstException);
}
// close fonts
for (TrueTypeFont ttf : fontsToClose)
{
firstException = IOUtils.closeAndLogException(ttf, LOG, "TrueTypeFont", firstException);
}
// rethrow first exception to keep method contract
if (firstException != null)
{
throw firstException;
}
}
}
/**
* Protects the document with a protection policy. The document content will be really
* encrypted when it will be saved. This method only marks the document for encryption. It also
* calls {@link #setAllSecurityToBeRemoved(boolean)} with a false argument if it was set to true
* previously and logs a warning.
*
* @see org.apache.pdfbox.pdmodel.encryption.StandardProtectionPolicy
* @see org.apache.pdfbox.pdmodel.encryption.PublicKeyProtectionPolicy
*
* @param policy The protection policy.
* @throws IOException if there isn't any suitable security handler.
*/
public void protect(ProtectionPolicy policy) throws IOException
{
if (isAllSecurityToBeRemoved())
{
LOG.warn("do not call setAllSecurityToBeRemoved(true) before calling protect(), "
+ "as protect() implies setAllSecurityToBeRemoved(false)");
setAllSecurityToBeRemoved(false);
}
if (!isEncrypted())
{
encryption = new PDEncryption();
}
SecurityHandler securityHandler = SecurityHandlerFactory.INSTANCE.newSecurityHandlerForPolicy(policy);
if (securityHandler == null)
{
throw new IOException("No security handler for policy " + policy);
}
getEncryption().setSecurityHandler(securityHandler);
}
/**
* Returns the access permissions granted when the document was decrypted. If the document was not decrypted this
* method returns the access permission for a document owner (ie can do everything). The returned object is in read
* only mode so that permissions cannot be changed. Methods providing access to content should rely on this object
* to verify if the current user is allowed to proceed.
*
* @return the access permissions for the current user on the document.
*/
public AccessPermission getCurrentAccessPermission()
{
if (accessPermission == null)
{
accessPermission = AccessPermission.getOwnerAccessPermission();
}
return accessPermission;
}
/**
* Indicates if all security is removed or not when writing the pdf.
*
* @return returns true if all security shall be removed otherwise false
*/
public boolean isAllSecurityToBeRemoved()
{
return allSecurityToBeRemoved;
}
/**
* Activates/Deactivates the removal of all security when writing the pdf.
*
* @param removeAllSecurity remove all security if set to true
*/
public void setAllSecurityToBeRemoved(boolean removeAllSecurity)
{
allSecurityToBeRemoved = removeAllSecurity;
}
/**
* Provides the document ID.
*
* @return the dcoument ID
*/
public Long getDocumentId()
{
return documentId;
}
/**
* Sets the document ID to the given value.
*
* @param docId the new document ID
*/
public void setDocumentId(Long docId)
{
documentId = docId;
}
/**
* Returns the PDF specification version this document conforms to.
*
* @return the PDF version (e.g. 1.4f)
*/
public float getVersion()
{
float headerVersionFloat = getDocument().getVersion();
// there may be a second version information in the document catalog starting with 1.4
if (headerVersionFloat >= 1.4f)
{
String catalogVersion = getDocumentCatalog().getVersion();
float catalogVersionFloat = -1;
if (catalogVersion != null)
{
try
{
catalogVersionFloat = Float.parseFloat(catalogVersion);
}
catch(NumberFormatException exception)
{
LOG.error("Can't extract the version number of the document catalog.", exception);
}
}
// the most recent version is the correct one
return Math.max(catalogVersionFloat, headerVersionFloat);
}
else
{
return headerVersionFloat;
}
}
/**
* Sets the PDF specification version for this document.
*
* @param newVersion the new PDF version (e.g. 1.4f)
*
*/
public void setVersion(float newVersion)
{
float currentVersion = getVersion();
// nothing to do?
if (Float.compare(newVersion,currentVersion) == 0)
{
return;
}
// the version can't be downgraded
if (newVersion < currentVersion)
{
LOG.error("It's not allowed to downgrade the version of a pdf.");
return;
}
// update the catalog version if the document version is >= 1.4
if (getDocument().getVersion() >= 1.4f)
{
getDocumentCatalog().setVersion(Float.toString(newVersion));
}
else
{
// versions < 1.4f have a version header only
getDocument().setVersion(newVersion);
}
}
/**
* Returns the resource cache associated with this document, or null if there is none.
*/
public ResourceCache getResourceCache()
{
return resourceCache;
}
/**
* Sets the resource cache associated with this document.
*
* @param resourceCache A resource cache, or null.
*/
public void setResourceCache(ResourceCache resourceCache)
{
this.resourceCache = resourceCache;
}
}
| PDFBOX-3017: make comment even scarier, as suggested by mkl in SO 52942313 comment
git-svn-id: c3ad59981690829a43dc34c293c4e2cd04bcd994@1844680 13f79535-47bb-0310-9956-ffa450edef68
| pdfbox/src/main/java/org/apache/pdfbox/pdmodel/PDDocument.java | PDFBOX-3017: make comment even scarier, as suggested by mkl in SO 52942313 comment | <ide><path>dfbox/src/main/java/org/apache/pdfbox/pdmodel/PDDocument.java
<ide> * Save the PDF as an incremental update. This is only possible if the PDF was loaded from a
<ide> * file or a stream, not if the document was created in PDFBox itself.
<ide> *
<del> * @param output stream to write to. It will be closed when done. It should <i><b>not</b></i>
<del> * point to the source file.
<add> * @param output stream to write to. It will be closed when done. It
<add> * <i><b>must never</b></i> point to the source file or that one will be
<add> * harmed!
<ide> * @throws IOException if the output could not be written
<ide> * @throws IllegalStateException if the document was not loaded from a file or a stream.
<ide> */
<ide> * {@code PDDocument} instance and only AFTER {@link ExternalSigningSupport} instance is used.
<ide> * </p>
<ide> *
<del> * @param output stream to write the final PDF. It should <i><b>not</b></i> point to the source
<del> * file. It will be closed when the document is closed.
<add> * @param output stream to write the final PDF. It will be closed when the
<add> * document is closed. It <i><b>must never</b></i> point to the source file
<add> * or that one will be harmed!
<ide> * @return instance to be used for external signing and setting CMS signature
<ide> * @throws IOException if the output could not be written
<ide> * @throws IllegalStateException if the document was not loaded from a file or a stream or |
|
Java | apache-2.0 | 7b64aefd9b0ecfc181f5b57e98bede3b10dc9779 | 0 | CloudifySource/cloudify-widget,CloudifySource/cloudify-widget,CloudifySource/cloudify-widget,CloudifySource/cloudify-widget | /*******************************************************************************
* Copyright (c) 2011 GigaSpaces Technologies 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 utils;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.apache.commons.exec.DefaultExecuteResultHandler;
import org.apache.commons.io.FileUtils;
import org.jclouds.ContextBuilder;
import org.jclouds.compute.ComputeServiceContext;
import org.jclouds.openstack.nova.v2_0.NovaApi;
import org.jclouds.openstack.nova.v2_0.NovaAsyncApi;
import org.jclouds.openstack.nova.v2_0.domain.Ingress;
import org.jclouds.openstack.nova.v2_0.domain.IpProtocol;
import org.jclouds.openstack.nova.v2_0.domain.KeyPair;
import org.jclouds.openstack.nova.v2_0.domain.SecurityGroup;
import org.jclouds.openstack.nova.v2_0.extensions.KeyPairApi;
import org.jclouds.openstack.nova.v2_0.extensions.SecurityGroupApi;
import org.jclouds.rest.RestContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import server.ApplicationContext;
import server.exceptions.ServerException;
import beans.config.ServerConfig.CloudBootstrapConfiguration;
import com.google.common.collect.FluentIterable;
/**
* This class provides different static cloudify utilities methods.
* @author adaml
*
*/
public class CloudifyUtils {
/**
* Creates a cloud folder containing all necessary credentials
* for bootstrapping to the HP cloud.
*
* @return
* A path to the newly created cloud folder.
* @throws IOException
*
*/
public static File createCloudFolder(String project, String key, String secretKey, ComputeServiceContext context) throws IOException {
CloudBootstrapConfiguration cloudConf = ApplicationContext.get().conf().server.cloudBootstrap;
String cloudifyBuildFolder = ApplicationContext.get().conf().server.environment.cloudifyHome;
File cloudifyEscFolder = new File(cloudifyBuildFolder, cloudConf.cloudifyEscDirRelativePath);
//copy the content of hp configuration files to a new folder
File destFolder = new File(cloudifyEscFolder, cloudConf.cloudName + getTempSuffix());
FileUtils.copyDirectory(new File(cloudifyEscFolder, cloudConf.cloudName), destFolder);
// create new pem file using new credentials.
File pemFolder = new File(destFolder, cloudConf.cloudifyHpUploadDirName);
File newPemFile = createPemFile( context );
FileUtils.copyFile(newPemFile, new File(pemFolder, newPemFile.getName() +".pem"), true);
List<String> cloudProperties = new ArrayList<String>();
cloudProperties.add("tenant=" + '"' + project + '"');
cloudProperties.add("user=" + '"' + key + '"');
cloudProperties.add("apiKey=" + '"' + secretKey + '"');
cloudProperties.add("keyFile=" + '"' + newPemFile.getName() +".pem" + '"');
cloudProperties.add("keyPair=" + '"' + newPemFile.getName() + '"');
cloudProperties.add("securityGroup=" + '"' + cloudConf.securityGroup + '"');
cloudProperties.add("hardwareId=" + '"' + cloudConf.hardwareId() + '"');
cloudProperties.add("linuxImageId=" + '"' + cloudConf.linuxImageId() + '"');
cloudProperties.add( "persistencePath=null" );
//create new props file and init with custom credentials.
File newPropertiesFile = new File(destFolder, cloudConf.cloudPropertiesFileName + ".new" );
newPropertiesFile.createNewFile();
FileUtils.writeLines(newPropertiesFile, cloudProperties);
//delete old props file
File propertiesFile = new File(destFolder, cloudConf.cloudPropertiesFileName );
if (propertiesFile.exists()) {
propertiesFile.delete();
}
//rename new props file.
if (!newPropertiesFile.renameTo(propertiesFile)){
throw new ServerException("Failed creating custom cloud folder." +
" Failed renaming custom cloud properties file.");
}
return destFolder;
}
/**
* returns the private key used for starting the remote machines.
*
* @param cloudFolder
* The folder used to bootstrap to the cloud.
* @param cloudBootstrapConfig
* The cloud configuration used to bootstrap to the cloud.
* @return
* The private key used for starting the remote machines
* @throws IOException
*/
public static String getCloudPrivateKey(File cloudFolder) throws IOException {
File pemFile = getPemFile(cloudFolder);
if (pemFile == null) {
return null;
}
return FileUtils.readFileToString(pemFile);
}
private static Logger logger = LoggerFactory.getLogger(CloudifyUtils.class);
// creates a new pem file for a given hp cloud account.
private static File createPemFile( ComputeServiceContext context ){
CloudBootstrapConfiguration cloudConf = ApplicationContext.get().conf().server.cloudBootstrap;
try {
RestContext<NovaApi, NovaAsyncApi> novaClient = context.unwrap();
NovaApi api = novaClient.getApi();
KeyPairApi keyPairApi = api.getKeyPairExtensionForZone( cloudConf.zoneName ).get();
KeyPair keyPair = keyPairApi.create( cloudConf.keyPairName + getTempSuffix());
File pemFile = new File(System.getProperty("java.io.tmpdir"), keyPair.getName());
pemFile.createNewFile();
FileUtils.writeStringToFile(pemFile, keyPair.getPrivateKey());
return pemFile;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
*
* Create a security group with all ports open.
*
* @param context The jClouds context.
*/
public static void createCloudifySecurityGroup( ComputeServiceContext context ) {
CloudBootstrapConfiguration cloudConf = ApplicationContext.get().conf().server.cloudBootstrap;
try {
RestContext<NovaApi, NovaAsyncApi> novaClient = context.unwrap();
NovaApi novaApi = novaClient.getApi();
SecurityGroupApi securityGroupClient = novaApi.getSecurityGroupExtensionForZone(cloudConf.zoneName).get();
//Check if group already exists.
FluentIterable<? extends SecurityGroup> groupsList = securityGroupClient.list();
for (Object group : groupsList) {
if (((SecurityGroup)group).getName().equals(cloudConf.securityGroup)) {
return;
}
}
//Create a new security group with open port range of 80-65535.
Ingress ingress = Ingress.builder().ipProtocol(IpProtocol.TCP).fromPort(1).toPort(65535).build();
SecurityGroup securityGroup = securityGroupClient.createWithDescription(cloudConf.securityGroup, "All ports open.");
securityGroupClient.createRuleAllowingCidrBlock(securityGroup.getId(), ingress, "0.0.0.0/0");
}
catch (Exception e) {
throw new RuntimeException("Failed creating security group.", e);
}
}
/**
* Create an HP cloud context.
* @param project HP cloud username.
* @param key HP cloud API key.
* @return the HP lClouds compute context.
*
* TODO : unify this with {@link beans.ServerBootstrapperImpl.NovaContext}
*
*/
public static ComputeServiceContext createJcloudsContext(String project, String key, String secretKey ) {
CloudBootstrapConfiguration cloudConf = ApplicationContext.get().conf().server.cloudBootstrap;
ComputeServiceContext context;
Properties overrides = new Properties();
overrides.put("jclouds.keystone.credential-type", "apiAccessKeyCredentials");
context = ContextBuilder.newBuilder( cloudConf.cloudProvider )
.credentials( project + ":" + key, secretKey )
.overrides(overrides)
.buildView(ComputeServiceContext.class);
return context;
}
private static String getTempSuffix() {
String currTime = Long.toString(System.currentTimeMillis());
return currTime.substring(currTime.length() - 4);
}
private static File getPemFile(File cloudFolder) {
final CloudBootstrapConfiguration cloudConf = ApplicationContext.get().conf().server.cloudBootstrap;
File uploadDir = new File(cloudFolder, cloudConf.cloudifyHpUploadDirName);
File[] filesList = uploadDir.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.startsWith(cloudConf.keyPairName)
&& name.endsWith( "pem" );
}
});
if ( filesList.length == 0 || filesList.length > 1) {
return null;
}
return filesList[0];
}
}
| app/utils/CloudifyUtils.java | /*******************************************************************************
* Copyright (c) 2011 GigaSpaces Technologies 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 utils;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.apache.commons.exec.DefaultExecuteResultHandler;
import org.apache.commons.io.FileUtils;
import org.jclouds.ContextBuilder;
import org.jclouds.compute.ComputeServiceContext;
import org.jclouds.openstack.nova.v2_0.NovaApi;
import org.jclouds.openstack.nova.v2_0.NovaAsyncApi;
import org.jclouds.openstack.nova.v2_0.domain.Ingress;
import org.jclouds.openstack.nova.v2_0.domain.IpProtocol;
import org.jclouds.openstack.nova.v2_0.domain.KeyPair;
import org.jclouds.openstack.nova.v2_0.domain.SecurityGroup;
import org.jclouds.openstack.nova.v2_0.extensions.KeyPairApi;
import org.jclouds.openstack.nova.v2_0.extensions.SecurityGroupApi;
import org.jclouds.rest.RestContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import server.ApplicationContext;
import server.exceptions.ServerException;
import beans.config.ServerConfig.CloudBootstrapConfiguration;
import com.google.common.collect.FluentIterable;
/**
* This class provides different static cloudify utilities methods.
* @author adaml
*
*/
public class CloudifyUtils {
/**
* Creates a cloud folder containing all necessary credentials
* for bootstrapping to the HP cloud.
*
* @return
* A path to the newly created cloud folder.
* @throws IOException
*
*/
public static File createCloudFolder(String project, String key, String secretKey, ComputeServiceContext context) throws IOException {
CloudBootstrapConfiguration cloudConf = ApplicationContext.get().conf().server.cloudBootstrap;
String cloudifyBuildFolder = ApplicationContext.get().conf().server.environment.cloudifyHome;
File cloudifyEscFolder = new File(cloudifyBuildFolder, cloudConf.cloudifyEscDirRelativePath);
//copy the content of hp configuration files to a new folder
File destFolder = new File(cloudifyEscFolder, cloudConf.cloudName + getTempSuffix());
FileUtils.copyDirectory(new File(cloudifyEscFolder, cloudConf.cloudName), destFolder);
// create new pem file using new credentials.
File pemFolder = new File(destFolder, cloudConf.cloudifyHpUploadDirName);
File newPemFile = createPemFile( context );
FileUtils.copyFile(newPemFile, new File(pemFolder, newPemFile.getName() +".pem"), true);
List<String> cloudProperties = new ArrayList<String>();
cloudProperties.add("tenant=" + '"' + project + '"');
cloudProperties.add("user=" + '"' + key + '"');
cloudProperties.add("apiKey=" + '"' + secretKey + '"');
cloudProperties.add("keyFile=" + '"' + newPemFile.getName() +".pem" + '"');
cloudProperties.add("keyPair=" + '"' + newPemFile.getName() + '"');
cloudProperties.add("securityGroup=" + '"' + cloudConf.securityGroup + '"');
cloudProperties.add("hardwareId=" + '"' + cloudConf.hardwareId + '"');
cloudProperties.add("linuxImageId=" + '"' + cloudConf.linuxImageId + '"');
cloudProperties.add( "persistencePath=null" );
//create new props file and init with custom credentials.
File newPropertiesFile = new File(destFolder, cloudConf.cloudPropertiesFileName + ".new" );
newPropertiesFile.createNewFile();
FileUtils.writeLines(newPropertiesFile, cloudProperties);
//delete old props file
File propertiesFile = new File(destFolder, cloudConf.cloudPropertiesFileName );
if (propertiesFile.exists()) {
propertiesFile.delete();
}
//rename new props file.
if (!newPropertiesFile.renameTo(propertiesFile)){
throw new ServerException("Failed creating custom cloud folder." +
" Failed renaming custom cloud properties file.");
}
return destFolder;
}
/**
* returns the private key used for starting the remote machines.
*
* @param cloudFolder
* The folder used to bootstrap to the cloud.
* @param cloudBootstrapConfig
* The cloud configuration used to bootstrap to the cloud.
* @return
* The private key used for starting the remote machines
* @throws IOException
*/
public static String getCloudPrivateKey(File cloudFolder) throws IOException {
File pemFile = getPemFile(cloudFolder);
if (pemFile == null) {
return null;
}
return FileUtils.readFileToString(pemFile);
}
private static Logger logger = LoggerFactory.getLogger(CloudifyUtils.class);
// creates a new pem file for a given hp cloud account.
private static File createPemFile( ComputeServiceContext context ){
CloudBootstrapConfiguration cloudConf = ApplicationContext.get().conf().server.cloudBootstrap;
try {
RestContext<NovaApi, NovaAsyncApi> novaClient = context.unwrap();
NovaApi api = novaClient.getApi();
KeyPairApi keyPairApi = api.getKeyPairExtensionForZone( cloudConf.zoneName ).get();
KeyPair keyPair = keyPairApi.create( cloudConf.keyPairName + getTempSuffix());
File pemFile = new File(System.getProperty("java.io.tmpdir"), keyPair.getName());
pemFile.createNewFile();
FileUtils.writeStringToFile(pemFile, keyPair.getPrivateKey());
return pemFile;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
*
* Create a security group with all ports open.
*
* @param context The jClouds context.
*/
public static void createCloudifySecurityGroup( ComputeServiceContext context ) {
CloudBootstrapConfiguration cloudConf = ApplicationContext.get().conf().server.cloudBootstrap;
try {
RestContext<NovaApi, NovaAsyncApi> novaClient = context.unwrap();
NovaApi novaApi = novaClient.getApi();
SecurityGroupApi securityGroupClient = novaApi.getSecurityGroupExtensionForZone(cloudConf.zoneName).get();
//Check if group already exists.
FluentIterable<? extends SecurityGroup> groupsList = securityGroupClient.list();
for (Object group : groupsList) {
if (((SecurityGroup)group).getName().equals(cloudConf.securityGroup)) {
return;
}
}
//Create a new security group with open port range of 80-65535.
Ingress ingress = Ingress.builder().ipProtocol(IpProtocol.TCP).fromPort(1).toPort(65535).build();
SecurityGroup securityGroup = securityGroupClient.createWithDescription(cloudConf.securityGroup, "All ports open.");
securityGroupClient.createRuleAllowingCidrBlock(securityGroup.getId(), ingress, "0.0.0.0/0");
}
catch (Exception e) {
throw new RuntimeException("Failed creating security group.", e);
}
}
/**
* Create an HP cloud context.
* @param project HP cloud username.
* @param key HP cloud API key.
* @return the HP lClouds compute context.
*
* TODO : unify this with {@link beans.ServerBootstrapperImpl.NovaContext}
*
*/
public static ComputeServiceContext createJcloudsContext(String project, String key, String secretKey ) {
CloudBootstrapConfiguration cloudConf = ApplicationContext.get().conf().server.cloudBootstrap;
ComputeServiceContext context;
Properties overrides = new Properties();
overrides.put("jclouds.keystone.credential-type", "apiAccessKeyCredentials");
context = ContextBuilder.newBuilder( cloudConf.cloudProvider )
.credentials( project + ":" + key, secretKey )
.overrides(overrides)
.buildView(ComputeServiceContext.class);
return context;
}
private static String getTempSuffix() {
String currTime = Long.toString(System.currentTimeMillis());
return currTime.substring(currTime.length() - 4);
}
private static File getPemFile(File cloudFolder) {
final CloudBootstrapConfiguration cloudConf = ApplicationContext.get().conf().server.cloudBootstrap;
File uploadDir = new File(cloudFolder, cloudConf.cloudifyHpUploadDirName);
File[] filesList = uploadDir.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.startsWith(cloudConf.keyPairName)
&& name.endsWith( "pem" );
}
});
if ( filesList.length == 0 || filesList.length > 1) {
return null;
}
return filesList[0];
}
}
| cloud bootstrap config bean not concatenating zone with other params
| app/utils/CloudifyUtils.java | cloud bootstrap config bean not concatenating zone with other params | <ide><path>pp/utils/CloudifyUtils.java
<ide> cloudProperties.add("keyFile=" + '"' + newPemFile.getName() +".pem" + '"');
<ide> cloudProperties.add("keyPair=" + '"' + newPemFile.getName() + '"');
<ide> cloudProperties.add("securityGroup=" + '"' + cloudConf.securityGroup + '"');
<del> cloudProperties.add("hardwareId=" + '"' + cloudConf.hardwareId + '"');
<del> cloudProperties.add("linuxImageId=" + '"' + cloudConf.linuxImageId + '"');
<add> cloudProperties.add("hardwareId=" + '"' + cloudConf.hardwareId() + '"');
<add> cloudProperties.add("linuxImageId=" + '"' + cloudConf.linuxImageId() + '"');
<ide> cloudProperties.add( "persistencePath=null" );
<ide>
<ide> //create new props file and init with custom credentials. |
|
Java | apache-2.0 | d3159347937bcad6032b8c4a8edc538484334da2 | 0 | neo4j/neo4j-ogm,neo4j/neo4j-ogm,neo4j/neo4j-ogm,neo4j/neo4j-ogm | /*
* Copyright (c) 2002-2021 "Neo4j,"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* 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.neo4j.ogm.metadata;
import static java.util.stream.Collectors.*;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.regex.Matcher;
import java.util.stream.Collectors;
import org.neo4j.ogm.annotation.*;
import org.neo4j.ogm.annotation.Relationship.Direction;
import org.neo4j.ogm.autoindex.AutoIndexManager;
import org.neo4j.ogm.driver.TypeSystem;
import org.neo4j.ogm.exception.core.InvalidPropertyFieldException;
import org.neo4j.ogm.exception.core.MappingException;
import org.neo4j.ogm.exception.core.MetadataException;
import org.neo4j.ogm.id.IdStrategy;
import org.neo4j.ogm.id.InternalIdStrategy;
import org.neo4j.ogm.id.UuidStrategy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Maintains object to graph mapping details at the class (type) level
* The ClassInfo object is used to maintain mappings from Java Types->Neo4j Labels
* thereby allowing the correct labels to be applied to new nodes when they
* are persisted.
* The ClassInfo object also maintains a map of FieldInfo and MethodInfo objects
* that maintain the appropriate information for mapping Java class attributes to Neo4j
* node properties / paths (node)-[:relationship]->(node), via field or method
* accessors respectively.
* Given a type hierarchy, the ClassInfo object guarantees that for any type in that
* hierarchy, the labels associated with that type will include the labels for
* all its superclass and interface types as well. This is to avoid the need to iterate
* through the ClassInfo hierarchy to recover label information.
*
* @author Vince Bickers
* @author Luanne Misquitta
* @author Mark Angrish
* @author Michael J. Simons
* @author Torsten Kuhnhenne
* @author Nicolas Labrot
*/
public class ClassInfo {
private static final Logger LOGGER = LoggerFactory.getLogger(ClassInfo.class);
private final List<ClassInfo> directSubclasses = new ArrayList<>();
private volatile Set<ClassInfo> allSubclasses;
private final List<ClassInfo> directInterfaces = new ArrayList<>();
private final List<ClassInfo> directImplementingClasses = new ArrayList<>();
/**
* Indirect super classes will only be filled for Kotlin classes that make use of Kotlin's
* <a href="https://kotlinlang.org/docs/reference/delegation.html">"Implementation by Delegation"</a>. Find a
* more in depth of the inner workings
* <a href="https://medium.com/til-kotlin/how-kotlins-class-delegation-works-and-di-101-de9887b95d3e">here</a>
* (and feel free to replace the above medium link with a real spec doc).
*/
private final List<ClassInfo> indirectSuperClasses = new ArrayList<>();
private final String className;
private final boolean isInterface;
private final boolean isAbstract;
private final boolean isEnum;
private ClassInfo directSuperclass;
private String directSuperclassName;
private String neo4jName;
private final FieldsInfo fieldsInfo;
private final MethodsInfo methodsInfo;
private final AnnotationsInfo annotationsInfo;
private final InterfacesInfo interfacesInfo;
private final Class<?> cls;
private final Map<Class, List<FieldInfo>> iterableFieldsForType = new HashMap<>();
private final Map<FieldInfo, Field> fieldInfoFields = new ConcurrentHashMap<>();
private volatile Map<String, FieldInfo> propertyFields;
private volatile Map<String, FieldInfo> indexFields;
private volatile Collection<FieldInfo> requiredFields;
private volatile Collection<CompositeIndex> compositeIndexes;
private volatile Optional<FieldInfo> identityField;
private volatile Optional<FieldInfo> versionField;
private volatile Optional<FieldInfo> primaryIndexField;
private volatile FieldInfo labelField = null;
private volatile boolean labelFieldMapped = false;
private volatile Optional<MethodInfo> postLoadMethod;
private volatile Collection<String> staticLabels;
private volatile Set<FieldInfo> relationshipFields;
private volatile Optional<FieldInfo> endNodeReader;
private volatile Optional<FieldInfo> startNodeReader;
private Class<? extends IdStrategy> idStrategyClass;
private IdStrategy idStrategy;
public ClassInfo(Class<?> cls, TypeSystem typeSystem) {
this(cls, null, typeSystem);
}
/**
* @param cls The type of this class
* @param parent Will be filled if containing class is a Kotlin class and this class is the type of a Kotlin delegate.
* @param typeSystem The typesystem in use
*/
private ClassInfo(Class<?> cls, Field parent, TypeSystem typeSystem) {
this.cls = cls;
final int modifiers = cls.getModifiers();
this.isInterface = Modifier.isInterface(modifiers);
this.isAbstract = Modifier.isAbstract(modifiers);
this.isEnum = org.neo4j.ogm.support.ClassUtils.isEnum(cls);
this.className = cls.getName();
if (cls.getSuperclass() != null) {
this.directSuperclassName = cls.getSuperclass().getName();
}
this.interfacesInfo = new InterfacesInfo(cls);
this.fieldsInfo = new FieldsInfo(this, cls, parent, typeSystem);
this.methodsInfo = new MethodsInfo(cls, parent);
this.annotationsInfo = new AnnotationsInfo(cls);
if (isRelationshipEntity() && labelFieldOrNull() != null) {
throw new MappingException(
String.format("'%s' is a relationship entity. The @Labels annotation can't be applied to " +
"relationship entities.", name()));
}
for (FieldInfo fieldInfo : fieldsInfo().fields()) {
if (fieldInfo.hasAnnotation(Property.class) && fieldInfo.hasCompositeConverter()) {
throw new MappingException(
String.format("'%s' has both @Convert and @Property annotations applied to the field '%s'",
name(), fieldInfo.getName()));
}
}
if (KotlinDetector.isKotlinType(cls)) {
this.inspectLocalDelegates(typeSystem);
}
}
private void inspectLocalDelegates(TypeSystem typeSystem) {
for (Field field : this.cls.getDeclaredFields()) {
if (!isKotlinDelegate(field)) {
continue;
}
ClassInfo indirectSuperClass = new ClassInfo(field.getType(), field, typeSystem);
this.extend(indirectSuperClass);
this.indirectSuperClasses.add(indirectSuperClass);
}
}
private static boolean isKotlinDelegate(Field field) {
return field.isSynthetic() && field.getName().startsWith("$$delegate_");
}
void extend(ClassInfo classInfo) {
this.interfacesInfo.append(classInfo.interfacesInfo());
this.fieldsInfo.append(classInfo.fieldsInfo());
this.methodsInfo.append(classInfo.methodsInfo());
}
/**
* Connect this class to a subclass.
*
* @param subclass the subclass
*/
void addSubclass(ClassInfo subclass) {
if (subclass.directSuperclass != null && subclass.directSuperclass != this) {
throw new RuntimeException(
subclass.className + " has two superclasses: " + subclass.directSuperclass.className + ", "
+ this.className);
}
subclass.directSuperclass = this;
this.directSubclasses.add(subclass);
}
public String name() {
return className;
}
String simpleName() {
return deriveSimpleName(this.cls);
}
public static String deriveSimpleName(Class<?> clazz) {
String className = clazz.getName();
return className.substring(className.lastIndexOf('.') + 1);
}
public ClassInfo directSuperclass() {
return directSuperclass;
}
/**
* <p>
* Retrieves the static labels that are applied to nodes in the database. If the class' instances are persisted by
* a relationship instead of a node then this method returns an empty collection.
* </p>
* <p>
* Note that this method returns only the static labels. A node entity instance may declare additional labels
* managed at runtime by using the @Labels annotation on a collection field, therefore the full set of labels to be
* mapped to a node will be the static labels, in addition to any labels declared by the backing field of an
* {@link Labels} annotation.
* </p>
*
* @return A {@link Collection} of all the static labels that apply to the node or an empty list if there aren't
* any, never <code>null</code>
*/
public Collection<String> staticLabels() {
Collection<String> knownStaticLabels = this.staticLabels;
if (knownStaticLabels == null) {
synchronized (this) {
knownStaticLabels = this.staticLabels;
if (knownStaticLabels == null) {
this.staticLabels = Collections.unmodifiableCollection(collectLabels());
knownStaticLabels = this.staticLabels;
}
}
}
return knownStaticLabels;
}
public String neo4jName() {
if (neo4jName == null) {
AnnotationInfo annotationInfo = annotationsInfo.get(NodeEntity.class);
if (annotationInfo != null) {
neo4jName = annotationInfo.get(NodeEntity.LABEL, simpleName());
return neo4jName;
}
annotationInfo = annotationsInfo.get(RelationshipEntity.class);
if (annotationInfo != null) {
neo4jName = annotationInfo.get(RelationshipEntity.TYPE, simpleName().toUpperCase());
return neo4jName;
}
if (!isAbstract) {
neo4jName = simpleName();
}
}
return neo4jName;
}
private Collection<String> collectLabels() {
List<String> labels = new ArrayList<>();
if (!isAbstract || annotationsInfo.get(NodeEntity.class) != null) {
labels.add(neo4jName());
}
if (directSuperclass != null && !"java.lang.Object".equals(directSuperclass.className)) {
labels.addAll(directSuperclass.collectLabels());
}
for (ClassInfo interfaceInfo : directInterfaces()) {
labels.addAll(interfaceInfo.collectLabels());
}
for (ClassInfo indirectSuperClass : indirectSuperClasses) {
labels.addAll(indirectSuperClass.collectLabels());
}
return labels;
}
public List<ClassInfo> directSubclasses() {
return directSubclasses;
}
/**
* @return A list of all implementing and extending subclasses.
* @since 3.1.20
*/
public Collection<ClassInfo> allSubclasses() {
Set<ClassInfo> computedSubclasses = this.allSubclasses;
if (computedSubclasses == null) {
synchronized (this) {
computedSubclasses = this.allSubclasses;
if (computedSubclasses == null) {
this.allSubclasses = computeSubclasses();
computedSubclasses = this.allSubclasses;
}
}
}
return computedSubclasses;
}
private Set<ClassInfo> computeSubclasses() {
Set<ClassInfo> computedSubclasses = new HashSet<>();
for (ClassInfo classInfo : this.directSubclasses()) {
computedSubclasses.add(classInfo);
computedSubclasses.addAll(classInfo.allSubclasses());
}
for (ClassInfo classInfo : this.directImplementingClasses()) {
computedSubclasses.add(classInfo);
computedSubclasses.addAll(classInfo.allSubclasses());
}
return Collections.unmodifiableSet(computedSubclasses);
}
List<ClassInfo> directImplementingClasses() {
return directImplementingClasses;
}
List<ClassInfo> directInterfaces() {
return directInterfaces;
}
InterfacesInfo interfacesInfo() {
return interfacesInfo;
}
public Collection<AnnotationInfo> annotations() {
return annotationsInfo.list();
}
public boolean isInterface() {
return isInterface;
}
public boolean isEnum() {
return isEnum;
}
public AnnotationsInfo annotationsInfo() {
return annotationsInfo;
}
String superclassName() {
return directSuperclassName;
}
public FieldsInfo fieldsInfo() {
return fieldsInfo;
}
MethodsInfo methodsInfo() {
return methodsInfo;
}
public FieldInfo identityFieldOrNull() {
return getOrComputeIdentityField().orElse(null);
}
/**
* The identity field is a field annotated with @NodeId, or if none exists, a field
* of type Long called 'id'
*
* @return A {@link FieldInfo} object representing the identity field never <code>null</code>
* @throws MappingException if no identity field can be found
*/
public FieldInfo identityField() {
return getOrComputeIdentityField()
.orElseThrow(() -> new MetadataException("No internal identity field found for class: " + this.className));
}
private Optional<FieldInfo> getOrComputeIdentityField() {
Optional<FieldInfo> result = this.identityField;
if (result == null) {
synchronized (this) {
result = this.identityField;
if (result == null) {
// Didn't want to add yet another method related to determining the identy field
// so the actual resolving of the field inside the Double-checked locking here
// has been inlined.
Collection<FieldInfo> identityFields = getFieldInfos(FieldInfo::isInternalIdentity);
if (identityFields.size() == 1) {
this.identityField = Optional.of(identityFields.iterator().next());
} else if (identityFields.size() > 1) {
throw new MetadataException("Expected exactly one internal identity field (@Id with " +
"InternalIdStrategy), found " + identityFields.size() + " " + identityFields);
} else {
this.identityField = fieldsInfo.fields().stream()
.filter(f -> "id".equals(f.getName()))
.filter(f -> "java.lang.Long".equals(f.getTypeDescriptor()))
.findFirst();
}
result = this.identityField;
}
}
}
return result;
}
public boolean hasIdentityField() {
return getOrComputeIdentityField().isPresent();
}
Collection<FieldInfo> getFieldInfos(Predicate<FieldInfo> predicate) {
return fieldsInfo().fields().stream()
.filter(predicate)
.collect(Collectors.toSet());
}
/**
* The label field is an optional field annotated with @Labels.
*
* @return A {@link FieldInfo} object representing the label field. Optionally <code>null</code>
*/
public FieldInfo labelFieldOrNull() {
if (labelFieldMapped) {
return labelField;
}
if (!labelFieldMapped) {
for (FieldInfo fieldInfo : fieldsInfo().fields()) {
if (fieldInfo.isLabelField()) {
if (!fieldInfo.isIterable()) {
throw new MappingException(String.format(
"Field '%s' in class '%s' includes the @Labels annotation, however this field is not a " +
"type of collection.", fieldInfo.getName(), this.name()));
}
labelFieldMapped = true;
labelField = fieldInfo;
return labelField;
}
}
labelFieldMapped = true;
}
return null;
}
public boolean isRelationshipEntity() {
for (AnnotationInfo info : annotations()) {
if (info.getName().equals(RelationshipEntity.class.getName())) {
return true;
}
}
return false;
}
/**
* A property field is any field annotated with @Property, or any field that can be mapped to a
* node property. The identity field is not a property field.
*
* @return A Collection of FieldInfo objects describing the classInfo's property fields
* @throws InvalidPropertyFieldException if the recognized property fields contain a field that is not
* actually persistable as property.
*/
public Collection<FieldInfo> propertyFields() {
return getOrComputePropertyFields().values();
}
/**
* Finds the property field with a specific property name from the ClassInfo's property fields
* Note that this method does not allow for property names with differing case. //TODO
*
* @param propertyName the propertyName of the field to find
* @return A FieldInfo object describing the required property field, or null if it doesn't exist.
* @throws InvalidPropertyFieldException if the recognized property fields contain a field that is not
* actually persistable as property.
*/
public FieldInfo propertyField(String propertyName) {
return propertyName == null ? null : getOrComputePropertyFields().get(propertyName);
}
private Map<String, FieldInfo> getOrComputePropertyFields() {
Map<String, FieldInfo> result = this.propertyFields;
if (result == null) {
synchronized (this) {
result = this.propertyFields;
if (result == null) {
Collection<FieldInfo> fields = fieldsInfo().fields();
FieldInfo optionalIdentityField = identityFieldOrNull();
Map<String, FieldInfo> intermediateFieldMap = new HashMap<>(fields.size());
for (FieldInfo fieldInfo : fields) {
if (fieldInfo == optionalIdentityField || fieldInfo.isLabelField() || fieldInfo.hasAnnotation(StartNode.class) || fieldInfo.hasAnnotation(EndNode.class)) {
continue;
}
if (!fieldInfo.getAnnotations().has(Property.class)) {
// If a field is not marked explicitly as a property but is persistable as such, add it.
if (fieldInfo.persistableAsProperty()) {
intermediateFieldMap.put(fieldInfo.property(), fieldInfo);
}
} else if (fieldInfo.persistableAsProperty()) {
// If it is marked as a property, then it should be persistable as such
intermediateFieldMap.put(fieldInfo.property(), fieldInfo);
} else {
// Otherwise, throw a fitting exception
throw new InvalidPropertyFieldException(fieldInfo);
}
}
this.propertyFields = Collections.unmodifiableMap(intermediateFieldMap);
result = this.propertyFields;
}
}
}
return result;
}
/**
* Finds the property field with a specific field name from the ClassInfo's property fields
*
* @param propertyName the propertyName of the field to find
* @return A FieldInfo object describing the required property field, or null if it doesn't exist.
*/
public FieldInfo propertyFieldByName(String propertyName) {
for (FieldInfo fieldInfo : propertyFields()) {
if (fieldInfo.getName().equalsIgnoreCase(propertyName)) {
return fieldInfo;
}
}
return null;
}
/**
* A relationship field is any field annotated with @Relationship, or any field that cannot be mapped to a
* node property. The identity field is not a relationship field.
*
* @return A Collection of FieldInfo objects describing the classInfo's relationship fields
*/
public Collection<FieldInfo> relationshipFields() {
Collection<FieldInfo> result = this.relationshipFields;
if (result == null) {
synchronized (this) {
result = this.relationshipFields;
if (result == null) {
FieldInfo optionalIdentityField = identityFieldOrNull();
Set<FieldInfo> identifiedRelationshipFields = new HashSet<>();
for (FieldInfo fieldInfo : fieldsInfo().fields()) {
if (fieldInfo == optionalIdentityField) {
continue;
}
if (fieldInfo.getAnnotations().has(Relationship.class)) {
identifiedRelationshipFields.add(fieldInfo);
} else if (!fieldInfo.persistableAsProperty()) {
identifiedRelationshipFields.add(fieldInfo);
}
}
this.relationshipFields = Collections.unmodifiableSet(identifiedRelationshipFields);
result = this.relationshipFields;
}
}
}
return result;
}
/**
* Finds the relationship field with a specific name from the ClassInfo's relationship fields
*
* @param relationshipName the relationshipName of the field to find
* @return A FieldInfo object describing the required relationship field, or null if it doesn't exist.
*/
public FieldInfo relationshipField(String relationshipName) {
for (FieldInfo fieldInfo : relationshipFields()) {
if (fieldInfo.relationship().equalsIgnoreCase(relationshipName)) {
return fieldInfo;
}
}
return null;
}
/**
* Finds the relationship field with a specific name and direction from the ClassInfo's relationship fields
*
* @param relationshipName the relationshipName of the field to find
* @param relationshipDirection the direction of the relationship represented by a string
* @param strict if true, does not infer relationship type but looks for it in the @Relationship annotation. Null if missing. If false, infers relationship type from FieldInfo
* @return A FieldInfo object describing the required relationship field, or null if it doesn't exist.
*/
public FieldInfo relationshipField(String relationshipName, Direction relationshipDirection, boolean strict) {
for (FieldInfo fieldInfo : relationshipFields()) {
String relationship = strict ? fieldInfo.relationshipTypeAnnotation() : fieldInfo.relationship();
if (relationshipName.equalsIgnoreCase(relationship)) {
Direction declaredDirection = fieldInfo.relationshipDirectionOrDefault(Direction.OUTGOING);
if (isActualDirectionCompatibleWithDeclaredDirection(relationshipDirection, declaredDirection)) {
return fieldInfo;
}
}
}
return null;
}
/**
* Finds all relationship fields with a specific name and direction from the ClassInfo's relationship fields
*
* @param relationshipName the relationshipName of the field to find
* @param relationshipDirection the direction of the relationship
* @param strict if true, does not infer relationship type but looks for it in the @Relationship annotation. Null if missing. If false, infers relationship type from FieldInfo
* @return Set of FieldInfo objects describing the required relationship field, or empty set if it doesn't exist.
*/
public Set<FieldInfo> candidateRelationshipFields(String relationshipName, Direction relationshipDirection, boolean strict) {
Set<FieldInfo> candidateFields = new HashSet<>();
for (FieldInfo fieldInfo : relationshipFields()) {
String relationship = strict ? fieldInfo.relationshipTypeAnnotation() : fieldInfo.relationship();
if (relationshipName.equalsIgnoreCase(relationship)) {
Direction declaredDirection = fieldInfo.relationshipDirectionOrDefault(Direction.OUTGOING);
if (isActualDirectionCompatibleWithDeclaredDirection(relationshipDirection, declaredDirection)) {
candidateFields.add(fieldInfo);
}
}
}
return candidateFields;
}
/**
* Finds the relationship field with a specific property name from the ClassInfo's relationship fields
*
* @param fieldName the name of the field
* @return A FieldInfo object describing the required relationship field, or null if it doesn't exist.
*/
public FieldInfo relationshipFieldByName(String fieldName) {
for (FieldInfo fieldInfo : relationshipFields()) {
if (fieldInfo.getName().equalsIgnoreCase(fieldName)) {
return fieldInfo;
}
}
return null;
}
public Field getField(FieldInfo fieldInfo) {
Field field = fieldInfoFields.get(fieldInfo);
if (field != null) {
return field;
}
try {
field = cls.getDeclaredField(fieldInfo.getName());
fieldInfoFields.put(fieldInfo, field);
return field;
} catch (NoSuchFieldException e) {
if (directSuperclass() != null) {
field = directSuperclass().getField(fieldInfo);
fieldInfoFields.put(fieldInfo, field);
return field;
} else {
throw new RuntimeException(
"Field " + fieldInfo.getName() + " not found in class " + name() + " or any of its superclasses");
}
}
}
/**
* Find all FieldInfos for the specified ClassInfo whose type matches the supplied fieldType
*
* @param fieldType The field type to look for
* @return A {@link List} of {@link FieldInfo} objects that are of the given type, never <code>null</code>
*/
public List<FieldInfo> findFields(Class<?> fieldType) {
String fieldSignature = fieldType.getName();
Predicate<FieldInfo> matchesType = f -> f.getTypeDescriptor().equals(fieldSignature);
return fieldsInfo().fields().stream().filter(matchesType).collect(toList());
}
/**
* Find all FieldInfos for the specified ClassInfo which have the specified annotation
*
* @param annotation The annotation
* @return A {@link List} of {@link FieldInfo} objects that are of the given type, never <code>null</code>
*/
public List<FieldInfo> findFields(String annotation) {
Predicate<FieldInfo> hasAnnotation = f -> f.hasAnnotation(annotation);
return fieldsInfo().fields().stream().filter(hasAnnotation).collect(toList());
}
/**
* Retrieves a {@link List} of {@link FieldInfo} representing all of the fields that can be iterated over
* using a "foreach" loop.
*
* @return {@link List} of {@link FieldInfo}
*/
public List<FieldInfo> findIterableFields() {
Predicate<FieldInfo> isIterable = f -> {
// The actual call to getField might throw an exception.
// While FieldInfo#type() should also return the type,
// ClassInfo#getField has side-effects which I cannot judge
// atm, so better keep it here
// and wrap the predicate in an exception below.
Class type = getField(f).getType();
return type.isArray() || Iterable.class.isAssignableFrom(type);
};
// See comment inside predicate regarding this exception.
try {
return fieldsInfo().fields().stream()
.filter(isIterable).collect(toList());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* Finds all fields whose type is equivalent to Array<X> or assignable from Iterable<X>
* where X is the generic parameter type of the Array or Iterable
*
* @param iteratedType the type of iterable
* @return {@link List} of {@link MethodInfo}, never <code>null</code>
*/
public List<FieldInfo> findIterableFields(Class iteratedType) {
if (iterableFieldsForType.containsKey(iteratedType)) {
return iterableFieldsForType.get(iteratedType);
}
String typeSignature = iteratedType.getName();
String arrayOfTypeSignature = typeSignature + "[]";
Predicate<FieldInfo> isIterableOfType = f -> {
String fieldType = f.getTypeDescriptor();
boolean isMatchingArray =
f.isArray() && (fieldType.equals(arrayOfTypeSignature) || f.isParameterisedTypeOf(iteratedType));
boolean isMatchingIterable =
f.isIterable() && (fieldType.equals(typeSignature) || f.isParameterisedTypeOf(iteratedType));
return isMatchingArray || isMatchingIterable;
};
return fieldsInfo().fields().stream()
.filter(isIterableOfType).collect(toList());
}
/**
* Finds all fields whose type is equivalent to Array<X> or assignable from Iterable<X>
* where X is the generic parameter type of the Array or Iterable and the relationship type backing this iterable is "relationshipType"
*
* @param iteratedType the type of iterable
* @param relationshipType the relationship type
* @param relationshipDirection the relationship direction
* @param strict if true, does not infer relationship type but looks for it in the @Relationship annotation. Null if missing. If false, infers relationship type from FieldInfo
* @return {@link List} of {@link MethodInfo}, never <code>null</code>
*/
public List<FieldInfo> findIterableFields(Class<?> iteratedType, String relationshipType, Direction relationshipDirection, boolean strict) {
List<FieldInfo> iterableFields = new ArrayList<>();
for (FieldInfo fieldInfo : findIterableFields(iteratedType)) {
String relationship = strict ? fieldInfo.relationshipTypeAnnotation() : fieldInfo.relationship();
if (relationshipType.equals(relationship)) {
Direction declaredDirection = fieldInfo.relationshipDirectionOrDefault(Direction.OUTGOING);
if (isActualDirectionCompatibleWithDeclaredDirection(relationshipDirection, declaredDirection)) {
iterableFields.add(fieldInfo);
}
}
}
return iterableFields;
}
private static boolean isActualDirectionCompatibleWithDeclaredDirection(Direction actual, Direction declared) {
return ((declared == Direction.INCOMING || declared == Direction.UNDIRECTED) && actual == Direction.INCOMING) ||
(declared != Direction.INCOMING && actual == Direction.OUTGOING);
}
public boolean isTransient() {
return annotationsInfo.get(Transient.class) != null;
}
public boolean isAbstract() {
return isAbstract;
}
/**
* Returns true if this classInfo is in the subclass hierarchy of b, or if this classInfo is the same as b, false otherwise
*
* @param classInfo the classInfo at the toplevel of a type hierarchy to search through
* @return true if this classInfo is in the subclass hierarchy of classInfo, false otherwise
*/
boolean isSubclassOf(ClassInfo classInfo) {
if (classInfo == null) {
return false;
}
if (this == classInfo) {
return true;
}
for (ClassInfo subclass : classInfo.directSubclasses()) {
if (isSubclassOf(subclass)) {
return true;
}
}
return this.indirectSuperClasses.stream()
.anyMatch(c -> c.getUnderlyingClass() == classInfo.getUnderlyingClass());
}
/**
* Get the underlying class represented by this ClassInfo
*
* @return the underlying class or null if it cannot be determined
*/
public Class<?> getUnderlyingClass() {
return cls;
}
/**
* Gets the class of the type parameter description of the entity related to this.
* The match is done based on the following-
* 2. Look for a field explicitly annotated with @Relationship for a type and implied direction
* 4. Look for a field with name derived from the relationship type for the given direction
*
* @param relationshipType the relationship type
* @param relationshipDirection the relationship direction
* @return class of the type parameter descriptor or null if it could not be determined
*/
Class<?> getTypeParameterDescriptorForRelationship(String relationshipType, Direction relationshipDirection) {
final boolean STRICT_MODE = true; //strict mode for matching methods and fields, will only look for explicit annotations
final boolean INFERRED_MODE = false; //inferred mode for matching methods and fields, will infer the relationship type from the getter/setter/property
try {
FieldInfo fieldInfo = relationshipField(relationshipType, relationshipDirection, STRICT_MODE);
if (fieldInfo != null && fieldInfo.getTypeDescriptor() != null) {
return DescriptorMappings.getType(fieldInfo.getTypeDescriptor());
}
if (relationshipDirection != Direction.INCOMING) { //we always expect an annotation for INCOMING
fieldInfo = relationshipField(relationshipType, relationshipDirection, INFERRED_MODE);
if (fieldInfo != null && fieldInfo.getTypeDescriptor() != null) {
return DescriptorMappings.getType(fieldInfo.getTypeDescriptor());
}
}
} catch (RuntimeException e) {
LOGGER.debug("Could not get {} class type for relationshipType {} and relationshipDirection {} ", className,
relationshipType, relationshipDirection);
}
return null;
}
/**
* @return If this class contains any fields/properties annotated with @Index.
*/
public boolean containsIndexes() {
return !(getIndexFields().isEmpty() && getCompositeIndexes().isEmpty());
}
/**
* @return The <code>FieldInfo</code>s representing the Indexed fields in this class.
*/
public Collection<FieldInfo> getIndexFields() {
Map<String, FieldInfo> result = this.indexFields;
if (result == null) {
synchronized (this) {
result = this.indexFields;
if (result == null) {
Map<String, FieldInfo> indexes = new HashMap<>();
Field[] declaredFields = cls.getDeclaredFields();
for (FieldInfo fieldInfo : fieldsInfo().fields()) {
if (isDeclaredField(declaredFields, fieldInfo.getName()) &&
(fieldInfo.hasAnnotation(Index.class) || fieldInfo.hasAnnotation(Id.class))) {
String propertyValue = fieldInfo.property();
if (fieldInfo.hasAnnotation(Property.class.getName())) {
propertyValue = fieldInfo.property();
}
indexes.put(propertyValue, fieldInfo);
}
}
this.indexFields = Collections.unmodifiableMap(indexes);
result = this.indexFields;
}
}
}
return result.values();
}
private static boolean isDeclaredField(Field[] declaredFields, String name) {
for (Field field : declaredFields) {
if (field.getName().equals(name)) {
return true;
}
}
return false;
}
public Collection<CompositeIndex> getCompositeIndexes() {
Collection<CompositeIndex> result = this.compositeIndexes;
if (result == null) {
synchronized (this) {
result = this.compositeIndexes;
if (result == null) {
CompositeIndex[] annotations = cls.getDeclaredAnnotationsByType(CompositeIndex.class);
List<CompositeIndex> intermediateResult = new ArrayList<>(annotations.length);
for (CompositeIndex annotation : annotations) {
String[] properties =
annotation.value().length > 0 ? annotation.value() : annotation.properties();
if (properties.length < 1) {
throw new MetadataException("Incorrect CompositeIndex definition on " + className +
". Provide at least 1 property");
}
for (String property : properties) {
// Determine the original field in case the user uses a MapCompositeConverter.
Matcher m = AutoIndexManager.COMPOSITE_KEY_MAP_COMPOSITE_PATTERN.matcher(property);
if (m.matches()) {
property = m.group(1);
}
FieldInfo fieldInfo = propertyField(property);
if (fieldInfo == null) {
throw new MetadataException(
"Incorrect CompositeIndex definition on " + className + ". Property " +
property + " does not exists.");
}
}
intermediateResult.add(annotation);
}
this.compositeIndexes = Collections.unmodifiableList(intermediateResult);
result = this.compositeIndexes;
}
}
}
return result;
}
public FieldInfo primaryIndexField() {
return getOrComputePrimaryIndexField().orElse(null);
}
private Optional<FieldInfo> getOrComputePrimaryIndexField() {
Optional<FieldInfo> result = this.primaryIndexField;
if (result == null) {
synchronized (this) {
result = this.primaryIndexField;
if (result == null) {
Optional<FieldInfo> potentialPrimaryIndexField = Optional.empty();
Collection<FieldInfo> primaryIndexFields = getFieldInfos(this::isPrimaryIndexField);
if (primaryIndexFields.size() > 1) {
throw new MetadataException(
"Only one @Id / @Index(primary=true, unique=true) annotation is allowed in a class hierarchy. Please check annotations in the class "
+ name() + " or its parents");
} else if (!primaryIndexFields.isEmpty()) {
FieldInfo selectedField = primaryIndexFields.iterator().next();
AnnotationInfo generatedValueAnnotation = selectedField.getAnnotations().get(GeneratedValue.class);
if (generatedValueAnnotation != null) {
// Here's a funny hidden side effect I wasn't able to refactor out with a clear idea during
// rethinking the whole collection of synchronized blocks :(
GeneratedValue value = (GeneratedValue) generatedValueAnnotation.getAnnotation();
idStrategyClass = value.strategy();
try {
idStrategy = idStrategyClass.getDeclaredConstructor().newInstance();
} catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
LOGGER.debug("Could not instantiate {}. Expecting this to be registered manually.", idStrategyClass);
}
}
potentialPrimaryIndexField = Optional.of(selectedField);
}
result = validateIdGenerationConfigFor(potentialPrimaryIndexField);
}
}
}
return result;
}
private Optional<FieldInfo> validateIdGenerationConfigFor(Optional<FieldInfo> potentialPrimaryIndexField) {
fieldsInfo().fields().forEach(info -> {
if (info.hasAnnotation(GeneratedValue.class) && !info.hasAnnotation(Id.class)) {
throw new MetadataException(
"The type of @Generated field in class " + className + " must be also annotated with @Id.");
}
});
if (UuidStrategy.class.equals(idStrategyClass)) {
potentialPrimaryIndexField.ifPresent(selectedField -> {
if (!(selectedField.isTypeOf(UUID.class) || selectedField.isTypeOf(String.class))) {
throw new MetadataException(
"The type of " + selectedField.getName() + " in class " + className
+ " must be of type java.lang.UUID or java.lang.String because it has an UUID generation strategy.");
}
});
}
return potentialPrimaryIndexField;
}
public boolean hasPrimaryIndexField() {
return getOrComputePrimaryIndexField().isPresent();
}
private boolean isPrimaryIndexField(FieldInfo fieldInfo) {
boolean hasIdAnnotation = fieldInfo.hasAnnotation(Id.class);
boolean hasStrategyOtherThanInternal = !fieldInfo.hasAnnotation(GeneratedValue.class)
|| !((GeneratedValue) fieldInfo.getAnnotations().get(GeneratedValue.class).getAnnotation()).strategy()
.equals(InternalIdStrategy.class);
return hasIdAnnotation && hasStrategyOtherThanInternal;
}
public IdStrategy idStrategy() {
// Forces initialization of the id strategy
return getOrComputePrimaryIndexField()
.map(ignored -> idStrategy).orElse(null);
}
public Class<? extends IdStrategy> idStrategyClass() {
return idStrategyClass;
}
public void registerIdGenerationStrategy(IdStrategy strategy) {
if (strategy.getClass().equals(idStrategyClass)) {
idStrategy = strategy;
} else {
throw new IllegalArgumentException("Strategy " + strategy +
" is not an instance of " + idStrategyClass);
}
}
public MethodInfo postLoadMethodOrNull() {
Optional<MethodInfo> result = this.postLoadMethod;
if (result == null) {
synchronized (this) {
result = this.postLoadMethod;
if (result == null) {
Collection<MethodInfo> possiblePostLoadMethods = methodsInfo
.findMethodInfoBy(methodInfo -> methodInfo.hasAnnotation(PostLoad.class));
if (possiblePostLoadMethods.size() > 1) {
throw new MetadataException(String
.format("Cannot have more than one post load method annotated with @PostLoad for class '%s'",
this.className));
}
this.postLoadMethod = possiblePostLoadMethods.stream().findFirst();
result = this.postLoadMethod;
}
}
}
return result.orElse(null);
}
public FieldInfo getFieldInfo(String propertyName) {
// fall back to the field if method cannot be found
FieldInfo optionalLabelField = labelFieldOrNull();
if (optionalLabelField != null && optionalLabelField.getName().equals(propertyName)) {
return optionalLabelField;
}
FieldInfo propertyField = propertyField(propertyName);
if (propertyField != null) {
return propertyField;
}
return fieldsInfo.get(propertyName);
}
/**
* Return a FieldInfo for the EndNode of a RelationshipEntity
*
* @return a FieldInfo for the field annotated as the EndNode, or none if not found
*/
public FieldInfo getEndNodeReader() {
Optional<FieldInfo> result = this.endNodeReader;
if (result == null) {
synchronized (this) {
result = this.endNodeReader;
if (result == null) {
if (isRelationshipEntity()) {
endNodeReader = fieldsInfo().fields().stream()
.filter(fieldInfo -> fieldInfo.getAnnotations().get(EndNode.class) != null)
.findFirst();
if (!endNodeReader.isPresent()) {
LOGGER.warn("Failed to find an @EndNode on {}", name());
}
} else {
endNodeReader = Optional.empty();
}
result = this.endNodeReader;
}
}
}
return result.orElse(null);
}
/**
* Return a FieldInfo for the StartNode of a RelationshipEntity
*
* @return a FieldInfo for the field annotated as the StartNode, or none if not found
*/
public FieldInfo getStartNodeReader() {
Optional<FieldInfo> result = this.startNodeReader;
if (result == null) {
synchronized (this) {
result = this.startNodeReader;
if (result == null) {
if (isRelationshipEntity()) {
startNodeReader = fieldsInfo().fields().stream()
.filter(fieldInfo -> fieldInfo.getAnnotations().get(StartNode.class) != null)
.findFirst();
if (!startNodeReader.isPresent()) {
LOGGER.warn("Failed to find an @StartNode on {}", name());
}
} else {
startNodeReader = Optional.empty();
}
result = this.startNodeReader;
}
}
}
return result.orElse(null);
}
/**
* Returns if the class as fields annotated with @Required annotation
*/
public boolean hasRequiredFields() {
return !requiredFields().isEmpty();
}
public Collection<FieldInfo> requiredFields() {
if (requiredFields == null) {
requiredFields = new ArrayList<>();
for (FieldInfo fieldInfo : propertyFields()) {
if (fieldInfo.getAnnotations().has(Required.class)) {
requiredFields.add(fieldInfo);
}
}
}
return requiredFields;
}
public boolean hasVersionField() {
return getOrComputeVersionField().isPresent();
}
public FieldInfo getVersionField() {
return getOrComputeVersionField().orElse(null);
}
private Optional<FieldInfo> getOrComputeVersionField() {
Optional<FieldInfo> result = this.versionField;
if (result == null) {
synchronized (this) {
result = this.versionField;
if (result == null) {
Collection<FieldInfo> fields = getFieldInfos(FieldInfo::isVersionField);
if (fields.size() > 1) {
throw new MetadataException("Only one version field is allowed, found " + fields);
}
Iterator<FieldInfo> iterator = fields.iterator();
if (iterator.hasNext()) {
this.versionField = Optional.of(iterator.next());
} else {
// cache that there is no version field
this.versionField = Optional.empty();
}
result = this.versionField;
}
}
}
return result;
}
/**
* Reads the value of the entity's primary index field if any.
*
* @param entity
* @return
*/
public Object readPrimaryIndexValueOf(Object entity) {
Objects.requireNonNull(entity, "Entity to read from must not be null.");
Object value = null;
if (this.hasPrimaryIndexField()) {
// One has to use #read here to get the ID as defined in the entity.
// #readProperty gives back the converted value the database sees.
// This breaks immediate in LoadOneDelegate#lookup(Class, Object).
// That is called by LoadOneDelegate#load(Class, Serializable, int)
// immediately after loading (and finding(!!) an entity, which is never
// returned directly but goes through a cache.
// However, LoadOneDelegate#load(Class, Serializable, int) deals with the
// ID as defined in the domain and so we have to use that in the same way here.
value = this.primaryIndexField().read(entity);
}
return value;
}
public Function<Object, Optional<Object>> getPrimaryIndexOrIdReader() {
Function<Object, Optional<Object>> reader;
if (this.hasPrimaryIndexField()) {
reader = t -> Optional.ofNullable(this.readPrimaryIndexValueOf(t));
} else {
reader = t -> Optional.ofNullable(this.identityField().read(t));
}
return reader;
}
static Object getInstanceOrDelegate(Object instance, Field delegateHolder) {
if (delegateHolder == null) {
return instance;
} else {
return AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
try {
delegateHolder.setAccessible(true);
return delegateHolder.get(instance);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
});
}
}
@Override
public String toString() {
return "ClassInfo{" +
"className='" + className + '\'' +
", neo4jName='" + neo4jName + '\'' +
'}';
}
}
| core/src/main/java/org/neo4j/ogm/metadata/ClassInfo.java | /*
* Copyright (c) 2002-2021 "Neo4j,"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* 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.neo4j.ogm.metadata;
import static java.util.stream.Collectors.*;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.regex.Matcher;
import java.util.stream.Collectors;
import org.neo4j.ogm.annotation.*;
import org.neo4j.ogm.annotation.Relationship.Direction;
import org.neo4j.ogm.autoindex.AutoIndexManager;
import org.neo4j.ogm.driver.TypeSystem;
import org.neo4j.ogm.exception.core.InvalidPropertyFieldException;
import org.neo4j.ogm.exception.core.MappingException;
import org.neo4j.ogm.exception.core.MetadataException;
import org.neo4j.ogm.id.IdStrategy;
import org.neo4j.ogm.id.InternalIdStrategy;
import org.neo4j.ogm.id.UuidStrategy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Maintains object to graph mapping details at the class (type) level
* The ClassInfo object is used to maintain mappings from Java Types->Neo4j Labels
* thereby allowing the correct labels to be applied to new nodes when they
* are persisted.
* The ClassInfo object also maintains a map of FieldInfo and MethodInfo objects
* that maintain the appropriate information for mapping Java class attributes to Neo4j
* node properties / paths (node)-[:relationship]->(node), via field or method
* accessors respectively.
* Given a type hierarchy, the ClassInfo object guarantees that for any type in that
* hierarchy, the labels associated with that type will include the labels for
* all its superclass and interface types as well. This is to avoid the need to iterate
* through the ClassInfo hierarchy to recover label information.
*
* @author Vince Bickers
* @author Luanne Misquitta
* @author Mark Angrish
* @author Michael J. Simons
* @author Torsten Kuhnhenne
* @author Nicolas Labrot
*/
public class ClassInfo {
private static final Logger LOGGER = LoggerFactory.getLogger(ClassInfo.class);
private final List<ClassInfo> directSubclasses = new ArrayList<>();
private volatile Set<ClassInfo> allSubclasses;
private final List<ClassInfo> directInterfaces = new ArrayList<>();
private final List<ClassInfo> directImplementingClasses = new ArrayList<>();
/**
* Indirect super classes will only be filled for Kotlin classes that make use of Kotlin's
* <a href="https://kotlinlang.org/docs/reference/delegation.html">"Implementation by Delegation"</a>. Find a
* more in depth of the inner workings
* <a href="https://medium.com/til-kotlin/how-kotlins-class-delegation-works-and-di-101-de9887b95d3e">here</a>
* (and feel free to replace the above medium link with a real spec doc).
*/
private final List<ClassInfo> indirectSuperClasses = new ArrayList<>();
private final String className;
private final boolean isInterface;
private final boolean isAbstract;
private final boolean isEnum;
private ClassInfo directSuperclass;
private String directSuperclassName;
private String neo4jName;
private final FieldsInfo fieldsInfo;
private final MethodsInfo methodsInfo;
private final AnnotationsInfo annotationsInfo;
private final InterfacesInfo interfacesInfo;
private final Class<?> cls;
private final Map<Class, List<FieldInfo>> iterableFieldsForType = new HashMap<>();
private final Map<FieldInfo, Field> fieldInfoFields = new ConcurrentHashMap<>();
private volatile Map<String, FieldInfo> propertyFields;
private volatile Map<String, FieldInfo> indexFields;
private volatile Collection<FieldInfo> requiredFields;
private volatile Collection<CompositeIndex> compositeIndexes;
private volatile Optional<FieldInfo> identityField;
private volatile Optional<FieldInfo> versionField;
private volatile Optional<FieldInfo> primaryIndexField;
private volatile FieldInfo labelField = null;
private volatile boolean labelFieldMapped = false;
private volatile Optional<MethodInfo> postLoadMethod;
private volatile Collection<String> staticLabels;
private volatile Set<FieldInfo> relationshipFields;
private volatile Optional<FieldInfo> endNodeReader;
private volatile Optional<FieldInfo> startNodeReader;
private Class<? extends IdStrategy> idStrategyClass;
private IdStrategy idStrategy;
public ClassInfo(Class<?> cls, TypeSystem typeSystem) {
this(cls, null, typeSystem);
}
/**
* @param cls The type of this class
* @param parent Will be filled if containing class is a Kotlin class and this class is the type of a Kotlin delegate.
* @param typeSystem The typesystem in use
*/
private ClassInfo(Class<?> cls, Field parent, TypeSystem typeSystem) {
this.cls = cls;
final int modifiers = cls.getModifiers();
this.isInterface = Modifier.isInterface(modifiers);
this.isAbstract = Modifier.isAbstract(modifiers);
this.isEnum = org.neo4j.ogm.support.ClassUtils.isEnum(cls);
this.className = cls.getName();
if (cls.getSuperclass() != null) {
this.directSuperclassName = cls.getSuperclass().getName();
}
this.interfacesInfo = new InterfacesInfo(cls);
this.fieldsInfo = new FieldsInfo(this, cls, parent, typeSystem);
this.methodsInfo = new MethodsInfo(cls, parent);
this.annotationsInfo = new AnnotationsInfo(cls);
if (isRelationshipEntity() && labelFieldOrNull() != null) {
throw new MappingException(
String.format("'%s' is a relationship entity. The @Labels annotation can't be applied to " +
"relationship entities.", name()));
}
for (FieldInfo fieldInfo : fieldsInfo().fields()) {
if (fieldInfo.hasAnnotation(Property.class) && fieldInfo.hasCompositeConverter()) {
throw new MappingException(
String.format("'%s' has both @Convert and @Property annotations applied to the field '%s'",
name(), fieldInfo.getName()));
}
}
if (KotlinDetector.isKotlinType(cls)) {
this.inspectLocalDelegates(typeSystem);
}
}
private void inspectLocalDelegates(TypeSystem typeSystem) {
for (Field field : this.cls.getDeclaredFields()) {
if (!isKotlinDelegate(field)) {
continue;
}
ClassInfo indirectSuperClass = new ClassInfo(field.getType(), field, typeSystem);
this.extend(indirectSuperClass);
this.indirectSuperClasses.add(indirectSuperClass);
}
}
private static boolean isKotlinDelegate(Field field) {
return field.isSynthetic() && field.getName().startsWith("$$delegate_");
}
void extend(ClassInfo classInfo) {
this.interfacesInfo.append(classInfo.interfacesInfo());
this.fieldsInfo.append(classInfo.fieldsInfo());
this.methodsInfo.append(classInfo.methodsInfo());
}
/**
* Connect this class to a subclass.
*
* @param subclass the subclass
*/
void addSubclass(ClassInfo subclass) {
if (subclass.directSuperclass != null && subclass.directSuperclass != this) {
throw new RuntimeException(
subclass.className + " has two superclasses: " + subclass.directSuperclass.className + ", "
+ this.className);
}
subclass.directSuperclass = this;
this.directSubclasses.add(subclass);
}
public String name() {
return className;
}
String simpleName() {
return deriveSimpleName(this.cls);
}
public static String deriveSimpleName(Class<?> clazz) {
String className = clazz.getName();
return className.substring(className.lastIndexOf('.') + 1);
}
public ClassInfo directSuperclass() {
return directSuperclass;
}
/**
* <p>
* Retrieves the static labels that are applied to nodes in the database. If the class' instances are persisted by
* a relationship instead of a node then this method returns an empty collection.
* </p>
* <p>
* Note that this method returns only the static labels. A node entity instance may declare additional labels
* managed at runtime by using the @Labels annotation on a collection field, therefore the full set of labels to be
* mapped to a node will be the static labels, in addition to any labels declared by the backing field of an
* {@link Labels} annotation.
* </p>
*
* @return A {@link Collection} of all the static labels that apply to the node or an empty list if there aren't
* any, never <code>null</code>
*/
public Collection<String> staticLabels() {
Collection<String> knownStaticLabels = this.staticLabels;
if (knownStaticLabels == null) {
synchronized (this) {
knownStaticLabels = this.staticLabels;
if (knownStaticLabels == null) {
this.staticLabels = Collections.unmodifiableCollection(collectLabels());
knownStaticLabels = this.staticLabels;
}
}
}
return knownStaticLabels;
}
public String neo4jName() {
if (neo4jName == null) {
AnnotationInfo annotationInfo = annotationsInfo.get(NodeEntity.class);
if (annotationInfo != null) {
neo4jName = annotationInfo.get(NodeEntity.LABEL, simpleName());
return neo4jName;
}
annotationInfo = annotationsInfo.get(RelationshipEntity.class);
if (annotationInfo != null) {
neo4jName = annotationInfo.get(RelationshipEntity.TYPE, simpleName().toUpperCase());
return neo4jName;
}
if (!isAbstract) {
neo4jName = simpleName();
}
}
return neo4jName;
}
private Collection<String> collectLabels() {
List<String> labels = new ArrayList<>();
if (!isAbstract || annotationsInfo.get(NodeEntity.class) != null) {
labels.add(neo4jName());
}
if (directSuperclass != null && !"java.lang.Object".equals(directSuperclass.className)) {
labels.addAll(directSuperclass.collectLabels());
}
for (ClassInfo interfaceInfo : directInterfaces()) {
labels.addAll(interfaceInfo.collectLabels());
}
for (ClassInfo indirectSuperClass : indirectSuperClasses) {
labels.addAll(indirectSuperClass.collectLabels());
}
return labels;
}
public List<ClassInfo> directSubclasses() {
return directSubclasses;
}
/**
* @return A list of all implementing and extending subclasses.
* @since 3.1.20
*/
public Collection<ClassInfo> allSubclasses() {
Set<ClassInfo> computedSubclasses = this.allSubclasses;
if (computedSubclasses == null) {
synchronized (this) {
computedSubclasses = this.allSubclasses;
if (computedSubclasses == null) {
this.allSubclasses = computeSubclasses();
computedSubclasses = this.allSubclasses;
}
}
}
return computedSubclasses;
}
private Set<ClassInfo> computeSubclasses() {
Set<ClassInfo> computedSubclasses = new HashSet<>();
for (ClassInfo classInfo : this.directSubclasses()) {
computedSubclasses.add(classInfo);
computedSubclasses.addAll(classInfo.allSubclasses());
}
for (ClassInfo classInfo : this.directImplementingClasses()) {
computedSubclasses.add(classInfo);
computedSubclasses.addAll(classInfo.allSubclasses());
}
return Collections.unmodifiableSet(computedSubclasses);
}
List<ClassInfo> directImplementingClasses() {
return directImplementingClasses;
}
List<ClassInfo> directInterfaces() {
return directInterfaces;
}
InterfacesInfo interfacesInfo() {
return interfacesInfo;
}
public Collection<AnnotationInfo> annotations() {
return annotationsInfo.list();
}
public boolean isInterface() {
return isInterface;
}
public boolean isEnum() {
return isEnum;
}
public AnnotationsInfo annotationsInfo() {
return annotationsInfo;
}
String superclassName() {
return directSuperclassName;
}
public FieldsInfo fieldsInfo() {
return fieldsInfo;
}
MethodsInfo methodsInfo() {
return methodsInfo;
}
public FieldInfo identityFieldOrNull() {
return getOrComputeIdentityField().orElse(null);
}
/**
* The identity field is a field annotated with @NodeId, or if none exists, a field
* of type Long called 'id'
*
* @return A {@link FieldInfo} object representing the identity field never <code>null</code>
* @throws MappingException if no identity field can be found
*/
public FieldInfo identityField() {
return getOrComputeIdentityField()
.orElseThrow(() -> new MetadataException("No internal identity field found for class: " + this.className));
}
private Optional<FieldInfo> getOrComputeIdentityField() {
Optional<FieldInfo> result = this.identityField;
if (result == null) {
synchronized (this) {
result = this.identityField;
if (result == null) {
// Didn't want to add yet another method related to determining the identy field
// so the actual resolving of the field inside the Double-checked locking here
// has been inlined.
Collection<FieldInfo> identityFields = getFieldInfos(FieldInfo::isInternalIdentity);
if (identityFields.size() == 1) {
this.identityField = Optional.of(identityFields.iterator().next());
} else if (identityFields.size() > 1) {
throw new MetadataException("Expected exactly one internal identity field (@Id with " +
"InternalIdStrategy), found " + identityFields.size() + " " + identityFields);
} else {
this.identityField = fieldsInfo.fields().stream()
.filter(f -> "id".equals(f.getName()))
.filter(f -> "java.lang.Long".equals(f.getTypeDescriptor()))
.findFirst();
}
result = this.identityField;
}
}
}
return result;
}
public boolean hasIdentityField() {
return getOrComputeIdentityField().isPresent();
}
Collection<FieldInfo> getFieldInfos(Predicate<FieldInfo> predicate) {
return fieldsInfo().fields().stream()
.filter(predicate)
.collect(Collectors.toSet());
}
/**
* The label field is an optional field annotated with @Labels.
*
* @return A {@link FieldInfo} object representing the label field. Optionally <code>null</code>
*/
public FieldInfo labelFieldOrNull() {
if (labelFieldMapped) {
return labelField;
}
if (!labelFieldMapped) {
for (FieldInfo fieldInfo : fieldsInfo().fields()) {
if (fieldInfo.isLabelField()) {
if (!fieldInfo.isIterable()) {
throw new MappingException(String.format(
"Field '%s' in class '%s' includes the @Labels annotation, however this field is not a " +
"type of collection.", fieldInfo.getName(), this.name()));
}
labelFieldMapped = true;
labelField = fieldInfo;
return labelField;
}
}
labelFieldMapped = true;
}
return null;
}
public boolean isRelationshipEntity() {
for (AnnotationInfo info : annotations()) {
if (info.getName().equals(RelationshipEntity.class.getName())) {
return true;
}
}
return false;
}
/**
* A property field is any field annotated with @Property, or any field that can be mapped to a
* node property. The identity field is not a property field.
*
* @return A Collection of FieldInfo objects describing the classInfo's property fields
* @throws InvalidPropertyFieldException if the recognized property fields contain a field that is not
* actually persistable as property.
*/
public Collection<FieldInfo> propertyFields() {
return getOrComputePropertyFields().values();
}
/**
* Finds the property field with a specific property name from the ClassInfo's property fields
* Note that this method does not allow for property names with differing case. //TODO
*
* @param propertyName the propertyName of the field to find
* @return A FieldInfo object describing the required property field, or null if it doesn't exist.
* @throws InvalidPropertyFieldException if the recognized property fields contain a field that is not
* actually persistable as property.
*/
public FieldInfo propertyField(String propertyName) {
return propertyName == null ? null : getOrComputePropertyFields().get(propertyName);
}
private Map<String, FieldInfo> getOrComputePropertyFields() {
Map<String, FieldInfo> result = this.propertyFields;
if (result == null) {
synchronized (this) {
result = this.propertyFields;
if (result == null) {
Collection<FieldInfo> fields = fieldsInfo().fields();
FieldInfo optionalIdentityField = identityFieldOrNull();
Map<String, FieldInfo> intermediateFieldMap = new HashMap<>(fields.size());
for (FieldInfo fieldInfo : fields) {
if (fieldInfo == optionalIdentityField || fieldInfo.isLabelField() || fieldInfo.hasAnnotation(StartNode.class) || fieldInfo.hasAnnotation(EndNode.class)) {
continue;
}
if (!fieldInfo.getAnnotations().has(Property.class)) {
// If a field is not marked explicitly as a property but is persistable as such, add it.
if (fieldInfo.persistableAsProperty()) {
intermediateFieldMap.put(fieldInfo.property(), fieldInfo);
}
} else if (fieldInfo.persistableAsProperty()) {
// If it is marked as a property, then it should be persistable as such
intermediateFieldMap.put(fieldInfo.property(), fieldInfo);
} else {
// Otherwise, throw a fitting exception
throw new InvalidPropertyFieldException(fieldInfo);
}
}
this.propertyFields = Collections.unmodifiableMap(intermediateFieldMap);
result = this.propertyFields;
}
}
}
return result;
}
/**
* Finds the property field with a specific field name from the ClassInfo's property fields
*
* @param propertyName the propertyName of the field to find
* @return A FieldInfo object describing the required property field, or null if it doesn't exist.
*/
public FieldInfo propertyFieldByName(String propertyName) {
for (FieldInfo fieldInfo : propertyFields()) {
if (fieldInfo.getName().equalsIgnoreCase(propertyName)) {
return fieldInfo;
}
}
return null;
}
/**
* A relationship field is any field annotated with @Relationship, or any field that cannot be mapped to a
* node property. The identity field is not a relationship field.
*
* @return A Collection of FieldInfo objects describing the classInfo's relationship fields
*/
public Collection<FieldInfo> relationshipFields() {
Collection<FieldInfo> result = this.relationshipFields;
if (result == null) {
synchronized (this) {
result = this.relationshipFields;
if (result == null) {
FieldInfo optionalIdentityField = identityFieldOrNull();
Set<FieldInfo> identifiedRelationshipFields = new HashSet<>();
for (FieldInfo fieldInfo : fieldsInfo().fields()) {
if (fieldInfo == optionalIdentityField) {
continue;
}
if (fieldInfo.getAnnotations().has(Relationship.class)) {
identifiedRelationshipFields.add(fieldInfo);
} else if (!fieldInfo.persistableAsProperty()) {
identifiedRelationshipFields.add(fieldInfo);
}
}
this.relationshipFields = Collections.unmodifiableSet(identifiedRelationshipFields);
result = this.relationshipFields;
}
}
}
return result;
}
/**
* Finds the relationship field with a specific name from the ClassInfo's relationship fields
*
* @param relationshipName the relationshipName of the field to find
* @return A FieldInfo object describing the required relationship field, or null if it doesn't exist.
*/
public FieldInfo relationshipField(String relationshipName) {
for (FieldInfo fieldInfo : relationshipFields()) {
if (fieldInfo.relationship().equalsIgnoreCase(relationshipName)) {
return fieldInfo;
}
}
return null;
}
/**
* Finds the relationship field with a specific name and direction from the ClassInfo's relationship fields
*
* @param relationshipName the relationshipName of the field to find
* @param relationshipDirection the direction of the relationship represented by a string
* @param strict if true, does not infer relationship type but looks for it in the @Relationship annotation. Null if missing. If false, infers relationship type from FieldInfo
* @return A FieldInfo object describing the required relationship field, or null if it doesn't exist.
*/
public FieldInfo relationshipField(String relationshipName, Direction relationshipDirection, boolean strict) {
for (FieldInfo fieldInfo : relationshipFields()) {
String relationship = strict ? fieldInfo.relationshipTypeAnnotation() : fieldInfo.relationship();
if (relationshipName.equalsIgnoreCase(relationship)) {
Direction declaredDirection = fieldInfo.relationshipDirectionOrDefault(Direction.OUTGOING);
if (isActualDirectionCompatibleWithDeclaredDirection(relationshipDirection, declaredDirection)) {
return fieldInfo;
}
}
}
return null;
}
/**
* Finds all relationship fields with a specific name and direction from the ClassInfo's relationship fields
*
* @param relationshipName the relationshipName of the field to find
* @param relationshipDirection the direction of the relationship
* @param strict if true, does not infer relationship type but looks for it in the @Relationship annotation. Null if missing. If false, infers relationship type from FieldInfo
* @return Set of FieldInfo objects describing the required relationship field, or empty set if it doesn't exist.
*/
public Set<FieldInfo> candidateRelationshipFields(String relationshipName, Direction relationshipDirection, boolean strict) {
Set<FieldInfo> candidateFields = new HashSet<>();
for (FieldInfo fieldInfo : relationshipFields()) {
String relationship = strict ? fieldInfo.relationshipTypeAnnotation() : fieldInfo.relationship();
if (relationshipName.equalsIgnoreCase(relationship)) {
Direction declaredDirection = fieldInfo.relationshipDirectionOrDefault(Direction.OUTGOING);
if (isActualDirectionCompatibleWithDeclaredDirection(relationshipDirection, declaredDirection)) {
candidateFields.add(fieldInfo);
}
}
}
return candidateFields;
}
/**
* Finds the relationship field with a specific property name from the ClassInfo's relationship fields
*
* @param fieldName the name of the field
* @return A FieldInfo object describing the required relationship field, or null if it doesn't exist.
*/
public FieldInfo relationshipFieldByName(String fieldName) {
for (FieldInfo fieldInfo : relationshipFields()) {
if (fieldInfo.getName().equalsIgnoreCase(fieldName)) {
return fieldInfo;
}
}
return null;
}
public Field getField(FieldInfo fieldInfo) {
Field field = fieldInfoFields.get(fieldInfo);
if (field != null) {
return field;
}
try {
field = cls.getDeclaredField(fieldInfo.getName());
fieldInfoFields.put(fieldInfo, field);
return field;
} catch (NoSuchFieldException e) {
if (directSuperclass() != null) {
field = directSuperclass().getField(fieldInfo);
fieldInfoFields.put(fieldInfo, field);
return field;
} else {
throw new RuntimeException(
"Field " + fieldInfo.getName() + " not found in class " + name() + " or any of its superclasses");
}
}
}
/**
* Find all FieldInfos for the specified ClassInfo whose type matches the supplied fieldType
*
* @param fieldType The field type to look for
* @return A {@link List} of {@link FieldInfo} objects that are of the given type, never <code>null</code>
*/
public List<FieldInfo> findFields(Class<?> fieldType) {
String fieldSignature = fieldType.getName();
Predicate<FieldInfo> matchesType = f -> f.getTypeDescriptor().equals(fieldSignature);
return fieldsInfo().fields().stream().filter(matchesType).collect(toList());
}
/**
* Find all FieldInfos for the specified ClassInfo which have the specified annotation
*
* @param annotation The annotation
* @return A {@link List} of {@link FieldInfo} objects that are of the given type, never <code>null</code>
*/
public List<FieldInfo> findFields(String annotation) {
Predicate<FieldInfo> hasAnnotation = f -> f.hasAnnotation(annotation);
return fieldsInfo().fields().stream().filter(hasAnnotation).collect(toList());
}
/**
* Retrieves a {@link List} of {@link FieldInfo} representing all of the fields that can be iterated over
* using a "foreach" loop.
*
* @return {@link List} of {@link FieldInfo}
*/
public List<FieldInfo> findIterableFields() {
Predicate<FieldInfo> isIterable = f -> {
// The actual call to getField might throw an exception.
// While FieldInfo#type() should also return the type,
// ClassInfo#getField has side-effects which I cannot judge
// atm, so better keep it here
// and wrap the predicate in an exception below.
Class type = getField(f).getType();
return type.isArray() || Iterable.class.isAssignableFrom(type);
};
// See comment inside predicate regarding this exception.
try {
return fieldsInfo().fields().stream()
.filter(isIterable).collect(toList());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* Finds all fields whose type is equivalent to Array<X> or assignable from Iterable<X>
* where X is the generic parameter type of the Array or Iterable
*
* @param iteratedType the type of iterable
* @return {@link List} of {@link MethodInfo}, never <code>null</code>
*/
public List<FieldInfo> findIterableFields(Class iteratedType) {
if (iterableFieldsForType.containsKey(iteratedType)) {
return iterableFieldsForType.get(iteratedType);
}
String typeSignature = iteratedType.getName();
String arrayOfTypeSignature = typeSignature + "[]";
Predicate<FieldInfo> isIterableOfType = f -> {
String fieldType = f.getTypeDescriptor();
boolean isMatchingArray =
f.isArray() && (fieldType.equals(arrayOfTypeSignature) || f.isParameterisedTypeOf(iteratedType));
boolean isMatchingIterable =
f.isIterable() && (fieldType.equals(typeSignature) || f.isParameterisedTypeOf(iteratedType));
return isMatchingArray || isMatchingIterable;
};
return fieldsInfo().fields().stream()
.filter(isIterableOfType).collect(toList());
}
/**
* Finds all fields whose type is equivalent to Array<X> or assignable from Iterable<X>
* where X is the generic parameter type of the Array or Iterable and the relationship type backing this iterable is "relationshipType"
*
* @param iteratedType the type of iterable
* @param relationshipType the relationship type
* @param relationshipDirection the relationship direction
* @param strict if true, does not infer relationship type but looks for it in the @Relationship annotation. Null if missing. If false, infers relationship type from FieldInfo
* @return {@link List} of {@link MethodInfo}, never <code>null</code>
*/
public List<FieldInfo> findIterableFields(Class<?> iteratedType, String relationshipType, Direction relationshipDirection, boolean strict) {
List<FieldInfo> iterableFields = new ArrayList<>();
for (FieldInfo fieldInfo : findIterableFields(iteratedType)) {
String relationship = strict ? fieldInfo.relationshipTypeAnnotation() : fieldInfo.relationship();
if (relationshipType.equals(relationship)) {
Direction declaredDirection = fieldInfo.relationshipDirectionOrDefault(Direction.OUTGOING);
if (isActualDirectionCompatibleWithDeclaredDirection(relationshipDirection, declaredDirection)) {
iterableFields.add(fieldInfo);
}
}
}
return iterableFields;
}
private static boolean isActualDirectionCompatibleWithDeclaredDirection(Direction actual, Direction declared) {
return ((declared == Direction.INCOMING || declared == Direction.UNDIRECTED) && actual == Direction.INCOMING) ||
(declared != Direction.INCOMING && actual == Direction.OUTGOING);
}
public boolean isTransient() {
return annotationsInfo.get(Transient.class) != null;
}
public boolean isAbstract() {
return isAbstract;
}
/**
* Returns true if this classInfo is in the subclass hierarchy of b, or if this classInfo is the same as b, false otherwise
*
* @param classInfo the classInfo at the toplevel of a type hierarchy to search through
* @return true if this classInfo is in the subclass hierarchy of classInfo, false otherwise
*/
boolean isSubclassOf(ClassInfo classInfo) {
if (classInfo == null) {
return false;
}
if (this == classInfo) {
return true;
}
for (ClassInfo subclass : classInfo.directSubclasses()) {
if (isSubclassOf(subclass)) {
return true;
}
}
return this.indirectSuperClasses.stream()
.anyMatch(c -> c.getUnderlyingClass() == classInfo.getUnderlyingClass());
}
/**
* Get the underlying class represented by this ClassInfo
*
* @return the underlying class or null if it cannot be determined
*/
public Class<?> getUnderlyingClass() {
return cls;
}
/**
* Gets the class of the type parameter description of the entity related to this.
* The match is done based on the following-
* 2. Look for a field explicitly annotated with @Relationship for a type and implied direction
* 4. Look for a field with name derived from the relationship type for the given direction
*
* @param relationshipType the relationship type
* @param relationshipDirection the relationship direction
* @return class of the type parameter descriptor or null if it could not be determined
*/
Class<?> getTypeParameterDescriptorForRelationship(String relationshipType, Direction relationshipDirection) {
final boolean STRICT_MODE = true; //strict mode for matching methods and fields, will only look for explicit annotations
final boolean INFERRED_MODE = false; //inferred mode for matching methods and fields, will infer the relationship type from the getter/setter/property
try {
FieldInfo fieldInfo = relationshipField(relationshipType, relationshipDirection, STRICT_MODE);
if (fieldInfo != null && fieldInfo.getTypeDescriptor() != null) {
return DescriptorMappings.getType(fieldInfo.getTypeDescriptor());
}
if (relationshipDirection != Direction.INCOMING) { //we always expect an annotation for INCOMING
fieldInfo = relationshipField(relationshipType, relationshipDirection, INFERRED_MODE);
if (fieldInfo != null && fieldInfo.getTypeDescriptor() != null) {
return DescriptorMappings.getType(fieldInfo.getTypeDescriptor());
}
}
} catch (RuntimeException e) {
LOGGER.debug("Could not get {} class type for relationshipType {} and relationshipDirection {} ", className,
relationshipType, relationshipDirection);
}
return null;
}
/**
* @return If this class contains any fields/properties annotated with @Index.
*/
public boolean containsIndexes() {
return !(getIndexFields().isEmpty() && getCompositeIndexes().isEmpty());
}
/**
* @return The <code>FieldInfo</code>s representing the Indexed fields in this class.
*/
public Collection<FieldInfo> getIndexFields() {
Map<String, FieldInfo> result = this.indexFields;
if (result == null) {
synchronized (this) {
result = this.indexFields;
if (result == null) {
Map<String, FieldInfo> indexes = new HashMap<>();
Field[] declaredFields = cls.getDeclaredFields();
for (FieldInfo fieldInfo : fieldsInfo().fields()) {
if (isDeclaredField(declaredFields, fieldInfo.getName()) &&
(fieldInfo.hasAnnotation(Index.class) || fieldInfo.hasAnnotation(Id.class))) {
String propertyValue = fieldInfo.property();
if (fieldInfo.hasAnnotation(Property.class.getName())) {
propertyValue = fieldInfo.property();
}
indexes.put(propertyValue, fieldInfo);
}
}
this.indexFields = Collections.unmodifiableMap(indexes);
result = this.indexFields;
}
}
}
return result.values();
}
private static boolean isDeclaredField(Field[] declaredFields, String name) {
for (Field field : declaredFields) {
if (field.getName().equals(name)) {
return true;
}
}
return false;
}
public Collection<CompositeIndex> getCompositeIndexes() {
Collection<CompositeIndex> result = this.compositeIndexes;
if (result == null) {
synchronized (this) {
result = this.compositeIndexes;
if (result == null) {
CompositeIndex[] annotations = cls.getDeclaredAnnotationsByType(CompositeIndex.class);
List<CompositeIndex> intermediateResult = new ArrayList<>(annotations.length);
for (CompositeIndex annotation : annotations) {
String[] properties =
annotation.value().length > 0 ? annotation.value() : annotation.properties();
if (properties.length < 1) {
throw new MetadataException("Incorrect CompositeIndex definition on " + className +
". Provide at least 1 property");
}
for (String property : properties) {
// Determine the original field in case the user uses a MapCompositeConverter.
Matcher m = AutoIndexManager.COMPOSITE_KEY_MAP_COMPOSITE_PATTERN.matcher(property);
if (m.matches()) {
property = m.group(1);
}
FieldInfo fieldInfo = propertyField(property);
if (fieldInfo == null) {
throw new MetadataException(
"Incorrect CompositeIndex definition on " + className + ". Property " +
property + " does not exists.");
}
}
intermediateResult.add(annotation);
}
this.compositeIndexes = Collections.unmodifiableList(intermediateResult);
result = this.compositeIndexes;
}
}
}
return result;
}
public FieldInfo primaryIndexField() {
return getOrComputePimaryIndexField().orElse(null);
}
private Optional<FieldInfo> getOrComputePimaryIndexField() {
Optional<FieldInfo> result = this.primaryIndexField;
if (result == null) {
synchronized (this) {
result = this.primaryIndexField;
if (result == null) {
Optional<FieldInfo> potentialPrimaryIndexField = Optional.empty();
Collection<FieldInfo> primaryIndexFields = getFieldInfos(this::isPrimaryIndexField);
if (primaryIndexFields.size() > 1) {
throw new MetadataException(
"Only one @Id / @Index(primary=true, unique=true) annotation is allowed in a class hierarchy. Please check annotations in the class "
+ name() + " or its parents");
} else if (!primaryIndexFields.isEmpty()) {
FieldInfo selectedField = primaryIndexFields.iterator().next();
AnnotationInfo generatedValueAnnotation = selectedField.getAnnotations().get(GeneratedValue.class);
if (generatedValueAnnotation != null) {
// Here's a funny hidden side effect I wasn't able to refactor out with a clear idea during
// rethinking the whole collection of synchronized blocks :(
GeneratedValue value = (GeneratedValue) generatedValueAnnotation.getAnnotation();
idStrategyClass = value.strategy();
try {
idStrategy = idStrategyClass.getDeclaredConstructor().newInstance();
} catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
LOGGER.debug("Could not instantiate {}. Expecting this to be registered manually.", idStrategyClass);
}
}
potentialPrimaryIndexField = Optional.of(selectedField);
}
result = validateIdGenerationConfigFor(potentialPrimaryIndexField);
}
}
}
return result;
}
private Optional<FieldInfo> validateIdGenerationConfigFor(Optional<FieldInfo> potentialPrimaryIndexField) {
fieldsInfo().fields().forEach(info -> {
if (info.hasAnnotation(GeneratedValue.class) && !info.hasAnnotation(Id.class)) {
throw new MetadataException(
"The type of @Generated field in class " + className + " must be also annotated with @Id.");
}
});
if (UuidStrategy.class.equals(idStrategyClass)) {
potentialPrimaryIndexField.ifPresent(selectedField -> {
if (!(selectedField.isTypeOf(UUID.class) || selectedField.isTypeOf(String.class))) {
throw new MetadataException(
"The type of " + selectedField.getName() + " in class " + className
+ " must be of type java.lang.UUID or java.lang.String because it has an UUID generation strategy.");
}
});
}
return potentialPrimaryIndexField;
}
public boolean hasPrimaryIndexField() {
return getOrComputePimaryIndexField().isPresent();
}
private boolean isPrimaryIndexField(FieldInfo fieldInfo) {
boolean hasIdAnnotation = fieldInfo.hasAnnotation(Id.class);
boolean hasStrategyOtherThanInternal = !fieldInfo.hasAnnotation(GeneratedValue.class)
|| !((GeneratedValue) fieldInfo.getAnnotations().get(GeneratedValue.class).getAnnotation()).strategy()
.equals(InternalIdStrategy.class);
return hasIdAnnotation && hasStrategyOtherThanInternal;
}
public IdStrategy idStrategy() {
// Forces initialization of the id strategy
return getOrComputePimaryIndexField()
.map(ignored -> idStrategy).orElse(null);
}
public Class<? extends IdStrategy> idStrategyClass() {
return idStrategyClass;
}
public void registerIdGenerationStrategy(IdStrategy strategy) {
if (strategy.getClass().equals(idStrategyClass)) {
idStrategy = strategy;
} else {
throw new IllegalArgumentException("Strategy " + strategy +
" is not an instance of " + idStrategyClass);
}
}
public MethodInfo postLoadMethodOrNull() {
Optional<MethodInfo> result = this.postLoadMethod;
if (result == null) {
synchronized (this) {
result = this.postLoadMethod;
if (result == null) {
Collection<MethodInfo> possiblePostLoadMethods = methodsInfo
.findMethodInfoBy(methodInfo -> methodInfo.hasAnnotation(PostLoad.class));
if (possiblePostLoadMethods.size() > 1) {
throw new MetadataException(String
.format("Cannot have more than one post load method annotated with @PostLoad for class '%s'",
this.className));
}
this.postLoadMethod = possiblePostLoadMethods.stream().findFirst();
result = this.postLoadMethod;
}
}
}
return result.orElse(null);
}
public FieldInfo getFieldInfo(String propertyName) {
// fall back to the field if method cannot be found
FieldInfo optionalLabelField = labelFieldOrNull();
if (optionalLabelField != null && optionalLabelField.getName().equals(propertyName)) {
return optionalLabelField;
}
FieldInfo propertyField = propertyField(propertyName);
if (propertyField != null) {
return propertyField;
}
return fieldsInfo.get(propertyName);
}
/**
* Return a FieldInfo for the EndNode of a RelationshipEntity
*
* @return a FieldInfo for the field annotated as the EndNode, or none if not found
*/
public FieldInfo getEndNodeReader() {
Optional<FieldInfo> result = this.endNodeReader;
if (result == null) {
synchronized (this) {
result = this.endNodeReader;
if (result == null) {
if (isRelationshipEntity()) {
endNodeReader = fieldsInfo().fields().stream()
.filter(fieldInfo -> fieldInfo.getAnnotations().get(EndNode.class) != null)
.findFirst();
if (!endNodeReader.isPresent()) {
LOGGER.warn("Failed to find an @EndNode on {}", name());
}
} else {
endNodeReader = Optional.empty();
}
result = this.endNodeReader;
}
}
}
return result.orElse(null);
}
/**
* Return a FieldInfo for the StartNode of a RelationshipEntity
*
* @return a FieldInfo for the field annotated as the StartNode, or none if not found
*/
public FieldInfo getStartNodeReader() {
Optional<FieldInfo> result = this.startNodeReader;
if (result == null) {
synchronized (this) {
result = this.startNodeReader;
if (result == null) {
if (isRelationshipEntity()) {
startNodeReader = fieldsInfo().fields().stream()
.filter(fieldInfo -> fieldInfo.getAnnotations().get(StartNode.class) != null)
.findFirst();
if (!startNodeReader.isPresent()) {
LOGGER.warn("Failed to find an @StartNode on {}", name());
}
} else {
startNodeReader = Optional.empty();
}
result = this.startNodeReader;
}
}
}
return result.orElse(null);
}
/**
* Returns if the class as fields annotated with @Required annotation
*/
public boolean hasRequiredFields() {
return !requiredFields().isEmpty();
}
public Collection<FieldInfo> requiredFields() {
if (requiredFields == null) {
requiredFields = new ArrayList<>();
for (FieldInfo fieldInfo : propertyFields()) {
if (fieldInfo.getAnnotations().has(Required.class)) {
requiredFields.add(fieldInfo);
}
}
}
return requiredFields;
}
public boolean hasVersionField() {
return getOrComputeVersionField().isPresent();
}
public FieldInfo getVersionField() {
return getOrComputeVersionField().orElse(null);
}
private Optional<FieldInfo> getOrComputeVersionField() {
Optional<FieldInfo> result = this.versionField;
if (result == null) {
synchronized (this) {
result = this.versionField;
if (result == null) {
Collection<FieldInfo> fields = getFieldInfos(FieldInfo::isVersionField);
if (fields.size() > 1) {
throw new MetadataException("Only one version field is allowed, found " + fields);
}
Iterator<FieldInfo> iterator = fields.iterator();
if (iterator.hasNext()) {
this.versionField = Optional.of(iterator.next());
} else {
// cache that there is no version field
this.versionField = Optional.empty();
}
result = this.versionField;
}
}
}
return result;
}
/**
* Reads the value of the entity's primary index field if any.
*
* @param entity
* @return
*/
public Object readPrimaryIndexValueOf(Object entity) {
Objects.requireNonNull(entity, "Entity to read from must not be null.");
Object value = null;
if (this.hasPrimaryIndexField()) {
// One has to use #read here to get the ID as defined in the entity.
// #readProperty gives back the converted value the database sees.
// This breaks immediate in LoadOneDelegate#lookup(Class, Object).
// That is called by LoadOneDelegate#load(Class, Serializable, int)
// immediately after loading (and finding(!!) an entity, which is never
// returned directly but goes through a cache.
// However, LoadOneDelegate#load(Class, Serializable, int) deals with the
// ID as defined in the domain and so we have to use that in the same way here.
value = this.primaryIndexField().read(entity);
}
return value;
}
public Function<Object, Optional<Object>> getPrimaryIndexOrIdReader() {
Function<Object, Optional<Object>> reader;
if (this.hasPrimaryIndexField()) {
reader = t -> Optional.ofNullable(this.readPrimaryIndexValueOf(t));
} else {
reader = t -> Optional.ofNullable(this.identityField().read(t));
}
return reader;
}
static Object getInstanceOrDelegate(Object instance, Field delegateHolder) {
if (delegateHolder == null) {
return instance;
} else {
return AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
try {
delegateHolder.setAccessible(true);
return delegateHolder.get(instance);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
});
}
}
@Override
public String toString() {
return "ClassInfo{" +
"className='" + className + '\'' +
", neo4jName='" + neo4jName + '\'' +
'}';
}
}
| Fix spelling mistake.
| core/src/main/java/org/neo4j/ogm/metadata/ClassInfo.java | Fix spelling mistake. | <ide><path>ore/src/main/java/org/neo4j/ogm/metadata/ClassInfo.java
<ide>
<ide> public FieldInfo primaryIndexField() {
<ide>
<del> return getOrComputePimaryIndexField().orElse(null);
<del> }
<del>
<del> private Optional<FieldInfo> getOrComputePimaryIndexField() {
<add> return getOrComputePrimaryIndexField().orElse(null);
<add> }
<add>
<add> private Optional<FieldInfo> getOrComputePrimaryIndexField() {
<ide>
<ide> Optional<FieldInfo> result = this.primaryIndexField;
<ide> if (result == null) {
<ide> }
<ide>
<ide> public boolean hasPrimaryIndexField() {
<del> return getOrComputePimaryIndexField().isPresent();
<add> return getOrComputePrimaryIndexField().isPresent();
<ide> }
<ide>
<ide> private boolean isPrimaryIndexField(FieldInfo fieldInfo) {
<ide>
<ide> public IdStrategy idStrategy() {
<ide> // Forces initialization of the id strategy
<del> return getOrComputePimaryIndexField()
<add> return getOrComputePrimaryIndexField()
<ide> .map(ignored -> idStrategy).orElse(null);
<ide> }
<ide> |
|
JavaScript | apache-2.0 | 9c2f6ab1ef7ff58749a73bba01e25ab7fc91577c | 0 | learningtapestry/lrmi-tagger,learningtapestry/lrmi-tagger | /*!
* jQuery JavaScript Library v1.8.3
* http://jquery.com/
*
* Includes Sizzle.js
* http://sizzlejs.com/
*
* Copyright 2012 jQuery Foundation and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: Tue Nov 13 2012 08:20:33 GMT-0500 (Eastern Standard Time)
*/
function hex_sha1(e) {
return binb2hex(core_sha1(str2binb(e), e.length * chrsz))
}
function b64_sha1(e) {
return binb2b64(core_sha1(str2binb(e), e.length * chrsz))
}
function str_sha1(e) {
return binb2str(core_sha1(str2binb(e), e.length * chrsz))
}
function hex_hmac_sha1(e, t) {
return binb2hex(core_hmac_sha1(e, t))
}
function b64_hmac_sha1(e, t) {
return binb2b64(core_hmac_sha1(e, t))
}
function str_hmac_sha1(e, t) {
return binb2str(core_hmac_sha1(e, t))
}
function sha1_vm_test() {
return hex_sha1("abc") == "a9993e364706816aba3e25717850c26c9cd0d89d"
}
function core_sha1(e, t) {
e[t >> 5] |= 128 << 24 - t % 32, e[(t + 64 >> 9 << 4) + 15] = t;
var n = Array(80),
r = 1732584193,
i = -271733879,
s = -1732584194,
o = 271733878,
u = -1009589776;
for (var a = 0; a < e.length; a += 16) {
var f = r,
l = i,
c = s,
h = o,
p = u;
for (var d = 0; d < 80; d++) {
d < 16 ? n[d] = e[a + d] : n[d] = rol(n[d - 3] ^ n[d - 8] ^ n[d - 14] ^ n[d - 16], 1);
var v = safe_add(safe_add(rol(r, 5), sha1_ft(d, i, s, o)), safe_add(safe_add(u, n[d]), sha1_kt(d)));
u = o, o = s, s = rol(i, 30), i = r, r = v
}
r = safe_add(r, f), i = safe_add(i, l), s = safe_add(s, c), o = safe_add(o, h), u = safe_add(u, p)
}
return Array(r, i, s, o, u)
}
function sha1_ft(e, t, n, r) {
return e < 20 ? t & n | ~t & r : e < 40 ? t ^ n ^ r : e < 60 ? t & n | t & r | n & r : t ^ n ^ r
}
function sha1_kt(e) {
return e < 20 ? 1518500249 : e < 40 ? 1859775393 : e < 60 ? -1894007588 : -899497514
}
function core_hmac_sha1(e, t) {
var n = str2binb(e);
n.length > 16 && (n = core_sha1(n, e.length * chrsz));
var r = Array(16),
i = Array(16);
for (var s = 0; s < 16; s++) r[s] = n[s] ^ 909522486, i[s] = n[s] ^ 1549556828;
var o = core_sha1(r.concat(str2binb(t)), 512 + t.length * chrsz);
return core_sha1(i.concat(o), 672)
}
function safe_add(e, t) {
var n = (e & 65535) + (t & 65535),
r = (e >> 16) + (t >> 16) + (n >> 16);
return r << 16 | n & 65535
}
function rol(e, t) {
return e << t | e >>> 32 - t
}
function str2binb(e) {
var t = Array(),
n = (1 << chrsz) - 1;
for (var r = 0; r < e.length * chrsz; r += chrsz) t[r >> 5] |= (e.charCodeAt(r / chrsz) & n) << 32 - chrsz - r % 32;
return t
}
function binb2str(e) {
var t = "",
n = (1 << chrsz) - 1;
for (var r = 0; r < e.length * 32; r += chrsz) t += String.fromCharCode(e[r >> 5] >>> 32 - chrsz - r % 32 & n);
return t
}
function binb2hex(e) {
var t = hexcase ? "0123456789ABCDEF" : "0123456789abcdef",
n = "";
for (var r = 0; r < e.length * 4; r++) n += t.charAt(e[r >> 2] >> (3 - r % 4) * 8 + 4 & 15) + t.charAt(e[r >> 2] >> (3 - r % 4) * 8 & 15);
return n
}
function binb2b64(e) {
var t = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
n = "";
for (var r = 0; r < e.length * 4; r += 3) {
var i = (e[r >> 2] >> 8 * (3 - r % 4) & 255) << 16 | (e[r + 1 >> 2] >> 8 * (3 - (r + 1) % 4) & 255) << 8 | e[r + 2 >> 2] >> 8 * (3 - (r + 2) % 4) & 255;
for (var s = 0; s < 4; s++) r * 8 + s * 6 > e.length * 32 ? n += b64pad : n += t.charAt(i >> 6 * (3 - s) & 63)
}
return n
}
function capitalize(e) {
return (e + "").replace(/^([a-z])|\s+([a-z])|,+([a-z])/g, function(e) {
return e.toUpperCase()
})
}
function csvPreprocess(e) {
return (e + "").replace(/^([a-z])|\s+([a-z])|,+([a-z])/g, function(e) {
return e.toUpperCase()
}).replace(/^\s+/, "").replace(/\s+$/, "").replace(/\s+,/g, ",").replace(/,\s+/g, ",")
}
function deleteTag(e) {
return items[e] != undefined && delete items[e], $("#" + e).length > 0 && ($("#" + e).addClass("deleted"), $("#" + e).parent().hide().addClass("deleted"), $("a[href=#" + e + "]").remove(), $("#resourceCount").html($("#multiItemSelector input[type=checkbox]:checked").not(".deleted").length + " of " + $("#multiItemSelector input[type=checkbox]").not(".deleted").length + " resources")), $("#deleteModal").modal("hide"), updateTextArea(), !1
}
function objectToHash(e) {
var t = "";
for (j in e) typeof e[j] == "string" && (t += e[j]);
return hex_sha1(t)
}
function wrapIfNeeded(e) {
return /"/.test(e) || /,/.test(e) ? '"' + e.replace(/"/g, '""') + '"' : e
}
function processDataForAlignmentArray(e) {
var t = e.split(/\n|\r/);
for (var n = 1; n < t.length - 1; n++) {
var r = t[n].split(",");
alignmentArray.push({
title: r[2],
url: r[3],
description: r[0],
guid: r[4]
}), dotNotationDisplayArray.push(r[2])
}
}
function redrawResourcesBasedOnItems() {
$("#multiItemSelector").empty(), $("#multiItemSelector input[type=checkbox]").each(function(e, t) {
t.checked = !1
}), updateInputFields();
for (itemCounter in items) {
$("#multiItemSelector span.notYet").hide();
var e = items[itemCounter].title.length > 25 ? items[itemCounter].title.substr(0, 25) + "…" : items[itemCounter].title;
$("#multiItemSelector").append($("<a href='#" + itemCounter + "' class='pull-right delete-tag'><i class='icon-remove'></i></a> <a href='#" + itemCounter + "' id='" + itemCounter + "URL' " + (items[itemCounter].url ? "" : "style='display:none;'") + " class='pull-right render-tag'><i class='icon-share'></i> </a> <label id='" + itemCounter + "Label' class='checkbox'><input id='" + itemCounter + "' type='checkbox' name='tagItem'/><span>" + e + "</span></label>"));
for (objHash in items[itemCounter].educationalAlignments) {
var t = {
educationalAlignment: items[itemCounter].educationalAlignments[objHash].educationalAlignment,
alignmentType: items[itemCounter].educationalAlignments[objHash].alignmentType,
dotNotation: items[itemCounter].educationalAlignments[objHash].dotNotation,
description: items[itemCounter].educationalAlignments[objHash].description,
itemURL: items[itemCounter].educationalAlignments[objHash].itemURL
};
alignments[objHash] == undefined && ($(".noAlignmentsYet").hide(), alignments[objHash] = t, $("#currentAlignmentTable > tbody:last").append('<tr><td><label class="checkbox"><input type="checkbox" class="alignment-checkbox" value="' + objHash + '" />' + t.dotNotation + "</label></td><td>" + capitalize(t.alignmentType) + "</td></tr>"))
}
}
updateTextArea(), updateResourceCount()
}
function redrawHistoryBasedOn(e) {
$("#history").empty();
for (i in e) {
var t = e[i].title.length > 25 ? e[i].title.substr(0, 25) + "…" : e[i].title;
$("#history").append($("<label><a href='#" + e[i].uuid + "'><i class='icon-repeat'></i> " + t + "</a></label>"))
}
}
function setupDisplayFieldsEducationTab(e, t) {
if (e[t] != undefined && e[t] != "" && $("select#" + t)[0] != undefined) {
var n = e[t].split(",");
$("select#" + t + " option").each(function() {
$.inArray($(this).val(), n) !== -1 && $(this).attr("selected", !0)
});
var r = $("select#" + t + " option").map(function() {
return this.value
}),
s = [];
for (i in n) $.inArray(n[i], r) === -1 && s.push(n[i]);
s.length > 0 && $("#" + t + "Other").attr("value", s.join(","))
}
}
function toggleForm() {
$("#multiItemSelector input[type=checkbox]:checked").length > 0 ? ($("#LRMIData input,#LRMIData select,#LRMIData textarea").removeAttr("disabled"), $("#educationTab,#alignmentTab").removeClass("disabled"), $("#educationTab a,#alignmentTab a").attr("data-toggle", "tab")) : ($("#generalTab a").click(), $("#LRMIData input,#LRMIData select,#LRMIData textarea").attr("disabled", "disabled"), $("#educationTab,#alignmentTab").addClass("disabled"), $("#educationTab a,#alignmentTab a").removeAttr("data-toggle"))
}
function updateInputFields() {
updateResourceCount(), $("#addThumbnailButton").addClass("disabled"), $("#thumbnail").attr("value", ""), $("#thumbnailImage").attr("src", ""), $("#removeThumbnailButton").hide(), $("#thumbnailImage").hide(), $("#publishButton").addClass("disabled"), $("form[name=LRMIData]").find("input[type=text], textarea, select").val(""), $("#currentAlignmentTable input[type=checkbox]").attr("checked", !1), clearTimeRequired(), updateMainContentBottom(), toggleForm();
if ($("#multiItemSelector input[type=checkbox]:checked").length == 1) {
$("#addThumbnailButton").removeClass("disabled"), $("#publishButton").removeClass("disabled");
var e = items[$("#multiItemSelector input[type=checkbox]:checked").first().attr("id")];
e.title != "" && $("#title").val(e.title), e.url != "" && $("#url").val(e.url), e.tagDescription != "" && $("#tagDescription").val(e.tagDescription), e.language != "" && $("#language").val(e.language), e.topic != "" && $("#topic").val(e.topic), e.createdBy != "" && $("#createdBy").val(e.createdBy), e.usageRightsURL != "" && $("#usageRightsURL").val(e.usageRightsURL), e.publisher != "" && $("#publisher").val(e.publisher), e.isBasedOnURL != "" && $("#isBasedOnURL").val(e.isBasedOnURL), e.thumbnail != "" && ($("#thumbnail").val(e.thumbnail), $("#thumbnailImage").attr("src", "http://media.inbloom.org.s3.amazonaws.com/tagger/images/browser_thumb_" + e.thumbnail), $("#removeThumbnailButton").show(), $("#thumbnailImage").show()), d = new Date;
var t = ("0" + d.getDate()).slice(-2),
n = d.getMonth() + 1,
r = d.getFullYear();
ds = r + "-" + n + "-" + t, e.createdOn != "" && $("#createdOn").val(e.createdOn);
if (e.timeRequired != "P0Y0M0W0DT0H0M0S" && e.timeRequired != "") {
var i = e.timeRequired.match(/(\d+)/g);
updateSlider(event, null, $("#slideryears"), "Year", i[0]), updateSlider(event, null, $("#slidermonths"), "Month", i[1]), updateSlider(event, null, $("#sliderweeks"), "Week", i[2]), updateSlider(event, null, $("#sliderdays"), "Day", i[3]), updateSlider(event, null, $("#sliderhours"), "Hour", i[4]), updateSlider(event, null, $("#sliderminutes"), "Minute", i[5]), updateSlider(event, null, $("#sliderseconds"), "Second", i[6])
}
e.url != "" && updateMainContentBottom(e.url), setupDisplayFieldsEducationTab(e, "endUser"), setupDisplayFieldsEducationTab(e, "ageRange"), setupDisplayFieldsEducationTab(e, "educationalUse"), setupDisplayFieldsEducationTab(e, "interactivityType"), setupDisplayFieldsEducationTab(e, "learningResourceType"), setupDisplayFieldsEducationTab(e, "mediaType"), setupDisplayFieldsEducationTab(e, "groupType");
for (j in e.educationalAlignments) $("input[type=checkbox][value=" + j + "]").attr("checked", !0)
} else $("#multiItemSelector input[type=checkbox]:checked").length > 1 && ($("#publishButton").removeClass("disabled"), $("#addThumbnailButton").removeClass("disabled"))
}
function updateItemEducationTab(e, t) {
$("#multiItemSelector input[type=checkbox]:checked").each(function(n, r) {
var i = !1,
s = document.forms.LRMIData,
o = "",
u = 0;
for (u = 0; u < s[e].length; u++) s[e][u].selected && (i ? o = o + "," + s[e][u].value : (o = s[e][u].value, i = !0));
s[t].value != "" && (o = o + (o == "" ? "" : ",") + s[t].value), items[r.id][e] = o
}), updateTextArea()
}
function updateMainContentBottom(e) {
e == "" || e == undefined ? $("#iframe").attr("src", "about:blank") : $("#iframe").attr("src", e)
}
function updateResourceCount() {
$("#resourceCount").html($("#multiItemSelector input[type=checkbox]:checked").not(".deleted").length + " of " + $("#multiItemSelector input[type=checkbox]").not(".deleted").length + " resources")
}
function updateTextArea() {
var e = "";
$("#multiItemSelector input[type=checkbox]:checked").each(function(t, n) {
items[n.id].title != undefined && items[n.id].title != "" && (e += "Title:\n" + items[n.id].title + "\n"), items[n.id].url != undefined && items[n.id].url != "" && (e += "URL:\n" + items[n.id].url + "\n"), items[n.id].tagDescription != undefined && items[n.id].tagDescription != "" && (e += "Description:\n" + items[n.id].tagDescription + "\n"), items[n.id].language != undefined && items[n.id].language != "" && (e += "Language:\n" + items[n.id].language + "\n"), items[n.id].createdOn != undefined && items[n.id].createdOn != "" && (e += "Created On:\n" + items[n.id].createdOn + "\n"), items[n.id].topic != undefined && items[n.id].topic != "" && (e += "Topic/Subject:\n" + items[n.id].topic + "\n"), items[n.id].createdBy != undefined && items[n.id].createdBy != "" && (e += "Created By:\n" + items[n.id].createdBy + "\n"), items[n.id].usageRightsURL != undefined && items[n.id].usageRightsURL != "" && (e += "Usage Rights URL:\n" + items[n.id].usageRightsURL + "\n"), items[n.id].publisher != undefined && items[n.id].publisher != "" && (e += "Publisher:\n" + items[n.id].publisher + "\n"), items[n.id].isBasedOnURL != undefined && items[n.id].isBasedOnURL != "" && (e += "Is Based On URL:\n" + items[n.id].isBasedOnURL + "\n"), items[n.id].endUser != undefined && items[n.id].endUser != "" && (e += "End User:\n" + items[n.id].endUser + "\n"), items[n.id].ageRange != undefined && items[n.id].ageRange != "" && (e += "Age Range:\n" + items[n.id].ageRange + "\n"), items[n.id].educationalUse != undefined && items[n.id].educationalUse != "" && (e += "Educational Use:\n" + items[n.id].educationalUse + "\n"), items[n.id].interactivityType != undefined && items[n.id].interactivityType != "" && (e += "Interactivity Type:\n" + items[n.id].interactivityType + "\n"), items[n.id].learningResourceType != undefined && items[n.id].learningResourceType != "" && (e += "Learning Res Type:\n" + items[n.id].learningResourceType + "\n"), items[n.id].mediaType != undefined && items[n.id].mediaType != "" && (e += "Media Type:\n" + items[n.id].mediaType + "\n"), items[n.id].groupType != undefined && items[n.id].groupType != "" && (e += "Group Type:\n" + items[n.id].groupType + "\n"), items[n.id].timeRequired != "P0Y0M0W0DT0H0M0S" && (e += "Time Required:\n" + items[n.id].timeRequired + "\n\n");
if (items[n.id].educationalAlignments != undefined)
for (j in items[n.id].educationalAlignments) items[n.id].educationalAlignments[j].educationalAlignment != undefined && items[n.id].educationalAlignments[j].educationalAlignment != "" && (e += "Educational Alignment:\n" + items[n.id].educationalAlignments[j].educationalAlignment + "\n"), items[n.id].educationalAlignments[j].alignmentType != undefined && items[n.id].educationalAlignments[j].alignmentType != "" && (e += "Alignment Type:\n" + items[n.id].educationalAlignments[j].alignmentType + "\n"), items[n.id].educationalAlignments[j].dotNotation != undefined && items[n.id].educationalAlignments[j].dotNotation != "" && (e += "Dot Notation:\n" + items[n.id].educationalAlignments[j].dotNotation + "\n"), items[n.id].educationalAlignments[j].itemURL != undefined && items[n.id].educationalAlignments[j].itemURL != "" && (e += "Item URL:\n" + items[n.id].educationalAlignments[j].itemURL + "\n"), items[n.id].educationalAlignments[j].description != undefined && items[n.id].educationalAlignments[j].description != "" && (e += "Description:\n" + items[n.id].educationalAlignments[j].description + "\n");
e += "\n-----------------------\n\n"
}), $("#textarea").val(e)
}
function toCorrectCase(e) {
var t = "";
e == "on-line" && (t = "On-Line"), e == "cd-rom" && (t = "CD-ROM"), e == "cd-i" && (t = "CD-I"), e == "pdf" && (t = "PDF"), e == "e-mail" && (t = "E-Mail"), e == "audio cd" && (t = "Audio CD"), e == "dvd/blu-ray" && (t = "DVD/Blu-ray"), e == "mbl (microcomputer based)" && (t = "MBL (Microcomputer Based)"), e == "person-to-person" && (t = "Person-to-Person");
if (t == "") {
var n = e.split(/\s/);
for (i in n) n[i] = n[i].charAt(0).toUpperCase() + n[i].slice(1);
t = n.join(" ");
var n = t.split(/\//);
for (i in n) n[i] = n[i].charAt(0).toUpperCase() + n[i].slice(1);
t = n.join("/")
}
return t
}
function compareValueEquals(e, t, n) {
if (typeof e == "string") e.toLowerCase() != t.toLowerCase() && (fileHasErrors = !0, fileErrors.push("<strong>Invalid file imported</strong><br /> " + n + ": '" + e + "' is not equals to the correct value of '" + t + "'<br /><br />"));
else if (typeof e == "object")
for (i in t)
if (e[i] == undefined || e[i].toLowerCase() != t[i].toLowerCase()) fileHasErrors = !0, e[i] == undefined ? fileErrors.push("<strong>Invalid file imported</strong><br /> " + n + ": '" + t[i] + "' appears to be missing entirely<br /><br />") : fileErrors.push("<strong>Invalid file imported</strong><br /> " + n + ": '" + e[i] + "' is not equals to the correct value of '" + t[i] + "'<br /><br />")
}
function showFileHasErrorsMessage(e) {
if (fileHasErrors) {
var t = "Data could not be imported. The file you're attempting to import appears to have some errors in rows or columns that Tagger does not understand. This is usually as a result of data that doesn't conform to requirements for each column of data.<br />Before Tagger can import this file, please correct the following errors.<br /><br />" + fileErrors.join("");
showMessage(t, "Import Errors! :: " + e)
}
}
function forcePublish() {
var e = processJSONOutput(!0);
saveRemote(e, "LR")
}
function updateSlider(e, t, n, r, i) {
i == undefined && (i = t.value), $(n).slider({
value: i
});
var s = $(n).prev();
i == 0 ? s.
html(r): i == 1 ? s.html(i + " " + r) : s.html(i + " " + r + "s")
}(function(e, t) {
function _(e) {
var t = M[e] = {};
return v.each(e.split(y), function(e, n) {
t[n] = !0
}), t
}
function H(e, n, r) {
if (r === t && e.nodeType === 1) {
var i = "data-" + n.replace(P, "-$1").toLowerCase();
r = e.getAttribute(i);
if (typeof r == "string") {
try {
r = r === "true" ? !0 : r === "false" ? !1 : r === "null" ? null : +r + "" === r ? +r : D.test(r) ? v.parseJSON(r) : r
} catch (s) {}
v.data(e, n, r)
} else r = t
}
return r
}
function B(e) {
var t;
for (t in e) {
if (t === "data" && v.isEmptyObject(e[t])) continue;
if (t !== "toJSON") return !1
}
return !0
}
function et() {
return !1
}
function tt() {
return !0
}
function ut(e) {
return !e || !e.parentNode || e.parentNode.nodeType === 11
}
function at(e, t) {
do e = e[t]; while (e && e.nodeType !== 1);
return e
}
function ft(e, t, n) {
t = t || 0;
if (v.isFunction(t)) return v.grep(e, function(e, r) {
var i = !!t.call(e, r, e);
return i === n
});
if (t.nodeType) return v.grep(e, function(e, r) {
return e === t === n
});
if (typeof t == "string") {
var r = v.grep(e, function(e) {
return e.nodeType === 1
});
if (it.test(t)) return v.filter(t, r, !n);
t = v.filter(t, r)
}
return v.grep(e, function(e, r) {
return v.inArray(e, t) >= 0 === n
})
}
function lt(e) {
var t = ct.split("|"),
n = e.createDocumentFragment();
if (n.createElement)
while (t.length) n.createElement(t.pop());
return n
}
function Lt(e, t) {
return e.getElementsByTagName(t)[0] || e.appendChild(e.ownerDocument.createElement(t))
}
function At(e, t) {
if (t.nodeType !== 1 || !v.hasData(e)) return;
var n, r, i, s = v._data(e),
o = v._data(t, s),
u = s.events;
if (u) {
delete o.handle, o.events = {};
for (n in u)
for (r = 0, i = u[n].length; r < i; r++) v.event.add(t, n, u[n][r])
}
o.data && (o.data = v.extend({}, o.data))
}
function Ot(e, t) {
var n;
if (t.nodeType !== 1) return;
t.clearAttributes && t.clearAttributes(), t.mergeAttributes && t.mergeAttributes(e), n = t.nodeName.toLowerCase(), n === "object" ? (t.parentNode && (t.outerHTML = e.outerHTML), v.support.html5Clone && e.innerHTML && !v.trim(t.innerHTML) && (t.innerHTML = e.innerHTML)) : n === "input" && Et.test(e.type) ? (t.defaultChecked = t.checked = e.checked, t.value !== e.value && (t.value = e.value)) : n === "option" ? t.selected = e.defaultSelected : n === "input" || n === "textarea" ? t.defaultValue = e.defaultValue : n === "script" && t.text !== e.text && (t.text = e.text), t.removeAttribute(v.expando)
}
function Mt(e) {
return typeof e.getElementsByTagName != "undefined" ? e.getElementsByTagName("*") : typeof e.querySelectorAll != "undefined" ? e.querySelectorAll("*") : []
}
function _t(e) {
Et.test(e.type) && (e.defaultChecked = e.checked)
}
function Qt(e, t) {
if (t in e) return t;
var n = t.charAt(0).toUpperCase() + t.slice(1),
r = t,
i = Jt.length;
while (i--) {
t = Jt[i] + n;
if (t in e) return t
}
return r
}
function Gt(e, t) {
return e = t || e, v.css(e, "display") === "none" || !v.contains(e.ownerDocument, e)
}
function Yt(e, t) {
var n, r, i = [],
s = 0,
o = e.length;
for (; s < o; s++) {
n = e[s];
if (!n.style) continue;
i[s] = v._data(n, "olddisplay"), t ? (!i[s] && n.style.display === "none" && (n.style.display = ""), n.style.display === "" && Gt(n) && (i[s] = v._data(n, "olddisplay", nn(n.nodeName)))) : (r = Dt(n, "display"), !i[s] && r !== "none" && v._data(n, "olddisplay", r))
}
for (s = 0; s < o; s++) {
n = e[s];
if (!n.style) continue;
if (!t || n.style.display === "none" || n.style.display === "") n.style.display = t ? i[s] || "" : "none"
}
return e
}
function Zt(e, t, n) {
var r = Rt.exec(t);
return r ? Math.max(0, r[1] - (n || 0)) + (r[2] || "px") : t
}
function en(e, t, n, r) {
var i = n === (r ? "border" : "content") ? 4 : t === "width" ? 1 : 0,
s = 0;
for (; i < 4; i += 2) n === "margin" && (s += v.css(e, n + $t[i], !0)), r ? (n === "content" && (s -= parseFloat(Dt(e, "padding" + $t[i])) || 0), n !== "margin" && (s -= parseFloat(Dt(e, "border" + $t[i] + "Width")) || 0)) : (s += parseFloat(Dt(e, "padding" + $t[i])) || 0, n !== "padding" && (s += parseFloat(Dt(e, "border" + $t[i] + "Width")) || 0));
return s
}
function tn(e, t, n) {
var r = t === "width" ? e.offsetWidth : e.offsetHeight,
i = !0,
s = v.support.boxSizing && v.css(e, "boxSizing") === "border-box";
if (r <= 0 || r == null) {
r = Dt(e, t);
if (r < 0 || r == null) r = e.style[t];
if (Ut.test(r)) return r;
i = s && (v.support.boxSizingReliable || r === e.style[t]), r = parseFloat(r) || 0
}
return r + en(e, t, n || (s ? "border" : "content"), i) + "px"
}
function nn(e) {
if (Wt[e]) return Wt[e];
var t = v("<" + e + ">").appendTo(i.body),
n = t.css("display");
t.remove();
if (n === "none" || n === "") {
Pt = i.body.appendChild(Pt || v.extend(i.createElement("iframe"), {
frameBorder: 0,
width: 0,
height: 0
}));
if (!Ht || !Pt.createElement) Ht = (Pt.contentWindow || Pt.contentDocument).document, Ht.write("<!doctype html><html><body>"), Ht.close();
t = Ht.body.appendChild(Ht.createElement(e)), n = Dt(t, "display"), i.body.removeChild(Pt)
}
return Wt[e] = n, n
}
function fn(e, t, n, r) {
var i;
if (v.isArray(t)) v.each(t, function(t, i) {
n || sn.test(e) ? r(e, i) : fn(e + "[" + (typeof i == "object" ? t : "") + "]", i, n, r)
});
else if (!n && v.type(t) === "object")
for (i in t) fn(e + "[" + i + "]", t[i], n, r);
else r(e, t)
}
function Cn(e) {
return function(t, n) {
typeof t != "string" && (n = t, t = "*");
var r, i, s, o = t.toLowerCase().split(y),
u = 0,
a = o.length;
if (v.isFunction(n))
for (; u < a; u++) r = o[u], s = /^\+/.test(r), s && (r = r.substr(1) || "*"), i = e[r] = e[r] || [], i[s ? "unshift" : "push"](n)
}
}
function kn(e, n, r, i, s, o) {
s = s || n.dataTypes[0], o = o || {}, o[s] = !0;
var u, a = e[s],
f = 0,
l = a ? a.length : 0,
c = e === Sn;
for (; f < l && (c || !u); f++) u = a[f](n, r, i), typeof u == "string" && (!c || o[u] ? u = t : (n.dataTypes.unshift(u), u = kn(e, n, r, i, u, o)));
return (c || !u) && !o["*"] && (u = kn(e, n, r, i, "*", o)), u
}
function Ln(e, n) {
var r, i, s = v.ajaxSettings.flatOptions || {};
for (r in n) n[r] !== t && ((s[r] ? e : i || (i = {}))[r] = n[r]);
i && v.extend(!0, e, i)
}
function An(e, n, r) {
var i, s, o, u, a = e.contents,
f = e.dataTypes,
l = e.responseFields;
for (s in l) s in r && (n[l[s]] = r[s]);
while (f[0] === "*") f.shift(), i === t && (i = e.mimeType || n.getResponseHeader("content-type"));
if (i)
for (s in a)
if (a[s] && a[s].test(i)) {
f.unshift(s);
break
}
if (f[0] in r) o = f[0];
else {
for (s in r) {
if (!f[0] || e.converters[s + " " + f[0]]) {
o = s;
break
}
u || (u = s)
}
o = o || u
}
if (o) return o !== f[0] && f.unshift(o), r[o]
}
function On(e, t) {
var n, r, i, s, o = e.dataTypes.slice(),
u = o[0],
a = {},
f = 0;
e.dataFilter && (t = e.dataFilter(t, e.dataType));
if (o[1])
for (n in e.converters) a[n.toLowerCase()] = e.converters[n];
for (; i = o[++f];)
if (i !== "*") {
if (u !== "*" && u !== i) {
n = a[u + " " + i] || a["* " + i];
if (!n)
for (r in a) {
s = r.split(" ");
if (s[1] === i) {
n = a[u + " " + s[0]] || a["* " + s[0]];
if (n) {
n === !0 ? n = a[r] : a[r] !== !0 && (i = s[0], o.splice(f--, 0, i));
break
}
}
}
if (n !== !0)
if (n && e["throws"]) t = n(t);
else try {
t = n(t)
} catch (l) {
return {
state: "parsererror",
error: n ? l : "No conversion from " + u + " to " + i
}
}
}
u = i
}
return {
state: "success",
data: t
}
}
function Fn() {
try {
return new e.XMLHttpRequest
} catch (t) {}
}
function In() {
try {
return new e.ActiveXObject("Microsoft.XMLHTTP")
} catch (t) {}
}
function $n() {
return setTimeout(function() {
qn = t
}, 0), qn = v.now()
}
function Jn(e, t) {
v.each(t, function(t, n) {
var r = (Vn[t] || []).concat(Vn["*"]),
i = 0,
s = r.length;
for (; i < s; i++)
if (r[i].call(e, t, n)) return
})
}
function Kn(e, t, n) {
var r, i = 0,
s = 0,
o = Xn.length,
u = v.Deferred().always(function() {
delete a.elem
}),
a = function() {
var t = qn || $n(),
n = Math.max(0, f.startTime + f.duration - t),
r = n / f.duration || 0,
i = 1 - r,
s = 0,
o = f.tweens.length;
for (; s < o; s++) f.tweens[s].run(i);
return u.notifyWith(e, [f, i, n]), i < 1 && o ? n : (u.resolveWith(e, [f]), !1)
},
f = u.promise({
elem: e,
props: v.extend({}, t),
opts: v.extend(!0, {
specialEasing: {}
}, n),
originalProperties: t,
originalOptions: n,
startTime: qn || $n(),
duration: n.duration,
tweens: [],
createTween: function(t, n, r) {
var i = v.Tween(e, f.opts, t, n, f.opts.specialEasing[t] || f.opts.easing);
return f.tweens.push(i), i
},
stop: function(t) {
var n = 0,
r = t ? f.tweens.length : 0;
for (; n < r; n++) f.tweens[n].run(1);
return t ? u.resolveWith(e, [f, t]) : u.rejectWith(e, [f, t]), this
}
}),
l = f.props;
Qn(l, f.opts.specialEasing);
for (; i < o; i++) {
r = Xn[i].call(f, e, l, f.opts);
if (r) return r
}
return Jn(f, l), v.isFunction(f.opts.start) && f.opts.start.call(e, f), v.fx.timer(v.extend(a, {
anim: f,
queue: f.opts.queue,
elem: e
})), f.progress(f.opts.progress).done(f.opts.done, f.opts.complete).fail(f.opts.fail).always(f.opts.always)
}
function Qn(e, t) {
var n, r, i, s, o;
for (n in e) {
r = v.camelCase(n), i = t[r], s = e[n], v.isArray(s) && (i = s[1], s = e[n] = s[0]), n !== r && (e[r] = s, delete e[n]), o = v.cssHooks[r];
if (o && "expand" in o) {
s = o.expand(s), delete e[r];
for (n in s) n in e || (e[n] = s[n], t[n] = i)
} else t[r] = i
}
}
function Gn(e, t, n) {
var r, i, s, o, u, a, f, l, c, h = this,
p = e.style,
d = {},
m = [],
g = e.nodeType && Gt(e);
n.queue || (l = v._queueHooks(e, "fx"), l.unqueued == null && (l.unqueued = 0, c = l.empty.fire, l.empty.fire = function() {
l.unqueued || c()
}), l.unqueued++, h.always(function() {
h.always(function() {
l.unqueued--, v.queue(e, "fx").length || l.empty.fire()
})
})), e.nodeType === 1 && ("height" in t || "width" in t) && (n.overflow = [p.overflow, p.overflowX, p.overflowY], v.css(e, "display") === "inline" && v.css(e, "float") === "none" && (!v.support.inlineBlockNeedsLayout || nn(e.nodeName) === "inline" ? p.display = "inline-block" : p.zoom = 1)), n.overflow && (p.overflow = "hidden", v.support.shrinkWrapBlocks || h.done(function() {
p.overflow = n.overflow[0], p.overflowX = n.overflow[1], p.overflowY = n.overflow[2]
}));
for (r in t) {
s = t[r];
if (Un.exec(s)) {
delete t[r], a = a || s === "toggle";
if (s === (g ? "hide" : "show")) continue;
m.push(r)
}
}
o = m.length;
if (o) {
u = v._data(e, "fxshow") || v._data(e, "fxshow", {}), "hidden" in u && (g = u.hidden), a && (u.hidden = !g), g ? v(e).show() : h.done(function() {
v(e).hide()
}), h.done(function() {
var t;
v.removeData(e, "fxshow", !0);
for (t in d) v.style(e, t, d[t])
});
for (r = 0; r < o; r++) i = m[r], f = h.createTween(i, g ? u[i] : 0), d[i] = u[i] || v.style(e, i), i in u || (u[i] = f.start, g && (f.end = f.start, f.start = i === "width" || i === "height" ? 1 : 0))
}
}
function Yn(e, t, n, r, i) {
return new Yn.prototype.init(e, t, n, r, i)
}
function Zn(e, t) {
var n, r = {
height: e
},
i = 0;
t = t ? 1 : 0;
for (; i < 4; i += 2 - t) n = $t[i], r["margin" + n] = r["padding" + n] = e;
return t && (r.opacity = r.width = e), r
}
function tr(e) {
return v.isWindow(e) ? e : e.nodeType === 9 ? e.defaultView || e.parentWindow : !1
}
var n, r, i = e.document,
s = e.location,
o = e.navigator,
u = e.jQuery,
a = e.$,
f = Array.prototype.push,
l = Array.prototype.slice,
c = Array.prototype.indexOf,
h = Object.prototype.toString,
p = Object.prototype.hasOwnProperty,
d = String.prototype.trim,
v = function(e, t) {
return new v.fn.init(e, t, n)
},
m = /[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source,
g = /\S/,
y = /\s+/,
b = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,
w = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,
E = /^<(\w+)\s*\/?>(?:<\/\1>|)$/,
S = /^[\],:{}\s]*$/,
x = /(?:^|:|,)(?:\s*\[)+/g,
T = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,
N = /"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g,
C = /^-ms-/,
k = /-([\da-z])/gi,
L = function(e, t) {
return (t + "").toUpperCase()
},
A = function() {
i.addEventListener ? (i.removeEventListener("DOMContentLoaded", A, !1), v.ready()) : i.readyState === "complete" && (i.detachEvent("onreadystatechange", A), v.ready())
},
O = {};
v.fn = v.prototype = {
constructor: v,
init: function(e, n, r) {
var s, o, u, a;
if (!e) return this;
if (e.nodeType) return this.context = this[0] = e, this.length = 1, this;
if (typeof e == "string") {
e.charAt(0) === "<" && e.charAt(e.length - 1) === ">" && e.length >= 3 ? s = [null, e, null] : s = w.exec(e);
if (s && (s[1] || !n)) {
if (s[1]) return n = n instanceof v ? n[0] : n, a = n && n.nodeType ? n.ownerDocument || n : i, e = v.parseHTML(s[1], a, !0), E.test(s[1]) && v.isPlainObject(n) && this.attr.call(e, n, !0), v.merge(this, e);
o = i.getElementById(s[2]);
if (o && o.parentNode) {
if (o.id !== s[2]) return r.find(e);
this.length = 1, this[0] = o
}
return this.context = i, this.selector = e, this
}
return !n || n.jquery ? (n || r).find(e) : this.constructor(n).find(e)
}
return v.isFunction(e) ? r.ready(e) : (e.selector !== t && (this.selector = e.selector, this.context = e.context), v.makeArray(e, this))
},
selector: "",
jquery: "1.8.3",
length: 0,
size: function() {
return this.length
},
toArray: function() {
return l.call(this)
},
get: function(e) {
return e == null ? this.toArray() : e < 0 ? this[this.length + e] : this[e]
},
pushStack: function(e, t, n) {
var r = v.merge(this.constructor(), e);
return r.prevObject = this, r.context = this.context, t === "find" ? r.selector = this.selector + (this.selector ? " " : "") + n : t && (r.selector = this.selector + "." + t + "(" + n + ")"), r
},
each: function(e, t) {
return v.each(this, e, t)
},
ready: function(e) {
return v.ready.promise().done(e), this
},
eq: function(e) {
return e = +e, e === -1 ? this.slice(e) : this.slice(e, e + 1)
},
first: function() {
return this.eq(0)
},
last: function() {
return this.eq(-1)
},
slice: function() {
return this.pushStack(l.apply(this, arguments), "slice", l.call(arguments).join(","))
},
map: function(e) {
return this.pushStack(v.map(this, function(t, n) {
return e.call(t, n, t)
}))
},
end: function() {
return this.prevObject || this.constructor(null)
},
push: f,
sort: [].sort,
splice: [].splice
}, v.fn.init.prototype = v.fn, v.extend = v.fn.extend = function() {
var e, n, r, i, s, o, u = arguments[0] || {},
a = 1,
f = arguments.length,
l = !1;
typeof u == "boolean" && (l = u, u = arguments[1] || {}, a = 2), typeof u != "object" && !v.isFunction(u) && (u = {}), f === a && (u = this, --a);
for (; a < f; a++)
if ((e = arguments[a]) != null)
for (n in e) {
r = u[n], i = e[n];
if (u === i) continue;
l && i && (v.isPlainObject(i) || (s = v.isArray(i))) ? (s ? (s = !1, o = r && v.isArray(r) ? r : []) : o = r && v.isPlainObject(r) ? r : {}, u[n] = v.extend(l, o, i)) : i !== t && (u[n] = i)
}
return u
}, v.extend({
noConflict: function(t) {
return e.$ === v && (e.$ = a), t && e.jQuery === v && (e.jQuery = u), v
},
isReady: !1,
readyWait: 1,
holdReady: function(e) {
e ? v.readyWait++ : v.ready(!0)
},
ready: function(e) {
if (e === !0 ? --v.readyWait : v.isReady) return;
if (!i.body) return setTimeout(v.ready, 1);
v.isReady = !0;
if (e !== !0 && --v.readyWait > 0) return;
r.resolveWith(i, [v]), v.fn.trigger && v(i).trigger("ready").off("ready")
},
isFunction: function(e) {
return v.type(e) === "function"
},
isArray: Array.isArray || function(e) {
return v.type(e) === "array"
},
isWindow: function(e) {
return e != null && e == e.window
},
isNumeric: function(e) {
return !isNaN(parseFloat(e)) && isFinite(e)
},
type: function(e) {
return e == null ? String(e) : O[h.call(e)] || "object"
},
isPlainObject: function(e) {
if (!e || v.type(e) !== "object" || e.nodeType || v.isWindow(e)) return !1;
try {
if (e.constructor && !p.call(e, "constructor") && !p.call(e.constructor.prototype, "isPrototypeOf")) return !1
} catch (n) {
return !1
}
var r;
for (r in e);
return r === t || p.call(e, r)
},
isEmptyObject: function(e) {
var t;
for (t in e) return !1;
return !0
},
error: function(e) {
throw new Error(e)
},
parseHTML: function(e, t, n) {
var r;
return !e || typeof e != "string" ? null : (typeof t == "boolean" && (n = t, t = 0), t = t || i, (r = E.exec(e)) ? [t.createElement(r[1])] : (r = v.buildFragment([e], t, n ? null : []), v.merge([], (r.cacheable ? v.clone(r.fragment) : r.fragment).childNodes)))
},
parseJSON: function(t) {
if (!t || typeof t != "string") return null;
t = v.trim(t);
if (e.JSON && e.JSON.parse) return e.JSON.parse(t);
if (S.test(t.replace(T, "@").replace(N, "]").replace(x, ""))) return (new Function("return " + t))();
v.error("Invalid JSON: " + t)
},
parseXML: function(n) {
var r, i;
if (!n || typeof n != "string") return null;
try {
e.DOMParser ? (i = new DOMParser, r = i.parseFromString(n, "text/xml")) : (r = new ActiveXObject("Microsoft.XMLDOM"), r.async = "false", r.loadXML(n))
} catch (s) {
r = t
}
return (!r || !r.documentElement || r.getElementsByTagName("parsererror").length) && v.error("Invalid XML: " + n), r
},
noop: function() {},
globalEval: function(t) {
t && g.test(t) && (e.execScript || function(t) {
e.eval.call(e, t)
})(t)
},
camelCase: function(e) {
return e.replace(C, "ms-").replace(k, L)
},
nodeName: function(e, t) {
return e.nodeName && e.nodeName.toLowerCase() === t.toLowerCase()
},
each: function(e, n, r) {
var i, s = 0,
o = e.length,
u = o === t || v.isFunction(e);
if (r) {
if (u) {
for (i in e)
if (n.apply(e[i], r) === !1) break
} else
for (; s < o;)
if (n.apply(e[s++], r) === !1) break
} else if (u) {
for (i in e)
if (n.call(e[i], i, e[i]) === !1) break
} else
for (; s < o;)
if (n.call(e[s], s, e[s++]) === !1) break; return e
},
trim: d && !d.call(" ") ? function(e) {
return e == null ? "" : d.call(e)
} : function(e) {
return e == null ? "" : (e + "").replace(b, "")
},
makeArray: function(e, t) {
var n, r = t || [];
return e != null && (n = v.type(e), e.length == null || n === "string" || n === "function" || n === "regexp" || v.isWindow(e) ? f.call(r, e) : v.merge(r, e)), r
},
inArray: function(e, t, n) {
var r;
if (t) {
if (c) return c.call(t, e, n);
r = t.length, n = n ? n < 0 ? Math.max(0, r + n) : n : 0;
for (; n < r; n++)
if (n in t && t[n] === e) return n
}
return -1
},
merge: function(e, n) {
var r = n.length,
i = e.length,
s = 0;
if (typeof r == "number")
for (; s < r; s++) e[i++] = n[s];
else
while (n[s] !== t) e[i++] = n[s++];
return e.length = i, e
},
grep: function(e, t, n) {
var r, i = [],
s = 0,
o = e.length;
n = !!n;
for (; s < o; s++) r = !!t(e[s], s), n !== r && i.push(e[s]);
return i
},
map: function(e, n, r) {
var i, s, o = [],
u = 0,
a = e.length,
f = e instanceof v || a !== t && typeof a == "number" && (a > 0 && e[0] && e[a - 1] || a === 0 || v.isArray(e));
if (f)
for (; u < a; u++) i = n(e[u], u, r), i != null && (o[o.length] = i);
else
for (s in e) i = n(e[s], s, r), i != null && (o[o.length] = i);
return o.concat.apply([], o)
},
guid: 1,
proxy: function(e, n) {
var r, i, s;
return typeof n == "string" && (r = e[n], n = e, e = r), v.isFunction(e) ? (i = l.call(arguments, 2), s = function() {
return e.apply(n, i.concat(l.call(arguments)))
}, s.guid = e.guid = e.guid || v.guid++, s) : t
},
access: function(e, n, r, i, s, o, u) {
var a, f = r == null,
l = 0,
c = e.length;
if (r && typeof r == "object") {
for (l in r) v.access(e, n, l, r[l], 1, o, i);
s = 1
} else if (i !== t) {
a = u === t && v.isFunction(i), f && (a ? (a = n, n = function(e, t, n) {
return a.call(v(e), n)
}) : (n.call(e, i), n = null));
if (n)
for (; l < c; l++) n(e[l], r, a ? i.call(e[l], l, n(e[l], r)) : i, u);
s = 1
}
return s ? e : f ? n.call(e) : c ? n(e[0], r) : o
},
now: function() {
return (new Date).getTime()
}
}), v.ready.promise = function(t) {
if (!r) {
r = v.Deferred();
if (i.readyState === "complete") setTimeout(v.ready, 1);
else if (i.addEventListener) i.addEventListener("DOMContentLoaded", A, !1), e.addEventListener("load", v.ready, !1);
else {
i.attachEvent("onreadystatechange", A), e.attachEvent("onload", v.ready);
var n = !1;
try {
n = e.frameElement == null && i.documentElement
} catch (s) {}
n && n.doScroll && function o() {
if (!v.isReady) {
try {
n.doScroll("left")
} catch (e) {
return setTimeout(o, 50)
}
v.ready()
}
}()
}
}
return r.promise(t)
}, v.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(e, t) {
O["[object " + t + "]"] = t.toLowerCase()
}), n = v(i);
var M = {};
v.Callbacks = function(e) {
e = typeof e == "string" ? M[e] || _(e) : v.extend({}, e);
var n, r, i, s, o, u, a = [],
f = !e.once && [],
l = function(t) {
n = e.memory && t, r = !0, u = s || 0, s = 0, o = a.length, i = !0;
for (; a && u < o; u++)
if (a[u].apply(t[0], t[1]) === !1 && e.stopOnFalse) {
n = !1;
break
}
i = !1, a && (f ? f.length && l(f.shift()) : n ? a = [] : c.disable())
},
c = {
add: function() {
if (a) {
var t = a.length;
(function r(t) {
v.each(t, function(t, n) {
var i = v.type(n);
i === "function" ? (!e.unique || !c.has(n)) && a.push(n) : n && n.length && i !== "string" && r(n)
})
})(arguments), i ? o = a.length : n && (s = t, l(n))
}
return this
},
remove: function() {
return a && v.each(arguments, function(e, t) {
var n;
while ((n = v.inArray(t, a, n)) > -1) a.splice(n, 1), i && (n <= o && o--, n <= u && u--)
}), this
},
has: function(e) {
return v.inArray(e, a) > -1
},
empty: function() {
return a = [], this
},
disable: function() {
return a = f = n = t, this
},
disabled: function() {
return !a
},
lock: function() {
return f = t, n || c.disable(), this
},
locked: function() {
return !f
},
fireWith: function(e, t) {
return t = t || [], t = [e, t.slice ? t.slice() : t], a && (!r || f) && (i ? f.push(t) : l(t)), this
},
fire: function() {
return c.fireWith(this, arguments), this
},
fired: function() {
return !!r
}
};
return c
}, v.extend({
Deferred: function(e) {
var t = [
["resolve", "done", v.Callbacks("once memory"), "resolved"],
["reject", "fail", v.Callbacks("once memory"), "rejected"],
["notify", "progress", v.Callbacks("memory")]
],
n = "pending",
r = {
state: function() {
return n
},
always: function() {
return i.done(arguments).fail(arguments), this
},
then: function() {
var e = arguments;
return v.Deferred(function(n) {
v.each(t, function(t, r) {
var s = r[0],
o = e[t];
i[r[1]](v.isFunction(o) ? function() {
var e = o.apply(this, arguments);
e && v.isFunction(e.promise) ? e.promise().done(n.resolve).fail(n.reject).progress(n.notify) : n[s + "With"](this === i ? n : this, [e])
} : n[s])
}), e = null
}).promise()
},
promise: function(e) {
return e != null ? v.extend(e, r) : r
}
},
i = {};
return r.pipe = r.then, v.each(t, function(e, s) {
var o = s[2],
u = s[3];
r[s[1]] = o.add, u && o.add(function() {
n = u
}, t[e ^ 1][2].disable, t[2][2].lock), i[s[0]] = o.fire, i[s[0] + "With"] = o.fireWith
}), r.promise(i), e && e.call(i, i), i
},
when: function(e) {
var t = 0,
n = l.call(arguments),
r = n.length,
i = r !== 1 || e && v.isFunction(e.promise) ? r : 0,
s = i === 1 ? e : v.Deferred(),
o = function(e, t, n) {
return function(r) {
t[e] = this, n[e] = arguments.length > 1 ? l.call(arguments) : r, n === u ? s.notifyWith(t, n) : --i || s.resolveWith(t, n)
}
},
u, a, f;
if (r > 1) {
u = new Array(r), a = new Array(r), f = new Array(r);
for (; t < r; t++) n[t] && v.isFunction(n[t].promise) ? n[t].promise().done(o(t, f, n)).fail(s.reject).progress(o(t, a, u)) : --i
}
return i || s.resolveWith(f, n), s.promise()
}
}), v.support = function() {
var t, n, r, s, o, u, a, f, l, c, h, p = i.createElement("div");
p.setAttribute("className", "t"), p.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>", n = p.getElementsByTagName("*"), r = p.getElementsByTagName("a")[0];
if (!n || !r || !n.length) return {};
s = i.createElement("select"), o = s.appendChild(i.createElement("option")), u = p.getElementsByTagName("input")[0], r.style.cssText = "top:1px;float:left;opacity:.5", t = {
leadingWhitespace: p.firstChild.nodeType === 3,
tbody: !p.getElementsByTagName("tbody").length,
htmlSerialize: !!p.getElementsByTagName("link").length,
style: /top/.test(r.getAttribute("style")),
hrefNormalized: r.getAttribute("href") === "/a",
opacity: /^0.5/.test(r.style.opacity),
cssFloat: !!r.style.cssFloat,
checkOn: u.value === "on",
optSelected: o.selected,
getSetAttribute: p.className !== "t",
enctype: !!i.createElement("form").enctype,
html5Clone: i.createElement("nav").cloneNode(!0).outerHTML !== "<:nav></:nav>",
boxModel: i.compatMode === "CSS1Compat",
submitBubbles: !0,
changeBubbles: !0,
focusinBubbles: !1,
deleteExpando: !0,
noCloneEvent: !0,
inlineBlockNeedsLayout: !1,
shrinkWrapBlocks: !1,
reliableMarginRight: !0,
boxSizingReliable: !0,
pixelPosition: !1
}, u.checked = !0, t.noCloneChecked = u.cloneNode(!0).checked, s.disabled = !0, t.optDisabled = !o.disabled;
try {
delete p.test
} catch (d) {
t.deleteExpando = !1
}!p.addEventListener && p.attachEvent && p.fireEvent && (p.attachEvent("onclick", h = function() {
t.noCloneEvent = !1
}), p.cloneNode(!0).fireEvent("onclick"), p.detachEvent("onclick", h)), u = i.createElement("input"), u.value = "t", u.setAttribute("type", "radio"), t.radioValue = u.value === "t", u.setAttribute("checked", "checked"), u.setAttribute("name", "t"), p.appendChild(u), a = i.createDocumentFragment(), a.appendChild(p.lastChild), t.checkClone = a.cloneNode(!0).cloneNode(!0).lastChild.checked, t.appendChecked = u.checked, a.removeChild(u), a.appendChild(p);
if (p.attachEvent)
for (l in {
submit: !0,
change: !0,
focusin: !0
}) f = "on" + l, c = f in p, c || (p.setAttribute(f, "return;"), c = typeof p[f] == "function"), t[l + "Bubbles"] = c;
return v(function() {
var n, r, s, o, u = "padding:0;margin:0;border:0;display:block;overflow:hidden;",
a = i.getElementsByTagName("body")[0];
if (!a) return;
n = i.createElement("div"), n.style.cssText = "visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px", a.insertBefore(n, a.firstChild), r = i.createElement("div"), n.appendChild(r), r.innerHTML = "<table><tr><td></td><td>t</td></tr></table>", s = r.getElementsByTagName("td"), s[0].style.cssText = "padding:0;margin:0;border:0;display:none", c = s[0].offsetHeight === 0, s[0].style.display = "", s[1].style.display = "none", t.reliableHiddenOffsets = c && s[0].offsetHeight === 0, r.innerHTML = "", r.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;", t.boxSizing = r.offsetWidth === 4, t.doesNotIncludeMarginInBodyOffset = a.offsetTop !== 1, e.getComputedStyle && (t.pixelPosition = (e.getComputedStyle(r, null) || {}).top !== "1%", t.boxSizingReliable = (e.getComputedStyle(r, null) || {
width: "4px"
}).width === "4px", o = i.createElement("div"), o.style.cssText = r.style.cssText = u, o.style.marginRight = o.style.width = "0", r.style.width = "1px", r.appendChild(o), t.reliableMarginRight = !parseFloat((e.getComputedStyle(o, null) || {}).marginRight)), typeof r.style.zoom != "undefined" && (r.innerHTML = "", r.style.cssText = u + "width:1px;padding:1px;display:inline;zoom:1", t.inlineBlockNeedsLayout = r.offsetWidth === 3, r.style.display = "block", r.style.overflow = "visible", r.innerHTML = "<div></div>", r.firstChild.style.width = "5px", t.shrinkWrapBlocks = r.offsetWidth !== 3, n.style.zoom = 1), a.removeChild(n), n = r = s = o = null
}), a.removeChild(p), n = r = s = o = u = a = p = null, t
}();
var D = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/,
P = /([A-Z])/g;
v.extend({
cache: {},
deletedIds: [],
uuid: 0,
expando: "jQuery" + (v.fn.jquery + Math.random()).replace(/\D/g, ""),
noData: {
embed: !0,
object: "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",
applet: !0
},
hasData: function(e) {
return e = e.nodeType ? v.cache[e[v.expando]] : e[v.expando], !!e && !B(e)
},
data: function(e, n, r, i) {
if (!v.acceptData(e)) return;
var s, o, u = v.expando,
a = typeof n == "string",
f = e.nodeType,
l = f ? v.cache : e,
c = f ? e[u] : e[u] && u;
if ((!c || !l[c] || !i && !l[c].data) && a && r === t) return;
c || (f ? e[u] = c = v.deletedIds.pop() || v.guid++ : c = u), l[c] || (l[c] = {}, f || (l[c].toJSON = v.noop));
if (typeof n == "object" || typeof n == "function") i ? l[c] = v.extend(l[c], n) : l[c].data = v.extend(l[c].data, n);
return s = l[c], i || (s.data || (s.data = {}), s = s.data), r !== t && (s[v.camelCase(n)] = r), a ? (o = s[n], o == null && (o = s[v.camelCase(n)])) : o = s, o
},
removeData: function(e, t, n) {
if (!v.acceptData(e)) return;
var r, i, s, o = e.nodeType,
u = o ? v.cache : e,
a = o ? e[v.expando] : v.expando;
if (!u[a]) return;
if (t) {
r = n ? u[a] : u[a].data;
if (r) {
v.isArray(t) || (t in r ? t = [t] : (t = v.camelCase(t), t in r ? t = [t] : t = t.split(" ")));
for (i = 0, s = t.length; i < s; i++) delete r[t[i]];
if (!(n ? B : v.isEmptyObject)(r)) return
}
}
if (!n) {
delete u[a].data;
if (!B(u[a])) return
}
o ? v.cleanData([e], !0) : v.support.deleteExpando || u != u.window ? delete u[a] : u[a] = null
},
_data: function(e, t, n) {
return v.data(e, t, n, !0)
},
acceptData: function(e) {
var t = e.nodeName && v.noData[e.nodeName.toLowerCase()];
return !t || t !== !0 && e.getAttribute("classid") === t
}
}), v.fn.extend({
data: function(e, n) {
var r, i, s, o, u, a = this[0],
f = 0,
l = null;
if (e === t) {
if (this.length) {
l = v.data(a);
if (a.nodeType === 1 && !v._data(a, "parsedAttrs")) {
s = a.attributes;
for (u = s.length; f < u; f++) o = s[f].name, o.indexOf("data-") || (o = v.camelCase(o.substring(5)), H(a, o, l[o]));
v._data(a, "parsedAttrs", !0)
}
}
return l
}
return typeof e == "object" ? this.each(function() {
v.data(this, e)
}) : (r = e.split(".", 2), r[1] = r[1] ? "." + r[1] : "", i = r[1] + "!", v.access(this, function(n) {
if (n === t) return l = this.triggerHandler("getData" + i, [r[0]]), l === t && a && (l = v.data(a, e), l = H(a, e, l)), l === t && r[1] ? this.data(r[0]) : l;
r[1] = n, this.each(function() {
var t = v(this);
t.triggerHandler("setData" + i, r), v.data(this, e, n), t.triggerHandler("changeData" + i, r)
})
}, null, n, arguments.length > 1, null, !1))
},
removeData: function(e) {
return this.each(function() {
v.removeData(this, e)
})
}
}), v.extend({
queue: function(e, t, n) {
var r;
if (e) return t = (t || "fx") + "queue", r = v._data(e, t), n && (!r || v.isArray(n) ? r = v._data(e, t, v.makeArray(n)) : r.push(n)), r || []
},
dequeue: function(e, t) {
t = t || "fx";
var n = v.queue(e, t),
r = n.length,
i = n.shift(),
s = v._queueHooks(e, t),
o = function() {
v.dequeue(e, t)
};
i === "inprogress" && (i = n.shift(), r--), i && (t === "fx" && n.unshift("inprogress"), delete s.stop, i.call(e, o, s)), !r && s && s.empty.fire()
},
_queueHooks: function(e, t) {
var n = t + "queueHooks";
return v._data(e, n) || v._data(e, n, {
empty: v.Callbacks("once memory").add(function() {
v.removeData(e, t + "queue", !0), v.removeData(e, n, !0)
})
})
}
}), v.fn.extend({
queue: function(e, n) {
var r = 2;
return typeof e != "string" && (n = e, e = "fx", r--), arguments.length < r ? v.queue(this[0], e) : n === t ? this : this.each(function() {
var t = v.queue(this, e, n);
v._queueHooks(this, e), e === "fx" && t[0] !== "inprogress" && v.dequeue(this, e)
})
},
dequeue: function(e) {
return this.each(function() {
v.dequeue(this, e)
})
},
delay: function(e, t) {
return e = v.fx ? v.fx.speeds[e] || e : e, t = t || "fx", this.queue(t, function(t, n) {
var r = setTimeout(t, e);
n.stop = function() {
clearTimeout(r)
}
})
},
clearQueue: function(e) {
return this.queue(e || "fx", [])
},
promise: function(e, n) {
var r, i = 1,
s = v.Deferred(),
o = this,
u = this.length,
a = function() {
--i || s.resolveWith(o, [o])
};
typeof e != "string" && (n = e, e = t), e = e || "fx";
while (u--) r = v._data(o[u], e + "queueHooks"), r && r.empty && (i++, r.empty.add(a));
return a(), s.promise(n)
}
});
var j, F, I, q = /[\t\r\n]/g,
R = /\r/g,
U = /^(?:button|input)$/i,
z = /^(?:button|input|object|select|textarea)$/i,
W = /^a(?:rea|)$/i,
X = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,
V = v.support.getSetAttribute;
v.fn.extend({
attr: function(e, t) {
return v.access(this, v.attr, e, t, arguments.length > 1)
},
removeAttr: function(e) {
return this.each(function() {
v.removeAttr(this, e)
})
},
prop: function(e, t) {
return v.access(this, v.prop, e, t, arguments.length > 1)
},
removeProp: function(e) {
return e = v.propFix[e] || e, this.each(function() {
try {
this[e] = t, delete this[e]
} catch (n) {}
})
},
addClass: function(e) {
var t, n, r, i, s, o, u;
if (v.isFunction(e)) return this.each(function(t) {
v(this).addClass(e.call(this, t, this.className))
});
if (e && typeof e == "string") {
t = e.split(y);
for (n = 0, r = this.length; n < r; n++) {
i = this[n];
if (i.nodeType === 1)
if (!i.className && t.length === 1) i.className = e;
else {
s = " " + i.className + " ";
for (o = 0, u = t.length; o < u; o++) s.indexOf(" " + t[o] + " ") < 0 && (s += t[o] + " ");
i.className = v.trim(s)
}
}
}
return this
},
removeClass: function(e) {
var n, r, i, s, o, u, a;
if (v.isFunction(e)) return this.each(function(t) {
v(this).removeClass(e.call(this, t, this.className))
});
if (e && typeof e == "string" || e === t) {
n = (e || "").split(y);
for (u = 0, a = this.length; u < a; u++) {
i = this[u];
if (i.nodeType === 1 && i.className) {
r = (" " + i.className + " ").replace(q, " ");
for (s = 0, o = n.length; s < o; s++)
while (r.indexOf(" " + n[s] + " ") >= 0) r = r.replace(" " + n[s] + " ", " ");
i.className = e ? v.trim(r) : ""
}
}
}
return this
},
toggleClass: function(e, t) {
var n = typeof e,
r = typeof t == "boolean";
return v.isFunction(e) ? this.each(function(n) {
v(this).toggleClass(e.call(this, n, this.className, t), t)
}) : this.each(function() {
if (n === "string") {
var i, s = 0,
o = v(this),
u = t,
a = e.split(y);
while (i = a[s++]) u = r ? u : !o.hasClass(i), o[u ? "addClass" : "removeClass"](i)
} else if (n === "undefined" || n === "boolean") this.className && v._data(this, "__className__", this.className), this.className = this.className || e === !1 ? "" : v._data(this, "__className__") || ""
})
},
hasClass: function(e) {
var t = " " + e + " ",
n = 0,
r = this.length;
for (; n < r; n++)
if (this[n].nodeType === 1 && (" " + this[n].className + " ").replace(q, " ").indexOf(t) >= 0) return !0;
return !1
},
val: function(e) {
var n, r, i, s = this[0];
if (!arguments.length) {
if (s) return n = v.valHooks[s.type] || v.valHooks[s.nodeName.toLowerCase()], n && "get" in n && (r = n.get(s, "value")) !== t ? r : (r = s.value, typeof r == "string" ? r.replace(R, "") : r == null ? "" : r);
return
}
return i = v.isFunction(e), this.each(function(r) {
var s, o = v(this);
if (this.nodeType !== 1) return;
i ? s = e.call(this, r, o.val()) : s = e, s == null ? s = "" : typeof s == "number" ? s += "" : v.isArray(s) && (s = v.map(s, function(e) {
return e == null ? "" : e + ""
})), n = v.valHooks[this.type] || v.valHooks[this.nodeName.toLowerCase()];
if (!n || !("set" in n) || n.set(this, s, "value") === t) this.value = s
})
}
}), v.extend({
valHooks: {
option: {
get: function(e) {
var t = e.attributes.value;
return !t || t.specified ? e.value : e.text
}
},
select: {
get: function(e) {
var t, n, r = e.options,
i = e.selectedIndex,
s = e.type === "select-one" || i < 0,
o = s ? null : [],
u = s ? i + 1 : r.length,
a = i < 0 ? u : s ? i : 0;
for (; a < u; a++) {
n = r[a];
if ((n.selected || a === i) && (v.support.optDisabled ? !n.disabled : n.getAttribute("disabled") === null) && (!n.parentNode.disabled || !v.nodeName(n.parentNode, "optgroup"))) {
t = v(n).val();
if (s) return t;
o.push(t)
}
}
return o
},
set: function(e, t) {
var n = v.makeArray(t);
return v(e).find("option").each(function() {
this.selected = v.inArray(v(this).val(), n) >= 0
}), n.length || (e.selectedIndex = -1), n
}
}
},
attrFn: {},
attr: function(e, n, r, i) {
var s, o, u, a = e.nodeType;
if (!e || a === 3 || a === 8 || a === 2) return;
if (i && v.isFunction(v.fn[n])) return v(e)[n](r);
if (typeof e.getAttribute == "undefined") return v.prop(e, n, r);
u = a !== 1 || !v.isXMLDoc(e), u && (n = n.toLowerCase(), o = v.attrHooks[n] || (X.test(n) ? F : j));
if (r !== t) {
if (r === null) {
v.removeAttr(e, n);
return
}
return o && "set" in o && u && (s = o.set(e, r, n)) !== t ? s : (e.setAttribute(n, r + ""), r)
}
return o && "get" in o && u && (s = o.get(e, n)) !== null ? s : (s = e.getAttribute(n), s === null ? t : s)
},
removeAttr: function(e, t) {
var n, r, i, s, o = 0;
if (t && e.nodeType === 1) {
r = t.split(y);
for (; o < r.length; o++) i = r[o], i && (n = v.propFix[i] || i, s = X.test(i), s || v.attr(e, i, ""), e.removeAttribute(V ? i : n), s && n in e && (e[n] = !1))
}
},
attrHooks: {
type: {
set: function(e, t) {
if (U.test(e.nodeName) && e.parentNode) v.error("type property can't be changed");
else if (!v.support.radioValue && t === "radio" && v.nodeName(e, "input")) {
var n = e.value;
return e.setAttribute("type", t), n && (e.value = n), t
}
}
},
value: {
get: function(e, t) {
return j && v.nodeName(e, "button") ? j.get(e, t) : t in e ? e.value : null
},
set: function(e, t, n) {
if (j && v.nodeName(e, "button")) return j.set(e, t, n);
e.value = t
}
}
},
propFix: {
tabindex: "tabIndex",
readonly: "readOnly",
"for": "htmlFor",
"class": "className",
maxlength: "maxLength",
cellspacing: "cellSpacing",
cellpadding: "cellPadding",
rowspan: "rowSpan",
colspan: "colSpan",
usemap: "useMap",
frameborder: "frameBorder",
contenteditable: "contentEditable"
},
prop: function(e, n, r) {
var i, s, o, u = e.nodeType;
if (!e || u === 3 || u === 8 || u === 2) return;
return o = u !== 1 || !v.isXMLDoc(e), o && (n = v.propFix[n] || n, s = v.propHooks[n]), r !== t ? s && "set" in s && (i = s.set(e, r, n)) !== t ? i : e[n] = r : s && "get" in s && (i = s.get(e, n)) !== null ? i : e[n]
},
propHooks: {
tabIndex: {
get: function(e) {
var n = e.getAttributeNode("tabindex");
return n && n.specified ? parseInt(n.value, 10) : z.test(e.nodeName) || W.test(e.nodeName) && e.href ? 0 : t
}
}
}
}), F = {
get: function(e, n) {
var r, i = v.prop(e, n);
return i === !0 || typeof i != "boolean" && (r = e.getAttributeNode(n)) && r.nodeValue !== !1 ? n.toLowerCase() : t
},
set: function(e, t, n) {
var r;
return t === !1 ? v.removeAttr(e, n) : (r = v.propFix[n] || n, r in e && (e[r] = !0), e.setAttribute(n, n.toLowerCase())), n
}
}, V || (I = {
name: !0,
id: !0,
coords: !0
}, j = v.valHooks.button = {
get: function(e, n) {
var r;
return r = e.getAttributeNode(n), r && (I[n] ? r.value !== "" : r.specified) ? r.value : t
},
set: function(e, t, n) {
var r = e.getAttributeNode(n);
return r || (r = i.createAttribute(n), e.setAttributeNode(r)), r.value = t + ""
}
}, v.each(["width", "height"], function(e, t) {
v.attrHooks[t] = v.extend(v.attrHooks[t], {
set: function(e, n) {
if (n === "") return e.setAttribute(t, "auto"), n
}
})
}), v.attrHooks.contenteditable = {
get: j.get,
set: function(e, t, n) {
t === "" && (t = "false"), j.set(e, t, n)
}
}), v.support.hrefNormalized || v.each(["href", "src", "width", "height"], function(e, n) {
v.attrHooks[n] = v.extend(v.attrHooks[n], {
get: function(e) {
var r = e.getAttribute(n, 2);
return r === null ? t : r
}
})
}), v.support.style || (v.attrHooks.style = {
get: function(e) {
return e.style.cssText.toLowerCase() || t
},
set: function(e,
t) {
return e.style.cssText = t + ""
}
}), v.support.optSelected || (v.propHooks.selected = v.extend(v.propHooks.selected, {
get: function(e) {
var t = e.parentNode;
return t && (t.selectedIndex, t.parentNode && t.parentNode.selectedIndex), null
}
})), v.support.enctype || (v.propFix.enctype = "encoding"), v.support.checkOn || v.each(["radio", "checkbox"], function() {
v.valHooks[this] = {
get: function(e) {
return e.getAttribute("value") === null ? "on" : e.value
}
}
}), v.each(["radio", "checkbox"], function() {
v.valHooks[this] = v.extend(v.valHooks[this], {
set: function(e, t) {
if (v.isArray(t)) return e.checked = v.inArray(v(e).val(), t) >= 0
}
})
});
var $ = /^(?:textarea|input|select)$/i,
J = /^([^\.]*|)(?:\.(.+)|)$/,
K = /(?:^|\s)hover(\.\S+|)\b/,
Q = /^key/,
G = /^(?:mouse|contextmenu)|click/,
Y = /^(?:focusinfocus|focusoutblur)$/,
Z = function(e) {
return v.event.special.hover ? e : e.replace(K, "mouseenter$1 mouseleave$1")
};
v.event = {
add: function(e, n, r, i, s) {
var o, u, a, f, l, c, h, p, d, m, g;
if (e.nodeType === 3 || e.nodeType === 8 || !n || !r || !(o = v._data(e))) return;
r.handler && (d = r, r = d.handler, s = d.selector), r.guid || (r.guid = v.guid++), a = o.events, a || (o.events = a = {}), u = o.handle, u || (o.handle = u = function(e) {
return typeof v == "undefined" || !!e && v.event.triggered === e.type ? t : v.event.dispatch.apply(u.elem, arguments)
}, u.elem = e), n = v.trim(Z(n)).split(" ");
for (f = 0; f < n.length; f++) {
l = J.exec(n[f]) || [], c = l[1], h = (l[2] || "").split(".").sort(), g = v.event.special[c] || {}, c = (s ? g.delegateType : g.bindType) || c, g = v.event.special[c] || {}, p = v.extend({
type: c,
origType: l[1],
data: i,
handler: r,
guid: r.guid,
selector: s,
needsContext: s && v.expr.match.needsContext.test(s),
namespace: h.join(".")
}, d), m = a[c];
if (!m) {
m = a[c] = [], m.delegateCount = 0;
if (!g.setup || g.setup.call(e, i, h, u) === !1) e.addEventListener ? e.addEventListener(c, u, !1) : e.attachEvent && e.attachEvent("on" + c, u)
}
g.add && (g.add.call(e, p), p.handler.guid || (p.handler.guid = r.guid)), s ? m.splice(m.delegateCount++, 0, p) : m.push(p), v.event.global[c] = !0
}
e = null
},
global: {},
remove: function(e, t, n, r, i) {
var s, o, u, a, f, l, c, h, p, d, m, g = v.hasData(e) && v._data(e);
if (!g || !(h = g.events)) return;
t = v.trim(Z(t || "")).split(" ");
for (s = 0; s < t.length; s++) {
o = J.exec(t[s]) || [], u = a = o[1], f = o[2];
if (!u) {
for (u in h) v.event.remove(e, u + t[s], n, r, !0);
continue
}
p = v.event.special[u] || {}, u = (r ? p.delegateType : p.bindType) || u, d = h[u] || [], l = d.length, f = f ? new RegExp("(^|\\.)" + f.split(".").sort().join("\\.(?:.*\\.|)") + "(\\.|$)") : null;
for (c = 0; c < d.length; c++) m = d[c], (i || a === m.origType) && (!n || n.guid === m.guid) && (!f || f.test(m.namespace)) && (!r || r === m.selector || r === "**" && m.selector) && (d.splice(c--, 1), m.selector && d.delegateCount--, p.remove && p.remove.call(e, m));
d.length === 0 && l !== d.length && ((!p.teardown || p.teardown.call(e, f, g.handle) === !1) && v.removeEvent(e, u, g.handle), delete h[u])
}
v.isEmptyObject(h) && (delete g.handle, v.removeData(e, "events", !0))
},
customEvent: {
getData: !0,
setData: !0,
changeData: !0
},
trigger: function(n, r, s, o) {
if (!s || s.nodeType !== 3 && s.nodeType !== 8) {
var u, a, f, l, c, h, p, d, m, g, y = n.type || n,
b = [];
if (Y.test(y + v.event.triggered)) return;
y.indexOf("!") >= 0 && (y = y.slice(0, -1), a = !0), y.indexOf(".") >= 0 && (b = y.split("."), y = b.shift(), b.sort());
if ((!s || v.event.customEvent[y]) && !v.event.global[y]) return;
n = typeof n == "object" ? n[v.expando] ? n : new v.Event(y, n) : new v.Event(y), n.type = y, n.isTrigger = !0, n.exclusive = a, n.namespace = b.join("."), n.namespace_re = n.namespace ? new RegExp("(^|\\.)" + b.join("\\.(?:.*\\.|)") + "(\\.|$)") : null, h = y.indexOf(":") < 0 ? "on" + y : "";
if (!s) {
u = v.cache;
for (f in u) u[f].events && u[f].events[y] && v.event.trigger(n, r, u[f].handle.elem, !0);
return
}
n.result = t, n.target || (n.target = s), r = r != null ? v.makeArray(r) : [], r.unshift(n), p = v.event.special[y] || {};
if (p.trigger && p.trigger.apply(s, r) === !1) return;
m = [
[s, p.bindType || y]
];
if (!o && !p.noBubble && !v.isWindow(s)) {
g = p.delegateType || y, l = Y.test(g + y) ? s : s.parentNode;
for (c = s; l; l = l.parentNode) m.push([l, g]), c = l;
c === (s.ownerDocument || i) && m.push([c.defaultView || c.parentWindow || e, g])
}
for (f = 0; f < m.length && !n.isPropagationStopped(); f++) l = m[f][0], n.type = m[f][1], d = (v._data(l, "events") || {})[n.type] && v._data(l, "handle"), d && d.apply(l, r), d = h && l[h], d && v.acceptData(l) && d.apply && d.apply(l, r) === !1 && n.preventDefault();
return n.type = y, !o && !n.isDefaultPrevented() && (!p._default || p._default.apply(s.ownerDocument, r) === !1) && (y !== "click" || !v.nodeName(s, "a")) && v.acceptData(s) && h && s[y] && (y !== "focus" && y !== "blur" || n.target.offsetWidth !== 0) && !v.isWindow(s) && (c = s[h], c && (s[h] = null), v.event.triggered = y, s[y](), v.event.triggered = t, c && (s[h] = c)), n.result
}
return
},
dispatch: function(n) {
n = v.event.fix(n || e.event);
var r, i, s, o, u, a, f, c, h, p, d = (v._data(this, "events") || {})[n.type] || [],
m = d.delegateCount,
g = l.call(arguments),
y = !n.exclusive && !n.namespace,
b = v.event.special[n.type] || {},
w = [];
g[0] = n, n.delegateTarget = this;
if (b.preDispatch && b.preDispatch.call(this, n) === !1) return;
if (m && (!n.button || n.type !== "click"))
for (s = n.target; s != this; s = s.parentNode || this)
if (s.disabled !== !0 || n.type !== "click") {
u = {}, f = [];
for (r = 0; r < m; r++) c = d[r], h = c.selector, u[h] === t && (u[h] = c.needsContext ? v(h, this).index(s) >= 0 : v.find(h, this, null, [s]).length), u[h] && f.push(c);
f.length && w.push({
elem: s,
matches: f
})
}
d.length > m && w.push({
elem: this,
matches: d.slice(m)
});
for (r = 0; r < w.length && !n.isPropagationStopped(); r++) {
a = w[r], n.currentTarget = a.elem;
for (i = 0; i < a.matches.length && !n.isImmediatePropagationStopped(); i++) {
c = a.matches[i];
if (y || !n.namespace && !c.namespace || n.namespace_re && n.namespace_re.test(c.namespace)) n.data = c.data, n.handleObj = c, o = ((v.event.special[c.origType] || {}).handle || c.handler).apply(a.elem, g), o !== t && (n.result = o, o === !1 && (n.preventDefault(), n.stopPropagation()))
}
}
return b.postDispatch && b.postDispatch.call(this, n), n.result
},
props: "attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),
fixHooks: {},
keyHooks: {
props: "char charCode key keyCode".split(" "),
filter: function(e, t) {
return e.which == null && (e.which = t.charCode != null ? t.charCode : t.keyCode), e
}
},
mouseHooks: {
props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),
filter: function(e, n) {
var r, s, o, u = n.button,
a = n.fromElement;
return e.pageX == null && n.clientX != null && (r = e.target.ownerDocument || i, s = r.documentElement, o = r.body, e.pageX = n.clientX + (s && s.scrollLeft || o && o.scrollLeft || 0) - (s && s.clientLeft || o && o.clientLeft || 0), e.pageY = n.clientY + (s && s.scrollTop || o && o.scrollTop || 0) - (s && s.clientTop || o && o.clientTop || 0)), !e.relatedTarget && a && (e.relatedTarget = a === e.target ? n.toElement : a), !e.which && u !== t && (e.which = u & 1 ? 1 : u & 2 ? 3 : u & 4 ? 2 : 0), e
}
},
fix: function(e) {
if (e[v.expando]) return e;
var t, n, r = e,
s = v.event.fixHooks[e.type] || {},
o = s.props ? this.props.concat(s.props) : this.props;
e = v.Event(r);
for (t = o.length; t;) n = o[--t], e[n] = r[n];
return e.target || (e.target = r.srcElement || i), e.target.nodeType === 3 && (e.target = e.target.parentNode), e.metaKey = !!e.metaKey, s.filter ? s.filter(e, r) : e
},
special: {
load: {
noBubble: !0
},
focus: {
delegateType: "focusin"
},
blur: {
delegateType: "focusout"
},
beforeunload: {
setup: function(e, t, n) {
v.isWindow(this) && (this.onbeforeunload = n)
},
teardown: function(e, t) {
this.onbeforeunload === t && (this.onbeforeunload = null)
}
}
},
simulate: function(e, t, n, r) {
var i = v.extend(new v.Event, n, {
type: e,
isSimulated: !0,
originalEvent: {}
});
r ? v.event.trigger(i, null, t) : v.event.dispatch.call(t, i), i.isDefaultPrevented() && n.preventDefault()
}
}, v.event.handle = v.event.dispatch, v.removeEvent = i.removeEventListener ? function(e, t, n) {
e.removeEventListener && e.removeEventListener(t, n, !1)
} : function(e, t, n) {
var r = "on" + t;
e.detachEvent && (typeof e[r] == "undefined" && (e[r] = null), e.detachEvent(r, n))
}, v.Event = function(e, t) {
if (!(this instanceof v.Event)) return new v.Event(e, t);
e && e.type ? (this.originalEvent = e, this.type = e.type, this.isDefaultPrevented = e.defaultPrevented || e.returnValue === !1 || e.getPreventDefault && e.getPreventDefault() ? tt : et) : this.type = e, t && v.extend(this, t), this.timeStamp = e && e.timeStamp || v.now(), this[v.expando] = !0
}, v.Event.prototype = {
preventDefault: function() {
this.isDefaultPrevented = tt;
var e = this.originalEvent;
if (!e) return;
e.preventDefault ? e.preventDefault() : e.returnValue = !1
},
stopPropagation: function() {
this.isPropagationStopped = tt;
var e = this.originalEvent;
if (!e) return;
e.stopPropagation && e.stopPropagation(), e.cancelBubble = !0
},
stopImmediatePropagation: function() {
this.isImmediatePropagationStopped = tt, this.stopPropagation()
},
isDefaultPrevented: et,
isPropagationStopped: et,
isImmediatePropagationStopped: et
}, v.each({
mouseenter: "mouseover",
mouseleave: "mouseout"
}, function(e, t) {
v.event.special[e] = {
delegateType: t,
bindType: t,
handle: function(e) {
var n, r = this,
i = e.relatedTarget,
s = e.handleObj,
o = s.selector;
if (!i || i !== r && !v.contains(r, i)) e.type = s.origType, n = s.handler.apply(this, arguments), e.type = t;
return n
}
}
}), v.support.submitBubbles || (v.event.special.submit = {
setup: function() {
if (v.nodeName(this, "form")) return !1;
v.event.add(this, "click._submit keypress._submit", function(e) {
var n = e.target,
r = v.nodeName(n, "input") || v.nodeName(n, "button") ? n.form : t;
r && !v._data(r, "_submit_attached") && (v.event.add(r, "submit._submit", function(e) {
e._submit_bubble = !0
}), v._data(r, "_submit_attached", !0))
})
},
postDispatch: function(e) {
e._submit_bubble && (delete e._submit_bubble, this.parentNode && !e.isTrigger && v.event.simulate("submit", this.parentNode, e, !0))
},
teardown: function() {
if (v.nodeName(this, "form")) return !1;
v.event.remove(this, "._submit")
}
}), v.support.changeBubbles || (v.event.special.change = {
setup: function() {
if ($.test(this.nodeName)) {
if (this.type === "checkbox" || this.type === "radio") v.event.add(this, "propertychange._change", function(e) {
e.originalEvent.propertyName === "checked" && (this._just_changed = !0)
}), v.event.add(this, "click._change", function(e) {
this._just_changed && !e.isTrigger && (this._just_changed = !1), v.event.simulate("change", this, e, !0)
});
return !1
}
v.event.add(this, "beforeactivate._change", function(e) {
var t = e.target;
$.test(t.nodeName) && !v._data(t, "_change_attached") && (v.event.add(t, "change._change", function(e) {
this.parentNode && !e.isSimulated && !e.isTrigger && v.event.simulate("change", this.parentNode, e, !0)
}), v._data(t, "_change_attached", !0))
})
},
handle: function(e) {
var t = e.target;
if (this !== t || e.isSimulated || e.isTrigger || t.type !== "radio" && t.type !== "checkbox") return e.handleObj.handler.apply(this, arguments)
},
teardown: function() {
return v.event.remove(this, "._change"), !$.test(this.nodeName)
}
}), v.support.focusinBubbles || v.each({
focus: "focusin",
blur: "focusout"
}, function(e, t) {
var n = 0,
r = function(e) {
v.event.simulate(t, e.target, v.event.fix(e), !0)
};
v.event.special[t] = {
setup: function() {
n++ === 0 && i.addEventListener(e, r, !0)
},
teardown: function() {
--n === 0 && i.removeEventListener(e, r, !0)
}
}
}), v.fn.extend({
on: function(e, n, r, i, s) {
var o, u;
if (typeof e == "object") {
typeof n != "string" && (r = r || n, n = t);
for (u in e) this.on(u, n, r, e[u], s);
return this
}
r == null && i == null ? (i = n, r = n = t) : i == null && (typeof n == "string" ? (i = r, r = t) : (i = r, r = n, n = t));
if (i === !1) i = et;
else if (!i) return this;
return s === 1 && (o = i, i = function(e) {
return v().off(e), o.apply(this, arguments)
}, i.guid = o.guid || (o.guid = v.guid++)), this.each(function() {
v.event.add(this, e, i, r, n)
})
},
one: function(e, t, n, r) {
return this.on(e, t, n, r, 1)
},
off: function(e, n, r) {
var i, s;
if (e && e.preventDefault && e.handleObj) return i = e.handleObj, v(e.delegateTarget).off(i.namespace ? i.origType + "." + i.namespace : i.origType, i.selector, i.handler), this;
if (typeof e == "object") {
for (s in e) this.off(s, n, e[s]);
return this
}
if (n === !1 || typeof n == "function") r = n, n = t;
return r === !1 && (r = et), this.each(function() {
v.event.remove(this, e, r, n)
})
},
bind: function(e, t, n) {
return this.on(e, null, t, n)
},
unbind: function(e, t) {
return this.off(e, null, t)
},
live: function(e, t, n) {
return v(this.context).on(e, this.selector, t, n), this
},
die: function(e, t) {
return v(this.context).off(e, this.selector || "**", t), this
},
delegate: function(e, t, n, r) {
return this.on(t, e, n, r)
},
undelegate: function(e, t, n) {
return arguments.length === 1 ? this.off(e, "**") : this.off(t, e || "**", n)
},
trigger: function(e, t) {
return this.each(function() {
v.event.trigger(e, t, this)
})
},
triggerHandler: function(e, t) {
if (this[0]) return v.event.trigger(e, t, this[0], !0)
},
toggle: function(e) {
var t = arguments,
n = e.guid || v.guid++,
r = 0,
i = function(n) {
var i = (v._data(this, "lastToggle" + e.guid) || 0) % r;
return v._data(this, "lastToggle" + e.guid, i + 1), n.preventDefault(), t[i].apply(this, arguments) || !1
};
i.guid = n;
while (r < t.length) t[r++].guid = n;
return this.click(i)
},
hover: function(e, t) {
return this.mouseenter(e).mouseleave(t || e)
}
}), v.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "), function(e, t) {
v.fn[t] = function(e, n) {
return n == null && (n = e, e = null), arguments.length > 0 ? this.on(t, null, e, n) : this.trigger(t)
}, Q.test(t) && (v.event.fixHooks[t] = v.event.keyHooks), G.test(t) && (v.event.fixHooks[t] = v.event.mouseHooks)
}),
function(e, t) {
function nt(e, t, n, r) {
n = n || [], t = t || g;
var i, s, a, f, l = t.nodeType;
if (!e || typeof e != "string") return n;
if (l !== 1 && l !== 9) return [];
a = o(t);
if (!a && !r)
if (i = R.exec(e))
if (f = i[1]) {
if (l === 9) {
s = t.getElementById(f);
if (!s || !s.parentNode) return n;
if (s.id === f) return n.push(s), n
} else if (t.ownerDocument && (s = t.ownerDocument.getElementById(f)) && u(t, s) && s.id === f) return n.push(s), n
} else {
if (i[2]) return S.apply(n, x.call(t.getElementsByTagName(e), 0)), n;
if ((f = i[3]) && Z && t.getElementsByClassName) return S.apply(n, x.call(t.getElementsByClassName(f), 0)), n
}
return vt(e.replace(j, "$1"), t, n, r, a)
}
function rt(e) {
return function(t) {
var n = t.nodeName.toLowerCase();
return n === "input" && t.type === e
}
}
function it(e) {
return function(t) {
var n = t.nodeName.toLowerCase();
return (n === "input" || n === "button") && t.type === e
}
}
function st(e) {
return N(function(t) {
return t = +t, N(function(n, r) {
var i, s = e([], n.length, t),
o = s.length;
while (o--) n[i = s[o]] && (n[i] = !(r[i] = n[i]))
})
})
}
function ot(e, t, n) {
if (e === t) return n;
var r = e.nextSibling;
while (r) {
if (r === t) return -1;
r = r.nextSibling
}
return 1
}
function ut(e, t) {
var n, r, s, o, u, a, f, l = L[d][e + " "];
if (l) return t ? 0 : l.slice(0);
u = e, a = [], f = i.preFilter;
while (u) {
if (!n || (r = F.exec(u))) r && (u = u.slice(r[0].length) || u), a.push(s = []);
n = !1;
if (r = I.exec(u)) s.push(n = new m(r.shift())), u = u.slice(n.length), n.type = r[0].replace(j, " ");
for (o in i.filter)(r = J[o].exec(u)) && (!f[o] || (r = f[o](r))) && (s.push(n = new m(r.shift())), u = u.slice(n.length), n.type = o, n.matches = r);
if (!n) break
}
return t ? u.length : u ? nt.error(e) : L(e, a).slice(0)
}
function at(e, t, r) {
var i = t.dir,
s = r && t.dir === "parentNode",
o = w++;
return t.first ? function(t, n, r) {
while (t = t[i])
if (s || t.nodeType === 1) return e(t, n, r)
} : function(t, r, u) {
if (!u) {
var a, f = b + " " + o + " ",
l = f + n;
while (t = t[i])
if (s || t.nodeType === 1) {
if ((a = t[d]) === l) return t.sizset;
if (typeof a == "string" && a.indexOf(f) === 0) {
if (t.sizset) return t
} else {
t[d] = l;
if (e(t, r, u)) return t.sizset = !0, t;
t.sizset = !1
}
}
} else
while (t = t[i])
if (s || t.nodeType === 1)
if (e(t, r, u)) return t
}
}
function ft(e) {
return e.length > 1 ? function(t, n, r) {
var i = e.length;
while (i--)
if (!e[i](t, n, r)) return !1;
return !0
} : e[0]
}
function lt(e, t, n, r, i) {
var s, o = [],
u = 0,
a = e.length,
f = t != null;
for (; u < a; u++)
if (s = e[u])
if (!n || n(s, r, i)) o.push(s), f && t.push(u);
return o
}
function ct(e, t, n, r, i, s) {
return r && !r[d] && (r = ct(r)), i && !i[d] && (i = ct(i, s)), N(function(s, o, u, a) {
var f, l, c, h = [],
p = [],
d = o.length,
v = s || dt(t || "*", u.nodeType ? [u] : u, []),
m = e && (s || !t) ? lt(v, h, e, u, a) : v,
g = n ? i || (s ? e : d || r) ? [] : o : m;
n && n(m, g, u, a);
if (r) {
f = lt(g, p), r(f, [], u, a), l = f.length;
while (l--)
if (c = f[l]) g[p[l]] = !(m[p[l]] = c)
}
if (s) {
if (i || e) {
if (i) {
f = [], l = g.length;
while (l--)(c = g[l]) && f.push(m[l] = c);
i(null, g = [], f, a)
}
l = g.length;
while (l--)(c = g[l]) && (f = i ? T.call(s, c) : h[l]) > -1 && (s[f] = !(o[f] = c))
}
} else g = lt(g === o ? g.splice(d, g.length) : g), i ? i(null, o, g, a) : S.apply(o, g)
})
}
function ht(e) {
var t, n, r, s = e.length,
o = i.relative[e[0].type],
u = o || i.relative[" "],
a = o ? 1 : 0,
f = at(function(e) {
return e === t
}, u, !0),
l = at(function(e) {
return T.call(t, e) > -1
}, u, !0),
h = [function(e, n, r) {
return !o && (r || n !== c) || ((t = n).nodeType ? f(e, n, r) : l(e, n, r))
}];
for (; a < s; a++)
if (n = i.relative[e[a].type]) h = [at(ft(h), n)];
else {
n = i.filter[e[a].type].apply(null, e[a].matches);
if (n[d]) {
r = ++a;
for (; r < s; r++)
if (i.relative[e[r].type]) break;
return ct(a > 1 && ft(h), a > 1 && e.slice(0, a - 1).join("").replace(j, "$1"), n, a < r && ht(e.slice(a, r)), r < s && ht(e = e.slice(r)), r < s && e.join(""))
}
h.push(n)
}
return ft(h)
}
function pt(e, t) {
var r = t.length > 0,
s = e.length > 0,
o = function(u, a, f, l, h) {
var p, d, v, m = [],
y = 0,
w = "0",
x = u && [],
T = h != null,
N = c,
C = u || s && i.find.TAG("*", h && a.parentNode || a),
k = b += N == null ? 1 : Math.E;
T && (c = a !== g && a, n = o.el);
for (;
(p = C[w]) != null; w++) {
if (s && p) {
for (d = 0; v = e[d]; d++)
if (v(p, a, f)) {
l.push(p);
break
}
T && (b = k, n = ++o.el)
}
r && ((p = !v && p) && y--, u && x.push(p))
}
y += w;
if (r && w !== y) {
for (d = 0; v = t[d]; d++) v(x, m, a, f);
if (u) {
if (y > 0)
while (w--) !x[w] && !m[w] && (m[w] = E.call(l));
m = lt(m)
}
S.apply(l, m), T && !u && m.length > 0 && y + t.length > 1 && nt.uniqueSort(l)
}
return T && (b = k, c = N), x
};
return o.el = 0, r ? N(o) : o
}
function dt(e, t, n) {
var r = 0,
i = t.length;
for (; r < i; r++) nt(e, t[r], n);
return n
}
function vt(e, t, n, r, s) {
var o, u, f, l, c, h = ut(e),
p = h.length;
if (!r && h.length === 1) {
u = h[0] = h[0].slice(0);
if (u.length > 2 && (f = u[0]).type === "ID" && t.nodeType === 9 && !s && i.relative[u[1].type]) {
t = i.find.ID(f.matches[0].replace($, ""), t, s)[0];
if (!t) return n;
e = e.slice(u.shift().length)
}
for (o = J.POS.test(e) ? -1 : u.length - 1; o >= 0; o--) {
f = u[o];
if (i.relative[l = f.type]) break;
if (c = i.find[l])
if (r = c(f.matches[0].replace($, ""), z.test(u[0].type) && t.parentNode || t, s)) {
u.splice(o, 1), e = r.length && u.join("");
if (!e) return S.apply(n, x.call(r, 0)), n;
break
}
}
}
return a(e, h)(r, t, s, n, z.test(e)), n
}
function mt() {}
var n, r, i, s, o, u, a, f, l, c, h = !0,
p = "undefined",
d = ("sizcache" + Math.random()).replace(".", ""),
m = String,
g = e.document,
y = g.documentElement,
b = 0,
w = 0,
E = [].pop,
S = [].push,
x = [].slice,
T = [].indexOf || function(e) {
var t = 0,
n = this.length;
for (; t < n; t++)
if (this[t] === e) return t;
return -1
},
N = function(e, t) {
return e[d] = t == null || t, e
},
C = function() {
var e = {},
t = [];
return N(function(n, r) {
return t.push(n) > i.cacheLength && delete e[t.shift()], e[n + " "] = r
}, e)
},
k = C(),
L = C(),
A = C(),
O = "[\\x20\\t\\r\\n\\f]",
M = "(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+",
_ = M.replace("w", "w#"),
D = "([*^$|!~]?=)",
P = "\\[" + O + "*(" + M + ")" + O + "*(?:" + D + O + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + _ + ")|)|)" + O + "*\\]",
H = ":(" + M + ")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:" + P + ")|[^:]|\\\\.)*|.*))\\)|)",
B = ":(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + O + "*((?:-\\d)?\\d*)" + O + "*\\)|)(?=[^-]|$)",
j = new RegExp("^" + O + "+|((?:^|[^\\\\])(?:\\\\.)*)" + O + "+$", "g"),
F = new RegExp("^" + O + "*," + O + "*"),
I = new RegExp("^" + O + "*([\\x20\\t\\r\\n\\f>+~])" + O + "*"),
q = new RegExp(H),
R = /^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,
U = /^:not/,
z = /[\x20\t\r\n\f]*[+~]/,
W = /:not\($/,
X = /h\d/i,
V = /input|select|textarea|button/i,
$ = /\\(?!\\)/g,
J = {
ID: new RegExp("^#(" + M + ")"),
CLASS: new RegExp("^\\.(" + M + ")"),
NAME: new RegExp("^\\[name=['\"]?(" + M + ")['\"]?\\]"),
TAG: new RegExp("^(" + M.replace("w", "w*") + ")"),
ATTR: new RegExp("^" + P),
PSEUDO: new RegExp("^" + H),
POS: new RegExp(B, "i"),
CHILD: new RegExp("^:(only|nth|first|last)-child(?:\\(" + O + "*(even|odd|(([+-]|)(\\d*)n|)" + O + "*(?:([+-]|)" + O + "*(\\d+)|))" + O + "*\\)|)", "i"),
needsContext: new RegExp("^" + O + "*[>+~]|" + B, "i")
},
K = function(e) {
var t = g.createElement("div");
try {
return e(t)
} catch (n) {
return !1
} finally {
t = null
}
},
Q = K(function(e) {
return e.appendChild(g.createComment("")), !e.getElementsByTagName("*").length
}),
G = K(function(e) {
return e.innerHTML = "<a href='#'></a>", e.firstChild && typeof e.firstChild.getAttribute !== p && e.firstChild.getAttribute("href") === "#"
}),
Y = K(function(e) {
e.innerHTML = "<select></select>";
var t = typeof e.lastChild.getAttribute("multiple");
return t !== "boolean" && t !== "string"
}),
Z = K(function(e) {
return e.innerHTML = "<div class='hidden e'></div><div class='hidden'></div>", !e.getElementsByClassName || !e.getElementsByClassName("e").length ? !1 : (e.lastChild.className = "e", e.getElementsByClassName("e").length === 2)
}),
et = K(function(e) {
e.id = d + 0, e.innerHTML = "<a name='" + d + "'></a><div name='" + d + "'></div>", y.insertBefore(e, y.firstChild);
var t = g.getElementsByName && g.getElementsByName(d).length === 2 + g.getElementsByName(d + 0).length;
return r = !g.getElementById(d), y.removeChild(e), t
});
try {
x.call(y.childNodes, 0)[0].nodeType
} catch (tt) {
x = function(e) {
var t, n = [];
for (; t = this[e]; e++) n.push(t);
return n
}
}
nt.matches = function(e, t) {
return nt(e, null, null, t)
}, nt.matchesSelector = function(e, t) {
return nt(t, null, null, [e]).length > 0
}, s = nt.getText = function(e) {
var t, n = "",
r = 0,
i = e.nodeType;
if (i) {
if (i === 1 || i === 9 || i === 11) {
if (typeof e.textContent == "string") return e.textContent;
for (e = e.firstChild; e; e = e.nextSibling) n += s(e)
} else if (i === 3 || i === 4) return e.nodeValue
} else
for (; t = e[r]; r++) n += s(t);
return n
}, o = nt.isXML = function(e) {
var t = e && (e.ownerDocument || e).documentElement;
return t ? t.nodeName !== "HTML" : !1
}, u = nt.contains = y.contains ? function(e, t) {
var n = e.nodeType === 9 ? e.documentElement : e,
r = t && t.parentNode;
return e === r || !!(r && r.nodeType === 1 && n.contains && n.contains(r))
} : y.compareDocumentPosition ? function(e, t) {
return t && !!(e.compareDocumentPosition(t) & 16)
} : function(e, t) {
while (t = t.parentNode)
if (t === e) return !0;
return !1
}, nt.attr = function(e, t) {
var n, r = o(e);
return r || (t = t.toLowerCase()), (n = i.attrHandle[t]) ? n(e) : r || Y ? e.getAttribute(t) : (n = e.getAttributeNode(t), n ? typeof e[t] == "boolean" ? e[t] ? t : null : n.specified ? n.value : null : null)
}, i = nt.selectors = {
cacheLength: 50,
createPseudo: N,
match: J,
attrHandle: G ? {} : {
href: function(e) {
return e.getAttribute("href", 2)
},
type: function(e) {
return e.getAttribute("type")
}
},
find: {
ID: r ? function(e, t, n) {
if (typeof t.getElementById !== p && !n) {
var r = t.getElementById(e);
return r && r.parentNode ? [r] : []
}
} : function(e, n, r) {
if (typeof n.getElementById !== p && !r) {
var i = n.getElementById(e);
return i ? i.id === e || typeof i.getAttributeNode !== p && i.getAttributeNode("id").value === e ? [i] : t : []
}
},
TAG: Q ? function(e, t) {
if (typeof t.getElementsByTagName !== p) return t.getElementsByTagName(e)
} : function(e, t) {
var n = t.getElementsByTagName(e);
if (e === "*") {
var r, i = [],
s = 0;
for (; r = n[s]; s++) r.nodeType === 1 && i.push(r);
return i
}
return n
},
NAME: et && function(e, t) {
if (typeof t.getElementsByName !== p) return t.getElementsByName(name)
},
CLASS: Z && function(e, t, n) {
if (typeof t.getElementsByClassName !== p && !n) return t.getElementsByClassName(e)
}
},
relative: {
">": {
dir: "parentNode",
first: !0
},
" ": {
dir: "parentNode"
},
"+": {
dir: "previousSibling",
first: !0
},
"~": {
dir: "previousSibling"
}
},
preFilter: {
ATTR: function(e) {
return e[1] = e[1].replace($, ""), e[3] = (e[4] || e[5] || "").replace($, ""), e[2] === "~=" && (e[3] = " " + e[3] + " "), e.slice(0, 4)
},
CHILD: function(e) {
return e[1] = e[1].toLowerCase(), e[1] === "nth" ? (e[2] || nt.error(e[0]), e[3] = +(e[3] ? e[4] + (e[5] || 1) : 2 * (e[2] === "even" || e[2] === "odd")), e[4] = +(e[6] + e[7] || e[2] === "odd")) : e[2] && nt.error(e[0]), e
},
PSEUDO: function(e) {
var t, n;
if (J.CHILD.test(e[0])) return null;
if (e[3]) e[2] = e[3];
else if (t = e[4]) q.test(t) && (n = ut(t, !0)) && (n = t.indexOf(")", t.length - n) - t.length) && (t = t.slice(0, n), e[0] = e[0].slice(0, n)), e[2] = t;
return e.slice(0, 3)
}
},
filter: {
ID: r ? function(e) {
return e = e.replace($, ""),
function(t) {
return t.getAttribute("id") === e
}
} : function(e) {
return e = e.replace($, ""),
function(t) {
var n = typeof t.getAttributeNode !== p && t.getAttributeNode("id");
return n && n.value === e
}
},
TAG: function(e) {
return e === "*" ? function() {
return !0
} : (e = e.replace($, "").toLowerCase(), function(t) {
return t.nodeName && t.nodeName.toLowerCase() === e
})
},
CLASS: function(e) {
var t = k[d][e + " "];
return t || (t = new RegExp("(^|" + O + ")" + e + "(" + O + "|$)")) && k(e, function(e) {
return t.test(e.className || typeof e.getAttribute !== p && e.getAttribute("class") || "")
})
},
ATTR: function(e, t, n) {
return function(r, i) {
var s = nt.attr(r, e);
return s == null ? t === "!=" : t ? (s += "", t === "=" ? s === n : t === "!=" ? s !== n : t === "^=" ? n && s.indexOf(n) === 0 : t === "*=" ? n && s.indexOf(n) > -1 : t === "$=" ? n && s.substr(s.length - n.length) === n : t === "~=" ? (" " + s + " ").indexOf(n) > -1 : t === "|=" ? s === n || s.substr(0, n.length + 1) === n + "-" : !1) : !0
}
},
CHILD: function(e, t, n, r) {
return e === "nth" ? function(e) {
var t, i, s = e.parentNode;
if (n === 1 && r === 0) return !0;
if (s) {
i = 0;
for (t = s.firstChild; t; t = t.nextSibling)
if (t.nodeType === 1) {
i++;
if (e === t) break
}
}
return i -= r, i === n || i % n === 0 && i / n >= 0
} : function(t) {
var n = t;
switch (e) {
case "only":
case "first":
while (n = n.previousSibling)
if (n.nodeType === 1) return !1;
if (e === "first") return !0;
n = t;
case "last":
while (n = n.nextSibling)
if (n.nodeType === 1) return !1;
return !0
}
}
},
PSEUDO: function(e, t) {
var n, r = i.pseudos[e] || i.setFilters[e.toLowerCase()] || nt.error("unsupported pseudo: " + e);
return r[d] ? r(t) : r.length > 1 ? (n = [e, e, "", t], i.setFilters.hasOwnProperty(e.toLowerCase()) ? N(function(e, n) {
var i, s = r(e, t),
o = s.length;
while (o--) i = T.call(e, s[o]), e[i] = !(n[i] = s[o])
}) : function(e) {
return r(e, 0, n)
}) : r
}
},
pseudos: {
not: N(function(e) {
var t = [],
n = [],
r = a(e.replace(j, "$1"));
return r[d] ? N(function(e, t, n, i) {
var s, o = r(e, null, i, []),
u = e.length;
while (u--)
if (s = o[u]) e[u] = !(t[u] = s)
}) : function(e, i, s) {
return t[0] = e, r(t, null, s, n), !n.pop()
}
}),
has: N(function(e) {
return function(t) {
return nt(e, t).length > 0
}
}),
contains: N(function(e) {
return function(t) {
return (t.textContent || t.innerText || s(t)).indexOf(e) > -1
}
}),
enabled: function(e) {
return e.disabled === !1
},
disabled: function(e) {
return e.disabled === !0
},
checked: function(e) {
var t = e.nodeName.toLowerCase();
return t === "input" && !!e.checked || t === "option" && !!e.selected
},
selected: function(e) {
return e.parentNode && e.parentNode.selectedIndex, e.selected === !0
},
parent: function(e) {
return !i.pseudos.empty(e)
},
empty: function(e) {
var t;
e = e.firstChild;
while (e) {
if (e.nodeName > "@" || (t = e.nodeType) === 3 || t === 4) return !1;
e = e.nextSibling
}
return !0
},
header: function(e) {
return X.test(e.nodeName)
},
text: function(e) {
var t, n;
return e.nodeName.toLowerCase() === "input" && (t = e.type) === "text" && ((n = e.getAttribute("type")) == null || n.toLowerCase() === t)
},
radio: rt("radio"),
checkbox: rt("checkbox"),
file: rt("file"),
password: rt("password"),
image: rt("image"),
submit: it("submit"),
reset: it("reset"),
button: function(e) {
var t = e.nodeName.toLowerCase();
return t === "input" && e.type === "button" || t === "button"
},
input: function(e) {
return V.test(e.nodeName)
},
focus: function(e) {
var t = e.ownerDocument;
return e === t.activeElement && (!t.hasFocus || t.hasFocus()) && !!(e.type || e.href || ~e.tabIndex)
},
active: function(e) {
return e === e.ownerDocument.activeElement
},
first: st(function() {
return [0]
}),
last: st(function(e, t) {
return [t - 1]
}),
eq: st(function(e, t, n) {
return [n < 0 ? n + t : n]
}),
even: st(function(e, t) {
for (var n = 0; n < t; n += 2) e.push(n);
return e
}),
odd: st(function(e, t) {
for (var n = 1; n < t; n += 2) e.push(n);
return e
}),
lt: st(function(e, t, n) {
for (var r = n < 0 ? n + t : n; --r >= 0;) e.push(r);
return e
}),
gt: st(function(e, t, n) {
for (var r = n < 0 ? n + t : n; ++r < t;) e.push(r);
return e
})
}
}, f = y.compareDocumentPosition ? function(e, t) {
return e === t ? (l = !0, 0) : (!e.compareDocumentPosition || !t.compareDocumentPosition ? e.compareDocumentPosition : e.compareDocumentPosition(t) & 4) ? -1 : 1
} : function(e, t) {
if (e === t) return l = !0, 0;
if (e.sourceIndex && t.sourceIndex) return e.sourceIndex - t.sourceIndex;
var n, r, i = [],
s = [],
o = e.parentNode,
u = t.parentNode,
a = o;
if (o === u) return ot(e, t);
if (!o) return -1;
if (!u) return 1;
while (a) i.unshift(a), a = a.parentNode;
a = u;
while (a) s.unshift(a), a = a.parentNode;
n = i.length, r = s.length;
for (var f = 0; f < n && f < r; f++)
if (i[f] !== s[f]) return ot(i[f], s[f]);
return f === n ? ot(e, s[f], -1) : ot(i[f], t, 1)
}, [0, 0].sort(f), h = !l, nt.uniqueSort = function(e) {
var t, n = [],
r = 1,
i = 0;
l = h, e.sort(f);
if (l) {
for (; t = e[r]; r++) t === e[r - 1] && (i = n.push(r));
while (i--) e.splice(n[i], 1)
}
return e
}, nt.error = function(e) {
throw new Error("Syntax error, unrecognized expression: " + e)
}, a = nt.compile = function(e, t) {
var n, r = [],
i = [],
s = A[d][e + " "];
if (!s) {
t || (t = ut(e)), n = t.length;
while (n--) s = ht(t[n]), s[d] ? r.push(s) : i.push(s);
s = A(e, pt(i, r))
}
return s
}, g.querySelectorAll && function() {
var e, t = vt,
n = /'|\\/g,
r = /\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,
i = [":focus"],
s = [":active"],
u = y.matchesSelector || y.mozMatchesSelector || y.webkitMatchesSelector || y.oMatchesSelector || y.msMatchesSelector;
K(function(e) {
e.innerHTML = "<select><option selected=''></option></select>", e.querySelectorAll("[selected]").length || i.push("\\[" + O + "*(?:checked|disabled|ismap|multiple|readonly|selected|value)"), e.querySelectorAll(":checked").length || i.push(":checked")
}), K(function(e) {
e.innerHTML = "<p test=''></p>", e.querySelectorAll("[test^='']").length && i.push("[*^$]=" + O + "*(?:\"\"|'')"), e.innerHTML = "<input type='hidden'/>", e.querySelectorAll(":enabled").length || i.push(":enabled", ":disabled")
}), i = new RegExp(i.join("|")), vt = function(e, r, s, o, u) {
if (!o && !u && !i.test(e)) {
var a, f, l = !0,
c = d,
h = r,
p = r.nodeType === 9 && e;
if (r.nodeType === 1 && r.nodeName.toLowerCase() !== "object") {
a = ut(e), (l = r.getAttribute("id")) ? c = l.replace(n, "\\$&") : r.setAttribute("id", c), c = "[id='" + c + "'] ", f = a.length;
while (f--) a[f] = c + a[f].join("");
h = z.test(e) && r.parentNode || r, p = a.join(",")
}
if (p) try {
return S.apply(s, x.call(h.querySelectorAll(p), 0)), s
} catch (v) {} finally {
l || r.removeAttribute("id")
}
}
return t(e, r, s, o, u)
}, u && (K(function(t) {
e = u.call(t, "div");
try {
u.call(t, "[test!='']:sizzle"), s.push("!=", H)
} catch (n) {}
}), s = new RegExp(s.join("|")), nt.matchesSelector = function(t, n) {
n = n.replace(r, "='$1']");
if (!o(t) && !s.test(n) && !i.test(n)) try {
var a = u.call(t, n);
if (a || e || t.document && t.document.nodeType !== 11) return a
} catch (f) {}
return nt(n, null, null, [t]).length > 0
})
}(), i.pseudos.nth = i.pseudos.eq, i.filters = mt.prototype = i.pseudos, i.setFilters = new mt, nt.attr = v.attr, v.find = nt, v.expr = nt.selectors, v.expr[":"] = v.expr.pseudos, v.unique = nt.uniqueSort, v.text = nt.getText, v.isXMLDoc = nt.isXML, v.contains = nt.contains
}(e);
var nt = /Until$/,
rt = /^(?:parents|prev(?:Until|All))/,
it = /^.[^:#\[\.,]*$/,
st = v.expr.match.needsContext,
ot = {
children: !0,
contents: !0,
next: !0,
prev: !0
};
v.fn.extend({
find: function(e) {
var t, n, r, i, s, o, u = this;
if (typeof e != "string") return v(e).filter(function() {
for (t = 0, n = u.length; t < n; t++)
if (v.contains(u[t], this)) return !0
});
o = this.pushStack("", "find", e);
for (t = 0, n = this.length; t < n; t++) {
r = o.length, v.find(e, this[t], o);
if (t > 0)
for (i = r; i < o.length; i++)
for (s = 0; s < r; s++)
if (o[s] === o[i]) {
o.splice(i--, 1);
break
}
}
return o
},
has: function(e) {
var t, n = v(e, this),
r = n.length;
return this.filter(function() {
for (t = 0; t < r; t++)
if (v.contains(this, n[t])) return !0
})
},
not: function(e) {
return this.pushStack(ft(this, e, !1), "not", e)
},
filter: function(e) {
return this.pushStack(ft(this, e, !0), "filter", e)
},
is: function(e) {
return !!e && (typeof e == "string" ? st.test(e) ? v(e, this.context).index(this[0]) >= 0 : v.filter(e, this).length > 0 : this.filter(e).length > 0)
},
closest: function(e, t) {
var n, r = 0,
i = this.length,
s = [],
o = st.test(e) || typeof e != "string" ? v(e, t || this.context) : 0;
for (; r < i; r++) {
n = this[r];
while (n && n.ownerDocument && n !== t && n.nodeType !== 11) {
if (o ? o.index(n) > -1 : v.find.matchesSelector(n, e)) {
s.push(n);
break
}
n = n.parentNode
}
}
return s = s.length > 1 ? v.unique(s) : s, this.pushStack(s, "closest", e)
},
index: function(e) {
return e ? typeof e == "string" ? v.inArray(this[0], v(e)) : v.inArray(e.jquery ? e[0] : e, this) : this[0] && this[0].parentNode ? this.prevAll().length : -1
},
add: function(e, t) {
var n = typeof e == "string" ? v(e, t) : v.makeArray(e && e.nodeType ? [e] : e),
r = v.merge(this.get(), n);
return this.pushStack(ut(n[0]) || ut(r[0]) ? r : v.unique(r))
},
addBack: function(e) {
return this.add(e == null ? this.prevObject : this.prevObject.filter(e))
}
}), v.fn.andSelf = v.fn.addBack, v.each({
parent: function(e) {
var t = e.parentNode;
return t && t.nodeType !== 11 ? t : null
},
parents: function(e) {
return v.dir(e, "parentNode")
},
parentsUntil: function(e, t, n) {
return v.dir(e, "parentNode", n)
},
next: function(e) {
return at(e, "nextSibling")
},
prev: function(e) {
return at(e, "previousSibling")
},
nextAll: function(e) {
return v.dir(e, "nextSibling")
},
prevAll: function(e) {
return v.dir(e, "previousSibling")
},
nextUntil: function(e, t, n) {
return v.dir(e, "nextSibling", n)
},
prevUntil: function(e, t, n) {
return v.dir(e, "previousSibling", n)
},
siblings: function(e) {
return v.sibling((e.parentNode || {}).firstChild, e)
},
children: function(e) {
return v.sibling(e.firstChild)
},
contents: function(e) {
return v.nodeName(e, "iframe") ? e.contentDocument || e.contentWindow.document : v.merge([], e.childNodes)
}
}, function(e, t) {
v.fn[e] = function(n, r) {
var i = v.map(this, t, n);
return nt.test(e) || (r = n), r && typeof r == "string" && (i = v.filter(r, i)), i = this.length > 1 && !ot[e] ? v.unique(i) : i, this.length > 1 && rt.test(e) && (i = i.reverse()), this.pushStack(i, e, l.call(arguments).join(","))
}
}), v.extend({
filter: function(e, t, n) {
return n && (e = ":not(" + e + ")"), t.length === 1 ? v.find.matchesSelector(t[0], e) ? [t[0]] : [] : v.find.matches(e, t)
},
dir: function(e, n, r) {
var i = [],
s = e[n];
while (s && s.nodeType !== 9 && (r === t || s.nodeType !== 1 || !v(s).is(r))) s.nodeType === 1 && i.push(s), s = s[n];
return i
},
sibling: function(e, t) {
var n = [];
for (; e; e = e.nextSibling) e.nodeType === 1 && e !== t && n.push(e);
return n
}
});
var ct = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",
ht = / jQuery\d+="(?:null|\d+)"/g,
pt = /^\s+/,
dt = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,
vt = /<([\w:]+)/,
mt = /<tbody/i,
gt = /<|&#?\w+;/,
yt = /<(?:script|style|link)/i,
bt = /<(?:script|object|embed|option|style)/i,
wt = new RegExp("<(?:" + ct + ")[\\s/>]", "i"),
Et = /^(?:checkbox|radio)$/,
St = /checked\s*(?:[^=]|=\s*.checked.)/i,
xt = /\/(java|ecma)script/i,
Tt = /^\s*<!(?:\[CDATA\[|\-\-)|[\]\-]{2}>\s*$/g,
Nt = {
option: [1, "<select multiple='multiple'>", "</select>"],
legend: [1, "<fieldset>", "</fieldset>"],
thead: [1, "<table>", "</table>"],
tr: [2, "<table><tbody>", "</tbody></table>"],
td: [3, "<table><tbody><tr>", "</tr></tbody></table>"],
col: [2, "<table><tbody></tbody><colgroup>", "</colgroup></table>"],
area: [1, "<map>", "</map>"],
_default: [0, "", ""]
},
Ct = lt(i),
kt = Ct.appendChild(i.createElement("div"));
Nt.optgroup = Nt.option, Nt.tbody = Nt.tfoot = Nt.colgroup = Nt.caption = Nt.thead, Nt.th = Nt.td, v.support.htmlSerialize || (Nt._default = [1, "X<div>", "</div>"]), v.fn.extend({
text: function(
e) {
return v.access(this, function(e) {
return e === t ? v.text(this) : this.empty().append((this[0] && this[0].ownerDocument || i).createTextNode(e))
}, null, e, arguments.length)
},
wrapAll: function(e) {
if (v.isFunction(e)) return this.each(function(t) {
v(this).wrapAll(e.call(this, t))
});
if (this[0]) {
var t = v(e, this[0].ownerDocument).eq(0).clone(!0);
this[0].parentNode && t.insertBefore(this[0]), t.map(function() {
var e = this;
while (e.firstChild && e.firstChild.nodeType === 1) e = e.firstChild;
return e
}).append(this)
}
return this
},
wrapInner: function(e) {
return v.isFunction(e) ? this.each(function(t) {
v(this).wrapInner(e.call(this, t))
}) : this.each(function() {
var t = v(this),
n = t.contents();
n.length ? n.wrapAll(e) : t.append(e)
})
},
wrap: function(e) {
var t = v.isFunction(e);
return this.each(function(n) {
v(this).wrapAll(t ? e.call(this, n) : e)
})
},
unwrap: function() {
return this.parent().each(function() {
v.nodeName(this, "body") || v(this).replaceWith(this.childNodes)
}).end()
},
append: function() {
return this.domManip(arguments, !0, function(e) {
(this.nodeType === 1 || this.nodeType === 11) && this.appendChild(e)
})
},
prepend: function() {
return this.domManip(arguments, !0, function(e) {
(this.nodeType === 1 || this.nodeType === 11) && this.insertBefore(e, this.firstChild)
})
},
before: function() {
if (!ut(this[0])) return this.domManip(arguments, !1, function(e) {
this.parentNode.insertBefore(e, this)
});
if (arguments.length) {
var e = v.clean(arguments);
return this.pushStack(v.merge(e, this), "before", this.selector)
}
},
after: function() {
if (!ut(this[0])) return this.domManip(arguments, !1, function(e) {
this.parentNode.insertBefore(e, this.nextSibling)
});
if (arguments.length) {
var e = v.clean(arguments);
return this.pushStack(v.merge(this, e), "after", this.selector)
}
},
remove: function(e, t) {
var n, r = 0;
for (;
(n = this[r]) != null; r++)
if (!e || v.filter(e, [n]).length) !t && n.nodeType === 1 && (v.cleanData(n.getElementsByTagName("*")), v.cleanData([n])), n.parentNode && n.parentNode.removeChild(n);
return this
},
empty: function() {
var e, t = 0;
for (;
(e = this[t]) != null; t++) {
e.nodeType === 1 && v.cleanData(e.getElementsByTagName("*"));
while (e.firstChild) e.removeChild(e.firstChild)
}
return this
},
clone: function(e, t) {
return e = e == null ? !1 : e, t = t == null ? e : t, this.map(function() {
return v.clone(this, e, t)
})
},
html: function(e) {
return v.access(this, function(e) {
var n = this[0] || {},
r = 0,
i = this.length;
if (e === t) return n.nodeType === 1 ? n.innerHTML.replace(ht, "") : t;
if (typeof e == "string" && !yt.test(e) && (v.support.htmlSerialize || !wt.test(e)) && (v.support.leadingWhitespace || !pt.test(e)) && !Nt[(vt.exec(e) || ["", ""])[1].toLowerCase()]) {
e = e.replace(dt, "<$1></$2>");
try {
for (; r < i; r++) n = this[r] || {}, n.nodeType === 1 && (v.cleanData(n.getElementsByTagName("*")), n.innerHTML = e);
n = 0
} catch (s) {}
}
n && this.empty().append(e)
}, null, e, arguments.length)
},
replaceWith: function(e) {
return ut(this[0]) ? this.length ? this.pushStack(v(v.isFunction(e) ? e() : e), "replaceWith", e) : this : v.isFunction(e) ? this.each(function(t) {
var n = v(this),
r = n.html();
n.replaceWith(e.call(this, t, r))
}) : (typeof e != "string" && (e = v(e).detach()), this.each(function() {
var t = this.nextSibling,
n = this.parentNode;
v(this).remove(), t ? v(t).before(e) : v(n).append(e)
}))
},
detach: function(e) {
return this.remove(e, !0)
},
domManip: function(e, n, r) {
e = [].concat.apply([], e);
var i, s, o, u, a = 0,
f = e[0],
l = [],
c = this.length;
if (!v.support.checkClone && c > 1 && typeof f == "string" && St.test(f)) return this.each(function() {
v(this).domManip(e, n, r)
});
if (v.isFunction(f)) return this.each(function(i) {
var s = v(this);
e[0] = f.call(this, i, n ? s.html() : t), s.domManip(e, n, r)
});
if (this[0]) {
i = v.buildFragment(e, this, l), o = i.fragment, s = o.firstChild, o.childNodes.length === 1 && (o = s);
if (s) {
n = n && v.nodeName(s, "tr");
for (u = i.cacheable || c - 1; a < c; a++) r.call(n && v.nodeName(this[a], "table") ? Lt(this[a], "tbody") : this[a], a === u ? o : v.clone(o, !0, !0))
}
o = s = null, l.length && v.each(l, function(e, t) {
t.src ? v.ajax ? v.ajax({
url: t.src,
type: "GET",
dataType: "script",
async: !1,
global: !1,
"throws": !0
}) : v.error("no ajax") : v.globalEval((t.text || t.textContent || t.innerHTML || "").replace(Tt, "")), t.parentNode && t.parentNode.removeChild(t)
})
}
return this
}
}), v.buildFragment = function(e, n, r) {
var s, o, u, a = e[0];
return n = n || i, n = !n.nodeType && n[0] || n, n = n.ownerDocument || n, e.length === 1 && typeof a == "string" && a.length < 512 && n === i && a.charAt(0) === "<" && !bt.test(a) && (v.support.checkClone || !St.test(a)) && (v.support.html5Clone || !wt.test(a)) && (o = !0, s = v.fragments[a], u = s !== t), s || (s = n.createDocumentFragment(), v.clean(e, n, s, r), o && (v.fragments[a] = u && s)), {
fragment: s,
cacheable: o
}
}, v.fragments = {}, v.each({
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
}, function(e, t) {
v.fn[e] = function(n) {
var r, i = 0,
s = [],
o = v(n),
u = o.length,
a = this.length === 1 && this[0].parentNode;
if ((a == null || a && a.nodeType === 11 && a.childNodes.length === 1) && u === 1) return o[t](this[0]), this;
for (; i < u; i++) r = (i > 0 ? this.clone(!0) : this).get(), v(o[i])[t](r), s = s.concat(r);
return this.pushStack(s, e, o.selector)
}
}), v.extend({
clone: function(e, t, n) {
var r, i, s, o;
v.support.html5Clone || v.isXMLDoc(e) || !wt.test("<" + e.nodeName + ">") ? o = e.cloneNode(!0) : (kt.innerHTML = e.outerHTML, kt.removeChild(o = kt.firstChild));
if ((!v.support.noCloneEvent || !v.support.noCloneChecked) && (e.nodeType === 1 || e.nodeType === 11) && !v.isXMLDoc(e)) {
Ot(e, o), r = Mt(e), i = Mt(o);
for (s = 0; r[s]; ++s) i[s] && Ot(r[s], i[s])
}
if (t) {
At(e, o);
if (n) {
r = Mt(e), i = Mt(o);
for (s = 0; r[s]; ++s) At(r[s], i[s])
}
}
return r = i = null, o
},
clean: function(e, t, n, r) {
var s, o, u, a, f, l, c, h, p, d, m, g, y = t === i && Ct,
b = [];
if (!t || typeof t.createDocumentFragment == "undefined") t = i;
for (s = 0;
(u = e[s]) != null; s++) {
typeof u == "number" && (u += "");
if (!u) continue;
if (typeof u == "string")
if (!gt.test(u)) u = t.createTextNode(u);
else {
y = y || lt(t), c = t.createElement("div"), y.appendChild(c), u = u.replace(dt, "<$1></$2>"), a = (vt.exec(u) || ["", ""])[1].toLowerCase(), f = Nt[a] || Nt._default, l = f[0], c.innerHTML = f[1] + u + f[2];
while (l--) c = c.lastChild;
if (!v.support.tbody) {
h = mt.test(u), p = a === "table" && !h ? c.firstChild && c.firstChild.childNodes : f[1] === "<table>" && !h ? c.childNodes : [];
for (o = p.length - 1; o >= 0; --o) v.nodeName(p[o], "tbody") && !p[o].childNodes.length && p[o].parentNode.removeChild(p[o])
}!v.support.leadingWhitespace && pt.test(u) && c.insertBefore(t.createTextNode(pt.exec(u)[0]), c.firstChild), u = c.childNodes, c.parentNode.removeChild(c)
}
u.nodeType ? b.push(u) : v.merge(b, u)
}
c && (u = c = y = null);
if (!v.support.appendChecked)
for (s = 0;
(u = b[s]) != null; s++) v.nodeName(u, "input") ? _t(u) : typeof u.getElementsByTagName != "undefined" && v.grep(u.getElementsByTagName("input"), _t);
if (n) {
m = function(e) {
if (!e.type || xt.test(e.type)) return r ? r.push(e.parentNode ? e.parentNode.removeChild(e) : e) : n.appendChild(e)
};
for (s = 0;
(u = b[s]) != null; s++)
if (!v.nodeName(u, "script") || !m(u)) n.appendChild(u), typeof u.getElementsByTagName != "undefined" && (g = v.grep(v.merge([], u.getElementsByTagName("script")), m), b.splice.apply(b, [s + 1, 0].concat(g)), s += g.length)
}
return b
},
cleanData: function(e, t) {
var n, r, i, s, o = 0,
u = v.expando,
a = v.cache,
f = v.support.deleteExpando,
l = v.event.special;
for (;
(i = e[o]) != null; o++)
if (t || v.acceptData(i)) {
r = i[u], n = r && a[r];
if (n) {
if (n.events)
for (s in n.events) l[s] ? v.event.remove(i, s) : v.removeEvent(i, s, n.handle);
a[r] && (delete a[r], f ? delete i[u] : i.removeAttribute ? i.removeAttribute(u) : i[u] = null, v.deletedIds.push(r))
}
}
}
}),
function() {
var e, t;
v.uaMatch = function(e) {
e = e.toLowerCase();
var t = /(chrome)[ \/]([\w.]+)/.exec(e) || /(webkit)[ \/]([\w.]+)/.exec(e) || /(opera)(?:.*version|)[ \/]([\w.]+)/.exec(e) || /(msie) ([\w.]+)/.exec(e) || e.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec(e) || [];
return {
browser: t[1] || "",
version: t[2] || "0"
}
}, e = v.uaMatch(o.userAgent), t = {}, e.browser && (t[e.browser] = !0, t.version = e.version), t.chrome ? t.webkit = !0 : t.webkit && (t.safari = !0), v.browser = t, v.sub = function() {
function e(t, n) {
return new e.fn.init(t, n)
}
v.extend(!0, e, this), e.superclass = this, e.fn = e.prototype = this(), e.fn.constructor = e, e.sub = this.sub, e.fn.init = function(r, i) {
return i && i instanceof v && !(i instanceof e) && (i = e(i)), v.fn.init.call(this, r, i, t)
}, e.fn.init.prototype = e.fn;
var t = e(i);
return e
}
}();
var Dt, Pt, Ht, Bt = /alpha\([^)]*\)/i,
jt = /opacity=([^)]*)/,
Ft = /^(top|right|bottom|left)$/,
It = /^(none|table(?!-c[ea]).+)/,
qt = /^margin/,
Rt = new RegExp("^(" + m + ")(.*)$", "i"),
Ut = new RegExp("^(" + m + ")(?!px)[a-z%]+$", "i"),
zt = new RegExp("^([-+])=(" + m + ")", "i"),
Wt = {
BODY: "block"
},
Xt = {
position: "absolute",
visibility: "hidden",
display: "block"
},
Vt = {
letterSpacing: 0,
fontWeight: 400
},
$t = ["Top", "Right", "Bottom", "Left"],
Jt = ["Webkit", "O", "Moz", "ms"],
Kt = v.fn.toggle;
v.fn.extend({
css: function(e, n) {
return v.access(this, function(e, n, r) {
return r !== t ? v.style(e, n, r) : v.css(e, n)
}, e, n, arguments.length > 1)
},
show: function() {
return Yt(this, !0)
},
hide: function() {
return Yt(this)
},
toggle: function(e, t) {
var n = typeof e == "boolean";
return v.isFunction(e) && v.isFunction(t) ? Kt.apply(this, arguments) : this.each(function() {
(n ? e : Gt(this)) ? v(this).show(): v(this).hide()
})
}
}), v.extend({
cssHooks: {
opacity: {
get: function(e, t) {
if (t) {
var n = Dt(e, "opacity");
return n === "" ? "1" : n
}
}
}
},
cssNumber: {
fillOpacity: !0,
fontWeight: !0,
lineHeight: !0,
opacity: !0,
orphans: !0,
widows: !0,
zIndex: !0,
zoom: !0
},
cssProps: {
"float": v.support.cssFloat ? "cssFloat" : "styleFloat"
},
style: function(e, n, r, i) {
if (!e || e.nodeType === 3 || e.nodeType === 8 || !e.style) return;
var s, o, u, a = v.camelCase(n),
f = e.style;
n = v.cssProps[a] || (v.cssProps[a] = Qt(f, a)), u = v.cssHooks[n] || v.cssHooks[a];
if (r === t) return u && "get" in u && (s = u.get(e, !1, i)) !== t ? s : f[n];
o = typeof r, o === "string" && (s = zt.exec(r)) && (r = (s[1] + 1) * s[2] + parseFloat(v.css(e, n)), o = "number");
if (r == null || o === "number" && isNaN(r)) return;
o === "number" && !v.cssNumber[a] && (r += "px");
if (!u || !("set" in u) || (r = u.set(e, r, i)) !== t) try {
f[n] = r
} catch (l) {}
},
css: function(e, n, r, i) {
var s, o, u, a = v.camelCase(n);
return n = v.cssProps[a] || (v.cssProps[a] = Qt(e.style, a)), u = v.cssHooks[n] || v.cssHooks[a], u && "get" in u && (s = u.get(e, !0, i)), s === t && (s = Dt(e, n)), s === "normal" && n in Vt && (s = Vt[n]), r || i !== t ? (o = parseFloat(s), r || v.isNumeric(o) ? o || 0 : s) : s
},
swap: function(e, t, n) {
var r, i, s = {};
for (i in t) s[i] = e.style[i], e.style[i] = t[i];
r = n.call(e);
for (i in t) e.style[i] = s[i];
return r
}
}), e.getComputedStyle ? Dt = function(t, n) {
var r, i, s, o, u = e.getComputedStyle(t, null),
a = t.style;
return u && (r = u.getPropertyValue(n) || u[n], r === "" && !v.contains(t.ownerDocument, t) && (r = v.style(t, n)), Ut.test(r) && qt.test(n) && (i = a.width, s = a.minWidth, o = a.maxWidth, a.minWidth = a.maxWidth = a.width = r, r = u.width, a.width = i, a.minWidth = s, a.maxWidth = o)), r
} : i.documentElement.currentStyle && (Dt = function(e, t) {
var n, r, i = e.currentStyle && e.currentStyle[t],
s = e.style;
return i == null && s && s[t] && (i = s[t]), Ut.test(i) && !Ft.test(t) && (n = s.left, r = e.runtimeStyle && e.runtimeStyle.left, r && (e.runtimeStyle.left = e.currentStyle.left), s.left = t === "fontSize" ? "1em" : i, i = s.pixelLeft + "px", s.left = n, r && (e.runtimeStyle.left = r)), i === "" ? "auto" : i
}), v.each(["height", "width"], function(e, t) {
v.cssHooks[t] = {
get: function(e, n, r) {
if (n) return e.offsetWidth === 0 && It.test(Dt(e, "display")) ? v.swap(e, Xt, function() {
return tn(e, t, r)
}) : tn(e, t, r)
},
set: function(e, n, r) {
return Zt(e, n, r ? en(e, t, r, v.support.boxSizing && v.css(e, "boxSizing") === "border-box") : 0)
}
}
}), v.support.opacity || (v.cssHooks.opacity = {
get: function(e, t) {
return jt.test((t && e.currentStyle ? e.currentStyle.filter : e.style.filter) || "") ? .01 * parseFloat(RegExp.$1) + "" : t ? "1" : ""
},
set: function(e, t) {
var n = e.style,
r = e.currentStyle,
i = v.isNumeric(t) ? "alpha(opacity=" + t * 100 + ")" : "",
s = r && r.filter || n.filter || "";
n.zoom = 1;
if (t >= 1 && v.trim(s.replace(Bt, "")) === "" && n.removeAttribute) {
n.removeAttribute("filter");
if (r && !r.filter) return
}
n.filter = Bt.test(s) ? s.replace(Bt, i) : s + " " + i
}
}), v(function() {
v.support.reliableMarginRight || (v.cssHooks.marginRight = {
get: function(e, t) {
return v.swap(e, {
display: "inline-block"
}, function() {
if (t) return Dt(e, "marginRight")
})
}
}), !v.support.pixelPosition && v.fn.position && v.each(["top", "left"], function(e, t) {
v.cssHooks[t] = {
get: function(e, n) {
if (n) {
var r = Dt(e, t);
return Ut.test(r) ? v(e).position()[t] + "px" : r
}
}
}
})
}), v.expr && v.expr.filters && (v.expr.filters.hidden = function(e) {
return e.offsetWidth === 0 && e.offsetHeight === 0 || !v.support.reliableHiddenOffsets && (e.style && e.style.display || Dt(e, "display")) === "none"
}, v.expr.filters.visible = function(e) {
return !v.expr.filters.hidden(e)
}), v.each({
margin: "",
padding: "",
border: "Width"
}, function(e, t) {
v.cssHooks[e + t] = {
expand: function(n) {
var r, i = typeof n == "string" ? n.split(" ") : [n],
s = {};
for (r = 0; r < 4; r++) s[e + $t[r] + t] = i[r] || i[r - 2] || i[0];
return s
}
}, qt.test(e) || (v.cssHooks[e + t].set = Zt)
});
var rn = /%20/g,
sn = /\[\]$/,
on = /\r?\n/g,
un = /^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,
an = /^(?:select|textarea)/i;
v.fn.extend({
serialize: function() {
return v.param(this.serializeArray())
},
serializeArray: function() {
return this.map(function() {
return this.elements ? v.makeArray(this.elements) : this
}).filter(function() {
return this.name && !this.disabled && (this.checked || an.test(this.nodeName) || un.test(this.type))
}).map(function(e, t) {
var n = v(this).val();
return n == null ? null : v.isArray(n) ? v.map(n, function(e, n) {
return {
name: t.name,
value: e.replace(on, "\r\n")
}
}) : {
name: t.name,
value: n.replace(on, "\r\n")
}
}).get()
}
}), v.param = function(e, n) {
var r, i = [],
s = function(e, t) {
t = v.isFunction(t) ? t() : t == null ? "" : t, i[i.length] = encodeURIComponent(e) + "=" + encodeURIComponent(t)
};
n === t && (n = v.ajaxSettings && v.ajaxSettings.traditional);
if (v.isArray(e) || e.jquery && !v.isPlainObject(e)) v.each(e, function() {
s(this.name, this.value)
});
else
for (r in e) fn(r, e[r], n, s);
return i.join("&").replace(rn, "+")
};
var ln, cn, hn = /#.*$/,
pn = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg,
dn = /^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,
vn = /^(?:GET|HEAD)$/,
mn = /^\/\//,
gn = /\?/,
yn = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
bn = /([?&])_=[^&]*/,
wn = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,
En = v.fn.load,
Sn = {},
xn = {},
Tn = ["*/"] + ["*"];
try {
cn = s.href
} catch (Nn) {
cn = i.createElement("a"), cn.href = "", cn = cn.href
}
ln = wn.exec(cn.toLowerCase()) || [], v.fn.load = function(e, n, r) {
if (typeof e != "string" && En) return En.apply(this, arguments);
if (!this.length) return this;
var i, s, o, u = this,
a = e.indexOf(" ");
return a >= 0 && (i = e.slice(a, e.length), e = e.slice(0, a)), v.isFunction(n) ? (r = n, n = t) : n && typeof n == "object" && (s = "POST"), v.ajax({
url: e,
type: s,
dataType: "html",
data: n,
complete: function(e, t) {
r && u.each(r, o || [e.responseText, t, e])
}
}).done(function(e) {
o = arguments, u.html(i ? v("<div>").append(e.replace(yn, "")).find(i) : e)
}), this
}, v.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "), function(e, t) {
v.fn[t] = function(e) {
return this.on(t, e)
}
}), v.each(["get", "post"], function(e, n) {
v[n] = function(e, r, i, s) {
return v.isFunction(r) && (s = s || i, i = r, r = t), v.ajax({
type: n,
url: e,
data: r,
success: i,
dataType: s
})
}
}), v.extend({
getScript: function(e, n) {
return v.get(e, t, n, "script")
},
getJSON: function(e, t, n) {
return v.get(e, t, n, "json")
},
ajaxSetup: function(e, t) {
return t ? Ln(e, v.ajaxSettings) : (t = e, e = v.ajaxSettings), Ln(e, t), e
},
ajaxSettings: {
url: cn,
isLocal: dn.test(ln[1]),
global: !0,
type: "GET",
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
processData: !0,
async: !0,
accepts: {
xml: "application/xml, text/xml",
html: "text/html",
text: "text/plain",
json: "application/json, text/javascript",
"*": Tn
},
contents: {
xml: /xml/,
html: /html/,
json: /json/
},
responseFields: {
xml: "responseXML",
text: "responseText"
},
converters: {
"* text": e.String,
"text html": !0,
"text json": v.parseJSON,
"text xml": v.parseXML
},
flatOptions: {
context: !0,
url: !0
}
},
ajaxPrefilter: Cn(Sn),
ajaxTransport: Cn(xn),
ajax: function(e, n) {
function T(e, n, s, a) {
var l, y, b, w, S, T = n;
if (E === 2) return;
E = 2, u && clearTimeout(u), o = t, i = a || "", x.readyState = e > 0 ? 4 : 0, s && (w = An(c, x, s));
if (e >= 200 && e < 300 || e === 304) c.ifModified && (S = x.getResponseHeader("Last-Modified"), S && (v.lastModified[r] = S), S = x.getResponseHeader("Etag"), S && (v.etag[r] = S)), e === 304 ? (T = "notmodified", l = !0) : (l = On(c, w), T = l.state, y = l.data, b = l.error, l = !b);
else {
b = T;
if (!T || e) T = "error", e < 0 && (e = 0)
}
x.status = e, x.statusText = (n || T) + "", l ? d.resolveWith(h, [y, T, x]) : d.rejectWith(h, [x, T, b]), x.statusCode(g), g = t, f && p.trigger("ajax" + (l ? "Success" : "Error"), [x, c, l ? y : b]), m.fireWith(h, [x, T]), f && (p.trigger("ajaxComplete", [x, c]), --v.active || v.event.trigger("ajaxStop"))
}
typeof e == "object" && (n = e, e = t), n = n || {};
var r, i, s, o, u, a, f, l, c = v.ajaxSetup({}, n),
h = c.context || c,
p = h !== c && (h.nodeType || h instanceof v) ? v(h) : v.event,
d = v.Deferred(),
m = v.Callbacks("once memory"),
g = c.statusCode || {},
b = {},
w = {},
E = 0,
S = "canceled",
x = {
readyState: 0,
setRequestHeader: function(e, t) {
if (!E) {
var n = e.toLowerCase();
e = w[n] = w[n] || e, b[e] = t
}
return this
},
getAllResponseHeaders: function() {
return E === 2 ? i : null
},
getResponseHeader: function(e) {
var n;
if (E === 2) {
if (!s) {
s = {};
while (n = pn.exec(i)) s[n[1].toLowerCase()] = n[2]
}
n = s[e.toLowerCase()]
}
return n === t ? null : n
},
overrideMimeType: function(e) {
return E || (c.mimeType = e), this
},
abort: function(e) {
return e = e || S, o && o.abort(e), T(0, e), this
}
};
d.promise(x), x.success = x.done, x.error = x.fail, x.complete = m.add, x.statusCode = function(e) {
if (e) {
var t;
if (E < 2)
for (t in e) g[t] = [g[t], e[t]];
else t = e[x.status], x.always(t)
}
return this
}, c.url = ((e || c.url) + "").replace(hn, "").replace(mn, ln[1] + "//"), c.dataTypes = v.trim(c.dataType || "*").toLowerCase().split(y), c.crossDomain == null && (a = wn.exec(c.url.toLowerCase()), c.crossDomain = !(!a || a[1] === ln[1] && a[2] === ln[2] && (a[3] || (a[1] === "http:" ? 80 : 443)) == (ln[3] || (ln[1] === "http:" ? 80 : 443)))), c.data && c.processData && typeof c.data != "string" && (c.data = v.param(c.data, c.traditional)), kn(Sn, c, n, x);
if (E === 2) return x;
f = c.global, c.type = c.type.toUpperCase(), c.hasContent = !vn.test(c.type), f && v.active++ === 0 && v.event.trigger("ajaxStart");
if (!c.hasContent) {
c.data && (c.url += (gn.test(c.url) ? "&" : "?") + c.data, delete c.data), r = c.url;
if (c.cache === !1) {
var N = v.now(),
C = c.url.replace(bn, "$1_=" + N);
c.url = C + (C === c.url ? (gn.test(c.url) ? "&" : "?") + "_=" + N : "")
}
}(c.data && c.hasContent && c.contentType !== !1 || n.contentType) && x.setRequestHeader("Content-Type", c.contentType), c.ifModified && (r = r || c.url, v.lastModified[r] && x.setRequestHeader("If-Modified-Since", v.lastModified[r]), v.etag[r] && x.setRequestHeader("If-None-Match", v.etag[r])), x.setRequestHeader("Accept", c.dataTypes[0] && c.accepts[c.dataTypes[0]] ? c.accepts[c.dataTypes[0]] + (c.dataTypes[0] !== "*" ? ", " + Tn + "; q=0.01" : "") : c.accepts["*"]);
for (l in c.headers) x.setRequestHeader(l, c.headers[l]);
if (!c.beforeSend || c.beforeSend.call(h, x, c) !== !1 && E !== 2) {
S = "abort";
for (l in {
success: 1,
error: 1,
complete: 1
}) x[l](c[l]);
o = kn(xn, c, n, x);
if (!o) T(-1, "No Transport");
else {
x.readyState = 1, f && p.trigger("ajaxSend", [x, c]), c.async && c.timeout > 0 && (u = setTimeout(function() {
x.abort("timeout")
}, c.timeout));
try {
E = 1, o.send(b, T)
} catch (k) {
if (!(E < 2)) throw k;
T(-1, k)
}
}
return x
}
return x.abort()
},
active: 0,
lastModified: {},
etag: {}
});
var Mn = [],
_n = /\?/,
Dn = /(=)\?(?=&|$)|\?\?/,
Pn = v.now();
v.ajaxSetup({
jsonp: "callback",
jsonpCallback: function() {
var e = Mn.pop() || v.expando + "_" + Pn++;
return this[e] = !0, e
}
}), v.ajaxPrefilter("json jsonp", function(n, r, i) {
var s, o, u, a = n.data,
f = n.url,
l = n.jsonp !== !1,
c = l && Dn.test(f),
h = l && !c && typeof a == "string" && !(n.contentType || "").indexOf("application/x-www-form-urlencoded") && Dn.test(a);
if (n.dataTypes[0] === "jsonp" || c || h) return s = n.jsonpCallback = v.isFunction(n.jsonpCallback) ? n.jsonpCallback() : n.jsonpCallback, o = e[s], c ? n.url = f.replace(Dn, "$1" + s) : h ? n.data = a.replace(Dn, "$1" + s) : l && (n.url += (_n.test(f) ? "&" : "?") + n.jsonp + "=" + s), n.converters["script json"] = function() {
return u || v.error(s + " was not called"), u[0]
}, n.dataTypes[0] = "json", e[s] = function() {
u = arguments
}, i.always(function() {
e[s] = o, n[s] && (n.jsonpCallback = r.jsonpCallback, Mn.push(s)), u && v.isFunction(o) && o(u[0]), u = o = t
}), "script"
}), v.ajaxSetup({
accepts: {
script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
},
contents: {
script: /javascript|ecmascript/
},
converters: {
"text script": function(e) {
return v.globalEval(e), e
}
}
}), v.ajaxPrefilter("script", function(e) {
e.cache === t && (e.cache = !1), e.crossDomain && (e.type = "GET", e.global = !1)
}), v.ajaxTransport("script", function(e) {
if (e.crossDomain) {
var n, r = i.head || i.getElementsByTagName("head")[0] || i.documentElement;
return {
send: function(s, o) {
n = i.createElement("script"), n.async = "async", e.scriptCharset && (n.charset = e.scriptCharset), n.src = e.url, n.onload = n.onreadystatechange = function(e, i) {
if (i || !n.readyState || /loaded|complete/.test(n.readyState)) n.onload = n.onreadystatechange = null, r && n.parentNode && r.removeChild(n), n = t, i || o(200, "success")
}, r.insertBefore(n, r.firstChild)
},
abort: function() {
n && n.onload(0, 1)
}
}
}
});
var Hn, Bn = e.ActiveXObject ? function() {
for (var e in Hn) Hn[e](0, 1)
} : !1,
jn = 0;
v.ajaxSettings.xhr = e.ActiveXObject ? function() {
return !this.isLocal && Fn() || In()
} : Fn,
function(e) {
v.extend(v.support, {
ajax: !!e,
cors: !!e && "withCredentials" in e
})
}(v.ajaxSettings.xhr()), v.support.ajax && v.ajaxTransport(function(n) {
if (!n.crossDomain || v.support.cors) {
var r;
return {
send: function(i, s) {
var o, u, a = n.xhr();
n.username ? a.open(n.type, n.url, n.async, n.username, n.password) : a.open(n.type, n.url, n.async);
if (n.xhrFields)
for (u in n.xhrFields) a[u] = n.xhrFields[u];
n.mimeType && a.overrideMimeType && a.overrideMimeType(n.mimeType), !n.crossDomain && !i["X-Requested-With"] && (i["X-Requested-With"] = "XMLHttpRequest");
try {
for (u in i) a.setRequestHeader(u, i[u])
} catch (f) {}
a.send(n.hasContent && n.data || null), r = function(e, i) {
var u, f, l, c, h;
try {
if (r && (i || a.readyState === 4)) {
r = t, o && (a.onreadystatechange = v.noop, Bn && delete Hn[o]);
if (i) a.readyState !== 4 && a.abort();
else {
u = a.status, l = a.getAllResponseHeaders(), c = {}, h = a.responseXML, h && h.documentElement && (c.xml = h);
try {
c.text = a.responseText
} catch (p) {}
try {
f = a.statusText
} catch (p) {
f = ""
}!u && n.isLocal && !n.crossDomain ? u = c.text ? 200 : 404 : u === 1223 && (u = 204)
}
}
} catch (d) {
i || s(-1, d)
}
c && s(u, f, c, l)
}, n.async ? a.readyState === 4 ? setTimeout(r, 0) : (o = ++jn, Bn && (Hn || (Hn = {}, v(e).unload(Bn)), Hn[o] = r), a.onreadystatechange = r) : r()
},
abort: function() {
r && r(0, 1)
}
}
}
});
var qn, Rn, Un = /^(?:toggle|show|hide)$/,
zn = new RegExp("^(?:([-+])=|)(" + m + ")([a-z%]*)$", "i"),
Wn = /queueHooks$/,
Xn = [Gn],
Vn = {
"*": [function(e, t) {
var n, r, i = this.createTween(e, t),
s = zn.exec(t),
o = i.cur(),
u = +o || 0,
a = 1,
f = 20;
if (s) {
n = +s[2], r = s[3] || (v.cssNumber[e] ? "" : "px");
if (r !== "px" && u) {
u = v.css(i.elem, e, !0) || n || 1;
do a = a || ".5", u /= a, v.style(i.elem, e, u + r); while (a !== (a = i.cur() / o) && a !== 1 && --f)
}
i.unit = r, i.start = u, i.end = s[1] ? u + (s[1] + 1) * n : n
}
return i
}]
};
v.Animation = v.extend(Kn, {
tweener: function(e, t) {
v.isFunction(e) ? (t = e, e = ["*"]) : e = e.split(" ");
var n, r = 0,
i = e.length;
for (; r < i; r++) n = e[r], Vn[n] = Vn[n] || [], Vn[n].unshift(t)
},
prefilter: function(e, t) {
t ? Xn.unshift(e) : Xn.push(e)
}
}), v.Tween = Yn, Yn.prototype = {
constructor: Yn,
init: function(e, t, n, r, i, s) {
this.elem = e, this.prop = n, this.easing = i || "swing", this.options = t, this.start = this.now = this.cur(), this.end = r, this.unit = s || (v.cssNumber[n] ? "" : "px")
},
cur: function() {
var e = Yn.propHooks[this.prop];
return e && e.get ? e.get(this) : Yn.propHooks._default.get(this)
},
run: function(e) {
var t, n = Yn.propHooks[this.prop];
return this.options.duration ? this.pos = t = v.easing[this.easing](e, this.options.duration * e, 0, 1, this.options.duration) : this.pos = t = e, this.now = (this.end - this.start) * t + this.start, this.options.step && this.options.step.call(this.elem, this.now, this), n && n.set ? n.set(this) : Yn.propHooks._default.set(this), this
}
}, Yn.prototype.init.prototype = Yn.prototype, Yn.propHooks = {
_default: {
get: function(e) {
var t;
return e.elem[e.prop] == null || !!e.elem.style && e.elem.style[e.prop] != null ? (t = v.css(e.elem, e.prop, !1, ""), !t || t === "auto" ? 0 : t) : e.elem[e.prop]
},
set: function(e) {
v.fx.step[e.prop] ? v.fx.step[e.prop](e) : e.elem.style && (e.elem.style[v.cssProps[e.prop]] != null || v.cssHooks[e.prop]) ? v.style(e.elem, e.prop, e.now + e.unit) : e.elem[e.prop] = e.now
}
}
}, Yn.propHooks.scrollTop = Yn.propHooks.scrollLeft = {
set: function(e) {
e.elem.nodeType && e.elem.parentNode && (e.elem[e.prop] = e.now)
}
}, v.each(["toggle", "show", "hide"], function(e, t) {
var n = v.fn[t];
v.fn[t] = function(r, i, s) {
return r == null || typeof r == "boolean" || !e && v.isFunction(r) && v.isFunction(i) ? n.apply(this, arguments) : this.animate(Zn(t, !0), r, i, s)
}
}), v.fn.extend({
fadeTo: function(e, t, n, r) {
return this.filter(Gt).css("opacity", 0).show().end().animate({
opacity: t
}, e, n, r)
},
animate: function(e, t, n, r) {
var i = v.isEmptyObject(e),
s = v.speed(t, n, r),
o = function() {
var t = Kn(this, v.extend({}, e), s);
i && t.stop(!0)
};
return i || s.queue === !1 ? this.each(o) : this.queue(s.queue, o)
},
stop: function(e, n, r) {
var i = function(e) {
var t = e.stop;
delete e.stop, t(r)
};
return typeof e != "string" && (r = n, n = e, e = t), n && e !== !1 && this.queue(e || "fx", []), this.each(function() {
var t = !0,
n = e != null && e + "queueHooks",
s = v.timers,
o = v._data(this);
if (n) o[n] && o[n].stop && i(o[n]);
else
for (n in o) o[n] && o[n].stop && Wn.test(n) && i(o[n]);
for (n = s.length; n--;) s[n].elem === this && (e == null || s[n].queue === e) && (s[n].anim.stop(r), t = !1, s.splice(n, 1));
(t || !r) && v.dequeue(this, e)
})
}
}), v.each({
slideDown: Zn("show"),
slideUp: Zn("hide"),
slideToggle: Zn("toggle"),
fadeIn: {
opacity: "show"
},
fadeOut: {
opacity: "hide"
},
fadeToggle: {
opacity: "toggle"
}
}, function(e, t) {
v.fn[e] = function(e, n, r) {
return this.animate(t, e, n, r)
}
}), v.speed = function(e, t, n) {
var r = e && typeof e == "object" ? v.extend({}, e) : {
complete: n || !n && t || v.isFunction(e) && e,
duration: e,
easing: n && t || t && !v.isFunction(t) && t
};
r.duration = v.fx.off ? 0 : typeof r.duration == "number" ? r.duration : r.duration in v.fx.speeds ? v.fx.speeds[r.duration] : v.fx.speeds._default;
if (r.queue == null || r.queue === !0) r.queue = "fx";
return r.old = r.complete, r.complete = function() {
v.isFunction(r.old) && r.old.call(this), r.queue && v.dequeue(this, r.queue)
}, r
}, v.easing = {
linear: function(e) {
return e
},
swing: function(e) {
return .5 - Math.cos(e * Math.PI) / 2
}
}, v.timers = [], v.fx = Yn.prototype.init, v.fx.tick = function() {
var e, n = v.timers,
r = 0;
qn = v.now();
for (; r < n.length; r++) e = n[r], !e() && n[r] === e && n.splice(r--, 1);
n.length || v.fx.stop(), qn = t
}, v.fx.timer = function(e) {
e() && v.timers.push(e) && !Rn && (Rn = setInterval(v.fx.tick, v.fx.interval))
}, v.fx.interval = 13, v.fx.stop = function() {
clearInterval(Rn), Rn = null
}, v.fx.speeds = {
slow: 600,
fast: 200,
_default: 400
}, v.fx.step = {}, v.expr && v.expr.filters && (v.expr.filters.animated = function(e) {
return v.grep(v.timers, function(t) {
return e === t.elem
}).length
});
var er = /^(?:body|html)$/i;
v.fn.offset = function(e) {
if (arguments.length) return e === t ? this : this.each(function(t) {
v.offset.setOffset(this, e, t)
});
var n, r, i, s, o, u, a, f = {
top: 0,
left: 0
},
l = this[0],
c = l && l.ownerDocument;
if (!c) return;
return (r = c.body) === l ? v.offset.bodyOffset(l) : (n = c.documentElement, v.contains(n, l) ? (typeof l.getBoundingClientRect != "undefined" && (f = l.getBoundingClientRect()), i = tr(c), s = n.clientTop || r.clientTop || 0, o = n.clientLeft || r.clientLeft || 0, u = i.pageYOffset || n.scrollTop, a = i.pageXOffset || n.scrollLeft, {
top: f.top + u - s,
left: f.left + a - o
}) : f)
}, v.offset = {
bodyOffset: function(e) {
var t = e.offsetTop,
n = e.offsetLeft;
return v.support.doesNotIncludeMarginInBodyOffset && (t += parseFloat(v.css(e, "marginTop")) || 0, n += parseFloat(v.css(e, "marginLeft")) || 0), {
top: t,
left: n
}
},
setOffset: function(e, t, n) {
var r = v.css(e, "position");
r === "static" && (e.style.position = "relative");
var i = v(e),
s = i.offset(),
o = v.css(e, "top"),
u = v.css(e, "left"),
a = (r === "absolute" || r === "fixed") && v.inArray("auto", [o, u]) > -1,
f = {},
l = {},
c, h;
a ? (l = i.position(), c = l.top, h = l.left) : (c = parseFloat(o) || 0, h = parseFloat(u) || 0), v.isFunction(t) && (t = t.call(e, n, s)), t.top != null && (f.top = t.top - s.top + c), t.left != null && (f.left = t.left - s.left + h), "using" in t ? t.using.call(e, f) : i.css(f)
}
}, v.fn.extend({
position: function() {
if (!this[0]) return;
var e = this[0],
t = this.offsetParent(),
n = this.offset(),
r = er.test(t[0].nodeName) ? {
top: 0,
left: 0
} : t.offset();
return n.top -= parseFloat(v.css(e, "marginTop")) || 0, n.left -= parseFloat(v.css(e, "marginLeft")) || 0, r.top += parseFloat(v.css(t[0], "borderTopWidth")) || 0, r.left += parseFloat(v.css(t[0], "borderLeftWidth")) || 0, {
top: n.top - r.top,
left: n.left - r.left
}
},
offsetParent: function() {
return this.map(function() {
var e = this.offsetParent || i.body;
while (e && !er.test(e.nodeName) && v.css(e, "position") === "static") e = e.offsetParent;
return e || i.body
})
}
}), v.each({
scrollLeft: "pageXOffset",
scrollTop: "pageYOffset"
}, function(e, n) {
var r = /Y/.test(n);
v.fn[e] = function(i) {
return v.access(this, function(e, i, s) {
var o = tr(e);
if (s === t) return o ? n in o ? o[n] : o.document.documentElement[i] : e[i];
o ? o.scrollTo(r ? v(o).scrollLeft() : s, r ? s : v(o).scrollTop()) : e[i] = s
}, e, i, arguments.length, null)
}
}), v.each({
Height: "height",
Width: "width"
}, function(e, n) {
v.each({
padding: "inner" + e,
content: n,
"": "outer" + e
}, function(r, i) {
v.fn[i] = function(i, s) {
var o = arguments.length && (r || typeof i != "boolean"),
u = r || (i === !0 || s === !0 ? "margin" : "border");
return v.access(this, function(n, r, i) {
var s;
return v.isWindow(n) ? n.document.documentElement["client" + e] : n.nodeType === 9 ? (s = n.documentElement, Math.max(n.body["scroll" + e], s["scroll" + e], n.body["offset" + e], s["offset" + e], s["client" + e])) : i === t ? v.css(n, r, i, u) : v.style(n, r, i, u)
}, n, o ? i : t, o, null)
}
})
}), e.jQuery = e.$ = v, typeof define == "function" && define.amd && define.amd.jQuery && define("jquery", [], function() {
return v
})
})(window),
function(e, t) {
var n = function() {
var t = e._data(document, "events");
return t && t.click && e.grep(t.click, function(e) {
return e.namespace === "rails"
}).length
};
n() && e.error("jquery-ujs has already been loaded!");
var r;
e.rails = r = {
linkClickSelector: "a[data-confirm], a[data-method], a[data-remote], a[data-disable-with]",
inputChangeSelector: "select[data-remote], input[data-remote], textarea[data-remote]",
formSubmitSelector: "form",
formInputClickSelector: "form input[type=submit], form input[type=image], form button[type=submit], form button:not([type])",
disableSelector: "input[data-disable-with], button[data-disable-with], textarea[data-disable-with]",
enableSelector: "input[data-disable-with]:disabled, button[data-disable-with]:disabled, textarea[data-disable-with]:disabled",
requiredInputSelector: "input[name][required]:not([disabled]),textarea[name][required]:not([disabled])",
fileInputSelector: "input:file",
linkDisableSelector: "a[data-disable-with]",
CSRFProtection: function(t) {
var n = e('meta[name="csrf-token"]').attr("content");
n && t.setRequestHeader("X-CSRF-Token", n)
},
fire: function(t, n, r) {
var i = e.Event(n);
return t.trigger(i, r), i.result !== !1
},
confirm: function(e) {
return confirm(e)
},
ajax: function(t) {
return e.ajax(t)
},
href: function(e) {
return e.attr("href")
},
handleRemote: function(n) {
var i, s, o, u, a, f, l, c;
if (r.fire(n, "ajax:before")) {
u = n.data("cross-domain"), a = u === t ? null : u, f = n.data("with-credentials") || null, l = n.data("type") || e.ajaxSettings && e.ajaxSettings.dataType;
if (n.is("form")) {
i = n.attr("method"), s = n.attr("action"), o = n.serializeArray();
var h = n.data("ujs:submit-button");
h && (o.push(h), n.data("ujs:submit-button", null))
} else n.is(r.inputChangeSelector) ? (i = n.data("method"), s = n.data("url"), o = n.serialize(), n.data("params") && (o = o + "&" + n.data("params"))) : (i = n.data("method"), s = r.href(n), o = n.data("params") || null);
c = {
type: i || "GET",
data: o,
dataType: l,
beforeSend: function(e, i) {
return i.dataType === t && e.setRequestHeader("accept", "*/*;q=0.5, " + i.accepts.script), r.fire(n, "ajax:beforeSend", [e, i])
},
success: function(e, t, r) {
n.trigger("ajax:success", [e, t, r])
},
complete: function(e, t) {
n.trigger("ajax:complete", [e, t])
},
error: function(e, t, r) {
n.trigger("ajax:error", [e, t, r])
},
xhrFields: {
withCredentials: f
},
crossDomain: a
}, s && (c.url = s);
var p = r.ajax(c);
return n.trigger("ajax:send", p), p
}
return !1
},
handleMethod: function(n) {
var i = r.href(n),
s = n.data("method"),
o = n.attr("target"),
u = e("meta[name=csrf-token]").attr("content"),
a = e("meta[name=csrf-param]").attr("content"),
f = e('<form method="post" action="' + i + '"></form>'),
l = '<input name="_method" value="' + s + '" type="hidden" />';
a !== t && u !== t && (l += '<input name="' + a + '" value="' + u + '" type="hidden" />'), o && f.attr("target", o), f.hide().append(l).appendTo("body"), f.submit()
},
disableFormElements: function(t) {
t.find(r.disableSelector).each(function() {
var t = e(this),
n = t.is("button") ? "html" : "val";
t.data("ujs:enable-with", t[n]()), t[n](t.data("disable-with")), t.prop("disabled", !0)
})
},
enableFormElements: function(t) {
t.find(r.enableSelector).each(function() {
var t = e(this),
n = t.is("button") ? "html" : "val";
t.data("ujs:enable-with") && t[n](t.data("ujs:enable-with")), t.prop("disabled", !1)
})
},
allowAction: function(e) {
var t = e.data("confirm"),
n = !1,
i;
return t ? (r.fire(e, "confirm") && (n = r.confirm(t), i = r.fire(e, "confirm:complete", [n])), n && i) : !0
},
blankInputs: function(t, n, r) {
var i = e(),
s, o, u = n || "input,textarea",
a = t.find(u);
return a.each(function() {
s = e(this), o = s.is(":checkbox,:radio") ? s.is(":checked") : s.val();
if (!o == !r) {
if (s.is(":radio") && a.filter('input:radio:checked[name="' + s.attr("name") + '"]').length) return !0;
i = i.add(s)
}
}), i.length ? i : !1
},
nonBlankInputs: function(e, t) {
return r.blankInputs(e, t, !0)
},
stopEverything: function(t) {
return e(t.target).trigger("ujs:everythingStopped"), t.stopImmediatePropagation(), !1
},
callFormSubmitBindings: function(n, r) {
var i = n.data("events"),
s = !0;
return i !== t && i.submit !== t && e.each(i.submit, function(e, t) {
if (typeof t.handler == "function") return s = t.handler(r)
}), s
},
disableElement: function(e) {
e.data("ujs:enable-with", e.html()), e.html(e.data("disable-with")), e.bind("click.railsDisable", function(e) {
return r.stopEverything(e)
})
},
enableElement: function(e) {
e.data("ujs:enable-with") !== t && (e.html(e.data("ujs:enable-with")), e.data("ujs:enable-with", !1)), e.unbind("click.railsDisable")
}
}, r.fire(e(document), "rails:attachBindings") && (e.ajaxPrefilter(function(e, t, n) {
e.crossDomain || r.CSRFProtection(n)
}), e(document).delegate(r.linkDisableSelector, "ajax:complete", function() {
r.enableElement(e(this))
}), e(document).delegate(r.linkClickSelector, "click.rails", function(n) {
var i = e(this),
s = i.data("method"),
o = i.data("params");
if (!r.allowAction(i)) return r.stopEverything(n);
i.is(r.linkDisableSelector) && r.disableElement(i);
if (i.data("remote") !== t) {
if ((n.metaKey || n.ctrlKey) &&
(!s || s === "GET") && !o) return !0;
var u = r.handleRemote(i);
return u === !1 ? r.enableElement(i) : u.error(function() {
r.enableElement(i)
}), !1
}
if (i.data("method")) return r.handleMethod(i), !1
}), e(document).delegate(r.inputChangeSelector, "change.rails", function(t) {
var n = e(this);
return r.allowAction(n) ? (r.handleRemote(n), !1) : r.stopEverything(t)
}), e(document).delegate(r.formSubmitSelector, "submit.rails", function(n) {
var i = e(this),
s = i.data("remote") !== t,
o = r.blankInputs(i, r.requiredInputSelector),
u = r.nonBlankInputs(i, r.fileInputSelector);
if (!r.allowAction(i)) return r.stopEverything(n);
if (o && i.attr("novalidate") == t && r.fire(i, "ajax:aborted:required", [o])) return r.stopEverything(n);
if (s) {
if (u) {
setTimeout(function() {
r.disableFormElements(i)
}, 13);
var a = r.fire(i, "ajax:aborted:file", [u]);
return a || setTimeout(function() {
r.enableFormElements(i)
}, 13), a
}
return !e.support.submitBubbles && e().jquery < "1.7" && r.callFormSubmitBindings(i, n) === !1 ? r.stopEverything(n) : (r.handleRemote(i), !1)
}
setTimeout(function() {
r.disableFormElements(i)
}, 13)
}), e(document).delegate(r.formInputClickSelector, "click.rails", function(t) {
var n = e(this);
if (!r.allowAction(n)) return r.stopEverything(t);
var i = n.attr("name"),
s = i ? {
name: i,
value: n.val()
} : null;
n.closest("form").data("ujs:submit-button", s)
}), e(document).delegate(r.formSubmitSelector, "ajax:beforeSend.rails", function(t) {
this == t.target && r.disableFormElements(e(this))
}), e(document).delegate(r.formSubmitSelector, "ajax:complete.rails", function(t) {
this == t.target && r.enableFormElements(e(this))
}), e(function() {
csrf_token = e("meta[name=csrf-token]").attr("content"), csrf_param = e("meta[name=csrf-param]").attr("content"), e('form input[name="' + csrf_param + '"]').val(csrf_token)
}))
}(jQuery), ! function(e) {
"use strict";
e(function() {
e.support.transition = function() {
var e = function() {
var e = document.createElement("bootstrap"),
t = {
WebkitTransition: "webkitTransitionEnd",
MozTransition: "transitionend",
OTransition: "oTransitionEnd otransitionend",
transition: "transitionend"
},
n;
for (n in t)
if (e.style[n] !== undefined) return t[n]
}();
return e && {
end: e
}
}()
})
}(window.jQuery), ! function(e) {
"use strict";
var t = '[data-dismiss="alert"]',
n = function(n) {
e(n).on("click", t, this.close)
};
n.prototype.close = function(t) {
function s() {
i.trigger("closed").remove()
}
var n = e(this),
r = n.attr("data-target"),
i;
r || (r = n.attr("href"), r = r && r.replace(/.*(?=#[^\s]*$)/, "")), i = e(r), t && t.preventDefault(), i.length || (i = n.hasClass("alert") ? n : n.parent()), i.trigger(t = e.Event("close"));
if (t.isDefaultPrevented()) return;
i.removeClass("in"), e.support.transition && i.hasClass("fade") ? i.on(e.support.transition.end, s) : s()
}, e.fn.alert = function(t) {
return this.each(function() {
var r = e(this),
i = r.data("alert");
i || r.data("alert", i = new n(this)), typeof t == "string" && i[t].call(r)
})
}, e.fn.alert.Constructor = n, e(document).on("click.alert.data-api", t, n.prototype.close)
}(window.jQuery), ! function(e) {
"use strict";
var t = function(t, n) {
this.options = n, this.$element = e(t).delegate('[data-dismiss="modal"]', "click.dismiss.modal", e.proxy(this.hide, this)), this.options.remote && this.$element.find(".modal-body").load(this.options.remote)
};
t.prototype = {
constructor: t,
toggle: function() {
return this[this.isShown ? "hide" : "show"]()
},
show: function() {
var t = this,
n = e.Event("show");
this.$element.trigger(n);
if (this.isShown || n.isDefaultPrevented()) return;
this.isShown = !0, this.escape(), this.backdrop(function() {
var n = e.support.transition && t.$element.hasClass("fade");
t.$element.parent().length || t.$element.appendTo(document.body), t.$element.show(), n && t.$element[0].offsetWidth, t.$element.addClass("in").attr("aria-hidden", !1), t.enforceFocus(), n ? t.$element.one(e.support.transition.end, function() {
t.$element.focus().trigger("shown")
}) : t.$element.focus().trigger("shown")
})
},
hide: function(t) {
t && t.preventDefault();
var n = this;
t = e.Event("hide"), this.$element.trigger(t);
if (!this.isShown || t.isDefaultPrevented()) return;
this.isShown = !1, this.escape(), e(document).off("focusin.modal"), this.$element.removeClass("in").attr("aria-hidden", !0), e.support.transition && this.$element.hasClass("fade") ? this.hideWithTransition() : this.hideModal()
},
enforceFocus: function() {
var t = this;
e(document).on("focusin.modal", function(e) {
t.$element[0] !== e.target && !t.$element.has(e.target).length && t.$element.focus()
})
},
escape: function() {
var e = this;
this.isShown && this.options.keyboard ? this.$element.on("keyup.dismiss.modal", function(t) {
t.which == 27 && e.hide()
}) : this.isShown || this.$element.off("keyup.dismiss.modal")
},
hideWithTransition: function() {
var t = this,
n = setTimeout(function() {
t.$element.off(e.support.transition.end), t.hideModal()
}, 500);
this.$element.one(e.support.transition.end, function() {
clearTimeout(n), t.hideModal()
})
},
hideModal: function(e) {
this.$element.hide().trigger("hidden"), this.backdrop()
},
removeBackdrop: function() {
this.$backdrop.remove(), this.$backdrop = null
},
backdrop: function(t) {
var n = this,
r = this.$element.hasClass("fade") ? "fade" : "";
if (this.isShown && this.options.backdrop) {
var i = e.support.transition && r;
this.$backdrop = e('<div class="modal-backdrop ' + r + '" />').appendTo(document.body), this.$backdrop.click(this.options.backdrop == "static" ? e.proxy(this.$element[0].focus, this.$element[0]) : e.proxy(this.hide, this)), i && this.$backdrop[0].offsetWidth, this.$backdrop.addClass("in"), i ? this.$backdrop.one(e.support.transition.end, t) : t()
} else !this.isShown && this.$backdrop ? (this.$backdrop.removeClass("in"), e.support.transition && this.$element.hasClass("fade") ? this.$backdrop.one(e.support.transition.end, e.proxy(this.removeBackdrop, this)) : this.removeBackdrop()) : t && t()
}
}, e.fn.modal = function(n) {
return this.each(function() {
var r = e(this),
i = r.data("modal"),
s = e.extend({}, e.fn.modal.defaults, r.data(), typeof n == "object" && n);
i || r.data("modal", i = new t(this, s)), typeof n == "string" ? i[n]() : s.show && i.show()
})
}, e.fn.modal.defaults = {
backdrop: !0,
keyboard: !0,
show: !0
}, e.fn.modal.Constructor = t, e(document).on("click.modal.data-api", '[data-toggle="modal"]', function(t) {
var n = e(this),
r = n.attr("href"),
i = e(n.attr("data-target") || r && r.replace(/.*(?=#[^\s]+$)/, "")),
s = i.data("modal") ? "toggle" : e.extend({
remote: !/#/.test(r) && r
}, i.data(), n.data());
t.preventDefault(), i.modal(s).one("hide", function() {
n.focus()
})
})
}(window.jQuery), ! function(e) {
"use strict";
function r() {
e(t).each(function() {
i(e(this)).removeClass("open")
})
}
function i(t) {
var n = t.attr("data-target"),
r;
return n || (n = t.attr("href"), n = n && /#/.test(n) && n.replace(/.*(?=#[^\s]*$)/, "")), r = e(n), r.length || (r = t.parent()), r
}
var t = "[data-toggle=dropdown]",
n = function(t) {
var n = e(t).on("click.dropdown.data-api", this.toggle);
e("html").on("click.dropdown.data-api", function() {
n.parent().removeClass("open")
})
};
n.prototype = {
constructor: n,
toggle: function(t) {
var n = e(this),
s, o;
if (n.is(".disabled, :disabled")) return;
return s = i(n), o = s.hasClass("open"), r(), o || (s.toggleClass("open"), n.focus()), !1
},
keydown: function(t) {
var n, r, s, o, u, a;
if (!/(38|40|27)/.test(t.keyCode)) return;
n = e(this), t.preventDefault(), t.stopPropagation();
if (n.is(".disabled, :disabled")) return;
o = i(n), u = o.hasClass("open");
if (!u || u && t.keyCode == 27) return n.click();
r = e("[role=menu] li:not(.divider) a", o);
if (!r.length) return;
a = r.index(r.filter(":focus")), t.keyCode == 38 && a > 0 && a--, t.keyCode == 40 && a < r.length - 1 && a++, ~a || (a = 0), r.eq(a).focus()
}
}, e.fn.dropdown = function(t) {
return this.each(function() {
var r = e(this),
i = r.data("dropdown");
i || r.data("dropdown", i = new n(this)), typeof t == "string" && i[t].call(r)
})
}, e.fn.dropdown.Constructor = n, e(document).on("click.dropdown.data-api touchstart.dropdown.data-api", r).on("click.dropdown touchstart.dropdown.data-api", ".dropdown form", function(e) {
e.stopPropagation()
}).on("click.dropdown.data-api touchstart.dropdown.data-api", t, n.prototype.toggle).on("keydown.dropdown.data-api touchstart.dropdown.data-api", t + ", [role=menu]", n.prototype.keydown)
}(window.jQuery), ! function(e) {
"use strict";
function t(t, n) {
var r = e.proxy(this.process, this),
i = e(t).is("body") ? e(window) : e(t),
s;
this.options = e.extend({}, e.fn.scrollspy.defaults, n), this.$scrollElement = i.on("scroll.scroll-spy.data-api", r), this.selector = (this.options.target || (s = e(t).attr("href")) && s.replace(/.*(?=#[^\s]+$)/, "") || "") + " .nav li > a", this.$body = e("body"), this.refresh(), this.process()
}
t.prototype = {
constructor: t,
refresh: function() {
var t = this,
n;
this.offsets = e([]), this.targets = e([]), n = this.$body.find(this.selector).map(function() {
var t = e(this),
n = t.data("target") || t.attr("href"),
r = /^#\w/.test(n) && e(n);
return r && r.length && [
[r.position().top, n]
] || null
}).sort(function(e, t) {
return e[0] - t[0]
}).each(function() {
t.offsets.push(this[0]), t.targets.push(this[1])
})
},
process: function() {
var e = this.$scrollElement.scrollTop() + this.options.offset,
t = this.$scrollElement[0].scrollHeight || this.$body[0].scrollHeight,
n = t - this.$scrollElement.height(),
r = this.offsets,
i = this.targets,
s = this.activeTarget,
o;
if (e >= n) return s != (o = i.last()[0]) && this.activate(o);
for (o = r.length; o--;) s != i[o] && e >= r[o] && (!r[o + 1] || e <= r[o + 1]) && this.activate(i[o])
},
activate: function(t) {
var n, r;
this.activeTarget = t, e(this.selector).parent(".active").removeClass("active"), r = this.selector + '[data-target="' + t + '"],' + this.selector + '[href="' + t + '"]', n = e(r).parent("li").addClass("active"), n.parent(".dropdown-menu").length && (n = n.closest("li.dropdown").addClass("active")), n.trigger("activate")
}
}, e.fn.scrollspy = function(n) {
return this.each(function() {
var r = e(this),
i = r.data("scrollspy"),
s = typeof n == "object" && n;
i || r.data("scrollspy", i = new t(this, s)), typeof n == "string" && i[n]()
})
}, e.fn.scrollspy.Constructor = t, e.fn.scrollspy.defaults = {
offset: 10
}, e(window).on("load", function() {
e('[data-spy="scroll"]').each(function() {
var t = e(this);
t.scrollspy(t.data())
})
})
}(window.jQuery), ! function(e) {
"use strict";
var t = function(t) {
this.element = e(t)
};
t.prototype = {
constructor: t,
show: function() {
var t = this.element,
n = t.closest("ul:not(.dropdown-menu)"),
r = t.attr("data-target"),
i, s, o;
r || (r = t.attr("href"), r = r && r.replace(/.*(?=#[^\s]*$)/, ""));
if (t.parent("li").hasClass("active")) return;
i = n.find(".active:last a")[0], o = e.Event("show", {
relatedTarget: i
}), t.trigger(o);
if (o.isDefaultPrevented()) return;
s = e(r), this.activate(t.parent("li"), n), this.activate(s, s.parent(), function() {
t.trigger({
type: "shown",
relatedTarget: i
})
})
},
activate: function(t, n, r) {
function o() {
i.removeClass("active").find("> .dropdown-menu > .active").removeClass("active"), t.addClass("active"), s ? (t[0].offsetWidth, t.addClass("in")) : t.removeClass("fade"), t.parent(".dropdown-menu") && t.closest("li.dropdown").addClass("active"), r && r()
}
var i = n.find("> .active"),
s = r && e.support.transition && i.hasClass("fade");
s ? i.one(e.support.transition.end, o) : o(), i.removeClass("in")
}
}, e.fn.tab = function(n) {
return this.each(function() {
var r = e(this),
i = r.data("tab");
i || r.data("tab", i = new t(this)), typeof n == "string" && i[n]()
})
}, e.fn.tab.Constructor = t, e(document).on("click.tab.data-api", '[data-toggle="tab"], [data-toggle="pill"]', function(t) {
t.preventDefault(), e(this).tab("show")
})
}(window.jQuery), ! function(e) {
"use strict";
var t = function(e, t) {
this.init("tooltip", e, t)
};
t.prototype = {
constructor: t,
init: function(t, n, r) {
var i, s;
this.type = t, this.$element = e(n), this.options = this.getOptions(r), this.enabled = !0, this.options.trigger == "click" ? this.$element.on("click." + this.type, this.options.selector, e.proxy(this.toggle, this)) : this.options.trigger != "manual" && (i = this.options.trigger == "hover" ? "mouseenter" : "focus", s = this.options.trigger == "hover" ? "mouseleave" : "blur", this.$element.on(i + "." + this.type, this.options.selector, e.proxy(this.enter, this)), this.$element.on(s + "." + this.type, this.options.selector, e.proxy(this.leave, this))), this.options.selector ? this._options = e.extend({}, this.options, {
trigger: "manual",
selector: ""
}) : this.fixTitle()
},
getOptions: function(t) {
return t = e.extend({}, e.fn[this.type].defaults, t, this.$element.data()), t.delay && typeof t.delay == "number" && (t.delay = {
show: t.delay,
hide: t.delay
}), t
},
enter: function(t) {
var n = e(t.currentTarget)[this.type](this._options).data(this.type);
if (!n.options.delay || !n.options.delay.show) return n.show();
clearTimeout(this.timeout), n.hoverState = "in", this.timeout = setTimeout(function() {
n.hoverState == "in" && n.show()
}, n.options.delay.show)
},
leave: function(t) {
var n = e(t.currentTarget)[this.type](this._options).data(this.type);
this.timeout && clearTimeout(this.timeout);
if (!n.options.delay || !n.options.delay.hide) return n.hide();
n.hoverState = "out", this.timeout = setTimeout(function() {
n.hoverState == "out" && n.hide()
}, n.options.delay.hide)
},
show: function() {
var e, t, n, r, i, s, o;
if (this.hasContent() && this.enabled) {
e = this.tip(), this.setContent(), this.options.animation && e.addClass("fade"), s = typeof this.options.placement == "function" ? this.options.placement.call(this, e[0], this.$element[0]) : this.options.placement, t = /in/.test(s), e.detach().css({
top: 0,
left: 0,
display: "block"
}).insertAfter(this.$element), n = this.getPosition(t), r = e[0].offsetWidth, i = e[0].offsetHeight;
switch (t ? s.split(" ")[1] : s) {
case "bottom":
o = {
top: n.top + n.height,
left: n.left + n.width / 2 - r / 2
};
break;
case "top":
o = {
top: n.top - i,
left: n.left + n.width / 2 - r / 2
};
break;
case "left":
o = {
top: n.top + n.height / 2 - i / 2,
left: n.left - r
};
break;
case "right":
o = {
top: n.top + n.height / 2 - i / 2,
left: n.left + n.width
}
}
e.offset(o).addClass(s).addClass("in")
}
},
setContent: function() {
var e = this.tip(),
t = this.getTitle();
e.find(".tooltip-inner")[this.options.html ? "html" : "text"](t), e.removeClass("fade in top bottom left right")
},
hide: function() {
function r() {
var t = setTimeout(function() {
n.off(e.support.transition.end).detach()
}, 500);
n.one(e.support.transition.end, function() {
clearTimeout(t), n.detach()
})
}
var t = this,
n = this.tip();
return n.removeClass("in"), e.support.transition && this.$tip.hasClass("fade") ? r() : n.detach(), this
},
fixTitle: function() {
var e = this.$element;
(e.attr("title") || typeof e.attr("data-original-title") != "string") && e.attr("data-original-title", e.attr("title") || "").removeAttr("title")
},
hasContent: function() {
return this.getTitle()
},
getPosition: function(t) {
return e.extend({}, t ? {
top: 0,
left: 0
} : this.$element.offset(), {
width: this.$element[0].offsetWidth,
height: this.$element[0].offsetHeight
})
},
getTitle: function() {
var e, t = this.$element,
n = this.options;
return e = t.attr("data-original-title") || (typeof n.title == "function" ? n.title.call(t[0]) : n.title), e
},
tip: function() {
return this.$tip = this.$tip || e(this.options.template)
},
validate: function() {
this.$element[0].parentNode || (this.hide(), this.$element = null, this.options = null)
},
enable: function() {
this.enabled = !0
},
disable: function() {
this.enabled = !1
},
toggleEnabled: function() {
this.enabled = !this.enabled
},
toggle: function(t) {
var n = e(t.currentTarget)[this.type](this._options).data(this.type);
n[n.tip().hasClass("in") ? "hide" : "show"]()
},
destroy: function() {
this.hide().$element.off("." + this.type).removeData(this.type)
}
}, e.fn.tooltip = function(n) {
return this.each(function() {
var r = e(this),
i = r.data("tooltip"),
s = typeof n == "object" && n;
i || r.data("tooltip", i = new t(this, s)), typeof n == "string" && i[n]()
})
}, e.fn.tooltip.Constructor = t, e.fn.tooltip.defaults = {
animation: !0,
placement: "top",
selector: !1,
template: '<div class="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>',
trigger: "hover",
title: "",
delay: 0,
html: !1
}
}(window.jQuery), ! function(e) {
"use strict";
var t = function(e, t) {
this.init("popover", e, t)
};
t.prototype = e.extend({}, e.fn.tooltip.Constructor.prototype, {
constructor: t,
setContent: function() {
var e = this.tip(),
t = this.getTitle(),
n = this.getContent();
e.find(".popover-title")[this.options.html ? "html" : "text"](t), e.find(".popover-content > *")[this.options.html ? "html" : "text"](n), e.removeClass("fade top bottom left right in")
},
hasContent: function() {
return this.getTitle() || this.getContent()
},
getContent: function() {
var e, t = this.$element,
n = this.options;
return e = t.attr("data-content") || (typeof n.content == "function" ? n.content.call(t[0]) : n.content), e
},
tip: function() {
return this.$tip || (this.$tip = e(this.options.template)), this.$tip
},
destroy: function() {
this.hide().$element.off("." + this.type).removeData(this.type)
}
}), e.fn.popover = function(n) {
return this.each(function() {
var r = e(this),
i = r.data("popover"),
s = typeof n == "object" && n;
i || r.data("popover", i = new t(this, s)), typeof n == "string" && i[n]()
})
}, e.fn.popover.Constructor = t, e.fn.popover.defaults = e.extend({}, e.fn.tooltip.defaults, {
placement: "right",
trigger: "click",
content: "",
template: '<div class="popover"><div class="arrow"></div><div class="popover-inner"><h3 class="popover-title"></h3><div class="popover-content"><p></p></div></div></div>'
})
}(window.jQuery), ! function(e) {
"use strict";
var t = function(t, n) {
this.$element = e(t), this.options = e.extend({}, e.fn.button.defaults, n)
};
t.prototype.setState = function(e) {
var t = "disabled",
n = this.$element,
r = n.data(),
i = n.is("input") ? "val" : "html";
e += "Text", r.resetText || n.data("resetText", n[i]()), n[i](r[e] || this.options[e]), setTimeout(function() {
e == "loadingText" ? n.addClass(t).attr(t, t) : n.removeClass(t).removeAttr(t)
}, 0)
}, t.prototype.toggle = function() {
var e = this.$element.closest('[data-toggle="buttons-radio"]');
e && e.find(".active").removeClass("active"), this.$element.toggleClass("active")
}, e.fn.button = function(n) {
return this.each(function() {
var r = e(this),
i = r.data("button"),
s = typeof n == "object" && n;
i || r.data("button", i = new t(this, s)), n == "toggle" ? i.toggle() : n && i.setState(n)
})
}, e.fn.button.defaults = {
loadingText: "loading..."
}, e.fn.button.Constructor = t, e(document).on("click.button.data-api", "[data-toggle^=button]", function(t) {
var n = e(t.target);
n.hasClass("btn") || (n = n.closest(".btn")), n.button("toggle")
})
}(window.jQuery), ! function(e) {
"use strict";
var t = function(t, n) {
this.$element = e(t), this.options = e.extend({}, e.fn.collapse.defaults, n), this.options.parent && (this.$parent = e(this.options.parent)), this.options.toggle && this.toggle()
};
t.prototype = {
constructor: t,
dimension: function() {
var e = this.$element.hasClass("width");
return e ? "width" : "height"
},
show: function() {
var t, n, r, i;
if (this.transitioning) return;
t = this.dimension(), n = e.camelCase(["scroll", t].join("-")), r = this.$parent && this.$parent.find("> .accordion-group > .in");
if (r && r.length) {
i = r.data("collapse");
if (i && i.transitioning) return;
r.collapse("hide"), i || r.data("collapse", null)
}
this.$element[t](0), this.transition("addClass", e.Event("show"), "shown"), e.support.transition && this.$element[t](this.$element[0][n])
},
hide: function() {
var t;
if (this.transitioning) return;
t = this.dimension(), this.reset(this.$element[t]()), this.transition("removeClass", e.Event("hide"), "hidden"), this.$element[t](0)
},
reset: function(e) {
var t = this.dimension();
return this.$element.removeClass("collapse")[t](e || "auto")[0].offsetWidth, this.$element[e !== null ? "addClass" : "removeClass"]("collapse"), this
},
transition: function(t, n, r) {
var i = this,
s = function() {
n.type == "show" && i.reset(), i.transitioning = 0, i.$element.trigger(r)
};
this.$element.trigger(n);
if (n.isDefaultPrevented()) return;
this.transitioning = 1, this.$element[t]("in"), e.support.transition && this.$element.hasClass("collapse") ? this.$element.one(e.support.transition.end, s) : s()
},
toggle: function() {
this[this.$element.hasClass("in") ? "hide" : "show"]()
}
}, e.fn.collapse = function(n) {
return this.each(function() {
var r = e(this),
i = r.data("collapse"),
s = typeof n == "object" && n;
i || r.data("collapse", i = new t(this, s)), typeof n == "string" && i[n]()
})
}, e.fn.collapse.defaults = {
toggle: !0
}, e.fn.collapse.Constructor = t, e(document).on("click.collapse.data-api", "[data-toggle=collapse]", function(t) {
var n = e(this),
r, i = n.attr("data-target") || t.preventDefault() || (r = n.attr("href")) && r.replace(/.*(?=#[^\s]+$)/, ""),
s = e(i).data("collapse") ? "toggle" : n.data();
n[e(i).hasClass("in") ? "addClass" : "removeClass"]("collapsed"), e(i).collapse(s)
})
}(window.jQuery), ! function(e) {
"use strict";
var t = function(t, n) {
this.$element = e(t), this.options = n, this.options.slide && this.slide(this.options.slide), this.options.pause == "hover" && this.$element.on("mouseenter", e.proxy(this.pause, this)).on("mouseleave", e.proxy(this.cycle, this))
};
t.prototype = {
cycle: function(t) {
return t || (this.paused = !1), this.options.interval && !this.paused && (this.interval = setInterval(e.proxy(this.next, this), this.options.interval)), this
},
to: function(t) {
var n = this.$element.find(".item.active"),
r = n.parent().children(),
i = r.index(n),
s = this;
if (t > r.length - 1 || t < 0) return;
return this.sliding ? this.$element.one("slid", function() {
s.to(t)
}) : i == t ? this.pause().cycle() : this.slide(t > i ? "next" : "prev", e(r[t]))
},
pause: function(t) {
return t || (this.paused = !0), this.$element.find(".next, .prev").length && e.support.transition.end && (this.$element.trigger(e.support.transition.end), this.cycle()), clearInterval(this.interval), this.interval = null, this
},
next: function() {
if (this.sliding) return;
return this.slide("next")
},
prev: function() {
if (this.sliding) return;
return this.slide("prev")
},
slide: function(t, n) {
var r = this.$element.find(".item.active"),
i = n || r[t](),
s = this.interval,
o = t == "next" ? "left" : "right",
u = t == "next" ? "first" : "last",
a = this,
f;
this.sliding = !0, s && this.pause(), i = i.length ? i : this.$element.find(".item")[u](), f = e.Event("slide", {
relatedTarget: i[0]
});
if (i.hasClass("active")) return;
if (e.support.transition && this.$element.hasClass("slide")) {
this.$element.trigger(f);
if (f.isDefaultPrevented()) return;
i.addClass(t), i[0].offsetWidth, r.addClass(o), i.addClass(o), this.$element.one(e.support.transition.end, function() {
i.removeClass([t, o].join(" ")).addClass("active"), r.removeClass(["active", o].join(" ")), a.sliding = !1, setTimeout(function() {
a.$element.trigger("slid")
}, 0)
})
} else {
this.$element.trigger(f);
if (f.isDefaultPrevented()) return;
r.removeClass("active"), i.addClass("active"), this.sliding = !1, this.$element.trigger("slid")
}
return s && this.cycle(), this
}
}, e.fn.carousel = function(n) {
return this.each(function() {
var r = e(this),
i = r.data("carousel"),
s = e.extend({}, e.fn.carousel.defaults, typeof n == "object" && n),
o = typeof n == "string" ? n : s.slide;
i || r.data("carousel", i = new t(this, s)), typeof n == "number" ? i.to(n) : o ? i[o]() : s.interval && i.cycle()
})
}, e.fn.carousel.defaults = {
interval: 5e3,
pause: "hover"
}, e.fn.carousel.Constructor = t, e(document).on("click.carousel.data-api", "[data-slide]", function(t) {
var n = e(this),
r, i = e(n.attr("data-target") || (r = n.attr("href")) && r.replace(/.*(?=#[^\s]+$)/, "")),
s = e.extend({}, i.data(), n.data());
i.carousel(s), t.preventDefault()
})
}(window.jQuery), ! function(e) {
"use strict";
var t = function(t, n) {
this.$element = e(t), this.options = e.extend({}, e.fn.typeahead.defaults, n), this.matcher = this.options.matcher || this.matcher, this.sorter = this.options.sorter || this.sorter, this.highlighter = this.options.highlighter || this.highlighter, this.updater = this.options.updater || this.updater, this.$menu = e(this.options.menu).appendTo("body"), this.source = this.options.source, this.shown = !1, this.listen()
};
t.prototype = {
constructor: t,
select: function() {
var e = this.$menu.find(".active").attr("data-value");
return this.$element.val(this.updater(e)).change(), this.hide()
},
updater: function(e) {
return e
},
show: function() {
var t = e.extend({}, this.$element.offset(), {
height: this.$element[0].offsetHeight
});
return this.$menu.css({
top: t.top + t.height,
left: t.left
}), this.$menu.show(), this.shown = !0, this
},
hide: function() {
return this.$menu.hide(), this.shown = !1, this
},
lookup: function(t) {
var n;
return this.query = this.$element.val(), !this.query || this.query.length < this.options.minLength ? this.shown ? this.hide() : this : (n = e.isFunction(this.source) ? this.source(this.query, e.proxy(this.process, this)) : this.source, n ? this.process(n) : this)
},
process: function(t) {
var n = this;
return t = e.grep(t, function(e) {
return n.matcher(e)
}), t = this.sorter(t), t.length ? this.render(t.slice(0, this.options.items)).show() : this.shown ? this.hide() : this
},
matcher: function(e) {
return ~e.toLowerCase().indexOf(this.query.toLowerCase())
},
sorter: function(e) {
var t = [],
n = [],
r = [],
i;
while (i = e.shift()) i.toLowerCase().indexOf(this.query.toLowerCase()) ? ~i.indexOf(this.query) ? n.push(i) : r.push(i) : t.push(i);
return t.concat(n, r)
},
highlighter: function(e) {
var t = this.query.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&");
return e.replace(new RegExp("(" + t + ")", "ig"), function(e, t) {
return "<strong>" + t + "</strong>"
})
},
render: function(t) {
var n = this;
return t = e(t).map(function(t, r) {
return t = e(n.options.item).attr("data-value", r), t.find("a").html(n.highlighter(r)), t[0]
}), t.first().addClass("active"), this.$menu.html(t), this
},
next: function(t) {
var n = this.$menu.find(".active").removeClass("active"),
r = n.next();
r.length || (r = e(this.$menu.find("li")[0])), r.addClass("active")
},
prev: function(e) {
var t = this.$menu.find(".active").removeClass("active"),
n = t.prev();
n.length || (n = this.$menu.find("li").last()), n.addClass("active")
},
listen: function() {
this.$element.on("blur", e.proxy(this.blur, this)).on("keypress", e.proxy(this.keypress, this)).on("keyup", e.proxy(this.keyup, this)), this.eventSupported("keydown") && this.$element.on("keydown", e.proxy(this.keydown, this)), this.$menu.on("click", e.proxy(this.click, this)).on("mouseenter", "li", e.proxy(this.mouseenter, this))
},
eventSupported: function(e) {
var t = e in this.$element;
return t || (this.$element.setAttribute(e, "return;"), t = typeof this.$element[e] == "function"), t
},
move: function(e) {
if (!this.shown) return;
switch (e.keyCode) {
case 9:
case 13:
case 27:
e.preventDefault();
break;
case 38:
e.preventDefault(), this.prev();
break;
case 40:
e.preventDefault(), this.next()
}
e.stopPropagation()
},
keydown: function(t) {
this.suppressKeyPressRepeat = !~e.inArray(t.keyCode, [40, 38, 9, 13, 27]), this.move(t)
},
keypress: function(e) {
if (this.suppressKeyPressRepeat) return;
this.move(e)
},
keyup: function(e) {
switch (e.keyCode) {
case 40:
case 38:
case 16:
case 17:
case 18:
break;
case 9:
case 13:
if (!this.shown) return;
this.select();
break;
case 27:
if (!this.shown) return;
this.hide();
break;
default:
this.lookup()
}
e.stopPropagation(), e.preventDefault()
},
blur: function(e) {
var t = this;
setTimeout(function() {
t.hide()
}, 150)
},
click: function(e) {
e.stopPropagation(), e.preventDefault(), this.select()
},
mouseenter: function(t) {
this.$menu.find(".active").removeClass("active"), e(t.currentTarget).addClass("active")
}
}, e.fn.typeahead = function(n) {
return this.each(function() {
var r = e(this),
i = r.data("typeahead"),
s = typeof n == "object" && n;
i || r.data("typeahead", i = new t(this, s)), typeof n == "string" && i[n]()
})
}, e.fn.typeahead.defaults = {
source: [],
items: 8,
menu: '<ul class="typeahead dropdown-menu"></ul>',
item: '<li><a href="#"></a></li>',
minLength: 1
}, e.fn.typeahead.Constructor = t, e(document).on("focus.typeahead.data-api", '[data-provide="typeahead"]', function(t) {
var n = e(this);
if (n.data("typeahead")) return;
t.preventDefault(), n.typeahead(n.data())
})
}(window.jQuery), ! function(e) {
"use strict";
var t = function(t, n) {
this.options = e.extend({}, e.fn.affix.defaults, n), this.$window = e(window).on("scroll.affix.data-api", e.proxy(this.checkPosition, this)).on("click.affix.data-api", e.proxy(function() {
setTimeout(e.proxy(this.checkPosition, this), 1)
}, this)), this.$element = e(t), this.checkPosition()
};
t.prototype.checkPosition = function() {
if (!this.$element.is(":visible")) return;
var t = e(document).height(),
n = this.$window.scrollTop(),
r = this.$element.offset(),
i = this.options.offset,
s = i.bottom,
o = i.top,
u = "affix affix-top affix-bottom",
a;
typeof i != "object" && (s = o = i), typeof o == "function" && (o = i.top()), typeof s == "function" && (s = i.bottom()), a = this.unpin != null && n + this.unpin <= r.top ? !1 : s != null && r.top + this.$element.height() >= t - s ? "bottom" : o != null && n <= o ? "top" : !1;
if (this.affixed === a) return;
this.affixed = a, this.unpin = a == "bottom" ? r.top - n : null, this.$element.removeClass(u).addClass("affix" + (a ? "-" + a : ""))
}, e.fn.affix = function(n) {
return this.each(function() {
var r = e(this),
i = r.data("affix"),
s = typeof n == "object" && n;
i || r.data("affix", i = new t(this, s)), typeof n == "string" && i[n]()
})
}, e.fn.affix.Constructor = t, e.fn.affix.defaults = {
offset: 0
}, e(window).on("load", function() {
e('[data-spy="affix"]').each(function() {
var t = e(this),
n = t.data();
n.offset = n.offset || {}, n.offsetBottom && (n.offset.bottom = n.offsetBottom), n.offsetTop && (n.offset.top = n.offsetTop), t.affix(n)
})
})
}(window.jQuery),
function(e, t) {
function i(t, n) {
var r, i, o, u = t.nodeName.toLowerCase();
return "area" === u ? (r = t.parentNode, i = r.name, !t.href || !i || r.nodeName.toLowerCase() !== "map" ? !1 : (o = e("img[usemap=#" + i + "]")[0], !!o && s(o))) : (/input|select|textarea|button|object/.test(u) ? !t.disabled : "a" === u ? t.href || n : n) && s(t)
}
function s(t) {
return e.expr.filters.visible(t) && !e(t).parents().andSelf().filter(function() {
return e.css(this, "visibility") === "hidden"
}).length
}
var n = 0,
r = /^ui-id-\d+$/;
e.ui = e.ui || {};
if (e.ui.version) return;
e.extend(e.ui, {
version: "1.9.2",
keyCode: {
BACKSPACE: 8,
COMMA: 188,
DELETE: 46,
DOWN: 40,
END: 35,
ENTER: 13,
ESCAPE: 27,
HOME: 36,
LEFT: 37,
NUMPAD_ADD: 107,
NUMPAD_DECIMAL: 110,
NUMPAD_DIVIDE: 111,
NUMPAD_ENTER: 108,
NUMPAD_MULTIPLY: 106,
NUMPAD_SUBTRACT: 109,
PAGE_DOWN: 34,
PAGE_UP: 33,
PERIOD: 190,
RIGHT: 39,
SPACE: 32,
TAB: 9,
UP: 38
}
}), e.fn.extend({
_focus: e.fn.focus,
focus: function(t, n) {
return typeof t == "number" ? this.each(function() {
var r = this;
setTimeout(function() {
e(r).focus(), n && n.call(r)
}, t)
}) : this._focus.apply(this, arguments)
},
scrollParent: function() {
var t;
return e.ui.ie && /(static|relative)/.test(this.css("position")) || /absolute/.test(this.css("position")) ? t = this.parents().filter(function() {
return /(relative|absolute|fixed)/.test(e.css(this, "position")) && /(auto|scroll)/.test(e.css(this, "overflow") + e.css(this, "overflow-y") + e.css(this, "overflow-x"))
}).eq(0) : t = this.parents().filter(function() {
return /(auto|scroll)/.test(e.css(this, "overflow") + e.css(this, "overflow-y") + e.css(this, "overflow-x"))
}).eq(0), /fixed/.test(this.css("position")) || !t.length ? e(document) : t
},
zIndex: function(n) {
if (n !== t) return this.css("zIndex", n);
if (this.length) {
var r = e(this[0]),
i, s;
while (r.length && r[0] !== document) {
i = r.css("position");
if (i === "absolute" || i === "relative" || i === "fixed") {
s = parseInt(r.css("zIndex"), 10);
if (!isNaN(s) && s !== 0) return s
}
r = r.parent()
}
}
return 0
},
uniqueId: function() {
return this.each(function() {
this.id || (this.id = "ui-id-" + ++n)
})
},
removeUniqueId: function() {
return this.each(function() {
r.test(this.id) && e(this).removeAttr("id")
})
}
}), e.extend(e.expr[":"], {
data: e.expr.createPseudo ? e.expr.createPseudo(function(t) {
return function(n) {
return !!e.data(n, t)
}
}) : function(t, n, r) {
return !!e.data(t, r[3])
},
focusable: function(t) {
return i(t, !isNaN(e.attr(t, "tabindex")))
},
tabbable: function(t) {
var n = e.attr(t, "tabindex"),
r = isNaN(n);
return (r || n >= 0) && i(t, !r)
}
}), e(function() {
var t = document.body,
n = t.appendChild(n = document.createElement("div"));
n.offsetHeight, e.extend(n.style, {
minHeight: "100px",
height: "auto",
padding: 0,
borderWidth: 0
}), e.support.minHeight = n.offsetHeight === 100, e.support.selectstart = "onselectstart" in n, t.removeChild(n).style.display = "none"
}), e("<a>").outerWidth(1).jquery || e.each(["Width", "Height"], function(n, r) {
function u(t, n, r, s) {
return e.each(i, function() {
n -= parseFloat(e.css(t, "padding" + this)) || 0, r && (n -= parseFloat(e.css(t, "border" + this + "Width")) || 0), s && (n -= parseFloat(e.css(t, "margin" + this)) || 0)
}), n
}
var i = r === "Width" ? ["Left", "Right"] : ["Top", "Bottom"],
s = r.toLowerCase(),
o = {
innerWidth: e.fn.innerWidth,
innerHeight: e.fn.innerHeight,
outerWidth: e.fn.outerWidth,
outerHeight: e.fn.outerHeight
};
e.fn["inner" + r] = function(n) {
return n === t ? o["inner" + r].call(this) : this.each(function() {
e(this).css(s, u(this, n) + "px")
})
}, e.fn["outer" + r] = function(t, n) {
return typeof t != "number" ? o["outer" + r].call(this, t) : this.each(function() {
e(this).css(s, u(this, t, !0, n) + "px")
})
}
}), e("<a>").data("a-b", "a").removeData("a-b").data("a-b") && (e.fn.removeData = function(t) {
return function(n) {
return arguments.length ? t.call(this, e.camelCase(n)) : t.call(this)
}
}(e.fn.removeData)),
function() {
var t = /msie ([\w.]+)/.exec(navigator.userAgent.toLowerCase()) || [];
e.ui.ie = t.length ? !0 : !1, e.ui.ie6 = parseFloat(t[1], 10) === 6
}(), e.fn.extend({
disableSelection: function() {
return this.bind((e.support.selectstart ? "selectstart" : "mousedown") + ".ui-disableSelection", function(e) {
e.preventDefault()
})
},
enableSelection: function() {
return this.unbind(".ui-disableSelection")
}
}), e.extend(e.ui, {
plugin: {
add: function(t, n, r) {
var i, s = e.ui[t].prototype;
for (i in r) s.plugins[i] = s.plugins[i] || [], s.plugins[i].push([n, r[i]])
},
call: function(e, t, n) {
var r, i = e.plugins[t];
if (!i || !e.element[0].parentNode || e.element[0].parentNode.nodeType === 11) return;
for (r = 0; r < i.length; r++) e.options[i[r][0]] && i[r][1].apply(e.element, n)
}
},
contains: e.contains,
hasScroll: function(t, n) {
if (e(t).css("overflow") === "hidden") return !1;
var r = n && n === "left" ? "scrollLeft" : "scrollTop",
i = !1;
return t[r] > 0 ? !0 : (t[r] = 1, i = t[r] > 0, t[r] = 0, i)
},
isOverAxis: function(e, t, n) {
return e > t && e < t + n
},
isOver: function(t, n, r, i, s, o) {
return e.ui.isOverAxis(t, r, s) && e.ui.isOverAxis(n, i, o)
}
})
}(jQuery),
function(e, t) {
var n = 0,
r = Array.prototype.slice,
i = e.cleanData;
e.cleanData = function(t) {
for (var n = 0, r;
(r = t[n]) != null; n++) try {
e(r).triggerHandler("remove")
} catch (s) {}
i(t)
}, e.widget = function(t, n, r) {
var i, s, o, u, a = t.split(".")[0];
t = t.split(".")[1], i = a + "-" + t, r || (r = n, n = e.Widget), e.expr[":"][i.toLowerCase()] = function(t) {
return !!e.data(t, i)
}, e[a] = e[a] || {}, s = e[a][t], o = e[a][t] = function(e, t) {
if (!this._createWidget) return new o(e, t);
arguments.length && this._createWidget(e, t)
}, e.extend(o, s, {
version: r.version,
_proto: e.extend({}, r),
_childConstructors: []
}), u = new n, u.options = e.widget.extend({}, u.options), e.each(r, function(t, i) {
e.isFunction(i) && (r[t] = function() {
var e = function() {
return n.prototype[t].apply(this, arguments)
},
r = function(e) {
return n.prototype[t].apply(this, e)
};
return function() {
var t = this._super,
n = this._superApply,
s;
return this._super = e, this._superApply = r, s = i.apply(this, arguments), this._super = t, this._superApply = n, s
}
}())
}),
o.prototype = e.widget.extend(u, {
widgetEventPrefix: s ? u.widgetEventPrefix : t
}, r, {
constructor: o,
namespace: a,
widgetName: t,
widgetBaseClass: i,
widgetFullName: i
}), s ? (e.each(s._childConstructors, function(t, n) {
var r = n.prototype;
e.widget(r.namespace + "." + r.widgetName, o, n._proto)
}), delete s._childConstructors) : n._childConstructors.push(o), e.widget.bridge(t, o)
}, e.widget.extend = function(n) {
var i = r.call(arguments, 1),
s = 0,
o = i.length,
u, a;
for (; s < o; s++)
for (u in i[s]) a = i[s][u], i[s].hasOwnProperty(u) && a !== t && (e.isPlainObject(a) ? n[u] = e.isPlainObject(n[u]) ? e.widget.extend({}, n[u], a) : e.widget.extend({}, a) : n[u] = a);
return n
}, e.widget.bridge = function(n, i) {
var s = i.prototype.widgetFullName || n;
e.fn[n] = function(o) {
var u = typeof o == "string",
a = r.call(arguments, 1),
f = this;
return o = !u && a.length ? e.widget.extend.apply(null, [o].concat(a)) : o, u ? this.each(function() {
var r, i = e.data(this, s);
if (!i) return e.error("cannot call methods on " + n + " prior to initialization; " + "attempted to call method '" + o + "'");
if (!e.isFunction(i[o]) || o.charAt(0) === "_") return e.error("no such method '" + o + "' for " + n + " widget instance");
r = i[o].apply(i, a);
if (r !== i && r !== t) return f = r && r.jquery ? f.pushStack(r.get()) : r, !1
}) : this.each(function() {
var t = e.data(this, s);
t ? t.option(o || {})._init() : e.data(this, s, new i(o, this))
}), f
}
}, e.Widget = function() {}, e.Widget._childConstructors = [], e.Widget.prototype = {
widgetName: "widget",
widgetEventPrefix: "",
defaultElement: "<div>",
options: {
disabled: !1,
create: null
},
_createWidget: function(t, r) {
r = e(r || this.defaultElement || this)[0], this.element = e(r), this.uuid = n++, this.eventNamespace = "." + this.widgetName + this.uuid, this.options = e.widget.extend({}, this.options, this._getCreateOptions(), t), this.bindings = e(), this.hoverable = e(), this.focusable = e(), r !== this && (e.data(r, this.widgetName, this), e.data(r, this.widgetFullName, this), this._on(!0, this.element, {
remove: function(e) {
e.target === r && this.destroy()
}
}), this.document = e(r.style ? r.ownerDocument : r.document || r), this.window = e(this.document[0].defaultView || this.document[0].parentWindow)), this._create(), this._trigger("create", null, this._getCreateEventData()), this._init()
},
_getCreateOptions: e.noop,
_getCreateEventData: e.noop,
_create: e.noop,
_init: e.noop,
destroy: function() {
this._destroy(), this.element.unbind(this.eventNamespace).removeData(this.widgetName).removeData(this.widgetFullName).removeData(e.camelCase(this.widgetFullName)), this.widget().unbind(this.eventNamespace).removeAttr("aria-disabled").removeClass(this.widgetFullName + "-disabled " + "ui-state-disabled"), this.bindings.unbind(this.eventNamespace), this.hoverable.removeClass("ui-state-hover"), this.focusable.removeClass("ui-state-focus")
},
_destroy: e.noop,
widget: function() {
return this.element
},
option: function(n, r) {
var i = n,
s, o, u;
if (arguments.length === 0) return e.widget.extend({}, this.options);
if (typeof n == "string") {
i = {}, s = n.split("."), n = s.shift();
if (s.length) {
o = i[n] = e.widget.extend({}, this.options[n]);
for (u = 0; u < s.length - 1; u++) o[s[u]] = o[s[u]] || {}, o = o[s[u]];
n = s.pop();
if (r === t) return o[n] === t ? null : o[n];
o[n] = r
} else {
if (r === t) return this.options[n] === t ? null : this.options[n];
i[n] = r
}
}
return this._setOptions(i), this
},
_setOptions: function(e) {
var t;
for (t in e) this._setOption(t, e[t]);
return this
},
_setOption: function(e, t) {
return this.options[e] = t, e === "disabled" && (this.widget().toggleClass(this.widgetFullName + "-disabled ui-state-disabled", !!t).attr("aria-disabled", t), this.hoverable.removeClass("ui-state-hover"), this.focusable.removeClass("ui-state-focus")), this
},
enable: function() {
return this._setOption("disabled", !1)
},
disable: function() {
return this._setOption("disabled", !0)
},
_on: function(t, n, r) {
var i, s = this;
typeof t != "boolean" && (r = n, n = t, t = !1), r ? (n = i = e(n), this.bindings = this.bindings.add(n)) : (r = n, n = this.element, i = this.widget()), e.each(r, function(r, o) {
function u() {
if (!t && (s.options.disabled === !0 || e(this).hasClass("ui-state-disabled"))) return;
return (typeof o == "string" ? s[o] : o).apply(s, arguments)
}
typeof o != "string" && (u.guid = o.guid = o.guid || u.guid || e.guid++);
var a = r.match(/^(\w+)\s*(.*)$/),
f = a[1] + s.eventNamespace,
l = a[2];
l ? i.delegate(l, f, u) : n.bind(f, u)
})
},
_off: function(e, t) {
t = (t || "").split(" ").join(this.eventNamespace + " ") + this.eventNamespace, e.unbind(t).undelegate(t)
},
_delay: function(e, t) {
function n() {
return (typeof e == "string" ? r[e] : e).apply(r, arguments)
}
var r = this;
return setTimeout(n, t || 0)
},
_hoverable: function(t) {
this.hoverable = this.hoverable.add(t), this._on(t, {
mouseenter: function(t) {
e(t.currentTarget).addClass("ui-state-hover")
},
mouseleave: function(t) {
e(t.currentTarget).removeClass("ui-state-hover")
}
})
},
_focusable: function(t) {
this.focusable = this.focusable.add(t), this._on(t, {
focusin: function(t) {
e(t.currentTarget).addClass("ui-state-focus")
},
focusout: function(t) {
e(t.currentTarget).removeClass("ui-state-focus")
}
})
},
_trigger: function(t, n, r) {
var i, s, o = this.options[t];
r = r || {}, n = e.Event(n), n.type = (t === this.widgetEventPrefix ? t : this.widgetEventPrefix + t).toLowerCase(), n.target = this.element[0], s = n.originalEvent;
if (s)
for (i in s) i in n || (n[i] = s[i]);
return this.element.trigger(n, r), !(e.isFunction(o) && o.apply(this.element[0], [n].concat(r)) === !1 || n.isDefaultPrevented())
}
}, e.each({
show: "fadeIn",
hide: "fadeOut"
}, function(t, n) {
e.Widget.prototype["_" + t] = function(r, i, s) {
typeof i == "string" && (i = {
effect: i
});
var o, u = i ? i === !0 || typeof i == "number" ? n : i.effect || n : t;
i = i || {}, typeof i == "number" && (i = {
duration: i
}), o = !e.isEmptyObject(i), i.complete = s, i.delay && r.delay(i.delay), o && e.effects && (e.effects.effect[u] || e.uiBackCompat !== !1 && e.effects[u]) ? r[t](i) : u !== t && r[u] ? r[u](i.duration, i.easing, s) : r.queue(function(n) {
e(this)[t](), s && s.call(r[0]), n()
})
}
}), e.uiBackCompat !== !1 && (e.Widget.prototype._getCreateOptions = function() {
return e.metadata && e.metadata.get(this.element[0])[this.widgetName]
})
}(jQuery),
function(e, t) {
var n = !1;
e(document).mouseup(function(e) {
n = !1
}), e.widget("ui.mouse", {
version: "1.9.2",
options: {
cancel: "input,textarea,button,select,option",
distance: 1,
delay: 0
},
_mouseInit: function() {
var t = this;
this.element.bind("mousedown." + this.widgetName, function(e) {
return t._mouseDown(e)
}).bind("click." + this.widgetName, function(n) {
if (!0 === e.data(n.target, t.widgetName + ".preventClickEvent")) return e.removeData(n.target, t.widgetName + ".preventClickEvent"), n.stopImmediatePropagation(), !1
}), this.started = !1
},
_mouseDestroy: function() {
this.element.unbind("." + this.widgetName), this._mouseMoveDelegate && e(document).unbind("mousemove." + this.widgetName, this._mouseMoveDelegate).unbind("mouseup." + this.widgetName, this._mouseUpDelegate)
},
_mouseDown: function(t) {
if (n) return;
this._mouseStarted && this._mouseUp(t), this._mouseDownEvent = t;
var r = this,
i = t.which === 1,
s = typeof this.options.cancel == "string" && t.target.nodeName ? e(t.target).closest(this.options.cancel).length : !1;
if (!i || s || !this._mouseCapture(t)) return !0;
this.mouseDelayMet = !this.options.delay, this.mouseDelayMet || (this._mouseDelayTimer = setTimeout(function() {
r.mouseDelayMet = !0
}, this.options.delay));
if (this._mouseDistanceMet(t) && this._mouseDelayMet(t)) {
this._mouseStarted = this._mouseStart(t) !== !1;
if (!this._mouseStarted) return t.preventDefault(), !0
}
return !0 === e.data(t.target, this.widgetName + ".preventClickEvent") && e.removeData(t.target, this.widgetName + ".preventClickEvent"), this._mouseMoveDelegate = function(e) {
return r._mouseMove(e)
}, this._mouseUpDelegate = function(e) {
return r._mouseUp(e)
}, e(document).bind("mousemove." + this.widgetName, this._mouseMoveDelegate).bind("mouseup." + this.widgetName, this._mouseUpDelegate), t.preventDefault(), n = !0, !0
},
_mouseMove: function(t) {
return !e.ui.ie || document.documentMode >= 9 || !!t.button ? this._mouseStarted ? (this._mouseDrag(t), t.preventDefault()) : (this._mouseDistanceMet(t) && this._mouseDelayMet(t) && (this._mouseStarted = this._mouseStart(this._mouseDownEvent, t) !== !1, this._mouseStarted ? this._mouseDrag(t) : this._mouseUp(t)), !this._mouseStarted) : this._mouseUp(t)
},
_mouseUp: function(t) {
return e(document).unbind("mousemove." + this.widgetName, this._mouseMoveDelegate).unbind("mouseup." + this.widgetName, this._mouseUpDelegate), this._mouseStarted && (this._mouseStarted = !1, t.target === this._mouseDownEvent.target && e.data(t.target, this.widgetName + ".preventClickEvent", !0), this._mouseStop(t)), !1
},
_mouseDistanceMet: function(e) {
return Math.max(Math.abs(this._mouseDownEvent.pageX - e.pageX), Math.abs(this._mouseDownEvent.pageY - e.pageY)) >= this.options.distance
},
_mouseDelayMet: function(e) {
return this.mouseDelayMet
},
_mouseStart: function(e) {},
_mouseDrag: function(e) {},
_mouseStop: function(e) {},
_mouseCapture: function(e) {
return !0
}
})
}(jQuery),
function(e, t) {
e.widget("ui.resizable", e.ui.mouse, {
version: "1.9.2",
widgetEventPrefix: "resize",
options: {
alsoResize: !1,
animate: !1,
animateDuration: "slow",
animateEasing: "swing",
aspectRatio: !1,
autoHide: !1,
containment: !1,
ghost: !1,
grid: !1,
handles: "e,s,se",
helper: !1,
maxHeight: null,
maxWidth: null,
minHeight: 10,
minWidth: 10,
zIndex: 1e3
},
_create: function() {
var t = this,
n = this.options;
this.element.addClass("ui-resizable"), e.extend(this, {
_aspectRatio: !!n.aspectRatio,
aspectRatio: n.aspectRatio,
originalElement: this.element,
_proportionallyResizeElements: [],
_helper: n.helper || n.ghost || n.animate ? n.helper || "ui-resizable-helper" : null
}), this.element[0].nodeName.match(/canvas|textarea|input|select|button|img/i) && (this.element.wrap(e('<div class="ui-wrapper" style="overflow: hidden;"></div>').css({
position: this.element.css("position"),
width: this.element.outerWidth(),
height: this.element.outerHeight(),
top: this.element.css("top"),
left: this.element.css("left")
})), this.element = this.element.parent().data("resizable", this.element.data("resizable")), this.elementIsWrapper = !0, this.element.css({
marginLeft: this.originalElement.css("marginLeft"),
marginTop: this.originalElement.css("marginTop"),
marginRight: this.originalElement.css("marginRight"),
marginBottom: this.originalElement.css("marginBottom")
}), this.originalElement.css({
marginLeft: 0,
marginTop: 0,
marginRight: 0,
marginBottom: 0
}), this.originalResizeStyle = this.originalElement.css("resize"), this.originalElement.css("resize", "none"), this._proportionallyResizeElements.push(this.originalElement.css({
position: "static",
zoom: 1,
display: "block"
})), this.originalElement.css({
margin: this.originalElement.css("margin")
}), this._proportionallyResize()), this.handles = n.handles || (e(".ui-resizable-handle", this.element).length ? {
n: ".ui-resizable-n",
e: ".ui-resizable-e",
s: ".ui-resizable-s",
w: ".ui-resizable-w",
se: ".ui-resizable-se",
sw: ".ui-resizable-sw",
ne: ".ui-resizable-ne",
nw: ".ui-resizable-nw"
} : "e,s,se");
if (this.handles.constructor == String) {
this.handles == "all" && (this.handles = "n,e,s,w,se,sw,ne,nw");
var r = this.handles.split(",");
this.handles = {};
for (var i = 0; i < r.length; i++) {
var s = e.trim(r[i]),
o = "ui-resizable-" + s,
u = e('<div class="ui-resizable-handle ' + o + '"></div>');
u.css({
zIndex: n.zIndex
}), "se" == s && u.addClass("ui-icon ui-icon-gripsmall-diagonal-se"), this.handles[s] = ".ui-resizable-" + s, this.element.append(u)
}
}
this._renderAxis = function(t) {
t = t || this.element;
for (var n in this.handles) {
this.handles[n].constructor == String && (this.handles[n] = e(this.handles[n], this.element).show());
if (this.elementIsWrapper && this.originalElement[0].nodeName.match(/textarea|input|select|button/i)) {
var r = e(this.handles[n], this.element),
i = 0;
i = /sw|ne|nw|se|n|s/.test(n) ? r.outerHeight() : r.outerWidth();
var s = ["padding", /ne|nw|n/.test(n) ? "Top" : /se|sw|s/.test(n) ? "Bottom" : /^e$/.test(n) ? "Right" : "Left"].join("");
t.css(s, i), this._proportionallyResize()
}
if (!e(this.handles[n]).length) continue
}
}, this._renderAxis(this.element), this._handles = e(".ui-resizable-handle", this.element).disableSelection(), this._handles.mouseover(function() {
if (!t.resizing) {
if (this.className) var e = this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i);
t.axis = e && e[1] ? e[1] : "se"
}
}), n.autoHide && (this._handles.hide(), e(this.element).addClass("ui-resizable-autohide").mouseenter(function() {
if (n.disabled) return;
e(this).removeClass("ui-resizable-autohide"), t._handles.show()
}).mouseleave(function() {
if (n.disabled) return;
t.resizing || (e(this).addClass("ui-resizable-autohide"), t._handles.hide())
})), this._mouseInit()
},
_destroy: function() {
this._mouseDestroy();
var t = function(t) {
e(t).removeClass("ui-resizable ui-resizable-disabled ui-resizable-resizing").removeData("resizable").removeData("ui-resizable").unbind(".resizable").find(".ui-resizable-handle").remove()
};
if (this.elementIsWrapper) {
t(this.element);
var n = this.element;
this.originalElement.css({
position: n.css("position"),
width: n.outerWidth(),
height: n.outerHeight(),
top: n.css("top"),
left: n.css("left")
}).insertAfter(n), n.remove()
}
return this.originalElement.css("resize", this.originalResizeStyle), t(this.originalElement), this
},
_mouseCapture: function(t) {
var n = !1;
for (var r in this.handles) e(this.handles[r])[0] == t.target && (n = !0);
return !this.options.disabled && n
},
_mouseStart: function(t) {
var r = this.options,
i = this.element.position(),
s = this.element;
this.resizing = !0, this.documentScroll = {
top: e(document).scrollTop(),
left: e(document).scrollLeft()
}, (s.is(".ui-draggable") || /absolute/.test(s.css("position"))) && s.css({
position: "absolute",
top: i.top,
left: i.left
}), this._renderProxy();
var o = n(this.helper.css("left")),
u = n(this.helper.css("top"));
r.containment && (o += e(r.containment).scrollLeft() || 0, u += e(r.containment).scrollTop() || 0), this.offset = this.helper.offset(), this.position = {
left: o,
top: u
}, this.size = this._helper ? {
width: s.outerWidth(),
height: s.outerHeight()
} : {
width: s.width(),
height: s.height()
}, this.originalSize = this._helper ? {
width: s.outerWidth(),
height: s.outerHeight()
} : {
width: s.width(),
height: s.height()
}, this.originalPosition = {
left: o,
top: u
}, this.sizeDiff = {
width: s.outerWidth() - s.width(),
height: s.outerHeight() - s.height()
}, this.originalMousePosition = {
left: t.pageX,
top: t.pageY
}, this.aspectRatio = typeof r.aspectRatio == "number" ? r.aspectRatio : this.originalSize.width / this.originalSize.height || 1;
var a = e(".ui-resizable-" + this.axis).css("cursor");
return e("body").css("cursor", a == "auto" ? this.axis + "-resize" : a), s.addClass("ui-resizable-resizing"), this._propagate("start", t), !0
},
_mouseDrag: function(e) {
var t = this.helper,
n = this.options,
r = {},
i = this,
s = this.originalMousePosition,
o = this.axis,
u = e.pageX - s.left || 0,
a = e.pageY - s.top || 0,
f = this._change[o];
if (!f) return !1;
var l = f.apply(this, [e, u, a]);
this._updateVirtualBoundaries(e.shiftKey);
if (this._aspectRatio || e.shiftKey) l = this._updateRatio(l, e);
return l = this._respectSize(l, e), this._propagate("resize", e), t.css({
top: this.position.top + "px",
left: this.position.left + "px",
width: this.size.width + "px",
height: this.size.height + "px"
}), !this._helper && this._proportionallyResizeElements.length && this._proportionallyResize(), this._updateCache(l), this._trigger("resize", e, this.ui()), !1
},
_mouseStop: function(t) {
this.resizing = !1;
var n = this.options,
r = this;
if (this._helper) {
var i = this._proportionallyResizeElements,
s = i.length && /textarea/i.test(i[0].nodeName),
o = s && e.ui.hasScroll(i[0], "left") ? 0 : r.sizeDiff.height,
u = s ? 0 : r.sizeDiff.width,
a = {
width: r.helper.width() - u,
height: r.helper.height() - o
},
f = parseInt(r.element.css("left"), 10) + (r.position.left - r.originalPosition.left) || null,
l = parseInt(r.element.css("top"), 10) + (r.position.top - r.originalPosition.top) || null;
n.animate || this.element.css(e.extend(a, {
top: l,
left: f
})), r.helper.height(r.size.height), r.helper.width(r.size.width), this._helper && !n.animate && this._proportionallyResize()
}
return e("body").css("cursor", "auto"), this.element.removeClass("ui-resizable-resizing"), this._propagate("stop", t), this._helper && this.helper.remove(), !1
},
_updateVirtualBoundaries: function(e) {
var t = this.options,
n, i, s, o, u;
u = {
minWidth: r(t.minWidth) ? t.minWidth : 0,
maxWidth: r(t.maxWidth) ? t.maxWidth : Infinity,
minHeight: r(t.minHeight) ? t.minHeight : 0,
maxHeight: r(t.maxHeight) ? t.maxHeight : Infinity
};
if (this._aspectRatio || e) n = u.minHeight * this.aspectRatio, s = u.minWidth / this.aspectRatio, i = u.maxHeight * this.aspectRatio, o = u.maxWidth / this.aspectRatio, n > u.minWidth && (u.minWidth = n), s > u.minHeight && (u.minHeight = s), i < u.maxWidth && (u.maxWidth = i), o < u.maxHeight && (u.maxHeight = o);
this._vBoundaries = u
},
_updateCache: function(e) {
var t = this.options;
this.offset = this.helper.offset(), r(e.left) && (this.position.left = e.left), r(e.top) && (this.position.top = e.top), r(e.height) && (this.size.height = e.height), r(e.width) && (this.size.width = e.width)
},
_updateRatio: function(e, t) {
var n = this.options,
i = this.position,
s = this.size,
o = this.axis;
return r(e.height) ? e.width = e.height * this.aspectRatio : r(e.width) && (e.height = e.width / this.aspectRatio), o == "sw" && (e.left = i.left + (s.width - e.width), e.top = null), o == "nw" && (e.top = i.top + (s.height - e.height), e.left = i.left + (s.width - e.width)), e
},
_respectSize: function(e, t) {
var n = this.helper,
i = this._vBoundaries,
s = this._aspectRatio || t.shiftKey,
o = this.axis,
u = r(e.width) && i.maxWidth && i.maxWidth < e.width,
a = r(e.height) && i.maxHeight && i.maxHeight < e.height,
f = r(e.width) && i.minWidth && i.minWidth > e.width,
l = r(e.height) && i.minHeight && i.minHeight > e.height;
f && (e.width = i.minWidth), l && (e.height = i.minHeight), u && (e.width = i.maxWidth), a && (e.height = i.maxHeight);
var c = this.originalPosition.left + this.originalSize.width,
h = this.position.top + this.size.height,
p = /sw|nw|w/.test(o),
d = /nw|ne|n/.test(o);
f && p && (e.left = c - i.minWidth), u && p && (e.left = c - i.maxWidth), l && d && (e.top = h - i.minHeight), a && d && (e.top = h - i.maxHeight);
var v = !e.width && !e.height;
return v && !e.left && e.top ? e.top = null : v && !e.top && e.left && (e.left = null), e
},
_proportionallyResize: function() {
var t = this.options;
if (!this._proportionallyResizeElements.length) return;
var n = this.helper || this.element;
for (var r = 0; r < this._proportionallyResizeElements.length; r++) {
var i = this._proportionallyResizeElements[r];
if (!this.borderDif) {
var s = [i.css("borderTopWidth"), i.css("borderRightWidth"), i.css("borderBottomWidth"), i.css("borderLeftWidth")],
o = [i.css("paddingTop"), i.css("paddingRight"), i.css("paddingBottom"), i.css("paddingLeft")];
this.borderDif = e.map(s, function(e, t) {
var n = parseInt(e, 10) || 0,
r = parseInt(o[t], 10) || 0;
return n + r
})
}
i.css({
height: n.height() - this.borderDif[0] - this.borderDif[2] || 0,
width: n.width() - this.borderDif[1] - this.borderDif[3] || 0
})
}
},
_renderProxy: function() {
var t = this.element,
n = this.options;
this.elementOffset = t.offset();
if (this._helper) {
this.helper = this.helper || e('<div style="overflow:hidden;"></div>');
var r = e.ui.ie6 ? 1 : 0,
i = e.ui.ie6 ? 2 : -1;
this.helper.addClass(this._helper).css({
width: this.element.outerWidth() + i,
height: this.element.outerHeight() + i,
position: "absolute",
left: this.elementOffset.left - r + "px",
top: this.elementOffset.top - r + "px",
zIndex: ++n.zIndex
}), this.helper.appendTo("body").disableSelection()
} else this.helper = this.element
},
_change: {
e: function(e, t, n) {
return {
width: this.originalSize.width + t
}
},
w: function(e, t, n) {
var r = this.options,
i = this.originalSize,
s = this.originalPosition;
return {
left: s.left + t,
width: i.width - t
}
},
n: function(e, t, n) {
var r = this.options,
i = this.originalSize,
s = this.originalPosition;
return {
top: s.top + n,
height: i.height - n
}
},
s: function(e, t, n) {
return {
height: this.originalSize.height + n
}
},
se: function(t, n, r) {
return e.extend(this._change.s.apply(this, arguments), this._change.e.apply(this, [t, n, r]))
},
sw: function(t, n, r) {
return e.extend(this._change.s.apply(this, arguments), this._change.w.apply(this, [t, n, r]))
},
ne: function(t, n, r) {
return e.extend(this._change.n.apply(this, arguments), this._change.e.apply(this, [t, n, r]))
},
nw: function(t, n, r) {
return e.extend(this._change.n.apply(this, arguments), this._change.w.apply(this, [t, n, r]))
}
},
_propagate: function(t, n) {
e.ui.plugin.call(this, t, [n, this.ui()]), t != "resize" && this._trigger(t, n, this.ui())
},
plugins: {},
ui: function() {
return {
originalElement: this.originalElement,
element: this.element,
helper: this.helper,
position: this.position,
size: this.size,
originalSize: this.originalSize,
originalPosition: this.originalPosition
}
}
}), e.ui.plugin.add("resizable", "alsoResize", {
start: function(t, n) {
var r = e(this).data("resizable"),
i = r.options,
s = function(t) {
e(t).each(function() {
var t = e(this);
t.data("resizable-alsoresize", {
width: parseInt(t.width(), 10),
height: parseInt(t.height(), 10),
left: parseInt(t.css("left"), 10),
top: parseInt(t.css("top"), 10)
})
})
};
typeof i.alsoResize == "object" && !i.alsoResize.parentNode ? i.alsoResize.length ? (i.alsoResize = i.alsoResize[0], s(i.alsoResize)) : e.each(i.alsoResize, function(e) {
s(e)
}) : s(i.alsoResize)
},
resize: function(t, n) {
var r = e(this).data("resizable"),
i = r.options,
s = r.originalSize,
o = r.originalPosition,
u = {
height: r.size.height - s.height || 0,
width: r.size.width - s.width || 0,
top: r.position.top - o.top || 0,
left: r.position.left - o.left || 0
},
a = function(t, r) {
e(t).each(function() {
var t = e(this),
i = e(this).data("resizable-alsoresize"),
s = {},
o = r && r.length ? r : t.parents(n.originalElement[0]).length ? ["width", "height"] : ["width", "height", "top", "left"];
e.each(o, function(e, t) {
var n = (i[t] || 0) + (u[t] || 0);
n && n >= 0 && (s[t] = n || null)
}), t.css(s)
})
};
typeof i.alsoResize == "object" && !i.alsoResize.nodeType ? e.each(i.alsoResize, function(e, t) {
a(e, t)
}) : a(i.alsoResize)
},
stop: function(t, n) {
e(this).removeData("resizable-alsoresize")
}
}), e.ui.plugin.add("resizable", "animate", {
stop: function(t, n) {
var r = e(this).data("resizable"),
i = r.options,
s = r._proportionallyResizeElements,
o = s.length && /textarea/i.test(s[0].nodeName),
u = o && e.ui.hasScroll(s[0], "left") ? 0 : r.sizeDiff.height,
a = o ? 0 : r.sizeDiff.width,
f = {
width: r.size.width - a,
height: r.size.height - u
},
l = parseInt(r.element.css("left"), 10) + (r.position.left - r.originalPosition.left) || null,
c = parseInt(r.element.css("top"), 10) + (r.position.top - r.originalPosition.top) || null;
r.element.animate(e.extend(f, c && l ? {
top: c,
left: l
} : {}), {
duration: i.animateDuration,
easing: i.animateEasing,
step: function() {
var n = {
width: parseInt(r.element.css("width"), 10),
height: parseInt(r.element.css("height"), 10),
top: parseInt(r.element.css("top"), 10),
left: parseInt(r.element.css("left"), 10)
};
s && s.length && e(s[0]).css({
width: n.width,
height: n.height
}), r._updateCache(n), r._propagate("resize", t)
}
})
}
}), e.ui.plugin.add("resizable", "containment", {
start: function(t, r) {
var i = e(this).data("resizable"),
s = i.options,
o = i.element,
u = s.containment,
a = u instanceof e ? u.get(0) : /parent/.test(u) ? o.parent().get(0) : u;
if (!a) return;
i.containerElement = e(a);
if (/document/.test(u) || u == document) i.containerOffset = {
left: 0,
top: 0
}, i.containerPosition = {
left: 0,
top: 0
}, i.parentData = {
element: e(document),
left: 0,
top: 0,
width: e(document).width(),
height: e(document).height() || document.body.parentNode.scrollHeight
};
else {
var f = e(a),
l = [];
e(["Top", "Right", "Left", "Bottom"]).each(function(e, t) {
l[e] = n(f.css("padding" + t))
}), i.containerOffset = f.offset(), i.containerPosition = f.position(), i.containerSize = {
height: f.innerHeight() - l[3],
width: f.innerWidth() - l[1]
};
var c = i.containerOffset,
h = i.containerSize.height,
p = i.containerSize.width,
d = e.ui.hasScroll(a, "left") ? a.scrollWidth : p,
v = e.ui.hasScroll(a) ? a.scrollHeight : h;
i.parentData = {
element: a,
left: c.left,
top: c.top,
width: d,
height: v
}
}
},
resize: function(t, n) {
var r = e(this).data("resizable"),
i = r.options,
s = r.containerSize,
o = r.containerOffset,
u = r.size,
a = r.position,
f = r._aspectRatio || t.shiftKey,
l = {
top: 0,
left: 0
},
c = r.containerElement;
c[0] != document && /static/.test(c.css("position")) && (l = o), a.left < (r._helper ? o.left : 0) && (r.size.width = r.size.width + (r._helper ? r.position.left - o.left : r.position.left - l.left), f && (r.size.height = r.size.width / r.aspectRatio), r.position.left = i.helper ? o.left : 0), a.top < (r._helper ? o.top : 0) && (r.size.height = r.size.height + (r._helper ? r.position.top - o.top : r.position.top), f && (r.size.width = r.size.height * r.aspectRatio), r.position.top = r._helper ? o.top : 0), r.offset.left = r.parentData.left + r.position.left, r.offset.top = r.parentData.top + r.position.top;
var h = Math.abs((r._helper ? r.offset.left - l.left : r.offset.left - l.left) + r.sizeDiff.width),
p = Math.abs((r._helper ? r.offset.top - l.top : r.offset.top - o.top) + r.sizeDiff.height),
d = r.containerElement.get(0) == r.element.parent().get(0),
v = /relative|absolute/.test(r.containerElement.css("position"));
d && v && (h -= r.parentData.left), h + r.size.width >= r.parentData.width && (r.size.width = r.parentData.width - h, f && (r.size.height = r.size.width / r.aspectRatio)), p + r.size.height >= r.parentData.height && (r.size.height = r.parentData.height - p, f && (r.size.width = r.size.height * r.aspectRatio))
},
stop: function(t, n) {
var r = e(this).data("resizable"),
i = r.options,
s = r.position,
o = r.containerOffset,
u = r.containerPosition,
a = r.containerElement,
f = e(r.helper),
l = f.offset(),
c = f.outerWidth() - r.sizeDiff.width,
h = f.outerHeight() - r.sizeDiff.height;
r._helper && !i.animate && /relative/.test(a.css("position")) && e(this).css({
left: l.left - u.left - o.left,
width: c,
height: h
}), r._helper && !i.animate && /static/.test(a.css("position")) && e(this).css({
left: l.left - u.left - o.left,
width: c,
height: h
})
}
}), e.ui.plugin.add("resizable", "ghost", {
start: function(t, n) {
var r = e(this).data("resizable"),
i = r.options,
s = r.size;
r.ghost = r.originalElement.clone(), r.ghost.css({
opacity: .25,
display: "block",
position: "relative",
height: s.height,
width: s.width,
margin: 0,
left: 0,
top: 0
}).addClass("ui-resizable-ghost").addClass(typeof i.ghost == "string" ? i.ghost : ""), r.ghost.appendTo(r.helper)
},
resize: function(t, n) {
var r = e(this).data("resizable"),
i = r.options;
r.ghost && r.ghost.css({
position: "relative",
height: r.size.height,
width: r.size.width
})
},
stop: function(t, n) {
var r = e(this).data("resizable"),
i = r.options;
r.ghost && r.helper && r.helper.get(0).removeChild(r.ghost.get(0))
}
}), e.ui.plugin.add("resizable", "grid", {
resize: function(t, n) {
var r = e(this).data("resizable"),
i = r.options,
s = r.size,
o = r.originalSize,
u = r.originalPosition,
a = r.axis,
f = i._aspectRatio || t.shiftKey;
i.grid = typeof i.grid == "number" ? [i.grid, i.grid] : i.grid;
var l = Math.round((s.width - o.width) / (i.grid[0] || 1)) * (i.grid[0] || 1),
c = Math.round((s.height - o.height) / (i.grid[1] || 1)) * (i.grid[1] || 1);
/^(se|s|e)$/.test(a) ? (r.size.width = o.width + l, r.size.height = o.height + c) : /^(ne)$/.test(a) ? (r.size.width = o.width + l, r.size.height = o.height + c, r.position.top = u.top - c) : /^(sw)$/.test(a) ? (r.size.width = o.width + l, r.size.height = o.height + c, r.position.left = u.left - l) : (r.size.width = o.width + l, r.size.height = o.height + c, r.position.top = u.top - c, r.position.left = u.left - l)
}
});
var n = function(e) {
return parseInt(e, 10) || 0
},
r = function(e) {
return !isNaN(parseInt(e, 10))
}
}(jQuery),
function(e, t) {
var n = 5;
e.widget("ui.slider", e.ui.mouse, {
version: "1.9.2",
widgetEventPrefix: "slide",
options: {
animate: !1,
distance: 0,
max: 100,
min: 0,
orientation: "horizontal",
range: !1,
step: 1,
value: 0,
values: null
},
_create: function() {
var t, r, i = this.options,
s = this.element.find(".ui-slider-handle").addClass("ui-state-default ui-corner-all"),
o = "<a class='ui-slider-handle ui-state-default ui-corner-all' href='#'></a>",
u = [];
this._keySliding = !1, this._mouseSliding = !1, this._animateOff = !0, this._handleIndex = null, this._detectOrientation(), this._mouseInit(), this.element.addClass("ui-slider ui-slider-" + this.orientation + " ui-widget" + " ui-widget-content" + " ui-corner-all" + (i.disabled ? " ui-slider-disabled ui-disabled" : "")), this.range = e([]), i.range && (i.range === !0 && (i.values || (i.values = [this._valueMin(), this._valueMin()]), i.values.length && i.values.length !== 2 && (i.values = [i.values[0], i.values[0]])), this.range = e("<div></div>").appendTo(this.element).addClass("ui-slider-range ui-widget-header" + (i.range === "min" || i.range === "max" ? " ui-slider-range-" + i.range : ""))), r = i.values && i.values.length || 1;
for (t = s.length; t < r; t++) u.push(o);
this.handles = s.add(e(u.join("")).appendTo(this.element)), this.handle = this.handles.eq(0), this.handles.add(this.range).filter("a").click(function(e) {
e.preventDefault()
}).mouseenter(function() {
i.disabled || e(this).addClass("ui-state-hover")
}).mouseleave(function() {
e(this).removeClass("ui-state-hover")
}).focus(function() {
i.disabled ? e(this).blur() : (e(".ui-slider .ui-state-focus").removeClass("ui-state-focus"), e(this).addClass("ui-state-focus"))
}).blur(function() {
e(this).removeClass("ui-state-focus")
}), this.handles.each(function(t) {
e(this).data("ui-slider-handle-index", t)
}), this._on(this.handles, {
keydown: function(t) {
var r, i, s, o, u = e(t.target).data("ui-slider-handle-index");
switch (t.keyCode) {
case e.ui.keyCode.HOME:
case e.ui.keyCode.END:
case e.ui.keyCode.PAGE_UP:
case e.ui.keyCode.PAGE_DOWN:
case e.ui.keyCode.UP:
case e.ui.keyCode.RIGHT:
case e.ui.keyCode.DOWN:
case e.ui.keyCode.LEFT:
t.preventDefault();
if (!this._keySliding) {
this._keySliding = !0, e(t.target).addClass("ui-state-active"), r = this._start(t, u);
if (r === !1) return
}
}
o = this.options.step, this.options.values && this.options.values.length ? i = s = this.values(u) : i = s = this.value();
switch (t.keyCode) {
case e.ui.keyCode.HOME:
s = this._valueMin();
break;
case e.ui.keyCode.END:
s = this._valueMax();
break;
case e.ui.keyCode.PAGE_UP:
s = this._trimAlignValue(i + (this._valueMax() - this._valueMin()) / n);
break;
case e.ui.keyCode.PAGE_DOWN:
s = this._trimAlignValue(i - (this._valueMax() - this._valueMin()) / n);
break;
case e.ui.keyCode.UP:
case e.ui.keyCode.RIGHT:
if (i === this._valueMax()) return;
s = this._trimAlignValue(i + o);
break;
case e.ui.keyCode.DOWN:
case e.ui.keyCode.LEFT:
if (i === this._valueMin()) return;
s = this._trimAlignValue(i - o)
}
this._slide(t, u, s)
},
keyup: function(t) {
var n = e(t.target).data("ui-slider-handle-index");
this._keySliding && (this._keySliding = !1, this._stop(t, n), this._change(t, n), e(t.target).removeClass("ui-state-active"))
}
}), this._refreshValue(), this._animateOff = !1
},
_destroy: function() {
this.handles.remove(), this.range.remove(), this.element.removeClass("ui-slider ui-slider-horizontal ui-slider-vertical ui-slider-disabled ui-widget ui-widget-content ui-corner-all"), this._mouseDestroy()
},
_mouseCapture: function(t) {
var n, r, i, s, o, u, a, f, l = this,
c = this.options;
return c.disabled ? !1 : (this.elementSize = {
width: this.element.outerWidth(),
height: this.element.outerHeight()
}, this.elementOffset = this.element.offset(), n = {
x: t.pageX,
y: t.pageY
}, r = this._normValueFromMouse(n), i = this._valueMax() - this._valueMin() + 1, this.handles.each(function(t) {
var n = Math.abs(r - l.values(t));
i > n && (i = n, s = e(this), o = t)
}), c.range === !0 && this.values(1) === c.min && (o += 1, s = e(this.handles[o])), u = this._start(t, o), u === !1 ? !1 : (this._mouseSliding = !0, this._handleIndex = o, s.addClass("ui-state-active").focus(), a = s.offset(), f = !e(t.target).parents().andSelf().is(".ui-slider-handle"), this._clickOffset = f ? {
left: 0,
top: 0
} : {
left: t.pageX - a.left - s.width() / 2,
top: t.pageY - a.top - s.height() / 2 - (parseInt(s.css("borderTopWidth"), 10) || 0) - (parseInt(s.css("borderBottomWidth"), 10) || 0) + (parseInt(s.css("marginTop"), 10) || 0)
}, this.handles.hasClass("ui-state-hover") || this._slide(t, o, r), this._animateOff = !0, !0))
},
_mouseStart: function() {
return !0
},
_mouseDrag: function(e) {
var t = {
x: e.pageX,
y: e.pageY
},
n = this._normValueFromMouse(t);
return this._slide(e, this._handleIndex, n), !1
},
_mouseStop: function(e) {
return this.handles.removeClass("ui-state-active"), this._mouseSliding = !1, this._stop(e, this._handleIndex), this._change(e, this._handleIndex), this._handleIndex = null, this._clickOffset = null, this._animateOff = !1, !1
},
_detectOrientation: function() {
this.orientation = this.options.orientation === "vertical" ? "vertical" : "horizontal"
},
_normValueFromMouse: function(e) {
var t, n, r, i, s;
return this.orientation === "horizontal" ? (t = this.elementSize.width, n = e.x - this.elementOffset.left - (this._clickOffset ? this._clickOffset.left : 0)) : (t = this.elementSize.height, n = e.y - this.elementOffset.top - (this._clickOffset ? this._clickOffset.top : 0)), r = n / t, r > 1 && (r = 1), r < 0 && (r = 0), this.orientation === "vertical" && (r = 1 - r), i = this._valueMax() - this._valueMin(), s = this._valueMin() + r * i, this._trimAlignValue(s)
},
_start: function(e, t) {
var n = {
handle: this.handles[t],
value: this.value()
};
return this.options.values && this.options.values.length && (n.value = this.values(t), n.values = this.values()), this._trigger("start", e, n)
},
_slide: function(e, t, n) {
var r, i, s;
this.options.values && this.options.values.length ? (r = this.values(t ? 0 : 1), this.options.values.length === 2 && this.options.range === !0 && (t === 0 && n > r || t === 1 && n < r) && (n = r), n !== this.values(t) && (i = this.values(), i[t] = n, s = this._trigger("slide", e, {
handle: this.handles[t],
value: n,
values: i
}), r = this.values(t ? 0 : 1), s !== !1 && this.values(t, n, !0))) : n !== this.value() && (s = this._trigger("slide", e, {
handle: this.handles[t],
value: n
}), s !== !1 && this.value(n))
},
_stop: function(e, t) {
var n = {
handle: this.handles[t],
value: this.value()
};
this.options.values && this.options.values.length && (n.value = this.values(t), n.values = this.values()), this._trigger("stop", e, n)
},
_change: function(e, t) {
if (!this._keySliding && !this._mouseSliding) {
var n = {
handle: this.handles[t],
value: this.value()
};
this.options.values && this.options.values.length && (n.value = this.values(t), n.values = this.values()), this._trigger("change", e, n)
}
},
value: function(e) {
if (arguments.length) {
this.options.value = this._trimAlignValue(e), this._refreshValue(), this._change(null, 0);
return
}
return this._value()
},
values: function(t, n) {
var r, i, s;
if (arguments.length > 1) {
this.options.values[t] = this._trimAlignValue(n), this._refreshValue(), this._change(null, t);
return
}
if (!arguments.length) return this._values();
if (!e.isArray(arguments[0])) return this.options.values && this.options.values.length ? this._values(t) : this.value();
r = this.options.values, i = arguments[0];
for (s = 0; s < r.length; s += 1) r[s] = this._trimAlignValue(i[s]), this._change(null, s);
this._refreshValue()
},
_setOption: function(t, n) {
var r, i = 0;
e.isArray(this.options.values) && (i = this.options.values.length), e.Widget.prototype._setOption.apply(this, arguments);
switch (t) {
case "disabled":
n ? (this.handles.filter(".ui-state-focus").blur(), this.handles.removeClass("ui-state-hover"), this.handles.prop("disabled", !0), this.element.addClass("ui-disabled")) : (this.handles.prop("disabled", !1), this.element.removeClass("ui-disabled"));
break;
case "orientation":
this
._detectOrientation(), this.element.removeClass("ui-slider-horizontal ui-slider-vertical").addClass("ui-slider-" + this.orientation), this._refreshValue();
break;
case "value":
this._animateOff = !0, this._refreshValue(), this._change(null, 0), this._animateOff = !1;
break;
case "values":
this._animateOff = !0, this._refreshValue();
for (r = 0; r < i; r += 1) this._change(null, r);
this._animateOff = !1;
break;
case "min":
case "max":
this._animateOff = !0, this._refreshValue(), this._animateOff = !1
}
},
_value: function() {
var e = this.options.value;
return e = this._trimAlignValue(e), e
},
_values: function(e) {
var t, n, r;
if (arguments.length) return t = this.options.values[e], t = this._trimAlignValue(t), t;
n = this.options.values.slice();
for (r = 0; r < n.length; r += 1) n[r] = this._trimAlignValue(n[r]);
return n
},
_trimAlignValue: function(e) {
if (e <= this._valueMin()) return this._valueMin();
if (e >= this._valueMax()) return this._valueMax();
var t = this.options.step > 0 ? this.options.step : 1,
n = (e - this._valueMin()) % t,
r = e - n;
return Math.abs(n) * 2 >= t && (r += n > 0 ? t : -t), parseFloat(r.toFixed(5))
},
_valueMin: function() {
return this.options.min
},
_valueMax: function() {
return this.options.max
},
_refreshValue: function() {
var t, n, r, i, s, o = this.options.range,
u = this.options,
a = this,
f = this._animateOff ? !1 : u.animate,
l = {};
this.options.values && this.options.values.length ? this.handles.each(function(r) {
n = (a.values(r) - a._valueMin()) / (a._valueMax() - a._valueMin()) * 100, l[a.orientation === "horizontal" ? "left" : "bottom"] = n + "%", e(this).stop(1, 1)[f ? "animate" : "css"](l, u.animate), a.options.range === !0 && (a.orientation === "horizontal" ? (r === 0 && a.range.stop(1, 1)[f ? "animate" : "css"]({
left: n + "%"
}, u.animate), r === 1 && a.range[f ? "animate" : "css"]({
width: n - t + "%"
}, {
queue: !1,
duration: u.animate
})) : (r === 0 && a.range.stop(1, 1)[f ? "animate" : "css"]({
bottom: n + "%"
}, u.animate), r === 1 && a.range[f ? "animate" : "css"]({
height: n - t + "%"
}, {
queue: !1,
duration: u.animate
}))), t = n
}) : (r = this.value(), i = this._valueMin(), s = this._valueMax(), n = s !== i ? (r - i) / (s - i) * 100 : 0, l[this.orientation === "horizontal" ? "left" : "bottom"] = n + "%", this.handle.stop(1, 1)[f ? "animate" : "css"](l, u.animate), o === "min" && this.orientation === "horizontal" && this.range.stop(1, 1)[f ? "animate" : "css"]({
width: n + "%"
}, u.animate), o === "max" && this.orientation === "horizontal" && this.range[f ? "animate" : "css"]({
width: 100 - n + "%"
}, {
queue: !1,
duration: u.animate
}), o === "min" && this.orientation === "vertical" && this.range.stop(1, 1)[f ? "animate" : "css"]({
height: n + "%"
}, u.animate), o === "max" && this.orientation === "vertical" && this.range[f ? "animate" : "css"]({
height: 100 - n + "%"
}, {
queue: !1,
duration: u.animate
}))
}
})
}(jQuery), ! function(e) {
function t() {
return new Date(Date.UTC.apply(Date, arguments))
}
function n() {
var e = new Date;
return t(e.getUTCFullYear(), e.getUTCMonth(), e.getUTCDate())
}
var r = function(t, n) {
var r = this;
this.element = e(t), this.language = n.language || this.element.data("date-language") || "en", this.language = this.language in i ? this.language : this.language.split("-")[0], this.language = this.language in i ? this.language : "en", this.isRTL = i[this.language].rtl || !1, this.format = s.parseFormat(n.format || this.element.data("date-format") || i[this.language].format || "mm/dd/yyyy"), this.isInline = !1, this.isInput = this.element.is("input"), this.component = this.element.is(".date") ? this.element.find(".add-on") : !1, this.hasInput = this.component && this.element.find("input").length, this.component && this.component.length === 0 && (this.component = !1), this._attachEvents(), this.forceParse = !0, "forceParse" in n ? this.forceParse = n.forceParse : "dateForceParse" in this.element.data() && (this.forceParse = this.element.data("date-force-parse")), this.picker = e(s.template).appendTo(this.isInline ? this.element : "body").on({
click: e.proxy(this.click, this),
mousedown: e.proxy(this.mousedown, this)
}), this.isInline ? this.picker.addClass("datepicker-inline") : this.picker.addClass("datepicker-dropdown dropdown-menu"), this.isRTL && (this.picker.addClass("datepicker-rtl"), this.picker.find(".prev i, .next i").toggleClass("icon-arrow-left icon-arrow-right")), e(document).on("mousedown", function(t) {
e(t.target).closest(".datepicker.datepicker-inline, .datepicker.datepicker-dropdown").length === 0 && r.hide()
}), this.autoclose = !1, "autoclose" in n ? this.autoclose = n.autoclose : "dateAutoclose" in this.element.data() && (this.autoclose = this.element.data("date-autoclose")), this.keyboardNavigation = !0, "keyboardNavigation" in n ? this.keyboardNavigation = n.keyboardNavigation : "dateKeyboardNavigation" in this.element.data() && (this.keyboardNavigation = this.element.data("date-keyboard-navigation")), this.viewMode = this.startViewMode = 0;
switch (n.startView || this.element.data("date-start-view")) {
case 2:
case "decade":
this.viewMode = this.startViewMode = 2;
break;
case 1:
case "year":
this.viewMode = this.startViewMode = 1
}
this.minViewMode = n.minViewMode || this.element.data("date-min-view-mode") || 0;
if (typeof this.minViewMode == "string") switch (this.minViewMode) {
case "months":
this.minViewMode = 1;
break;
case "years":
this.minViewMode = 2;
break;
default:
this.minViewMode = 0
}
this.viewMode = this.startViewMode = Math.max(this.startViewMode, this.minViewMode), this.todayBtn = n.todayBtn || this.element.data("date-today-btn") || !1, this.todayHighlight = n.todayHighlight || this.element.data("date-today-highlight") || !1, this.calendarWeeks = !1, "calendarWeeks" in n ? this.calendarWeeks = n.calendarWeeks : "dateCalendarWeeks" in this.element.data() && (this.calendarWeeks = this.element.data("date-calendar-weeks")), this.calendarWeeks && this.picker.find("tfoot th.today").attr("colspan", function(e, t) {
return parseInt(t) + 1
}), this.weekStart = (n.weekStart || this.element.data("date-weekstart") || i[this.language].weekStart || 0) % 7, this.weekEnd = (this.weekStart + 6) % 7, this.startDate = -Infinity, this.endDate = Infinity, this.daysOfWeekDisabled = [], this.setStartDate(n.startDate || this.element.data("date-startdate")), this.setEndDate(n.endDate || this.element.data("date-enddate")), this.setDaysOfWeekDisabled(n.daysOfWeekDisabled || this.element.data("date-days-of-week-disabled")), this.fillDow(), this.fillMonths(), this.update(), this.showMode(), this.isInline && this.show()
};
r.prototype = {
constructor: r,
_events: [],
_attachEvents: function() {
this._detachEvents(), this.isInput ? this._events = [
[this.element, {
focus: e.proxy(this.show, this),
keyup: e.proxy(this.update, this),
keydown: e.proxy(this.keydown, this)
}]
] : this.component && this.hasInput ? this._events = [
[this.element.find("input"), {
focus: e.proxy(this.show, this),
keyup: e.proxy(this.update, this),
keydown: e.proxy(this.keydown, this)
}],
[this.component, {
click: e.proxy(this.show, this)
}]
] : this.element.is("div") ? this.isInline = !0 : this._events = [
[this.element, {
click: e.proxy(this.show, this)
}]
];
for (var t = 0, n, r; t < this._events.length; t++) n = this._events[t][0], r = this._events[t][1], n.on(r)
},
_detachEvents: function() {
for (var e = 0, t, n; e < this._events.length; e++) t = this._events[e][0], n = this._events[e][1], t.off(n);
this._events = []
},
show: function(t) {
this.picker.show(), this.height = this.component ? this.component.outerHeight() : this.element.outerHeight(), this.update(), this.place(), e(window).on("resize", e.proxy(this.place, this)), t && (t.stopPropagation(), t.preventDefault()), this.element.trigger({
type: "show",
date: this.date
})
},
hide: function(t) {
if (this.isInline) return;
if (!this.picker.is(":visible")) return;
this.picker.hide(), e(window).off("resize", this.place), this.viewMode = this.startViewMode, this.showMode(), this.isInput || e(document).off("mousedown", this.hide), this.forceParse && (this.isInput && this.element.val() || this.hasInput && this.element.find("input").val()) && this.setValue(), this.element.trigger({
type: "hide",
date: this.date
})
},
remove: function() {
this._detachEvents(), this.picker.remove(), delete this.element.data().datepicker
},
getDate: function() {
var e = this.getUTCDate();
return new Date(e.getTime() + e.getTimezoneOffset() * 6e4)
},
getUTCDate: function() {
return this.date
},
setDate: function(e) {
this.setUTCDate(new Date(e.getTime() - e.getTimezoneOffset() * 6e4))
},
setUTCDate: function(e) {
this.date = e, this.setValue()
},
setValue: function() {
var e = this.getFormattedDate();
this.isInput ? this.element.val(e) : (this.component && this.element.find("input").val(e), this.element.data("date", e))
},
getFormattedDate: function(e) {
return e === undefined && (e = this.format), s.formatDate(this.date, e, this.language)
},
setStartDate: function(e) {
this.startDate = e || -Infinity, this.startDate !== -Infinity && (this.startDate = s.parseDate(this.startDate, this.format, this.language)), this.update(), this.updateNavArrows()
},
setEndDate: function(e) {
this.endDate = e || Infinity, this.endDate !== Infinity && (this.endDate = s.parseDate(this.endDate, this.format, this.language)), this.update(), this.updateNavArrows()
},
setDaysOfWeekDisabled: function(t) {
this.daysOfWeekDisabled = t || [], e.isArray(this.daysOfWeekDisabled) || (this.daysOfWeekDisabled = this.daysOfWeekDisabled.split(/,\s*/)), this.daysOfWeekDisabled = e.map(this.daysOfWeekDisabled, function(e) {
return parseInt(e, 10)
}), this.update(), this.updateNavArrows()
},
place: function() {
if (this.isInline) return;
var t = parseInt(this.element.parents().filter(function() {
return e(this).css("z-index") != "auto"
}).first().css("z-index")) + 10,
n = this.component ? this.component.offset() : this.element.offset(),
r = this.component ? this.component.outerHeight(!0) : this.element.outerHeight(!0);
this.picker.css({
top: n.top + r,
left: n.left,
zIndex: t
})
},
update: function() {
var e, t = !1;
arguments && arguments.length && (typeof arguments[0] == "string" || arguments[0] instanceof Date) ? (e = arguments[0], t = !0) : e = this.isInput ? this.element.val() : this.element.data("date") || this.element.find("input").val(), this.date = s.parseDate(e, this.format, this.language), t && this.setValue(), this.date < this.startDate ? this.viewDate = new Date(this.startDate) : this.date > this.endDate ? this.viewDate = new Date(this.endDate) : this.viewDate = new Date(this.date), this.fill()
},
fillDow: function() {
var e = this.weekStart,
t = "<tr>";
if (this.calendarWeeks) {
var n = '<th class="cw"> </th>';
t += n, this.picker.find(".datepicker-days thead tr:first-child").prepend(n)
}
while (e < this.weekStart + 7) t += '<th class="dow">' + i[this.language].daysMin[e++ % 7] + "</th>";
t += "</tr>", this.picker.find(".datepicker-days thead").append(t)
},
fillMonths: function() {
var e = "",
t = 0;
while (t < 12) e += '<span class="month">' + i[this.language].monthsShort[t++] + "</span>";
this.picker.find(".datepicker-months td").html(e)
},
fill: function() {
var n = new Date(this.viewDate),
r = n.getUTCFullYear(),
o = n.getUTCMonth(),
u = this.startDate !== -Infinity ? this.startDate.getUTCFullYear() : -Infinity,
a = this.startDate !== -Infinity ? this.startDate.getUTCMonth() : -Infinity,
f = this.endDate !== Infinity ? this.endDate.getUTCFullYear() : Infinity,
l = this.endDate !== Infinity ? this.endDate.getUTCMonth() : Infinity,
c = this.date && this.date.valueOf(),
h = new Date;
this.picker.find(".datepicker-days thead th.switch").text(i[this.language].months[o] + " " + r), this.picker.find("tfoot th.today").text(i[this.language].today).toggle(this.todayBtn !== !1), this.updateNavArrows(), this.fillMonths();
var p = t(r, o - 1, 28, 0, 0, 0, 0),
d = s.getDaysInMonth(p.getUTCFullYear(), p.getUTCMonth());
p.setUTCDate(d), p.setUTCDate(d - (p.getUTCDay() - this.weekStart + 7) % 7);
var v = new Date(p);
v.setUTCDate(v.getUTCDate() + 42), v = v.valueOf();
var m = [],
g;
while (p.valueOf() < v) {
if (p.getUTCDay() == this.weekStart) {
m.push("<tr>");
if (this.calendarWeeks) {
var y = new Date(+p + (this.weekStart - p.getUTCDay() - 7) % 7 * 864e5),
b = new Date(+y + (11 - y.getUTCDay()) % 7 * 864e5),
w = new Date(+(w = t(b.getUTCFullYear(), 0, 1)) + (11 - w.getUTCDay()) % 7 * 864e5),
E = (b - w) / 864e5 / 7 + 1;
m.push('<td class="cw">' + E + "</td>")
}
}
g = "";
if (p.getUTCFullYear() < r || p.getUTCFullYear() == r && p.getUTCMonth() < o) g += " old";
else if (p.getUTCFullYear() > r || p.getUTCFullYear() == r && p.getUTCMonth() > o) g += " new";
this.todayHighlight && p.getUTCFullYear() == h.getFullYear() && p.getUTCMonth() == h.getMonth() && p.getUTCDate() == h.getDate() && (g += " today"), c && p.valueOf() == c && (g += " active");
if (p.valueOf() < this.startDate || p.valueOf() > this.endDate || e.inArray(p.getUTCDay(), this.daysOfWeekDisabled) !== -1) g += " disabled";
m.push('<td class="day' + g + '">' + p.getUTCDate() + "</td>"), p.getUTCDay() == this.weekEnd && m.push("</tr>"), p.setUTCDate(p.getUTCDate() + 1)
}
this.picker.find(".datepicker-days tbody").empty().append(m.join(""));
var S = this.date && this.date.getUTCFullYear(),
x = this.picker.find(".datepicker-months").find("th:eq(1)").text(r).end().find("span").removeClass("active");
S && S == r && x.eq(this.date.getUTCMonth()).addClass("active"), (r < u || r > f) && x.addClass("disabled"), r == u && x.slice(0, a).addClass("disabled"), r == f && x.slice(l + 1).addClass("disabled"), m = "", r = parseInt(r / 10, 10) * 10;
var T = this.picker.find(".datepicker-years").find("th:eq(1)").text(r + "-" + (r + 9)).end().find("td");
r -= 1;
for (var N = -1; N < 11; N++) m += '<span class="year' + (N == -1 || N == 10 ? " old" : "") + (S == r ? " active" : "") + (r < u || r > f ? " disabled" : "") + '">' + r + "</span>", r += 1;
T.html(m)
},
updateNavArrows: function() {
var e = new Date(this.viewDate),
t = e.getUTCFullYear(),
n = e.getUTCMonth();
switch (this.viewMode) {
case 0:
this.startDate !== -Infinity && t <= this.startDate.getUTCFullYear() && n <= this.startDate.getUTCMonth() ? this.picker.find(".prev").css({
visibility: "hidden"
}) : this.picker.find(".prev").css({
visibility: "visible"
}), this.endDate !== Infinity && t >= this.endDate.getUTCFullYear() && n >= this.endDate.getUTCMonth() ? this.picker.find(".next").css({
visibility: "hidden"
}) : this.picker.find(".next").css({
visibility: "visible"
});
break;
case 1:
case 2:
this.startDate !== -Infinity && t <= this.startDate.getUTCFullYear() ? this.picker.find(".prev").css({
visibility: "hidden"
}) : this.picker.find(".prev").css({
visibility: "visible"
}), this.endDate !== Infinity && t >= this.endDate.getUTCFullYear() ? this.picker.find(".next").css({
visibility: "hidden"
}) : this.picker.find(".next").css({
visibility: "visible"
})
}
},
click: function(n) {
n.stopPropagation(), n.preventDefault();
var r = e(n.target).closest("span, td, th");
if (r.length == 1) switch (r[0].nodeName.toLowerCase()) {
case "th":
switch (r[0].className) {
case "switch":
this.showMode(1);
break;
case "prev":
case "next":
var i = s.modes[this.viewMode].navStep * (r[0].className == "prev" ? -1 : 1);
switch (this.viewMode) {
case 0:
this.viewDate = this.moveMonth(this.viewDate, i);
break;
case 1:
case 2:
this.viewDate = this.moveYear(this.viewDate, i)
}
this.fill();
break;
case "today":
var o = new Date;
o = t(o.getFullYear(), o.getMonth(), o.getDate(), 0, 0, 0), this.showMode(-2);
var u = this.todayBtn == "linked" ? null : "view";
this._setDate(o, u)
}
break;
case "span":
if (!r.is(".disabled")) {
this.viewDate.setUTCDate(1);
if (r.is(".month")) {
var a = 1,
f = r.parent().find("span").index(r),
l = this.viewDate.getUTCFullYear();
this.viewDate.setUTCMonth(f), this.element.trigger({
type: "changeMonth",
date: this.viewDate
}), this.minViewMode == 1 && this._setDate(t(l, f, a, 0, 0, 0, 0))
} else {
var l = parseInt(r.text(), 10) || 0,
a = 1,
f = 0;
this.viewDate.setUTCFullYear(l), this.element.trigger({
type: "changeYear",
date: this.viewDate
}), this.minViewMode == 2 && this._setDate(t(l, f, a, 0, 0, 0, 0))
}
this.showMode(-1), this.fill()
}
break;
case "td":
if (r.is(".day") && !r.is(".disabled")) {
var a = parseInt(r.text(), 10) || 1,
l = this.viewDate.getUTCFullYear(),
f = this.viewDate.getUTCMonth();
r.is(".old") ? f === 0 ? (f = 11, l -= 1) : f -= 1 : r.is(".new") && (f == 11 ? (f = 0, l += 1) : f += 1), this._setDate(t(l, f, a, 0, 0, 0, 0))
}
}
},
_setDate: function(e, t) {
if (!t || t == "date") this.date = e;
if (!t || t == "view") this.viewDate = e;
this.fill(), this.setValue(), this.element.trigger({
type: "changeDate",
date: this.date
});
var n;
this.isInput ? n = this.element : this.component && (n = this.element.find("input")), n && (n.change(), this.autoclose && (!t || t == "date") && this.hide())
},
moveMonth: function(e, t) {
if (!t) return e;
var n = new Date(e.valueOf()),
r = n.getUTCDate(),
i = n.getUTCMonth(),
s = Math.abs(t),
o, u;
t = t > 0 ? 1 : -1;
if (s == 1) {
u = t == -1 ? function() {
return n.getUTCMonth() == i
} : function() {
return n.getUTCMonth() != o
}, o = i + t, n.setUTCMonth(o);
if (o < 0 || o > 11) o = (o + 12) % 12
} else {
for (var a = 0; a < s; a++) n = this.moveMonth(n, t);
o = n.getUTCMonth(), n.setUTCDate(r), u = function() {
return o != n.getUTCMonth()
}
}
while (u()) n.setUTCDate(--r), n.setUTCMonth(o);
return n
},
moveYear: function(e, t) {
return this.moveMonth(e, t * 12)
},
dateWithinRange: function(e) {
return e >= this.startDate && e <= this.endDate
},
keydown: function(e) {
if (this.picker.is(":not(:visible)")) {
e.keyCode == 27 && this.show();
return
}
var t = !1,
n, r, i, s, o;
switch (e.keyCode) {
case 27:
this.hide(), e.preventDefault();
break;
case 37:
case 39:
if (!this.keyboardNavigation) break;
n = e.keyCode == 37 ? -1 : 1, e.ctrlKey ? (s = this.moveYear(this.date, n), o = this.moveYear(this.viewDate, n)) : e.shiftKey ? (s = this.moveMonth(this.date, n), o = this.moveMonth(this.viewDate, n)) : (s = new Date(this.date), s.setUTCDate(this.date.getUTCDate() + n), o = new Date(this.viewDate), o.setUTCDate(this.viewDate.getUTCDate() + n)), this.dateWithinRange(s) && (this.date = s, this.viewDate = o, this.setValue(), this.update(), e.preventDefault(), t = !0);
break;
case 38:
case 40:
if (!this.keyboardNavigation) break;
n = e.keyCode == 38 ? -1 : 1, e.ctrlKey ? (s = this.moveYear(this.date, n), o = this.moveYear(this.viewDate, n)) : e.shiftKey ? (s = this.moveMonth(this.date, n), o = this.moveMonth(this.viewDate, n)) : (s = new Date(this.date), s.setUTCDate(this.date.getUTCDate() + n * 7), o = new Date(this.viewDate), o.setUTCDate(this.viewDate.getUTCDate() + n * 7)), this.dateWithinRange(s) && (this.date = s, this.viewDate = o, this.setValue(), this.update(), e.preventDefault(), t = !0);
break;
case 13:
this.hide(), e.preventDefault();
break;
case 9:
this.hide()
}
if (t) {
this.element.trigger({
type: "changeDate",
date: this.date
});
var u;
this.isInput ? u = this.element : this.component && (u = this.element.find("input")), u && u.change()
}
},
showMode: function(e) {
e && (this.viewMode = Math.max(this.minViewMode, Math.min(2, this.viewMode + e))), this.picker.find(">div").hide().filter(".datepicker-" + s.modes[this.viewMode].clsName).css("display", "block"), this.updateNavArrows()
}
}, e.fn.datepicker = function(t) {
var n = Array.apply(null, arguments);
return n.shift(), this.each(function() {
var i = e(this),
s = i.data("datepicker"),
o = typeof t == "object" && t;
s || i.data("datepicker", s = new r(this, e.extend({}, e.fn.datepicker.defaults, o))), typeof t == "string" && typeof s[t] == "function" && s[t].apply(s, n)
})
}, e.fn.datepicker.defaults = {}, e.fn.datepicker.Constructor = r;
var i = e.fn.datepicker.dates = {
en: {
days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"],
daysShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
daysMin: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"],
months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
monthsShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
today: "Today"
}
},
s = {
modes: [{
clsName: "days",
navFnc: "Month",
navStep: 1
}, {
clsName: "months",
navFnc: "FullYear",
navStep: 1
}, {
clsName: "years",
navFnc: "FullYear",
navStep: 10
}],
isLeapYear: function(e) {
return e % 4 === 0 && e % 100 !== 0 || e % 400 === 0
},
getDaysInMonth: function(e, t) {
return [31, s.isLeapYear(e) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][t]
},
validParts: /dd?|DD?|mm?|MM?|yy(?:yy)?/g,
nonpunctuation: /[^ -\/:-@\[\u3400-\u9fff-`{-~\t\n\r]+/g,
parseFormat: function(e) {
var t = e.replace(this.validParts, "\0").split("\0"),
n = e.match(this.validParts);
if (!t || !t.length || !n || n.length === 0) throw new Error("Invalid date format.");
return {
separators: t,
parts: n
}
},
parseDate: function(n, s, o) {
if (n instanceof Date) return n;
if (/^[\-+]\d+[dmwy]([\s,]+[\-+]\d+[dmwy])*$/.test(n)) {
var u = /([\-+]\d+)([dmwy])/,
a = n.match(/([\-+]\d+)([dmwy])/g),
f, l;
n = new Date;
for (var c = 0; c < a.length; c++) {
f = u.exec(a[c]), l = parseInt(f[1]);
switch (f[2]) {
case "d":
n.setUTCDate(n.getUTCDate() + l);
break;
case "m":
n = r.prototype.moveMonth.call(r.prototype, n, l);
break;
case "w":
n.setUTCDate(n.getUTCDate() + l * 7);
break;
case "y":
n = r.prototype.moveYear.call(r.prototype, n, l)
}
}
return t(n.getUTCFullYear(), n.getUTCMonth(), n.getUTCDate(), 0, 0, 0)
}
var a = n && n.match(this.nonpunctuation) || [],
n = new Date,
h = {},
p = ["yyyy", "yy", "M", "MM", "m", "mm", "d", "dd"],
d = {
yyyy: function(e, t) {
return e.setUTCFullYear(t)
},
yy: function(e, t) {
return e.setUTCFullYear(2e3 + t)
},
m: function(e, t) {
t -= 1;
while (t < 0) t += 12;
t %= 12, e.setUTCMonth(t);
while (e.getUTCMonth() != t) e.setUTCDate(e.getUTCDate() - 1);
return e
},
d: function(e, t) {
return e.setUTCDate(t)
}
},
v, m, f;
d.M = d.MM = d.mm = d.m, d.dd = d.d, n = t(n.getFullYear(), n.getMonth(), n.getDate(), 0, 0, 0);
var g = s.parts.slice();
a.length != g.length && (g = e(g).filter(function(t, n) {
return e.inArray(n, p) !== -1
}).toArray());
if (a.length == g.length) {
for (var c = 0, y = g.length; c < y; c++) {
v = parseInt(a[c], 10), f = g[c];
if (isNaN(v)) switch (f) {
case "MM":
m = e(i[o].months).filter(function() {
var e = this.slice(0, a[c].length),
t = a[c].slice(0, e.length);
return e == t
}), v = e.inArray(m[0], i[o].months) + 1;
break;
case "M":
m = e(i[o].monthsShort).filter(function() {
var e = this.slice(0, a[c].length),
t = a[c].slice(0, e.length);
return e == t
}), v = e.inArray(m[0], i[o].monthsShort) + 1
}
h[f] = v
}
for (var c = 0, b; c < p.length; c++) b = p[c], b in h && !isNaN(h[b]) && d[b](n, h[b])
}
return n
},
formatDate: function(t, n, r) {
var s = {
d: t.getUTCDate(),
D: i[r].daysShort[t.getUTCDay()],
DD: i[r].days[t.getUTCDay()],
m: t.getUTCMonth() + 1,
M: i[r].monthsShort[t.getUTCMonth()],
MM: i[r].months[t.getUTCMonth()],
yy: t.getUTCFullYear().toString().substring(2),
yyyy: t.getUTCFullYear()
};
s.dd = (s.d < 10 ? "0" : "") + s.d, s.mm = (s.m < 10 ? "0" : "") + s.m;
var t = [],
o = e.extend([], n.separators);
for (var u = 0, a = n.parts.length; u < a; u++) o.length && t.push(o.shift()), t.push(s[n.parts[u]]);
return t.join("")
},
headTemplate: '<thead><tr><th class="prev"><i class="icon-arrow-left"/></th><th colspan="5" class="switch"></th><th class="next"><i class="icon-arrow-right"/></th></tr></thead>',
contTemplate: '<tbody><tr><td colspan="7"></td></tr></tbody>',
footTemplate: '<tfoot><tr><th colspan="7" class="today"></th></tr></tfoot>'
};
s.template = '<div class="datepicker"><div class="datepicker-days"><table class=" table-condensed">' + s.headTemplate + "<tbody></tbody>" + s.footTemplate + "</table>" + "</div>" + '<div class="datepicker-months">' + '<table class="table-condensed">' + s.headTemplate + s.contTemplate + s.footTemplate + "</table>" + "</div>" + '<div class="datepicker-years">' + '<table class="table-condensed">' + s.headTemplate + s.contTemplate + s.footTemplate + "</table>" + "</div>" + "</div>", e.fn.datepicker.DPGlobal = s
}(window.jQuery),
function(e) {
e.fn.datepicker.dates.bg = {
days: ["Неделя", "Понеделник", "Вторник", "Сряда", "Четвъртък", "Петък", "Събота", "Неделя"],
daysShort: ["Нед", "Пон", "Вто", "Сря", "Чет", "Пет", "Съб", "Нед"],
daysMin: ["Н", "П", "В", "С", "Ч", "П", "С", "Н"],
months: ["Януари", "Февруари", "Март", "Април", "Май", "Юни", "Юли", "Август", "Септември", "Октомври", "Ноември", "Декември"],
monthsShort: ["Ян", "Фев", "Мар", "Апр", "Май", "Юни", "Юли", "Авг", "Сеп", "Окт", "Ное", "Дек"],
today: "днес"
}
}(jQuery),
function(e) {
e.fn.datepicker.dates.br = {
days: ["Domingo", "Segunda", "Terça", "Quarta", "Quinta", "Sexta", "Sábado", "Domingo"],
daysShort: ["Dom", "Seg", "Ter", "Qua", "Qui", "Sex", "Sáb", "Dom"],
daysMin: ["Do", "Se", "Te", "Qu", "Qu", "Se", "Sa", "Do"],
months: ["Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"],
monthsShort: ["Jan", "Fev", "Mar", "Abr", "Mai", "Jun", "Jul", "Ago", "Set", "Out", "Nov", "Dez"]
}
}(jQuery),
function(e) {
e.fn.datepicker.dates.ca = {
days: ["Diumenge", "Dilluns", "Dimarts", "Dimecres", "Dijous", "Divendres", "Dissabte", "Diumenge"],
daysShort: ["Diu", "Dil", "Dmt", "Dmc", "Dij", "Div", "Dis", "Diu"],
daysMin: ["dg", "dl", "dt", "dc", "dj", "dv", "ds", "dg"],
months: ["Gener", "Febrer", "Març", "Abril", "Maig", "Juny", "Juliol", "Agost", "Setembre", "Octubre", "Novembre", "Desembre"],
monthsShort: ["Gen", "Feb", "Mar", "Abr", "Mai", "Jun", "Jul", "Ago", "Set", "Oct", "Nov", "Des"],
today: "Avui"
}
}(jQuery),
function(e) {
e.fn.datepicker.dates.cs = {
days: ["Neděle", "Pondělí", "Úterý", "Středa", "Čtvrtek", "Pátek", "Sobota", "Neděle"],
daysShort: ["Ned", "Pon", "Úte", "Stř", "Čtv", "Pát", "Sob", "Ned"],
daysMin: ["Ne", "Po", "Út", "St", "Čt", "Pá", "So", "Ne"],
months: ["Leden", "Únor", "Březen", "Duben", "Květen", "Červen", "Červenec", "Srpen", "Září", "Říjen", "Listopad", "Prosinec"],
monthsShort: ["Led", "Úno", "Bře", "Dub", "Kvě", "Čer", "Čnc", "Srp", "Zář", "Říj", "Lis", "Pro"],
today: "Dnes"
}
}(jQuery),
function(e) {
e.fn.datepicker.dates.da = {
days: ["Søndag", "Mandag", "Tirsdag", "Onsdag", "Torsdag", "Fredag", "Lørdag", "Søndag"],
daysShort: ["Søn", "Man", "Tir", "Ons", "Tor", "Fre", "Lør", "Søn"],
daysMin: ["Sø", "Ma", "Ti", "On", "To", "Fr", "Lø", "Sø"],
months: ["Januar", "Februar", "Marts", "April", "Maj", "Juni", "Juli", "August", "September", "Oktober", "November", "December"],
monthsShort: ["Jan", "Feb", "Mar", "Apr", "Maj", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dec"],
today: "I Dag"
}
}(jQuery),
function(e) {
e.fn.datepicker.dates.de = {
days: ["Sonntag", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag", "Sonntag"],
daysShort: ["Son", "Mon", "Die", "Mit", "Don", "Fre", "Sam", "Son"],
daysMin: ["So", "Mo", "Di", "Mi", "Do", "Fr", "Sa", "So"],
months: ["Januar", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"],
monthsShort: ["Jan", "Feb", "Mär", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dez"],
today: "Heute",
weekStart: 1,
format: "dd.mm.yyyy"
}
}(jQuery),
function(e) {
e.fn.datepicker.dates.el = {
days: ["Κυριακή", "Δευτέρα", "Τρίτη", "Τετάρτη", "Πέμπτη", "Παρασκευή", "Σάββατο", "Κυριακή"],
daysShort: ["Κυρ", "Δευ", "Τρι", "Τετ", "Πεμ", "Παρ", "Σαβ", "Κυρ"],
daysMin: ["Κυ", "Δε", "Τρ", "Τε", "Πε", "Πα", "Σα", "Κυ"],
months: ["Ιανουάριος", "Φεβρουάριος", "Μάρτιος", "Απρίλιος", "Μάιος", "Ιούνιος", "Ιούλιος", "Αύγουστος", "Σεπτέμβριος", "Οκτώβριος", "Νοέμβριος", "Δεκέμβριος"],
monthsShort: ["Ιαν", "Φεβ", "Μαρ", "Απρ", "Μάι", "Ιουν", "Ιουλ", "Αυγ", "Σεπ", "Οκτ", "Νοε", "Δεκ"],
today: "Σήμερα"
}
}(jQuery),
function(e) {
e.fn.datepicker.dates.es = {
days: ["Domingo", "Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado", "Domingo"],
daysShort: ["Dom", "Lun", "Mar", "Mié", "Jue", "Vie", "Sáb", "Dom"],
daysMin: ["Do", "Lu", "Ma", "Mi", "Ju", "Vi", "Sa", "Do"],
months: ["Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"],
monthsShort: ["Ene", "Feb", "Mar", "Abr", "May", "Jun", "Jul", "Ago", "Sep", "Oct", "Nov", "Dic"],
today: "Hoy"
}
}(jQuery),
function(e) {
e.fn.datepicker.dates.fi = {
days: ["sunnuntai", "maanantai", "tiistai", "keskiviikko", "torstai", "perjantai", "lauantai", "sunnuntai"],
daysShort: ["sun", "maa", "tii", "kes", "tor", "per", "lau", "sun"],
daysMin: ["su", "ma", "ti", "ke", "to", "pe", "la", "su"],
months: ["tammikuu", "helmikuu", "maaliskuu", "huhtikuu", "toukokuu", "kesäkuu", "heinäkuu", "elokuu", "syyskuu", "lokakuu", "marraskuu", "joulukuu"],
monthsShort: ["tam", "hel", "maa", "huh", "tou", "kes", "hei", "elo", "syy", "lok", "mar", "jou"],
today: "tänään"
}
}(jQuery),
function(e) {
e.fn.datepicker.dates.fr = {
days: ["Dimanche", "Lundi", "Mardi", "Mercredi", "Jeudi", "Vendredi", "Samedi", "Dimanche"],
daysShort: ["Dim", "Lun", "Mar", "Mer", "Jeu", "Ven", "Sam", "Dim"],
daysMin: ["D", "L", "Ma", "Me", "J", "V", "S", "D"],
months: ["Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre"],
monthsShort: ["Jan", "Fev", "Mar", "Avr", "Mai", "Jui", "Jul", "Aou", "Sep", "Oct", "Nov", "Dec"],
today: "Aujourd'hui",
weekStart: 1,
format: "dd/mm/yyyy"
}
}(jQuery),
function(e) {
e.fn.datepicker.dates.he = {
days: ["ראשון", "שני", "שלישי", "רביעי", "חמישי", "שישי", "שבת", "ראשון"],
daysShort: ["א", "ב", "ג", "ד", "ה", "ו", "ש", "א"],
daysMin: ["א", "ב", "ג", "ד", "ה", "ו", "ש", "א"],
months: ["ינואר", "פברואר", "מרץ", "אפריל", "מאי", "יוני", "יולי", "אוגוסט", "ספטמבר", "אוקטובר", "נובמבר", "דצמבר"],
monthsShort: ["ינו", "פבר", "מרץ", "אפר", "מאי", "יונ", "יול", "אוג", "ספט", "אוק", "נוב", "דצמ"],
today: "היום",
rtl: !0
}
}(jQuery),
function(e) {
e.fn.datepicker.dates.hr = {
days: ["Nedjelja", "Ponedjelja", "Utorak", "Srijeda", "Četrtak", "Petak", "Subota", "Nedjelja"],
daysShort: ["Ned", "Pon", "Uto", "Srr", "Čet", "Pet", "Sub", "Ned"],
daysMin: ["Ne", "Po", "Ut", "Sr", "Če", "Pe", "Su", "Ne"],
months: ["Siječanj", "Veljača", "Ožujak", "Travanj", "Svibanj", "Lipanj", "Srpanj", "Kolovoz", "Rujan", "Listopad", "Studeni", "Prosinac"],
monthsShort: ["Sije", "Velj", "Ožu", "Tra", "Svi", "Lip", "Jul", "Kol", "Ruj", "Lis", "Stu", "Pro"],
today: "Danas"
}
}(jQuery),
function(e) {
e.fn.datepicker.dates.id = {
days: ["Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu", "Minggu"],
daysShort: ["Mgu", "Sen", "Sel", "Rab", "Kam", "Jum", "Sab", "Mgu"],
daysMin: ["Mg", "Sn", "Sl", "Ra", "Ka", "Ju", "Sa", "Mg"],
months: ["Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"],
monthsShort: ["Jan", "Feb", "Mar", "Apr", "Mei", "Jun", "Jul", "Ags", "Sep", "Okt", "Nov", "Des"]
}
}(jQuery),
function(e) {
e.fn.datepicker.dates.is = {
days: ["Sunnudagur", "Mánudagur", "Þriðjudagur", "Miðvikudagur", "Fimmtudagur", "Föstudagur", "Laugardagur", "Sunnudagur"],
daysShort: ["Sun", "Mán", "Þri", "Mið", "Fim", "Fös", "Lau", "Sun"],
daysMin: ["Su", "Má", "Þr", "Mi", "Fi", "Fö", "La", "Su"],
months: ["Janúar", "Febrúar", "Mars", "Apríl", "Maí", "Júní", "Júlí", "Ágúst", "September", "Október", "Nóvember", "Desember"],
monthsShort: ["Jan", "Feb", "Mar", "Apr", "Maí", "Jún", "Júl", "Ágú", "Sep", "Okt", "Nóv", "Des"],
today: "Í Dag"
}
}(jQuery),
function(e) {
e.fn.datepicker.dates.it = {
days: ["Domenica", "Lunedì", "Martedì", "Mercoledì", "Giovedì", "Venerdì", "Sabato", "Domenica"],
daysShort: ["Dom", "Lun", "Mar", "Mer", "Gio", "Ven", "Sab", "Dom"],
daysMin: ["Do", "Lu", "Ma", "Me", "Gi", "Ve", "Sa", "Do"],
months: ["Gennaio", "Febbraio", "Marzo", "Aprile", "Maggio", "Giugno", "Luglio", "Agosto", "Settembre", "Ottobre", "Novembre", "Dicembre"],
monthsShort: ["Gen", "Feb", "Mar", "Apr", "Mag", "Giu", "Lug", "Ago", "Set", "Ott", "Nov", "Dic"],
today: "Oggi",
weekStart: 1,
format: "dd/mm/yyyy"
}
}(jQuery),
function(e) {
e.fn.datepicker.dates.ja = {
days: ["日曜", "月曜", "火曜", "水曜", "木曜", "金曜", "土曜", "日曜"],
daysShort: ["日", "月", "火", "水", "木", "金", "土", "日"],
daysMin: ["日", "月", "火", "水", "木", "金", "土", "日"],
months: ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"],
monthsShort: ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"]
}
}(jQuery),
function(e) {
e.fn.datepicker.dates.kr = {
days: ["일요일", "월요일", "화요일", "수요일", "목요일", "금요일", "토요일", "일요일"],
daysShort: ["일", "월", "화", "수", "목", "금", "토", "일"],
daysMin: ["일", "월", "화", "수", "목", "금", "토", "일"],
months: ["1월", "2월", "3월", "4월", "5월", "6월", "7월", "8월", "9월", "10월", "11월", "12월"],
monthsShort: ["1월", "2월", "3월", "4월", "5월", "6월", "7월", "8월", "9월", "10월", "11월", "12월"]
}
}(jQuery),
function(e) {
e.fn.datepicker.dates.lt = {
days: ["Sekmadienis", "Pirmadienis", "Antradienis", "Trečiadienis", "Ketvirtadienis", "Penktadienis", "Šeštadienis", "Sekmadienis"],
daysShort: ["S", "Pr", "A", "T", "K", "Pn", "Š", "S"],
daysMin: ["Sk", "Pr", "An", "Tr", "Ke", "Pn", "Št", "Sk"],
months: ["Sausis", "Vasaris", "Kovas", "Balandis", "Gegužė", "Birželis", "Liepa", "Rugpjūtis", "Rugsėjis", "Spalis", "Lapkritis", "Gruodis"],
monthsShort: ["Sau", "Vas", "Kov", "Bal", "Geg", "Bir", "Lie", "Rugp", "Rugs", "Spa", "Lap", "Gru"],
today: "Šiandien",
weekStart: 1
}
}(jQuery),
function(e) {
e.fn.datepicker.dates.lv = {
days: ["Svētdiena", "Pirmdiena", "Otrdiena", "Trešdiena", "Ceturtdiena", "Piektdiena", "Sestdiena", "Svētdiena"],
daysShort: ["Sv", "P", "O", "T", "C", "Pk", "S", "Sv"],
daysMin: ["Sv", "Pr", "Ot", "Tr", "Ce", "Pk", "St", "Sv"],
months: ["Janvāris", "Februāris", "Marts", "Aprīlis", "Maijs", "Jūnijs", "Jūlijs", "Augusts", "Septembris", "Oktobris", "Novembris", "Decembris"],
monthsShort: ["Jan", "Feb", "Mar", "Apr", "Mai", "Jūn", "Jūl", "Aug", "Sep", "Okt", "Nov", "Dec."],
today: "Šodien",
weekStart: 1
}
}(jQuery),
function(e) {
e.fn.datepicker.dates.ms = {
days: ["Ahad", "Isnin", "Selasa", "Rabu", "Khamis", "Jumaat", "Sabtu", "Ahad"],
daysShort: ["Aha", "Isn", "Sel", "Rab", "Kha", "Jum", "Sab", "Aha"],
daysMin: ["Ah", "Is", "Se", "Ra", "Kh", "Ju", "Sa", "Ah"],
months: ["Januari", "Februari", "Mac", "April", "Mei", "Jun", "Julai", "Ogos", "September", "Oktober", "November", "Disember"],
monthsShort: ["Jan", "Feb", "Mar", "Apr", "Mei", "Jun", "Jul", "Ogo", "Sep", "Okt", "Nov", "Dis"],
today: "Hari Ini"
}
}(jQuery),
function(e) {
e.fn.datepicker.dates.nb = {
days: ["Søndag", "Mandag", "Tirsdag", "Onsdag", "Torsdag", "Fredag", "Lørdag", "Søndag"],
daysShort: ["Søn", "Man", "Tir", "Ons", "Tor", "Fre", "Lør", "Søn"],
daysMin: ["Sø", "Ma", "Ti", "On", "To", "Fr", "Lø", "Sø"],
months: ["Januar", "Februar", "Mars", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Desember"],
monthsShort: ["Jan", "Feb", "Mar", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Des"],
today: "I Dag"
}
}(jQuery),
function(e) {
e.fn.datepicker.dates.nl = {
days: ["Zondag", "Maandag", "Dinsdag", "Woensdag", "Donderdag", "Vrijdag", "Zaterdag", "Zondag"],
daysShort: ["Zo", "Ma", "Di", "Wo", "Do", "Vr", "Za", "Zo"],
daysMin: ["Zo", "Ma", "Di", "Wo", "Do", "Vr", "Za", "Zo"],
months: ["Januari", "Februari", "Maart", "April", "Mei", "Juni", "Juli", "Augustus", "September", "Oktober", "November", "December"],
monthsShort: ["Jan", "Feb", "Mrt", "Apr", "Mei", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dec"],
today: "Vandaag"
}
}(jQuery),
function(e) {
e.fn.datepicker.dates.pl = {
days: ["Niedziela", "Poniedziałek", "Wtorek", "Środa", "Czwartek", "Piątek", "Sobota", "Niedziela"],
daysShort: ["Nie", "Pn", "Wt", "Śr", "Czw", "Pt", "So", "Nie"],
daysMin: ["N", "Pn", "Wt", "Śr", "Cz", "Pt", "So", "N"],
months: ["Styczeń", "Luty", "Marzec", "Kwiecień", "Maj", "Czerwiec", "Lipiec", "Sierpień", "Wrzesień", "Październik", "Listopad", "Grudzień"],
monthsShort: ["Sty", "Lu", "Mar", "Kw", "Maj", "Cze", "Lip", "Sie", "Wrz", "Pa", "Lis", "Gru"],
today: "Dzisiaj",
weekStart: 1
}
}(jQuery),
function(e) {
e.fn.datepicker.dates["pt-BR"] = {
days: ["Domingo", "Segunda", "Terça", "Quarta", "Quinta", "Sexta", "Sábado", "Domingo"],
daysShort: ["Dom", "Seg", "Ter", "Qua", "Qui", "Sex", "Sáb", "Dom"],
daysMin: ["Do", "Se", "Te", "Qu", "Qu", "Se", "Sa", "Do"],
months: ["Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"],
monthsShort: ["Jan", "Fev", "Mar", "Abr", "Mai", "Jun", "Jul", "Ago", "Set", "Out", "Nov", "Dez"],
today: "Hoje"
}
}(jQuery),
function(e) {
e.fn.datepicker.dates.pt = {
days: ["Domingo", "Segunda", "Terça", "Quarta", "Quinta", "Sexta", "Sábado", "Domingo"],
daysShort: ["Dom", "Seg", "Ter", "Qua", "Qui", "Sex", "Sáb", "Dom"],
daysMin: ["Do", "Se", "Te", "Qu", "Qu", "Se", "Sa", "Do"],
months: ["Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"],
monthsShort: ["Jan", "Fev", "Mar", "Abr", "Mai", "Jun", "Jul", "Ago", "Set", "Out", "Nov", "Dez"]
}
}(jQuery),
function(e) {
e.fn.datepicker.dates.ro = {
days: ["Duminică", "Luni", "Marţi", "Miercuri", "Joi", "Vineri", "Sâmbătă", "Duminică"],
daysShort: ["Dum", "Lun", "Mar", "Mie", "Joi", "Vin", "Sâm", "Dum"],
daysMin: ["Du", "Lu", "Ma", "Mi", "Jo", "Vi", "Sâ", "Du"],
months: ["Ianuarie", "Februarie", "Martie", "Aprilie", "Mai", "Iunie", "Iulie", "August", "Septembrie", "Octombrie", "Noiembrie", "Decembrie"],
monthsShort: ["Ian", "Feb", "Mar", "Apr", "Mai", "Iun", "Iul", "Aug", "Sep", "Oct", "Nov", "Dec"],
today: "Astăzi",
weekStart: 1
}
}(jQuery),
function(e) {
e.fn.datepicker.dates.rs = {
days: ["Nedelja", "Ponedeljak", "Utorak", "Sreda", "Četvrtak", "Petak", "Subota", "Nedelja"],
daysShort: ["Ned", "Pon", "Uto", "Sre", "Čet", "Pet", "Sub", "Ned"],
daysMin: ["N", "Po", "U", "Sr", "Č", "Pe", "Su", "N"],
months: ["Januar", "Februar", "Mart", "April", "Maj", "Jun", "Jul", "Avgust", "Septembar", "Oktobar", "Novembar", "Decembar"],
monthsShort: ["Jan", "Feb", "Mar", "Apr", "Maj", "Jun", "Jul", "Avg", "Sep", "Okt", "Nov", "Dec"],
today: "Danas"
}
}(jQuery),
function(e) {
e.fn.datepicker.dates.rs = {
days: ["Недеља", "Понедељак", "Уторак", "Среда", "Четвртак", "Петак", "Субота", "Недеља"],
daysShort: ["Нед", "Пон", "Уто", "Сре", "Чет", "Пет", "Суб", "Нед"],
daysMin: ["Н", "По", "У", "Ср", "Ч", "Пе", "Су", "Н"],
months: ["Јануар", "Фебруар", "Март", "Април", "Мај", "Јун", "Јул", "Август", "Септембар", "Октобар", "Новембар", "Децембар"],
monthsShort: ["Јан", "Феб", "Мар", "Апр", "Мај", "Јун", "Јул", "Авг", "Сеп", "Окт", "Нов", "Дец"],
today: "Данас"
}
}(jQuery),
function(e) {
e.fn.datepicker.dates.ru = {
days: ["Воскресенье", "Понедельник", "Вторник", "Среда", "Четверг", "Пятница", "Суббота", "Воскресенье"],
daysShort: ["Вск", "Пнд", "Втр", "Срд", "Чтв", "Птн", "Суб", "Вск"],
daysMin: ["Вс", "Пн", "Вт", "Ср", "Чт", "Пт", "Сб", "Вс"],
months: ["Январь", "Февраль", "Март", "Апрель", "Май", "Июнь", "Июль", "Август", "Сентябрь", "Октябрь", "Ноябрь", "Декабрь"],
monthsShort: ["Янв", "Фев", "Мар", "Апр", "Май", "Июн", "Июл", "Авг", "Сен", "Окт", "Ноя", "Дек"],
today: "Сегодня"
}
}(jQuery),
function(e) {
e.fn.datepicker.dates.sk = {
days: ["Nedeľa", "Pondelok", "Utorok", "Streda", "Štvrtok", "Piatok", "Sobota", "Nedeľa"],
daysShort: ["Ned", "Pon", "Uto", "Str", "Štv", "Pia", "Sob", "Ned"],
daysMin: ["Ne", "Po", "Ut", "St", "Št", "Pia", "So", "Ne"],
months: ["Január", "Február", "Marec", "Apríl", "Máj", "Jún", "Júl", "August", "September", "Október", "November", "December"],
monthsShort: ["Jan", "Feb", "Mar", "Apr", "Máj", "Jún", "Júl", "Aug", "Sep", "Okt", "Nov", "Dec"],
today: "Dnes"
}
}(jQuery),
function(e) {
e.fn.datepicker.dates.sl = {
days: ["Nedelja", "Ponedeljek", "Torek", "Sreda", "Četrtek", "Petek", "Sobota", "Nedelja"],
daysShort: ["Ned", "Pon", "Tor", "Sre", "Čet", "Pet", "Sob", "Ned"],
daysMin: ["Ne", "Po", "To", "Sr", "Če", "Pe", "So", "Ne"],
months: ["Januar", "Februar", "Marec", "April", "Maj", "Junij", "Julij", "Avgust", "September", "Oktober", "November", "December"],
monthsShort: ["Jan", "Feb", "Mar", "Apr", "Maj", "Jun", "Jul", "Avg", "Sep", "Okt", "Nov", "Dec"],
today: "Danes"
}
}(jQuery),
function(e) {
e.fn.datepicker.dates.sv = {
days: ["Söndag", "Måndag", "Tisdag", "Onsdag", "Torsdag", "Fredag", "Lördag", "Söndag"],
daysShort: ["Sön", "Mån", "Tis", "Ons", "Tor", "Fre", "Lör", "Sön"],
daysMin: ["Sö", "Må", "Ti", "On", "To", "Fr", "Lö", "Sö"],
months: ["Januari", "Februari", "Mars", "April", "Maj", "Juni", "Juli", "Augusti", "September", "Oktober", "November", "December"],
monthsShort: ["Jan", "Feb", "Mar", "Apr", "Maj", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dec"],
today: "I Dag"
}
}(jQuery),
function(e) {
e.fn.datepicker.dates.sw = {
days: ["Jumapili", "Jumatatu", "Jumanne", "Jumatano", "Alhamisi", "Ijumaa", "Jumamosi", "Jumapili"],
daysShort: ["J2", "J3", "J4", "J5", "Alh", "Ij", "J1", "J2"],
daysMin: ["2", "3", "4", "5", "A", "I", "1", "2"],
months: ["Januari", "Februari", "Machi", "Aprili", "Mei", "Juni", "Julai", "Agosti", "Septemba", "Oktoba", "Novemba", "Desemba"],
monthsShort: ["Jan", "Feb", "Mac", "Apr", "Mei", "Jun", "Jul", "Ago", "Sep", "Okt", "Nov", "Des"],
today: "Leo"
}
}(jQuery),
function(e) {
e.fn.datepicker.dates.th = {
days: ["อาทิตย์", "จันทร์", "อังคาร", "พุธ", "พฤหัส", "ศุกร์", "เสาร์", "อาทิตย์"],
daysShort: ["อา", "จ", "อ", "พ", "พฤ", "ศ", "ส", "อา"],
daysMin: ["อา", "จ", "อ", "พ", "พฤ", "ศ", "ส", "อา"],
months: ["มกราคม", "กุมภาพันธ์", "มีนาคม", "เมษายน", "พฤษภาคม", "มิถุนายน", "กรกฎาคม", "สิงหาคม", "กันยายน", "ตุลาคม", "พฤศจิกายน", "ธันวาคม"],
monthsShort: ["ม.ค.", "ก.พ.", "มี.ค.", "เม.ย.", "พ.ค.", "มิ.ย.", "ก.ค.", "ส.ค.", "ก.ย.", "ต.ค.", "พ.ย.", "ธ.ค."],
today: "วันนี้"
}
}(jQuery),
function(e) {
e.fn.datepicker.dates.tr = {
days: ["Pazar", "Pazartesi", "Salı", "Çarşamba", "Perşembe", "Cuma", "Cumartesi", "Pazar"],
daysShort: ["Pz", "Pzt", "Sal", "Çrş", "Prş", "Cu", "Cts", "Pz"],
daysMin: ["Pz", "Pzt", "Sa", "Çr", "Pr", "Cu", "Ct", "Pz"],
months: ["Ocak", "Şubat", "Mart", "Nisan", "Mayıs", "Haziran", "Temmuz", "Ağustos", "Eylül", "Ekim", "Kasım", "Aralık"],
monthsShort: ["Oca", "Şub", "Mar", "Nis", "May", "Haz", "Tem", "Ağu", "Eyl", "Eki", "Kas", "Ara"],
today: "Bugün"
}
}(jQuery),
function(e) {
e.fn.datepicker.dates.uk = {
days: ["Неділя", "Понеділок", "Вівторок", "Середа", "Четвер", "П'ятниця", "Субота", "Неділя"],
daysShort: ["Нед", "Пнд", "Втр", "Срд", "Чтв", "Птн", "Суб", "Нед"],
daysMin: ["Нд", "Пн", "Вт", "Ср", "Чт", "Пт", "Сб", "Нд"],
months: ["Січень", "Лютий", "Березень", "Квітень", "Травень", "Червень", "Липень", "Серпень", "Вересень", "Жовтень", "Листопад", "Грудень"],
monthsShort: ["Січ", "Лют", "Бер", "Кві", "Тра", "Чер", "Лип", "Сер", "Вер", "Жов", "Лис", "Гру"],
today: "Сьогодні"
}
}(jQuery),
function(e) {
e.fn.datepicker.dates["zh-CN"] = {
days: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"],
daysShort: ["周日", "周一", "周二", "周三", "周四", "周五", "周六", "周日"],
daysMin: ["日", "一", "二", "三", "四", "五", "六", "日"],
months: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
monthsShort: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
today: "今日"
}
}(jQuery),
function(e) {
e.fn.datepicker.dates["zh-TW"] = {
days: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"],
daysShort: ["周日", "周一", "周二", "周三", "周四", "周五", "周六", "周日"],
daysMin: ["日", "一", "二", "三", "四", "五", "六", "日"],
months: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
monthsShort: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"]
}
}(jQuery),
function() {
jQuery(function() {
return $("a[rel=popover]").popover(), $(".tooltip").tooltip(), $("a[rel=tooltip]").tooltip()
})
}.call(this), ! function(e) {
"use strict";
var t = function(t, n) {
this.$element = e(t), this.options = e.extend({}, e.fn.typeahead.defaults, n), this.matcher = this.options.matcher || this.matcher, this.sorter = this.options.sorter || this.sorter, this.highlighter = this.options.highlighter || this.highlighter, this.updater = this.options.updater || this.updater, this.$menu = e(this.options.menu).appendTo("body"), this.source = this.options.source, this.shown = !1, this.listen()
};
t.prototype = {
constructor: t,
select: function() {
var e = this.$menu.find(".active").attr("data-value");
return this.$element.val(this.updater(e)).change(), this.hide()
},
updater: function(e) {
return e
},
show: function() {
var t = e.extend({}, this.$element.offset(), {
height: this.$element[0].offsetHeight
});
return this.$menu.css({
top: t.top + t.height,
left: t.left
}), this.$menu.show(), this.shown = !0, this
},
hide: function() {
return this.$menu.hide(), this.shown = !1, this
},
lookup: function(t) {
var n;
return this.query = this.$element.val(), !this.query || this.query.length < this.options.minLength ? this.shown ? this.hide() : this : (n = e.isFunction(this.source) ? this.source(this.query, e.proxy(this.process, this)) : this.source, n ? this.process(n) : this)
},
process: function(t) {
var n = this;
return t = e.grep(t, function(e) {
return n.matcher(e)
}), t = this.sorter(t), t.length ? this.render(t.slice(0, this.options.items)).show() : this.shown ? this.hide() : this
},
matcher: function(e) {
return ~e.toLowerCase().indexOf(this.query.toLowerCase())
},
sorter: function(e) {
var t = [],
n = [],
r = [],
i;
while (i = e.shift()) i.toLowerCase().indexOf(this.query.toLowerCase()) ? ~i.indexOf(this.query) ? n.push(i) : r.push(i) : t.push(i);
return t.concat(n, r)
},
highlighter: function(e) {
var t = this.query.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&");
return e.replace(new RegExp("(" + t + ")", "ig"), function(e, t) {
return "<strong>" + t + "</strong>"
})
},
render: function(t) {
var n = this;
return t = e(t).map(function(t, r) {
return t = e(n.options.item).attr("data-value", r), t.find("a").html(n.highlighter(r)), t[0]
}), t.first().addClass("active"), this.$menu.html(t), this
},
next: function(t) {
var n = this.$menu.find(".active").removeClass("active"),
r = n.next();
r.length || (r = e(this.$menu.find("li")[0])), r.addClass("active")
},
prev: function(e) {
var t = this.$menu.find(".active").removeClass("active"),
n = t.prev();
n.length || (n = this.$menu.find("li").last()), n.addClass("active")
},
listen: function() {
this.$element.on("blur", e.proxy(this.blur, this)).on("keypress", e.proxy(this.keypress, this)).on("keyup", e.proxy(this.keyup, this)), (e.browser.chrome || e.browser.webkit || e.browser.msie) && this.$element.on("keydown", e.proxy(this.keydown, this)), this.$menu.on("click", e.proxy(this.click, this)).on("mouseenter", "li", e.proxy(this.mouseenter, this))
},
move: function(e) {
if (!this.shown) return;
switch (e.keyCode) {
case 9:
case 13:
case 27:
e.preventDefault();
break;
case 38:
e.preventDefault(), this.prev();
break;
case 40:
e.preventDefault(), this.next()
}
e.stopPropagation()
},
keydown: function(t) {
this.suppressKeyPressRepeat = !~e.inArray(t.keyCode, [40, 38, 9, 13, 27]), this.move(t)
},
keypress: function(e) {
if (this.suppressKeyPressRepeat) return;
this.move(e)
},
keyup: function(e) {
switch (e.keyCode) {
case 40:
case 38:
break;
case 9:
case 13:
if (!this.shown) return;
this.select();
break;
case 27:
if (!this.shown) return;
this.hide();
break;
default:
this.lookup()
}
e.stopPropagation(), e.preventDefault()
},
blur: function(e) {
var t = this;
setTimeout(function() {
t.hide()
}, 150)
},
click: function(e) {
e.stopPropagation(), e.preventDefault(), this.select()
},
mouseenter: function(t) {
this.$menu.find(".active").removeClass("active"), e(t.currentTarget).addClass("active")
}
}, e.fn.typeahead = function(n) {
return this.each(function() {
var r = e(this),
i = r.data("typeahead"),
s = typeof n == "object" && n;
i || r.data("typeahead", i = new t(this, s)), typeof n == "string" && i[n]()
})
}, e.fn.typeahead.defaults = {
source: [],
items: 8,
menu: '<ul class="typeahead dropdown-menu"></ul>',
item: '<li><a href="#"></a></li>',
minLength: 1
}, e.fn.typeahead.Constructor = t, e(function() {
e("body").on("focus.typeahead.data-api", '[data-provide="typeahead"]', function(t) {
var n = e(this);
if (n.data("typeahead")) return;
t.preventDefault(), n.typeahead(n.data())
})
})
}(window.jQuery),
function(e, t) {
function n(e) {
var t = [2, 3, 4, 5, 7, 8, 9],
n = [0, 0, 0, 0, 0, 0, 0],
r;
e = e.toUpperCase();
if (!e) return n;
if (typeof e != "string") throw new Error("Invalid iso8601 period string '" + e + "'");
if (r = /^P((\d+Y)?(\d+M)?(\d+W)?(\d+D)?)?(T(\d+H)?(\d+M)?(\d+S)?)?$/.exec(e)) {
for (var i = 0; i < t.length; i++) {
var s = t[i];
n[i] = r[s] ? +r[s].replace(/[A-Za-z]+/g, "") : 0
}
return n
}
throw new Error("String '" + e + "' is not a valid ISO8601 period.")
}
e.iso8601 || (e.iso8601 = {}), e.iso8601.Period || (e.iso8601.Period = {}), e.iso8601.version = "0.1", e.iso8601.Period.parse = function(e) {
return n(e)
}, e.iso8601.Period.parseToTotalSeconds = function(e) {
var t = [31104e3, 2592e3, 604800, 86400, 3600, 60, 1],
r = n(e),
i = 0;
for (var s = 0; s < r.length; s++) i += r[s] * t[s];
return i
}, e.iso8601.Period.isValid = function(e) {
try {
return n(e), !0
} catch (t) {
return !1
}
}, e.iso8601.Period.parseToString = function(e, t, r) {
var i = ["", "", "", "", "", "", ""],
s = n(e);
t || (t = ["year", "month", "week", "day", "hour", "minute", "second"]), r || (r = ["years", "months", "weeks", "days", "hours", "minutes", "seconds"]);
for (var o = 0; o < s.length; o++) s[o] > 0 && (s[o] == 1 ? i[o] = s[o] + " " + t[o] : i[o] = s[o] + " " + r[o]);
return i.join(" ").trim().replace(/[ ]{2,}/g, " ")
}
}(window.nezasa = window.nezasa || {}), RegExp.escape = function(e) {
return e.replace(/[-\/\\^$*+?.()|[\]{}]/g, "\\$&")
},
function(e) {
"use strict";
e.csv = {
defaults: {
separator: ",",
delimiter: '"',
headers: !0
},
hooks: {
castToScalar: function(e, t) {
var n = /\./;
if (isNaN(e)) return e;
if (n.test(e)) return parseFloat(e);
var r = parseInt(e);
return isNaN(r) ? null : r
}
},
parsers: {
parse: function(e, t) {
function f() {
o = 0, u = "";
if (t.start && t.state.rowNum < t.start) {
s = [], t.state.rowNum++, t.state.colNum = 1;
return
}
if (t.onParseEntry === undefined) i.push(s);
else {
var e = t.onParseEntry(s, t.state);
e !== !1 && i.push(e)
}
s = [], t.end && t.state.rowNum >= t.end && (a = !0), t.state.rowNum++, t.state.colNum = 1
}
function l() {
if (t.onParseValue === undefined) s.push(u);
else {
var e = t.onParseValue(u, t.state);
e !== !1 && s.push(e)
}
u = "", o = 0, t.state.colNum++
}
var n = t.separator,
r = t.delimiter;
t.state.rowNum || (t.state.rowNum = 1), t.state.colNum || (t.state.colNum = 1);
var i = [],
s = [],
o = 0,
u = "",
a = !1,
c = RegExp.escape(n),
h = RegExp.escape(r),
p = /(D|S|\n|\r|[^DS\r\n]+)/,
d = p.source;
return d = d.replace(/S/g, c), d = d.replace(/D/g, h), p = RegExp(d, "gm"), e.replace(p, function(e) {
if (a) return;
switch (o) {
case 0:
if (e === n) {
u += "", l();
break
}
if (e === r) {
o = 1;
break
}
if (e === "\n") {
l(), f();
break
}
if (/^\r$/.test(e)) break;
u += e, o = 3;
break;
case 1:
if (e === r) {
o = 2;
break
}
u += e, o = 1;
break;
case 2:
if (e === r) {
u += e, o = 1;
break
}
if (e === n) {
l();
break
}
if (e === "\n") {
l(), f();
break
}
if (/^\r$/.test(e)) break;
throw new Error("CSVDataError: Illegal State [Row:" + t.state.rowNum + "][Col:" + t.state.colNum + "]");
case 3:
if (e === n) {
l();
break
}
if (e === "\n") {
l(), f();
break
}
if (/^\r$/.test(e)) break;
if (e === r) throw new Error("CSVDataError: Illegal Quote [Row:" + t.state.rowNum + "][Col:" + t.state.colNum + "]");
throw new Error("CSVDataError: Illegal Data [Row:" + t.state.rowNum + "][Col:" + t.state.colNum + "]");
default:
throw new Error("CSVDataError: Unknown State [Row:" + t.state.rowNum + "][Col:" + t.state.colNum + "]")
}
}), s.length !== 0 && (l(), f()), i
},
splitLines: function(e, t) {
function a() {
s = 0;
if (t.start && t.state.rowNum < t.start) {
o = "", t.state.rowNum++;
return
}
if (t.onParseEntry === undefined) i.push(o);
else {
var e = t.onParseEntry(o, t.state);
e !== !1 && i.push(e)
}
o = "", t.end && t.state.rowNum >= t.end && (u = !0), t.state.rowNum++
}
var n = t.separator,
r = t.delimiter;
t.state.rowNum || (t.state.rowNum = 1);
var i = [],
s = 0,
o = "",
u = !1,
f = RegExp.escape(n),
l = RegExp.escape(r),
c = /(D|S|\n|\r|[^DS\r\n]+)/,
h = c.source;
return h = h.replace(/S/g, f), h = h.replace(/D/g, l), c = RegExp(h, "gm"), e.replace(c, function(e) {
if (u) return;
switch (s) {
case 0:
if (e === n) {
o += e, s = 0;
break
}
if (e === r) {
o += e, s = 1;
break
}
if (e === "\n") {
a();
break
}
if (/^\r$/.test(e)) break;
o += e, s = 3;
break;
case 1:
if (e === r) {
o += e, s = 2;
break
}
o += e, s = 1;
break;
case 2:
var i = o.substr(o.length - 1);
if (e === r && i === r) {
o += e, s = 1;
break
}
if (e === n) {
o += e, s = 0;
break
}
if (e === "\n") {
a();
break
}
if (e === "\r") break;
throw new Error("CSVDataError: Illegal state [Row:" + t.state.rowNum + "]");
case 3:
if (e === n) {
o += e, s = 0;
break
}
if (e === "\n") {
a();
break
}
if (e === "\r") break;
if (e === r) throw new Error("CSVDataError: Illegal quote [Row:" + t.state.rowNum + "]");
throw new Error("CSVDataError: Illegal state [Row:" + t.state.rowNum + "]");
default:
throw new Error("CSVDataError: Unknown state [Row:" + t.state.rowNum + "]")
}
}), o !== "" && a(), i
},
parseEntry: function(e, t) {
function u() {
if (t.onParseValue === undefined) i.push(o);
else {
var e = t.onParseValue(o, t.state);
e !== !1 && i.push(e)
}
o = "", s = 0, t.state.colNum++
}
var n = t.separator,
r = t.delimiter;
t.state.rowNum || (t.state.rowNum = 1), t.state.colNum || (t.state.colNum = 1);
var i = [],
s = 0,
o = "";
if (!t.match) {
var a = RegExp.escape(n),
f = RegExp.escape(r),
l = /(D|S|\n|\r|[^DS\r\n]+)/,
c = l.source;
c = c.replace(/S/g, a), c = c.replace(/D/g, f), t.match = RegExp(c, "gm")
}
return e.replace(t.match, function(e) {
switch (s) {
case 0:
if (e === n) {
o += "", u();
break
}
if (e === r) {
s = 1;
break
}
if (e === "\n" || e === "\r") break;
o += e, s = 3;
break;
case 1:
if (e === r) {
s = 2;
break
}
o += e, s = 1;
break;
case 2:
if (e === r) {
o += e, s = 1;
break
}
if (e === n) {
u();
break
}
if (e === "\n" || e === "\r") break;
throw new Error("CSVDataError: Illegal State [Row:" + t.state.rowNum + "][Col:" + t.state.colNum + "]");
case 3:
if (e === n) {
u();
break
}
if (e === "\n" || e === "\r") break;
if (e === r) throw new Error("CSVDataError: Illegal Quote [Row:" + t.state.rowNum + "][Col:" + t.state.colNum + "]");
throw new Error("CSVDataError: Illegal Data [Row:" + t.state.rowNum + "][Col:" + t.state.colNum + "]");
default:
throw new Error("CSVDataError: Unknown State [Row:" + t.state.rowNum + "][Col:" + t.state.colNum + "]")
}
}), u(), i
}
},
toArray: function(t, n, r) {
var n = n !== undefined ? n : {},
i = {};
i.callback = r !== undefined && typeof r == "function" ? r : !1, i.separator = "separator" in n ? n.separator : e.csv.defaults.separator, i.delimiter = "delimiter" in n ? n.delimiter : e.csv.defaults.delimiter;
var s = n.state !== undefined ? n.state : {},
n = {
delimiter: i.delimiter,
separator: i.separator,
onParseEntry: n.onParseEntry,
onParseValue: n.onParseValue,
state: s
},
o = e.csv.parsers.parseEntry(t, n);
if (!i.callback) return o;
i.callback("", o)
},
toArrays: function(t, n, r) {
var n = n !== undefined ? n : {},
i = {};
i.callback = r !== undefined && typeof r == "function" ? r : !1, i.separator = "separator" in n ? n.separator : e.csv.defaults.separator, i.delimiter = "delimiter" in n ? n.delimiter : e.csv.defaults.delimiter;
var s = [],
n = {
delimiter: i.delimiter,
separator: i.separator,
onParseEntry: n.onParseEntry,
onParseValue: n.onParseValue,
start: n.start,
end: n.end,
state: {
rowNum: 1,
colNum: 1
}
};
s = e.csv.parsers.parse(t, n);
if (!i.callback) return s;
i.callback("", s)
},
toObjects: function(t, n, r) {
var n = n !== undefined ? n : {},
i = {};
i.callback = r !== undefined && typeof r == "function" ? r : !1, i.separator = "separator" in n ? n.separator : e.csv.defaults.separator, i.delimiter = "delimiter" in n ? n.delimiter : e.csv.defaults.delimiter, i.headers = "headers" in n ? n.headers : e.csv.defaults.headers, n.start = "start" in n ? n.start : 1, i.headers && n.start++, n.end && i.headers && n.end++;
var s = [],
o = [],
n = {
delimiter: i.delimiter,
separator: i.separator,
onParseEntry: n.onParseEntry,
onParseValue: n.onParseValue,
start: n.start,
end: n.end,
state: {
rowNum: 1,
colNum: 1
},
match: !1
},
u = {
delimiter: i.delimiter,
separator: i.separator,
start: 1,
end: 1,
state: {
rowNum: 1,
colNum: 1
}
},
a = e.csv.parsers.splitLines(t, u),
f = e.csv.toArray(a[0], n),
s = e.csv.parsers.splitLines(t, n);
n.state.colNum = 1, f ? n.state.rowNum = 2 : n.state.rowNum = 1;
for (var l = 0, c = s.length; l < c; l++) {
var h = e.csv.toArray(s[l], n),
p = {};
for (var d in f) p[f[d]] = h[d];
o.push(p), n.state.rowNum++
}
if (!i.callback) return o;
i.callback("", o)
},
fromArrays: function(t, n, r) {
var n = n !== undefined ? n : {},
s = {};
s.callback = r !== undefined && typeof r == "function" ? r : !1, s.separator = "separator" in n ? n.separator : e.csv.defaults.separator, s.delimiter = "delimiter" in n ? n.delimiter : e.csv.defaults.delimiter, s.escaper = "escaper" in n ? n.escaper : e.csv.defaults.escaper, s.experimental = "experimental" in n ? n.experimental : !1;
if (!s.experimental) throw new Error("not implemented");
var o = [];
for (i in t) o.push(t[i]);
if (!s.callback) return o;
s.callback("", o)
},
fromObjects2CSV: function(t, n, r) {
var n = n !== undefined ? n : {},
s = {};
s.callback = r !== undefined && typeof r == "function" ? r : !1, s.separator = "separator" in n ? n.separator : e.csv.defaults.separator, s.delimiter = "delimiter" in n ? n.delimiter : e.csv.defaults.delimiter, s.experimental = "experimental" in n ? n.experimental : !1;
if (!s.experimental) throw new Error("not implemented");
var o = [];
for (i in t) o.push(arrays[i]);
if (!s.callback) return o;
s.callback("", o)
}
}, e.csvEntry2Array = e.csv.toArray, e.csv2Array = e.csv.toArrays, e.csv2Dictionary = e.csv.toObjects
}(jQuery),
function(e, t) {
e.ajaxPrefilter(function(e, t, n) {
if (e.iframe) return "iframe"
}), e.ajaxTransport("iframe", function(t, n, r) {
function h() {
e(f).each(function() {
this.remove()
}), e(l).each(function() {
this.disabled = !1
}), i.attr("action", o || "").attr("target", u || "").attr("enctype", a || ""), s.attr("src", "javascript:false;").remove()
}
var i = null,
s = null,
o = null,
u = null,
a = null,
f = [],
l = [],
c = e(t.files).filter(":file:enabled");
t.dataTypes.shift();
if (c.length) return c.each(function() {
i !== null && this.form !== i && jQuery.error("All file fields must belong to the same form"), i = this.form
}), i = e(i), o = i.attr("action"), u = i.attr("target"), a = i.attr("enctype"), i.find(":input:not(:submit)").each(function() {
!this.disabled && (this.type != "file" || c.index(this) < 0) && (this.disabled = !0, l.push(this))
}), typeof t.data == "string" && t.data.length > 0 && jQuery.error("data must not be serialized"), e.each(t.data || {}, function(t, n) {
e.isPlainObject(n) && (t = n.name, n = n.value), f.push(e("<input type='hidden'>").attr("name", t).attr("value", n).appendTo(i))
}), f.push(e("<input type='hidden' name='X-Requested-With'>").attr("value", "IFrame").appendTo(i)), accepts = t.dataTypes[0] && t.accepts[t.dataTypes[0]] ? t.accepts[t.dataTypes[0]] + (t.dataTypes[0] !== "*" ? ", */*; q=0.01" : "") : t.accepts["*"], f.push(e("<input type='hidden' name='X-Http-Accept'>").attr("value", accepts).appendTo(i)), {
send: function(n, r) {
s = e("<iframe src='javascript:false;' name='iframe-" + e.now() + "' style='display:none'></iframe>"), s.bind("load", function() {
s.unbind("load").bind("load", function() {
var e = this.contentWindow ? this.contentWindow.document : this.contentDocument ? this.contentDocument : this.document,
t = e.documentElement ? e.documentElement : e.body,
n = t.getElementsByTagName("textarea")[0],
i = n ? n.getAttribute("data-type") : null,
s = n ? parseInt(n.getAttribute("response-code")) : 200,
o = "OK",
u = {
text: i ? n.value : t ? t.innerHTML : null
},
a = "Content-Type: " + (i || "text/html");
r(s, o, u, a), setTimeout(h, 50)
}), i.attr("action", t.url).attr("target", s.attr("name")).attr("enctype", "multipart/form-data").get(0).submit()
}), s.insertAfter(i)
},
abort: function() {
s !== null && (s.unbind("load").attr("src", "javascript:false;"), h())
}
}
})
}(jQuery),
function($) {
var escapeable = /["\\\x00-\x1f\x7f-\x9f]/g,
meta = {
"\b": "\\b",
" ": "\\t",
"\n": "\\n",
"\f": "\\f",
"\r": "\\r",
'"': '\\"',
"\\": "\\\\"
};
$.toJSON = typeof JSON == "object" && JSON.stringify ? JSON.stringify : function(e) {
if (e === null) return "null";
var t = typeof e;
if (t === "undefined") return undefined;
if (t === "number" || t === "boolean") return "" + e;
if (t === "string") return $.quoteString(e);
if (t === "object") {
if (typeof e.toJSON == "function") return $.toJSON(e.toJSON());
if (e.constructor === Date) {
var n = e.getUTCMonth() + 1,
r = e.getUTCDate(),
i = e.getUTCFullYear(),
s = e.getUTCHours(),
o = e.getUTCMinutes(),
u = e.getUTCSeconds(),
a = e.getUTCMilliseconds();
return n < 10 && (n = "0" + n), r < 10 && (r = "0" + r), s < 10 && (s = "0" + s), o < 10 && (o = "0" + o), u < 10 && (u = "0" + u), a < 100 && (a = "0" + a), a < 10 && (a = "0" + a), '"' + i + "-" + n + "-" + r + "T" + s + ":" + o + ":" + u + "." + a + 'Z"'
}
if (e.constructor === Array) {
var f = [];
for (var l = 0; l < e.length; l++) f.push($.toJSON(e[l]) || "null");
return "[" + f.join(",") + "]"
}
var c, h, p = [];
for (var d in e) {
t = typeof d;
if (t === "number") c = '"' + d + '"';
else {
if (t !== "string") continue;
c = $.quoteString(d)
}
t = typeof e[d];
if (t === "function" || t === "undefined") continue;
h = $.toJSON(e[d]), p.push(c + ":" + h)
}
return "{" + p.join(",") + "}"
}
}, $.evalJSON = typeof JSON == "object" && JSON.parse ? JSON.parse : function(src) {
return eval("(" + src + ")")
}, $.secureEvalJSON = typeof JSON == "object" && JSON.parse ? JSON.parse : function(src) {
var filtered = src.replace(/\\["\\\/bfnrtu]/g, "@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, "]").replace(/(?:^|:|,)(?:\s*\[)+/g, "");
if (/^[\],:{}\s]*$/.test(filtered)) return eval("(" + src + ")");
throw new SyntaxError("Error parsing JSON, source is not valid.")
}, $.quoteString = function(e) {
return e.match(escapeable) ? '"' + e.replace(escapeable, function(e) {
var t = meta[e];
return typeof t == "string" ? t : (t = e.charCodeAt(), "\\u00" + Math.floor(t / 16).toString(16) + (t % 16).toString(16))
}) + '"' : '"' + e + '"'
}
}(jQuery),
function(e, t) {
e.ajaxPrefilter(function(e, t, n) {
if (e.iframe) return "iframe"
}), e.ajaxTransport("iframe", function(t, n, r) {
function h() {
e(f).each(function() {
this.remove()
}), e(l).each(function() {
this.disabled = !1
}), i.attr("action", o || "").attr("target", u || "").attr("enctype", a || ""), s.attr("src", "javascript:false;").remove()
}
var i = null,
s = null,
o = null,
u = null,
a = null,
f = [],
l = [],
c = e(t.files).filter(":file:enabled");
t.dataTypes.shift();
if (c.length) return c.each(function() {
i !== null && this.form !== i && jQuery.error("All file fields must belong to the same form"), i = this.form
}), i = e(i), o = i.attr("action"), u = i.attr("target"), a = i.attr("enctype"), i.find(":input:not(:submit)").each(function() {
!this.disabled && (this.type != "file" || c.index(this) < 0) && (this.disabled = !0, l.push(this))
}), typeof t.data == "string" && t.data.length > 0 && jQuery.error("data must not be serialized"), e.each(t.data || {}, function(t, n) {
e.isPlainObject(n) && (t = n.name, n = n.value), f.push(e("<input type='hidden'>").attr("name", t).attr("value", n).appendTo(i))
}), f.push(e("<input type='hidden' name='X-Requested-With'>").attr("value", "IFrame").appendTo(i)), accepts = t.dataTypes[0] && t.accepts[t.dataTypes[0]] ? t.accepts[t.dataTypes[0]] + (t.dataTypes[0] !== "*" ? ", */*; q=0.01" : "") : t.accepts["*"], f.push(e("<input type='hidden' name='X-Http-Accept'>").attr("value", accepts).appendTo(i)), {
send: function(n, r) {
s = e("<iframe src='javascript:false;' name='iframe-" + e.now() + "' style='display:none'></iframe>"), s.bind("load", function() {
s.unbind("load").bind("load", function() {
var e = this.contentWindow ? this.contentWindow.document : this.contentDocument ? this.contentDocument : this.document,
t = e.documentElement ? e.documentElement : e.body,
n = t.getElementsByTagName("textarea")[0],
i = n ? n.getAttribute("data-type") : null,
s = n ? parseInt(n.getAttribute("response-code")) : 200,
o = "OK",
u = {
text: i ? n.value : t ? t.innerHTML : null
},
a = "Content-Type: " + (i || "text/html");
r(s, o, u, a), setTimeout(h, 50)
}), i.attr("action", t.url).attr("target", s.attr("name")).attr("enctype", "multipart/form-data").get(0).submit()
}), s.insertAfter(i)
},
abort: function() {
s !== null && (s.unbind("load").attr("src", "javascript:false;"), h())
}
}
})
}(jQuery),
function(t) {
var n;
t.remotipart = n = {
setup: function(e) {
e.one("ajax:beforeSend.remotipart", function(r, i, s) {
return delete s.beforeSend, s.iframe = !0, s.files = t(t.rails.fileInputSelector, e), s.data = e.serializeArray(), s.processData = !1, s.dataType === undefined && (s.dataType = "script *"), s.data.push({
name: "remotipart_submitted",
value: !0
}), t.rails.fire(e, "ajax:remotipartSubmit", [i, s]) && t.rails.ajax(s), n.teardown(e), !1
}).data("remotipartSubmitted", !0)
},
teardown: function(e) {
e.unbind("ajax:beforeSend.remotipart").removeData("remotipartSubmitted")
}
}, t("form").live("ajax:aborted:file", function() {
var r = t(this);
return n.setup(r), !t.support.submitBubbles && t().jquery < "1.7" && t.rails.callFormSubmitBindings(r) === !1 ? t.rails.stopEverything(e) : (t.rails.handleRemote(r), !1)
})
}(jQuery),
function() {
var e;
e = jQuery, e.fn.savefile = function(t) {
var n, r, i, s;
return s = e.extend({
filename: "file",
extension: "txt"
}, t), i = function(e, t) {
var n;
n = "http://savefile.joshmcarthur.com/" + encodeURIComponent(e);
if (t) return n += encodeURIComponent(t)
}, n = "" + s.filename + "." + s.extension, r = function(t) {
return e("<form></form>", {
action: i(n()),
method: "POST"
}).append(e("<input></input>", {
type: "hidden",
name: "content",
value: t
}))
}, this.each(function() {
var e;
return e = this.val() !== "" ? this.val() : this.text(), s.content != null && (e = s.content), r(e).submit()
})
}
}.call(this),
function(e, t) {
var n = 5;
e.widget("ui.slider", e.ui.mouse, {
widgetEventPrefix: "slide",
options: {
animate: !1,
distance: 0,
max: 100,
min: 0,
orientation: "horizontal",
range: !1,
step: 1,
value: 0,
values: null
},
_create: function() {
var t = this,
r = this.options,
i = this.element.find(".ui-slider-handle").addClass("ui-state-default ui-corner-all"),
s = "<a class='ui-slider-handle ui-state-default ui-corner-all' href='#'></a>",
o = r.values && r.values.length || 1,
u = [];
this._keySliding = !1, this._mouseSliding = !1, this._animateOff = !0, this._handleIndex = null, this._detectOrientation(), this._mouseInit(), this.element.addClass("ui-slider ui-slider-" + this.orientation + " ui-widget" + " ui-widget-content" + " ui-corner-all" + (r.disabled ? " ui-slider-disabled ui-disabled" : "")), this.range = e([]), r.range && (r.range === !0 && (r.values || (r.values = [this._valueMin(), this._valueMin()]), r.values.length && r.values.length !== 2 && (r.values = [r.values[0], r.values[0]])), this.range = e("<div></div>").appendTo(this.element).addClass("ui-slider-range ui-widget-header" + (r.range === "min" || r.range === "max" ? " ui-slider-range-" + r.range : "")));
for (var a = i.length; a < o; a += 1) u.push(s);
this.handles = i.add(e(u.join("")).appendTo(t.element)), this.handle = this.handles.eq(0), this.handles.add(this.range).filter("a").click(function(e) {
e.preventDefault()
}).hover(function() {
r.disabled || e(this).addClass("ui-state-hover")
}, function() {
e(this).removeClass("ui-state-hover")
}).focus(function() {
r.disabled ? e(this).blur() : (e(".ui-slider .ui-state-focus").removeClass("ui-state-focus"), e(this).addClass("ui-state-focus"))
}).blur(function() {
e(this).removeClass("ui-state-focus")
}), this.handles.each(function(t) {
e(this).data("index.ui-slider-handle", t)
}), this.handles.keydown(function(r) {
var i = e(this).data("index.ui-slider-handle"),
s, o, u, a;
if (t.options.disabled) return;
switch (r.keyCode) {
case e.ui.keyCode.HOME:
case e.ui.keyCode.END:
case e.ui.keyCode.PAGE_UP:
case e.ui.keyCode.PAGE_DOWN:
case e.ui.keyCode.UP:
case e.ui.keyCode.RIGHT:
case e.ui.keyCode.DOWN:
case e.ui.keyCode.LEFT:
r.preventDefault();
if (!t._keySliding) {
t._keySliding = !0, e(this).addClass("ui-state-active"), s = t._start(r, i);
if (s === !1) return
}
}
a = t.options.step, t.options.values && t.options.values.length ? o = u = t.values(i) : o = u = t.value();
switch (r.keyCode) {
case e.ui.keyCode.HOME:
u = t._valueMin();
break;
case e.ui.keyCode.END:
u = t._valueMax();
break;
case e.ui.keyCode.PAGE_UP:
u = t._trimAlignValue(o + (t._valueMax() - t._valueMin()) / n);
break;
case e.ui.keyCode.PAGE_DOWN:
u = t._trimAlignValue(o - (t._valueMax() - t._valueMin()) / n);
break;
case e.ui.keyCode.UP:
case e.ui.keyCode.RIGHT:
if (o === t._valueMax()) return;
u = t._trimAlignValue(o + a);
break;
case e.ui.keyCode.DOWN:
case e.ui.keyCode.LEFT:
if (o === t._valueMin()) return;
u = t._trimAlignValue(o - a)
}
t._slide(r, i, u)
}).keyup(function(n) {
var r = e(this).data("index.ui-slider-handle");
t._keySliding && (t._keySliding = !1, t._stop(n, r), t._change(n, r), e(this).removeClass("ui-state-active"))
}), this._refreshValue(), this._animateOff = !1
},
destroy: function() {
return this.handles.remove(), this.range.remove(), this.element.removeClass("ui-slider ui-slider-horizontal ui-slider-vertical ui-slider-disabled ui-widget ui-widget-content ui-corner-all").removeData("slider").unbind(".slider"), this._mouseDestroy(), this
},
_mouseCapture: function(t) {
var n = this.options,
r, i, s, o, u, a, f, l, c;
return n.disabled ? !1 : (this.elementSize = {
width: this.element.outerWidth(),
height: this.element.outerHeight()
}, this.elementOffset = this.element.offset(), r = {
x: t.pageX,
y: t.pageY
}, i = this._normValueFromMouse(r), s = this._valueMax() - this._valueMin() + 1, u = this, this.handles.each(function(t) {
var n = Math.abs(i - u.values(t));
s > n && (s = n, o = e(this), a = t)
}), n.range === !0 && this.values(1) === n.min && (a += 1, o = e(this.handles[a])), f = this._start(t, a), f === !1 ? !1 : (this._mouseSliding = !0, u._handleIndex = a, o.addClass("ui-state-active").focus(), l = o.offset(), c = !e(t.target).parents().andSelf().is(".ui-slider-handle"), this._clickOffset = c ? {
left: 0,
top: 0
} : {
left: t.pageX - l.left - o.width() / 2,
top: t.pageY - l.top - o.height() / 2 - (parseInt(o.css("borderTopWidth"), 10) || 0) - (parseInt(o.css("borderBottomWidth"), 10) || 0) + (parseInt(o.css("marginTop"), 10) || 0)
}, this.handles.hasClass("ui-state-hover") || this._slide(t, a, i), this._animateOff = !0, !0))
},
_mouseStart: function(e) {
return !0
},
_mouseDrag: function(e) {
var t = {
x: e.pageX,
y: e.pageY
},
n = this._normValueFromMouse(t);
return this._slide(e, this._handleIndex, n), !1
},
_mouseStop: function(e) {
return this.handles.removeClass("ui-state-active"), this._mouseSliding = !1, this._stop(e, this._handleIndex), this._change(e, this._handleIndex), this._handleIndex = null, this._clickOffset = null, this._animateOff = !1, !1
},
_detectOrientation: function() {
this.orientation = this.options.orientation === "vertical" ? "vertical" : "horizontal"
},
_normValueFromMouse: function(e) {
var t, n, r, i, s;
return this.orientation === "horizontal" ? (t = this.elementSize.width, n = e.x - this.elementOffset.left - (this._clickOffset ? this._clickOffset.left : 0)) : (t = this.elementSize.height, n = e.y - this.elementOffset.top - (this._clickOffset ? this._clickOffset.top : 0)), r = n / t, r > 1 && (r = 1), r < 0 && (r = 0), this.orientation === "vertical" && (r = 1 - r), i = this._valueMax() - this._valueMin(), s = this._valueMin() + r * i, this._trimAlignValue(s)
},
_start: function(e, t) {
var n = {
handle: this.handles[t],
value: this.value()
};
return this.options.values && this.options.values.length && (n.value = this.values(t), n.values = this.values()), this._trigger("start", e, n)
},
_slide: function(e, t, n) {
var r, i, s;
this.options.values && this.options.values.length ? (r = this.values(t ? 0 : 1), this.options.values.length === 2 && this.options.range === !0 && (t === 0 && n > r || t === 1 && n < r) && (n = r), n !== this.values(t) && (i = this.values(), i[t] = n, s = this._trigger("slide", e, {
handle: this.handles[t],
value: n,
values: i
}), r = this.values(t ? 0 : 1), s !== !1 && this.values(t, n, !0))) : n !== this.value() && (s = this._trigger("slide", e, {
handle: this.handles[t],
value: n
}), s !== !1 && this.value(n))
},
_stop: function(e, t) {
var n = {
handle: this.handles[t],
value: this.value()
};
this.options.values && this.options.values.length && (n.value = this.values(t), n.values = this.values()), this._trigger("stop", e, n)
},
_change: function(e, t) {
if (!this._keySliding && !this._mouseSliding) {
var n = {
handle: this.handles[t],
value: this.value()
};
this.options.values && this.options.values.length && (n.value = this.values(t), n.values = this.values()), this._trigger("change", e, n)
}
},
value: function(e) {
if (arguments.length) {
this.options.value = this._trimAlignValue(e), this._refreshValue(), this._change(null, 0);
return
}
return this._value()
},
values: function(t, n) {
var r, i, s;
if (arguments.length > 1) {
this.options.values[t] = this._trimAlignValue(n), this._refreshValue(), this._change(null, t);
return
}
if (!arguments.length) return this._values();
if (!e.isArray(arguments[0])) return this.options.values && this.options.values.length ? this._values(t) : this.value();
r = this.options.values, i = arguments[0];
for (s = 0; s < r.length; s += 1) r[s] = this._trimAlignValue(i[s]), this._change(null, s);
this._refreshValue()
},
_setOption: function(t, n) {
var r, i = 0;
e.isArray(this.options.values) && (i = this.options.values.length), e.Widget.prototype._setOption.apply(this, arguments);
switch (t) {
case "disabled":
n ? (this.handles.filter(".ui-state-focus").blur(), this.handles.removeClass("ui-state-hover"), this.handles.propAttr("disabled", !0), this.element.addClass("ui-disabled")) : (this.handles.propAttr("disabled", !1), this.element.removeClass("ui-disabled"));
break;
case "orientation":
this._detectOrientation(), this.element.removeClass("ui-slider-horizontal ui-slider-vertical").addClass("ui-slider-" + this.orientation), this._refreshValue();
break;
case "value":
this._animateOff = !0, this._refreshValue(), this._change(null, 0), this._animateOff = !1;
break;
case "values":
this._animateOff = !0, this._refreshValue();
for (r = 0; r < i; r += 1) this._change(null, r);
this._animateOff = !1
}
},
_value: function() {
var e = this.options.value;
return e = this._trimAlignValue(e), e
},
_values: function(e) {
var t, n, r;
if (arguments.length) return t = this.options.values[e], t = this._trimAlignValue(t), t;
n = this.options.values.slice();
for (r = 0; r < n.length; r += 1) n[r] = this._trimAlignValue(n[r]);
return n
},
_trimAlignValue: function(e) {
if (e <= this._valueMin()) return this._valueMin();
if (e >= this._valueMax()) return this._valueMax();
var t = this.options.step > 0 ? this.options.step : 1,
n = (e - this._valueMin()) % t,
r = e - n;
return Math.abs(n) * 2 >= t && (r += n > 0 ? t : -t), parseFloat(r.toFixed(5))
},
_valueMin: function() {
return this.options.min
},
_valueMax: function() {
return this.options.max
},
_refreshValue: function() {
var t = this.options.range,
n = this.options,
r = this,
i = this._animateOff ? !1 : n.animate,
s, o = {},
u, a, f, l;
this.options.values && this.options.values.length ? this.handles.each(function(t, a) {
s = (r.values(t) - r._valueMin()) / (r._valueMax() - r._valueMin()) * 100, o[r.orientation === "horizontal" ? "left" : "bottom"] = s + "%", e(this).stop(1, 1)[i ? "animate" : "css"](o, n.animate), r.options.range === !0 && (r.orientation === "horizontal" ? (t === 0 && r.range.stop(1, 1)[i ? "animate" : "css"]({
left: s + "%"
}, n.animate), t === 1 && r.range[i ? "animate" : "css"]({
width: s - u + "%"
}, {
queue: !1,
duration: n.animate
})) : (t === 0 && r.range.stop(1, 1)[i ? "animate" : "css"]({
bottom: s + "%"
}, n.animate), t === 1 && r.range[i ? "animate" : "css"]({
height: s - u + "%"
}, {
queue: !1,
duration: n.animate
}))), u = s
}) : (a = this.value(), f = this._valueMin(), l = this._valueMax(), s = l !== f ? (a - f) / (l - f) * 100 : 0, o[r.orientation === "horizontal" ? "left" : "bottom"] = s + "%", this.handle.stop(1, 1)[i ? "animate" : "css"](o, n.animate), t === "min" && this.orientation === "horizontal" && this.range.stop(1, 1)[i ? "animate" : "css"]({
width: s + "%"
}, n.animate), t === "max" && this.orientation === "horizontal" && this.range[i ? "animate" : "css"]({
width: 100 - s + "%"
}, {
queue: !1,
duration: n.animate
}), t === "min" && this.orientation === "vertical" && this.range.stop(1, 1)[i ? "animate" : "css"]({
height: s + "%"
}, n.animate), t === "max" && this.orientation === "vertical" && this.range[i ? "animate" : "css"]({
height: 100 - s + "%"
}, {
queue: !1,
duration: n.animate
}))
}
}), e.extend(e.ui.slider, {
version: "1.8.22"
})
}(jQuery);
var JSON;
JSON || (JSON = {}),
function() {
"use strict";
function f(e) {
return e < 10 ? "0" + e : e
}
function quote(e) {
return escapable.lastIndex = 0, escapable.test(e) ? '"' + e.replace(escapable, function(e) {
var t = meta[e];
return typeof t == "string" ? t : "\\u" + ("0000" + e.charCodeAt(0).toString(16)).slice(-4)
}) + '"' : '"' + e + '"'
}
function str(e, t) {
var n, r, i, s, o = gap,
u, a = t[e];
a && typeof a == "object" && typeof a.toJSON == "function" && (a = a.toJSON(e)), typeof rep == "function" && (a = rep.call(t, e, a));
switch (typeof a) {
case "string":
return quote(a);
case "number":
return isFinite(a) ? String(a) : "null";
case "boolean":
case "null":
return String(a);
case "object":
if (!a) return "null";
gap += indent, u = [];
if (Object.prototype.toString.apply(a) === "[object Array]") {
s = a.length;
for (n = 0; n < s; n += 1) u[n] = str(n, a) || "null";
return i = u.length === 0 ? "[]" : gap ? "[\n" + gap + u.join(",\n" + gap) + "\n" + o + "]" : "[" + u.join(",") + "]", gap = o, i
}
if (rep && typeof rep == "object") {
s = rep.length;
for (n = 0; n < s; n += 1) typeof rep[n] == "string" && (r = rep[n], i = str(r, a), i && u.push(quote(r) + (gap ? ": " : ":") + i))
} else
for (r in a) Object.prototype.hasOwnProperty.call(a, r) && (i = str(r, a), i && u.push(quote(r) + (gap ? ": " : ":") + i));
return i = u.length === 0 ? "{}" : gap ? "{\n" + gap + u.join(",\n" + gap) + "\n" + o + "}" : "{" + u.join(",") + "}", gap = o, i
}
}
typeof Date.prototype.toJSON != "function" && (Date.prototype.toJSON = function(e) {
return isFinite(this.valueOf()) ? this.getUTCFullYear() + "-" + f(this.getUTCMonth() + 1) + "-" + f(this.getUTCDate()) + "T" + f(this.getUTCHours()) + ":" + f(this.getUTCMinutes()) + ":" + f(this.getUTCSeconds()) + "Z" : null
}, String.prototype.toJSON = Number.prototype.toJSON = Boolean.prototype.toJSON = function(e) {
return this.valueOf()
});
var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
gap, indent, meta = {
"\b": "\\b",
" ": "\\t",
"\n": "\\n",
"\f": "\\f",
"\r": "\\r",
'"': '\\"',
"\\": "\\\\"
},
rep;
typeof JSON.stringify != "function" && (JSON.stringify = function(e, t, n) {
var r;
gap = "", indent = "";
if (typeof n == "number")
for (r = 0; r < n; r += 1) indent += " ";
else typeof n == "string" && (indent = n);
rep = t;
if (!t || typeof t == "function" || typeof t == "object" && typeof t.length == "number") return str("", {
"": e
});
throw new Error("JSON.stringify")
}), typeof JSON.parse != "function" && (JSON.parse = function(text, reviver) {
function walk(e, t) {
var n, r, i = e[t];
if (i && typeof i == "object")
for (n in i) Object.prototype.hasOwnProperty.call(i, n) && (r = walk(i, n), r !== undefined ? i[n] = r : delete i[n]);
return reviver.call(e, t, i)
}
var j;
text = String(text), cx.lastIndex = 0, cx.test(text) && (text = text.replace(cx, function(e) {
return "\\u" + ("0000" + e.charCodeAt(0).toString(16)).slice(-4)
}));
if (/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, "@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, "]").replace(/(?:^|:|,)(?:\s*\[)+/g, ""))) return j = eval("(" + text + ")"), typeof reviver == "function" ? walk({
"": j
}, "") : j;
throw new SyntaxError("JSON.parse")
})
}();
var hexcase = 0,
b64pad = "",
chrsz = 8;
(function() {}).call(this), $(function() {
$(".required").live("change", function() {
validateAlignmentForm()
})
}), $(function() {
$("#ageRange").change(function() {
updateItemEducationTab("ageRange", "ageRangeOther")
})
}), $(function() {
$("#ageRangeOther").change(function() {
updateItemEducationTab("ageRange", "ageRangeOther")
})
}), $(function() {
$("#alignmentType").change(function(e) {})
}), $(function() {
var e = "createdBy";
$("#" + e).change(function(t) {
var n = $(t.target).val();
$("#multiItemSelector input[type=checkbox]:checked").each(function(t, r) {
items[r.id][e] = n
}), updateTextArea()
})
}), $(function() {
var e = "tagDescription";
$("#" + e).change(function(t) {
var n = $(t.target).val();
$("#multiItemSelector input[type=checkbox]:checked").each(function(t, r) {
items[r.id][e] = n
}), updateTextArea()
})
}), $(function() {
$("#dotNotation").change(function(e) {
if (e.target.value != previousDotValue) {
previousDotValue = $("#dotNotation").val(), document.getElementById("description").value = "";
var t = $.inArray(e.target.value, dotNotationDisplayArray);
if (t == -1) $("#description").attr("value", "Error: The Dot Notation you entered doesn't appear to be valid.");
else {
document.getElementById("description").value = "Loading (please wait)....";
for (i = 0; i < alignmentArray.length; i++) $("#dotNotation").val() == alignmentArray[i].title && (document.getElementById("itemGUID").value = alignmentArray[i].guid, $.ajax({
async: !1,
url: "http://anyorigin.com/get?url=" + alignmentArray[i].description + "&callback=?",
dataType: "json",
success: function(e) {
var t = $(e.contents).filter("title").text().replace(" | Achievement Standards Network", "");
if (t != "") {
var n = t.length;
document.getElementById("description").value = t
}
t == "" && (document.getElementById("description").value = "No Description Available"), validateAlignmentForm()
}
}))
}
}
})
}), $(function() {
$("#educationalUse").change(function() {
updateItemEducationTab("educationalUse", "educationalUseOther")
})
}), $(function() {
$("#educationalAlignment").change(function(e) {})
}), $(function() {
$("#educationalUseOther").change(function() {
updateItemEducationTab("educationalUse", "educationalUseOther")
})
}), $(function() {
$("#endUser").change(function() {
updateItemEducationTab("endUser", "endUserOther")
})
}), $(function() {
$("#endUserOther").change(function() {
updateItemEducationTab("endUser", "endUserOther")
})
}), $(function() {
$("#groupType").change(function() {
updateItemEducationTab("groupType", "groupTypeOther")
})
}), $(function() {
$("#groupTypeOther").change(function() {
updateItemEducationTab("groupType", "groupTypeOther")
})
}), $(function() {
$("#files").change(function(e) {
importedFiles = e.target.files;
for (var t = 0, n; n = importedFiles[t]; t++) reader = new FileReader, reader.onload = function(e) {
return itemCounter = 0, jQuery("#multiItemSelector input[type=checkbox]").each(function(e, t) {
t.checked = !1, itemCounter++
}),
function(e) {
$("#loadModal").modal("hide"), fileHasErrors = !1, fileErrors = [], jQuery("#multiItemSelector input[type=checkbox]").each(function(e, t) {
t.checked = !1
}), updateInputFields(), itemCounter == 0 && jQuery("#multiItemSelector").empty();
var t = e.target.result;
if (t[0] == "{") {
var n = JSON.parse(t);
for (u in n) {
if (n[u] == undefined || n[u].length == 0) continue;
n[u].id = itemCounter, items["itemTag" + itemCounter] = n[u];
var r = n[u].title != "" ? n[u].title.length > 25 ? n[u].title.substr(0, 25) + "…" : n[u].title : "New Item " + itemCounter,
i = n[u].url;
for (v in n[u].educationalAlignments) alignments[v] == undefined && ($(".noAlignmentsYet").hide(), alignments[v] = n[u].educationalAlignments[v], $("#currentAlignmentTable > tbody:last").append('<tr><td><label class="checkbox"><input type="checkbox" class="alignment-checkbox" value="' + v + '" />' + n[u].educationalAlignments[v].dotNotation + "</label></td><td>" + capitalize(n[u].educationalAlignments[v].alignmentType) + "</td></tr>"));
$("#multiItemSelector").append($("<a href='#itemTag" + itemCounter + "' class='pull-right delete-tag'><i class='icon-remove'></i></a> <a href='#itemTag" + itemCounter + "' id='itemTag" + itemCounter + "URL' " + (i != "" ? "" : "style='display:none;'") + " class='pull-right render-tag'><i class='icon-share'></i> </a> <label id='itemTag" + itemCounter + "Label' class='checkbox'><input id='itemTag" + itemCounter + "' type='checkbox' name='tagItem'/><span>" + r + "</span></label>")), itemCounter++
}
}
if (t[0] != "{") {
var s = [],
o = t.replace(/\r/g, "\r\n").replace(/\n\n/, "\n"),
n = $.csv.toArrays(o);
validateImportHeaders(n), fileHasErrors || validateImportColumns(n), fileHasErrors && showFileHasErrorsMessage("File Format Error");
for (var u = 1; u < n.length; u++) {
if (fileHasErrors) continue;
if (n[u] == undefined || n[u].length < 25) continue;
var r = n[u][1] != "" && n[u][1] != undefined ? n[u][1].length > 25 ? n[u][1].substr(0, 25) + "…" : n[u][1] : "New Item " + itemCounter,
i = n[u][2],
a = n[u][17].split(","),
f = n[u][18].split(","),
l = n[u][19].split(","),
c = n[u][21].split(","),
h = n[u][20].split(","),
p = {};
for (ea = 0; ea < a.length; ea++) {
if (l[ea] == "") continue;
var d = validateImportEducationalAlignment({
educationalAlignment: a[ea],
alignmentType: f[ea],
dotNotation: l[ea],
description: c[ea],
itemURL: h[ea]
});
if (!fileHasErrors) {
var v = objectToHash(d);
alignments[v] == undefined && ($(".noAlignmentsYet").hide(), alignments[v] = d, $("#currentAlignmentTable > tbody:last").append('<tr><td><label class="checkbox"><input type="checkbox" class="alignment-checkbox" value="' + v + '" />' + l[ea] + "</label></td><td>" + capitalize(f[ea]) + "</td></tr>")), p[v] = d
}
}
tempItem = {
id: itemCounter,
title: validateImportField("title", n[u][1]),
language: validateImportField("language", n[u][8]),
thumbnail: validateImportField("thumbnail", n[u][23]),
url: validateImportField("url", i),
tagDescription: validateImportField("tagDescription", n[u][24]),
createdOn: validateImportField("createdOn", n[u][5]),
topic: validateImportField("topic", n[u][4]),
createdBy: validateImportField("createdBy", n[u][6]),
usageRightsURL: validateImportField("usageRightsURL", n[u][10]),
publisher: validateImportField("publisher", n[u][7]),
isBasedOnURL: validateImportField("isBasedOnURL", n[u][11]),
endUser: validateImportField("endUser", n[u][12]),
ageRange: validateImportField("ageRange", n[u][14]),
educationalUse: validateImportField("educationalUse", n[u][13]),
interactivityType: validateImportField("interactivityType", n[u][15]),
learningResourceType: validateImportField("learningResourceType", n[u][16]),
mediaType: validateImportField("mediaType", n[u][9]),
groupType: validateImportField("groupType", n[u][22]),
timeRequired: validateImportField("timeRequired", n[u][3]),
educationalAlignments: p
}, fileHasErrors ? showFileHasErrorsMessage("Errors found in row #" + u) : (items["itemTag" + itemCounter] = tempItem, $("#multiItemSelector").append($("<a href='#itemTag" + itemCounter + "' class='pull-right delete-tag'><i class='icon-remove'></i></a> <a href='#itemTag" + itemCounter + "' id='itemTag" + itemCounter + "URL' " + (i != "" ? "" : "style='display:none;'") + " class='pull-right render-tag'><i class='icon-share'></i> </a> <label id='itemTag" + itemCounter + "Label' class='checkbox'><input id='itemTag" + itemCounter + "' type='checkbox' name='tagItem'/><span>" + r + "</span></label>")), itemCounter++)
}
}
updateResourceCount(), $("#pleasewait").hide()
}
}(n), /(csv|json)$/.test(n.name.toLowerCase()) ? ($("#pleasewait").show(), reader.readAsText(n), $("#fileForm")[0].reset()) : (alert("Please select a .CSV file"), $("#fileForm")[0].reset())
})
}), $(function() {
$("#interactivityType").change(function() {
updateItemEducationTab("interactivityType", "interactivityTypeOther")
})
}), $(function() {
$("#interactivityTypeOther").change(function() {
updateItemEducationTab("interactivityType", "interactivityTypeOther")
})
}), $(function() {
var e = "isBasedOnURL";
$("#" + e).change(function(t) {
var n = $(t.target).val();
$("#multiItemSelector input[type=checkbox]:checked").each(function(t, r) {
items[r.id][e] = n
}), updateTextArea()
})
}), $(function() {
$("#itemURL").change(function(e) {})
}), $(function() {
var e = "language";
$("#" + e).change(function(t) {
var n = $(t.target).val();
$("#multiItemSelector input[type=checkbox]:checked").each(function(t, r) {
items[r.id][e] = n
}), updateTextArea()
})
}), $(function() {
$("#learningResourceType").change(function() {
updateItemEducationTab("learningResourceType", "learningResourceTypeOther")
})
}), $(function() {
$("#learningResourceTypeOther").change(function() {
updateItemEducationTab("learningResourceType", "learningResourceTypeOther")
})
}), $(function() {
$("#mediaType").change(function() {
updateItemEducationTab("mediaType", "mediaTypeOther")
})
}), $(function() {
$("#mediaTypeOther").change(function() {
updateItemEducationTab("mediaType", "mediaTypeOther")
})
}), $(function() {
$("#multiItemSelector").change(function() {
updateInputFields(), updateTextArea()
})
}), $(function() {
var e = "publisher";
$("#" + e).change(function(t) {
var n = $(t.target).val();
$("#multiItemSelector input[type=checkbox]:checked").each(function(t, r) {
items[r.id][e] = n
}), updateTextArea()
})
}), $(function() {
var e = "title";
$("#" + e).change(function(t) {
var n = $(t.target).val();
$("#multiItemSelector input[type=checkbox]:checked").each(function(t, r) {
items[r.id][e] = n;
var i = n.length > 25 ? n.substr(0, 25) + "…" : n;
$("#" + r.id + "Label span")[0].innerHTML = i
}), updateTextArea()
})
}), $(function() {
var e = "topic";
$("#" + e).change(function(t) {
var n = $(t.target).val();
$("#multiItemSelector input[type=checkbox]:checked").each(function(t, r) {
items[r.id][e] = n
}), updateTextArea()
})
}), $(function() {
var e = "url";
$("#" + e).change(function(t) {
var n = $(t.target).val();
$("#multiItemSelector input[type=checkbox]:checked").each(function(t, r) {
items[r.id][e] = n, n != "" ? $("#" + r.id + "URL").show() : $("#" + r.id + "URL").hide()
}), updateTextArea(), updateMainContentBottom(n)
})
}), $(function() {
var e = "usageRightsURL";
$("#" + e).change(function(t) {
var n = $(t.target).val();
$("#multiItemSelector input[type=checkbox]:checked").each(function(t, r) {
items[r.id][e] = n
}), updateTextArea()
})
}), $(function() {
$(".add-alignment").click(function(e) {
return $("#alignmentsModal").modal("show"), !1
}), document.onkeypress = function(e) {
if (e.which == 13) return !1
}
}), $(function() {
$("#addButton").click(function() {
$("#alignmentsModal").modal("hide"), $(".noAlignmentsYet").hide();
var e = $("#educationalAlignment").val(),
t = $("#alignmentType").val(),
n = $("#dotNotation").val(),
r = $("#description").val(),
i = $("#itemURL").val(),
s = {
educationalAlignment: e,
alignmentType: t,
dotNotation: n,
description: r,
itemURL: i
},
o = objectToHash(s);
return alignments[o] == undefined && (alignments[o] = s, n == "" && (n = "N/A"), $("#currentAlignmentTable > tbody:last").append('<tr><td><label class="checkbox"><input type="checkbox" class="alignment-checkbox" value="' + o + '" />' + n + "</label></td><td>" + capitalize(t) + "</td></tr>")), updateTextArea(), $("#alignmentType").val(""), $("#dotNotation").val(""), $("#description").val(""), $("#itemURL").val(""), $("#itemGUID").val(""), !1
})
}), $(function() {
$("#addThumbnailButton").click(function() {
return $(this).hasClass("disabled") || $("#thumbModal").modal("show"), !1
})
}), $(function() {
$(".alignment-checkbox").live("click", function(e) {
checkbox = e.target, objectHash = $(checkbox).attr("value"), $("#multiItemSelector input[type=checkbox]:checked").each(function(e, t) {
$(checkbox).is(":checked") ? items[t.id].educationalAlignments[objectHash] = alignments[objectHash] : delete items[t.id].educationalAlignments[objectHash]
}), updateTextArea()
})
}), $(function() {
$("#closeModalButton").click(function() {
jQuery("#mainContentTopLeft").show(), jQuery("#mainContentTopRight").show(), jQuery("#mainContentBottom").show()
})
}), $(function() {
$(".delete-tag").live("click", function(e) {
var t = $(e.target).parent().attr("href").substr(1);
return $("#deleteModal .btn-danger").attr("onclick", "deleteTag('" + t + "');").attr("href", "#"), $("#deleteModal").modal("show"), !1
})
}), $(function() {
$("#exportCsvButton").click(function() {
var e = processCSVOutput(!0);
saveAndExport(e, ".csv")
})
}), $(function() {
$("#exportHtmlButton").click(function() {
var e = processHTMLOutput(!0);
saveAndExport(e, ".html")
})
}), $(function() {
$("#exportJsonButton").click(function() {
var e = processJSONOutput(!0);
saveAndExport(e, ".json")
})
}), $(function() {
$("#history a").live("click", function(e) {
var t = $(this).attr("href").substr(1);
return $("#resetModal .btn-success").attr("onclick", "resetResource('" + t + "');").attr("href", "#"), $("#resetModal").modal("show"), !1
})
}), $(function() {
$("#loadButton").click(function() {})
}), $(function() {
$("#newbutton").click(function() {
toggleForm()
})
}), $(function() {
$("#publishButton").click(function() {
if (!$(this).hasClass("disabled")) {
showPleaseWait("Publishing... (This can take some time depending on the number of resources you have selected..)");
var e = processJSONOutput();
saveDraft(e);
var e = processJSONOutput(!0);
saveRemote(e, "LR")
}
})
}), $(function() {
$("#removeThumbnailButton").click(function() {
return $("#thumbnail").attr("value", ""), $("#thumbnailImage").attr("src", ""), $("#removeThumbnailButton").hide(), $("#thumbnailImage").hide(), $("#multiItemSelector input[type=checkbox]:checked").each(function(e, t) {
items[t.id].thumbnail = ""
}), !1
})
}), $(function() {
$(".render-tag").live("click", function(e) {
var t = $(e.target).first().parent().attr("href").substr(1);
return updateMainContentBottom(items[t].url), !1
})
}), $(function() {
$("#saveDraftButton").click(function() {
var e = processJSONOutput();
saveDraft(e)
})
}), $(function() {
$("#saveLoadModalButton").click(function() {
if (document.getElementById("loadModalTextArea").value != "") {
itemCounter = 0, jQuery("#multiItemSelector input[type=checkbox]").each(function(e, t) {
t.checked = !1, itemCounter++
}), document.getElementById("loadModalTextArea").value = document.getElementById("loadModalTextArea").value.replace(/^\s+|\s+$/g, "");
var e = document.getElementById("loadModalTextArea").value.split("\n");
for (var t = 0; t < e.length; t++) {
var n = e[t].split(",");
items["itemTag" + itemCounter] = {
id: itemCounter,
title: n[0],
language: "",
thumbnail: "",
url: n[1],
tagDescription: "",
createdOn: "",
topic: "",
createdBy: "",
usageRightsURL: "",
publisher: "",
isBasedOnURL: "",
endUser: "",
ageRange: "",
educationalUse: "",
interactivityType: "",
learningResourceType: "",
mediaType: "",
groupType: "",
timeRequired: "P0Y0M0W0DT0H0M0S",
educationalAlignments: {}
}, itemCounter++
}
document.getElementById("loadModalTextArea").value = ""
} else document.getElementById("files").value != "";
redrawResourcesBasedOnItems()
})
}), $(function() {
$("#selectDeselectAllResources").click(function() {
checked = $(this).attr("checked"), $("#multiItemSelector input[type=checkbox]").each(function() {
checked ? ($(this).attr("checked", !0), $("#publishButton").removeClass("disabled")) : ($(this).removeAttr("checked"), $("#publishButton").addClass("disabled"))
}), updateResourceCount()
})
}), $(function() {
$("#description").keypress(function(e) {})
}), $(function() {
$("#dotNotation").keypress(function(e) {
e.keyCode == 13 && $("#dotNotation").blur()
})
}), $(function() {
$("#itemURL").keypress(function(e) {})
}); | public/appmain-expanded.js | /*!
* jQuery JavaScript Library v1.8.3
* http://jquery.com/
*
* Includes Sizzle.js
* http://sizzlejs.com/
*
* Copyright 2012 jQuery Foundation and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: Tue Nov 13 2012 08:20:33 GMT-0500 (Eastern Standard Time)
*/
function hex_sha1(e) {
return binb2hex(core_sha1(str2binb(e), e.length * chrsz))
}
function b64_sha1(e) {
return binb2b64(core_sha1(str2binb(e), e.length * chrsz))
}
function str_sha1(e) {
return binb2str(core_sha1(str2binb(e), e.length * chrsz))
}
function hex_hmac_sha1(e, t) {
return binb2hex(core_hmac_sha1(e, t))
}
function b64_hmac_sha1(e, t) {
return binb2b64(core_hmac_sha1(e, t))
}
function str_hmac_sha1(e, t) {
return binb2str(core_hmac_sha1(e, t))
}
function sha1_vm_test() {
return hex_sha1("abc") == "a9993e364706816aba3e25717850c26c9cd0d89d"
}
function core_sha1(e, t) {
e[t >> 5] |= 128 << 24 - t % 32, e[(t + 64 >> 9 << 4) + 15] = t;
var n = Array(80),
r = 1732584193,
i = -271733879,
s = -1732584194,
o = 271733878,
u = -1009589776;
for (var a = 0; a < e.length; a += 16) {
var f = r,
l = i,
c = s,
h = o,
p = u;
for (var d = 0; d < 80; d++) {
d < 16 ? n[d] = e[a + d] : n[d] = rol(n[d - 3] ^ n[d - 8] ^ n[d - 14] ^ n[d - 16], 1);
var v = safe_add(safe_add(rol(r, 5), sha1_ft(d, i, s, o)), safe_add(safe_add(u, n[d]), sha1_kt(d)));
u = o, o = s, s = rol(i, 30), i = r, r = v
}
r = safe_add(r, f), i = safe_add(i, l), s = safe_add(s, c), o = safe_add(o, h), u = safe_add(u, p)
}
return Array(r, i, s, o, u)
}
function sha1_ft(e, t, n, r) {
return e < 20 ? t & n | ~t & r : e < 40 ? t ^ n ^ r : e < 60 ? t & n | t & r | n & r : t ^ n ^ r
}
function sha1_kt(e) {
return e < 20 ? 1518500249 : e < 40 ? 1859775393 : e < 60 ? -1894007588 : -899497514
}
function core_hmac_sha1(e, t) {
var n = str2binb(e);
n.length > 16 && (n = core_sha1(n, e.length * chrsz));
var r = Array(16),
i = Array(16);
for (var s = 0; s < 16; s++) r[s] = n[s] ^ 909522486, i[s] = n[s] ^ 1549556828;
var o = core_sha1(r.concat(str2binb(t)), 512 + t.length * chrsz);
return core_sha1(i.concat(o), 672)
}
function safe_add(e, t) {
var n = (e & 65535) + (t & 65535),
r = (e >> 16) + (t >> 16) + (n >> 16);
return r << 16 | n & 65535
}
function rol(e, t) {
return e << t | e >>> 32 - t
}
function str2binb(e) {
var t = Array(),
n = (1 << chrsz) - 1;
for (var r = 0; r < e.length * chrsz; r += chrsz) t[r >> 5] |= (e.charCodeAt(r / chrsz) & n) << 32 - chrsz - r % 32;
return t
}
function binb2str(e) {
var t = "",
n = (1 << chrsz) - 1;
for (var r = 0; r < e.length * 32; r += chrsz) t += String.fromCharCode(e[r >> 5] >>> 32 - chrsz - r % 32 & n);
return t
}
function binb2hex(e) {
var t = hexcase ? "0123456789ABCDEF" : "0123456789abcdef",
n = "";
for (var r = 0; r < e.length * 4; r++) n += t.charAt(e[r >> 2] >> (3 - r % 4) * 8 + 4 & 15) + t.charAt(e[r >> 2] >> (3 - r % 4) * 8 & 15);
return n
}
function binb2b64(e) {
var t = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
n = "";
for (var r = 0; r < e.length * 4; r += 3) {
var i = (e[r >> 2] >> 8 * (3 - r % 4) & 255) << 16 | (e[r + 1 >> 2] >> 8 * (3 - (r + 1) % 4) & 255) << 8 | e[r + 2 >> 2] >> 8 * (3 - (r + 2) % 4) & 255;
for (var s = 0; s < 4; s++) r * 8 + s * 6 > e.length * 32 ? n += b64pad : n += t.charAt(i >> 6 * (3 - s) & 63)
}
return n
}
function capitalize(e) {
return (e + "").replace(/^([a-z])|\s+([a-z])|,+([a-z])/g, function(e) {
return e.toUpperCase()
})
}
function clearTimeRequired() {
$("#slideryears").slider({
value: 0
}), $("#slidermonths").slider({
value: 0
}), $("#sliderweeks").slider({
value: 0
}), $("#sliderdays").slider({
value: 0
}), $("#sliderhours").slider({
value: 0
}), $("#sliderminutes").slider({
value: 0
}), $("#sliderseconds").slider({
value: 0
}), $("#amountyears").html("Year"), $("#amountmonths").html("Month"), $("#amountweeks").html("Week"), $("#amountdays").html("Day"), $("#amounthours").html("Hour"), $("#amountminutes").html("Minute"), $("#amountseconds").html("Second")
}
function csvPreprocess(e) {
return (e + "").replace(/^([a-z])|\s+([a-z])|,+([a-z])/g, function(e) {
return e.toUpperCase()
}).replace(/^\s+/, "").replace(/\s+$/, "").replace(/\s+,/g, ",").replace(/,\s+/g, ",")
}
function deleteTag(e) {
return items[e] != undefined && delete items[e], $("#" + e).length > 0 && ($("#" + e).addClass("deleted"), $("#" + e).parent().hide().addClass("deleted"), $("a[href=#" + e + "]").remove(), $("#resourceCount").html($("#multiItemSelector input[type=checkbox]:checked").not(".deleted").length + " of " + $("#multiItemSelector input[type=checkbox]").not(".deleted").length + " resources")), $("#deleteModal").modal("hide"), updateTextArea(), !1
}
function objectToHash(e) {
var t = "";
for (j in e) typeof e[j] == "string" && (t += e[j]);
return hex_sha1(t)
}
function wrapIfNeeded(e) {
return /"/.test(e) || /,/.test(e) ? '"' + e.replace(/"/g, '""') + '"' : e
}
function processDataForAlignmentArray(e) {
var t = e.split(/\n|\r/);
for (var n = 1; n < t.length - 1; n++) {
var r = t[n].split(",");
alignmentArray.push({
title: r[2],
url: r[3],
description: r[0],
guid: r[4]
}), dotNotationDisplayArray.push(r[2])
}
}
function saveAndExport(e, t) {
var n = new Date,
r = location.protocol + "//" + location.host + "/tagger/save_export/";
$("<form></form>", {
action: r,
method: "POST"
}).append($("<input></input>", {
name: "filename",
type: "hidden",
value: t + "_" + n.toISOString() + t
})).append($("<input></input>", {
name: "data",
type: "hidden",
value: e
})).appendTo("body").submit()
}
function redrawResourcesBasedOnItems() {
$("#multiItemSelector").empty(), $("#multiItemSelector input[type=checkbox]").each(function(e, t) {
t.checked = !1
}), updateInputFields();
for (itemCounter in items) {
$("#multiItemSelector span.notYet").hide();
var e = items[itemCounter].title.length > 25 ? items[itemCounter].title.substr(0, 25) + "…" : items[itemCounter].title;
$("#multiItemSelector").append($("<a href='#" + itemCounter + "' class='pull-right delete-tag'><i class='icon-remove'></i></a> <a href='#" + itemCounter + "' id='" + itemCounter + "URL' " + (items[itemCounter].url ? "" : "style='display:none;'") + " class='pull-right render-tag'><i class='icon-share'></i> </a> <label id='" + itemCounter + "Label' class='checkbox'><input id='" + itemCounter + "' type='checkbox' name='tagItem'/><span>" + e + "</span></label>"));
for (objHash in items[itemCounter].educationalAlignments) {
var t = {
educationalAlignment: items[itemCounter].educationalAlignments[objHash].educationalAlignment,
alignmentType: items[itemCounter].educationalAlignments[objHash].alignmentType,
dotNotation: items[itemCounter].educationalAlignments[objHash].dotNotation,
description: items[itemCounter].educationalAlignments[objHash].description,
itemURL: items[itemCounter].educationalAlignments[objHash].itemURL
};
alignments[objHash] == undefined && ($(".noAlignmentsYet").hide(), alignments[objHash] = t, $("#currentAlignmentTable > tbody:last").append('<tr><td><label class="checkbox"><input type="checkbox" class="alignment-checkbox" value="' + objHash + '" />' + t.dotNotation + "</label></td><td>" + capitalize(t.alignmentType) + "</td></tr>"))
}
}
updateTextArea(), updateResourceCount()
}
function redrawHistoryBasedOn(e) {
$("#history").empty();
for (i in e) {
var t = e[i].title.length > 25 ? e[i].title.substr(0, 25) + "…" : e[i].title;
$("#history").append($("<label><a href='#" + e[i].uuid + "'><i class='icon-repeat'></i> " + t + "</a></label>"))
}
}
function setupDisplayFieldsEducationTab(e, t) {
if (e[t] != undefined && e[t] != "" && $("select#" + t)[0] != undefined) {
var n = e[t].split(",");
$("select#" + t + " option").each(function() {
$.inArray($(this).val(), n) !== -1 && $(this).attr("selected", !0)
});
var r = $("select#" + t + " option").map(function() {
return this.value
}),
s = [];
for (i in n) $.inArray(n[i], r) === -1 && s.push(n[i]);
s.length > 0 && $("#" + t + "Other").attr("value", s.join(","))
}
}
function showMessage(e, t) {
$("#pleaseWaitModal").modal("hide"), t == undefined && (t = "System Message"), $("#messageModal .header-text").html(t), $("#messageModal .body-text").html(e), $("#messageModal").modal("show")
}
function showPleaseWait(e) {
$("#pleaseWaitModal .body-text").html(e), $("#pleaseWaitModal").modal("show")
}
function toggleForm() {
$("#multiItemSelector input[type=checkbox]:checked").length > 0 ? ($("#LRMIData input,#LRMIData select,#LRMIData textarea").removeAttr("disabled"), $("#educationTab,#alignmentTab").removeClass("disabled"), $("#educationTab a,#alignmentTab a").attr("data-toggle", "tab")) : ($("#generalTab a").click(), $("#LRMIData input,#LRMIData select,#LRMIData textarea").attr("disabled", "disabled"), $("#educationTab,#alignmentTab").addClass("disabled"), $("#educationTab a,#alignmentTab a").removeAttr("data-toggle"))
}
function updateInputFields() {
updateResourceCount(), $("#addThumbnailButton").addClass("disabled"), $("#thumbnail").attr("value", ""), $("#thumbnailImage").attr("src", ""), $("#removeThumbnailButton").hide(), $("#thumbnailImage").hide(), $("#publishButton").addClass("disabled"), $("form[name=LRMIData]").find("input[type=text], textarea, select").val(""), $("#currentAlignmentTable input[type=checkbox]").attr("checked", !1), clearTimeRequired(), updateMainContentBottom(), toggleForm();
if ($("#multiItemSelector input[type=checkbox]:checked").length == 1) {
$("#addThumbnailButton").removeClass("disabled"), $("#publishButton").removeClass("disabled");
var e = items[$("#multiItemSelector input[type=checkbox]:checked").first().attr("id")];
e.title != "" && $("#title").val(e.title), e.url != "" && $("#url").val(e.url), e.tagDescription != "" && $("#tagDescription").val(e.tagDescription), e.language != "" && $("#language").val(e.language), e.topic != "" && $("#topic").val(e.topic), e.createdBy != "" && $("#createdBy").val(e.createdBy), e.usageRightsURL != "" && $("#usageRightsURL").val(e.usageRightsURL), e.publisher != "" && $("#publisher").val(e.publisher), e.isBasedOnURL != "" && $("#isBasedOnURL").val(e.isBasedOnURL), e.thumbnail != "" && ($("#thumbnail").val(e.thumbnail), $("#thumbnailImage").attr("src", "http://media.inbloom.org.s3.amazonaws.com/tagger/images/browser_thumb_" + e.thumbnail), $("#removeThumbnailButton").show(), $("#thumbnailImage").show()), d = new Date;
var t = ("0" + d.getDate()).slice(-2),
n = d.getMonth() + 1,
r = d.getFullYear();
ds = r + "-" + n + "-" + t, e.createdOn != "" && $("#createdOn").val(e.createdOn);
if (e.timeRequired != "P0Y0M0W0DT0H0M0S" && e.timeRequired != "") {
var i = e.timeRequired.match(/(\d+)/g);
updateSlider(event, null, $("#slideryears"), "Year", i[0]), updateSlider(event, null, $("#slidermonths"), "Month", i[1]), updateSlider(event, null, $("#sliderweeks"), "Week", i[2]), updateSlider(event, null, $("#sliderdays"), "Day", i[3]), updateSlider(event, null, $("#sliderhours"), "Hour", i[4]), updateSlider(event, null, $("#sliderminutes"), "Minute", i[5]), updateSlider(event, null, $("#sliderseconds"), "Second", i[6])
}
e.url != "" && updateMainContentBottom(e.url), setupDisplayFieldsEducationTab(e, "endUser"), setupDisplayFieldsEducationTab(e, "ageRange"), setupDisplayFieldsEducationTab(e, "educationalUse"), setupDisplayFieldsEducationTab(e, "interactivityType"), setupDisplayFieldsEducationTab(e, "learningResourceType"), setupDisplayFieldsEducationTab(e, "mediaType"), setupDisplayFieldsEducationTab(e, "groupType");
for (j in e.educationalAlignments) $("input[type=checkbox][value=" + j + "]").attr("checked", !0)
} else $("#multiItemSelector input[type=checkbox]:checked").length > 1 && ($("#publishButton").removeClass("disabled"), $("#addThumbnailButton").removeClass("disabled"))
}
function updateItemEducationTab(e, t) {
$("#multiItemSelector input[type=checkbox]:checked").each(function(n, r) {
var i = !1,
s = document.forms.LRMIData,
o = "",
u = 0;
for (u = 0; u < s[e].length; u++) s[e][u].selected && (i ? o = o + "," + s[e][u].value : (o = s[e][u].value, i = !0));
s[t].value != "" && (o = o + (o == "" ? "" : ",") + s[t].value), items[r.id][e] = o
}), updateTextArea()
}
function updateMainContentBottom(e) {
e == "" || e == undefined ? $("#iframe").attr("src", "about:blank") : $("#iframe").attr("src", e)
}
function updateResourceCount() {
$("#resourceCount").html($("#multiItemSelector input[type=checkbox]:checked").not(".deleted").length + " of " + $("#multiItemSelector input[type=checkbox]").not(".deleted").length + " resources")
}
function updateTextArea() {
var e = "";
$("#multiItemSelector input[type=checkbox]:checked").each(function(t, n) {
items[n.id].title != undefined && items[n.id].title != "" && (e += "Title:\n" + items[n.id].title + "\n"), items[n.id].url != undefined && items[n.id].url != "" && (e += "URL:\n" + items[n.id].url + "\n"), items[n.id].tagDescription != undefined && items[n.id].tagDescription != "" && (e += "Description:\n" + items[n.id].tagDescription + "\n"), items[n.id].language != undefined && items[n.id].language != "" && (e += "Language:\n" + items[n.id].language + "\n"), items[n.id].createdOn != undefined && items[n.id].createdOn != "" && (e += "Created On:\n" + items[n.id].createdOn + "\n"), items[n.id].topic != undefined && items[n.id].topic != "" && (e += "Topic/Subject:\n" + items[n.id].topic + "\n"), items[n.id].createdBy != undefined && items[n.id].createdBy != "" && (e += "Created By:\n" + items[n.id].createdBy + "\n"), items[n.id].usageRightsURL != undefined && items[n.id].usageRightsURL != "" && (e += "Usage Rights URL:\n" + items[n.id].usageRightsURL + "\n"), items[n.id].publisher != undefined && items[n.id].publisher != "" && (e += "Publisher:\n" + items[n.id].publisher + "\n"), items[n.id].isBasedOnURL != undefined && items[n.id].isBasedOnURL != "" && (e += "Is Based On URL:\n" + items[n.id].isBasedOnURL + "\n"), items[n.id].endUser != undefined && items[n.id].endUser != "" && (e += "End User:\n" + items[n.id].endUser + "\n"), items[n.id].ageRange != undefined && items[n.id].ageRange != "" && (e += "Age Range:\n" + items[n.id].ageRange + "\n"), items[n.id].educationalUse != undefined && items[n.id].educationalUse != "" && (e += "Educational Use:\n" + items[n.id].educationalUse + "\n"), items[n.id].interactivityType != undefined && items[n.id].interactivityType != "" && (e += "Interactivity Type:\n" + items[n.id].interactivityType + "\n"), items[n.id].learningResourceType != undefined && items[n.id].learningResourceType != "" && (e += "Learning Res Type:\n" + items[n.id].learningResourceType + "\n"), items[n.id].mediaType != undefined && items[n.id].mediaType != "" && (e += "Media Type:\n" + items[n.id].mediaType + "\n"), items[n.id].groupType != undefined && items[n.id].groupType != "" && (e += "Group Type:\n" + items[n.id].groupType + "\n"), items[n.id].timeRequired != "P0Y0M0W0DT0H0M0S" && (e += "Time Required:\n" + items[n.id].timeRequired + "\n\n");
if (items[n.id].educationalAlignments != undefined)
for (j in items[n.id].educationalAlignments) items[n.id].educationalAlignments[j].educationalAlignment != undefined && items[n.id].educationalAlignments[j].educationalAlignment != "" && (e += "Educational Alignment:\n" + items[n.id].educationalAlignments[j].educationalAlignment + "\n"), items[n.id].educationalAlignments[j].alignmentType != undefined && items[n.id].educationalAlignments[j].alignmentType != "" && (e += "Alignment Type:\n" + items[n.id].educationalAlignments[j].alignmentType + "\n"), items[n.id].educationalAlignments[j].dotNotation != undefined && items[n.id].educationalAlignments[j].dotNotation != "" && (e += "Dot Notation:\n" + items[n.id].educationalAlignments[j].dotNotation + "\n"), items[n.id].educationalAlignments[j].itemURL != undefined && items[n.id].educationalAlignments[j].itemURL != "" && (e += "Item URL:\n" + items[n.id].educationalAlignments[j].itemURL + "\n"), items[n.id].educationalAlignments[j].description != undefined && items[n.id].educationalAlignments[j].description != "" && (e += "Description:\n" + items[n.id].educationalAlignments[j].description + "\n");
e += "\n-----------------------\n\n"
}), $("#textarea").val(e)
}
function updateTimeRequired(e) {
if (e != undefined) {
var t = "timeRequired";
$("#multiItemSelector input[type=checkbox]:checked").each(function(n, r) {
var i = items[r.id][t].match(/(\d+)/g);
items[r.id][t] = "P" + (e == "Year" ? $("#slideryears").slider("value") : i[0]) + "Y" + (e == "Month" ? $("#slidermonths").slider("value") : i[1]) + "M" + (e == "Week" ? $("#sliderweeks").slider("value") : i[2]) + "W" + (e == "Day" ? $("#sliderdays").slider("value") : i[3]) + "DT" + (e == "Hour" ? $("#sliderhours").slider("value") : i[4]) + "H" + (e == "Minute" ? $("#sliderminutes").slider("value") : i[5]) + "M" + (e == "Second" ? $("#sliderseconds").slider("value") : i[6]) + "S"
}), updateTextArea()
}
}
function validateAlignmentForm() {
default_values = new Array, $(".required").each(function(e, t) {
default_values[e] = t.value
}), req_all = default_values.length, filled_out_values = $.grep(default_values, function(e) {
return e
}), filled_out_values = $.grep(filled_out_values, function(e) {
return e != "Alignment Type..."
}), filled_out_values = $.grep(filled_out_values, function(e) {
return e != "Loading (please wait)...."
}), req_filled = filled_out_values.length, req_filled > 0 && req_all == req_filled ? $("#addButton").removeAttr("disabled") : $("#addButton").attr("disabled", "disabled")
}
function validateImportHeaders(e) {
var t = e[0],
n = t[0];
n == "Metadata:" ? (validValues = ["Metadata:", "Title", "URL", "Time Required (FORMAT: P0Y0M0W0DT0H0M0S) ISO8601", "Topic", "Created (FORMAT: YYYY-MM-DD)", "Creator", "Publisher", "Language", "Mediatype", "Use Rights URL", "Is based on URL", "Intended End User Role", "Educational Use", "Typical Age Range", "Interactivity Type", "Learning Resource Type", "Educational Alignment", "Alignment Type", "Dot Notation", "Target URL", "Target Description", "Group Type", "Thumbnail URL", "Tag Description"], compareValueEquals(t, validValues, "There appears to be a value comparison error in the firstRow headers preventing Tagger from knowing if this is a valid file")) : (fileHasErrors = !0, fileErrors.push("<strong>Invalid file imported</strong><br /> The file you attempted to import doesn't appear to have the correct header identifier ('" + n + "' was sent, it should be 'Metadata:') for this version of Tagger (v1.1).<br /><br />"))
}
function validateImportColumns(e) {
var t = e[0],
n = t[0];
if (n == "Metadata:")
if (e.length > 1)
for (i in e) e[i].length != 25 && e[i].length > 1 && (fileHasErrors = !0, fileErrors.push("<strong>Invalid file imported</strong><br /> The file you attempted to import doesn't appear to have the correct number of columns in row #" + i + " (There appear to be '" + e[i].length + "', it should be '25') for this version of Tagger (v1.1).<br /><br />"));
else fileHasErrors = !0, fileErrors.push("<strong>Empty file imported</strong><br /> The file you attempted to import doesn't appear to have any content in it.<br /><br />")
}
function validateImportField(e, t) {
t == undefined && (t = "");
var n = "";
switch (e) {
case "title":
case "topic":
case "tagDescription":
case "thumbnail":
case "url":
case "usageRightsURL":
case "isBasedOnURL":
case "publisher":
case "createdBy":
n = t;
break;
case "language":
t != undefined && t != "" && (tValue = t.toLowerCase(), tValue = tValue.replace(/^en$/, "EN_US"), tValue = tValue.replace(/^english$/, "EN_US"), tValue = tValue.replace(/^engrish$/, "EN_US"), tValue = tValue.replace(/^spanish$/, "ES_ES"), tValue = tValue.replace(/^es$/, "ES_ES"), tValue = tValue.replace(/^espanol$/, "ES_ES"), tValue = tValue.replace(/^español$/, "ES_ES"), validOptions = ["EN_US", "ES_ES"], tValue = tValue.toUpperCase(), tValue = tValue.replace("-", "_"), $.inArray(tValue, validOptions) == -1 ? (fileHasErrors = !0, fileErrors.push('<strong>Invalid file imported -- <em>"Language"</em></strong><br /> It appears the sent language value is incorrect: "' + tValue + '" -- Valid Options: "' + validOptions.join() + '"<br /><br />')) : n = tValue);
break;
case "createdOn":
if (t != undefined && t != "") {
var r = 216e5,
i = Date.parse(t),
s = new Date(i + r);
isNaN(s) || s.getMonth() + 1 == 0 || s.getDate() == 0 || s.getFullYear() == 0 ? (fileHasErrors = !0, fileErrors.push("<strong>Invalid file imported -- <em>"Created On"</em></strong><br /> It would appear you're attempting to import a file that is containing a "Created On" date that is an invalid ISO8601 value. Value sent: "" + t + ""<br /><br />")) : n = (s.getMonth() + 1 < 10 ? "0" + (s.getMonth() + 1) : s.getMonth() + 1) + "-" + (s.getDate() < 10 ? "0" + s.getDate() : s.getDate()) + "-" + s.getFullYear()
}
break;
case "endUser":
t != undefined && t != "" && (validOptions = ["Administrator", "Mentor", "Parent", "Peer Tutor", "Specialist", "Student", "Teacher", "Team"], n = checkCSVValuesForValidOptions("End User", validOptions, t));
break;
case "ageRange":
t != undefined && t != "" && (validOptions = ["0-2", "3-5", "5-8", "8-10", "10-12", "12-14", "14-16", "16-18", "18+"], n = checkCSVValuesForValidOptions("Age Range", validOptions, t));
break;
case "educationalUse":
t != undefined && t != "" && (validOptions = ["Activity", "Analogies", "Assessment", "Auditory", "Brainstorming", "Classifying", "Comparing", "Cooperative Learning", "Creative Response", "Demonstration", "Differentiation", "Discovery Learning", "Discussion/Debate", "Drill & Practice", "Experiential", "Field Trip", "Game", "Generating Hypotheses", "Guided Questions", "Hands-on", "Homework", "Identify Similarities & Differences", "Inquiry", "Interactive", "Interview/Survey", "Interviews", "Introduction", "Journaling", "Kinesthetic", "Laboratory", "Lecture", "Metaphors", "Model & Simulation", "Musical", "Nonlinguistic", "Note Taking", "Peer Coaching", "Peer Response", "Play", "Presentation", "Problem Solving", "Problem Based", "Project", "Questioning", "Reading", "Reciprocal Teaching", "Reflection", "Reinforcement", "Research", "Review", "Role Playing", "Service Learning", "Simulations", "Summarizing", "Technology", "Testing Hypotheses", "Thematic Instruction", "Visual/Spatial", "Word Association", "Writing"], n = checkCSVValuesForValidOptions("Educational Use", validOptions, t));
break;
case "interactivityType":
t != undefined && t != "" && (validOptions = ["Active", "Expositive", "Mixed"], n = checkCSVValuesForValidOptions("Interactivity Type", validOptions, t));
break;
case "learningResourceType":
t != undefined && t != "" && (validOptions = ["Activity", "Assessment", "Audio", "Broadcast", "Calculator", "Discussion", "E-Mail", "Field Trip", "Hands-on", "In-person/Speaker", "Kinesthetic", "Lab Material", "Lesson Plan", "Manipulative", "MBL (Microcomputer Based)", "Model", "On-Line", "Podcast", "Presentation", "Printed", "Quiz", "Robotics", "Still Image", "Test", "Video", "Wiki", "Worksheet"], n = checkCSVValuesForValidOptions("Learning Resource Type", validOptions, t));
break;
case "mediaType":
t != undefined && t != "" && (validOptions = ["Audio CD", "Audiotape", "Calculator", "CD-I", "CD-ROM", "Diskette", "Duplication Master", "DVD/Blu-ray", "E-Mail", "Electronic Slides", "Field Trip", "Filmstrip", "Flash", "Image", "In-person/Speaker", "Interactive Whiteboard", "Manipulative", "MBL (Microcomputer Based)", "Microfiche", "Overhead", "Pamphlet", "PDF", "Person-to-Person", "Phonograph Record", "Photo", "Podcast", "Printed", "Radio", "Robotics", "Satellite", "Slides", "Television", "Transparency", "Video Conference", "Videodisc", "Webpage", "Wiki"], n = checkCSVValuesForValidOptions("Media Type", validOptions, t));
break;
case "groupType":
t != undefined && t != "" && (validOptions = ["Class", "Community", "Grade", "Group Large (6+ Members)", "Group Small (3-5 Members)", "Individual", "Inter-generational", "Multiple Class", "Pair", "School", "State/Province", "World"], n = checkCSVValuesForValidOptions("Group Type", validOptions, t));
break;
case "timeRequired":
t != undefined && t != "" ? nezasa.iso8601.Period.isValid(t) ? (parsedTimeRequired = nezasa.iso8601.Period.parse(t), parsedTimeRequired[0] = "P" + parsedTimeRequired[0] + "Y", parsedTimeRequired[1] = parsedTimeRequired[1] + "M", parsedTimeRequired[2] = parsedTimeRequired[2] + "W", parsedTimeRequired[3] = parsedTimeRequired[3] + "D", parsedTimeRequired[4] = "T" + parsedTimeRequired[4] + "H", parsedTimeRequired[5] = parsedTimeRequired[5] + "M", parsedTimeRequired[6] = parsedTimeRequired[6] + "S", n = parsedTimeRequired.join("")) : (n = "", fileHasErrors = !0, fileErrors.push("<strong>Invalid file imported -- <em>"Time Required"</em></strong><br /> It would appear you're attempting to import a file with an invalid ISO8601 "Time Required" value. Value sent "" + t + ""<br /><br />")) : n = "P0Y0M0W0DT0H0M0S"
}
return n
}
function validateImportEducationalAlignment(e) {
var t = ["Teaches", "Assesses", "Requires"];
checkCSVValuesForValidOptions("Alignment Type", t, e.alignmentType, !0);
var n = $.inArray(e.dotNotation, dotNotationDisplayArray);
if (n != -1) {
var r = e.dotNotation.split(".");
r[0].toUpperCase() == "CCSS" && (e.educationalAlignment = "Common Core State Standards")
}
return e
}
function checkCSVValuesForValidOptions(e, n, r, i) {
r == undefined && i == 1 && (fileHasErrors = !0, fileErrors.push('<strong>Invalid file imported -- <em>"' + e + '"</em></strong><br /> Value set: "undefined" -- Valid Options: "' + n.join() + '"<br /><br />'));
if (r == undefined) return "";
resValues = [], tValues = r.toLowerCase(), tValues = tValues.split(",");
for (t in tValues) tValue = $.trim(tValues[t]), tValue = toCorrectCase(tValue), $.inArray(tValue, n) == -1 && i == 1 ? (fileHasErrors = !0, fileErrors.push('<strong>Invalid file imported -- <em>"' + e + '"</em></strong><br /> Value set: "' + tValue + '" -- Valid Options: "' + n.join() + '"<br /><br />')) : resValues.push(tValue);
return resValues.join(",")
}
function toCorrectCase(e) {
var t = "";
e == "on-line" && (t = "On-Line"), e == "cd-rom" && (t = "CD-ROM"), e == "cd-i" && (t = "CD-I"), e == "pdf" && (t = "PDF"), e == "e-mail" && (t = "E-Mail"), e == "audio cd" && (t = "Audio CD"), e == "dvd/blu-ray" && (t = "DVD/Blu-ray"), e == "mbl (microcomputer based)" && (t = "MBL (Microcomputer Based)"), e == "person-to-person" && (t = "Person-to-Person");
if (t == "") {
var n = e.split(/\s/);
for (i in n) n[i] = n[i].charAt(0).toUpperCase() + n[i].slice(1);
t = n.join(" ");
var n = t.split(/\//);
for (i in n) n[i] = n[i].charAt(0).toUpperCase() + n[i].slice(1);
t = n.join("/")
}
return t
}
function compareValueEquals(e, t, n) {
if (typeof e == "string") e.toLowerCase() != t.toLowerCase() && (fileHasErrors = !0, fileErrors.push("<strong>Invalid file imported</strong><br /> " + n + ": '" + e + "' is not equals to the correct value of '" + t + "'<br /><br />"));
else if (typeof e == "object")
for (i in t)
if (e[i] == undefined || e[i].toLowerCase() != t[i].toLowerCase()) fileHasErrors = !0, e[i] == undefined ? fileErrors.push("<strong>Invalid file imported</strong><br /> " + n + ": '" + t[i] + "' appears to be missing entirely<br /><br />") : fileErrors.push("<strong>Invalid file imported</strong><br /> " + n + ": '" + e[i] + "' is not equals to the correct value of '" + t[i] + "'<br /><br />")
}
function showFileHasErrorsMessage(e) {
if (fileHasErrors) {
var t = "Data could not be imported. The file you're attempting to import appears to have some errors in rows or columns that Tagger does not understand. This is usually as a result of data that doesn't conform to requirements for each column of data.<br />Before Tagger can import this file, please correct the following errors.<br /><br />" + fileErrors.join("");
showMessage(t, "Import Errors! :: " + e)
}
}
function forcePublish() {
var e = processJSONOutput(!0);
saveRemote(e, "LR")
}
function updateSlider(e, t, n, r, i) {
i == undefined && (i = t.value), $(n).slider({
value: i
});
var s = $(n).prev();
i == 0 ? s.
html(r): i == 1 ? s.html(i + " " + r) : s.html(i + " " + r + "s")
}(function(e, t) {
function _(e) {
var t = M[e] = {};
return v.each(e.split(y), function(e, n) {
t[n] = !0
}), t
}
function H(e, n, r) {
if (r === t && e.nodeType === 1) {
var i = "data-" + n.replace(P, "-$1").toLowerCase();
r = e.getAttribute(i);
if (typeof r == "string") {
try {
r = r === "true" ? !0 : r === "false" ? !1 : r === "null" ? null : +r + "" === r ? +r : D.test(r) ? v.parseJSON(r) : r
} catch (s) {}
v.data(e, n, r)
} else r = t
}
return r
}
function B(e) {
var t;
for (t in e) {
if (t === "data" && v.isEmptyObject(e[t])) continue;
if (t !== "toJSON") return !1
}
return !0
}
function et() {
return !1
}
function tt() {
return !0
}
function ut(e) {
return !e || !e.parentNode || e.parentNode.nodeType === 11
}
function at(e, t) {
do e = e[t]; while (e && e.nodeType !== 1);
return e
}
function ft(e, t, n) {
t = t || 0;
if (v.isFunction(t)) return v.grep(e, function(e, r) {
var i = !!t.call(e, r, e);
return i === n
});
if (t.nodeType) return v.grep(e, function(e, r) {
return e === t === n
});
if (typeof t == "string") {
var r = v.grep(e, function(e) {
return e.nodeType === 1
});
if (it.test(t)) return v.filter(t, r, !n);
t = v.filter(t, r)
}
return v.grep(e, function(e, r) {
return v.inArray(e, t) >= 0 === n
})
}
function lt(e) {
var t = ct.split("|"),
n = e.createDocumentFragment();
if (n.createElement)
while (t.length) n.createElement(t.pop());
return n
}
function Lt(e, t) {
return e.getElementsByTagName(t)[0] || e.appendChild(e.ownerDocument.createElement(t))
}
function At(e, t) {
if (t.nodeType !== 1 || !v.hasData(e)) return;
var n, r, i, s = v._data(e),
o = v._data(t, s),
u = s.events;
if (u) {
delete o.handle, o.events = {};
for (n in u)
for (r = 0, i = u[n].length; r < i; r++) v.event.add(t, n, u[n][r])
}
o.data && (o.data = v.extend({}, o.data))
}
function Ot(e, t) {
var n;
if (t.nodeType !== 1) return;
t.clearAttributes && t.clearAttributes(), t.mergeAttributes && t.mergeAttributes(e), n = t.nodeName.toLowerCase(), n === "object" ? (t.parentNode && (t.outerHTML = e.outerHTML), v.support.html5Clone && e.innerHTML && !v.trim(t.innerHTML) && (t.innerHTML = e.innerHTML)) : n === "input" && Et.test(e.type) ? (t.defaultChecked = t.checked = e.checked, t.value !== e.value && (t.value = e.value)) : n === "option" ? t.selected = e.defaultSelected : n === "input" || n === "textarea" ? t.defaultValue = e.defaultValue : n === "script" && t.text !== e.text && (t.text = e.text), t.removeAttribute(v.expando)
}
function Mt(e) {
return typeof e.getElementsByTagName != "undefined" ? e.getElementsByTagName("*") : typeof e.querySelectorAll != "undefined" ? e.querySelectorAll("*") : []
}
function _t(e) {
Et.test(e.type) && (e.defaultChecked = e.checked)
}
function Qt(e, t) {
if (t in e) return t;
var n = t.charAt(0).toUpperCase() + t.slice(1),
r = t,
i = Jt.length;
while (i--) {
t = Jt[i] + n;
if (t in e) return t
}
return r
}
function Gt(e, t) {
return e = t || e, v.css(e, "display") === "none" || !v.contains(e.ownerDocument, e)
}
function Yt(e, t) {
var n, r, i = [],
s = 0,
o = e.length;
for (; s < o; s++) {
n = e[s];
if (!n.style) continue;
i[s] = v._data(n, "olddisplay"), t ? (!i[s] && n.style.display === "none" && (n.style.display = ""), n.style.display === "" && Gt(n) && (i[s] = v._data(n, "olddisplay", nn(n.nodeName)))) : (r = Dt(n, "display"), !i[s] && r !== "none" && v._data(n, "olddisplay", r))
}
for (s = 0; s < o; s++) {
n = e[s];
if (!n.style) continue;
if (!t || n.style.display === "none" || n.style.display === "") n.style.display = t ? i[s] || "" : "none"
}
return e
}
function Zt(e, t, n) {
var r = Rt.exec(t);
return r ? Math.max(0, r[1] - (n || 0)) + (r[2] || "px") : t
}
function en(e, t, n, r) {
var i = n === (r ? "border" : "content") ? 4 : t === "width" ? 1 : 0,
s = 0;
for (; i < 4; i += 2) n === "margin" && (s += v.css(e, n + $t[i], !0)), r ? (n === "content" && (s -= parseFloat(Dt(e, "padding" + $t[i])) || 0), n !== "margin" && (s -= parseFloat(Dt(e, "border" + $t[i] + "Width")) || 0)) : (s += parseFloat(Dt(e, "padding" + $t[i])) || 0, n !== "padding" && (s += parseFloat(Dt(e, "border" + $t[i] + "Width")) || 0));
return s
}
function tn(e, t, n) {
var r = t === "width" ? e.offsetWidth : e.offsetHeight,
i = !0,
s = v.support.boxSizing && v.css(e, "boxSizing") === "border-box";
if (r <= 0 || r == null) {
r = Dt(e, t);
if (r < 0 || r == null) r = e.style[t];
if (Ut.test(r)) return r;
i = s && (v.support.boxSizingReliable || r === e.style[t]), r = parseFloat(r) || 0
}
return r + en(e, t, n || (s ? "border" : "content"), i) + "px"
}
function nn(e) {
if (Wt[e]) return Wt[e];
var t = v("<" + e + ">").appendTo(i.body),
n = t.css("display");
t.remove();
if (n === "none" || n === "") {
Pt = i.body.appendChild(Pt || v.extend(i.createElement("iframe"), {
frameBorder: 0,
width: 0,
height: 0
}));
if (!Ht || !Pt.createElement) Ht = (Pt.contentWindow || Pt.contentDocument).document, Ht.write("<!doctype html><html><body>"), Ht.close();
t = Ht.body.appendChild(Ht.createElement(e)), n = Dt(t, "display"), i.body.removeChild(Pt)
}
return Wt[e] = n, n
}
function fn(e, t, n, r) {
var i;
if (v.isArray(t)) v.each(t, function(t, i) {
n || sn.test(e) ? r(e, i) : fn(e + "[" + (typeof i == "object" ? t : "") + "]", i, n, r)
});
else if (!n && v.type(t) === "object")
for (i in t) fn(e + "[" + i + "]", t[i], n, r);
else r(e, t)
}
function Cn(e) {
return function(t, n) {
typeof t != "string" && (n = t, t = "*");
var r, i, s, o = t.toLowerCase().split(y),
u = 0,
a = o.length;
if (v.isFunction(n))
for (; u < a; u++) r = o[u], s = /^\+/.test(r), s && (r = r.substr(1) || "*"), i = e[r] = e[r] || [], i[s ? "unshift" : "push"](n)
}
}
function kn(e, n, r, i, s, o) {
s = s || n.dataTypes[0], o = o || {}, o[s] = !0;
var u, a = e[s],
f = 0,
l = a ? a.length : 0,
c = e === Sn;
for (; f < l && (c || !u); f++) u = a[f](n, r, i), typeof u == "string" && (!c || o[u] ? u = t : (n.dataTypes.unshift(u), u = kn(e, n, r, i, u, o)));
return (c || !u) && !o["*"] && (u = kn(e, n, r, i, "*", o)), u
}
function Ln(e, n) {
var r, i, s = v.ajaxSettings.flatOptions || {};
for (r in n) n[r] !== t && ((s[r] ? e : i || (i = {}))[r] = n[r]);
i && v.extend(!0, e, i)
}
function An(e, n, r) {
var i, s, o, u, a = e.contents,
f = e.dataTypes,
l = e.responseFields;
for (s in l) s in r && (n[l[s]] = r[s]);
while (f[0] === "*") f.shift(), i === t && (i = e.mimeType || n.getResponseHeader("content-type"));
if (i)
for (s in a)
if (a[s] && a[s].test(i)) {
f.unshift(s);
break
}
if (f[0] in r) o = f[0];
else {
for (s in r) {
if (!f[0] || e.converters[s + " " + f[0]]) {
o = s;
break
}
u || (u = s)
}
o = o || u
}
if (o) return o !== f[0] && f.unshift(o), r[o]
}
function On(e, t) {
var n, r, i, s, o = e.dataTypes.slice(),
u = o[0],
a = {},
f = 0;
e.dataFilter && (t = e.dataFilter(t, e.dataType));
if (o[1])
for (n in e.converters) a[n.toLowerCase()] = e.converters[n];
for (; i = o[++f];)
if (i !== "*") {
if (u !== "*" && u !== i) {
n = a[u + " " + i] || a["* " + i];
if (!n)
for (r in a) {
s = r.split(" ");
if (s[1] === i) {
n = a[u + " " + s[0]] || a["* " + s[0]];
if (n) {
n === !0 ? n = a[r] : a[r] !== !0 && (i = s[0], o.splice(f--, 0, i));
break
}
}
}
if (n !== !0)
if (n && e["throws"]) t = n(t);
else try {
t = n(t)
} catch (l) {
return {
state: "parsererror",
error: n ? l : "No conversion from " + u + " to " + i
}
}
}
u = i
}
return {
state: "success",
data: t
}
}
function Fn() {
try {
return new e.XMLHttpRequest
} catch (t) {}
}
function In() {
try {
return new e.ActiveXObject("Microsoft.XMLHTTP")
} catch (t) {}
}
function $n() {
return setTimeout(function() {
qn = t
}, 0), qn = v.now()
}
function Jn(e, t) {
v.each(t, function(t, n) {
var r = (Vn[t] || []).concat(Vn["*"]),
i = 0,
s = r.length;
for (; i < s; i++)
if (r[i].call(e, t, n)) return
})
}
function Kn(e, t, n) {
var r, i = 0,
s = 0,
o = Xn.length,
u = v.Deferred().always(function() {
delete a.elem
}),
a = function() {
var t = qn || $n(),
n = Math.max(0, f.startTime + f.duration - t),
r = n / f.duration || 0,
i = 1 - r,
s = 0,
o = f.tweens.length;
for (; s < o; s++) f.tweens[s].run(i);
return u.notifyWith(e, [f, i, n]), i < 1 && o ? n : (u.resolveWith(e, [f]), !1)
},
f = u.promise({
elem: e,
props: v.extend({}, t),
opts: v.extend(!0, {
specialEasing: {}
}, n),
originalProperties: t,
originalOptions: n,
startTime: qn || $n(),
duration: n.duration,
tweens: [],
createTween: function(t, n, r) {
var i = v.Tween(e, f.opts, t, n, f.opts.specialEasing[t] || f.opts.easing);
return f.tweens.push(i), i
},
stop: function(t) {
var n = 0,
r = t ? f.tweens.length : 0;
for (; n < r; n++) f.tweens[n].run(1);
return t ? u.resolveWith(e, [f, t]) : u.rejectWith(e, [f, t]), this
}
}),
l = f.props;
Qn(l, f.opts.specialEasing);
for (; i < o; i++) {
r = Xn[i].call(f, e, l, f.opts);
if (r) return r
}
return Jn(f, l), v.isFunction(f.opts.start) && f.opts.start.call(e, f), v.fx.timer(v.extend(a, {
anim: f,
queue: f.opts.queue,
elem: e
})), f.progress(f.opts.progress).done(f.opts.done, f.opts.complete).fail(f.opts.fail).always(f.opts.always)
}
function Qn(e, t) {
var n, r, i, s, o;
for (n in e) {
r = v.camelCase(n), i = t[r], s = e[n], v.isArray(s) && (i = s[1], s = e[n] = s[0]), n !== r && (e[r] = s, delete e[n]), o = v.cssHooks[r];
if (o && "expand" in o) {
s = o.expand(s), delete e[r];
for (n in s) n in e || (e[n] = s[n], t[n] = i)
} else t[r] = i
}
}
function Gn(e, t, n) {
var r, i, s, o, u, a, f, l, c, h = this,
p = e.style,
d = {},
m = [],
g = e.nodeType && Gt(e);
n.queue || (l = v._queueHooks(e, "fx"), l.unqueued == null && (l.unqueued = 0, c = l.empty.fire, l.empty.fire = function() {
l.unqueued || c()
}), l.unqueued++, h.always(function() {
h.always(function() {
l.unqueued--, v.queue(e, "fx").length || l.empty.fire()
})
})), e.nodeType === 1 && ("height" in t || "width" in t) && (n.overflow = [p.overflow, p.overflowX, p.overflowY], v.css(e, "display") === "inline" && v.css(e, "float") === "none" && (!v.support.inlineBlockNeedsLayout || nn(e.nodeName) === "inline" ? p.display = "inline-block" : p.zoom = 1)), n.overflow && (p.overflow = "hidden", v.support.shrinkWrapBlocks || h.done(function() {
p.overflow = n.overflow[0], p.overflowX = n.overflow[1], p.overflowY = n.overflow[2]
}));
for (r in t) {
s = t[r];
if (Un.exec(s)) {
delete t[r], a = a || s === "toggle";
if (s === (g ? "hide" : "show")) continue;
m.push(r)
}
}
o = m.length;
if (o) {
u = v._data(e, "fxshow") || v._data(e, "fxshow", {}), "hidden" in u && (g = u.hidden), a && (u.hidden = !g), g ? v(e).show() : h.done(function() {
v(e).hide()
}), h.done(function() {
var t;
v.removeData(e, "fxshow", !0);
for (t in d) v.style(e, t, d[t])
});
for (r = 0; r < o; r++) i = m[r], f = h.createTween(i, g ? u[i] : 0), d[i] = u[i] || v.style(e, i), i in u || (u[i] = f.start, g && (f.end = f.start, f.start = i === "width" || i === "height" ? 1 : 0))
}
}
function Yn(e, t, n, r, i) {
return new Yn.prototype.init(e, t, n, r, i)
}
function Zn(e, t) {
var n, r = {
height: e
},
i = 0;
t = t ? 1 : 0;
for (; i < 4; i += 2 - t) n = $t[i], r["margin" + n] = r["padding" + n] = e;
return t && (r.opacity = r.width = e), r
}
function tr(e) {
return v.isWindow(e) ? e : e.nodeType === 9 ? e.defaultView || e.parentWindow : !1
}
var n, r, i = e.document,
s = e.location,
o = e.navigator,
u = e.jQuery,
a = e.$,
f = Array.prototype.push,
l = Array.prototype.slice,
c = Array.prototype.indexOf,
h = Object.prototype.toString,
p = Object.prototype.hasOwnProperty,
d = String.prototype.trim,
v = function(e, t) {
return new v.fn.init(e, t, n)
},
m = /[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source,
g = /\S/,
y = /\s+/,
b = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,
w = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,
E = /^<(\w+)\s*\/?>(?:<\/\1>|)$/,
S = /^[\],:{}\s]*$/,
x = /(?:^|:|,)(?:\s*\[)+/g,
T = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,
N = /"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g,
C = /^-ms-/,
k = /-([\da-z])/gi,
L = function(e, t) {
return (t + "").toUpperCase()
},
A = function() {
i.addEventListener ? (i.removeEventListener("DOMContentLoaded", A, !1), v.ready()) : i.readyState === "complete" && (i.detachEvent("onreadystatechange", A), v.ready())
},
O = {};
v.fn = v.prototype = {
constructor: v,
init: function(e, n, r) {
var s, o, u, a;
if (!e) return this;
if (e.nodeType) return this.context = this[0] = e, this.length = 1, this;
if (typeof e == "string") {
e.charAt(0) === "<" && e.charAt(e.length - 1) === ">" && e.length >= 3 ? s = [null, e, null] : s = w.exec(e);
if (s && (s[1] || !n)) {
if (s[1]) return n = n instanceof v ? n[0] : n, a = n && n.nodeType ? n.ownerDocument || n : i, e = v.parseHTML(s[1], a, !0), E.test(s[1]) && v.isPlainObject(n) && this.attr.call(e, n, !0), v.merge(this, e);
o = i.getElementById(s[2]);
if (o && o.parentNode) {
if (o.id !== s[2]) return r.find(e);
this.length = 1, this[0] = o
}
return this.context = i, this.selector = e, this
}
return !n || n.jquery ? (n || r).find(e) : this.constructor(n).find(e)
}
return v.isFunction(e) ? r.ready(e) : (e.selector !== t && (this.selector = e.selector, this.context = e.context), v.makeArray(e, this))
},
selector: "",
jquery: "1.8.3",
length: 0,
size: function() {
return this.length
},
toArray: function() {
return l.call(this)
},
get: function(e) {
return e == null ? this.toArray() : e < 0 ? this[this.length + e] : this[e]
},
pushStack: function(e, t, n) {
var r = v.merge(this.constructor(), e);
return r.prevObject = this, r.context = this.context, t === "find" ? r.selector = this.selector + (this.selector ? " " : "") + n : t && (r.selector = this.selector + "." + t + "(" + n + ")"), r
},
each: function(e, t) {
return v.each(this, e, t)
},
ready: function(e) {
return v.ready.promise().done(e), this
},
eq: function(e) {
return e = +e, e === -1 ? this.slice(e) : this.slice(e, e + 1)
},
first: function() {
return this.eq(0)
},
last: function() {
return this.eq(-1)
},
slice: function() {
return this.pushStack(l.apply(this, arguments), "slice", l.call(arguments).join(","))
},
map: function(e) {
return this.pushStack(v.map(this, function(t, n) {
return e.call(t, n, t)
}))
},
end: function() {
return this.prevObject || this.constructor(null)
},
push: f,
sort: [].sort,
splice: [].splice
}, v.fn.init.prototype = v.fn, v.extend = v.fn.extend = function() {
var e, n, r, i, s, o, u = arguments[0] || {},
a = 1,
f = arguments.length,
l = !1;
typeof u == "boolean" && (l = u, u = arguments[1] || {}, a = 2), typeof u != "object" && !v.isFunction(u) && (u = {}), f === a && (u = this, --a);
for (; a < f; a++)
if ((e = arguments[a]) != null)
for (n in e) {
r = u[n], i = e[n];
if (u === i) continue;
l && i && (v.isPlainObject(i) || (s = v.isArray(i))) ? (s ? (s = !1, o = r && v.isArray(r) ? r : []) : o = r && v.isPlainObject(r) ? r : {}, u[n] = v.extend(l, o, i)) : i !== t && (u[n] = i)
}
return u
}, v.extend({
noConflict: function(t) {
return e.$ === v && (e.$ = a), t && e.jQuery === v && (e.jQuery = u), v
},
isReady: !1,
readyWait: 1,
holdReady: function(e) {
e ? v.readyWait++ : v.ready(!0)
},
ready: function(e) {
if (e === !0 ? --v.readyWait : v.isReady) return;
if (!i.body) return setTimeout(v.ready, 1);
v.isReady = !0;
if (e !== !0 && --v.readyWait > 0) return;
r.resolveWith(i, [v]), v.fn.trigger && v(i).trigger("ready").off("ready")
},
isFunction: function(e) {
return v.type(e) === "function"
},
isArray: Array.isArray || function(e) {
return v.type(e) === "array"
},
isWindow: function(e) {
return e != null && e == e.window
},
isNumeric: function(e) {
return !isNaN(parseFloat(e)) && isFinite(e)
},
type: function(e) {
return e == null ? String(e) : O[h.call(e)] || "object"
},
isPlainObject: function(e) {
if (!e || v.type(e) !== "object" || e.nodeType || v.isWindow(e)) return !1;
try {
if (e.constructor && !p.call(e, "constructor") && !p.call(e.constructor.prototype, "isPrototypeOf")) return !1
} catch (n) {
return !1
}
var r;
for (r in e);
return r === t || p.call(e, r)
},
isEmptyObject: function(e) {
var t;
for (t in e) return !1;
return !0
},
error: function(e) {
throw new Error(e)
},
parseHTML: function(e, t, n) {
var r;
return !e || typeof e != "string" ? null : (typeof t == "boolean" && (n = t, t = 0), t = t || i, (r = E.exec(e)) ? [t.createElement(r[1])] : (r = v.buildFragment([e], t, n ? null : []), v.merge([], (r.cacheable ? v.clone(r.fragment) : r.fragment).childNodes)))
},
parseJSON: function(t) {
if (!t || typeof t != "string") return null;
t = v.trim(t);
if (e.JSON && e.JSON.parse) return e.JSON.parse(t);
if (S.test(t.replace(T, "@").replace(N, "]").replace(x, ""))) return (new Function("return " + t))();
v.error("Invalid JSON: " + t)
},
parseXML: function(n) {
var r, i;
if (!n || typeof n != "string") return null;
try {
e.DOMParser ? (i = new DOMParser, r = i.parseFromString(n, "text/xml")) : (r = new ActiveXObject("Microsoft.XMLDOM"), r.async = "false", r.loadXML(n))
} catch (s) {
r = t
}
return (!r || !r.documentElement || r.getElementsByTagName("parsererror").length) && v.error("Invalid XML: " + n), r
},
noop: function() {},
globalEval: function(t) {
t && g.test(t) && (e.execScript || function(t) {
e.eval.call(e, t)
})(t)
},
camelCase: function(e) {
return e.replace(C, "ms-").replace(k, L)
},
nodeName: function(e, t) {
return e.nodeName && e.nodeName.toLowerCase() === t.toLowerCase()
},
each: function(e, n, r) {
var i, s = 0,
o = e.length,
u = o === t || v.isFunction(e);
if (r) {
if (u) {
for (i in e)
if (n.apply(e[i], r) === !1) break
} else
for (; s < o;)
if (n.apply(e[s++], r) === !1) break
} else if (u) {
for (i in e)
if (n.call(e[i], i, e[i]) === !1) break
} else
for (; s < o;)
if (n.call(e[s], s, e[s++]) === !1) break; return e
},
trim: d && !d.call(" ") ? function(e) {
return e == null ? "" : d.call(e)
} : function(e) {
return e == null ? "" : (e + "").replace(b, "")
},
makeArray: function(e, t) {
var n, r = t || [];
return e != null && (n = v.type(e), e.length == null || n === "string" || n === "function" || n === "regexp" || v.isWindow(e) ? f.call(r, e) : v.merge(r, e)), r
},
inArray: function(e, t, n) {
var r;
if (t) {
if (c) return c.call(t, e, n);
r = t.length, n = n ? n < 0 ? Math.max(0, r + n) : n : 0;
for (; n < r; n++)
if (n in t && t[n] === e) return n
}
return -1
},
merge: function(e, n) {
var r = n.length,
i = e.length,
s = 0;
if (typeof r == "number")
for (; s < r; s++) e[i++] = n[s];
else
while (n[s] !== t) e[i++] = n[s++];
return e.length = i, e
},
grep: function(e, t, n) {
var r, i = [],
s = 0,
o = e.length;
n = !!n;
for (; s < o; s++) r = !!t(e[s], s), n !== r && i.push(e[s]);
return i
},
map: function(e, n, r) {
var i, s, o = [],
u = 0,
a = e.length,
f = e instanceof v || a !== t && typeof a == "number" && (a > 0 && e[0] && e[a - 1] || a === 0 || v.isArray(e));
if (f)
for (; u < a; u++) i = n(e[u], u, r), i != null && (o[o.length] = i);
else
for (s in e) i = n(e[s], s, r), i != null && (o[o.length] = i);
return o.concat.apply([], o)
},
guid: 1,
proxy: function(e, n) {
var r, i, s;
return typeof n == "string" && (r = e[n], n = e, e = r), v.isFunction(e) ? (i = l.call(arguments, 2), s = function() {
return e.apply(n, i.concat(l.call(arguments)))
}, s.guid = e.guid = e.guid || v.guid++, s) : t
},
access: function(e, n, r, i, s, o, u) {
var a, f = r == null,
l = 0,
c = e.length;
if (r && typeof r == "object") {
for (l in r) v.access(e, n, l, r[l], 1, o, i);
s = 1
} else if (i !== t) {
a = u === t && v.isFunction(i), f && (a ? (a = n, n = function(e, t, n) {
return a.call(v(e), n)
}) : (n.call(e, i), n = null));
if (n)
for (; l < c; l++) n(e[l], r, a ? i.call(e[l], l, n(e[l], r)) : i, u);
s = 1
}
return s ? e : f ? n.call(e) : c ? n(e[0], r) : o
},
now: function() {
return (new Date).getTime()
}
}), v.ready.promise = function(t) {
if (!r) {
r = v.Deferred();
if (i.readyState === "complete") setTimeout(v.ready, 1);
else if (i.addEventListener) i.addEventListener("DOMContentLoaded", A, !1), e.addEventListener("load", v.ready, !1);
else {
i.attachEvent("onreadystatechange", A), e.attachEvent("onload", v.ready);
var n = !1;
try {
n = e.frameElement == null && i.documentElement
} catch (s) {}
n && n.doScroll && function o() {
if (!v.isReady) {
try {
n.doScroll("left")
} catch (e) {
return setTimeout(o, 50)
}
v.ready()
}
}()
}
}
return r.promise(t)
}, v.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(e, t) {
O["[object " + t + "]"] = t.toLowerCase()
}), n = v(i);
var M = {};
v.Callbacks = function(e) {
e = typeof e == "string" ? M[e] || _(e) : v.extend({}, e);
var n, r, i, s, o, u, a = [],
f = !e.once && [],
l = function(t) {
n = e.memory && t, r = !0, u = s || 0, s = 0, o = a.length, i = !0;
for (; a && u < o; u++)
if (a[u].apply(t[0], t[1]) === !1 && e.stopOnFalse) {
n = !1;
break
}
i = !1, a && (f ? f.length && l(f.shift()) : n ? a = [] : c.disable())
},
c = {
add: function() {
if (a) {
var t = a.length;
(function r(t) {
v.each(t, function(t, n) {
var i = v.type(n);
i === "function" ? (!e.unique || !c.has(n)) && a.push(n) : n && n.length && i !== "string" && r(n)
})
})(arguments), i ? o = a.length : n && (s = t, l(n))
}
return this
},
remove: function() {
return a && v.each(arguments, function(e, t) {
var n;
while ((n = v.inArray(t, a, n)) > -1) a.splice(n, 1), i && (n <= o && o--, n <= u && u--)
}), this
},
has: function(e) {
return v.inArray(e, a) > -1
},
empty: function() {
return a = [], this
},
disable: function() {
return a = f = n = t, this
},
disabled: function() {
return !a
},
lock: function() {
return f = t, n || c.disable(), this
},
locked: function() {
return !f
},
fireWith: function(e, t) {
return t = t || [], t = [e, t.slice ? t.slice() : t], a && (!r || f) && (i ? f.push(t) : l(t)), this
},
fire: function() {
return c.fireWith(this, arguments), this
},
fired: function() {
return !!r
}
};
return c
}, v.extend({
Deferred: function(e) {
var t = [
["resolve", "done", v.Callbacks("once memory"), "resolved"],
["reject", "fail", v.Callbacks("once memory"), "rejected"],
["notify", "progress", v.Callbacks("memory")]
],
n = "pending",
r = {
state: function() {
return n
},
always: function() {
return i.done(arguments).fail(arguments), this
},
then: function() {
var e = arguments;
return v.Deferred(function(n) {
v.each(t, function(t, r) {
var s = r[0],
o = e[t];
i[r[1]](v.isFunction(o) ? function() {
var e = o.apply(this, arguments);
e && v.isFunction(e.promise) ? e.promise().done(n.resolve).fail(n.reject).progress(n.notify) : n[s + "With"](this === i ? n : this, [e])
} : n[s])
}), e = null
}).promise()
},
promise: function(e) {
return e != null ? v.extend(e, r) : r
}
},
i = {};
return r.pipe = r.then, v.each(t, function(e, s) {
var o = s[2],
u = s[3];
r[s[1]] = o.add, u && o.add(function() {
n = u
}, t[e ^ 1][2].disable, t[2][2].lock), i[s[0]] = o.fire, i[s[0] + "With"] = o.fireWith
}), r.promise(i), e && e.call(i, i), i
},
when: function(e) {
var t = 0,
n = l.call(arguments),
r = n.length,
i = r !== 1 || e && v.isFunction(e.promise) ? r : 0,
s = i === 1 ? e : v.Deferred(),
o = function(e, t, n) {
return function(r) {
t[e] = this, n[e] = arguments.length > 1 ? l.call(arguments) : r, n === u ? s.notifyWith(t, n) : --i || s.resolveWith(t, n)
}
},
u, a, f;
if (r > 1) {
u = new Array(r), a = new Array(r), f = new Array(r);
for (; t < r; t++) n[t] && v.isFunction(n[t].promise) ? n[t].promise().done(o(t, f, n)).fail(s.reject).progress(o(t, a, u)) : --i
}
return i || s.resolveWith(f, n), s.promise()
}
}), v.support = function() {
var t, n, r, s, o, u, a, f, l, c, h, p = i.createElement("div");
p.setAttribute("className", "t"), p.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>", n = p.getElementsByTagName("*"), r = p.getElementsByTagName("a")[0];
if (!n || !r || !n.length) return {};
s = i.createElement("select"), o = s.appendChild(i.createElement("option")), u = p.getElementsByTagName("input")[0], r.style.cssText = "top:1px;float:left;opacity:.5", t = {
leadingWhitespace: p.firstChild.nodeType === 3,
tbody: !p.getElementsByTagName("tbody").length,
htmlSerialize: !!p.getElementsByTagName("link").length,
style: /top/.test(r.getAttribute("style")),
hrefNormalized: r.getAttribute("href") === "/a",
opacity: /^0.5/.test(r.style.opacity),
cssFloat: !!r.style.cssFloat,
checkOn: u.value === "on",
optSelected: o.selected,
getSetAttribute: p.className !== "t",
enctype: !!i.createElement("form").enctype,
html5Clone: i.createElement("nav").cloneNode(!0).outerHTML !== "<:nav></:nav>",
boxModel: i.compatMode === "CSS1Compat",
submitBubbles: !0,
changeBubbles: !0,
focusinBubbles: !1,
deleteExpando: !0,
noCloneEvent: !0,
inlineBlockNeedsLayout: !1,
shrinkWrapBlocks: !1,
reliableMarginRight: !0,
boxSizingReliable: !0,
pixelPosition: !1
}, u.checked = !0, t.noCloneChecked = u.cloneNode(!0).checked, s.disabled = !0, t.optDisabled = !o.disabled;
try {
delete p.test
} catch (d) {
t.deleteExpando = !1
}!p.addEventListener && p.attachEvent && p.fireEvent && (p.attachEvent("onclick", h = function() {
t.noCloneEvent = !1
}), p.cloneNode(!0).fireEvent("onclick"), p.detachEvent("onclick", h)), u = i.createElement("input"), u.value = "t", u.setAttribute("type", "radio"), t.radioValue = u.value === "t", u.setAttribute("checked", "checked"), u.setAttribute("name", "t"), p.appendChild(u), a = i.createDocumentFragment(), a.appendChild(p.lastChild), t.checkClone = a.cloneNode(!0).cloneNode(!0).lastChild.checked, t.appendChecked = u.checked, a.removeChild(u), a.appendChild(p);
if (p.attachEvent)
for (l in {
submit: !0,
change: !0,
focusin: !0
}) f = "on" + l, c = f in p, c || (p.setAttribute(f, "return;"), c = typeof p[f] == "function"), t[l + "Bubbles"] = c;
return v(function() {
var n, r, s, o, u = "padding:0;margin:0;border:0;display:block;overflow:hidden;",
a = i.getElementsByTagName("body")[0];
if (!a) return;
n = i.createElement("div"), n.style.cssText = "visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px", a.insertBefore(n, a.firstChild), r = i.createElement("div"), n.appendChild(r), r.innerHTML = "<table><tr><td></td><td>t</td></tr></table>", s = r.getElementsByTagName("td"), s[0].style.cssText = "padding:0;margin:0;border:0;display:none", c = s[0].offsetHeight === 0, s[0].style.display = "", s[1].style.display = "none", t.reliableHiddenOffsets = c && s[0].offsetHeight === 0, r.innerHTML = "", r.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;", t.boxSizing = r.offsetWidth === 4, t.doesNotIncludeMarginInBodyOffset = a.offsetTop !== 1, e.getComputedStyle && (t.pixelPosition = (e.getComputedStyle(r, null) || {}).top !== "1%", t.boxSizingReliable = (e.getComputedStyle(r, null) || {
width: "4px"
}).width === "4px", o = i.createElement("div"), o.style.cssText = r.style.cssText = u, o.style.marginRight = o.style.width = "0", r.style.width = "1px", r.appendChild(o), t.reliableMarginRight = !parseFloat((e.getComputedStyle(o, null) || {}).marginRight)), typeof r.style.zoom != "undefined" && (r.innerHTML = "", r.style.cssText = u + "width:1px;padding:1px;display:inline;zoom:1", t.inlineBlockNeedsLayout = r.offsetWidth === 3, r.style.display = "block", r.style.overflow = "visible", r.innerHTML = "<div></div>", r.firstChild.style.width = "5px", t.shrinkWrapBlocks = r.offsetWidth !== 3, n.style.zoom = 1), a.removeChild(n), n = r = s = o = null
}), a.removeChild(p), n = r = s = o = u = a = p = null, t
}();
var D = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/,
P = /([A-Z])/g;
v.extend({
cache: {},
deletedIds: [],
uuid: 0,
expando: "jQuery" + (v.fn.jquery + Math.random()).replace(/\D/g, ""),
noData: {
embed: !0,
object: "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",
applet: !0
},
hasData: function(e) {
return e = e.nodeType ? v.cache[e[v.expando]] : e[v.expando], !!e && !B(e)
},
data: function(e, n, r, i) {
if (!v.acceptData(e)) return;
var s, o, u = v.expando,
a = typeof n == "string",
f = e.nodeType,
l = f ? v.cache : e,
c = f ? e[u] : e[u] && u;
if ((!c || !l[c] || !i && !l[c].data) && a && r === t) return;
c || (f ? e[u] = c = v.deletedIds.pop() || v.guid++ : c = u), l[c] || (l[c] = {}, f || (l[c].toJSON = v.noop));
if (typeof n == "object" || typeof n == "function") i ? l[c] = v.extend(l[c], n) : l[c].data = v.extend(l[c].data, n);
return s = l[c], i || (s.data || (s.data = {}), s = s.data), r !== t && (s[v.camelCase(n)] = r), a ? (o = s[n], o == null && (o = s[v.camelCase(n)])) : o = s, o
},
removeData: function(e, t, n) {
if (!v.acceptData(e)) return;
var r, i, s, o = e.nodeType,
u = o ? v.cache : e,
a = o ? e[v.expando] : v.expando;
if (!u[a]) return;
if (t) {
r = n ? u[a] : u[a].data;
if (r) {
v.isArray(t) || (t in r ? t = [t] : (t = v.camelCase(t), t in r ? t = [t] : t = t.split(" ")));
for (i = 0, s = t.length; i < s; i++) delete r[t[i]];
if (!(n ? B : v.isEmptyObject)(r)) return
}
}
if (!n) {
delete u[a].data;
if (!B(u[a])) return
}
o ? v.cleanData([e], !0) : v.support.deleteExpando || u != u.window ? delete u[a] : u[a] = null
},
_data: function(e, t, n) {
return v.data(e, t, n, !0)
},
acceptData: function(e) {
var t = e.nodeName && v.noData[e.nodeName.toLowerCase()];
return !t || t !== !0 && e.getAttribute("classid") === t
}
}), v.fn.extend({
data: function(e, n) {
var r, i, s, o, u, a = this[0],
f = 0,
l = null;
if (e === t) {
if (this.length) {
l = v.data(a);
if (a.nodeType === 1 && !v._data(a, "parsedAttrs")) {
s = a.attributes;
for (u = s.length; f < u; f++) o = s[f].name, o.indexOf("data-") || (o = v.camelCase(o.substring(5)), H(a, o, l[o]));
v._data(a, "parsedAttrs", !0)
}
}
return l
}
return typeof e == "object" ? this.each(function() {
v.data(this, e)
}) : (r = e.split(".", 2), r[1] = r[1] ? "." + r[1] : "", i = r[1] + "!", v.access(this, function(n) {
if (n === t) return l = this.triggerHandler("getData" + i, [r[0]]), l === t && a && (l = v.data(a, e), l = H(a, e, l)), l === t && r[1] ? this.data(r[0]) : l;
r[1] = n, this.each(function() {
var t = v(this);
t.triggerHandler("setData" + i, r), v.data(this, e, n), t.triggerHandler("changeData" + i, r)
})
}, null, n, arguments.length > 1, null, !1))
},
removeData: function(e) {
return this.each(function() {
v.removeData(this, e)
})
}
}), v.extend({
queue: function(e, t, n) {
var r;
if (e) return t = (t || "fx") + "queue", r = v._data(e, t), n && (!r || v.isArray(n) ? r = v._data(e, t, v.makeArray(n)) : r.push(n)), r || []
},
dequeue: function(e, t) {
t = t || "fx";
var n = v.queue(e, t),
r = n.length,
i = n.shift(),
s = v._queueHooks(e, t),
o = function() {
v.dequeue(e, t)
};
i === "inprogress" && (i = n.shift(), r--), i && (t === "fx" && n.unshift("inprogress"), delete s.stop, i.call(e, o, s)), !r && s && s.empty.fire()
},
_queueHooks: function(e, t) {
var n = t + "queueHooks";
return v._data(e, n) || v._data(e, n, {
empty: v.Callbacks("once memory").add(function() {
v.removeData(e, t + "queue", !0), v.removeData(e, n, !0)
})
})
}
}), v.fn.extend({
queue: function(e, n) {
var r = 2;
return typeof e != "string" && (n = e, e = "fx", r--), arguments.length < r ? v.queue(this[0], e) : n === t ? this : this.each(function() {
var t = v.queue(this, e, n);
v._queueHooks(this, e), e === "fx" && t[0] !== "inprogress" && v.dequeue(this, e)
})
},
dequeue: function(e) {
return this.each(function() {
v.dequeue(this, e)
})
},
delay: function(e, t) {
return e = v.fx ? v.fx.speeds[e] || e : e, t = t || "fx", this.queue(t, function(t, n) {
var r = setTimeout(t, e);
n.stop = function() {
clearTimeout(r)
}
})
},
clearQueue: function(e) {
return this.queue(e || "fx", [])
},
promise: function(e, n) {
var r, i = 1,
s = v.Deferred(),
o = this,
u = this.length,
a = function() {
--i || s.resolveWith(o, [o])
};
typeof e != "string" && (n = e, e = t), e = e || "fx";
while (u--) r = v._data(o[u], e + "queueHooks"), r && r.empty && (i++, r.empty.add(a));
return a(), s.promise(n)
}
});
var j, F, I, q = /[\t\r\n]/g,
R = /\r/g,
U = /^(?:button|input)$/i,
z = /^(?:button|input|object|select|textarea)$/i,
W = /^a(?:rea|)$/i,
X = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,
V = v.support.getSetAttribute;
v.fn.extend({
attr: function(e, t) {
return v.access(this, v.attr, e, t, arguments.length > 1)
},
removeAttr: function(e) {
return this.each(function() {
v.removeAttr(this, e)
})
},
prop: function(e, t) {
return v.access(this, v.prop, e, t, arguments.length > 1)
},
removeProp: function(e) {
return e = v.propFix[e] || e, this.each(function() {
try {
this[e] = t, delete this[e]
} catch (n) {}
})
},
addClass: function(e) {
var t, n, r, i, s, o, u;
if (v.isFunction(e)) return this.each(function(t) {
v(this).addClass(e.call(this, t, this.className))
});
if (e && typeof e == "string") {
t = e.split(y);
for (n = 0, r = this.length; n < r; n++) {
i = this[n];
if (i.nodeType === 1)
if (!i.className && t.length === 1) i.className = e;
else {
s = " " + i.className + " ";
for (o = 0, u = t.length; o < u; o++) s.indexOf(" " + t[o] + " ") < 0 && (s += t[o] + " ");
i.className = v.trim(s)
}
}
}
return this
},
removeClass: function(e) {
var n, r, i, s, o, u, a;
if (v.isFunction(e)) return this.each(function(t) {
v(this).removeClass(e.call(this, t, this.className))
});
if (e && typeof e == "string" || e === t) {
n = (e || "").split(y);
for (u = 0, a = this.length; u < a; u++) {
i = this[u];
if (i.nodeType === 1 && i.className) {
r = (" " + i.className + " ").replace(q, " ");
for (s = 0, o = n.length; s < o; s++)
while (r.indexOf(" " + n[s] + " ") >= 0) r = r.replace(" " + n[s] + " ", " ");
i.className = e ? v.trim(r) : ""
}
}
}
return this
},
toggleClass: function(e, t) {
var n = typeof e,
r = typeof t == "boolean";
return v.isFunction(e) ? this.each(function(n) {
v(this).toggleClass(e.call(this, n, this.className, t), t)
}) : this.each(function() {
if (n === "string") {
var i, s = 0,
o = v(this),
u = t,
a = e.split(y);
while (i = a[s++]) u = r ? u : !o.hasClass(i), o[u ? "addClass" : "removeClass"](i)
} else if (n === "undefined" || n === "boolean") this.className && v._data(this, "__className__", this.className), this.className = this.className || e === !1 ? "" : v._data(this, "__className__") || ""
})
},
hasClass: function(e) {
var t = " " + e + " ",
n = 0,
r = this.length;
for (; n < r; n++)
if (this[n].nodeType === 1 && (" " + this[n].className + " ").replace(q, " ").indexOf(t) >= 0) return !0;
return !1
},
val: function(e) {
var n, r, i, s = this[0];
if (!arguments.length) {
if (s) return n = v.valHooks[s.type] || v.valHooks[s.nodeName.toLowerCase()], n && "get" in n && (r = n.get(s, "value")) !== t ? r : (r = s.value, typeof r == "string" ? r.replace(R, "") : r == null ? "" : r);
return
}
return i = v.isFunction(e), this.each(function(r) {
var s, o = v(this);
if (this.nodeType !== 1) return;
i ? s = e.call(this, r, o.val()) : s = e, s == null ? s = "" : typeof s == "number" ? s += "" : v.isArray(s) && (s = v.map(s, function(e) {
return e == null ? "" : e + ""
})), n = v.valHooks[this.type] || v.valHooks[this.nodeName.toLowerCase()];
if (!n || !("set" in n) || n.set(this, s, "value") === t) this.value = s
})
}
}), v.extend({
valHooks: {
option: {
get: function(e) {
var t = e.attributes.value;
return !t || t.specified ? e.value : e.text
}
},
select: {
get: function(e) {
var t, n, r = e.options,
i = e.selectedIndex,
s = e.type === "select-one" || i < 0,
o = s ? null : [],
u = s ? i + 1 : r.length,
a = i < 0 ? u : s ? i : 0;
for (; a < u; a++) {
n = r[a];
if ((n.selected || a === i) && (v.support.optDisabled ? !n.disabled : n.getAttribute("disabled") === null) && (!n.parentNode.disabled || !v.nodeName(n.parentNode, "optgroup"))) {
t = v(n).val();
if (s) return t;
o.push(t)
}
}
return o
},
set: function(e, t) {
var n = v.makeArray(t);
return v(e).find("option").each(function() {
this.selected = v.inArray(v(this).val(), n) >= 0
}), n.length || (e.selectedIndex = -1), n
}
}
},
attrFn: {},
attr: function(e, n, r, i) {
var s, o, u, a = e.nodeType;
if (!e || a === 3 || a === 8 || a === 2) return;
if (i && v.isFunction(v.fn[n])) return v(e)[n](r);
if (typeof e.getAttribute == "undefined") return v.prop(e, n, r);
u = a !== 1 || !v.isXMLDoc(e), u && (n = n.toLowerCase(), o = v.attrHooks[n] || (X.test(n) ? F : j));
if (r !== t) {
if (r === null) {
v.removeAttr(e, n);
return
}
return o && "set" in o && u && (s = o.set(e, r, n)) !== t ? s : (e.setAttribute(n, r + ""), r)
}
return o && "get" in o && u && (s = o.get(e, n)) !== null ? s : (s = e.getAttribute(n), s === null ? t : s)
},
removeAttr: function(e, t) {
var n, r, i, s, o = 0;
if (t && e.nodeType === 1) {
r = t.split(y);
for (; o < r.length; o++) i = r[o], i && (n = v.propFix[i] || i, s = X.test(i), s || v.attr(e, i, ""), e.removeAttribute(V ? i : n), s && n in e && (e[n] = !1))
}
},
attrHooks: {
type: {
set: function(e, t) {
if (U.test(e.nodeName) && e.parentNode) v.error("type property can't be changed");
else if (!v.support.radioValue && t === "radio" && v.nodeName(e, "input")) {
var n = e.value;
return e.setAttribute("type", t), n && (e.value = n), t
}
}
},
value: {
get: function(e, t) {
return j && v.nodeName(e, "button") ? j.get(e, t) : t in e ? e.value : null
},
set: function(e, t, n) {
if (j && v.nodeName(e, "button")) return j.set(e, t, n);
e.value = t
}
}
},
propFix: {
tabindex: "tabIndex",
readonly: "readOnly",
"for": "htmlFor",
"class": "className",
maxlength: "maxLength",
cellspacing: "cellSpacing",
cellpadding: "cellPadding",
rowspan: "rowSpan",
colspan: "colSpan",
usemap: "useMap",
frameborder: "frameBorder",
contenteditable: "contentEditable"
},
prop: function(e, n, r) {
var i, s, o, u = e.nodeType;
if (!e || u === 3 || u === 8 || u === 2) return;
return o = u !== 1 || !v.isXMLDoc(e), o && (n = v.propFix[n] || n, s = v.propHooks[n]), r !== t ? s && "set" in s && (i = s.set(e, r, n)) !== t ? i : e[n] = r : s && "get" in s && (i = s.get(e, n)) !== null ? i : e[n]
},
propHooks: {
tabIndex: {
get: function(e) {
var n = e.getAttributeNode("tabindex");
return n && n.specified ? parseInt(n.value, 10) : z.test(e.nodeName) || W.test(e.nodeName) && e.href ? 0 : t
}
}
}
}), F = {
get: function(e, n) {
var r, i = v.prop(e, n);
return i === !0 || typeof i != "boolean" && (r = e.getAttributeNode(n)) && r.nodeValue !== !1 ? n.toLowerCase() : t
},
set: function(e, t, n) {
var r;
return t === !1 ? v.removeAttr(e, n) : (r = v.propFix[n] || n, r in e && (e[r] = !0), e.setAttribute(n, n.toLowerCase())), n
}
}, V || (I = {
name: !0,
id: !0,
coords: !0
}, j = v.valHooks.button = {
get: function(e, n) {
var r;
return r = e.getAttributeNode(n), r && (I[n] ? r.value !== "" : r.specified) ? r.value : t
},
set: function(e, t, n) {
var r = e.getAttributeNode(n);
return r || (r = i.createAttribute(n), e.setAttributeNode(r)), r.value = t + ""
}
}, v.each(["width", "height"], function(e, t) {
v.attrHooks[t] = v.extend(v.attrHooks[t], {
set: function(e, n) {
if (n === "") return e.setAttribute(t, "auto"), n
}
})
}), v.attrHooks.contenteditable = {
get: j.get,
set: function(e, t, n) {
t === "" && (t = "false"), j.set(e, t, n)
}
}), v.support.hrefNormalized || v.each(["href", "src", "width", "height"], function(e, n) {
v.attrHooks[n] = v.extend(v.attrHooks[n], {
get: function(e) {
var r = e.getAttribute(n, 2);
return r === null ? t : r
}
})
}), v.support.style || (v.attrHooks.style = {
get: function(e) {
return e.style.cssText.toLowerCase() || t
},
set: function(e,
t) {
return e.style.cssText = t + ""
}
}), v.support.optSelected || (v.propHooks.selected = v.extend(v.propHooks.selected, {
get: function(e) {
var t = e.parentNode;
return t && (t.selectedIndex, t.parentNode && t.parentNode.selectedIndex), null
}
})), v.support.enctype || (v.propFix.enctype = "encoding"), v.support.checkOn || v.each(["radio", "checkbox"], function() {
v.valHooks[this] = {
get: function(e) {
return e.getAttribute("value") === null ? "on" : e.value
}
}
}), v.each(["radio", "checkbox"], function() {
v.valHooks[this] = v.extend(v.valHooks[this], {
set: function(e, t) {
if (v.isArray(t)) return e.checked = v.inArray(v(e).val(), t) >= 0
}
})
});
var $ = /^(?:textarea|input|select)$/i,
J = /^([^\.]*|)(?:\.(.+)|)$/,
K = /(?:^|\s)hover(\.\S+|)\b/,
Q = /^key/,
G = /^(?:mouse|contextmenu)|click/,
Y = /^(?:focusinfocus|focusoutblur)$/,
Z = function(e) {
return v.event.special.hover ? e : e.replace(K, "mouseenter$1 mouseleave$1")
};
v.event = {
add: function(e, n, r, i, s) {
var o, u, a, f, l, c, h, p, d, m, g;
if (e.nodeType === 3 || e.nodeType === 8 || !n || !r || !(o = v._data(e))) return;
r.handler && (d = r, r = d.handler, s = d.selector), r.guid || (r.guid = v.guid++), a = o.events, a || (o.events = a = {}), u = o.handle, u || (o.handle = u = function(e) {
return typeof v == "undefined" || !!e && v.event.triggered === e.type ? t : v.event.dispatch.apply(u.elem, arguments)
}, u.elem = e), n = v.trim(Z(n)).split(" ");
for (f = 0; f < n.length; f++) {
l = J.exec(n[f]) || [], c = l[1], h = (l[2] || "").split(".").sort(), g = v.event.special[c] || {}, c = (s ? g.delegateType : g.bindType) || c, g = v.event.special[c] || {}, p = v.extend({
type: c,
origType: l[1],
data: i,
handler: r,
guid: r.guid,
selector: s,
needsContext: s && v.expr.match.needsContext.test(s),
namespace: h.join(".")
}, d), m = a[c];
if (!m) {
m = a[c] = [], m.delegateCount = 0;
if (!g.setup || g.setup.call(e, i, h, u) === !1) e.addEventListener ? e.addEventListener(c, u, !1) : e.attachEvent && e.attachEvent("on" + c, u)
}
g.add && (g.add.call(e, p), p.handler.guid || (p.handler.guid = r.guid)), s ? m.splice(m.delegateCount++, 0, p) : m.push(p), v.event.global[c] = !0
}
e = null
},
global: {},
remove: function(e, t, n, r, i) {
var s, o, u, a, f, l, c, h, p, d, m, g = v.hasData(e) && v._data(e);
if (!g || !(h = g.events)) return;
t = v.trim(Z(t || "")).split(" ");
for (s = 0; s < t.length; s++) {
o = J.exec(t[s]) || [], u = a = o[1], f = o[2];
if (!u) {
for (u in h) v.event.remove(e, u + t[s], n, r, !0);
continue
}
p = v.event.special[u] || {}, u = (r ? p.delegateType : p.bindType) || u, d = h[u] || [], l = d.length, f = f ? new RegExp("(^|\\.)" + f.split(".").sort().join("\\.(?:.*\\.|)") + "(\\.|$)") : null;
for (c = 0; c < d.length; c++) m = d[c], (i || a === m.origType) && (!n || n.guid === m.guid) && (!f || f.test(m.namespace)) && (!r || r === m.selector || r === "**" && m.selector) && (d.splice(c--, 1), m.selector && d.delegateCount--, p.remove && p.remove.call(e, m));
d.length === 0 && l !== d.length && ((!p.teardown || p.teardown.call(e, f, g.handle) === !1) && v.removeEvent(e, u, g.handle), delete h[u])
}
v.isEmptyObject(h) && (delete g.handle, v.removeData(e, "events", !0))
},
customEvent: {
getData: !0,
setData: !0,
changeData: !0
},
trigger: function(n, r, s, o) {
if (!s || s.nodeType !== 3 && s.nodeType !== 8) {
var u, a, f, l, c, h, p, d, m, g, y = n.type || n,
b = [];
if (Y.test(y + v.event.triggered)) return;
y.indexOf("!") >= 0 && (y = y.slice(0, -1), a = !0), y.indexOf(".") >= 0 && (b = y.split("."), y = b.shift(), b.sort());
if ((!s || v.event.customEvent[y]) && !v.event.global[y]) return;
n = typeof n == "object" ? n[v.expando] ? n : new v.Event(y, n) : new v.Event(y), n.type = y, n.isTrigger = !0, n.exclusive = a, n.namespace = b.join("."), n.namespace_re = n.namespace ? new RegExp("(^|\\.)" + b.join("\\.(?:.*\\.|)") + "(\\.|$)") : null, h = y.indexOf(":") < 0 ? "on" + y : "";
if (!s) {
u = v.cache;
for (f in u) u[f].events && u[f].events[y] && v.event.trigger(n, r, u[f].handle.elem, !0);
return
}
n.result = t, n.target || (n.target = s), r = r != null ? v.makeArray(r) : [], r.unshift(n), p = v.event.special[y] || {};
if (p.trigger && p.trigger.apply(s, r) === !1) return;
m = [
[s, p.bindType || y]
];
if (!o && !p.noBubble && !v.isWindow(s)) {
g = p.delegateType || y, l = Y.test(g + y) ? s : s.parentNode;
for (c = s; l; l = l.parentNode) m.push([l, g]), c = l;
c === (s.ownerDocument || i) && m.push([c.defaultView || c.parentWindow || e, g])
}
for (f = 0; f < m.length && !n.isPropagationStopped(); f++) l = m[f][0], n.type = m[f][1], d = (v._data(l, "events") || {})[n.type] && v._data(l, "handle"), d && d.apply(l, r), d = h && l[h], d && v.acceptData(l) && d.apply && d.apply(l, r) === !1 && n.preventDefault();
return n.type = y, !o && !n.isDefaultPrevented() && (!p._default || p._default.apply(s.ownerDocument, r) === !1) && (y !== "click" || !v.nodeName(s, "a")) && v.acceptData(s) && h && s[y] && (y !== "focus" && y !== "blur" || n.target.offsetWidth !== 0) && !v.isWindow(s) && (c = s[h], c && (s[h] = null), v.event.triggered = y, s[y](), v.event.triggered = t, c && (s[h] = c)), n.result
}
return
},
dispatch: function(n) {
n = v.event.fix(n || e.event);
var r, i, s, o, u, a, f, c, h, p, d = (v._data(this, "events") || {})[n.type] || [],
m = d.delegateCount,
g = l.call(arguments),
y = !n.exclusive && !n.namespace,
b = v.event.special[n.type] || {},
w = [];
g[0] = n, n.delegateTarget = this;
if (b.preDispatch && b.preDispatch.call(this, n) === !1) return;
if (m && (!n.button || n.type !== "click"))
for (s = n.target; s != this; s = s.parentNode || this)
if (s.disabled !== !0 || n.type !== "click") {
u = {}, f = [];
for (r = 0; r < m; r++) c = d[r], h = c.selector, u[h] === t && (u[h] = c.needsContext ? v(h, this).index(s) >= 0 : v.find(h, this, null, [s]).length), u[h] && f.push(c);
f.length && w.push({
elem: s,
matches: f
})
}
d.length > m && w.push({
elem: this,
matches: d.slice(m)
});
for (r = 0; r < w.length && !n.isPropagationStopped(); r++) {
a = w[r], n.currentTarget = a.elem;
for (i = 0; i < a.matches.length && !n.isImmediatePropagationStopped(); i++) {
c = a.matches[i];
if (y || !n.namespace && !c.namespace || n.namespace_re && n.namespace_re.test(c.namespace)) n.data = c.data, n.handleObj = c, o = ((v.event.special[c.origType] || {}).handle || c.handler).apply(a.elem, g), o !== t && (n.result = o, o === !1 && (n.preventDefault(), n.stopPropagation()))
}
}
return b.postDispatch && b.postDispatch.call(this, n), n.result
},
props: "attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),
fixHooks: {},
keyHooks: {
props: "char charCode key keyCode".split(" "),
filter: function(e, t) {
return e.which == null && (e.which = t.charCode != null ? t.charCode : t.keyCode), e
}
},
mouseHooks: {
props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),
filter: function(e, n) {
var r, s, o, u = n.button,
a = n.fromElement;
return e.pageX == null && n.clientX != null && (r = e.target.ownerDocument || i, s = r.documentElement, o = r.body, e.pageX = n.clientX + (s && s.scrollLeft || o && o.scrollLeft || 0) - (s && s.clientLeft || o && o.clientLeft || 0), e.pageY = n.clientY + (s && s.scrollTop || o && o.scrollTop || 0) - (s && s.clientTop || o && o.clientTop || 0)), !e.relatedTarget && a && (e.relatedTarget = a === e.target ? n.toElement : a), !e.which && u !== t && (e.which = u & 1 ? 1 : u & 2 ? 3 : u & 4 ? 2 : 0), e
}
},
fix: function(e) {
if (e[v.expando]) return e;
var t, n, r = e,
s = v.event.fixHooks[e.type] || {},
o = s.props ? this.props.concat(s.props) : this.props;
e = v.Event(r);
for (t = o.length; t;) n = o[--t], e[n] = r[n];
return e.target || (e.target = r.srcElement || i), e.target.nodeType === 3 && (e.target = e.target.parentNode), e.metaKey = !!e.metaKey, s.filter ? s.filter(e, r) : e
},
special: {
load: {
noBubble: !0
},
focus: {
delegateType: "focusin"
},
blur: {
delegateType: "focusout"
},
beforeunload: {
setup: function(e, t, n) {
v.isWindow(this) && (this.onbeforeunload = n)
},
teardown: function(e, t) {
this.onbeforeunload === t && (this.onbeforeunload = null)
}
}
},
simulate: function(e, t, n, r) {
var i = v.extend(new v.Event, n, {
type: e,
isSimulated: !0,
originalEvent: {}
});
r ? v.event.trigger(i, null, t) : v.event.dispatch.call(t, i), i.isDefaultPrevented() && n.preventDefault()
}
}, v.event.handle = v.event.dispatch, v.removeEvent = i.removeEventListener ? function(e, t, n) {
e.removeEventListener && e.removeEventListener(t, n, !1)
} : function(e, t, n) {
var r = "on" + t;
e.detachEvent && (typeof e[r] == "undefined" && (e[r] = null), e.detachEvent(r, n))
}, v.Event = function(e, t) {
if (!(this instanceof v.Event)) return new v.Event(e, t);
e && e.type ? (this.originalEvent = e, this.type = e.type, this.isDefaultPrevented = e.defaultPrevented || e.returnValue === !1 || e.getPreventDefault && e.getPreventDefault() ? tt : et) : this.type = e, t && v.extend(this, t), this.timeStamp = e && e.timeStamp || v.now(), this[v.expando] = !0
}, v.Event.prototype = {
preventDefault: function() {
this.isDefaultPrevented = tt;
var e = this.originalEvent;
if (!e) return;
e.preventDefault ? e.preventDefault() : e.returnValue = !1
},
stopPropagation: function() {
this.isPropagationStopped = tt;
var e = this.originalEvent;
if (!e) return;
e.stopPropagation && e.stopPropagation(), e.cancelBubble = !0
},
stopImmediatePropagation: function() {
this.isImmediatePropagationStopped = tt, this.stopPropagation()
},
isDefaultPrevented: et,
isPropagationStopped: et,
isImmediatePropagationStopped: et
}, v.each({
mouseenter: "mouseover",
mouseleave: "mouseout"
}, function(e, t) {
v.event.special[e] = {
delegateType: t,
bindType: t,
handle: function(e) {
var n, r = this,
i = e.relatedTarget,
s = e.handleObj,
o = s.selector;
if (!i || i !== r && !v.contains(r, i)) e.type = s.origType, n = s.handler.apply(this, arguments), e.type = t;
return n
}
}
}), v.support.submitBubbles || (v.event.special.submit = {
setup: function() {
if (v.nodeName(this, "form")) return !1;
v.event.add(this, "click._submit keypress._submit", function(e) {
var n = e.target,
r = v.nodeName(n, "input") || v.nodeName(n, "button") ? n.form : t;
r && !v._data(r, "_submit_attached") && (v.event.add(r, "submit._submit", function(e) {
e._submit_bubble = !0
}), v._data(r, "_submit_attached", !0))
})
},
postDispatch: function(e) {
e._submit_bubble && (delete e._submit_bubble, this.parentNode && !e.isTrigger && v.event.simulate("submit", this.parentNode, e, !0))
},
teardown: function() {
if (v.nodeName(this, "form")) return !1;
v.event.remove(this, "._submit")
}
}), v.support.changeBubbles || (v.event.special.change = {
setup: function() {
if ($.test(this.nodeName)) {
if (this.type === "checkbox" || this.type === "radio") v.event.add(this, "propertychange._change", function(e) {
e.originalEvent.propertyName === "checked" && (this._just_changed = !0)
}), v.event.add(this, "click._change", function(e) {
this._just_changed && !e.isTrigger && (this._just_changed = !1), v.event.simulate("change", this, e, !0)
});
return !1
}
v.event.add(this, "beforeactivate._change", function(e) {
var t = e.target;
$.test(t.nodeName) && !v._data(t, "_change_attached") && (v.event.add(t, "change._change", function(e) {
this.parentNode && !e.isSimulated && !e.isTrigger && v.event.simulate("change", this.parentNode, e, !0)
}), v._data(t, "_change_attached", !0))
})
},
handle: function(e) {
var t = e.target;
if (this !== t || e.isSimulated || e.isTrigger || t.type !== "radio" && t.type !== "checkbox") return e.handleObj.handler.apply(this, arguments)
},
teardown: function() {
return v.event.remove(this, "._change"), !$.test(this.nodeName)
}
}), v.support.focusinBubbles || v.each({
focus: "focusin",
blur: "focusout"
}, function(e, t) {
var n = 0,
r = function(e) {
v.event.simulate(t, e.target, v.event.fix(e), !0)
};
v.event.special[t] = {
setup: function() {
n++ === 0 && i.addEventListener(e, r, !0)
},
teardown: function() {
--n === 0 && i.removeEventListener(e, r, !0)
}
}
}), v.fn.extend({
on: function(e, n, r, i, s) {
var o, u;
if (typeof e == "object") {
typeof n != "string" && (r = r || n, n = t);
for (u in e) this.on(u, n, r, e[u], s);
return this
}
r == null && i == null ? (i = n, r = n = t) : i == null && (typeof n == "string" ? (i = r, r = t) : (i = r, r = n, n = t));
if (i === !1) i = et;
else if (!i) return this;
return s === 1 && (o = i, i = function(e) {
return v().off(e), o.apply(this, arguments)
}, i.guid = o.guid || (o.guid = v.guid++)), this.each(function() {
v.event.add(this, e, i, r, n)
})
},
one: function(e, t, n, r) {
return this.on(e, t, n, r, 1)
},
off: function(e, n, r) {
var i, s;
if (e && e.preventDefault && e.handleObj) return i = e.handleObj, v(e.delegateTarget).off(i.namespace ? i.origType + "." + i.namespace : i.origType, i.selector, i.handler), this;
if (typeof e == "object") {
for (s in e) this.off(s, n, e[s]);
return this
}
if (n === !1 || typeof n == "function") r = n, n = t;
return r === !1 && (r = et), this.each(function() {
v.event.remove(this, e, r, n)
})
},
bind: function(e, t, n) {
return this.on(e, null, t, n)
},
unbind: function(e, t) {
return this.off(e, null, t)
},
live: function(e, t, n) {
return v(this.context).on(e, this.selector, t, n), this
},
die: function(e, t) {
return v(this.context).off(e, this.selector || "**", t), this
},
delegate: function(e, t, n, r) {
return this.on(t, e, n, r)
},
undelegate: function(e, t, n) {
return arguments.length === 1 ? this.off(e, "**") : this.off(t, e || "**", n)
},
trigger: function(e, t) {
return this.each(function() {
v.event.trigger(e, t, this)
})
},
triggerHandler: function(e, t) {
if (this[0]) return v.event.trigger(e, t, this[0], !0)
},
toggle: function(e) {
var t = arguments,
n = e.guid || v.guid++,
r = 0,
i = function(n) {
var i = (v._data(this, "lastToggle" + e.guid) || 0) % r;
return v._data(this, "lastToggle" + e.guid, i + 1), n.preventDefault(), t[i].apply(this, arguments) || !1
};
i.guid = n;
while (r < t.length) t[r++].guid = n;
return this.click(i)
},
hover: function(e, t) {
return this.mouseenter(e).mouseleave(t || e)
}
}), v.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "), function(e, t) {
v.fn[t] = function(e, n) {
return n == null && (n = e, e = null), arguments.length > 0 ? this.on(t, null, e, n) : this.trigger(t)
}, Q.test(t) && (v.event.fixHooks[t] = v.event.keyHooks), G.test(t) && (v.event.fixHooks[t] = v.event.mouseHooks)
}),
function(e, t) {
function nt(e, t, n, r) {
n = n || [], t = t || g;
var i, s, a, f, l = t.nodeType;
if (!e || typeof e != "string") return n;
if (l !== 1 && l !== 9) return [];
a = o(t);
if (!a && !r)
if (i = R.exec(e))
if (f = i[1]) {
if (l === 9) {
s = t.getElementById(f);
if (!s || !s.parentNode) return n;
if (s.id === f) return n.push(s), n
} else if (t.ownerDocument && (s = t.ownerDocument.getElementById(f)) && u(t, s) && s.id === f) return n.push(s), n
} else {
if (i[2]) return S.apply(n, x.call(t.getElementsByTagName(e), 0)), n;
if ((f = i[3]) && Z && t.getElementsByClassName) return S.apply(n, x.call(t.getElementsByClassName(f), 0)), n
}
return vt(e.replace(j, "$1"), t, n, r, a)
}
function rt(e) {
return function(t) {
var n = t.nodeName.toLowerCase();
return n === "input" && t.type === e
}
}
function it(e) {
return function(t) {
var n = t.nodeName.toLowerCase();
return (n === "input" || n === "button") && t.type === e
}
}
function st(e) {
return N(function(t) {
return t = +t, N(function(n, r) {
var i, s = e([], n.length, t),
o = s.length;
while (o--) n[i = s[o]] && (n[i] = !(r[i] = n[i]))
})
})
}
function ot(e, t, n) {
if (e === t) return n;
var r = e.nextSibling;
while (r) {
if (r === t) return -1;
r = r.nextSibling
}
return 1
}
function ut(e, t) {
var n, r, s, o, u, a, f, l = L[d][e + " "];
if (l) return t ? 0 : l.slice(0);
u = e, a = [], f = i.preFilter;
while (u) {
if (!n || (r = F.exec(u))) r && (u = u.slice(r[0].length) || u), a.push(s = []);
n = !1;
if (r = I.exec(u)) s.push(n = new m(r.shift())), u = u.slice(n.length), n.type = r[0].replace(j, " ");
for (o in i.filter)(r = J[o].exec(u)) && (!f[o] || (r = f[o](r))) && (s.push(n = new m(r.shift())), u = u.slice(n.length), n.type = o, n.matches = r);
if (!n) break
}
return t ? u.length : u ? nt.error(e) : L(e, a).slice(0)
}
function at(e, t, r) {
var i = t.dir,
s = r && t.dir === "parentNode",
o = w++;
return t.first ? function(t, n, r) {
while (t = t[i])
if (s || t.nodeType === 1) return e(t, n, r)
} : function(t, r, u) {
if (!u) {
var a, f = b + " " + o + " ",
l = f + n;
while (t = t[i])
if (s || t.nodeType === 1) {
if ((a = t[d]) === l) return t.sizset;
if (typeof a == "string" && a.indexOf(f) === 0) {
if (t.sizset) return t
} else {
t[d] = l;
if (e(t, r, u)) return t.sizset = !0, t;
t.sizset = !1
}
}
} else
while (t = t[i])
if (s || t.nodeType === 1)
if (e(t, r, u)) return t
}
}
function ft(e) {
return e.length > 1 ? function(t, n, r) {
var i = e.length;
while (i--)
if (!e[i](t, n, r)) return !1;
return !0
} : e[0]
}
function lt(e, t, n, r, i) {
var s, o = [],
u = 0,
a = e.length,
f = t != null;
for (; u < a; u++)
if (s = e[u])
if (!n || n(s, r, i)) o.push(s), f && t.push(u);
return o
}
function ct(e, t, n, r, i, s) {
return r && !r[d] && (r = ct(r)), i && !i[d] && (i = ct(i, s)), N(function(s, o, u, a) {
var f, l, c, h = [],
p = [],
d = o.length,
v = s || dt(t || "*", u.nodeType ? [u] : u, []),
m = e && (s || !t) ? lt(v, h, e, u, a) : v,
g = n ? i || (s ? e : d || r) ? [] : o : m;
n && n(m, g, u, a);
if (r) {
f = lt(g, p), r(f, [], u, a), l = f.length;
while (l--)
if (c = f[l]) g[p[l]] = !(m[p[l]] = c)
}
if (s) {
if (i || e) {
if (i) {
f = [], l = g.length;
while (l--)(c = g[l]) && f.push(m[l] = c);
i(null, g = [], f, a)
}
l = g.length;
while (l--)(c = g[l]) && (f = i ? T.call(s, c) : h[l]) > -1 && (s[f] = !(o[f] = c))
}
} else g = lt(g === o ? g.splice(d, g.length) : g), i ? i(null, o, g, a) : S.apply(o, g)
})
}
function ht(e) {
var t, n, r, s = e.length,
o = i.relative[e[0].type],
u = o || i.relative[" "],
a = o ? 1 : 0,
f = at(function(e) {
return e === t
}, u, !0),
l = at(function(e) {
return T.call(t, e) > -1
}, u, !0),
h = [function(e, n, r) {
return !o && (r || n !== c) || ((t = n).nodeType ? f(e, n, r) : l(e, n, r))
}];
for (; a < s; a++)
if (n = i.relative[e[a].type]) h = [at(ft(h), n)];
else {
n = i.filter[e[a].type].apply(null, e[a].matches);
if (n[d]) {
r = ++a;
for (; r < s; r++)
if (i.relative[e[r].type]) break;
return ct(a > 1 && ft(h), a > 1 && e.slice(0, a - 1).join("").replace(j, "$1"), n, a < r && ht(e.slice(a, r)), r < s && ht(e = e.slice(r)), r < s && e.join(""))
}
h.push(n)
}
return ft(h)
}
function pt(e, t) {
var r = t.length > 0,
s = e.length > 0,
o = function(u, a, f, l, h) {
var p, d, v, m = [],
y = 0,
w = "0",
x = u && [],
T = h != null,
N = c,
C = u || s && i.find.TAG("*", h && a.parentNode || a),
k = b += N == null ? 1 : Math.E;
T && (c = a !== g && a, n = o.el);
for (;
(p = C[w]) != null; w++) {
if (s && p) {
for (d = 0; v = e[d]; d++)
if (v(p, a, f)) {
l.push(p);
break
}
T && (b = k, n = ++o.el)
}
r && ((p = !v && p) && y--, u && x.push(p))
}
y += w;
if (r && w !== y) {
for (d = 0; v = t[d]; d++) v(x, m, a, f);
if (u) {
if (y > 0)
while (w--) !x[w] && !m[w] && (m[w] = E.call(l));
m = lt(m)
}
S.apply(l, m), T && !u && m.length > 0 && y + t.length > 1 && nt.uniqueSort(l)
}
return T && (b = k, c = N), x
};
return o.el = 0, r ? N(o) : o
}
function dt(e, t, n) {
var r = 0,
i = t.length;
for (; r < i; r++) nt(e, t[r], n);
return n
}
function vt(e, t, n, r, s) {
var o, u, f, l, c, h = ut(e),
p = h.length;
if (!r && h.length === 1) {
u = h[0] = h[0].slice(0);
if (u.length > 2 && (f = u[0]).type === "ID" && t.nodeType === 9 && !s && i.relative[u[1].type]) {
t = i.find.ID(f.matches[0].replace($, ""), t, s)[0];
if (!t) return n;
e = e.slice(u.shift().length)
}
for (o = J.POS.test(e) ? -1 : u.length - 1; o >= 0; o--) {
f = u[o];
if (i.relative[l = f.type]) break;
if (c = i.find[l])
if (r = c(f.matches[0].replace($, ""), z.test(u[0].type) && t.parentNode || t, s)) {
u.splice(o, 1), e = r.length && u.join("");
if (!e) return S.apply(n, x.call(r, 0)), n;
break
}
}
}
return a(e, h)(r, t, s, n, z.test(e)), n
}
function mt() {}
var n, r, i, s, o, u, a, f, l, c, h = !0,
p = "undefined",
d = ("sizcache" + Math.random()).replace(".", ""),
m = String,
g = e.document,
y = g.documentElement,
b = 0,
w = 0,
E = [].pop,
S = [].push,
x = [].slice,
T = [].indexOf || function(e) {
var t = 0,
n = this.length;
for (; t < n; t++)
if (this[t] === e) return t;
return -1
},
N = function(e, t) {
return e[d] = t == null || t, e
},
C = function() {
var e = {},
t = [];
return N(function(n, r) {
return t.push(n) > i.cacheLength && delete e[t.shift()], e[n + " "] = r
}, e)
},
k = C(),
L = C(),
A = C(),
O = "[\\x20\\t\\r\\n\\f]",
M = "(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+",
_ = M.replace("w", "w#"),
D = "([*^$|!~]?=)",
P = "\\[" + O + "*(" + M + ")" + O + "*(?:" + D + O + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + _ + ")|)|)" + O + "*\\]",
H = ":(" + M + ")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:" + P + ")|[^:]|\\\\.)*|.*))\\)|)",
B = ":(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + O + "*((?:-\\d)?\\d*)" + O + "*\\)|)(?=[^-]|$)",
j = new RegExp("^" + O + "+|((?:^|[^\\\\])(?:\\\\.)*)" + O + "+$", "g"),
F = new RegExp("^" + O + "*," + O + "*"),
I = new RegExp("^" + O + "*([\\x20\\t\\r\\n\\f>+~])" + O + "*"),
q = new RegExp(H),
R = /^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,
U = /^:not/,
z = /[\x20\t\r\n\f]*[+~]/,
W = /:not\($/,
X = /h\d/i,
V = /input|select|textarea|button/i,
$ = /\\(?!\\)/g,
J = {
ID: new RegExp("^#(" + M + ")"),
CLASS: new RegExp("^\\.(" + M + ")"),
NAME: new RegExp("^\\[name=['\"]?(" + M + ")['\"]?\\]"),
TAG: new RegExp("^(" + M.replace("w", "w*") + ")"),
ATTR: new RegExp("^" + P),
PSEUDO: new RegExp("^" + H),
POS: new RegExp(B, "i"),
CHILD: new RegExp("^:(only|nth|first|last)-child(?:\\(" + O + "*(even|odd|(([+-]|)(\\d*)n|)" + O + "*(?:([+-]|)" + O + "*(\\d+)|))" + O + "*\\)|)", "i"),
needsContext: new RegExp("^" + O + "*[>+~]|" + B, "i")
},
K = function(e) {
var t = g.createElement("div");
try {
return e(t)
} catch (n) {
return !1
} finally {
t = null
}
},
Q = K(function(e) {
return e.appendChild(g.createComment("")), !e.getElementsByTagName("*").length
}),
G = K(function(e) {
return e.innerHTML = "<a href='#'></a>", e.firstChild && typeof e.firstChild.getAttribute !== p && e.firstChild.getAttribute("href") === "#"
}),
Y = K(function(e) {
e.innerHTML = "<select></select>";
var t = typeof e.lastChild.getAttribute("multiple");
return t !== "boolean" && t !== "string"
}),
Z = K(function(e) {
return e.innerHTML = "<div class='hidden e'></div><div class='hidden'></div>", !e.getElementsByClassName || !e.getElementsByClassName("e").length ? !1 : (e.lastChild.className = "e", e.getElementsByClassName("e").length === 2)
}),
et = K(function(e) {
e.id = d + 0, e.innerHTML = "<a name='" + d + "'></a><div name='" + d + "'></div>", y.insertBefore(e, y.firstChild);
var t = g.getElementsByName && g.getElementsByName(d).length === 2 + g.getElementsByName(d + 0).length;
return r = !g.getElementById(d), y.removeChild(e), t
});
try {
x.call(y.childNodes, 0)[0].nodeType
} catch (tt) {
x = function(e) {
var t, n = [];
for (; t = this[e]; e++) n.push(t);
return n
}
}
nt.matches = function(e, t) {
return nt(e, null, null, t)
}, nt.matchesSelector = function(e, t) {
return nt(t, null, null, [e]).length > 0
}, s = nt.getText = function(e) {
var t, n = "",
r = 0,
i = e.nodeType;
if (i) {
if (i === 1 || i === 9 || i === 11) {
if (typeof e.textContent == "string") return e.textContent;
for (e = e.firstChild; e; e = e.nextSibling) n += s(e)
} else if (i === 3 || i === 4) return e.nodeValue
} else
for (; t = e[r]; r++) n += s(t);
return n
}, o = nt.isXML = function(e) {
var t = e && (e.ownerDocument || e).documentElement;
return t ? t.nodeName !== "HTML" : !1
}, u = nt.contains = y.contains ? function(e, t) {
var n = e.nodeType === 9 ? e.documentElement : e,
r = t && t.parentNode;
return e === r || !!(r && r.nodeType === 1 && n.contains && n.contains(r))
} : y.compareDocumentPosition ? function(e, t) {
return t && !!(e.compareDocumentPosition(t) & 16)
} : function(e, t) {
while (t = t.parentNode)
if (t === e) return !0;
return !1
}, nt.attr = function(e, t) {
var n, r = o(e);
return r || (t = t.toLowerCase()), (n = i.attrHandle[t]) ? n(e) : r || Y ? e.getAttribute(t) : (n = e.getAttributeNode(t), n ? typeof e[t] == "boolean" ? e[t] ? t : null : n.specified ? n.value : null : null)
}, i = nt.selectors = {
cacheLength: 50,
createPseudo: N,
match: J,
attrHandle: G ? {} : {
href: function(e) {
return e.getAttribute("href", 2)
},
type: function(e) {
return e.getAttribute("type")
}
},
find: {
ID: r ? function(e, t, n) {
if (typeof t.getElementById !== p && !n) {
var r = t.getElementById(e);
return r && r.parentNode ? [r] : []
}
} : function(e, n, r) {
if (typeof n.getElementById !== p && !r) {
var i = n.getElementById(e);
return i ? i.id === e || typeof i.getAttributeNode !== p && i.getAttributeNode("id").value === e ? [i] : t : []
}
},
TAG: Q ? function(e, t) {
if (typeof t.getElementsByTagName !== p) return t.getElementsByTagName(e)
} : function(e, t) {
var n = t.getElementsByTagName(e);
if (e === "*") {
var r, i = [],
s = 0;
for (; r = n[s]; s++) r.nodeType === 1 && i.push(r);
return i
}
return n
},
NAME: et && function(e, t) {
if (typeof t.getElementsByName !== p) return t.getElementsByName(name)
},
CLASS: Z && function(e, t, n) {
if (typeof t.getElementsByClassName !== p && !n) return t.getElementsByClassName(e)
}
},
relative: {
">": {
dir: "parentNode",
first: !0
},
" ": {
dir: "parentNode"
},
"+": {
dir: "previousSibling",
first: !0
},
"~": {
dir: "previousSibling"
}
},
preFilter: {
ATTR: function(e) {
return e[1] = e[1].replace($, ""), e[3] = (e[4] || e[5] || "").replace($, ""), e[2] === "~=" && (e[3] = " " + e[3] + " "), e.slice(0, 4)
},
CHILD: function(e) {
return e[1] = e[1].toLowerCase(), e[1] === "nth" ? (e[2] || nt.error(e[0]), e[3] = +(e[3] ? e[4] + (e[5] || 1) : 2 * (e[2] === "even" || e[2] === "odd")), e[4] = +(e[6] + e[7] || e[2] === "odd")) : e[2] && nt.error(e[0]), e
},
PSEUDO: function(e) {
var t, n;
if (J.CHILD.test(e[0])) return null;
if (e[3]) e[2] = e[3];
else if (t = e[4]) q.test(t) && (n = ut(t, !0)) && (n = t.indexOf(")", t.length - n) - t.length) && (t = t.slice(0, n), e[0] = e[0].slice(0, n)), e[2] = t;
return e.slice(0, 3)
}
},
filter: {
ID: r ? function(e) {
return e = e.replace($, ""),
function(t) {
return t.getAttribute("id") === e
}
} : function(e) {
return e = e.replace($, ""),
function(t) {
var n = typeof t.getAttributeNode !== p && t.getAttributeNode("id");
return n && n.value === e
}
},
TAG: function(e) {
return e === "*" ? function() {
return !0
} : (e = e.replace($, "").toLowerCase(), function(t) {
return t.nodeName && t.nodeName.toLowerCase() === e
})
},
CLASS: function(e) {
var t = k[d][e + " "];
return t || (t = new RegExp("(^|" + O + ")" + e + "(" + O + "|$)")) && k(e, function(e) {
return t.test(e.className || typeof e.getAttribute !== p && e.getAttribute("class") || "")
})
},
ATTR: function(e, t, n) {
return function(r, i) {
var s = nt.attr(r, e);
return s == null ? t === "!=" : t ? (s += "", t === "=" ? s === n : t === "!=" ? s !== n : t === "^=" ? n && s.indexOf(n) === 0 : t === "*=" ? n && s.indexOf(n) > -1 : t === "$=" ? n && s.substr(s.length - n.length) === n : t === "~=" ? (" " + s + " ").indexOf(n) > -1 : t === "|=" ? s === n || s.substr(0, n.length + 1) === n + "-" : !1) : !0
}
},
CHILD: function(e, t, n, r) {
return e === "nth" ? function(e) {
var t, i, s = e.parentNode;
if (n === 1 && r === 0) return !0;
if (s) {
i = 0;
for (t = s.firstChild; t; t = t.nextSibling)
if (t.nodeType === 1) {
i++;
if (e === t) break
}
}
return i -= r, i === n || i % n === 0 && i / n >= 0
} : function(t) {
var n = t;
switch (e) {
case "only":
case "first":
while (n = n.previousSibling)
if (n.nodeType === 1) return !1;
if (e === "first") return !0;
n = t;
case "last":
while (n = n.nextSibling)
if (n.nodeType === 1) return !1;
return !0
}
}
},
PSEUDO: function(e, t) {
var n, r = i.pseudos[e] || i.setFilters[e.toLowerCase()] || nt.error("unsupported pseudo: " + e);
return r[d] ? r(t) : r.length > 1 ? (n = [e, e, "", t], i.setFilters.hasOwnProperty(e.toLowerCase()) ? N(function(e, n) {
var i, s = r(e, t),
o = s.length;
while (o--) i = T.call(e, s[o]), e[i] = !(n[i] = s[o])
}) : function(e) {
return r(e, 0, n)
}) : r
}
},
pseudos: {
not: N(function(e) {
var t = [],
n = [],
r = a(e.replace(j, "$1"));
return r[d] ? N(function(e, t, n, i) {
var s, o = r(e, null, i, []),
u = e.length;
while (u--)
if (s = o[u]) e[u] = !(t[u] = s)
}) : function(e, i, s) {
return t[0] = e, r(t, null, s, n), !n.pop()
}
}),
has: N(function(e) {
return function(t) {
return nt(e, t).length > 0
}
}),
contains: N(function(e) {
return function(t) {
return (t.textContent || t.innerText || s(t)).indexOf(e) > -1
}
}),
enabled: function(e) {
return e.disabled === !1
},
disabled: function(e) {
return e.disabled === !0
},
checked: function(e) {
var t = e.nodeName.toLowerCase();
return t === "input" && !!e.checked || t === "option" && !!e.selected
},
selected: function(e) {
return e.parentNode && e.parentNode.selectedIndex, e.selected === !0
},
parent: function(e) {
return !i.pseudos.empty(e)
},
empty: function(e) {
var t;
e = e.firstChild;
while (e) {
if (e.nodeName > "@" || (t = e.nodeType) === 3 || t === 4) return !1;
e = e.nextSibling
}
return !0
},
header: function(e) {
return X.test(e.nodeName)
},
text: function(e) {
var t, n;
return e.nodeName.toLowerCase() === "input" && (t = e.type) === "text" && ((n = e.getAttribute("type")) == null || n.toLowerCase() === t)
},
radio: rt("radio"),
checkbox: rt("checkbox"),
file: rt("file"),
password: rt("password"),
image: rt("image"),
submit: it("submit"),
reset: it("reset"),
button: function(e) {
var t = e.nodeName.toLowerCase();
return t === "input" && e.type === "button" || t === "button"
},
input: function(e) {
return V.test(e.nodeName)
},
focus: function(e) {
var t = e.ownerDocument;
return e === t.activeElement && (!t.hasFocus || t.hasFocus()) && !!(e.type || e.href || ~e.tabIndex)
},
active: function(e) {
return e === e.ownerDocument.activeElement
},
first: st(function() {
return [0]
}),
last: st(function(e, t) {
return [t - 1]
}),
eq: st(function(e, t, n) {
return [n < 0 ? n + t : n]
}),
even: st(function(e, t) {
for (var n = 0; n < t; n += 2) e.push(n);
return e
}),
odd: st(function(e, t) {
for (var n = 1; n < t; n += 2) e.push(n);
return e
}),
lt: st(function(e, t, n) {
for (var r = n < 0 ? n + t : n; --r >= 0;) e.push(r);
return e
}),
gt: st(function(e, t, n) {
for (var r = n < 0 ? n + t : n; ++r < t;) e.push(r);
return e
})
}
}, f = y.compareDocumentPosition ? function(e, t) {
return e === t ? (l = !0, 0) : (!e.compareDocumentPosition || !t.compareDocumentPosition ? e.compareDocumentPosition : e.compareDocumentPosition(t) & 4) ? -1 : 1
} : function(e, t) {
if (e === t) return l = !0, 0;
if (e.sourceIndex && t.sourceIndex) return e.sourceIndex - t.sourceIndex;
var n, r, i = [],
s = [],
o = e.parentNode,
u = t.parentNode,
a = o;
if (o === u) return ot(e, t);
if (!o) return -1;
if (!u) return 1;
while (a) i.unshift(a), a = a.parentNode;
a = u;
while (a) s.unshift(a), a = a.parentNode;
n = i.length, r = s.length;
for (var f = 0; f < n && f < r; f++)
if (i[f] !== s[f]) return ot(i[f], s[f]);
return f === n ? ot(e, s[f], -1) : ot(i[f], t, 1)
}, [0, 0].sort(f), h = !l, nt.uniqueSort = function(e) {
var t, n = [],
r = 1,
i = 0;
l = h, e.sort(f);
if (l) {
for (; t = e[r]; r++) t === e[r - 1] && (i = n.push(r));
while (i--) e.splice(n[i], 1)
}
return e
}, nt.error = function(e) {
throw new Error("Syntax error, unrecognized expression: " + e)
}, a = nt.compile = function(e, t) {
var n, r = [],
i = [],
s = A[d][e + " "];
if (!s) {
t || (t = ut(e)), n = t.length;
while (n--) s = ht(t[n]), s[d] ? r.push(s) : i.push(s);
s = A(e, pt(i, r))
}
return s
}, g.querySelectorAll && function() {
var e, t = vt,
n = /'|\\/g,
r = /\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,
i = [":focus"],
s = [":active"],
u = y.matchesSelector || y.mozMatchesSelector || y.webkitMatchesSelector || y.oMatchesSelector || y.msMatchesSelector;
K(function(e) {
e.innerHTML = "<select><option selected=''></option></select>", e.querySelectorAll("[selected]").length || i.push("\\[" + O + "*(?:checked|disabled|ismap|multiple|readonly|selected|value)"), e.querySelectorAll(":checked").length || i.push(":checked")
}), K(function(e) {
e.innerHTML = "<p test=''></p>", e.querySelectorAll("[test^='']").length && i.push("[*^$]=" + O + "*(?:\"\"|'')"), e.innerHTML = "<input type='hidden'/>", e.querySelectorAll(":enabled").length || i.push(":enabled", ":disabled")
}), i = new RegExp(i.join("|")), vt = function(e, r, s, o, u) {
if (!o && !u && !i.test(e)) {
var a, f, l = !0,
c = d,
h = r,
p = r.nodeType === 9 && e;
if (r.nodeType === 1 && r.nodeName.toLowerCase() !== "object") {
a = ut(e), (l = r.getAttribute("id")) ? c = l.replace(n, "\\$&") : r.setAttribute("id", c), c = "[id='" + c + "'] ", f = a.length;
while (f--) a[f] = c + a[f].join("");
h = z.test(e) && r.parentNode || r, p = a.join(",")
}
if (p) try {
return S.apply(s, x.call(h.querySelectorAll(p), 0)), s
} catch (v) {} finally {
l || r.removeAttribute("id")
}
}
return t(e, r, s, o, u)
}, u && (K(function(t) {
e = u.call(t, "div");
try {
u.call(t, "[test!='']:sizzle"), s.push("!=", H)
} catch (n) {}
}), s = new RegExp(s.join("|")), nt.matchesSelector = function(t, n) {
n = n.replace(r, "='$1']");
if (!o(t) && !s.test(n) && !i.test(n)) try {
var a = u.call(t, n);
if (a || e || t.document && t.document.nodeType !== 11) return a
} catch (f) {}
return nt(n, null, null, [t]).length > 0
})
}(), i.pseudos.nth = i.pseudos.eq, i.filters = mt.prototype = i.pseudos, i.setFilters = new mt, nt.attr = v.attr, v.find = nt, v.expr = nt.selectors, v.expr[":"] = v.expr.pseudos, v.unique = nt.uniqueSort, v.text = nt.getText, v.isXMLDoc = nt.isXML, v.contains = nt.contains
}(e);
var nt = /Until$/,
rt = /^(?:parents|prev(?:Until|All))/,
it = /^.[^:#\[\.,]*$/,
st = v.expr.match.needsContext,
ot = {
children: !0,
contents: !0,
next: !0,
prev: !0
};
v.fn.extend({
find: function(e) {
var t, n, r, i, s, o, u = this;
if (typeof e != "string") return v(e).filter(function() {
for (t = 0, n = u.length; t < n; t++)
if (v.contains(u[t], this)) return !0
});
o = this.pushStack("", "find", e);
for (t = 0, n = this.length; t < n; t++) {
r = o.length, v.find(e, this[t], o);
if (t > 0)
for (i = r; i < o.length; i++)
for (s = 0; s < r; s++)
if (o[s] === o[i]) {
o.splice(i--, 1);
break
}
}
return o
},
has: function(e) {
var t, n = v(e, this),
r = n.length;
return this.filter(function() {
for (t = 0; t < r; t++)
if (v.contains(this, n[t])) return !0
})
},
not: function(e) {
return this.pushStack(ft(this, e, !1), "not", e)
},
filter: function(e) {
return this.pushStack(ft(this, e, !0), "filter", e)
},
is: function(e) {
return !!e && (typeof e == "string" ? st.test(e) ? v(e, this.context).index(this[0]) >= 0 : v.filter(e, this).length > 0 : this.filter(e).length > 0)
},
closest: function(e, t) {
var n, r = 0,
i = this.length,
s = [],
o = st.test(e) || typeof e != "string" ? v(e, t || this.context) : 0;
for (; r < i; r++) {
n = this[r];
while (n && n.ownerDocument && n !== t && n.nodeType !== 11) {
if (o ? o.index(n) > -1 : v.find.matchesSelector(n, e)) {
s.push(n);
break
}
n = n.parentNode
}
}
return s = s.length > 1 ? v.unique(s) : s, this.pushStack(s, "closest", e)
},
index: function(e) {
return e ? typeof e == "string" ? v.inArray(this[0], v(e)) : v.inArray(e.jquery ? e[0] : e, this) : this[0] && this[0].parentNode ? this.prevAll().length : -1
},
add: function(e, t) {
var n = typeof e == "string" ? v(e, t) : v.makeArray(e && e.nodeType ? [e] : e),
r = v.merge(this.get(), n);
return this.pushStack(ut(n[0]) || ut(r[0]) ? r : v.unique(r))
},
addBack: function(e) {
return this.add(e == null ? this.prevObject : this.prevObject.filter(e))
}
}), v.fn.andSelf = v.fn.addBack, v.each({
parent: function(e) {
var t = e.parentNode;
return t && t.nodeType !== 11 ? t : null
},
parents: function(e) {
return v.dir(e, "parentNode")
},
parentsUntil: function(e, t, n) {
return v.dir(e, "parentNode", n)
},
next: function(e) {
return at(e, "nextSibling")
},
prev: function(e) {
return at(e, "previousSibling")
},
nextAll: function(e) {
return v.dir(e, "nextSibling")
},
prevAll: function(e) {
return v.dir(e, "previousSibling")
},
nextUntil: function(e, t, n) {
return v.dir(e, "nextSibling", n)
},
prevUntil: function(e, t, n) {
return v.dir(e, "previousSibling", n)
},
siblings: function(e) {
return v.sibling((e.parentNode || {}).firstChild, e)
},
children: function(e) {
return v.sibling(e.firstChild)
},
contents: function(e) {
return v.nodeName(e, "iframe") ? e.contentDocument || e.contentWindow.document : v.merge([], e.childNodes)
}
}, function(e, t) {
v.fn[e] = function(n, r) {
var i = v.map(this, t, n);
return nt.test(e) || (r = n), r && typeof r == "string" && (i = v.filter(r, i)), i = this.length > 1 && !ot[e] ? v.unique(i) : i, this.length > 1 && rt.test(e) && (i = i.reverse()), this.pushStack(i, e, l.call(arguments).join(","))
}
}), v.extend({
filter: function(e, t, n) {
return n && (e = ":not(" + e + ")"), t.length === 1 ? v.find.matchesSelector(t[0], e) ? [t[0]] : [] : v.find.matches(e, t)
},
dir: function(e, n, r) {
var i = [],
s = e[n];
while (s && s.nodeType !== 9 && (r === t || s.nodeType !== 1 || !v(s).is(r))) s.nodeType === 1 && i.push(s), s = s[n];
return i
},
sibling: function(e, t) {
var n = [];
for (; e; e = e.nextSibling) e.nodeType === 1 && e !== t && n.push(e);
return n
}
});
var ct = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",
ht = / jQuery\d+="(?:null|\d+)"/g,
pt = /^\s+/,
dt = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,
vt = /<([\w:]+)/,
mt = /<tbody/i,
gt = /<|&#?\w+;/,
yt = /<(?:script|style|link)/i,
bt = /<(?:script|object|embed|option|style)/i,
wt = new RegExp("<(?:" + ct + ")[\\s/>]", "i"),
Et = /^(?:checkbox|radio)$/,
St = /checked\s*(?:[^=]|=\s*.checked.)/i,
xt = /\/(java|ecma)script/i,
Tt = /^\s*<!(?:\[CDATA\[|\-\-)|[\]\-]{2}>\s*$/g,
Nt = {
option: [1, "<select multiple='multiple'>", "</select>"],
legend: [1, "<fieldset>", "</fieldset>"],
thead: [1, "<table>", "</table>"],
tr: [2, "<table><tbody>", "</tbody></table>"],
td: [3, "<table><tbody><tr>", "</tr></tbody></table>"],
col: [2, "<table><tbody></tbody><colgroup>", "</colgroup></table>"],
area: [1, "<map>", "</map>"],
_default: [0, "", ""]
},
Ct = lt(i),
kt = Ct.appendChild(i.createElement("div"));
Nt.optgroup = Nt.option, Nt.tbody = Nt.tfoot = Nt.colgroup = Nt.caption = Nt.thead, Nt.th = Nt.td, v.support.htmlSerialize || (Nt._default = [1, "X<div>", "</div>"]), v.fn.extend({
text: function(
e) {
return v.access(this, function(e) {
return e === t ? v.text(this) : this.empty().append((this[0] && this[0].ownerDocument || i).createTextNode(e))
}, null, e, arguments.length)
},
wrapAll: function(e) {
if (v.isFunction(e)) return this.each(function(t) {
v(this).wrapAll(e.call(this, t))
});
if (this[0]) {
var t = v(e, this[0].ownerDocument).eq(0).clone(!0);
this[0].parentNode && t.insertBefore(this[0]), t.map(function() {
var e = this;
while (e.firstChild && e.firstChild.nodeType === 1) e = e.firstChild;
return e
}).append(this)
}
return this
},
wrapInner: function(e) {
return v.isFunction(e) ? this.each(function(t) {
v(this).wrapInner(e.call(this, t))
}) : this.each(function() {
var t = v(this),
n = t.contents();
n.length ? n.wrapAll(e) : t.append(e)
})
},
wrap: function(e) {
var t = v.isFunction(e);
return this.each(function(n) {
v(this).wrapAll(t ? e.call(this, n) : e)
})
},
unwrap: function() {
return this.parent().each(function() {
v.nodeName(this, "body") || v(this).replaceWith(this.childNodes)
}).end()
},
append: function() {
return this.domManip(arguments, !0, function(e) {
(this.nodeType === 1 || this.nodeType === 11) && this.appendChild(e)
})
},
prepend: function() {
return this.domManip(arguments, !0, function(e) {
(this.nodeType === 1 || this.nodeType === 11) && this.insertBefore(e, this.firstChild)
})
},
before: function() {
if (!ut(this[0])) return this.domManip(arguments, !1, function(e) {
this.parentNode.insertBefore(e, this)
});
if (arguments.length) {
var e = v.clean(arguments);
return this.pushStack(v.merge(e, this), "before", this.selector)
}
},
after: function() {
if (!ut(this[0])) return this.domManip(arguments, !1, function(e) {
this.parentNode.insertBefore(e, this.nextSibling)
});
if (arguments.length) {
var e = v.clean(arguments);
return this.pushStack(v.merge(this, e), "after", this.selector)
}
},
remove: function(e, t) {
var n, r = 0;
for (;
(n = this[r]) != null; r++)
if (!e || v.filter(e, [n]).length) !t && n.nodeType === 1 && (v.cleanData(n.getElementsByTagName("*")), v.cleanData([n])), n.parentNode && n.parentNode.removeChild(n);
return this
},
empty: function() {
var e, t = 0;
for (;
(e = this[t]) != null; t++) {
e.nodeType === 1 && v.cleanData(e.getElementsByTagName("*"));
while (e.firstChild) e.removeChild(e.firstChild)
}
return this
},
clone: function(e, t) {
return e = e == null ? !1 : e, t = t == null ? e : t, this.map(function() {
return v.clone(this, e, t)
})
},
html: function(e) {
return v.access(this, function(e) {
var n = this[0] || {},
r = 0,
i = this.length;
if (e === t) return n.nodeType === 1 ? n.innerHTML.replace(ht, "") : t;
if (typeof e == "string" && !yt.test(e) && (v.support.htmlSerialize || !wt.test(e)) && (v.support.leadingWhitespace || !pt.test(e)) && !Nt[(vt.exec(e) || ["", ""])[1].toLowerCase()]) {
e = e.replace(dt, "<$1></$2>");
try {
for (; r < i; r++) n = this[r] || {}, n.nodeType === 1 && (v.cleanData(n.getElementsByTagName("*")), n.innerHTML = e);
n = 0
} catch (s) {}
}
n && this.empty().append(e)
}, null, e, arguments.length)
},
replaceWith: function(e) {
return ut(this[0]) ? this.length ? this.pushStack(v(v.isFunction(e) ? e() : e), "replaceWith", e) : this : v.isFunction(e) ? this.each(function(t) {
var n = v(this),
r = n.html();
n.replaceWith(e.call(this, t, r))
}) : (typeof e != "string" && (e = v(e).detach()), this.each(function() {
var t = this.nextSibling,
n = this.parentNode;
v(this).remove(), t ? v(t).before(e) : v(n).append(e)
}))
},
detach: function(e) {
return this.remove(e, !0)
},
domManip: function(e, n, r) {
e = [].concat.apply([], e);
var i, s, o, u, a = 0,
f = e[0],
l = [],
c = this.length;
if (!v.support.checkClone && c > 1 && typeof f == "string" && St.test(f)) return this.each(function() {
v(this).domManip(e, n, r)
});
if (v.isFunction(f)) return this.each(function(i) {
var s = v(this);
e[0] = f.call(this, i, n ? s.html() : t), s.domManip(e, n, r)
});
if (this[0]) {
i = v.buildFragment(e, this, l), o = i.fragment, s = o.firstChild, o.childNodes.length === 1 && (o = s);
if (s) {
n = n && v.nodeName(s, "tr");
for (u = i.cacheable || c - 1; a < c; a++) r.call(n && v.nodeName(this[a], "table") ? Lt(this[a], "tbody") : this[a], a === u ? o : v.clone(o, !0, !0))
}
o = s = null, l.length && v.each(l, function(e, t) {
t.src ? v.ajax ? v.ajax({
url: t.src,
type: "GET",
dataType: "script",
async: !1,
global: !1,
"throws": !0
}) : v.error("no ajax") : v.globalEval((t.text || t.textContent || t.innerHTML || "").replace(Tt, "")), t.parentNode && t.parentNode.removeChild(t)
})
}
return this
}
}), v.buildFragment = function(e, n, r) {
var s, o, u, a = e[0];
return n = n || i, n = !n.nodeType && n[0] || n, n = n.ownerDocument || n, e.length === 1 && typeof a == "string" && a.length < 512 && n === i && a.charAt(0) === "<" && !bt.test(a) && (v.support.checkClone || !St.test(a)) && (v.support.html5Clone || !wt.test(a)) && (o = !0, s = v.fragments[a], u = s !== t), s || (s = n.createDocumentFragment(), v.clean(e, n, s, r), o && (v.fragments[a] = u && s)), {
fragment: s,
cacheable: o
}
}, v.fragments = {}, v.each({
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
}, function(e, t) {
v.fn[e] = function(n) {
var r, i = 0,
s = [],
o = v(n),
u = o.length,
a = this.length === 1 && this[0].parentNode;
if ((a == null || a && a.nodeType === 11 && a.childNodes.length === 1) && u === 1) return o[t](this[0]), this;
for (; i < u; i++) r = (i > 0 ? this.clone(!0) : this).get(), v(o[i])[t](r), s = s.concat(r);
return this.pushStack(s, e, o.selector)
}
}), v.extend({
clone: function(e, t, n) {
var r, i, s, o;
v.support.html5Clone || v.isXMLDoc(e) || !wt.test("<" + e.nodeName + ">") ? o = e.cloneNode(!0) : (kt.innerHTML = e.outerHTML, kt.removeChild(o = kt.firstChild));
if ((!v.support.noCloneEvent || !v.support.noCloneChecked) && (e.nodeType === 1 || e.nodeType === 11) && !v.isXMLDoc(e)) {
Ot(e, o), r = Mt(e), i = Mt(o);
for (s = 0; r[s]; ++s) i[s] && Ot(r[s], i[s])
}
if (t) {
At(e, o);
if (n) {
r = Mt(e), i = Mt(o);
for (s = 0; r[s]; ++s) At(r[s], i[s])
}
}
return r = i = null, o
},
clean: function(e, t, n, r) {
var s, o, u, a, f, l, c, h, p, d, m, g, y = t === i && Ct,
b = [];
if (!t || typeof t.createDocumentFragment == "undefined") t = i;
for (s = 0;
(u = e[s]) != null; s++) {
typeof u == "number" && (u += "");
if (!u) continue;
if (typeof u == "string")
if (!gt.test(u)) u = t.createTextNode(u);
else {
y = y || lt(t), c = t.createElement("div"), y.appendChild(c), u = u.replace(dt, "<$1></$2>"), a = (vt.exec(u) || ["", ""])[1].toLowerCase(), f = Nt[a] || Nt._default, l = f[0], c.innerHTML = f[1] + u + f[2];
while (l--) c = c.lastChild;
if (!v.support.tbody) {
h = mt.test(u), p = a === "table" && !h ? c.firstChild && c.firstChild.childNodes : f[1] === "<table>" && !h ? c.childNodes : [];
for (o = p.length - 1; o >= 0; --o) v.nodeName(p[o], "tbody") && !p[o].childNodes.length && p[o].parentNode.removeChild(p[o])
}!v.support.leadingWhitespace && pt.test(u) && c.insertBefore(t.createTextNode(pt.exec(u)[0]), c.firstChild), u = c.childNodes, c.parentNode.removeChild(c)
}
u.nodeType ? b.push(u) : v.merge(b, u)
}
c && (u = c = y = null);
if (!v.support.appendChecked)
for (s = 0;
(u = b[s]) != null; s++) v.nodeName(u, "input") ? _t(u) : typeof u.getElementsByTagName != "undefined" && v.grep(u.getElementsByTagName("input"), _t);
if (n) {
m = function(e) {
if (!e.type || xt.test(e.type)) return r ? r.push(e.parentNode ? e.parentNode.removeChild(e) : e) : n.appendChild(e)
};
for (s = 0;
(u = b[s]) != null; s++)
if (!v.nodeName(u, "script") || !m(u)) n.appendChild(u), typeof u.getElementsByTagName != "undefined" && (g = v.grep(v.merge([], u.getElementsByTagName("script")), m), b.splice.apply(b, [s + 1, 0].concat(g)), s += g.length)
}
return b
},
cleanData: function(e, t) {
var n, r, i, s, o = 0,
u = v.expando,
a = v.cache,
f = v.support.deleteExpando,
l = v.event.special;
for (;
(i = e[o]) != null; o++)
if (t || v.acceptData(i)) {
r = i[u], n = r && a[r];
if (n) {
if (n.events)
for (s in n.events) l[s] ? v.event.remove(i, s) : v.removeEvent(i, s, n.handle);
a[r] && (delete a[r], f ? delete i[u] : i.removeAttribute ? i.removeAttribute(u) : i[u] = null, v.deletedIds.push(r))
}
}
}
}),
function() {
var e, t;
v.uaMatch = function(e) {
e = e.toLowerCase();
var t = /(chrome)[ \/]([\w.]+)/.exec(e) || /(webkit)[ \/]([\w.]+)/.exec(e) || /(opera)(?:.*version|)[ \/]([\w.]+)/.exec(e) || /(msie) ([\w.]+)/.exec(e) || e.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec(e) || [];
return {
browser: t[1] || "",
version: t[2] || "0"
}
}, e = v.uaMatch(o.userAgent), t = {}, e.browser && (t[e.browser] = !0, t.version = e.version), t.chrome ? t.webkit = !0 : t.webkit && (t.safari = !0), v.browser = t, v.sub = function() {
function e(t, n) {
return new e.fn.init(t, n)
}
v.extend(!0, e, this), e.superclass = this, e.fn = e.prototype = this(), e.fn.constructor = e, e.sub = this.sub, e.fn.init = function(r, i) {
return i && i instanceof v && !(i instanceof e) && (i = e(i)), v.fn.init.call(this, r, i, t)
}, e.fn.init.prototype = e.fn;
var t = e(i);
return e
}
}();
var Dt, Pt, Ht, Bt = /alpha\([^)]*\)/i,
jt = /opacity=([^)]*)/,
Ft = /^(top|right|bottom|left)$/,
It = /^(none|table(?!-c[ea]).+)/,
qt = /^margin/,
Rt = new RegExp("^(" + m + ")(.*)$", "i"),
Ut = new RegExp("^(" + m + ")(?!px)[a-z%]+$", "i"),
zt = new RegExp("^([-+])=(" + m + ")", "i"),
Wt = {
BODY: "block"
},
Xt = {
position: "absolute",
visibility: "hidden",
display: "block"
},
Vt = {
letterSpacing: 0,
fontWeight: 400
},
$t = ["Top", "Right", "Bottom", "Left"],
Jt = ["Webkit", "O", "Moz", "ms"],
Kt = v.fn.toggle;
v.fn.extend({
css: function(e, n) {
return v.access(this, function(e, n, r) {
return r !== t ? v.style(e, n, r) : v.css(e, n)
}, e, n, arguments.length > 1)
},
show: function() {
return Yt(this, !0)
},
hide: function() {
return Yt(this)
},
toggle: function(e, t) {
var n = typeof e == "boolean";
return v.isFunction(e) && v.isFunction(t) ? Kt.apply(this, arguments) : this.each(function() {
(n ? e : Gt(this)) ? v(this).show(): v(this).hide()
})
}
}), v.extend({
cssHooks: {
opacity: {
get: function(e, t) {
if (t) {
var n = Dt(e, "opacity");
return n === "" ? "1" : n
}
}
}
},
cssNumber: {
fillOpacity: !0,
fontWeight: !0,
lineHeight: !0,
opacity: !0,
orphans: !0,
widows: !0,
zIndex: !0,
zoom: !0
},
cssProps: {
"float": v.support.cssFloat ? "cssFloat" : "styleFloat"
},
style: function(e, n, r, i) {
if (!e || e.nodeType === 3 || e.nodeType === 8 || !e.style) return;
var s, o, u, a = v.camelCase(n),
f = e.style;
n = v.cssProps[a] || (v.cssProps[a] = Qt(f, a)), u = v.cssHooks[n] || v.cssHooks[a];
if (r === t) return u && "get" in u && (s = u.get(e, !1, i)) !== t ? s : f[n];
o = typeof r, o === "string" && (s = zt.exec(r)) && (r = (s[1] + 1) * s[2] + parseFloat(v.css(e, n)), o = "number");
if (r == null || o === "number" && isNaN(r)) return;
o === "number" && !v.cssNumber[a] && (r += "px");
if (!u || !("set" in u) || (r = u.set(e, r, i)) !== t) try {
f[n] = r
} catch (l) {}
},
css: function(e, n, r, i) {
var s, o, u, a = v.camelCase(n);
return n = v.cssProps[a] || (v.cssProps[a] = Qt(e.style, a)), u = v.cssHooks[n] || v.cssHooks[a], u && "get" in u && (s = u.get(e, !0, i)), s === t && (s = Dt(e, n)), s === "normal" && n in Vt && (s = Vt[n]), r || i !== t ? (o = parseFloat(s), r || v.isNumeric(o) ? o || 0 : s) : s
},
swap: function(e, t, n) {
var r, i, s = {};
for (i in t) s[i] = e.style[i], e.style[i] = t[i];
r = n.call(e);
for (i in t) e.style[i] = s[i];
return r
}
}), e.getComputedStyle ? Dt = function(t, n) {
var r, i, s, o, u = e.getComputedStyle(t, null),
a = t.style;
return u && (r = u.getPropertyValue(n) || u[n], r === "" && !v.contains(t.ownerDocument, t) && (r = v.style(t, n)), Ut.test(r) && qt.test(n) && (i = a.width, s = a.minWidth, o = a.maxWidth, a.minWidth = a.maxWidth = a.width = r, r = u.width, a.width = i, a.minWidth = s, a.maxWidth = o)), r
} : i.documentElement.currentStyle && (Dt = function(e, t) {
var n, r, i = e.currentStyle && e.currentStyle[t],
s = e.style;
return i == null && s && s[t] && (i = s[t]), Ut.test(i) && !Ft.test(t) && (n = s.left, r = e.runtimeStyle && e.runtimeStyle.left, r && (e.runtimeStyle.left = e.currentStyle.left), s.left = t === "fontSize" ? "1em" : i, i = s.pixelLeft + "px", s.left = n, r && (e.runtimeStyle.left = r)), i === "" ? "auto" : i
}), v.each(["height", "width"], function(e, t) {
v.cssHooks[t] = {
get: function(e, n, r) {
if (n) return e.offsetWidth === 0 && It.test(Dt(e, "display")) ? v.swap(e, Xt, function() {
return tn(e, t, r)
}) : tn(e, t, r)
},
set: function(e, n, r) {
return Zt(e, n, r ? en(e, t, r, v.support.boxSizing && v.css(e, "boxSizing") === "border-box") : 0)
}
}
}), v.support.opacity || (v.cssHooks.opacity = {
get: function(e, t) {
return jt.test((t && e.currentStyle ? e.currentStyle.filter : e.style.filter) || "") ? .01 * parseFloat(RegExp.$1) + "" : t ? "1" : ""
},
set: function(e, t) {
var n = e.style,
r = e.currentStyle,
i = v.isNumeric(t) ? "alpha(opacity=" + t * 100 + ")" : "",
s = r && r.filter || n.filter || "";
n.zoom = 1;
if (t >= 1 && v.trim(s.replace(Bt, "")) === "" && n.removeAttribute) {
n.removeAttribute("filter");
if (r && !r.filter) return
}
n.filter = Bt.test(s) ? s.replace(Bt, i) : s + " " + i
}
}), v(function() {
v.support.reliableMarginRight || (v.cssHooks.marginRight = {
get: function(e, t) {
return v.swap(e, {
display: "inline-block"
}, function() {
if (t) return Dt(e, "marginRight")
})
}
}), !v.support.pixelPosition && v.fn.position && v.each(["top", "left"], function(e, t) {
v.cssHooks[t] = {
get: function(e, n) {
if (n) {
var r = Dt(e, t);
return Ut.test(r) ? v(e).position()[t] + "px" : r
}
}
}
})
}), v.expr && v.expr.filters && (v.expr.filters.hidden = function(e) {
return e.offsetWidth === 0 && e.offsetHeight === 0 || !v.support.reliableHiddenOffsets && (e.style && e.style.display || Dt(e, "display")) === "none"
}, v.expr.filters.visible = function(e) {
return !v.expr.filters.hidden(e)
}), v.each({
margin: "",
padding: "",
border: "Width"
}, function(e, t) {
v.cssHooks[e + t] = {
expand: function(n) {
var r, i = typeof n == "string" ? n.split(" ") : [n],
s = {};
for (r = 0; r < 4; r++) s[e + $t[r] + t] = i[r] || i[r - 2] || i[0];
return s
}
}, qt.test(e) || (v.cssHooks[e + t].set = Zt)
});
var rn = /%20/g,
sn = /\[\]$/,
on = /\r?\n/g,
un = /^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,
an = /^(?:select|textarea)/i;
v.fn.extend({
serialize: function() {
return v.param(this.serializeArray())
},
serializeArray: function() {
return this.map(function() {
return this.elements ? v.makeArray(this.elements) : this
}).filter(function() {
return this.name && !this.disabled && (this.checked || an.test(this.nodeName) || un.test(this.type))
}).map(function(e, t) {
var n = v(this).val();
return n == null ? null : v.isArray(n) ? v.map(n, function(e, n) {
return {
name: t.name,
value: e.replace(on, "\r\n")
}
}) : {
name: t.name,
value: n.replace(on, "\r\n")
}
}).get()
}
}), v.param = function(e, n) {
var r, i = [],
s = function(e, t) {
t = v.isFunction(t) ? t() : t == null ? "" : t, i[i.length] = encodeURIComponent(e) + "=" + encodeURIComponent(t)
};
n === t && (n = v.ajaxSettings && v.ajaxSettings.traditional);
if (v.isArray(e) || e.jquery && !v.isPlainObject(e)) v.each(e, function() {
s(this.name, this.value)
});
else
for (r in e) fn(r, e[r], n, s);
return i.join("&").replace(rn, "+")
};
var ln, cn, hn = /#.*$/,
pn = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg,
dn = /^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,
vn = /^(?:GET|HEAD)$/,
mn = /^\/\//,
gn = /\?/,
yn = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
bn = /([?&])_=[^&]*/,
wn = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,
En = v.fn.load,
Sn = {},
xn = {},
Tn = ["*/"] + ["*"];
try {
cn = s.href
} catch (Nn) {
cn = i.createElement("a"), cn.href = "", cn = cn.href
}
ln = wn.exec(cn.toLowerCase()) || [], v.fn.load = function(e, n, r) {
if (typeof e != "string" && En) return En.apply(this, arguments);
if (!this.length) return this;
var i, s, o, u = this,
a = e.indexOf(" ");
return a >= 0 && (i = e.slice(a, e.length), e = e.slice(0, a)), v.isFunction(n) ? (r = n, n = t) : n && typeof n == "object" && (s = "POST"), v.ajax({
url: e,
type: s,
dataType: "html",
data: n,
complete: function(e, t) {
r && u.each(r, o || [e.responseText, t, e])
}
}).done(function(e) {
o = arguments, u.html(i ? v("<div>").append(e.replace(yn, "")).find(i) : e)
}), this
}, v.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "), function(e, t) {
v.fn[t] = function(e) {
return this.on(t, e)
}
}), v.each(["get", "post"], function(e, n) {
v[n] = function(e, r, i, s) {
return v.isFunction(r) && (s = s || i, i = r, r = t), v.ajax({
type: n,
url: e,
data: r,
success: i,
dataType: s
})
}
}), v.extend({
getScript: function(e, n) {
return v.get(e, t, n, "script")
},
getJSON: function(e, t, n) {
return v.get(e, t, n, "json")
},
ajaxSetup: function(e, t) {
return t ? Ln(e, v.ajaxSettings) : (t = e, e = v.ajaxSettings), Ln(e, t), e
},
ajaxSettings: {
url: cn,
isLocal: dn.test(ln[1]),
global: !0,
type: "GET",
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
processData: !0,
async: !0,
accepts: {
xml: "application/xml, text/xml",
html: "text/html",
text: "text/plain",
json: "application/json, text/javascript",
"*": Tn
},
contents: {
xml: /xml/,
html: /html/,
json: /json/
},
responseFields: {
xml: "responseXML",
text: "responseText"
},
converters: {
"* text": e.String,
"text html": !0,
"text json": v.parseJSON,
"text xml": v.parseXML
},
flatOptions: {
context: !0,
url: !0
}
},
ajaxPrefilter: Cn(Sn),
ajaxTransport: Cn(xn),
ajax: function(e, n) {
function T(e, n, s, a) {
var l, y, b, w, S, T = n;
if (E === 2) return;
E = 2, u && clearTimeout(u), o = t, i = a || "", x.readyState = e > 0 ? 4 : 0, s && (w = An(c, x, s));
if (e >= 200 && e < 300 || e === 304) c.ifModified && (S = x.getResponseHeader("Last-Modified"), S && (v.lastModified[r] = S), S = x.getResponseHeader("Etag"), S && (v.etag[r] = S)), e === 304 ? (T = "notmodified", l = !0) : (l = On(c, w), T = l.state, y = l.data, b = l.error, l = !b);
else {
b = T;
if (!T || e) T = "error", e < 0 && (e = 0)
}
x.status = e, x.statusText = (n || T) + "", l ? d.resolveWith(h, [y, T, x]) : d.rejectWith(h, [x, T, b]), x.statusCode(g), g = t, f && p.trigger("ajax" + (l ? "Success" : "Error"), [x, c, l ? y : b]), m.fireWith(h, [x, T]), f && (p.trigger("ajaxComplete", [x, c]), --v.active || v.event.trigger("ajaxStop"))
}
typeof e == "object" && (n = e, e = t), n = n || {};
var r, i, s, o, u, a, f, l, c = v.ajaxSetup({}, n),
h = c.context || c,
p = h !== c && (h.nodeType || h instanceof v) ? v(h) : v.event,
d = v.Deferred(),
m = v.Callbacks("once memory"),
g = c.statusCode || {},
b = {},
w = {},
E = 0,
S = "canceled",
x = {
readyState: 0,
setRequestHeader: function(e, t) {
if (!E) {
var n = e.toLowerCase();
e = w[n] = w[n] || e, b[e] = t
}
return this
},
getAllResponseHeaders: function() {
return E === 2 ? i : null
},
getResponseHeader: function(e) {
var n;
if (E === 2) {
if (!s) {
s = {};
while (n = pn.exec(i)) s[n[1].toLowerCase()] = n[2]
}
n = s[e.toLowerCase()]
}
return n === t ? null : n
},
overrideMimeType: function(e) {
return E || (c.mimeType = e), this
},
abort: function(e) {
return e = e || S, o && o.abort(e), T(0, e), this
}
};
d.promise(x), x.success = x.done, x.error = x.fail, x.complete = m.add, x.statusCode = function(e) {
if (e) {
var t;
if (E < 2)
for (t in e) g[t] = [g[t], e[t]];
else t = e[x.status], x.always(t)
}
return this
}, c.url = ((e || c.url) + "").replace(hn, "").replace(mn, ln[1] + "//"), c.dataTypes = v.trim(c.dataType || "*").toLowerCase().split(y), c.crossDomain == null && (a = wn.exec(c.url.toLowerCase()), c.crossDomain = !(!a || a[1] === ln[1] && a[2] === ln[2] && (a[3] || (a[1] === "http:" ? 80 : 443)) == (ln[3] || (ln[1] === "http:" ? 80 : 443)))), c.data && c.processData && typeof c.data != "string" && (c.data = v.param(c.data, c.traditional)), kn(Sn, c, n, x);
if (E === 2) return x;
f = c.global, c.type = c.type.toUpperCase(), c.hasContent = !vn.test(c.type), f && v.active++ === 0 && v.event.trigger("ajaxStart");
if (!c.hasContent) {
c.data && (c.url += (gn.test(c.url) ? "&" : "?") + c.data, delete c.data), r = c.url;
if (c.cache === !1) {
var N = v.now(),
C = c.url.replace(bn, "$1_=" + N);
c.url = C + (C === c.url ? (gn.test(c.url) ? "&" : "?") + "_=" + N : "")
}
}(c.data && c.hasContent && c.contentType !== !1 || n.contentType) && x.setRequestHeader("Content-Type", c.contentType), c.ifModified && (r = r || c.url, v.lastModified[r] && x.setRequestHeader("If-Modified-Since", v.lastModified[r]), v.etag[r] && x.setRequestHeader("If-None-Match", v.etag[r])), x.setRequestHeader("Accept", c.dataTypes[0] && c.accepts[c.dataTypes[0]] ? c.accepts[c.dataTypes[0]] + (c.dataTypes[0] !== "*" ? ", " + Tn + "; q=0.01" : "") : c.accepts["*"]);
for (l in c.headers) x.setRequestHeader(l, c.headers[l]);
if (!c.beforeSend || c.beforeSend.call(h, x, c) !== !1 && E !== 2) {
S = "abort";
for (l in {
success: 1,
error: 1,
complete: 1
}) x[l](c[l]);
o = kn(xn, c, n, x);
if (!o) T(-1, "No Transport");
else {
x.readyState = 1, f && p.trigger("ajaxSend", [x, c]), c.async && c.timeout > 0 && (u = setTimeout(function() {
x.abort("timeout")
}, c.timeout));
try {
E = 1, o.send(b, T)
} catch (k) {
if (!(E < 2)) throw k;
T(-1, k)
}
}
return x
}
return x.abort()
},
active: 0,
lastModified: {},
etag: {}
});
var Mn = [],
_n = /\?/,
Dn = /(=)\?(?=&|$)|\?\?/,
Pn = v.now();
v.ajaxSetup({
jsonp: "callback",
jsonpCallback: function() {
var e = Mn.pop() || v.expando + "_" + Pn++;
return this[e] = !0, e
}
}), v.ajaxPrefilter("json jsonp", function(n, r, i) {
var s, o, u, a = n.data,
f = n.url,
l = n.jsonp !== !1,
c = l && Dn.test(f),
h = l && !c && typeof a == "string" && !(n.contentType || "").indexOf("application/x-www-form-urlencoded") && Dn.test(a);
if (n.dataTypes[0] === "jsonp" || c || h) return s = n.jsonpCallback = v.isFunction(n.jsonpCallback) ? n.jsonpCallback() : n.jsonpCallback, o = e[s], c ? n.url = f.replace(Dn, "$1" + s) : h ? n.data = a.replace(Dn, "$1" + s) : l && (n.url += (_n.test(f) ? "&" : "?") + n.jsonp + "=" + s), n.converters["script json"] = function() {
return u || v.error(s + " was not called"), u[0]
}, n.dataTypes[0] = "json", e[s] = function() {
u = arguments
}, i.always(function() {
e[s] = o, n[s] && (n.jsonpCallback = r.jsonpCallback, Mn.push(s)), u && v.isFunction(o) && o(u[0]), u = o = t
}), "script"
}), v.ajaxSetup({
accepts: {
script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
},
contents: {
script: /javascript|ecmascript/
},
converters: {
"text script": function(e) {
return v.globalEval(e), e
}
}
}), v.ajaxPrefilter("script", function(e) {
e.cache === t && (e.cache = !1), e.crossDomain && (e.type = "GET", e.global = !1)
}), v.ajaxTransport("script", function(e) {
if (e.crossDomain) {
var n, r = i.head || i.getElementsByTagName("head")[0] || i.documentElement;
return {
send: function(s, o) {
n = i.createElement("script"), n.async = "async", e.scriptCharset && (n.charset = e.scriptCharset), n.src = e.url, n.onload = n.onreadystatechange = function(e, i) {
if (i || !n.readyState || /loaded|complete/.test(n.readyState)) n.onload = n.onreadystatechange = null, r && n.parentNode && r.removeChild(n), n = t, i || o(200, "success")
}, r.insertBefore(n, r.firstChild)
},
abort: function() {
n && n.onload(0, 1)
}
}
}
});
var Hn, Bn = e.ActiveXObject ? function() {
for (var e in Hn) Hn[e](0, 1)
} : !1,
jn = 0;
v.ajaxSettings.xhr = e.ActiveXObject ? function() {
return !this.isLocal && Fn() || In()
} : Fn,
function(e) {
v.extend(v.support, {
ajax: !!e,
cors: !!e && "withCredentials" in e
})
}(v.ajaxSettings.xhr()), v.support.ajax && v.ajaxTransport(function(n) {
if (!n.crossDomain || v.support.cors) {
var r;
return {
send: function(i, s) {
var o, u, a = n.xhr();
n.username ? a.open(n.type, n.url, n.async, n.username, n.password) : a.open(n.type, n.url, n.async);
if (n.xhrFields)
for (u in n.xhrFields) a[u] = n.xhrFields[u];
n.mimeType && a.overrideMimeType && a.overrideMimeType(n.mimeType), !n.crossDomain && !i["X-Requested-With"] && (i["X-Requested-With"] = "XMLHttpRequest");
try {
for (u in i) a.setRequestHeader(u, i[u])
} catch (f) {}
a.send(n.hasContent && n.data || null), r = function(e, i) {
var u, f, l, c, h;
try {
if (r && (i || a.readyState === 4)) {
r = t, o && (a.onreadystatechange = v.noop, Bn && delete Hn[o]);
if (i) a.readyState !== 4 && a.abort();
else {
u = a.status, l = a.getAllResponseHeaders(), c = {}, h = a.responseXML, h && h.documentElement && (c.xml = h);
try {
c.text = a.responseText
} catch (p) {}
try {
f = a.statusText
} catch (p) {
f = ""
}!u && n.isLocal && !n.crossDomain ? u = c.text ? 200 : 404 : u === 1223 && (u = 204)
}
}
} catch (d) {
i || s(-1, d)
}
c && s(u, f, c, l)
}, n.async ? a.readyState === 4 ? setTimeout(r, 0) : (o = ++jn, Bn && (Hn || (Hn = {}, v(e).unload(Bn)), Hn[o] = r), a.onreadystatechange = r) : r()
},
abort: function() {
r && r(0, 1)
}
}
}
});
var qn, Rn, Un = /^(?:toggle|show|hide)$/,
zn = new RegExp("^(?:([-+])=|)(" + m + ")([a-z%]*)$", "i"),
Wn = /queueHooks$/,
Xn = [Gn],
Vn = {
"*": [function(e, t) {
var n, r, i = this.createTween(e, t),
s = zn.exec(t),
o = i.cur(),
u = +o || 0,
a = 1,
f = 20;
if (s) {
n = +s[2], r = s[3] || (v.cssNumber[e] ? "" : "px");
if (r !== "px" && u) {
u = v.css(i.elem, e, !0) || n || 1;
do a = a || ".5", u /= a, v.style(i.elem, e, u + r); while (a !== (a = i.cur() / o) && a !== 1 && --f)
}
i.unit = r, i.start = u, i.end = s[1] ? u + (s[1] + 1) * n : n
}
return i
}]
};
v.Animation = v.extend(Kn, {
tweener: function(e, t) {
v.isFunction(e) ? (t = e, e = ["*"]) : e = e.split(" ");
var n, r = 0,
i = e.length;
for (; r < i; r++) n = e[r], Vn[n] = Vn[n] || [], Vn[n].unshift(t)
},
prefilter: function(e, t) {
t ? Xn.unshift(e) : Xn.push(e)
}
}), v.Tween = Yn, Yn.prototype = {
constructor: Yn,
init: function(e, t, n, r, i, s) {
this.elem = e, this.prop = n, this.easing = i || "swing", this.options = t, this.start = this.now = this.cur(), this.end = r, this.unit = s || (v.cssNumber[n] ? "" : "px")
},
cur: function() {
var e = Yn.propHooks[this.prop];
return e && e.get ? e.get(this) : Yn.propHooks._default.get(this)
},
run: function(e) {
var t, n = Yn.propHooks[this.prop];
return this.options.duration ? this.pos = t = v.easing[this.easing](e, this.options.duration * e, 0, 1, this.options.duration) : this.pos = t = e, this.now = (this.end - this.start) * t + this.start, this.options.step && this.options.step.call(this.elem, this.now, this), n && n.set ? n.set(this) : Yn.propHooks._default.set(this), this
}
}, Yn.prototype.init.prototype = Yn.prototype, Yn.propHooks = {
_default: {
get: function(e) {
var t;
return e.elem[e.prop] == null || !!e.elem.style && e.elem.style[e.prop] != null ? (t = v.css(e.elem, e.prop, !1, ""), !t || t === "auto" ? 0 : t) : e.elem[e.prop]
},
set: function(e) {
v.fx.step[e.prop] ? v.fx.step[e.prop](e) : e.elem.style && (e.elem.style[v.cssProps[e.prop]] != null || v.cssHooks[e.prop]) ? v.style(e.elem, e.prop, e.now + e.unit) : e.elem[e.prop] = e.now
}
}
}, Yn.propHooks.scrollTop = Yn.propHooks.scrollLeft = {
set: function(e) {
e.elem.nodeType && e.elem.parentNode && (e.elem[e.prop] = e.now)
}
}, v.each(["toggle", "show", "hide"], function(e, t) {
var n = v.fn[t];
v.fn[t] = function(r, i, s) {
return r == null || typeof r == "boolean" || !e && v.isFunction(r) && v.isFunction(i) ? n.apply(this, arguments) : this.animate(Zn(t, !0), r, i, s)
}
}), v.fn.extend({
fadeTo: function(e, t, n, r) {
return this.filter(Gt).css("opacity", 0).show().end().animate({
opacity: t
}, e, n, r)
},
animate: function(e, t, n, r) {
var i = v.isEmptyObject(e),
s = v.speed(t, n, r),
o = function() {
var t = Kn(this, v.extend({}, e), s);
i && t.stop(!0)
};
return i || s.queue === !1 ? this.each(o) : this.queue(s.queue, o)
},
stop: function(e, n, r) {
var i = function(e) {
var t = e.stop;
delete e.stop, t(r)
};
return typeof e != "string" && (r = n, n = e, e = t), n && e !== !1 && this.queue(e || "fx", []), this.each(function() {
var t = !0,
n = e != null && e + "queueHooks",
s = v.timers,
o = v._data(this);
if (n) o[n] && o[n].stop && i(o[n]);
else
for (n in o) o[n] && o[n].stop && Wn.test(n) && i(o[n]);
for (n = s.length; n--;) s[n].elem === this && (e == null || s[n].queue === e) && (s[n].anim.stop(r), t = !1, s.splice(n, 1));
(t || !r) && v.dequeue(this, e)
})
}
}), v.each({
slideDown: Zn("show"),
slideUp: Zn("hide"),
slideToggle: Zn("toggle"),
fadeIn: {
opacity: "show"
},
fadeOut: {
opacity: "hide"
},
fadeToggle: {
opacity: "toggle"
}
}, function(e, t) {
v.fn[e] = function(e, n, r) {
return this.animate(t, e, n, r)
}
}), v.speed = function(e, t, n) {
var r = e && typeof e == "object" ? v.extend({}, e) : {
complete: n || !n && t || v.isFunction(e) && e,
duration: e,
easing: n && t || t && !v.isFunction(t) && t
};
r.duration = v.fx.off ? 0 : typeof r.duration == "number" ? r.duration : r.duration in v.fx.speeds ? v.fx.speeds[r.duration] : v.fx.speeds._default;
if (r.queue == null || r.queue === !0) r.queue = "fx";
return r.old = r.complete, r.complete = function() {
v.isFunction(r.old) && r.old.call(this), r.queue && v.dequeue(this, r.queue)
}, r
}, v.easing = {
linear: function(e) {
return e
},
swing: function(e) {
return .5 - Math.cos(e * Math.PI) / 2
}
}, v.timers = [], v.fx = Yn.prototype.init, v.fx.tick = function() {
var e, n = v.timers,
r = 0;
qn = v.now();
for (; r < n.length; r++) e = n[r], !e() && n[r] === e && n.splice(r--, 1);
n.length || v.fx.stop(), qn = t
}, v.fx.timer = function(e) {
e() && v.timers.push(e) && !Rn && (Rn = setInterval(v.fx.tick, v.fx.interval))
}, v.fx.interval = 13, v.fx.stop = function() {
clearInterval(Rn), Rn = null
}, v.fx.speeds = {
slow: 600,
fast: 200,
_default: 400
}, v.fx.step = {}, v.expr && v.expr.filters && (v.expr.filters.animated = function(e) {
return v.grep(v.timers, function(t) {
return e === t.elem
}).length
});
var er = /^(?:body|html)$/i;
v.fn.offset = function(e) {
if (arguments.length) return e === t ? this : this.each(function(t) {
v.offset.setOffset(this, e, t)
});
var n, r, i, s, o, u, a, f = {
top: 0,
left: 0
},
l = this[0],
c = l && l.ownerDocument;
if (!c) return;
return (r = c.body) === l ? v.offset.bodyOffset(l) : (n = c.documentElement, v.contains(n, l) ? (typeof l.getBoundingClientRect != "undefined" && (f = l.getBoundingClientRect()), i = tr(c), s = n.clientTop || r.clientTop || 0, o = n.clientLeft || r.clientLeft || 0, u = i.pageYOffset || n.scrollTop, a = i.pageXOffset || n.scrollLeft, {
top: f.top + u - s,
left: f.left + a - o
}) : f)
}, v.offset = {
bodyOffset: function(e) {
var t = e.offsetTop,
n = e.offsetLeft;
return v.support.doesNotIncludeMarginInBodyOffset && (t += parseFloat(v.css(e, "marginTop")) || 0, n += parseFloat(v.css(e, "marginLeft")) || 0), {
top: t,
left: n
}
},
setOffset: function(e, t, n) {
var r = v.css(e, "position");
r === "static" && (e.style.position = "relative");
var i = v(e),
s = i.offset(),
o = v.css(e, "top"),
u = v.css(e, "left"),
a = (r === "absolute" || r === "fixed") && v.inArray("auto", [o, u]) > -1,
f = {},
l = {},
c, h;
a ? (l = i.position(), c = l.top, h = l.left) : (c = parseFloat(o) || 0, h = parseFloat(u) || 0), v.isFunction(t) && (t = t.call(e, n, s)), t.top != null && (f.top = t.top - s.top + c), t.left != null && (f.left = t.left - s.left + h), "using" in t ? t.using.call(e, f) : i.css(f)
}
}, v.fn.extend({
position: function() {
if (!this[0]) return;
var e = this[0],
t = this.offsetParent(),
n = this.offset(),
r = er.test(t[0].nodeName) ? {
top: 0,
left: 0
} : t.offset();
return n.top -= parseFloat(v.css(e, "marginTop")) || 0, n.left -= parseFloat(v.css(e, "marginLeft")) || 0, r.top += parseFloat(v.css(t[0], "borderTopWidth")) || 0, r.left += parseFloat(v.css(t[0], "borderLeftWidth")) || 0, {
top: n.top - r.top,
left: n.left - r.left
}
},
offsetParent: function() {
return this.map(function() {
var e = this.offsetParent || i.body;
while (e && !er.test(e.nodeName) && v.css(e, "position") === "static") e = e.offsetParent;
return e || i.body
})
}
}), v.each({
scrollLeft: "pageXOffset",
scrollTop: "pageYOffset"
}, function(e, n) {
var r = /Y/.test(n);
v.fn[e] = function(i) {
return v.access(this, function(e, i, s) {
var o = tr(e);
if (s === t) return o ? n in o ? o[n] : o.document.documentElement[i] : e[i];
o ? o.scrollTo(r ? v(o).scrollLeft() : s, r ? s : v(o).scrollTop()) : e[i] = s
}, e, i, arguments.length, null)
}
}), v.each({
Height: "height",
Width: "width"
}, function(e, n) {
v.each({
padding: "inner" + e,
content: n,
"": "outer" + e
}, function(r, i) {
v.fn[i] = function(i, s) {
var o = arguments.length && (r || typeof i != "boolean"),
u = r || (i === !0 || s === !0 ? "margin" : "border");
return v.access(this, function(n, r, i) {
var s;
return v.isWindow(n) ? n.document.documentElement["client" + e] : n.nodeType === 9 ? (s = n.documentElement, Math.max(n.body["scroll" + e], s["scroll" + e], n.body["offset" + e], s["offset" + e], s["client" + e])) : i === t ? v.css(n, r, i, u) : v.style(n, r, i, u)
}, n, o ? i : t, o, null)
}
})
}), e.jQuery = e.$ = v, typeof define == "function" && define.amd && define.amd.jQuery && define("jquery", [], function() {
return v
})
})(window),
function(e, t) {
var n = function() {
var t = e._data(document, "events");
return t && t.click && e.grep(t.click, function(e) {
return e.namespace === "rails"
}).length
};
n() && e.error("jquery-ujs has already been loaded!");
var r;
e.rails = r = {
linkClickSelector: "a[data-confirm], a[data-method], a[data-remote], a[data-disable-with]",
inputChangeSelector: "select[data-remote], input[data-remote], textarea[data-remote]",
formSubmitSelector: "form",
formInputClickSelector: "form input[type=submit], form input[type=image], form button[type=submit], form button:not([type])",
disableSelector: "input[data-disable-with], button[data-disable-with], textarea[data-disable-with]",
enableSelector: "input[data-disable-with]:disabled, button[data-disable-with]:disabled, textarea[data-disable-with]:disabled",
requiredInputSelector: "input[name][required]:not([disabled]),textarea[name][required]:not([disabled])",
fileInputSelector: "input:file",
linkDisableSelector: "a[data-disable-with]",
CSRFProtection: function(t) {
var n = e('meta[name="csrf-token"]').attr("content");
n && t.setRequestHeader("X-CSRF-Token", n)
},
fire: function(t, n, r) {
var i = e.Event(n);
return t.trigger(i, r), i.result !== !1
},
confirm: function(e) {
return confirm(e)
},
ajax: function(t) {
return e.ajax(t)
},
href: function(e) {
return e.attr("href")
},
handleRemote: function(n) {
var i, s, o, u, a, f, l, c;
if (r.fire(n, "ajax:before")) {
u = n.data("cross-domain"), a = u === t ? null : u, f = n.data("with-credentials") || null, l = n.data("type") || e.ajaxSettings && e.ajaxSettings.dataType;
if (n.is("form")) {
i = n.attr("method"), s = n.attr("action"), o = n.serializeArray();
var h = n.data("ujs:submit-button");
h && (o.push(h), n.data("ujs:submit-button", null))
} else n.is(r.inputChangeSelector) ? (i = n.data("method"), s = n.data("url"), o = n.serialize(), n.data("params") && (o = o + "&" + n.data("params"))) : (i = n.data("method"), s = r.href(n), o = n.data("params") || null);
c = {
type: i || "GET",
data: o,
dataType: l,
beforeSend: function(e, i) {
return i.dataType === t && e.setRequestHeader("accept", "*/*;q=0.5, " + i.accepts.script), r.fire(n, "ajax:beforeSend", [e, i])
},
success: function(e, t, r) {
n.trigger("ajax:success", [e, t, r])
},
complete: function(e, t) {
n.trigger("ajax:complete", [e, t])
},
error: function(e, t, r) {
n.trigger("ajax:error", [e, t, r])
},
xhrFields: {
withCredentials: f
},
crossDomain: a
}, s && (c.url = s);
var p = r.ajax(c);
return n.trigger("ajax:send", p), p
}
return !1
},
handleMethod: function(n) {
var i = r.href(n),
s = n.data("method"),
o = n.attr("target"),
u = e("meta[name=csrf-token]").attr("content"),
a = e("meta[name=csrf-param]").attr("content"),
f = e('<form method="post" action="' + i + '"></form>'),
l = '<input name="_method" value="' + s + '" type="hidden" />';
a !== t && u !== t && (l += '<input name="' + a + '" value="' + u + '" type="hidden" />'), o && f.attr("target", o), f.hide().append(l).appendTo("body"), f.submit()
},
disableFormElements: function(t) {
t.find(r.disableSelector).each(function() {
var t = e(this),
n = t.is("button") ? "html" : "val";
t.data("ujs:enable-with", t[n]()), t[n](t.data("disable-with")), t.prop("disabled", !0)
})
},
enableFormElements: function(t) {
t.find(r.enableSelector).each(function() {
var t = e(this),
n = t.is("button") ? "html" : "val";
t.data("ujs:enable-with") && t[n](t.data("ujs:enable-with")), t.prop("disabled", !1)
})
},
allowAction: function(e) {
var t = e.data("confirm"),
n = !1,
i;
return t ? (r.fire(e, "confirm") && (n = r.confirm(t), i = r.fire(e, "confirm:complete", [n])), n && i) : !0
},
blankInputs: function(t, n, r) {
var i = e(),
s, o, u = n || "input,textarea",
a = t.find(u);
return a.each(function() {
s = e(this), o = s.is(":checkbox,:radio") ? s.is(":checked") : s.val();
if (!o == !r) {
if (s.is(":radio") && a.filter('input:radio:checked[name="' + s.attr("name") + '"]').length) return !0;
i = i.add(s)
}
}), i.length ? i : !1
},
nonBlankInputs: function(e, t) {
return r.blankInputs(e, t, !0)
},
stopEverything: function(t) {
return e(t.target).trigger("ujs:everythingStopped"), t.stopImmediatePropagation(), !1
},
callFormSubmitBindings: function(n, r) {
var i = n.data("events"),
s = !0;
return i !== t && i.submit !== t && e.each(i.submit, function(e, t) {
if (typeof t.handler == "function") return s = t.handler(r)
}), s
},
disableElement: function(e) {
e.data("ujs:enable-with", e.html()), e.html(e.data("disable-with")), e.bind("click.railsDisable", function(e) {
return r.stopEverything(e)
})
},
enableElement: function(e) {
e.data("ujs:enable-with") !== t && (e.html(e.data("ujs:enable-with")), e.data("ujs:enable-with", !1)), e.unbind("click.railsDisable")
}
}, r.fire(e(document), "rails:attachBindings") && (e.ajaxPrefilter(function(e, t, n) {
e.crossDomain || r.CSRFProtection(n)
}), e(document).delegate(r.linkDisableSelector, "ajax:complete", function() {
r.enableElement(e(this))
}), e(document).delegate(r.linkClickSelector, "click.rails", function(n) {
var i = e(this),
s = i.data("method"),
o = i.data("params");
if (!r.allowAction(i)) return r.stopEverything(n);
i.is(r.linkDisableSelector) && r.disableElement(i);
if (i.data("remote") !== t) {
if ((n.metaKey || n.ctrlKey) &&
(!s || s === "GET") && !o) return !0;
var u = r.handleRemote(i);
return u === !1 ? r.enableElement(i) : u.error(function() {
r.enableElement(i)
}), !1
}
if (i.data("method")) return r.handleMethod(i), !1
}), e(document).delegate(r.inputChangeSelector, "change.rails", function(t) {
var n = e(this);
return r.allowAction(n) ? (r.handleRemote(n), !1) : r.stopEverything(t)
}), e(document).delegate(r.formSubmitSelector, "submit.rails", function(n) {
var i = e(this),
s = i.data("remote") !== t,
o = r.blankInputs(i, r.requiredInputSelector),
u = r.nonBlankInputs(i, r.fileInputSelector);
if (!r.allowAction(i)) return r.stopEverything(n);
if (o && i.attr("novalidate") == t && r.fire(i, "ajax:aborted:required", [o])) return r.stopEverything(n);
if (s) {
if (u) {
setTimeout(function() {
r.disableFormElements(i)
}, 13);
var a = r.fire(i, "ajax:aborted:file", [u]);
return a || setTimeout(function() {
r.enableFormElements(i)
}, 13), a
}
return !e.support.submitBubbles && e().jquery < "1.7" && r.callFormSubmitBindings(i, n) === !1 ? r.stopEverything(n) : (r.handleRemote(i), !1)
}
setTimeout(function() {
r.disableFormElements(i)
}, 13)
}), e(document).delegate(r.formInputClickSelector, "click.rails", function(t) {
var n = e(this);
if (!r.allowAction(n)) return r.stopEverything(t);
var i = n.attr("name"),
s = i ? {
name: i,
value: n.val()
} : null;
n.closest("form").data("ujs:submit-button", s)
}), e(document).delegate(r.formSubmitSelector, "ajax:beforeSend.rails", function(t) {
this == t.target && r.disableFormElements(e(this))
}), e(document).delegate(r.formSubmitSelector, "ajax:complete.rails", function(t) {
this == t.target && r.enableFormElements(e(this))
}), e(function() {
csrf_token = e("meta[name=csrf-token]").attr("content"), csrf_param = e("meta[name=csrf-param]").attr("content"), e('form input[name="' + csrf_param + '"]').val(csrf_token)
}))
}(jQuery), ! function(e) {
"use strict";
e(function() {
e.support.transition = function() {
var e = function() {
var e = document.createElement("bootstrap"),
t = {
WebkitTransition: "webkitTransitionEnd",
MozTransition: "transitionend",
OTransition: "oTransitionEnd otransitionend",
transition: "transitionend"
},
n;
for (n in t)
if (e.style[n] !== undefined) return t[n]
}();
return e && {
end: e
}
}()
})
}(window.jQuery), ! function(e) {
"use strict";
var t = '[data-dismiss="alert"]',
n = function(n) {
e(n).on("click", t, this.close)
};
n.prototype.close = function(t) {
function s() {
i.trigger("closed").remove()
}
var n = e(this),
r = n.attr("data-target"),
i;
r || (r = n.attr("href"), r = r && r.replace(/.*(?=#[^\s]*$)/, "")), i = e(r), t && t.preventDefault(), i.length || (i = n.hasClass("alert") ? n : n.parent()), i.trigger(t = e.Event("close"));
if (t.isDefaultPrevented()) return;
i.removeClass("in"), e.support.transition && i.hasClass("fade") ? i.on(e.support.transition.end, s) : s()
}, e.fn.alert = function(t) {
return this.each(function() {
var r = e(this),
i = r.data("alert");
i || r.data("alert", i = new n(this)), typeof t == "string" && i[t].call(r)
})
}, e.fn.alert.Constructor = n, e(document).on("click.alert.data-api", t, n.prototype.close)
}(window.jQuery), ! function(e) {
"use strict";
var t = function(t, n) {
this.options = n, this.$element = e(t).delegate('[data-dismiss="modal"]', "click.dismiss.modal", e.proxy(this.hide, this)), this.options.remote && this.$element.find(".modal-body").load(this.options.remote)
};
t.prototype = {
constructor: t,
toggle: function() {
return this[this.isShown ? "hide" : "show"]()
},
show: function() {
var t = this,
n = e.Event("show");
this.$element.trigger(n);
if (this.isShown || n.isDefaultPrevented()) return;
this.isShown = !0, this.escape(), this.backdrop(function() {
var n = e.support.transition && t.$element.hasClass("fade");
t.$element.parent().length || t.$element.appendTo(document.body), t.$element.show(), n && t.$element[0].offsetWidth, t.$element.addClass("in").attr("aria-hidden", !1), t.enforceFocus(), n ? t.$element.one(e.support.transition.end, function() {
t.$element.focus().trigger("shown")
}) : t.$element.focus().trigger("shown")
})
},
hide: function(t) {
t && t.preventDefault();
var n = this;
t = e.Event("hide"), this.$element.trigger(t);
if (!this.isShown || t.isDefaultPrevented()) return;
this.isShown = !1, this.escape(), e(document).off("focusin.modal"), this.$element.removeClass("in").attr("aria-hidden", !0), e.support.transition && this.$element.hasClass("fade") ? this.hideWithTransition() : this.hideModal()
},
enforceFocus: function() {
var t = this;
e(document).on("focusin.modal", function(e) {
t.$element[0] !== e.target && !t.$element.has(e.target).length && t.$element.focus()
})
},
escape: function() {
var e = this;
this.isShown && this.options.keyboard ? this.$element.on("keyup.dismiss.modal", function(t) {
t.which == 27 && e.hide()
}) : this.isShown || this.$element.off("keyup.dismiss.modal")
},
hideWithTransition: function() {
var t = this,
n = setTimeout(function() {
t.$element.off(e.support.transition.end), t.hideModal()
}, 500);
this.$element.one(e.support.transition.end, function() {
clearTimeout(n), t.hideModal()
})
},
hideModal: function(e) {
this.$element.hide().trigger("hidden"), this.backdrop()
},
removeBackdrop: function() {
this.$backdrop.remove(), this.$backdrop = null
},
backdrop: function(t) {
var n = this,
r = this.$element.hasClass("fade") ? "fade" : "";
if (this.isShown && this.options.backdrop) {
var i = e.support.transition && r;
this.$backdrop = e('<div class="modal-backdrop ' + r + '" />').appendTo(document.body), this.$backdrop.click(this.options.backdrop == "static" ? e.proxy(this.$element[0].focus, this.$element[0]) : e.proxy(this.hide, this)), i && this.$backdrop[0].offsetWidth, this.$backdrop.addClass("in"), i ? this.$backdrop.one(e.support.transition.end, t) : t()
} else !this.isShown && this.$backdrop ? (this.$backdrop.removeClass("in"), e.support.transition && this.$element.hasClass("fade") ? this.$backdrop.one(e.support.transition.end, e.proxy(this.removeBackdrop, this)) : this.removeBackdrop()) : t && t()
}
}, e.fn.modal = function(n) {
return this.each(function() {
var r = e(this),
i = r.data("modal"),
s = e.extend({}, e.fn.modal.defaults, r.data(), typeof n == "object" && n);
i || r.data("modal", i = new t(this, s)), typeof n == "string" ? i[n]() : s.show && i.show()
})
}, e.fn.modal.defaults = {
backdrop: !0,
keyboard: !0,
show: !0
}, e.fn.modal.Constructor = t, e(document).on("click.modal.data-api", '[data-toggle="modal"]', function(t) {
var n = e(this),
r = n.attr("href"),
i = e(n.attr("data-target") || r && r.replace(/.*(?=#[^\s]+$)/, "")),
s = i.data("modal") ? "toggle" : e.extend({
remote: !/#/.test(r) && r
}, i.data(), n.data());
t.preventDefault(), i.modal(s).one("hide", function() {
n.focus()
})
})
}(window.jQuery), ! function(e) {
"use strict";
function r() {
e(t).each(function() {
i(e(this)).removeClass("open")
})
}
function i(t) {
var n = t.attr("data-target"),
r;
return n || (n = t.attr("href"), n = n && /#/.test(n) && n.replace(/.*(?=#[^\s]*$)/, "")), r = e(n), r.length || (r = t.parent()), r
}
var t = "[data-toggle=dropdown]",
n = function(t) {
var n = e(t).on("click.dropdown.data-api", this.toggle);
e("html").on("click.dropdown.data-api", function() {
n.parent().removeClass("open")
})
};
n.prototype = {
constructor: n,
toggle: function(t) {
var n = e(this),
s, o;
if (n.is(".disabled, :disabled")) return;
return s = i(n), o = s.hasClass("open"), r(), o || (s.toggleClass("open"), n.focus()), !1
},
keydown: function(t) {
var n, r, s, o, u, a;
if (!/(38|40|27)/.test(t.keyCode)) return;
n = e(this), t.preventDefault(), t.stopPropagation();
if (n.is(".disabled, :disabled")) return;
o = i(n), u = o.hasClass("open");
if (!u || u && t.keyCode == 27) return n.click();
r = e("[role=menu] li:not(.divider) a", o);
if (!r.length) return;
a = r.index(r.filter(":focus")), t.keyCode == 38 && a > 0 && a--, t.keyCode == 40 && a < r.length - 1 && a++, ~a || (a = 0), r.eq(a).focus()
}
}, e.fn.dropdown = function(t) {
return this.each(function() {
var r = e(this),
i = r.data("dropdown");
i || r.data("dropdown", i = new n(this)), typeof t == "string" && i[t].call(r)
})
}, e.fn.dropdown.Constructor = n, e(document).on("click.dropdown.data-api touchstart.dropdown.data-api", r).on("click.dropdown touchstart.dropdown.data-api", ".dropdown form", function(e) {
e.stopPropagation()
}).on("click.dropdown.data-api touchstart.dropdown.data-api", t, n.prototype.toggle).on("keydown.dropdown.data-api touchstart.dropdown.data-api", t + ", [role=menu]", n.prototype.keydown)
}(window.jQuery), ! function(e) {
"use strict";
function t(t, n) {
var r = e.proxy(this.process, this),
i = e(t).is("body") ? e(window) : e(t),
s;
this.options = e.extend({}, e.fn.scrollspy.defaults, n), this.$scrollElement = i.on("scroll.scroll-spy.data-api", r), this.selector = (this.options.target || (s = e(t).attr("href")) && s.replace(/.*(?=#[^\s]+$)/, "") || "") + " .nav li > a", this.$body = e("body"), this.refresh(), this.process()
}
t.prototype = {
constructor: t,
refresh: function() {
var t = this,
n;
this.offsets = e([]), this.targets = e([]), n = this.$body.find(this.selector).map(function() {
var t = e(this),
n = t.data("target") || t.attr("href"),
r = /^#\w/.test(n) && e(n);
return r && r.length && [
[r.position().top, n]
] || null
}).sort(function(e, t) {
return e[0] - t[0]
}).each(function() {
t.offsets.push(this[0]), t.targets.push(this[1])
})
},
process: function() {
var e = this.$scrollElement.scrollTop() + this.options.offset,
t = this.$scrollElement[0].scrollHeight || this.$body[0].scrollHeight,
n = t - this.$scrollElement.height(),
r = this.offsets,
i = this.targets,
s = this.activeTarget,
o;
if (e >= n) return s != (o = i.last()[0]) && this.activate(o);
for (o = r.length; o--;) s != i[o] && e >= r[o] && (!r[o + 1] || e <= r[o + 1]) && this.activate(i[o])
},
activate: function(t) {
var n, r;
this.activeTarget = t, e(this.selector).parent(".active").removeClass("active"), r = this.selector + '[data-target="' + t + '"],' + this.selector + '[href="' + t + '"]', n = e(r).parent("li").addClass("active"), n.parent(".dropdown-menu").length && (n = n.closest("li.dropdown").addClass("active")), n.trigger("activate")
}
}, e.fn.scrollspy = function(n) {
return this.each(function() {
var r = e(this),
i = r.data("scrollspy"),
s = typeof n == "object" && n;
i || r.data("scrollspy", i = new t(this, s)), typeof n == "string" && i[n]()
})
}, e.fn.scrollspy.Constructor = t, e.fn.scrollspy.defaults = {
offset: 10
}, e(window).on("load", function() {
e('[data-spy="scroll"]').each(function() {
var t = e(this);
t.scrollspy(t.data())
})
})
}(window.jQuery), ! function(e) {
"use strict";
var t = function(t) {
this.element = e(t)
};
t.prototype = {
constructor: t,
show: function() {
var t = this.element,
n = t.closest("ul:not(.dropdown-menu)"),
r = t.attr("data-target"),
i, s, o;
r || (r = t.attr("href"), r = r && r.replace(/.*(?=#[^\s]*$)/, ""));
if (t.parent("li").hasClass("active")) return;
i = n.find(".active:last a")[0], o = e.Event("show", {
relatedTarget: i
}), t.trigger(o);
if (o.isDefaultPrevented()) return;
s = e(r), this.activate(t.parent("li"), n), this.activate(s, s.parent(), function() {
t.trigger({
type: "shown",
relatedTarget: i
})
})
},
activate: function(t, n, r) {
function o() {
i.removeClass("active").find("> .dropdown-menu > .active").removeClass("active"), t.addClass("active"), s ? (t[0].offsetWidth, t.addClass("in")) : t.removeClass("fade"), t.parent(".dropdown-menu") && t.closest("li.dropdown").addClass("active"), r && r()
}
var i = n.find("> .active"),
s = r && e.support.transition && i.hasClass("fade");
s ? i.one(e.support.transition.end, o) : o(), i.removeClass("in")
}
}, e.fn.tab = function(n) {
return this.each(function() {
var r = e(this),
i = r.data("tab");
i || r.data("tab", i = new t(this)), typeof n == "string" && i[n]()
})
}, e.fn.tab.Constructor = t, e(document).on("click.tab.data-api", '[data-toggle="tab"], [data-toggle="pill"]', function(t) {
t.preventDefault(), e(this).tab("show")
})
}(window.jQuery), ! function(e) {
"use strict";
var t = function(e, t) {
this.init("tooltip", e, t)
};
t.prototype = {
constructor: t,
init: function(t, n, r) {
var i, s;
this.type = t, this.$element = e(n), this.options = this.getOptions(r), this.enabled = !0, this.options.trigger == "click" ? this.$element.on("click." + this.type, this.options.selector, e.proxy(this.toggle, this)) : this.options.trigger != "manual" && (i = this.options.trigger == "hover" ? "mouseenter" : "focus", s = this.options.trigger == "hover" ? "mouseleave" : "blur", this.$element.on(i + "." + this.type, this.options.selector, e.proxy(this.enter, this)), this.$element.on(s + "." + this.type, this.options.selector, e.proxy(this.leave, this))), this.options.selector ? this._options = e.extend({}, this.options, {
trigger: "manual",
selector: ""
}) : this.fixTitle()
},
getOptions: function(t) {
return t = e.extend({}, e.fn[this.type].defaults, t, this.$element.data()), t.delay && typeof t.delay == "number" && (t.delay = {
show: t.delay,
hide: t.delay
}), t
},
enter: function(t) {
var n = e(t.currentTarget)[this.type](this._options).data(this.type);
if (!n.options.delay || !n.options.delay.show) return n.show();
clearTimeout(this.timeout), n.hoverState = "in", this.timeout = setTimeout(function() {
n.hoverState == "in" && n.show()
}, n.options.delay.show)
},
leave: function(t) {
var n = e(t.currentTarget)[this.type](this._options).data(this.type);
this.timeout && clearTimeout(this.timeout);
if (!n.options.delay || !n.options.delay.hide) return n.hide();
n.hoverState = "out", this.timeout = setTimeout(function() {
n.hoverState == "out" && n.hide()
}, n.options.delay.hide)
},
show: function() {
var e, t, n, r, i, s, o;
if (this.hasContent() && this.enabled) {
e = this.tip(), this.setContent(), this.options.animation && e.addClass("fade"), s = typeof this.options.placement == "function" ? this.options.placement.call(this, e[0], this.$element[0]) : this.options.placement, t = /in/.test(s), e.detach().css({
top: 0,
left: 0,
display: "block"
}).insertAfter(this.$element), n = this.getPosition(t), r = e[0].offsetWidth, i = e[0].offsetHeight;
switch (t ? s.split(" ")[1] : s) {
case "bottom":
o = {
top: n.top + n.height,
left: n.left + n.width / 2 - r / 2
};
break;
case "top":
o = {
top: n.top - i,
left: n.left + n.width / 2 - r / 2
};
break;
case "left":
o = {
top: n.top + n.height / 2 - i / 2,
left: n.left - r
};
break;
case "right":
o = {
top: n.top + n.height / 2 - i / 2,
left: n.left + n.width
}
}
e.offset(o).addClass(s).addClass("in")
}
},
setContent: function() {
var e = this.tip(),
t = this.getTitle();
e.find(".tooltip-inner")[this.options.html ? "html" : "text"](t), e.removeClass("fade in top bottom left right")
},
hide: function() {
function r() {
var t = setTimeout(function() {
n.off(e.support.transition.end).detach()
}, 500);
n.one(e.support.transition.end, function() {
clearTimeout(t), n.detach()
})
}
var t = this,
n = this.tip();
return n.removeClass("in"), e.support.transition && this.$tip.hasClass("fade") ? r() : n.detach(), this
},
fixTitle: function() {
var e = this.$element;
(e.attr("title") || typeof e.attr("data-original-title") != "string") && e.attr("data-original-title", e.attr("title") || "").removeAttr("title")
},
hasContent: function() {
return this.getTitle()
},
getPosition: function(t) {
return e.extend({}, t ? {
top: 0,
left: 0
} : this.$element.offset(), {
width: this.$element[0].offsetWidth,
height: this.$element[0].offsetHeight
})
},
getTitle: function() {
var e, t = this.$element,
n = this.options;
return e = t.attr("data-original-title") || (typeof n.title == "function" ? n.title.call(t[0]) : n.title), e
},
tip: function() {
return this.$tip = this.$tip || e(this.options.template)
},
validate: function() {
this.$element[0].parentNode || (this.hide(), this.$element = null, this.options = null)
},
enable: function() {
this.enabled = !0
},
disable: function() {
this.enabled = !1
},
toggleEnabled: function() {
this.enabled = !this.enabled
},
toggle: function(t) {
var n = e(t.currentTarget)[this.type](this._options).data(this.type);
n[n.tip().hasClass("in") ? "hide" : "show"]()
},
destroy: function() {
this.hide().$element.off("." + this.type).removeData(this.type)
}
}, e.fn.tooltip = function(n) {
return this.each(function() {
var r = e(this),
i = r.data("tooltip"),
s = typeof n == "object" && n;
i || r.data("tooltip", i = new t(this, s)), typeof n == "string" && i[n]()
})
}, e.fn.tooltip.Constructor = t, e.fn.tooltip.defaults = {
animation: !0,
placement: "top",
selector: !1,
template: '<div class="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>',
trigger: "hover",
title: "",
delay: 0,
html: !1
}
}(window.jQuery), ! function(e) {
"use strict";
var t = function(e, t) {
this.init("popover", e, t)
};
t.prototype = e.extend({}, e.fn.tooltip.Constructor.prototype, {
constructor: t,
setContent: function() {
var e = this.tip(),
t = this.getTitle(),
n = this.getContent();
e.find(".popover-title")[this.options.html ? "html" : "text"](t), e.find(".popover-content > *")[this.options.html ? "html" : "text"](n), e.removeClass("fade top bottom left right in")
},
hasContent: function() {
return this.getTitle() || this.getContent()
},
getContent: function() {
var e, t = this.$element,
n = this.options;
return e = t.attr("data-content") || (typeof n.content == "function" ? n.content.call(t[0]) : n.content), e
},
tip: function() {
return this.$tip || (this.$tip = e(this.options.template)), this.$tip
},
destroy: function() {
this.hide().$element.off("." + this.type).removeData(this.type)
}
}), e.fn.popover = function(n) {
return this.each(function() {
var r = e(this),
i = r.data("popover"),
s = typeof n == "object" && n;
i || r.data("popover", i = new t(this, s)), typeof n == "string" && i[n]()
})
}, e.fn.popover.Constructor = t, e.fn.popover.defaults = e.extend({}, e.fn.tooltip.defaults, {
placement: "right",
trigger: "click",
content: "",
template: '<div class="popover"><div class="arrow"></div><div class="popover-inner"><h3 class="popover-title"></h3><div class="popover-content"><p></p></div></div></div>'
})
}(window.jQuery), ! function(e) {
"use strict";
var t = function(t, n) {
this.$element = e(t), this.options = e.extend({}, e.fn.button.defaults, n)
};
t.prototype.setState = function(e) {
var t = "disabled",
n = this.$element,
r = n.data(),
i = n.is("input") ? "val" : "html";
e += "Text", r.resetText || n.data("resetText", n[i]()), n[i](r[e] || this.options[e]), setTimeout(function() {
e == "loadingText" ? n.addClass(t).attr(t, t) : n.removeClass(t).removeAttr(t)
}, 0)
}, t.prototype.toggle = function() {
var e = this.$element.closest('[data-toggle="buttons-radio"]');
e && e.find(".active").removeClass("active"), this.$element.toggleClass("active")
}, e.fn.button = function(n) {
return this.each(function() {
var r = e(this),
i = r.data("button"),
s = typeof n == "object" && n;
i || r.data("button", i = new t(this, s)), n == "toggle" ? i.toggle() : n && i.setState(n)
})
}, e.fn.button.defaults = {
loadingText: "loading..."
}, e.fn.button.Constructor = t, e(document).on("click.button.data-api", "[data-toggle^=button]", function(t) {
var n = e(t.target);
n.hasClass("btn") || (n = n.closest(".btn")), n.button("toggle")
})
}(window.jQuery), ! function(e) {
"use strict";
var t = function(t, n) {
this.$element = e(t), this.options = e.extend({}, e.fn.collapse.defaults, n), this.options.parent && (this.$parent = e(this.options.parent)), this.options.toggle && this.toggle()
};
t.prototype = {
constructor: t,
dimension: function() {
var e = this.$element.hasClass("width");
return e ? "width" : "height"
},
show: function() {
var t, n, r, i;
if (this.transitioning) return;
t = this.dimension(), n = e.camelCase(["scroll", t].join("-")), r = this.$parent && this.$parent.find("> .accordion-group > .in");
if (r && r.length) {
i = r.data("collapse");
if (i && i.transitioning) return;
r.collapse("hide"), i || r.data("collapse", null)
}
this.$element[t](0), this.transition("addClass", e.Event("show"), "shown"), e.support.transition && this.$element[t](this.$element[0][n])
},
hide: function() {
var t;
if (this.transitioning) return;
t = this.dimension(), this.reset(this.$element[t]()), this.transition("removeClass", e.Event("hide"), "hidden"), this.$element[t](0)
},
reset: function(e) {
var t = this.dimension();
return this.$element.removeClass("collapse")[t](e || "auto")[0].offsetWidth, this.$element[e !== null ? "addClass" : "removeClass"]("collapse"), this
},
transition: function(t, n, r) {
var i = this,
s = function() {
n.type == "show" && i.reset(), i.transitioning = 0, i.$element.trigger(r)
};
this.$element.trigger(n);
if (n.isDefaultPrevented()) return;
this.transitioning = 1, this.$element[t]("in"), e.support.transition && this.$element.hasClass("collapse") ? this.$element.one(e.support.transition.end, s) : s()
},
toggle: function() {
this[this.$element.hasClass("in") ? "hide" : "show"]()
}
}, e.fn.collapse = function(n) {
return this.each(function() {
var r = e(this),
i = r.data("collapse"),
s = typeof n == "object" && n;
i || r.data("collapse", i = new t(this, s)), typeof n == "string" && i[n]()
})
}, e.fn.collapse.defaults = {
toggle: !0
}, e.fn.collapse.Constructor = t, e(document).on("click.collapse.data-api", "[data-toggle=collapse]", function(t) {
var n = e(this),
r, i = n.attr("data-target") || t.preventDefault() || (r = n.attr("href")) && r.replace(/.*(?=#[^\s]+$)/, ""),
s = e(i).data("collapse") ? "toggle" : n.data();
n[e(i).hasClass("in") ? "addClass" : "removeClass"]("collapsed"), e(i).collapse(s)
})
}(window.jQuery), ! function(e) {
"use strict";
var t = function(t, n) {
this.$element = e(t), this.options = n, this.options.slide && this.slide(this.options.slide), this.options.pause == "hover" && this.$element.on("mouseenter", e.proxy(this.pause, this)).on("mouseleave", e.proxy(this.cycle, this))
};
t.prototype = {
cycle: function(t) {
return t || (this.paused = !1), this.options.interval && !this.paused && (this.interval = setInterval(e.proxy(this.next, this), this.options.interval)), this
},
to: function(t) {
var n = this.$element.find(".item.active"),
r = n.parent().children(),
i = r.index(n),
s = this;
if (t > r.length - 1 || t < 0) return;
return this.sliding ? this.$element.one("slid", function() {
s.to(t)
}) : i == t ? this.pause().cycle() : this.slide(t > i ? "next" : "prev", e(r[t]))
},
pause: function(t) {
return t || (this.paused = !0), this.$element.find(".next, .prev").length && e.support.transition.end && (this.$element.trigger(e.support.transition.end), this.cycle()), clearInterval(this.interval), this.interval = null, this
},
next: function() {
if (this.sliding) return;
return this.slide("next")
},
prev: function() {
if (this.sliding) return;
return this.slide("prev")
},
slide: function(t, n) {
var r = this.$element.find(".item.active"),
i = n || r[t](),
s = this.interval,
o = t == "next" ? "left" : "right",
u = t == "next" ? "first" : "last",
a = this,
f;
this.sliding = !0, s && this.pause(), i = i.length ? i : this.$element.find(".item")[u](), f = e.Event("slide", {
relatedTarget: i[0]
});
if (i.hasClass("active")) return;
if (e.support.transition && this.$element.hasClass("slide")) {
this.$element.trigger(f);
if (f.isDefaultPrevented()) return;
i.addClass(t), i[0].offsetWidth, r.addClass(o), i.addClass(o), this.$element.one(e.support.transition.end, function() {
i.removeClass([t, o].join(" ")).addClass("active"), r.removeClass(["active", o].join(" ")), a.sliding = !1, setTimeout(function() {
a.$element.trigger("slid")
}, 0)
})
} else {
this.$element.trigger(f);
if (f.isDefaultPrevented()) return;
r.removeClass("active"), i.addClass("active"), this.sliding = !1, this.$element.trigger("slid")
}
return s && this.cycle(), this
}
}, e.fn.carousel = function(n) {
return this.each(function() {
var r = e(this),
i = r.data("carousel"),
s = e.extend({}, e.fn.carousel.defaults, typeof n == "object" && n),
o = typeof n == "string" ? n : s.slide;
i || r.data("carousel", i = new t(this, s)), typeof n == "number" ? i.to(n) : o ? i[o]() : s.interval && i.cycle()
})
}, e.fn.carousel.defaults = {
interval: 5e3,
pause: "hover"
}, e.fn.carousel.Constructor = t, e(document).on("click.carousel.data-api", "[data-slide]", function(t) {
var n = e(this),
r, i = e(n.attr("data-target") || (r = n.attr("href")) && r.replace(/.*(?=#[^\s]+$)/, "")),
s = e.extend({}, i.data(), n.data());
i.carousel(s), t.preventDefault()
})
}(window.jQuery), ! function(e) {
"use strict";
var t = function(t, n) {
this.$element = e(t), this.options = e.extend({}, e.fn.typeahead.defaults, n), this.matcher = this.options.matcher || this.matcher, this.sorter = this.options.sorter || this.sorter, this.highlighter = this.options.highlighter || this.highlighter, this.updater = this.options.updater || this.updater, this.$menu = e(this.options.menu).appendTo("body"), this.source = this.options.source, this.shown = !1, this.listen()
};
t.prototype = {
constructor: t,
select: function() {
var e = this.$menu.find(".active").attr("data-value");
return this.$element.val(this.updater(e)).change(), this.hide()
},
updater: function(e) {
return e
},
show: function() {
var t = e.extend({}, this.$element.offset(), {
height: this.$element[0].offsetHeight
});
return this.$menu.css({
top: t.top + t.height,
left: t.left
}), this.$menu.show(), this.shown = !0, this
},
hide: function() {
return this.$menu.hide(), this.shown = !1, this
},
lookup: function(t) {
var n;
return this.query = this.$element.val(), !this.query || this.query.length < this.options.minLength ? this.shown ? this.hide() : this : (n = e.isFunction(this.source) ? this.source(this.query, e.proxy(this.process, this)) : this.source, n ? this.process(n) : this)
},
process: function(t) {
var n = this;
return t = e.grep(t, function(e) {
return n.matcher(e)
}), t = this.sorter(t), t.length ? this.render(t.slice(0, this.options.items)).show() : this.shown ? this.hide() : this
},
matcher: function(e) {
return ~e.toLowerCase().indexOf(this.query.toLowerCase())
},
sorter: function(e) {
var t = [],
n = [],
r = [],
i;
while (i = e.shift()) i.toLowerCase().indexOf(this.query.toLowerCase()) ? ~i.indexOf(this.query) ? n.push(i) : r.push(i) : t.push(i);
return t.concat(n, r)
},
highlighter: function(e) {
var t = this.query.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&");
return e.replace(new RegExp("(" + t + ")", "ig"), function(e, t) {
return "<strong>" + t + "</strong>"
})
},
render: function(t) {
var n = this;
return t = e(t).map(function(t, r) {
return t = e(n.options.item).attr("data-value", r), t.find("a").html(n.highlighter(r)), t[0]
}), t.first().addClass("active"), this.$menu.html(t), this
},
next: function(t) {
var n = this.$menu.find(".active").removeClass("active"),
r = n.next();
r.length || (r = e(this.$menu.find("li")[0])), r.addClass("active")
},
prev: function(e) {
var t = this.$menu.find(".active").removeClass("active"),
n = t.prev();
n.length || (n = this.$menu.find("li").last()), n.addClass("active")
},
listen: function() {
this.$element.on("blur", e.proxy(this.blur, this)).on("keypress", e.proxy(this.keypress, this)).on("keyup", e.proxy(this.keyup, this)), this.eventSupported("keydown") && this.$element.on("keydown", e.proxy(this.keydown, this)), this.$menu.on("click", e.proxy(this.click, this)).on("mouseenter", "li", e.proxy(this.mouseenter, this))
},
eventSupported: function(e) {
var t = e in this.$element;
return t || (this.$element.setAttribute(e, "return;"), t = typeof this.$element[e] == "function"), t
},
move: function(e) {
if (!this.shown) return;
switch (e.keyCode) {
case 9:
case 13:
case 27:
e.preventDefault();
break;
case 38:
e.preventDefault(), this.prev();
break;
case 40:
e.preventDefault(), this.next()
}
e.stopPropagation()
},
keydown: function(t) {
this.suppressKeyPressRepeat = !~e.inArray(t.keyCode, [40, 38, 9, 13, 27]), this.move(t)
},
keypress: function(e) {
if (this.suppressKeyPressRepeat) return;
this.move(e)
},
keyup: function(e) {
switch (e.keyCode) {
case 40:
case 38:
case 16:
case 17:
case 18:
break;
case 9:
case 13:
if (!this.shown) return;
this.select();
break;
case 27:
if (!this.shown) return;
this.hide();
break;
default:
this.lookup()
}
e.stopPropagation(), e.preventDefault()
},
blur: function(e) {
var t = this;
setTimeout(function() {
t.hide()
}, 150)
},
click: function(e) {
e.stopPropagation(), e.preventDefault(), this.select()
},
mouseenter: function(t) {
this.$menu.find(".active").removeClass("active"), e(t.currentTarget).addClass("active")
}
}, e.fn.typeahead = function(n) {
return this.each(function() {
var r = e(this),
i = r.data("typeahead"),
s = typeof n == "object" && n;
i || r.data("typeahead", i = new t(this, s)), typeof n == "string" && i[n]()
})
}, e.fn.typeahead.defaults = {
source: [],
items: 8,
menu: '<ul class="typeahead dropdown-menu"></ul>',
item: '<li><a href="#"></a></li>',
minLength: 1
}, e.fn.typeahead.Constructor = t, e(document).on("focus.typeahead.data-api", '[data-provide="typeahead"]', function(t) {
var n = e(this);
if (n.data("typeahead")) return;
t.preventDefault(), n.typeahead(n.data())
})
}(window.jQuery), ! function(e) {
"use strict";
var t = function(t, n) {
this.options = e.extend({}, e.fn.affix.defaults, n), this.$window = e(window).on("scroll.affix.data-api", e.proxy(this.checkPosition, this)).on("click.affix.data-api", e.proxy(function() {
setTimeout(e.proxy(this.checkPosition, this), 1)
}, this)), this.$element = e(t), this.checkPosition()
};
t.prototype.checkPosition = function() {
if (!this.$element.is(":visible")) return;
var t = e(document).height(),
n = this.$window.scrollTop(),
r = this.$element.offset(),
i = this.options.offset,
s = i.bottom,
o = i.top,
u = "affix affix-top affix-bottom",
a;
typeof i != "object" && (s = o = i), typeof o == "function" && (o = i.top()), typeof s == "function" && (s = i.bottom()), a = this.unpin != null && n + this.unpin <= r.top ? !1 : s != null && r.top + this.$element.height() >= t - s ? "bottom" : o != null && n <= o ? "top" : !1;
if (this.affixed === a) return;
this.affixed = a, this.unpin = a == "bottom" ? r.top - n : null, this.$element.removeClass(u).addClass("affix" + (a ? "-" + a : ""))
}, e.fn.affix = function(n) {
return this.each(function() {
var r = e(this),
i = r.data("affix"),
s = typeof n == "object" && n;
i || r.data("affix", i = new t(this, s)), typeof n == "string" && i[n]()
})
}, e.fn.affix.Constructor = t, e.fn.affix.defaults = {
offset: 0
}, e(window).on("load", function() {
e('[data-spy="affix"]').each(function() {
var t = e(this),
n = t.data();
n.offset = n.offset || {}, n.offsetBottom && (n.offset.bottom = n.offsetBottom), n.offsetTop && (n.offset.top = n.offsetTop), t.affix(n)
})
})
}(window.jQuery),
function(e, t) {
function i(t, n) {
var r, i, o, u = t.nodeName.toLowerCase();
return "area" === u ? (r = t.parentNode, i = r.name, !t.href || !i || r.nodeName.toLowerCase() !== "map" ? !1 : (o = e("img[usemap=#" + i + "]")[0], !!o && s(o))) : (/input|select|textarea|button|object/.test(u) ? !t.disabled : "a" === u ? t.href || n : n) && s(t)
}
function s(t) {
return e.expr.filters.visible(t) && !e(t).parents().andSelf().filter(function() {
return e.css(this, "visibility") === "hidden"
}).length
}
var n = 0,
r = /^ui-id-\d+$/;
e.ui = e.ui || {};
if (e.ui.version) return;
e.extend(e.ui, {
version: "1.9.2",
keyCode: {
BACKSPACE: 8,
COMMA: 188,
DELETE: 46,
DOWN: 40,
END: 35,
ENTER: 13,
ESCAPE: 27,
HOME: 36,
LEFT: 37,
NUMPAD_ADD: 107,
NUMPAD_DECIMAL: 110,
NUMPAD_DIVIDE: 111,
NUMPAD_ENTER: 108,
NUMPAD_MULTIPLY: 106,
NUMPAD_SUBTRACT: 109,
PAGE_DOWN: 34,
PAGE_UP: 33,
PERIOD: 190,
RIGHT: 39,
SPACE: 32,
TAB: 9,
UP: 38
}
}), e.fn.extend({
_focus: e.fn.focus,
focus: function(t, n) {
return typeof t == "number" ? this.each(function() {
var r = this;
setTimeout(function() {
e(r).focus(), n && n.call(r)
}, t)
}) : this._focus.apply(this, arguments)
},
scrollParent: function() {
var t;
return e.ui.ie && /(static|relative)/.test(this.css("position")) || /absolute/.test(this.css("position")) ? t = this.parents().filter(function() {
return /(relative|absolute|fixed)/.test(e.css(this, "position")) && /(auto|scroll)/.test(e.css(this, "overflow") + e.css(this, "overflow-y") + e.css(this, "overflow-x"))
}).eq(0) : t = this.parents().filter(function() {
return /(auto|scroll)/.test(e.css(this, "overflow") + e.css(this, "overflow-y") + e.css(this, "overflow-x"))
}).eq(0), /fixed/.test(this.css("position")) || !t.length ? e(document) : t
},
zIndex: function(n) {
if (n !== t) return this.css("zIndex", n);
if (this.length) {
var r = e(this[0]),
i, s;
while (r.length && r[0] !== document) {
i = r.css("position");
if (i === "absolute" || i === "relative" || i === "fixed") {
s = parseInt(r.css("zIndex"), 10);
if (!isNaN(s) && s !== 0) return s
}
r = r.parent()
}
}
return 0
},
uniqueId: function() {
return this.each(function() {
this.id || (this.id = "ui-id-" + ++n)
})
},
removeUniqueId: function() {
return this.each(function() {
r.test(this.id) && e(this).removeAttr("id")
})
}
}), e.extend(e.expr[":"], {
data: e.expr.createPseudo ? e.expr.createPseudo(function(t) {
return function(n) {
return !!e.data(n, t)
}
}) : function(t, n, r) {
return !!e.data(t, r[3])
},
focusable: function(t) {
return i(t, !isNaN(e.attr(t, "tabindex")))
},
tabbable: function(t) {
var n = e.attr(t, "tabindex"),
r = isNaN(n);
return (r || n >= 0) && i(t, !r)
}
}), e(function() {
var t = document.body,
n = t.appendChild(n = document.createElement("div"));
n.offsetHeight, e.extend(n.style, {
minHeight: "100px",
height: "auto",
padding: 0,
borderWidth: 0
}), e.support.minHeight = n.offsetHeight === 100, e.support.selectstart = "onselectstart" in n, t.removeChild(n).style.display = "none"
}), e("<a>").outerWidth(1).jquery || e.each(["Width", "Height"], function(n, r) {
function u(t, n, r, s) {
return e.each(i, function() {
n -= parseFloat(e.css(t, "padding" + this)) || 0, r && (n -= parseFloat(e.css(t, "border" + this + "Width")) || 0), s && (n -= parseFloat(e.css(t, "margin" + this)) || 0)
}), n
}
var i = r === "Width" ? ["Left", "Right"] : ["Top", "Bottom"],
s = r.toLowerCase(),
o = {
innerWidth: e.fn.innerWidth,
innerHeight: e.fn.innerHeight,
outerWidth: e.fn.outerWidth,
outerHeight: e.fn.outerHeight
};
e.fn["inner" + r] = function(n) {
return n === t ? o["inner" + r].call(this) : this.each(function() {
e(this).css(s, u(this, n) + "px")
})
}, e.fn["outer" + r] = function(t, n) {
return typeof t != "number" ? o["outer" + r].call(this, t) : this.each(function() {
e(this).css(s, u(this, t, !0, n) + "px")
})
}
}), e("<a>").data("a-b", "a").removeData("a-b").data("a-b") && (e.fn.removeData = function(t) {
return function(n) {
return arguments.length ? t.call(this, e.camelCase(n)) : t.call(this)
}
}(e.fn.removeData)),
function() {
var t = /msie ([\w.]+)/.exec(navigator.userAgent.toLowerCase()) || [];
e.ui.ie = t.length ? !0 : !1, e.ui.ie6 = parseFloat(t[1], 10) === 6
}(), e.fn.extend({
disableSelection: function() {
return this.bind((e.support.selectstart ? "selectstart" : "mousedown") + ".ui-disableSelection", function(e) {
e.preventDefault()
})
},
enableSelection: function() {
return this.unbind(".ui-disableSelection")
}
}), e.extend(e.ui, {
plugin: {
add: function(t, n, r) {
var i, s = e.ui[t].prototype;
for (i in r) s.plugins[i] = s.plugins[i] || [], s.plugins[i].push([n, r[i]])
},
call: function(e, t, n) {
var r, i = e.plugins[t];
if (!i || !e.element[0].parentNode || e.element[0].parentNode.nodeType === 11) return;
for (r = 0; r < i.length; r++) e.options[i[r][0]] && i[r][1].apply(e.element, n)
}
},
contains: e.contains,
hasScroll: function(t, n) {
if (e(t).css("overflow") === "hidden") return !1;
var r = n && n === "left" ? "scrollLeft" : "scrollTop",
i = !1;
return t[r] > 0 ? !0 : (t[r] = 1, i = t[r] > 0, t[r] = 0, i)
},
isOverAxis: function(e, t, n) {
return e > t && e < t + n
},
isOver: function(t, n, r, i, s, o) {
return e.ui.isOverAxis(t, r, s) && e.ui.isOverAxis(n, i, o)
}
})
}(jQuery),
function(e, t) {
var n = 0,
r = Array.prototype.slice,
i = e.cleanData;
e.cleanData = function(t) {
for (var n = 0, r;
(r = t[n]) != null; n++) try {
e(r).triggerHandler("remove")
} catch (s) {}
i(t)
}, e.widget = function(t, n, r) {
var i, s, o, u, a = t.split(".")[0];
t = t.split(".")[1], i = a + "-" + t, r || (r = n, n = e.Widget), e.expr[":"][i.toLowerCase()] = function(t) {
return !!e.data(t, i)
}, e[a] = e[a] || {}, s = e[a][t], o = e[a][t] = function(e, t) {
if (!this._createWidget) return new o(e, t);
arguments.length && this._createWidget(e, t)
}, e.extend(o, s, {
version: r.version,
_proto: e.extend({}, r),
_childConstructors: []
}), u = new n, u.options = e.widget.extend({}, u.options), e.each(r, function(t, i) {
e.isFunction(i) && (r[t] = function() {
var e = function() {
return n.prototype[t].apply(this, arguments)
},
r = function(e) {
return n.prototype[t].apply(this, e)
};
return function() {
var t = this._super,
n = this._superApply,
s;
return this._super = e, this._superApply = r, s = i.apply(this, arguments), this._super = t, this._superApply = n, s
}
}())
}),
o.prototype = e.widget.extend(u, {
widgetEventPrefix: s ? u.widgetEventPrefix : t
}, r, {
constructor: o,
namespace: a,
widgetName: t,
widgetBaseClass: i,
widgetFullName: i
}), s ? (e.each(s._childConstructors, function(t, n) {
var r = n.prototype;
e.widget(r.namespace + "." + r.widgetName, o, n._proto)
}), delete s._childConstructors) : n._childConstructors.push(o), e.widget.bridge(t, o)
}, e.widget.extend = function(n) {
var i = r.call(arguments, 1),
s = 0,
o = i.length,
u, a;
for (; s < o; s++)
for (u in i[s]) a = i[s][u], i[s].hasOwnProperty(u) && a !== t && (e.isPlainObject(a) ? n[u] = e.isPlainObject(n[u]) ? e.widget.extend({}, n[u], a) : e.widget.extend({}, a) : n[u] = a);
return n
}, e.widget.bridge = function(n, i) {
var s = i.prototype.widgetFullName || n;
e.fn[n] = function(o) {
var u = typeof o == "string",
a = r.call(arguments, 1),
f = this;
return o = !u && a.length ? e.widget.extend.apply(null, [o].concat(a)) : o, u ? this.each(function() {
var r, i = e.data(this, s);
if (!i) return e.error("cannot call methods on " + n + " prior to initialization; " + "attempted to call method '" + o + "'");
if (!e.isFunction(i[o]) || o.charAt(0) === "_") return e.error("no such method '" + o + "' for " + n + " widget instance");
r = i[o].apply(i, a);
if (r !== i && r !== t) return f = r && r.jquery ? f.pushStack(r.get()) : r, !1
}) : this.each(function() {
var t = e.data(this, s);
t ? t.option(o || {})._init() : e.data(this, s, new i(o, this))
}), f
}
}, e.Widget = function() {}, e.Widget._childConstructors = [], e.Widget.prototype = {
widgetName: "widget",
widgetEventPrefix: "",
defaultElement: "<div>",
options: {
disabled: !1,
create: null
},
_createWidget: function(t, r) {
r = e(r || this.defaultElement || this)[0], this.element = e(r), this.uuid = n++, this.eventNamespace = "." + this.widgetName + this.uuid, this.options = e.widget.extend({}, this.options, this._getCreateOptions(), t), this.bindings = e(), this.hoverable = e(), this.focusable = e(), r !== this && (e.data(r, this.widgetName, this), e.data(r, this.widgetFullName, this), this._on(!0, this.element, {
remove: function(e) {
e.target === r && this.destroy()
}
}), this.document = e(r.style ? r.ownerDocument : r.document || r), this.window = e(this.document[0].defaultView || this.document[0].parentWindow)), this._create(), this._trigger("create", null, this._getCreateEventData()), this._init()
},
_getCreateOptions: e.noop,
_getCreateEventData: e.noop,
_create: e.noop,
_init: e.noop,
destroy: function() {
this._destroy(), this.element.unbind(this.eventNamespace).removeData(this.widgetName).removeData(this.widgetFullName).removeData(e.camelCase(this.widgetFullName)), this.widget().unbind(this.eventNamespace).removeAttr("aria-disabled").removeClass(this.widgetFullName + "-disabled " + "ui-state-disabled"), this.bindings.unbind(this.eventNamespace), this.hoverable.removeClass("ui-state-hover"), this.focusable.removeClass("ui-state-focus")
},
_destroy: e.noop,
widget: function() {
return this.element
},
option: function(n, r) {
var i = n,
s, o, u;
if (arguments.length === 0) return e.widget.extend({}, this.options);
if (typeof n == "string") {
i = {}, s = n.split("."), n = s.shift();
if (s.length) {
o = i[n] = e.widget.extend({}, this.options[n]);
for (u = 0; u < s.length - 1; u++) o[s[u]] = o[s[u]] || {}, o = o[s[u]];
n = s.pop();
if (r === t) return o[n] === t ? null : o[n];
o[n] = r
} else {
if (r === t) return this.options[n] === t ? null : this.options[n];
i[n] = r
}
}
return this._setOptions(i), this
},
_setOptions: function(e) {
var t;
for (t in e) this._setOption(t, e[t]);
return this
},
_setOption: function(e, t) {
return this.options[e] = t, e === "disabled" && (this.widget().toggleClass(this.widgetFullName + "-disabled ui-state-disabled", !!t).attr("aria-disabled", t), this.hoverable.removeClass("ui-state-hover"), this.focusable.removeClass("ui-state-focus")), this
},
enable: function() {
return this._setOption("disabled", !1)
},
disable: function() {
return this._setOption("disabled", !0)
},
_on: function(t, n, r) {
var i, s = this;
typeof t != "boolean" && (r = n, n = t, t = !1), r ? (n = i = e(n), this.bindings = this.bindings.add(n)) : (r = n, n = this.element, i = this.widget()), e.each(r, function(r, o) {
function u() {
if (!t && (s.options.disabled === !0 || e(this).hasClass("ui-state-disabled"))) return;
return (typeof o == "string" ? s[o] : o).apply(s, arguments)
}
typeof o != "string" && (u.guid = o.guid = o.guid || u.guid || e.guid++);
var a = r.match(/^(\w+)\s*(.*)$/),
f = a[1] + s.eventNamespace,
l = a[2];
l ? i.delegate(l, f, u) : n.bind(f, u)
})
},
_off: function(e, t) {
t = (t || "").split(" ").join(this.eventNamespace + " ") + this.eventNamespace, e.unbind(t).undelegate(t)
},
_delay: function(e, t) {
function n() {
return (typeof e == "string" ? r[e] : e).apply(r, arguments)
}
var r = this;
return setTimeout(n, t || 0)
},
_hoverable: function(t) {
this.hoverable = this.hoverable.add(t), this._on(t, {
mouseenter: function(t) {
e(t.currentTarget).addClass("ui-state-hover")
},
mouseleave: function(t) {
e(t.currentTarget).removeClass("ui-state-hover")
}
})
},
_focusable: function(t) {
this.focusable = this.focusable.add(t), this._on(t, {
focusin: function(t) {
e(t.currentTarget).addClass("ui-state-focus")
},
focusout: function(t) {
e(t.currentTarget).removeClass("ui-state-focus")
}
})
},
_trigger: function(t, n, r) {
var i, s, o = this.options[t];
r = r || {}, n = e.Event(n), n.type = (t === this.widgetEventPrefix ? t : this.widgetEventPrefix + t).toLowerCase(), n.target = this.element[0], s = n.originalEvent;
if (s)
for (i in s) i in n || (n[i] = s[i]);
return this.element.trigger(n, r), !(e.isFunction(o) && o.apply(this.element[0], [n].concat(r)) === !1 || n.isDefaultPrevented())
}
}, e.each({
show: "fadeIn",
hide: "fadeOut"
}, function(t, n) {
e.Widget.prototype["_" + t] = function(r, i, s) {
typeof i == "string" && (i = {
effect: i
});
var o, u = i ? i === !0 || typeof i == "number" ? n : i.effect || n : t;
i = i || {}, typeof i == "number" && (i = {
duration: i
}), o = !e.isEmptyObject(i), i.complete = s, i.delay && r.delay(i.delay), o && e.effects && (e.effects.effect[u] || e.uiBackCompat !== !1 && e.effects[u]) ? r[t](i) : u !== t && r[u] ? r[u](i.duration, i.easing, s) : r.queue(function(n) {
e(this)[t](), s && s.call(r[0]), n()
})
}
}), e.uiBackCompat !== !1 && (e.Widget.prototype._getCreateOptions = function() {
return e.metadata && e.metadata.get(this.element[0])[this.widgetName]
})
}(jQuery),
function(e, t) {
var n = !1;
e(document).mouseup(function(e) {
n = !1
}), e.widget("ui.mouse", {
version: "1.9.2",
options: {
cancel: "input,textarea,button,select,option",
distance: 1,
delay: 0
},
_mouseInit: function() {
var t = this;
this.element.bind("mousedown." + this.widgetName, function(e) {
return t._mouseDown(e)
}).bind("click." + this.widgetName, function(n) {
if (!0 === e.data(n.target, t.widgetName + ".preventClickEvent")) return e.removeData(n.target, t.widgetName + ".preventClickEvent"), n.stopImmediatePropagation(), !1
}), this.started = !1
},
_mouseDestroy: function() {
this.element.unbind("." + this.widgetName), this._mouseMoveDelegate && e(document).unbind("mousemove." + this.widgetName, this._mouseMoveDelegate).unbind("mouseup." + this.widgetName, this._mouseUpDelegate)
},
_mouseDown: function(t) {
if (n) return;
this._mouseStarted && this._mouseUp(t), this._mouseDownEvent = t;
var r = this,
i = t.which === 1,
s = typeof this.options.cancel == "string" && t.target.nodeName ? e(t.target).closest(this.options.cancel).length : !1;
if (!i || s || !this._mouseCapture(t)) return !0;
this.mouseDelayMet = !this.options.delay, this.mouseDelayMet || (this._mouseDelayTimer = setTimeout(function() {
r.mouseDelayMet = !0
}, this.options.delay));
if (this._mouseDistanceMet(t) && this._mouseDelayMet(t)) {
this._mouseStarted = this._mouseStart(t) !== !1;
if (!this._mouseStarted) return t.preventDefault(), !0
}
return !0 === e.data(t.target, this.widgetName + ".preventClickEvent") && e.removeData(t.target, this.widgetName + ".preventClickEvent"), this._mouseMoveDelegate = function(e) {
return r._mouseMove(e)
}, this._mouseUpDelegate = function(e) {
return r._mouseUp(e)
}, e(document).bind("mousemove." + this.widgetName, this._mouseMoveDelegate).bind("mouseup." + this.widgetName, this._mouseUpDelegate), t.preventDefault(), n = !0, !0
},
_mouseMove: function(t) {
return !e.ui.ie || document.documentMode >= 9 || !!t.button ? this._mouseStarted ? (this._mouseDrag(t), t.preventDefault()) : (this._mouseDistanceMet(t) && this._mouseDelayMet(t) && (this._mouseStarted = this._mouseStart(this._mouseDownEvent, t) !== !1, this._mouseStarted ? this._mouseDrag(t) : this._mouseUp(t)), !this._mouseStarted) : this._mouseUp(t)
},
_mouseUp: function(t) {
return e(document).unbind("mousemove." + this.widgetName, this._mouseMoveDelegate).unbind("mouseup." + this.widgetName, this._mouseUpDelegate), this._mouseStarted && (this._mouseStarted = !1, t.target === this._mouseDownEvent.target && e.data(t.target, this.widgetName + ".preventClickEvent", !0), this._mouseStop(t)), !1
},
_mouseDistanceMet: function(e) {
return Math.max(Math.abs(this._mouseDownEvent.pageX - e.pageX), Math.abs(this._mouseDownEvent.pageY - e.pageY)) >= this.options.distance
},
_mouseDelayMet: function(e) {
return this.mouseDelayMet
},
_mouseStart: function(e) {},
_mouseDrag: function(e) {},
_mouseStop: function(e) {},
_mouseCapture: function(e) {
return !0
}
})
}(jQuery),
function(e, t) {
e.widget("ui.resizable", e.ui.mouse, {
version: "1.9.2",
widgetEventPrefix: "resize",
options: {
alsoResize: !1,
animate: !1,
animateDuration: "slow",
animateEasing: "swing",
aspectRatio: !1,
autoHide: !1,
containment: !1,
ghost: !1,
grid: !1,
handles: "e,s,se",
helper: !1,
maxHeight: null,
maxWidth: null,
minHeight: 10,
minWidth: 10,
zIndex: 1e3
},
_create: function() {
var t = this,
n = this.options;
this.element.addClass("ui-resizable"), e.extend(this, {
_aspectRatio: !!n.aspectRatio,
aspectRatio: n.aspectRatio,
originalElement: this.element,
_proportionallyResizeElements: [],
_helper: n.helper || n.ghost || n.animate ? n.helper || "ui-resizable-helper" : null
}), this.element[0].nodeName.match(/canvas|textarea|input|select|button|img/i) && (this.element.wrap(e('<div class="ui-wrapper" style="overflow: hidden;"></div>').css({
position: this.element.css("position"),
width: this.element.outerWidth(),
height: this.element.outerHeight(),
top: this.element.css("top"),
left: this.element.css("left")
})), this.element = this.element.parent().data("resizable", this.element.data("resizable")), this.elementIsWrapper = !0, this.element.css({
marginLeft: this.originalElement.css("marginLeft"),
marginTop: this.originalElement.css("marginTop"),
marginRight: this.originalElement.css("marginRight"),
marginBottom: this.originalElement.css("marginBottom")
}), this.originalElement.css({
marginLeft: 0,
marginTop: 0,
marginRight: 0,
marginBottom: 0
}), this.originalResizeStyle = this.originalElement.css("resize"), this.originalElement.css("resize", "none"), this._proportionallyResizeElements.push(this.originalElement.css({
position: "static",
zoom: 1,
display: "block"
})), this.originalElement.css({
margin: this.originalElement.css("margin")
}), this._proportionallyResize()), this.handles = n.handles || (e(".ui-resizable-handle", this.element).length ? {
n: ".ui-resizable-n",
e: ".ui-resizable-e",
s: ".ui-resizable-s",
w: ".ui-resizable-w",
se: ".ui-resizable-se",
sw: ".ui-resizable-sw",
ne: ".ui-resizable-ne",
nw: ".ui-resizable-nw"
} : "e,s,se");
if (this.handles.constructor == String) {
this.handles == "all" && (this.handles = "n,e,s,w,se,sw,ne,nw");
var r = this.handles.split(",");
this.handles = {};
for (var i = 0; i < r.length; i++) {
var s = e.trim(r[i]),
o = "ui-resizable-" + s,
u = e('<div class="ui-resizable-handle ' + o + '"></div>');
u.css({
zIndex: n.zIndex
}), "se" == s && u.addClass("ui-icon ui-icon-gripsmall-diagonal-se"), this.handles[s] = ".ui-resizable-" + s, this.element.append(u)
}
}
this._renderAxis = function(t) {
t = t || this.element;
for (var n in this.handles) {
this.handles[n].constructor == String && (this.handles[n] = e(this.handles[n], this.element).show());
if (this.elementIsWrapper && this.originalElement[0].nodeName.match(/textarea|input|select|button/i)) {
var r = e(this.handles[n], this.element),
i = 0;
i = /sw|ne|nw|se|n|s/.test(n) ? r.outerHeight() : r.outerWidth();
var s = ["padding", /ne|nw|n/.test(n) ? "Top" : /se|sw|s/.test(n) ? "Bottom" : /^e$/.test(n) ? "Right" : "Left"].join("");
t.css(s, i), this._proportionallyResize()
}
if (!e(this.handles[n]).length) continue
}
}, this._renderAxis(this.element), this._handles = e(".ui-resizable-handle", this.element).disableSelection(), this._handles.mouseover(function() {
if (!t.resizing) {
if (this.className) var e = this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i);
t.axis = e && e[1] ? e[1] : "se"
}
}), n.autoHide && (this._handles.hide(), e(this.element).addClass("ui-resizable-autohide").mouseenter(function() {
if (n.disabled) return;
e(this).removeClass("ui-resizable-autohide"), t._handles.show()
}).mouseleave(function() {
if (n.disabled) return;
t.resizing || (e(this).addClass("ui-resizable-autohide"), t._handles.hide())
})), this._mouseInit()
},
_destroy: function() {
this._mouseDestroy();
var t = function(t) {
e(t).removeClass("ui-resizable ui-resizable-disabled ui-resizable-resizing").removeData("resizable").removeData("ui-resizable").unbind(".resizable").find(".ui-resizable-handle").remove()
};
if (this.elementIsWrapper) {
t(this.element);
var n = this.element;
this.originalElement.css({
position: n.css("position"),
width: n.outerWidth(),
height: n.outerHeight(),
top: n.css("top"),
left: n.css("left")
}).insertAfter(n), n.remove()
}
return this.originalElement.css("resize", this.originalResizeStyle), t(this.originalElement), this
},
_mouseCapture: function(t) {
var n = !1;
for (var r in this.handles) e(this.handles[r])[0] == t.target && (n = !0);
return !this.options.disabled && n
},
_mouseStart: function(t) {
var r = this.options,
i = this.element.position(),
s = this.element;
this.resizing = !0, this.documentScroll = {
top: e(document).scrollTop(),
left: e(document).scrollLeft()
}, (s.is(".ui-draggable") || /absolute/.test(s.css("position"))) && s.css({
position: "absolute",
top: i.top,
left: i.left
}), this._renderProxy();
var o = n(this.helper.css("left")),
u = n(this.helper.css("top"));
r.containment && (o += e(r.containment).scrollLeft() || 0, u += e(r.containment).scrollTop() || 0), this.offset = this.helper.offset(), this.position = {
left: o,
top: u
}, this.size = this._helper ? {
width: s.outerWidth(),
height: s.outerHeight()
} : {
width: s.width(),
height: s.height()
}, this.originalSize = this._helper ? {
width: s.outerWidth(),
height: s.outerHeight()
} : {
width: s.width(),
height: s.height()
}, this.originalPosition = {
left: o,
top: u
}, this.sizeDiff = {
width: s.outerWidth() - s.width(),
height: s.outerHeight() - s.height()
}, this.originalMousePosition = {
left: t.pageX,
top: t.pageY
}, this.aspectRatio = typeof r.aspectRatio == "number" ? r.aspectRatio : this.originalSize.width / this.originalSize.height || 1;
var a = e(".ui-resizable-" + this.axis).css("cursor");
return e("body").css("cursor", a == "auto" ? this.axis + "-resize" : a), s.addClass("ui-resizable-resizing"), this._propagate("start", t), !0
},
_mouseDrag: function(e) {
var t = this.helper,
n = this.options,
r = {},
i = this,
s = this.originalMousePosition,
o = this.axis,
u = e.pageX - s.left || 0,
a = e.pageY - s.top || 0,
f = this._change[o];
if (!f) return !1;
var l = f.apply(this, [e, u, a]);
this._updateVirtualBoundaries(e.shiftKey);
if (this._aspectRatio || e.shiftKey) l = this._updateRatio(l, e);
return l = this._respectSize(l, e), this._propagate("resize", e), t.css({
top: this.position.top + "px",
left: this.position.left + "px",
width: this.size.width + "px",
height: this.size.height + "px"
}), !this._helper && this._proportionallyResizeElements.length && this._proportionallyResize(), this._updateCache(l), this._trigger("resize", e, this.ui()), !1
},
_mouseStop: function(t) {
this.resizing = !1;
var n = this.options,
r = this;
if (this._helper) {
var i = this._proportionallyResizeElements,
s = i.length && /textarea/i.test(i[0].nodeName),
o = s && e.ui.hasScroll(i[0], "left") ? 0 : r.sizeDiff.height,
u = s ? 0 : r.sizeDiff.width,
a = {
width: r.helper.width() - u,
height: r.helper.height() - o
},
f = parseInt(r.element.css("left"), 10) + (r.position.left - r.originalPosition.left) || null,
l = parseInt(r.element.css("top"), 10) + (r.position.top - r.originalPosition.top) || null;
n.animate || this.element.css(e.extend(a, {
top: l,
left: f
})), r.helper.height(r.size.height), r.helper.width(r.size.width), this._helper && !n.animate && this._proportionallyResize()
}
return e("body").css("cursor", "auto"), this.element.removeClass("ui-resizable-resizing"), this._propagate("stop", t), this._helper && this.helper.remove(), !1
},
_updateVirtualBoundaries: function(e) {
var t = this.options,
n, i, s, o, u;
u = {
minWidth: r(t.minWidth) ? t.minWidth : 0,
maxWidth: r(t.maxWidth) ? t.maxWidth : Infinity,
minHeight: r(t.minHeight) ? t.minHeight : 0,
maxHeight: r(t.maxHeight) ? t.maxHeight : Infinity
};
if (this._aspectRatio || e) n = u.minHeight * this.aspectRatio, s = u.minWidth / this.aspectRatio, i = u.maxHeight * this.aspectRatio, o = u.maxWidth / this.aspectRatio, n > u.minWidth && (u.minWidth = n), s > u.minHeight && (u.minHeight = s), i < u.maxWidth && (u.maxWidth = i), o < u.maxHeight && (u.maxHeight = o);
this._vBoundaries = u
},
_updateCache: function(e) {
var t = this.options;
this.offset = this.helper.offset(), r(e.left) && (this.position.left = e.left), r(e.top) && (this.position.top = e.top), r(e.height) && (this.size.height = e.height), r(e.width) && (this.size.width = e.width)
},
_updateRatio: function(e, t) {
var n = this.options,
i = this.position,
s = this.size,
o = this.axis;
return r(e.height) ? e.width = e.height * this.aspectRatio : r(e.width) && (e.height = e.width / this.aspectRatio), o == "sw" && (e.left = i.left + (s.width - e.width), e.top = null), o == "nw" && (e.top = i.top + (s.height - e.height), e.left = i.left + (s.width - e.width)), e
},
_respectSize: function(e, t) {
var n = this.helper,
i = this._vBoundaries,
s = this._aspectRatio || t.shiftKey,
o = this.axis,
u = r(e.width) && i.maxWidth && i.maxWidth < e.width,
a = r(e.height) && i.maxHeight && i.maxHeight < e.height,
f = r(e.width) && i.minWidth && i.minWidth > e.width,
l = r(e.height) && i.minHeight && i.minHeight > e.height;
f && (e.width = i.minWidth), l && (e.height = i.minHeight), u && (e.width = i.maxWidth), a && (e.height = i.maxHeight);
var c = this.originalPosition.left + this.originalSize.width,
h = this.position.top + this.size.height,
p = /sw|nw|w/.test(o),
d = /nw|ne|n/.test(o);
f && p && (e.left = c - i.minWidth), u && p && (e.left = c - i.maxWidth), l && d && (e.top = h - i.minHeight), a && d && (e.top = h - i.maxHeight);
var v = !e.width && !e.height;
return v && !e.left && e.top ? e.top = null : v && !e.top && e.left && (e.left = null), e
},
_proportionallyResize: function() {
var t = this.options;
if (!this._proportionallyResizeElements.length) return;
var n = this.helper || this.element;
for (var r = 0; r < this._proportionallyResizeElements.length; r++) {
var i = this._proportionallyResizeElements[r];
if (!this.borderDif) {
var s = [i.css("borderTopWidth"), i.css("borderRightWidth"), i.css("borderBottomWidth"), i.css("borderLeftWidth")],
o = [i.css("paddingTop"), i.css("paddingRight"), i.css("paddingBottom"), i.css("paddingLeft")];
this.borderDif = e.map(s, function(e, t) {
var n = parseInt(e, 10) || 0,
r = parseInt(o[t], 10) || 0;
return n + r
})
}
i.css({
height: n.height() - this.borderDif[0] - this.borderDif[2] || 0,
width: n.width() - this.borderDif[1] - this.borderDif[3] || 0
})
}
},
_renderProxy: function() {
var t = this.element,
n = this.options;
this.elementOffset = t.offset();
if (this._helper) {
this.helper = this.helper || e('<div style="overflow:hidden;"></div>');
var r = e.ui.ie6 ? 1 : 0,
i = e.ui.ie6 ? 2 : -1;
this.helper.addClass(this._helper).css({
width: this.element.outerWidth() + i,
height: this.element.outerHeight() + i,
position: "absolute",
left: this.elementOffset.left - r + "px",
top: this.elementOffset.top - r + "px",
zIndex: ++n.zIndex
}), this.helper.appendTo("body").disableSelection()
} else this.helper = this.element
},
_change: {
e: function(e, t, n) {
return {
width: this.originalSize.width + t
}
},
w: function(e, t, n) {
var r = this.options,
i = this.originalSize,
s = this.originalPosition;
return {
left: s.left + t,
width: i.width - t
}
},
n: function(e, t, n) {
var r = this.options,
i = this.originalSize,
s = this.originalPosition;
return {
top: s.top + n,
height: i.height - n
}
},
s: function(e, t, n) {
return {
height: this.originalSize.height + n
}
},
se: function(t, n, r) {
return e.extend(this._change.s.apply(this, arguments), this._change.e.apply(this, [t, n, r]))
},
sw: function(t, n, r) {
return e.extend(this._change.s.apply(this, arguments), this._change.w.apply(this, [t, n, r]))
},
ne: function(t, n, r) {
return e.extend(this._change.n.apply(this, arguments), this._change.e.apply(this, [t, n, r]))
},
nw: function(t, n, r) {
return e.extend(this._change.n.apply(this, arguments), this._change.w.apply(this, [t, n, r]))
}
},
_propagate: function(t, n) {
e.ui.plugin.call(this, t, [n, this.ui()]), t != "resize" && this._trigger(t, n, this.ui())
},
plugins: {},
ui: function() {
return {
originalElement: this.originalElement,
element: this.element,
helper: this.helper,
position: this.position,
size: this.size,
originalSize: this.originalSize,
originalPosition: this.originalPosition
}
}
}), e.ui.plugin.add("resizable", "alsoResize", {
start: function(t, n) {
var r = e(this).data("resizable"),
i = r.options,
s = function(t) {
e(t).each(function() {
var t = e(this);
t.data("resizable-alsoresize", {
width: parseInt(t.width(), 10),
height: parseInt(t.height(), 10),
left: parseInt(t.css("left"), 10),
top: parseInt(t.css("top"), 10)
})
})
};
typeof i.alsoResize == "object" && !i.alsoResize.parentNode ? i.alsoResize.length ? (i.alsoResize = i.alsoResize[0], s(i.alsoResize)) : e.each(i.alsoResize, function(e) {
s(e)
}) : s(i.alsoResize)
},
resize: function(t, n) {
var r = e(this).data("resizable"),
i = r.options,
s = r.originalSize,
o = r.originalPosition,
u = {
height: r.size.height - s.height || 0,
width: r.size.width - s.width || 0,
top: r.position.top - o.top || 0,
left: r.position.left - o.left || 0
},
a = function(t, r) {
e(t).each(function() {
var t = e(this),
i = e(this).data("resizable-alsoresize"),
s = {},
o = r && r.length ? r : t.parents(n.originalElement[0]).length ? ["width", "height"] : ["width", "height", "top", "left"];
e.each(o, function(e, t) {
var n = (i[t] || 0) + (u[t] || 0);
n && n >= 0 && (s[t] = n || null)
}), t.css(s)
})
};
typeof i.alsoResize == "object" && !i.alsoResize.nodeType ? e.each(i.alsoResize, function(e, t) {
a(e, t)
}) : a(i.alsoResize)
},
stop: function(t, n) {
e(this).removeData("resizable-alsoresize")
}
}), e.ui.plugin.add("resizable", "animate", {
stop: function(t, n) {
var r = e(this).data("resizable"),
i = r.options,
s = r._proportionallyResizeElements,
o = s.length && /textarea/i.test(s[0].nodeName),
u = o && e.ui.hasScroll(s[0], "left") ? 0 : r.sizeDiff.height,
a = o ? 0 : r.sizeDiff.width,
f = {
width: r.size.width - a,
height: r.size.height - u
},
l = parseInt(r.element.css("left"), 10) + (r.position.left - r.originalPosition.left) || null,
c = parseInt(r.element.css("top"), 10) + (r.position.top - r.originalPosition.top) || null;
r.element.animate(e.extend(f, c && l ? {
top: c,
left: l
} : {}), {
duration: i.animateDuration,
easing: i.animateEasing,
step: function() {
var n = {
width: parseInt(r.element.css("width"), 10),
height: parseInt(r.element.css("height"), 10),
top: parseInt(r.element.css("top"), 10),
left: parseInt(r.element.css("left"), 10)
};
s && s.length && e(s[0]).css({
width: n.width,
height: n.height
}), r._updateCache(n), r._propagate("resize", t)
}
})
}
}), e.ui.plugin.add("resizable", "containment", {
start: function(t, r) {
var i = e(this).data("resizable"),
s = i.options,
o = i.element,
u = s.containment,
a = u instanceof e ? u.get(0) : /parent/.test(u) ? o.parent().get(0) : u;
if (!a) return;
i.containerElement = e(a);
if (/document/.test(u) || u == document) i.containerOffset = {
left: 0,
top: 0
}, i.containerPosition = {
left: 0,
top: 0
}, i.parentData = {
element: e(document),
left: 0,
top: 0,
width: e(document).width(),
height: e(document).height() || document.body.parentNode.scrollHeight
};
else {
var f = e(a),
l = [];
e(["Top", "Right", "Left", "Bottom"]).each(function(e, t) {
l[e] = n(f.css("padding" + t))
}), i.containerOffset = f.offset(), i.containerPosition = f.position(), i.containerSize = {
height: f.innerHeight() - l[3],
width: f.innerWidth() - l[1]
};
var c = i.containerOffset,
h = i.containerSize.height,
p = i.containerSize.width,
d = e.ui.hasScroll(a, "left") ? a.scrollWidth : p,
v = e.ui.hasScroll(a) ? a.scrollHeight : h;
i.parentData = {
element: a,
left: c.left,
top: c.top,
width: d,
height: v
}
}
},
resize: function(t, n) {
var r = e(this).data("resizable"),
i = r.options,
s = r.containerSize,
o = r.containerOffset,
u = r.size,
a = r.position,
f = r._aspectRatio || t.shiftKey,
l = {
top: 0,
left: 0
},
c = r.containerElement;
c[0] != document && /static/.test(c.css("position")) && (l = o), a.left < (r._helper ? o.left : 0) && (r.size.width = r.size.width + (r._helper ? r.position.left - o.left : r.position.left - l.left), f && (r.size.height = r.size.width / r.aspectRatio), r.position.left = i.helper ? o.left : 0), a.top < (r._helper ? o.top : 0) && (r.size.height = r.size.height + (r._helper ? r.position.top - o.top : r.position.top), f && (r.size.width = r.size.height * r.aspectRatio), r.position.top = r._helper ? o.top : 0), r.offset.left = r.parentData.left + r.position.left, r.offset.top = r.parentData.top + r.position.top;
var h = Math.abs((r._helper ? r.offset.left - l.left : r.offset.left - l.left) + r.sizeDiff.width),
p = Math.abs((r._helper ? r.offset.top - l.top : r.offset.top - o.top) + r.sizeDiff.height),
d = r.containerElement.get(0) == r.element.parent().get(0),
v = /relative|absolute/.test(r.containerElement.css("position"));
d && v && (h -= r.parentData.left), h + r.size.width >= r.parentData.width && (r.size.width = r.parentData.width - h, f && (r.size.height = r.size.width / r.aspectRatio)), p + r.size.height >= r.parentData.height && (r.size.height = r.parentData.height - p, f && (r.size.width = r.size.height * r.aspectRatio))
},
stop: function(t, n) {
var r = e(this).data("resizable"),
i = r.options,
s = r.position,
o = r.containerOffset,
u = r.containerPosition,
a = r.containerElement,
f = e(r.helper),
l = f.offset(),
c = f.outerWidth() - r.sizeDiff.width,
h = f.outerHeight() - r.sizeDiff.height;
r._helper && !i.animate && /relative/.test(a.css("position")) && e(this).css({
left: l.left - u.left - o.left,
width: c,
height: h
}), r._helper && !i.animate && /static/.test(a.css("position")) && e(this).css({
left: l.left - u.left - o.left,
width: c,
height: h
})
}
}), e.ui.plugin.add("resizable", "ghost", {
start: function(t, n) {
var r = e(this).data("resizable"),
i = r.options,
s = r.size;
r.ghost = r.originalElement.clone(), r.ghost.css({
opacity: .25,
display: "block",
position: "relative",
height: s.height,
width: s.width,
margin: 0,
left: 0,
top: 0
}).addClass("ui-resizable-ghost").addClass(typeof i.ghost == "string" ? i.ghost : ""), r.ghost.appendTo(r.helper)
},
resize: function(t, n) {
var r = e(this).data("resizable"),
i = r.options;
r.ghost && r.ghost.css({
position: "relative",
height: r.size.height,
width: r.size.width
})
},
stop: function(t, n) {
var r = e(this).data("resizable"),
i = r.options;
r.ghost && r.helper && r.helper.get(0).removeChild(r.ghost.get(0))
}
}), e.ui.plugin.add("resizable", "grid", {
resize: function(t, n) {
var r = e(this).data("resizable"),
i = r.options,
s = r.size,
o = r.originalSize,
u = r.originalPosition,
a = r.axis,
f = i._aspectRatio || t.shiftKey;
i.grid = typeof i.grid == "number" ? [i.grid, i.grid] : i.grid;
var l = Math.round((s.width - o.width) / (i.grid[0] || 1)) * (i.grid[0] || 1),
c = Math.round((s.height - o.height) / (i.grid[1] || 1)) * (i.grid[1] || 1);
/^(se|s|e)$/.test(a) ? (r.size.width = o.width + l, r.size.height = o.height + c) : /^(ne)$/.test(a) ? (r.size.width = o.width + l, r.size.height = o.height + c, r.position.top = u.top - c) : /^(sw)$/.test(a) ? (r.size.width = o.width + l, r.size.height = o.height + c, r.position.left = u.left - l) : (r.size.width = o.width + l, r.size.height = o.height + c, r.position.top = u.top - c, r.position.left = u.left - l)
}
});
var n = function(e) {
return parseInt(e, 10) || 0
},
r = function(e) {
return !isNaN(parseInt(e, 10))
}
}(jQuery),
function(e, t) {
var n = 5;
e.widget("ui.slider", e.ui.mouse, {
version: "1.9.2",
widgetEventPrefix: "slide",
options: {
animate: !1,
distance: 0,
max: 100,
min: 0,
orientation: "horizontal",
range: !1,
step: 1,
value: 0,
values: null
},
_create: function() {
var t, r, i = this.options,
s = this.element.find(".ui-slider-handle").addClass("ui-state-default ui-corner-all"),
o = "<a class='ui-slider-handle ui-state-default ui-corner-all' href='#'></a>",
u = [];
this._keySliding = !1, this._mouseSliding = !1, this._animateOff = !0, this._handleIndex = null, this._detectOrientation(), this._mouseInit(), this.element.addClass("ui-slider ui-slider-" + this.orientation + " ui-widget" + " ui-widget-content" + " ui-corner-all" + (i.disabled ? " ui-slider-disabled ui-disabled" : "")), this.range = e([]), i.range && (i.range === !0 && (i.values || (i.values = [this._valueMin(), this._valueMin()]), i.values.length && i.values.length !== 2 && (i.values = [i.values[0], i.values[0]])), this.range = e("<div></div>").appendTo(this.element).addClass("ui-slider-range ui-widget-header" + (i.range === "min" || i.range === "max" ? " ui-slider-range-" + i.range : ""))), r = i.values && i.values.length || 1;
for (t = s.length; t < r; t++) u.push(o);
this.handles = s.add(e(u.join("")).appendTo(this.element)), this.handle = this.handles.eq(0), this.handles.add(this.range).filter("a").click(function(e) {
e.preventDefault()
}).mouseenter(function() {
i.disabled || e(this).addClass("ui-state-hover")
}).mouseleave(function() {
e(this).removeClass("ui-state-hover")
}).focus(function() {
i.disabled ? e(this).blur() : (e(".ui-slider .ui-state-focus").removeClass("ui-state-focus"), e(this).addClass("ui-state-focus"))
}).blur(function() {
e(this).removeClass("ui-state-focus")
}), this.handles.each(function(t) {
e(this).data("ui-slider-handle-index", t)
}), this._on(this.handles, {
keydown: function(t) {
var r, i, s, o, u = e(t.target).data("ui-slider-handle-index");
switch (t.keyCode) {
case e.ui.keyCode.HOME:
case e.ui.keyCode.END:
case e.ui.keyCode.PAGE_UP:
case e.ui.keyCode.PAGE_DOWN:
case e.ui.keyCode.UP:
case e.ui.keyCode.RIGHT:
case e.ui.keyCode.DOWN:
case e.ui.keyCode.LEFT:
t.preventDefault();
if (!this._keySliding) {
this._keySliding = !0, e(t.target).addClass("ui-state-active"), r = this._start(t, u);
if (r === !1) return
}
}
o = this.options.step, this.options.values && this.options.values.length ? i = s = this.values(u) : i = s = this.value();
switch (t.keyCode) {
case e.ui.keyCode.HOME:
s = this._valueMin();
break;
case e.ui.keyCode.END:
s = this._valueMax();
break;
case e.ui.keyCode.PAGE_UP:
s = this._trimAlignValue(i + (this._valueMax() - this._valueMin()) / n);
break;
case e.ui.keyCode.PAGE_DOWN:
s = this._trimAlignValue(i - (this._valueMax() - this._valueMin()) / n);
break;
case e.ui.keyCode.UP:
case e.ui.keyCode.RIGHT:
if (i === this._valueMax()) return;
s = this._trimAlignValue(i + o);
break;
case e.ui.keyCode.DOWN:
case e.ui.keyCode.LEFT:
if (i === this._valueMin()) return;
s = this._trimAlignValue(i - o)
}
this._slide(t, u, s)
},
keyup: function(t) {
var n = e(t.target).data("ui-slider-handle-index");
this._keySliding && (this._keySliding = !1, this._stop(t, n), this._change(t, n), e(t.target).removeClass("ui-state-active"))
}
}), this._refreshValue(), this._animateOff = !1
},
_destroy: function() {
this.handles.remove(), this.range.remove(), this.element.removeClass("ui-slider ui-slider-horizontal ui-slider-vertical ui-slider-disabled ui-widget ui-widget-content ui-corner-all"), this._mouseDestroy()
},
_mouseCapture: function(t) {
var n, r, i, s, o, u, a, f, l = this,
c = this.options;
return c.disabled ? !1 : (this.elementSize = {
width: this.element.outerWidth(),
height: this.element.outerHeight()
}, this.elementOffset = this.element.offset(), n = {
x: t.pageX,
y: t.pageY
}, r = this._normValueFromMouse(n), i = this._valueMax() - this._valueMin() + 1, this.handles.each(function(t) {
var n = Math.abs(r - l.values(t));
i > n && (i = n, s = e(this), o = t)
}), c.range === !0 && this.values(1) === c.min && (o += 1, s = e(this.handles[o])), u = this._start(t, o), u === !1 ? !1 : (this._mouseSliding = !0, this._handleIndex = o, s.addClass("ui-state-active").focus(), a = s.offset(), f = !e(t.target).parents().andSelf().is(".ui-slider-handle"), this._clickOffset = f ? {
left: 0,
top: 0
} : {
left: t.pageX - a.left - s.width() / 2,
top: t.pageY - a.top - s.height() / 2 - (parseInt(s.css("borderTopWidth"), 10) || 0) - (parseInt(s.css("borderBottomWidth"), 10) || 0) + (parseInt(s.css("marginTop"), 10) || 0)
}, this.handles.hasClass("ui-state-hover") || this._slide(t, o, r), this._animateOff = !0, !0))
},
_mouseStart: function() {
return !0
},
_mouseDrag: function(e) {
var t = {
x: e.pageX,
y: e.pageY
},
n = this._normValueFromMouse(t);
return this._slide(e, this._handleIndex, n), !1
},
_mouseStop: function(e) {
return this.handles.removeClass("ui-state-active"), this._mouseSliding = !1, this._stop(e, this._handleIndex), this._change(e, this._handleIndex), this._handleIndex = null, this._clickOffset = null, this._animateOff = !1, !1
},
_detectOrientation: function() {
this.orientation = this.options.orientation === "vertical" ? "vertical" : "horizontal"
},
_normValueFromMouse: function(e) {
var t, n, r, i, s;
return this.orientation === "horizontal" ? (t = this.elementSize.width, n = e.x - this.elementOffset.left - (this._clickOffset ? this._clickOffset.left : 0)) : (t = this.elementSize.height, n = e.y - this.elementOffset.top - (this._clickOffset ? this._clickOffset.top : 0)), r = n / t, r > 1 && (r = 1), r < 0 && (r = 0), this.orientation === "vertical" && (r = 1 - r), i = this._valueMax() - this._valueMin(), s = this._valueMin() + r * i, this._trimAlignValue(s)
},
_start: function(e, t) {
var n = {
handle: this.handles[t],
value: this.value()
};
return this.options.values && this.options.values.length && (n.value = this.values(t), n.values = this.values()), this._trigger("start", e, n)
},
_slide: function(e, t, n) {
var r, i, s;
this.options.values && this.options.values.length ? (r = this.values(t ? 0 : 1), this.options.values.length === 2 && this.options.range === !0 && (t === 0 && n > r || t === 1 && n < r) && (n = r), n !== this.values(t) && (i = this.values(), i[t] = n, s = this._trigger("slide", e, {
handle: this.handles[t],
value: n,
values: i
}), r = this.values(t ? 0 : 1), s !== !1 && this.values(t, n, !0))) : n !== this.value() && (s = this._trigger("slide", e, {
handle: this.handles[t],
value: n
}), s !== !1 && this.value(n))
},
_stop: function(e, t) {
var n = {
handle: this.handles[t],
value: this.value()
};
this.options.values && this.options.values.length && (n.value = this.values(t), n.values = this.values()), this._trigger("stop", e, n)
},
_change: function(e, t) {
if (!this._keySliding && !this._mouseSliding) {
var n = {
handle: this.handles[t],
value: this.value()
};
this.options.values && this.options.values.length && (n.value = this.values(t), n.values = this.values()), this._trigger("change", e, n)
}
},
value: function(e) {
if (arguments.length) {
this.options.value = this._trimAlignValue(e), this._refreshValue(), this._change(null, 0);
return
}
return this._value()
},
values: function(t, n) {
var r, i, s;
if (arguments.length > 1) {
this.options.values[t] = this._trimAlignValue(n), this._refreshValue(), this._change(null, t);
return
}
if (!arguments.length) return this._values();
if (!e.isArray(arguments[0])) return this.options.values && this.options.values.length ? this._values(t) : this.value();
r = this.options.values, i = arguments[0];
for (s = 0; s < r.length; s += 1) r[s] = this._trimAlignValue(i[s]), this._change(null, s);
this._refreshValue()
},
_setOption: function(t, n) {
var r, i = 0;
e.isArray(this.options.values) && (i = this.options.values.length), e.Widget.prototype._setOption.apply(this, arguments);
switch (t) {
case "disabled":
n ? (this.handles.filter(".ui-state-focus").blur(), this.handles.removeClass("ui-state-hover"), this.handles.prop("disabled", !0), this.element.addClass("ui-disabled")) : (this.handles.prop("disabled", !1), this.element.removeClass("ui-disabled"));
break;
case "orientation":
this
._detectOrientation(), this.element.removeClass("ui-slider-horizontal ui-slider-vertical").addClass("ui-slider-" + this.orientation), this._refreshValue();
break;
case "value":
this._animateOff = !0, this._refreshValue(), this._change(null, 0), this._animateOff = !1;
break;
case "values":
this._animateOff = !0, this._refreshValue();
for (r = 0; r < i; r += 1) this._change(null, r);
this._animateOff = !1;
break;
case "min":
case "max":
this._animateOff = !0, this._refreshValue(), this._animateOff = !1
}
},
_value: function() {
var e = this.options.value;
return e = this._trimAlignValue(e), e
},
_values: function(e) {
var t, n, r;
if (arguments.length) return t = this.options.values[e], t = this._trimAlignValue(t), t;
n = this.options.values.slice();
for (r = 0; r < n.length; r += 1) n[r] = this._trimAlignValue(n[r]);
return n
},
_trimAlignValue: function(e) {
if (e <= this._valueMin()) return this._valueMin();
if (e >= this._valueMax()) return this._valueMax();
var t = this.options.step > 0 ? this.options.step : 1,
n = (e - this._valueMin()) % t,
r = e - n;
return Math.abs(n) * 2 >= t && (r += n > 0 ? t : -t), parseFloat(r.toFixed(5))
},
_valueMin: function() {
return this.options.min
},
_valueMax: function() {
return this.options.max
},
_refreshValue: function() {
var t, n, r, i, s, o = this.options.range,
u = this.options,
a = this,
f = this._animateOff ? !1 : u.animate,
l = {};
this.options.values && this.options.values.length ? this.handles.each(function(r) {
n = (a.values(r) - a._valueMin()) / (a._valueMax() - a._valueMin()) * 100, l[a.orientation === "horizontal" ? "left" : "bottom"] = n + "%", e(this).stop(1, 1)[f ? "animate" : "css"](l, u.animate), a.options.range === !0 && (a.orientation === "horizontal" ? (r === 0 && a.range.stop(1, 1)[f ? "animate" : "css"]({
left: n + "%"
}, u.animate), r === 1 && a.range[f ? "animate" : "css"]({
width: n - t + "%"
}, {
queue: !1,
duration: u.animate
})) : (r === 0 && a.range.stop(1, 1)[f ? "animate" : "css"]({
bottom: n + "%"
}, u.animate), r === 1 && a.range[f ? "animate" : "css"]({
height: n - t + "%"
}, {
queue: !1,
duration: u.animate
}))), t = n
}) : (r = this.value(), i = this._valueMin(), s = this._valueMax(), n = s !== i ? (r - i) / (s - i) * 100 : 0, l[this.orientation === "horizontal" ? "left" : "bottom"] = n + "%", this.handle.stop(1, 1)[f ? "animate" : "css"](l, u.animate), o === "min" && this.orientation === "horizontal" && this.range.stop(1, 1)[f ? "animate" : "css"]({
width: n + "%"
}, u.animate), o === "max" && this.orientation === "horizontal" && this.range[f ? "animate" : "css"]({
width: 100 - n + "%"
}, {
queue: !1,
duration: u.animate
}), o === "min" && this.orientation === "vertical" && this.range.stop(1, 1)[f ? "animate" : "css"]({
height: n + "%"
}, u.animate), o === "max" && this.orientation === "vertical" && this.range[f ? "animate" : "css"]({
height: 100 - n + "%"
}, {
queue: !1,
duration: u.animate
}))
}
})
}(jQuery), ! function(e) {
function t() {
return new Date(Date.UTC.apply(Date, arguments))
}
function n() {
var e = new Date;
return t(e.getUTCFullYear(), e.getUTCMonth(), e.getUTCDate())
}
var r = function(t, n) {
var r = this;
this.element = e(t), this.language = n.language || this.element.data("date-language") || "en", this.language = this.language in i ? this.language : this.language.split("-")[0], this.language = this.language in i ? this.language : "en", this.isRTL = i[this.language].rtl || !1, this.format = s.parseFormat(n.format || this.element.data("date-format") || i[this.language].format || "mm/dd/yyyy"), this.isInline = !1, this.isInput = this.element.is("input"), this.component = this.element.is(".date") ? this.element.find(".add-on") : !1, this.hasInput = this.component && this.element.find("input").length, this.component && this.component.length === 0 && (this.component = !1), this._attachEvents(), this.forceParse = !0, "forceParse" in n ? this.forceParse = n.forceParse : "dateForceParse" in this.element.data() && (this.forceParse = this.element.data("date-force-parse")), this.picker = e(s.template).appendTo(this.isInline ? this.element : "body").on({
click: e.proxy(this.click, this),
mousedown: e.proxy(this.mousedown, this)
}), this.isInline ? this.picker.addClass("datepicker-inline") : this.picker.addClass("datepicker-dropdown dropdown-menu"), this.isRTL && (this.picker.addClass("datepicker-rtl"), this.picker.find(".prev i, .next i").toggleClass("icon-arrow-left icon-arrow-right")), e(document).on("mousedown", function(t) {
e(t.target).closest(".datepicker.datepicker-inline, .datepicker.datepicker-dropdown").length === 0 && r.hide()
}), this.autoclose = !1, "autoclose" in n ? this.autoclose = n.autoclose : "dateAutoclose" in this.element.data() && (this.autoclose = this.element.data("date-autoclose")), this.keyboardNavigation = !0, "keyboardNavigation" in n ? this.keyboardNavigation = n.keyboardNavigation : "dateKeyboardNavigation" in this.element.data() && (this.keyboardNavigation = this.element.data("date-keyboard-navigation")), this.viewMode = this.startViewMode = 0;
switch (n.startView || this.element.data("date-start-view")) {
case 2:
case "decade":
this.viewMode = this.startViewMode = 2;
break;
case 1:
case "year":
this.viewMode = this.startViewMode = 1
}
this.minViewMode = n.minViewMode || this.element.data("date-min-view-mode") || 0;
if (typeof this.minViewMode == "string") switch (this.minViewMode) {
case "months":
this.minViewMode = 1;
break;
case "years":
this.minViewMode = 2;
break;
default:
this.minViewMode = 0
}
this.viewMode = this.startViewMode = Math.max(this.startViewMode, this.minViewMode), this.todayBtn = n.todayBtn || this.element.data("date-today-btn") || !1, this.todayHighlight = n.todayHighlight || this.element.data("date-today-highlight") || !1, this.calendarWeeks = !1, "calendarWeeks" in n ? this.calendarWeeks = n.calendarWeeks : "dateCalendarWeeks" in this.element.data() && (this.calendarWeeks = this.element.data("date-calendar-weeks")), this.calendarWeeks && this.picker.find("tfoot th.today").attr("colspan", function(e, t) {
return parseInt(t) + 1
}), this.weekStart = (n.weekStart || this.element.data("date-weekstart") || i[this.language].weekStart || 0) % 7, this.weekEnd = (this.weekStart + 6) % 7, this.startDate = -Infinity, this.endDate = Infinity, this.daysOfWeekDisabled = [], this.setStartDate(n.startDate || this.element.data("date-startdate")), this.setEndDate(n.endDate || this.element.data("date-enddate")), this.setDaysOfWeekDisabled(n.daysOfWeekDisabled || this.element.data("date-days-of-week-disabled")), this.fillDow(), this.fillMonths(), this.update(), this.showMode(), this.isInline && this.show()
};
r.prototype = {
constructor: r,
_events: [],
_attachEvents: function() {
this._detachEvents(), this.isInput ? this._events = [
[this.element, {
focus: e.proxy(this.show, this),
keyup: e.proxy(this.update, this),
keydown: e.proxy(this.keydown, this)
}]
] : this.component && this.hasInput ? this._events = [
[this.element.find("input"), {
focus: e.proxy(this.show, this),
keyup: e.proxy(this.update, this),
keydown: e.proxy(this.keydown, this)
}],
[this.component, {
click: e.proxy(this.show, this)
}]
] : this.element.is("div") ? this.isInline = !0 : this._events = [
[this.element, {
click: e.proxy(this.show, this)
}]
];
for (var t = 0, n, r; t < this._events.length; t++) n = this._events[t][0], r = this._events[t][1], n.on(r)
},
_detachEvents: function() {
for (var e = 0, t, n; e < this._events.length; e++) t = this._events[e][0], n = this._events[e][1], t.off(n);
this._events = []
},
show: function(t) {
this.picker.show(), this.height = this.component ? this.component.outerHeight() : this.element.outerHeight(), this.update(), this.place(), e(window).on("resize", e.proxy(this.place, this)), t && (t.stopPropagation(), t.preventDefault()), this.element.trigger({
type: "show",
date: this.date
})
},
hide: function(t) {
if (this.isInline) return;
if (!this.picker.is(":visible")) return;
this.picker.hide(), e(window).off("resize", this.place), this.viewMode = this.startViewMode, this.showMode(), this.isInput || e(document).off("mousedown", this.hide), this.forceParse && (this.isInput && this.element.val() || this.hasInput && this.element.find("input").val()) && this.setValue(), this.element.trigger({
type: "hide",
date: this.date
})
},
remove: function() {
this._detachEvents(), this.picker.remove(), delete this.element.data().datepicker
},
getDate: function() {
var e = this.getUTCDate();
return new Date(e.getTime() + e.getTimezoneOffset() * 6e4)
},
getUTCDate: function() {
return this.date
},
setDate: function(e) {
this.setUTCDate(new Date(e.getTime() - e.getTimezoneOffset() * 6e4))
},
setUTCDate: function(e) {
this.date = e, this.setValue()
},
setValue: function() {
var e = this.getFormattedDate();
this.isInput ? this.element.val(e) : (this.component && this.element.find("input").val(e), this.element.data("date", e))
},
getFormattedDate: function(e) {
return e === undefined && (e = this.format), s.formatDate(this.date, e, this.language)
},
setStartDate: function(e) {
this.startDate = e || -Infinity, this.startDate !== -Infinity && (this.startDate = s.parseDate(this.startDate, this.format, this.language)), this.update(), this.updateNavArrows()
},
setEndDate: function(e) {
this.endDate = e || Infinity, this.endDate !== Infinity && (this.endDate = s.parseDate(this.endDate, this.format, this.language)), this.update(), this.updateNavArrows()
},
setDaysOfWeekDisabled: function(t) {
this.daysOfWeekDisabled = t || [], e.isArray(this.daysOfWeekDisabled) || (this.daysOfWeekDisabled = this.daysOfWeekDisabled.split(/,\s*/)), this.daysOfWeekDisabled = e.map(this.daysOfWeekDisabled, function(e) {
return parseInt(e, 10)
}), this.update(), this.updateNavArrows()
},
place: function() {
if (this.isInline) return;
var t = parseInt(this.element.parents().filter(function() {
return e(this).css("z-index") != "auto"
}).first().css("z-index")) + 10,
n = this.component ? this.component.offset() : this.element.offset(),
r = this.component ? this.component.outerHeight(!0) : this.element.outerHeight(!0);
this.picker.css({
top: n.top + r,
left: n.left,
zIndex: t
})
},
update: function() {
var e, t = !1;
arguments && arguments.length && (typeof arguments[0] == "string" || arguments[0] instanceof Date) ? (e = arguments[0], t = !0) : e = this.isInput ? this.element.val() : this.element.data("date") || this.element.find("input").val(), this.date = s.parseDate(e, this.format, this.language), t && this.setValue(), this.date < this.startDate ? this.viewDate = new Date(this.startDate) : this.date > this.endDate ? this.viewDate = new Date(this.endDate) : this.viewDate = new Date(this.date), this.fill()
},
fillDow: function() {
var e = this.weekStart,
t = "<tr>";
if (this.calendarWeeks) {
var n = '<th class="cw"> </th>';
t += n, this.picker.find(".datepicker-days thead tr:first-child").prepend(n)
}
while (e < this.weekStart + 7) t += '<th class="dow">' + i[this.language].daysMin[e++ % 7] + "</th>";
t += "</tr>", this.picker.find(".datepicker-days thead").append(t)
},
fillMonths: function() {
var e = "",
t = 0;
while (t < 12) e += '<span class="month">' + i[this.language].monthsShort[t++] + "</span>";
this.picker.find(".datepicker-months td").html(e)
},
fill: function() {
var n = new Date(this.viewDate),
r = n.getUTCFullYear(),
o = n.getUTCMonth(),
u = this.startDate !== -Infinity ? this.startDate.getUTCFullYear() : -Infinity,
a = this.startDate !== -Infinity ? this.startDate.getUTCMonth() : -Infinity,
f = this.endDate !== Infinity ? this.endDate.getUTCFullYear() : Infinity,
l = this.endDate !== Infinity ? this.endDate.getUTCMonth() : Infinity,
c = this.date && this.date.valueOf(),
h = new Date;
this.picker.find(".datepicker-days thead th.switch").text(i[this.language].months[o] + " " + r), this.picker.find("tfoot th.today").text(i[this.language].today).toggle(this.todayBtn !== !1), this.updateNavArrows(), this.fillMonths();
var p = t(r, o - 1, 28, 0, 0, 0, 0),
d = s.getDaysInMonth(p.getUTCFullYear(), p.getUTCMonth());
p.setUTCDate(d), p.setUTCDate(d - (p.getUTCDay() - this.weekStart + 7) % 7);
var v = new Date(p);
v.setUTCDate(v.getUTCDate() + 42), v = v.valueOf();
var m = [],
g;
while (p.valueOf() < v) {
if (p.getUTCDay() == this.weekStart) {
m.push("<tr>");
if (this.calendarWeeks) {
var y = new Date(+p + (this.weekStart - p.getUTCDay() - 7) % 7 * 864e5),
b = new Date(+y + (11 - y.getUTCDay()) % 7 * 864e5),
w = new Date(+(w = t(b.getUTCFullYear(), 0, 1)) + (11 - w.getUTCDay()) % 7 * 864e5),
E = (b - w) / 864e5 / 7 + 1;
m.push('<td class="cw">' + E + "</td>")
}
}
g = "";
if (p.getUTCFullYear() < r || p.getUTCFullYear() == r && p.getUTCMonth() < o) g += " old";
else if (p.getUTCFullYear() > r || p.getUTCFullYear() == r && p.getUTCMonth() > o) g += " new";
this.todayHighlight && p.getUTCFullYear() == h.getFullYear() && p.getUTCMonth() == h.getMonth() && p.getUTCDate() == h.getDate() && (g += " today"), c && p.valueOf() == c && (g += " active");
if (p.valueOf() < this.startDate || p.valueOf() > this.endDate || e.inArray(p.getUTCDay(), this.daysOfWeekDisabled) !== -1) g += " disabled";
m.push('<td class="day' + g + '">' + p.getUTCDate() + "</td>"), p.getUTCDay() == this.weekEnd && m.push("</tr>"), p.setUTCDate(p.getUTCDate() + 1)
}
this.picker.find(".datepicker-days tbody").empty().append(m.join(""));
var S = this.date && this.date.getUTCFullYear(),
x = this.picker.find(".datepicker-months").find("th:eq(1)").text(r).end().find("span").removeClass("active");
S && S == r && x.eq(this.date.getUTCMonth()).addClass("active"), (r < u || r > f) && x.addClass("disabled"), r == u && x.slice(0, a).addClass("disabled"), r == f && x.slice(l + 1).addClass("disabled"), m = "", r = parseInt(r / 10, 10) * 10;
var T = this.picker.find(".datepicker-years").find("th:eq(1)").text(r + "-" + (r + 9)).end().find("td");
r -= 1;
for (var N = -1; N < 11; N++) m += '<span class="year' + (N == -1 || N == 10 ? " old" : "") + (S == r ? " active" : "") + (r < u || r > f ? " disabled" : "") + '">' + r + "</span>", r += 1;
T.html(m)
},
updateNavArrows: function() {
var e = new Date(this.viewDate),
t = e.getUTCFullYear(),
n = e.getUTCMonth();
switch (this.viewMode) {
case 0:
this.startDate !== -Infinity && t <= this.startDate.getUTCFullYear() && n <= this.startDate.getUTCMonth() ? this.picker.find(".prev").css({
visibility: "hidden"
}) : this.picker.find(".prev").css({
visibility: "visible"
}), this.endDate !== Infinity && t >= this.endDate.getUTCFullYear() && n >= this.endDate.getUTCMonth() ? this.picker.find(".next").css({
visibility: "hidden"
}) : this.picker.find(".next").css({
visibility: "visible"
});
break;
case 1:
case 2:
this.startDate !== -Infinity && t <= this.startDate.getUTCFullYear() ? this.picker.find(".prev").css({
visibility: "hidden"
}) : this.picker.find(".prev").css({
visibility: "visible"
}), this.endDate !== Infinity && t >= this.endDate.getUTCFullYear() ? this.picker.find(".next").css({
visibility: "hidden"
}) : this.picker.find(".next").css({
visibility: "visible"
})
}
},
click: function(n) {
n.stopPropagation(), n.preventDefault();
var r = e(n.target).closest("span, td, th");
if (r.length == 1) switch (r[0].nodeName.toLowerCase()) {
case "th":
switch (r[0].className) {
case "switch":
this.showMode(1);
break;
case "prev":
case "next":
var i = s.modes[this.viewMode].navStep * (r[0].className == "prev" ? -1 : 1);
switch (this.viewMode) {
case 0:
this.viewDate = this.moveMonth(this.viewDate, i);
break;
case 1:
case 2:
this.viewDate = this.moveYear(this.viewDate, i)
}
this.fill();
break;
case "today":
var o = new Date;
o = t(o.getFullYear(), o.getMonth(), o.getDate(), 0, 0, 0), this.showMode(-2);
var u = this.todayBtn == "linked" ? null : "view";
this._setDate(o, u)
}
break;
case "span":
if (!r.is(".disabled")) {
this.viewDate.setUTCDate(1);
if (r.is(".month")) {
var a = 1,
f = r.parent().find("span").index(r),
l = this.viewDate.getUTCFullYear();
this.viewDate.setUTCMonth(f), this.element.trigger({
type: "changeMonth",
date: this.viewDate
}), this.minViewMode == 1 && this._setDate(t(l, f, a, 0, 0, 0, 0))
} else {
var l = parseInt(r.text(), 10) || 0,
a = 1,
f = 0;
this.viewDate.setUTCFullYear(l), this.element.trigger({
type: "changeYear",
date: this.viewDate
}), this.minViewMode == 2 && this._setDate(t(l, f, a, 0, 0, 0, 0))
}
this.showMode(-1), this.fill()
}
break;
case "td":
if (r.is(".day") && !r.is(".disabled")) {
var a = parseInt(r.text(), 10) || 1,
l = this.viewDate.getUTCFullYear(),
f = this.viewDate.getUTCMonth();
r.is(".old") ? f === 0 ? (f = 11, l -= 1) : f -= 1 : r.is(".new") && (f == 11 ? (f = 0, l += 1) : f += 1), this._setDate(t(l, f, a, 0, 0, 0, 0))
}
}
},
_setDate: function(e, t) {
if (!t || t == "date") this.date = e;
if (!t || t == "view") this.viewDate = e;
this.fill(), this.setValue(), this.element.trigger({
type: "changeDate",
date: this.date
});
var n;
this.isInput ? n = this.element : this.component && (n = this.element.find("input")), n && (n.change(), this.autoclose && (!t || t == "date") && this.hide())
},
moveMonth: function(e, t) {
if (!t) return e;
var n = new Date(e.valueOf()),
r = n.getUTCDate(),
i = n.getUTCMonth(),
s = Math.abs(t),
o, u;
t = t > 0 ? 1 : -1;
if (s == 1) {
u = t == -1 ? function() {
return n.getUTCMonth() == i
} : function() {
return n.getUTCMonth() != o
}, o = i + t, n.setUTCMonth(o);
if (o < 0 || o > 11) o = (o + 12) % 12
} else {
for (var a = 0; a < s; a++) n = this.moveMonth(n, t);
o = n.getUTCMonth(), n.setUTCDate(r), u = function() {
return o != n.getUTCMonth()
}
}
while (u()) n.setUTCDate(--r), n.setUTCMonth(o);
return n
},
moveYear: function(e, t) {
return this.moveMonth(e, t * 12)
},
dateWithinRange: function(e) {
return e >= this.startDate && e <= this.endDate
},
keydown: function(e) {
if (this.picker.is(":not(:visible)")) {
e.keyCode == 27 && this.show();
return
}
var t = !1,
n, r, i, s, o;
switch (e.keyCode) {
case 27:
this.hide(), e.preventDefault();
break;
case 37:
case 39:
if (!this.keyboardNavigation) break;
n = e.keyCode == 37 ? -1 : 1, e.ctrlKey ? (s = this.moveYear(this.date, n), o = this.moveYear(this.viewDate, n)) : e.shiftKey ? (s = this.moveMonth(this.date, n), o = this.moveMonth(this.viewDate, n)) : (s = new Date(this.date), s.setUTCDate(this.date.getUTCDate() + n), o = new Date(this.viewDate), o.setUTCDate(this.viewDate.getUTCDate() + n)), this.dateWithinRange(s) && (this.date = s, this.viewDate = o, this.setValue(), this.update(), e.preventDefault(), t = !0);
break;
case 38:
case 40:
if (!this.keyboardNavigation) break;
n = e.keyCode == 38 ? -1 : 1, e.ctrlKey ? (s = this.moveYear(this.date, n), o = this.moveYear(this.viewDate, n)) : e.shiftKey ? (s = this.moveMonth(this.date, n), o = this.moveMonth(this.viewDate, n)) : (s = new Date(this.date), s.setUTCDate(this.date.getUTCDate() + n * 7), o = new Date(this.viewDate), o.setUTCDate(this.viewDate.getUTCDate() + n * 7)), this.dateWithinRange(s) && (this.date = s, this.viewDate = o, this.setValue(), this.update(), e.preventDefault(), t = !0);
break;
case 13:
this.hide(), e.preventDefault();
break;
case 9:
this.hide()
}
if (t) {
this.element.trigger({
type: "changeDate",
date: this.date
});
var u;
this.isInput ? u = this.element : this.component && (u = this.element.find("input")), u && u.change()
}
},
showMode: function(e) {
e && (this.viewMode = Math.max(this.minViewMode, Math.min(2, this.viewMode + e))), this.picker.find(">div").hide().filter(".datepicker-" + s.modes[this.viewMode].clsName).css("display", "block"), this.updateNavArrows()
}
}, e.fn.datepicker = function(t) {
var n = Array.apply(null, arguments);
return n.shift(), this.each(function() {
var i = e(this),
s = i.data("datepicker"),
o = typeof t == "object" && t;
s || i.data("datepicker", s = new r(this, e.extend({}, e.fn.datepicker.defaults, o))), typeof t == "string" && typeof s[t] == "function" && s[t].apply(s, n)
})
}, e.fn.datepicker.defaults = {}, e.fn.datepicker.Constructor = r;
var i = e.fn.datepicker.dates = {
en: {
days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"],
daysShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
daysMin: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"],
months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
monthsShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
today: "Today"
}
},
s = {
modes: [{
clsName: "days",
navFnc: "Month",
navStep: 1
}, {
clsName: "months",
navFnc: "FullYear",
navStep: 1
}, {
clsName: "years",
navFnc: "FullYear",
navStep: 10
}],
isLeapYear: function(e) {
return e % 4 === 0 && e % 100 !== 0 || e % 400 === 0
},
getDaysInMonth: function(e, t) {
return [31, s.isLeapYear(e) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][t]
},
validParts: /dd?|DD?|mm?|MM?|yy(?:yy)?/g,
nonpunctuation: /[^ -\/:-@\[\u3400-\u9fff-`{-~\t\n\r]+/g,
parseFormat: function(e) {
var t = e.replace(this.validParts, "\0").split("\0"),
n = e.match(this.validParts);
if (!t || !t.length || !n || n.length === 0) throw new Error("Invalid date format.");
return {
separators: t,
parts: n
}
},
parseDate: function(n, s, o) {
if (n instanceof Date) return n;
if (/^[\-+]\d+[dmwy]([\s,]+[\-+]\d+[dmwy])*$/.test(n)) {
var u = /([\-+]\d+)([dmwy])/,
a = n.match(/([\-+]\d+)([dmwy])/g),
f, l;
n = new Date;
for (var c = 0; c < a.length; c++) {
f = u.exec(a[c]), l = parseInt(f[1]);
switch (f[2]) {
case "d":
n.setUTCDate(n.getUTCDate() + l);
break;
case "m":
n = r.prototype.moveMonth.call(r.prototype, n, l);
break;
case "w":
n.setUTCDate(n.getUTCDate() + l * 7);
break;
case "y":
n = r.prototype.moveYear.call(r.prototype, n, l)
}
}
return t(n.getUTCFullYear(), n.getUTCMonth(), n.getUTCDate(), 0, 0, 0)
}
var a = n && n.match(this.nonpunctuation) || [],
n = new Date,
h = {},
p = ["yyyy", "yy", "M", "MM", "m", "mm", "d", "dd"],
d = {
yyyy: function(e, t) {
return e.setUTCFullYear(t)
},
yy: function(e, t) {
return e.setUTCFullYear(2e3 + t)
},
m: function(e, t) {
t -= 1;
while (t < 0) t += 12;
t %= 12, e.setUTCMonth(t);
while (e.getUTCMonth() != t) e.setUTCDate(e.getUTCDate() - 1);
return e
},
d: function(e, t) {
return e.setUTCDate(t)
}
},
v, m, f;
d.M = d.MM = d.mm = d.m, d.dd = d.d, n = t(n.getFullYear(), n.getMonth(), n.getDate(), 0, 0, 0);
var g = s.parts.slice();
a.length != g.length && (g = e(g).filter(function(t, n) {
return e.inArray(n, p) !== -1
}).toArray());
if (a.length == g.length) {
for (var c = 0, y = g.length; c < y; c++) {
v = parseInt(a[c], 10), f = g[c];
if (isNaN(v)) switch (f) {
case "MM":
m = e(i[o].months).filter(function() {
var e = this.slice(0, a[c].length),
t = a[c].slice(0, e.length);
return e == t
}), v = e.inArray(m[0], i[o].months) + 1;
break;
case "M":
m = e(i[o].monthsShort).filter(function() {
var e = this.slice(0, a[c].length),
t = a[c].slice(0, e.length);
return e == t
}), v = e.inArray(m[0], i[o].monthsShort) + 1
}
h[f] = v
}
for (var c = 0, b; c < p.length; c++) b = p[c], b in h && !isNaN(h[b]) && d[b](n, h[b])
}
return n
},
formatDate: function(t, n, r) {
var s = {
d: t.getUTCDate(),
D: i[r].daysShort[t.getUTCDay()],
DD: i[r].days[t.getUTCDay()],
m: t.getUTCMonth() + 1,
M: i[r].monthsShort[t.getUTCMonth()],
MM: i[r].months[t.getUTCMonth()],
yy: t.getUTCFullYear().toString().substring(2),
yyyy: t.getUTCFullYear()
};
s.dd = (s.d < 10 ? "0" : "") + s.d, s.mm = (s.m < 10 ? "0" : "") + s.m;
var t = [],
o = e.extend([], n.separators);
for (var u = 0, a = n.parts.length; u < a; u++) o.length && t.push(o.shift()), t.push(s[n.parts[u]]);
return t.join("")
},
headTemplate: '<thead><tr><th class="prev"><i class="icon-arrow-left"/></th><th colspan="5" class="switch"></th><th class="next"><i class="icon-arrow-right"/></th></tr></thead>',
contTemplate: '<tbody><tr><td colspan="7"></td></tr></tbody>',
footTemplate: '<tfoot><tr><th colspan="7" class="today"></th></tr></tfoot>'
};
s.template = '<div class="datepicker"><div class="datepicker-days"><table class=" table-condensed">' + s.headTemplate + "<tbody></tbody>" + s.footTemplate + "</table>" + "</div>" + '<div class="datepicker-months">' + '<table class="table-condensed">' + s.headTemplate + s.contTemplate + s.footTemplate + "</table>" + "</div>" + '<div class="datepicker-years">' + '<table class="table-condensed">' + s.headTemplate + s.contTemplate + s.footTemplate + "</table>" + "</div>" + "</div>", e.fn.datepicker.DPGlobal = s
}(window.jQuery),
function(e) {
e.fn.datepicker.dates.bg = {
days: ["Неделя", "Понеделник", "Вторник", "Сряда", "Четвъртък", "Петък", "Събота", "Неделя"],
daysShort: ["Нед", "Пон", "Вто", "Сря", "Чет", "Пет", "Съб", "Нед"],
daysMin: ["Н", "П", "В", "С", "Ч", "П", "С", "Н"],
months: ["Януари", "Февруари", "Март", "Април", "Май", "Юни", "Юли", "Август", "Септември", "Октомври", "Ноември", "Декември"],
monthsShort: ["Ян", "Фев", "Мар", "Апр", "Май", "Юни", "Юли", "Авг", "Сеп", "Окт", "Ное", "Дек"],
today: "днес"
}
}(jQuery),
function(e) {
e.fn.datepicker.dates.br = {
days: ["Domingo", "Segunda", "Terça", "Quarta", "Quinta", "Sexta", "Sábado", "Domingo"],
daysShort: ["Dom", "Seg", "Ter", "Qua", "Qui", "Sex", "Sáb", "Dom"],
daysMin: ["Do", "Se", "Te", "Qu", "Qu", "Se", "Sa", "Do"],
months: ["Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"],
monthsShort: ["Jan", "Fev", "Mar", "Abr", "Mai", "Jun", "Jul", "Ago", "Set", "Out", "Nov", "Dez"]
}
}(jQuery),
function(e) {
e.fn.datepicker.dates.ca = {
days: ["Diumenge", "Dilluns", "Dimarts", "Dimecres", "Dijous", "Divendres", "Dissabte", "Diumenge"],
daysShort: ["Diu", "Dil", "Dmt", "Dmc", "Dij", "Div", "Dis", "Diu"],
daysMin: ["dg", "dl", "dt", "dc", "dj", "dv", "ds", "dg"],
months: ["Gener", "Febrer", "Març", "Abril", "Maig", "Juny", "Juliol", "Agost", "Setembre", "Octubre", "Novembre", "Desembre"],
monthsShort: ["Gen", "Feb", "Mar", "Abr", "Mai", "Jun", "Jul", "Ago", "Set", "Oct", "Nov", "Des"],
today: "Avui"
}
}(jQuery),
function(e) {
e.fn.datepicker.dates.cs = {
days: ["Neděle", "Pondělí", "Úterý", "Středa", "Čtvrtek", "Pátek", "Sobota", "Neděle"],
daysShort: ["Ned", "Pon", "Úte", "Stř", "Čtv", "Pát", "Sob", "Ned"],
daysMin: ["Ne", "Po", "Út", "St", "Čt", "Pá", "So", "Ne"],
months: ["Leden", "Únor", "Březen", "Duben", "Květen", "Červen", "Červenec", "Srpen", "Září", "Říjen", "Listopad", "Prosinec"],
monthsShort: ["Led", "Úno", "Bře", "Dub", "Kvě", "Čer", "Čnc", "Srp", "Zář", "Říj", "Lis", "Pro"],
today: "Dnes"
}
}(jQuery),
function(e) {
e.fn.datepicker.dates.da = {
days: ["Søndag", "Mandag", "Tirsdag", "Onsdag", "Torsdag", "Fredag", "Lørdag", "Søndag"],
daysShort: ["Søn", "Man", "Tir", "Ons", "Tor", "Fre", "Lør", "Søn"],
daysMin: ["Sø", "Ma", "Ti", "On", "To", "Fr", "Lø", "Sø"],
months: ["Januar", "Februar", "Marts", "April", "Maj", "Juni", "Juli", "August", "September", "Oktober", "November", "December"],
monthsShort: ["Jan", "Feb", "Mar", "Apr", "Maj", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dec"],
today: "I Dag"
}
}(jQuery),
function(e) {
e.fn.datepicker.dates.de = {
days: ["Sonntag", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag", "Sonntag"],
daysShort: ["Son", "Mon", "Die", "Mit", "Don", "Fre", "Sam", "Son"],
daysMin: ["So", "Mo", "Di", "Mi", "Do", "Fr", "Sa", "So"],
months: ["Januar", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"],
monthsShort: ["Jan", "Feb", "Mär", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dez"],
today: "Heute",
weekStart: 1,
format: "dd.mm.yyyy"
}
}(jQuery),
function(e) {
e.fn.datepicker.dates.el = {
days: ["Κυριακή", "Δευτέρα", "Τρίτη", "Τετάρτη", "Πέμπτη", "Παρασκευή", "Σάββατο", "Κυριακή"],
daysShort: ["Κυρ", "Δευ", "Τρι", "Τετ", "Πεμ", "Παρ", "Σαβ", "Κυρ"],
daysMin: ["Κυ", "Δε", "Τρ", "Τε", "Πε", "Πα", "Σα", "Κυ"],
months: ["Ιανουάριος", "Φεβρουάριος", "Μάρτιος", "Απρίλιος", "Μάιος", "Ιούνιος", "Ιούλιος", "Αύγουστος", "Σεπτέμβριος", "Οκτώβριος", "Νοέμβριος", "Δεκέμβριος"],
monthsShort: ["Ιαν", "Φεβ", "Μαρ", "Απρ", "Μάι", "Ιουν", "Ιουλ", "Αυγ", "Σεπ", "Οκτ", "Νοε", "Δεκ"],
today: "Σήμερα"
}
}(jQuery),
function(e) {
e.fn.datepicker.dates.es = {
days: ["Domingo", "Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado", "Domingo"],
daysShort: ["Dom", "Lun", "Mar", "Mié", "Jue", "Vie", "Sáb", "Dom"],
daysMin: ["Do", "Lu", "Ma", "Mi", "Ju", "Vi", "Sa", "Do"],
months: ["Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"],
monthsShort: ["Ene", "Feb", "Mar", "Abr", "May", "Jun", "Jul", "Ago", "Sep", "Oct", "Nov", "Dic"],
today: "Hoy"
}
}(jQuery),
function(e) {
e.fn.datepicker.dates.fi = {
days: ["sunnuntai", "maanantai", "tiistai", "keskiviikko", "torstai", "perjantai", "lauantai", "sunnuntai"],
daysShort: ["sun", "maa", "tii", "kes", "tor", "per", "lau", "sun"],
daysMin: ["su", "ma", "ti", "ke", "to", "pe", "la", "su"],
months: ["tammikuu", "helmikuu", "maaliskuu", "huhtikuu", "toukokuu", "kesäkuu", "heinäkuu", "elokuu", "syyskuu", "lokakuu", "marraskuu", "joulukuu"],
monthsShort: ["tam", "hel", "maa", "huh", "tou", "kes", "hei", "elo", "syy", "lok", "mar", "jou"],
today: "tänään"
}
}(jQuery),
function(e) {
e.fn.datepicker.dates.fr = {
days: ["Dimanche", "Lundi", "Mardi", "Mercredi", "Jeudi", "Vendredi", "Samedi", "Dimanche"],
daysShort: ["Dim", "Lun", "Mar", "Mer", "Jeu", "Ven", "Sam", "Dim"],
daysMin: ["D", "L", "Ma", "Me", "J", "V", "S", "D"],
months: ["Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre"],
monthsShort: ["Jan", "Fev", "Mar", "Avr", "Mai", "Jui", "Jul", "Aou", "Sep", "Oct", "Nov", "Dec"],
today: "Aujourd'hui",
weekStart: 1,
format: "dd/mm/yyyy"
}
}(jQuery),
function(e) {
e.fn.datepicker.dates.he = {
days: ["ראשון", "שני", "שלישי", "רביעי", "חמישי", "שישי", "שבת", "ראשון"],
daysShort: ["א", "ב", "ג", "ד", "ה", "ו", "ש", "א"],
daysMin: ["א", "ב", "ג", "ד", "ה", "ו", "ש", "א"],
months: ["ינואר", "פברואר", "מרץ", "אפריל", "מאי", "יוני", "יולי", "אוגוסט", "ספטמבר", "אוקטובר", "נובמבר", "דצמבר"],
monthsShort: ["ינו", "פבר", "מרץ", "אפר", "מאי", "יונ", "יול", "אוג", "ספט", "אוק", "נוב", "דצמ"],
today: "היום",
rtl: !0
}
}(jQuery),
function(e) {
e.fn.datepicker.dates.hr = {
days: ["Nedjelja", "Ponedjelja", "Utorak", "Srijeda", "Četrtak", "Petak", "Subota", "Nedjelja"],
daysShort: ["Ned", "Pon", "Uto", "Srr", "Čet", "Pet", "Sub", "Ned"],
daysMin: ["Ne", "Po", "Ut", "Sr", "Če", "Pe", "Su", "Ne"],
months: ["Siječanj", "Veljača", "Ožujak", "Travanj", "Svibanj", "Lipanj", "Srpanj", "Kolovoz", "Rujan", "Listopad", "Studeni", "Prosinac"],
monthsShort: ["Sije", "Velj", "Ožu", "Tra", "Svi", "Lip", "Jul", "Kol", "Ruj", "Lis", "Stu", "Pro"],
today: "Danas"
}
}(jQuery),
function(e) {
e.fn.datepicker.dates.id = {
days: ["Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu", "Minggu"],
daysShort: ["Mgu", "Sen", "Sel", "Rab", "Kam", "Jum", "Sab", "Mgu"],
daysMin: ["Mg", "Sn", "Sl", "Ra", "Ka", "Ju", "Sa", "Mg"],
months: ["Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"],
monthsShort: ["Jan", "Feb", "Mar", "Apr", "Mei", "Jun", "Jul", "Ags", "Sep", "Okt", "Nov", "Des"]
}
}(jQuery),
function(e) {
e.fn.datepicker.dates.is = {
days: ["Sunnudagur", "Mánudagur", "Þriðjudagur", "Miðvikudagur", "Fimmtudagur", "Föstudagur", "Laugardagur", "Sunnudagur"],
daysShort: ["Sun", "Mán", "Þri", "Mið", "Fim", "Fös", "Lau", "Sun"],
daysMin: ["Su", "Má", "Þr", "Mi", "Fi", "Fö", "La", "Su"],
months: ["Janúar", "Febrúar", "Mars", "Apríl", "Maí", "Júní", "Júlí", "Ágúst", "September", "Október", "Nóvember", "Desember"],
monthsShort: ["Jan", "Feb", "Mar", "Apr", "Maí", "Jún", "Júl", "Ágú", "Sep", "Okt", "Nóv", "Des"],
today: "Í Dag"
}
}(jQuery),
function(e) {
e.fn.datepicker.dates.it = {
days: ["Domenica", "Lunedì", "Martedì", "Mercoledì", "Giovedì", "Venerdì", "Sabato", "Domenica"],
daysShort: ["Dom", "Lun", "Mar", "Mer", "Gio", "Ven", "Sab", "Dom"],
daysMin: ["Do", "Lu", "Ma", "Me", "Gi", "Ve", "Sa", "Do"],
months: ["Gennaio", "Febbraio", "Marzo", "Aprile", "Maggio", "Giugno", "Luglio", "Agosto", "Settembre", "Ottobre", "Novembre", "Dicembre"],
monthsShort: ["Gen", "Feb", "Mar", "Apr", "Mag", "Giu", "Lug", "Ago", "Set", "Ott", "Nov", "Dic"],
today: "Oggi",
weekStart: 1,
format: "dd/mm/yyyy"
}
}(jQuery),
function(e) {
e.fn.datepicker.dates.ja = {
days: ["日曜", "月曜", "火曜", "水曜", "木曜", "金曜", "土曜", "日曜"],
daysShort: ["日", "月", "火", "水", "木", "金", "土", "日"],
daysMin: ["日", "月", "火", "水", "木", "金", "土", "日"],
months: ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"],
monthsShort: ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"]
}
}(jQuery),
function(e) {
e.fn.datepicker.dates.kr = {
days: ["일요일", "월요일", "화요일", "수요일", "목요일", "금요일", "토요일", "일요일"],
daysShort: ["일", "월", "화", "수", "목", "금", "토", "일"],
daysMin: ["일", "월", "화", "수", "목", "금", "토", "일"],
months: ["1월", "2월", "3월", "4월", "5월", "6월", "7월", "8월", "9월", "10월", "11월", "12월"],
monthsShort: ["1월", "2월", "3월", "4월", "5월", "6월", "7월", "8월", "9월", "10월", "11월", "12월"]
}
}(jQuery),
function(e) {
e.fn.datepicker.dates.lt = {
days: ["Sekmadienis", "Pirmadienis", "Antradienis", "Trečiadienis", "Ketvirtadienis", "Penktadienis", "Šeštadienis", "Sekmadienis"],
daysShort: ["S", "Pr", "A", "T", "K", "Pn", "Š", "S"],
daysMin: ["Sk", "Pr", "An", "Tr", "Ke", "Pn", "Št", "Sk"],
months: ["Sausis", "Vasaris", "Kovas", "Balandis", "Gegužė", "Birželis", "Liepa", "Rugpjūtis", "Rugsėjis", "Spalis", "Lapkritis", "Gruodis"],
monthsShort: ["Sau", "Vas", "Kov", "Bal", "Geg", "Bir", "Lie", "Rugp", "Rugs", "Spa", "Lap", "Gru"],
today: "Šiandien",
weekStart: 1
}
}(jQuery),
function(e) {
e.fn.datepicker.dates.lv = {
days: ["Svētdiena", "Pirmdiena", "Otrdiena", "Trešdiena", "Ceturtdiena", "Piektdiena", "Sestdiena", "Svētdiena"],
daysShort: ["Sv", "P", "O", "T", "C", "Pk", "S", "Sv"],
daysMin: ["Sv", "Pr", "Ot", "Tr", "Ce", "Pk", "St", "Sv"],
months: ["Janvāris", "Februāris", "Marts", "Aprīlis", "Maijs", "Jūnijs", "Jūlijs", "Augusts", "Septembris", "Oktobris", "Novembris", "Decembris"],
monthsShort: ["Jan", "Feb", "Mar", "Apr", "Mai", "Jūn", "Jūl", "Aug", "Sep", "Okt", "Nov", "Dec."],
today: "Šodien",
weekStart: 1
}
}(jQuery),
function(e) {
e.fn.datepicker.dates.ms = {
days: ["Ahad", "Isnin", "Selasa", "Rabu", "Khamis", "Jumaat", "Sabtu", "Ahad"],
daysShort: ["Aha", "Isn", "Sel", "Rab", "Kha", "Jum", "Sab", "Aha"],
daysMin: ["Ah", "Is", "Se", "Ra", "Kh", "Ju", "Sa", "Ah"],
months: ["Januari", "Februari", "Mac", "April", "Mei", "Jun", "Julai", "Ogos", "September", "Oktober", "November", "Disember"],
monthsShort: ["Jan", "Feb", "Mar", "Apr", "Mei", "Jun", "Jul", "Ogo", "Sep", "Okt", "Nov", "Dis"],
today: "Hari Ini"
}
}(jQuery),
function(e) {
e.fn.datepicker.dates.nb = {
days: ["Søndag", "Mandag", "Tirsdag", "Onsdag", "Torsdag", "Fredag", "Lørdag", "Søndag"],
daysShort: ["Søn", "Man", "Tir", "Ons", "Tor", "Fre", "Lør", "Søn"],
daysMin: ["Sø", "Ma", "Ti", "On", "To", "Fr", "Lø", "Sø"],
months: ["Januar", "Februar", "Mars", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Desember"],
monthsShort: ["Jan", "Feb", "Mar", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Des"],
today: "I Dag"
}
}(jQuery),
function(e) {
e.fn.datepicker.dates.nl = {
days: ["Zondag", "Maandag", "Dinsdag", "Woensdag", "Donderdag", "Vrijdag", "Zaterdag", "Zondag"],
daysShort: ["Zo", "Ma", "Di", "Wo", "Do", "Vr", "Za", "Zo"],
daysMin: ["Zo", "Ma", "Di", "Wo", "Do", "Vr", "Za", "Zo"],
months: ["Januari", "Februari", "Maart", "April", "Mei", "Juni", "Juli", "Augustus", "September", "Oktober", "November", "December"],
monthsShort: ["Jan", "Feb", "Mrt", "Apr", "Mei", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dec"],
today: "Vandaag"
}
}(jQuery),
function(e) {
e.fn.datepicker.dates.pl = {
days: ["Niedziela", "Poniedziałek", "Wtorek", "Środa", "Czwartek", "Piątek", "Sobota", "Niedziela"],
daysShort: ["Nie", "Pn", "Wt", "Śr", "Czw", "Pt", "So", "Nie"],
daysMin: ["N", "Pn", "Wt", "Śr", "Cz", "Pt", "So", "N"],
months: ["Styczeń", "Luty", "Marzec", "Kwiecień", "Maj", "Czerwiec", "Lipiec", "Sierpień", "Wrzesień", "Październik", "Listopad", "Grudzień"],
monthsShort: ["Sty", "Lu", "Mar", "Kw", "Maj", "Cze", "Lip", "Sie", "Wrz", "Pa", "Lis", "Gru"],
today: "Dzisiaj",
weekStart: 1
}
}(jQuery),
function(e) {
e.fn.datepicker.dates["pt-BR"] = {
days: ["Domingo", "Segunda", "Terça", "Quarta", "Quinta", "Sexta", "Sábado", "Domingo"],
daysShort: ["Dom", "Seg", "Ter", "Qua", "Qui", "Sex", "Sáb", "Dom"],
daysMin: ["Do", "Se", "Te", "Qu", "Qu", "Se", "Sa", "Do"],
months: ["Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"],
monthsShort: ["Jan", "Fev", "Mar", "Abr", "Mai", "Jun", "Jul", "Ago", "Set", "Out", "Nov", "Dez"],
today: "Hoje"
}
}(jQuery),
function(e) {
e.fn.datepicker.dates.pt = {
days: ["Domingo", "Segunda", "Terça", "Quarta", "Quinta", "Sexta", "Sábado", "Domingo"],
daysShort: ["Dom", "Seg", "Ter", "Qua", "Qui", "Sex", "Sáb", "Dom"],
daysMin: ["Do", "Se", "Te", "Qu", "Qu", "Se", "Sa", "Do"],
months: ["Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"],
monthsShort: ["Jan", "Fev", "Mar", "Abr", "Mai", "Jun", "Jul", "Ago", "Set", "Out", "Nov", "Dez"]
}
}(jQuery),
function(e) {
e.fn.datepicker.dates.ro = {
days: ["Duminică", "Luni", "Marţi", "Miercuri", "Joi", "Vineri", "Sâmbătă", "Duminică"],
daysShort: ["Dum", "Lun", "Mar", "Mie", "Joi", "Vin", "Sâm", "Dum"],
daysMin: ["Du", "Lu", "Ma", "Mi", "Jo", "Vi", "Sâ", "Du"],
months: ["Ianuarie", "Februarie", "Martie", "Aprilie", "Mai", "Iunie", "Iulie", "August", "Septembrie", "Octombrie", "Noiembrie", "Decembrie"],
monthsShort: ["Ian", "Feb", "Mar", "Apr", "Mai", "Iun", "Iul", "Aug", "Sep", "Oct", "Nov", "Dec"],
today: "Astăzi",
weekStart: 1
}
}(jQuery),
function(e) {
e.fn.datepicker.dates.rs = {
days: ["Nedelja", "Ponedeljak", "Utorak", "Sreda", "Četvrtak", "Petak", "Subota", "Nedelja"],
daysShort: ["Ned", "Pon", "Uto", "Sre", "Čet", "Pet", "Sub", "Ned"],
daysMin: ["N", "Po", "U", "Sr", "Č", "Pe", "Su", "N"],
months: ["Januar", "Februar", "Mart", "April", "Maj", "Jun", "Jul", "Avgust", "Septembar", "Oktobar", "Novembar", "Decembar"],
monthsShort: ["Jan", "Feb", "Mar", "Apr", "Maj", "Jun", "Jul", "Avg", "Sep", "Okt", "Nov", "Dec"],
today: "Danas"
}
}(jQuery),
function(e) {
e.fn.datepicker.dates.rs = {
days: ["Недеља", "Понедељак", "Уторак", "Среда", "Четвртак", "Петак", "Субота", "Недеља"],
daysShort: ["Нед", "Пон", "Уто", "Сре", "Чет", "Пет", "Суб", "Нед"],
daysMin: ["Н", "По", "У", "Ср", "Ч", "Пе", "Су", "Н"],
months: ["Јануар", "Фебруар", "Март", "Април", "Мај", "Јун", "Јул", "Август", "Септембар", "Октобар", "Новембар", "Децембар"],
monthsShort: ["Јан", "Феб", "Мар", "Апр", "Мај", "Јун", "Јул", "Авг", "Сеп", "Окт", "Нов", "Дец"],
today: "Данас"
}
}(jQuery),
function(e) {
e.fn.datepicker.dates.ru = {
days: ["Воскресенье", "Понедельник", "Вторник", "Среда", "Четверг", "Пятница", "Суббота", "Воскресенье"],
daysShort: ["Вск", "Пнд", "Втр", "Срд", "Чтв", "Птн", "Суб", "Вск"],
daysMin: ["Вс", "Пн", "Вт", "Ср", "Чт", "Пт", "Сб", "Вс"],
months: ["Январь", "Февраль", "Март", "Апрель", "Май", "Июнь", "Июль", "Август", "Сентябрь", "Октябрь", "Ноябрь", "Декабрь"],
monthsShort: ["Янв", "Фев", "Мар", "Апр", "Май", "Июн", "Июл", "Авг", "Сен", "Окт", "Ноя", "Дек"],
today: "Сегодня"
}
}(jQuery),
function(e) {
e.fn.datepicker.dates.sk = {
days: ["Nedeľa", "Pondelok", "Utorok", "Streda", "Štvrtok", "Piatok", "Sobota", "Nedeľa"],
daysShort: ["Ned", "Pon", "Uto", "Str", "Štv", "Pia", "Sob", "Ned"],
daysMin: ["Ne", "Po", "Ut", "St", "Št", "Pia", "So", "Ne"],
months: ["Január", "Február", "Marec", "Apríl", "Máj", "Jún", "Júl", "August", "September", "Október", "November", "December"],
monthsShort: ["Jan", "Feb", "Mar", "Apr", "Máj", "Jún", "Júl", "Aug", "Sep", "Okt", "Nov", "Dec"],
today: "Dnes"
}
}(jQuery),
function(e) {
e.fn.datepicker.dates.sl = {
days: ["Nedelja", "Ponedeljek", "Torek", "Sreda", "Četrtek", "Petek", "Sobota", "Nedelja"],
daysShort: ["Ned", "Pon", "Tor", "Sre", "Čet", "Pet", "Sob", "Ned"],
daysMin: ["Ne", "Po", "To", "Sr", "Če", "Pe", "So", "Ne"],
months: ["Januar", "Februar", "Marec", "April", "Maj", "Junij", "Julij", "Avgust", "September", "Oktober", "November", "December"],
monthsShort: ["Jan", "Feb", "Mar", "Apr", "Maj", "Jun", "Jul", "Avg", "Sep", "Okt", "Nov", "Dec"],
today: "Danes"
}
}(jQuery),
function(e) {
e.fn.datepicker.dates.sv = {
days: ["Söndag", "Måndag", "Tisdag", "Onsdag", "Torsdag", "Fredag", "Lördag", "Söndag"],
daysShort: ["Sön", "Mån", "Tis", "Ons", "Tor", "Fre", "Lör", "Sön"],
daysMin: ["Sö", "Må", "Ti", "On", "To", "Fr", "Lö", "Sö"],
months: ["Januari", "Februari", "Mars", "April", "Maj", "Juni", "Juli", "Augusti", "September", "Oktober", "November", "December"],
monthsShort: ["Jan", "Feb", "Mar", "Apr", "Maj", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dec"],
today: "I Dag"
}
}(jQuery),
function(e) {
e.fn.datepicker.dates.sw = {
days: ["Jumapili", "Jumatatu", "Jumanne", "Jumatano", "Alhamisi", "Ijumaa", "Jumamosi", "Jumapili"],
daysShort: ["J2", "J3", "J4", "J5", "Alh", "Ij", "J1", "J2"],
daysMin: ["2", "3", "4", "5", "A", "I", "1", "2"],
months: ["Januari", "Februari", "Machi", "Aprili", "Mei", "Juni", "Julai", "Agosti", "Septemba", "Oktoba", "Novemba", "Desemba"],
monthsShort: ["Jan", "Feb", "Mac", "Apr", "Mei", "Jun", "Jul", "Ago", "Sep", "Okt", "Nov", "Des"],
today: "Leo"
}
}(jQuery),
function(e) {
e.fn.datepicker.dates.th = {
days: ["อาทิตย์", "จันทร์", "อังคาร", "พุธ", "พฤหัส", "ศุกร์", "เสาร์", "อาทิตย์"],
daysShort: ["อา", "จ", "อ", "พ", "พฤ", "ศ", "ส", "อา"],
daysMin: ["อา", "จ", "อ", "พ", "พฤ", "ศ", "ส", "อา"],
months: ["มกราคม", "กุมภาพันธ์", "มีนาคม", "เมษายน", "พฤษภาคม", "มิถุนายน", "กรกฎาคม", "สิงหาคม", "กันยายน", "ตุลาคม", "พฤศจิกายน", "ธันวาคม"],
monthsShort: ["ม.ค.", "ก.พ.", "มี.ค.", "เม.ย.", "พ.ค.", "มิ.ย.", "ก.ค.", "ส.ค.", "ก.ย.", "ต.ค.", "พ.ย.", "ธ.ค."],
today: "วันนี้"
}
}(jQuery),
function(e) {
e.fn.datepicker.dates.tr = {
days: ["Pazar", "Pazartesi", "Salı", "Çarşamba", "Perşembe", "Cuma", "Cumartesi", "Pazar"],
daysShort: ["Pz", "Pzt", "Sal", "Çrş", "Prş", "Cu", "Cts", "Pz"],
daysMin: ["Pz", "Pzt", "Sa", "Çr", "Pr", "Cu", "Ct", "Pz"],
months: ["Ocak", "Şubat", "Mart", "Nisan", "Mayıs", "Haziran", "Temmuz", "Ağustos", "Eylül", "Ekim", "Kasım", "Aralık"],
monthsShort: ["Oca", "Şub", "Mar", "Nis", "May", "Haz", "Tem", "Ağu", "Eyl", "Eki", "Kas", "Ara"],
today: "Bugün"
}
}(jQuery),
function(e) {
e.fn.datepicker.dates.uk = {
days: ["Неділя", "Понеділок", "Вівторок", "Середа", "Четвер", "П'ятниця", "Субота", "Неділя"],
daysShort: ["Нед", "Пнд", "Втр", "Срд", "Чтв", "Птн", "Суб", "Нед"],
daysMin: ["Нд", "Пн", "Вт", "Ср", "Чт", "Пт", "Сб", "Нд"],
months: ["Січень", "Лютий", "Березень", "Квітень", "Травень", "Червень", "Липень", "Серпень", "Вересень", "Жовтень", "Листопад", "Грудень"],
monthsShort: ["Січ", "Лют", "Бер", "Кві", "Тра", "Чер", "Лип", "Сер", "Вер", "Жов", "Лис", "Гру"],
today: "Сьогодні"
}
}(jQuery),
function(e) {
e.fn.datepicker.dates["zh-CN"] = {
days: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"],
daysShort: ["周日", "周一", "周二", "周三", "周四", "周五", "周六", "周日"],
daysMin: ["日", "一", "二", "三", "四", "五", "六", "日"],
months: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
monthsShort: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
today: "今日"
}
}(jQuery),
function(e) {
e.fn.datepicker.dates["zh-TW"] = {
days: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"],
daysShort: ["周日", "周一", "周二", "周三", "周四", "周五", "周六", "周日"],
daysMin: ["日", "一", "二", "三", "四", "五", "六", "日"],
months: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
monthsShort: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"]
}
}(jQuery),
function() {
jQuery(function() {
return $("a[rel=popover]").popover(), $(".tooltip").tooltip(), $("a[rel=tooltip]").tooltip()
})
}.call(this), ! function(e) {
"use strict";
var t = function(t, n) {
this.$element = e(t), this.options = e.extend({}, e.fn.typeahead.defaults, n), this.matcher = this.options.matcher || this.matcher, this.sorter = this.options.sorter || this.sorter, this.highlighter = this.options.highlighter || this.highlighter, this.updater = this.options.updater || this.updater, this.$menu = e(this.options.menu).appendTo("body"), this.source = this.options.source, this.shown = !1, this.listen()
};
t.prototype = {
constructor: t,
select: function() {
var e = this.$menu.find(".active").attr("data-value");
return this.$element.val(this.updater(e)).change(), this.hide()
},
updater: function(e) {
return e
},
show: function() {
var t = e.extend({}, this.$element.offset(), {
height: this.$element[0].offsetHeight
});
return this.$menu.css({
top: t.top + t.height,
left: t.left
}), this.$menu.show(), this.shown = !0, this
},
hide: function() {
return this.$menu.hide(), this.shown = !1, this
},
lookup: function(t) {
var n;
return this.query = this.$element.val(), !this.query || this.query.length < this.options.minLength ? this.shown ? this.hide() : this : (n = e.isFunction(this.source) ? this.source(this.query, e.proxy(this.process, this)) : this.source, n ? this.process(n) : this)
},
process: function(t) {
var n = this;
return t = e.grep(t, function(e) {
return n.matcher(e)
}), t = this.sorter(t), t.length ? this.render(t.slice(0, this.options.items)).show() : this.shown ? this.hide() : this
},
matcher: function(e) {
return ~e.toLowerCase().indexOf(this.query.toLowerCase())
},
sorter: function(e) {
var t = [],
n = [],
r = [],
i;
while (i = e.shift()) i.toLowerCase().indexOf(this.query.toLowerCase()) ? ~i.indexOf(this.query) ? n.push(i) : r.push(i) : t.push(i);
return t.concat(n, r)
},
highlighter: function(e) {
var t = this.query.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&");
return e.replace(new RegExp("(" + t + ")", "ig"), function(e, t) {
return "<strong>" + t + "</strong>"
})
},
render: function(t) {
var n = this;
return t = e(t).map(function(t, r) {
return t = e(n.options.item).attr("data-value", r), t.find("a").html(n.highlighter(r)), t[0]
}), t.first().addClass("active"), this.$menu.html(t), this
},
next: function(t) {
var n = this.$menu.find(".active").removeClass("active"),
r = n.next();
r.length || (r = e(this.$menu.find("li")[0])), r.addClass("active")
},
prev: function(e) {
var t = this.$menu.find(".active").removeClass("active"),
n = t.prev();
n.length || (n = this.$menu.find("li").last()), n.addClass("active")
},
listen: function() {
this.$element.on("blur", e.proxy(this.blur, this)).on("keypress", e.proxy(this.keypress, this)).on("keyup", e.proxy(this.keyup, this)), (e.browser.chrome || e.browser.webkit || e.browser.msie) && this.$element.on("keydown", e.proxy(this.keydown, this)), this.$menu.on("click", e.proxy(this.click, this)).on("mouseenter", "li", e.proxy(this.mouseenter, this))
},
move: function(e) {
if (!this.shown) return;
switch (e.keyCode) {
case 9:
case 13:
case 27:
e.preventDefault();
break;
case 38:
e.preventDefault(), this.prev();
break;
case 40:
e.preventDefault(), this.next()
}
e.stopPropagation()
},
keydown: function(t) {
this.suppressKeyPressRepeat = !~e.inArray(t.keyCode, [40, 38, 9, 13, 27]), this.move(t)
},
keypress: function(e) {
if (this.suppressKeyPressRepeat) return;
this.move(e)
},
keyup: function(e) {
switch (e.keyCode) {
case 40:
case 38:
break;
case 9:
case 13:
if (!this.shown) return;
this.select();
break;
case 27:
if (!this.shown) return;
this.hide();
break;
default:
this.lookup()
}
e.stopPropagation(), e.preventDefault()
},
blur: function(e) {
var t = this;
setTimeout(function() {
t.hide()
}, 150)
},
click: function(e) {
e.stopPropagation(), e.preventDefault(), this.select()
},
mouseenter: function(t) {
this.$menu.find(".active").removeClass("active"), e(t.currentTarget).addClass("active")
}
}, e.fn.typeahead = function(n) {
return this.each(function() {
var r = e(this),
i = r.data("typeahead"),
s = typeof n == "object" && n;
i || r.data("typeahead", i = new t(this, s)), typeof n == "string" && i[n]()
})
}, e.fn.typeahead.defaults = {
source: [],
items: 8,
menu: '<ul class="typeahead dropdown-menu"></ul>',
item: '<li><a href="#"></a></li>',
minLength: 1
}, e.fn.typeahead.Constructor = t, e(function() {
e("body").on("focus.typeahead.data-api", '[data-provide="typeahead"]', function(t) {
var n = e(this);
if (n.data("typeahead")) return;
t.preventDefault(), n.typeahead(n.data())
})
})
}(window.jQuery),
function(e, t) {
function n(e) {
var t = [2, 3, 4, 5, 7, 8, 9],
n = [0, 0, 0, 0, 0, 0, 0],
r;
e = e.toUpperCase();
if (!e) return n;
if (typeof e != "string") throw new Error("Invalid iso8601 period string '" + e + "'");
if (r = /^P((\d+Y)?(\d+M)?(\d+W)?(\d+D)?)?(T(\d+H)?(\d+M)?(\d+S)?)?$/.exec(e)) {
for (var i = 0; i < t.length; i++) {
var s = t[i];
n[i] = r[s] ? +r[s].replace(/[A-Za-z]+/g, "") : 0
}
return n
}
throw new Error("String '" + e + "' is not a valid ISO8601 period.")
}
e.iso8601 || (e.iso8601 = {}), e.iso8601.Period || (e.iso8601.Period = {}), e.iso8601.version = "0.1", e.iso8601.Period.parse = function(e) {
return n(e)
}, e.iso8601.Period.parseToTotalSeconds = function(e) {
var t = [31104e3, 2592e3, 604800, 86400, 3600, 60, 1],
r = n(e),
i = 0;
for (var s = 0; s < r.length; s++) i += r[s] * t[s];
return i
}, e.iso8601.Period.isValid = function(e) {
try {
return n(e), !0
} catch (t) {
return !1
}
}, e.iso8601.Period.parseToString = function(e, t, r) {
var i = ["", "", "", "", "", "", ""],
s = n(e);
t || (t = ["year", "month", "week", "day", "hour", "minute", "second"]), r || (r = ["years", "months", "weeks", "days", "hours", "minutes", "seconds"]);
for (var o = 0; o < s.length; o++) s[o] > 0 && (s[o] == 1 ? i[o] = s[o] + " " + t[o] : i[o] = s[o] + " " + r[o]);
return i.join(" ").trim().replace(/[ ]{2,}/g, " ")
}
}(window.nezasa = window.nezasa || {}), RegExp.escape = function(e) {
return e.replace(/[-\/\\^$*+?.()|[\]{}]/g, "\\$&")
},
function(e) {
"use strict";
e.csv = {
defaults: {
separator: ",",
delimiter: '"',
headers: !0
},
hooks: {
castToScalar: function(e, t) {
var n = /\./;
if (isNaN(e)) return e;
if (n.test(e)) return parseFloat(e);
var r = parseInt(e);
return isNaN(r) ? null : r
}
},
parsers: {
parse: function(e, t) {
function f() {
o = 0, u = "";
if (t.start && t.state.rowNum < t.start) {
s = [], t.state.rowNum++, t.state.colNum = 1;
return
}
if (t.onParseEntry === undefined) i.push(s);
else {
var e = t.onParseEntry(s, t.state);
e !== !1 && i.push(e)
}
s = [], t.end && t.state.rowNum >= t.end && (a = !0), t.state.rowNum++, t.state.colNum = 1
}
function l() {
if (t.onParseValue === undefined) s.push(u);
else {
var e = t.onParseValue(u, t.state);
e !== !1 && s.push(e)
}
u = "", o = 0, t.state.colNum++
}
var n = t.separator,
r = t.delimiter;
t.state.rowNum || (t.state.rowNum = 1), t.state.colNum || (t.state.colNum = 1);
var i = [],
s = [],
o = 0,
u = "",
a = !1,
c = RegExp.escape(n),
h = RegExp.escape(r),
p = /(D|S|\n|\r|[^DS\r\n]+)/,
d = p.source;
return d = d.replace(/S/g, c), d = d.replace(/D/g, h), p = RegExp(d, "gm"), e.replace(p, function(e) {
if (a) return;
switch (o) {
case 0:
if (e === n) {
u += "", l();
break
}
if (e === r) {
o = 1;
break
}
if (e === "\n") {
l(), f();
break
}
if (/^\r$/.test(e)) break;
u += e, o = 3;
break;
case 1:
if (e === r) {
o = 2;
break
}
u += e, o = 1;
break;
case 2:
if (e === r) {
u += e, o = 1;
break
}
if (e === n) {
l();
break
}
if (e === "\n") {
l(), f();
break
}
if (/^\r$/.test(e)) break;
throw new Error("CSVDataError: Illegal State [Row:" + t.state.rowNum + "][Col:" + t.state.colNum + "]");
case 3:
if (e === n) {
l();
break
}
if (e === "\n") {
l(), f();
break
}
if (/^\r$/.test(e)) break;
if (e === r) throw new Error("CSVDataError: Illegal Quote [Row:" + t.state.rowNum + "][Col:" + t.state.colNum + "]");
throw new Error("CSVDataError: Illegal Data [Row:" + t.state.rowNum + "][Col:" + t.state.colNum + "]");
default:
throw new Error("CSVDataError: Unknown State [Row:" + t.state.rowNum + "][Col:" + t.state.colNum + "]")
}
}), s.length !== 0 && (l(), f()), i
},
splitLines: function(e, t) {
function a() {
s = 0;
if (t.start && t.state.rowNum < t.start) {
o = "", t.state.rowNum++;
return
}
if (t.onParseEntry === undefined) i.push(o);
else {
var e = t.onParseEntry(o, t.state);
e !== !1 && i.push(e)
}
o = "", t.end && t.state.rowNum >= t.end && (u = !0), t.state.rowNum++
}
var n = t.separator,
r = t.delimiter;
t.state.rowNum || (t.state.rowNum = 1);
var i = [],
s = 0,
o = "",
u = !1,
f = RegExp.escape(n),
l = RegExp.escape(r),
c = /(D|S|\n|\r|[^DS\r\n]+)/,
h = c.source;
return h = h.replace(/S/g, f), h = h.replace(/D/g, l), c = RegExp(h, "gm"), e.replace(c, function(e) {
if (u) return;
switch (s) {
case 0:
if (e === n) {
o += e, s = 0;
break
}
if (e === r) {
o += e, s = 1;
break
}
if (e === "\n") {
a();
break
}
if (/^\r$/.test(e)) break;
o += e, s = 3;
break;
case 1:
if (e === r) {
o += e, s = 2;
break
}
o += e, s = 1;
break;
case 2:
var i = o.substr(o.length - 1);
if (e === r && i === r) {
o += e, s = 1;
break
}
if (e === n) {
o += e, s = 0;
break
}
if (e === "\n") {
a();
break
}
if (e === "\r") break;
throw new Error("CSVDataError: Illegal state [Row:" + t.state.rowNum + "]");
case 3:
if (e === n) {
o += e, s = 0;
break
}
if (e === "\n") {
a();
break
}
if (e === "\r") break;
if (e === r) throw new Error("CSVDataError: Illegal quote [Row:" + t.state.rowNum + "]");
throw new Error("CSVDataError: Illegal state [Row:" + t.state.rowNum + "]");
default:
throw new Error("CSVDataError: Unknown state [Row:" + t.state.rowNum + "]")
}
}), o !== "" && a(), i
},
parseEntry: function(e, t) {
function u() {
if (t.onParseValue === undefined) i.push(o);
else {
var e = t.onParseValue(o, t.state);
e !== !1 && i.push(e)
}
o = "", s = 0, t.state.colNum++
}
var n = t.separator,
r = t.delimiter;
t.state.rowNum || (t.state.rowNum = 1), t.state.colNum || (t.state.colNum = 1);
var i = [],
s = 0,
o = "";
if (!t.match) {
var a = RegExp.escape(n),
f = RegExp.escape(r),
l = /(D|S|\n|\r|[^DS\r\n]+)/,
c = l.source;
c = c.replace(/S/g, a), c = c.replace(/D/g, f), t.match = RegExp(c, "gm")
}
return e.replace(t.match, function(e) {
switch (s) {
case 0:
if (e === n) {
o += "", u();
break
}
if (e === r) {
s = 1;
break
}
if (e === "\n" || e === "\r") break;
o += e, s = 3;
break;
case 1:
if (e === r) {
s = 2;
break
}
o += e, s = 1;
break;
case 2:
if (e === r) {
o += e, s = 1;
break
}
if (e === n) {
u();
break
}
if (e === "\n" || e === "\r") break;
throw new Error("CSVDataError: Illegal State [Row:" + t.state.rowNum + "][Col:" + t.state.colNum + "]");
case 3:
if (e === n) {
u();
break
}
if (e === "\n" || e === "\r") break;
if (e === r) throw new Error("CSVDataError: Illegal Quote [Row:" + t.state.rowNum + "][Col:" + t.state.colNum + "]");
throw new Error("CSVDataError: Illegal Data [Row:" + t.state.rowNum + "][Col:" + t.state.colNum + "]");
default:
throw new Error("CSVDataError: Unknown State [Row:" + t.state.rowNum + "][Col:" + t.state.colNum + "]")
}
}), u(), i
}
},
toArray: function(t, n, r) {
var n = n !== undefined ? n : {},
i = {};
i.callback = r !== undefined && typeof r == "function" ? r : !1, i.separator = "separator" in n ? n.separator : e.csv.defaults.separator, i.delimiter = "delimiter" in n ? n.delimiter : e.csv.defaults.delimiter;
var s = n.state !== undefined ? n.state : {},
n = {
delimiter: i.delimiter,
separator: i.separator,
onParseEntry: n.onParseEntry,
onParseValue: n.onParseValue,
state: s
},
o = e.csv.parsers.parseEntry(t, n);
if (!i.callback) return o;
i.callback("", o)
},
toArrays: function(t, n, r) {
var n = n !== undefined ? n : {},
i = {};
i.callback = r !== undefined && typeof r == "function" ? r : !1, i.separator = "separator" in n ? n.separator : e.csv.defaults.separator, i.delimiter = "delimiter" in n ? n.delimiter : e.csv.defaults.delimiter;
var s = [],
n = {
delimiter: i.delimiter,
separator: i.separator,
onParseEntry: n.onParseEntry,
onParseValue: n.onParseValue,
start: n.start,
end: n.end,
state: {
rowNum: 1,
colNum: 1
}
};
s = e.csv.parsers.parse(t, n);
if (!i.callback) return s;
i.callback("", s)
},
toObjects: function(t, n, r) {
var n = n !== undefined ? n : {},
i = {};
i.callback = r !== undefined && typeof r == "function" ? r : !1, i.separator = "separator" in n ? n.separator : e.csv.defaults.separator, i.delimiter = "delimiter" in n ? n.delimiter : e.csv.defaults.delimiter, i.headers = "headers" in n ? n.headers : e.csv.defaults.headers, n.start = "start" in n ? n.start : 1, i.headers && n.start++, n.end && i.headers && n.end++;
var s = [],
o = [],
n = {
delimiter: i.delimiter,
separator: i.separator,
onParseEntry: n.onParseEntry,
onParseValue: n.onParseValue,
start: n.start,
end: n.end,
state: {
rowNum: 1,
colNum: 1
},
match: !1
},
u = {
delimiter: i.delimiter,
separator: i.separator,
start: 1,
end: 1,
state: {
rowNum: 1,
colNum: 1
}
},
a = e.csv.parsers.splitLines(t, u),
f = e.csv.toArray(a[0], n),
s = e.csv.parsers.splitLines(t, n);
n.state.colNum = 1, f ? n.state.rowNum = 2 : n.state.rowNum = 1;
for (var l = 0, c = s.length; l < c; l++) {
var h = e.csv.toArray(s[l], n),
p = {};
for (var d in f) p[f[d]] = h[d];
o.push(p), n.state.rowNum++
}
if (!i.callback) return o;
i.callback("", o)
},
fromArrays: function(t, n, r) {
var n = n !== undefined ? n : {},
s = {};
s.callback = r !== undefined && typeof r == "function" ? r : !1, s.separator = "separator" in n ? n.separator : e.csv.defaults.separator, s.delimiter = "delimiter" in n ? n.delimiter : e.csv.defaults.delimiter, s.escaper = "escaper" in n ? n.escaper : e.csv.defaults.escaper, s.experimental = "experimental" in n ? n.experimental : !1;
if (!s.experimental) throw new Error("not implemented");
var o = [];
for (i in t) o.push(t[i]);
if (!s.callback) return o;
s.callback("", o)
},
fromObjects2CSV: function(t, n, r) {
var n = n !== undefined ? n : {},
s = {};
s.callback = r !== undefined && typeof r == "function" ? r : !1, s.separator = "separator" in n ? n.separator : e.csv.defaults.separator, s.delimiter = "delimiter" in n ? n.delimiter : e.csv.defaults.delimiter, s.experimental = "experimental" in n ? n.experimental : !1;
if (!s.experimental) throw new Error("not implemented");
var o = [];
for (i in t) o.push(arrays[i]);
if (!s.callback) return o;
s.callback("", o)
}
}, e.csvEntry2Array = e.csv.toArray, e.csv2Array = e.csv.toArrays, e.csv2Dictionary = e.csv.toObjects
}(jQuery),
function(e, t) {
e.ajaxPrefilter(function(e, t, n) {
if (e.iframe) return "iframe"
}), e.ajaxTransport("iframe", function(t, n, r) {
function h() {
e(f).each(function() {
this.remove()
}), e(l).each(function() {
this.disabled = !1
}), i.attr("action", o || "").attr("target", u || "").attr("enctype", a || ""), s.attr("src", "javascript:false;").remove()
}
var i = null,
s = null,
o = null,
u = null,
a = null,
f = [],
l = [],
c = e(t.files).filter(":file:enabled");
t.dataTypes.shift();
if (c.length) return c.each(function() {
i !== null && this.form !== i && jQuery.error("All file fields must belong to the same form"), i = this.form
}), i = e(i), o = i.attr("action"), u = i.attr("target"), a = i.attr("enctype"), i.find(":input:not(:submit)").each(function() {
!this.disabled && (this.type != "file" || c.index(this) < 0) && (this.disabled = !0, l.push(this))
}), typeof t.data == "string" && t.data.length > 0 && jQuery.error("data must not be serialized"), e.each(t.data || {}, function(t, n) {
e.isPlainObject(n) && (t = n.name, n = n.value), f.push(e("<input type='hidden'>").attr("name", t).attr("value", n).appendTo(i))
}), f.push(e("<input type='hidden' name='X-Requested-With'>").attr("value", "IFrame").appendTo(i)), accepts = t.dataTypes[0] && t.accepts[t.dataTypes[0]] ? t.accepts[t.dataTypes[0]] + (t.dataTypes[0] !== "*" ? ", */*; q=0.01" : "") : t.accepts["*"], f.push(e("<input type='hidden' name='X-Http-Accept'>").attr("value", accepts).appendTo(i)), {
send: function(n, r) {
s = e("<iframe src='javascript:false;' name='iframe-" + e.now() + "' style='display:none'></iframe>"), s.bind("load", function() {
s.unbind("load").bind("load", function() {
var e = this.contentWindow ? this.contentWindow.document : this.contentDocument ? this.contentDocument : this.document,
t = e.documentElement ? e.documentElement : e.body,
n = t.getElementsByTagName("textarea")[0],
i = n ? n.getAttribute("data-type") : null,
s = n ? parseInt(n.getAttribute("response-code")) : 200,
o = "OK",
u = {
text: i ? n.value : t ? t.innerHTML : null
},
a = "Content-Type: " + (i || "text/html");
r(s, o, u, a), setTimeout(h, 50)
}), i.attr("action", t.url).attr("target", s.attr("name")).attr("enctype", "multipart/form-data").get(0).submit()
}), s.insertAfter(i)
},
abort: function() {
s !== null && (s.unbind("load").attr("src", "javascript:false;"), h())
}
}
})
}(jQuery),
function($) {
var escapeable = /["\\\x00-\x1f\x7f-\x9f]/g,
meta = {
"\b": "\\b",
" ": "\\t",
"\n": "\\n",
"\f": "\\f",
"\r": "\\r",
'"': '\\"',
"\\": "\\\\"
};
$.toJSON = typeof JSON == "object" && JSON.stringify ? JSON.stringify : function(e) {
if (e === null) return "null";
var t = typeof e;
if (t === "undefined") return undefined;
if (t === "number" || t === "boolean") return "" + e;
if (t === "string") return $.quoteString(e);
if (t === "object") {
if (typeof e.toJSON == "function") return $.toJSON(e.toJSON());
if (e.constructor === Date) {
var n = e.getUTCMonth() + 1,
r = e.getUTCDate(),
i = e.getUTCFullYear(),
s = e.getUTCHours(),
o = e.getUTCMinutes(),
u = e.getUTCSeconds(),
a = e.getUTCMilliseconds();
return n < 10 && (n = "0" + n), r < 10 && (r = "0" + r), s < 10 && (s = "0" + s), o < 10 && (o = "0" + o), u < 10 && (u = "0" + u), a < 100 && (a = "0" + a), a < 10 && (a = "0" + a), '"' + i + "-" + n + "-" + r + "T" + s + ":" + o + ":" + u + "." + a + 'Z"'
}
if (e.constructor === Array) {
var f = [];
for (var l = 0; l < e.length; l++) f.push($.toJSON(e[l]) || "null");
return "[" + f.join(",") + "]"
}
var c, h, p = [];
for (var d in e) {
t = typeof d;
if (t === "number") c = '"' + d + '"';
else {
if (t !== "string") continue;
c = $.quoteString(d)
}
t = typeof e[d];
if (t === "function" || t === "undefined") continue;
h = $.toJSON(e[d]), p.push(c + ":" + h)
}
return "{" + p.join(",") + "}"
}
}, $.evalJSON = typeof JSON == "object" && JSON.parse ? JSON.parse : function(src) {
return eval("(" + src + ")")
}, $.secureEvalJSON = typeof JSON == "object" && JSON.parse ? JSON.parse : function(src) {
var filtered = src.replace(/\\["\\\/bfnrtu]/g, "@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, "]").replace(/(?:^|:|,)(?:\s*\[)+/g, "");
if (/^[\],:{}\s]*$/.test(filtered)) return eval("(" + src + ")");
throw new SyntaxError("Error parsing JSON, source is not valid.")
}, $.quoteString = function(e) {
return e.match(escapeable) ? '"' + e.replace(escapeable, function(e) {
var t = meta[e];
return typeof t == "string" ? t : (t = e.charCodeAt(), "\\u00" + Math.floor(t / 16).toString(16) + (t % 16).toString(16))
}) + '"' : '"' + e + '"'
}
}(jQuery),
function(e, t) {
e.ajaxPrefilter(function(e, t, n) {
if (e.iframe) return "iframe"
}), e.ajaxTransport("iframe", function(t, n, r) {
function h() {
e(f).each(function() {
this.remove()
}), e(l).each(function() {
this.disabled = !1
}), i.attr("action", o || "").attr("target", u || "").attr("enctype", a || ""), s.attr("src", "javascript:false;").remove()
}
var i = null,
s = null,
o = null,
u = null,
a = null,
f = [],
l = [],
c = e(t.files).filter(":file:enabled");
t.dataTypes.shift();
if (c.length) return c.each(function() {
i !== null && this.form !== i && jQuery.error("All file fields must belong to the same form"), i = this.form
}), i = e(i), o = i.attr("action"), u = i.attr("target"), a = i.attr("enctype"), i.find(":input:not(:submit)").each(function() {
!this.disabled && (this.type != "file" || c.index(this) < 0) && (this.disabled = !0, l.push(this))
}), typeof t.data == "string" && t.data.length > 0 && jQuery.error("data must not be serialized"), e.each(t.data || {}, function(t, n) {
e.isPlainObject(n) && (t = n.name, n = n.value), f.push(e("<input type='hidden'>").attr("name", t).attr("value", n).appendTo(i))
}), f.push(e("<input type='hidden' name='X-Requested-With'>").attr("value", "IFrame").appendTo(i)), accepts = t.dataTypes[0] && t.accepts[t.dataTypes[0]] ? t.accepts[t.dataTypes[0]] + (t.dataTypes[0] !== "*" ? ", */*; q=0.01" : "") : t.accepts["*"], f.push(e("<input type='hidden' name='X-Http-Accept'>").attr("value", accepts).appendTo(i)), {
send: function(n, r) {
s = e("<iframe src='javascript:false;' name='iframe-" + e.now() + "' style='display:none'></iframe>"), s.bind("load", function() {
s.unbind("load").bind("load", function() {
var e = this.contentWindow ? this.contentWindow.document : this.contentDocument ? this.contentDocument : this.document,
t = e.documentElement ? e.documentElement : e.body,
n = t.getElementsByTagName("textarea")[0],
i = n ? n.getAttribute("data-type") : null,
s = n ? parseInt(n.getAttribute("response-code")) : 200,
o = "OK",
u = {
text: i ? n.value : t ? t.innerHTML : null
},
a = "Content-Type: " + (i || "text/html");
r(s, o, u, a), setTimeout(h, 50)
}), i.attr("action", t.url).attr("target", s.attr("name")).attr("enctype", "multipart/form-data").get(0).submit()
}), s.insertAfter(i)
},
abort: function() {
s !== null && (s.unbind("load").attr("src", "javascript:false;"), h())
}
}
})
}(jQuery),
function(t) {
var n;
t.remotipart = n = {
setup: function(e) {
e.one("ajax:beforeSend.remotipart", function(r, i, s) {
return delete s.beforeSend, s.iframe = !0, s.files = t(t.rails.fileInputSelector, e), s.data = e.serializeArray(), s.processData = !1, s.dataType === undefined && (s.dataType = "script *"), s.data.push({
name: "remotipart_submitted",
value: !0
}), t.rails.fire(e, "ajax:remotipartSubmit", [i, s]) && t.rails.ajax(s), n.teardown(e), !1
}).data("remotipartSubmitted", !0)
},
teardown: function(e) {
e.unbind("ajax:beforeSend.remotipart").removeData("remotipartSubmitted")
}
}, t("form").live("ajax:aborted:file", function() {
var r = t(this);
return n.setup(r), !t.support.submitBubbles && t().jquery < "1.7" && t.rails.callFormSubmitBindings(r) === !1 ? t.rails.stopEverything(e) : (t.rails.handleRemote(r), !1)
})
}(jQuery),
function() {
var e;
e = jQuery, e.fn.savefile = function(t) {
var n, r, i, s;
return s = e.extend({
filename: "file",
extension: "txt"
}, t), i = function(e, t) {
var n;
n = "http://savefile.joshmcarthur.com/" + encodeURIComponent(e);
if (t) return n += encodeURIComponent(t)
}, n = "" + s.filename + "." + s.extension, r = function(t) {
return e("<form></form>", {
action: i(n()),
method: "POST"
}).append(e("<input></input>", {
type: "hidden",
name: "content",
value: t
}))
}, this.each(function() {
var e;
return e = this.val() !== "" ? this.val() : this.text(), s.content != null && (e = s.content), r(e).submit()
})
}
}.call(this),
function(e, t) {
var n = 5;
e.widget("ui.slider", e.ui.mouse, {
widgetEventPrefix: "slide",
options: {
animate: !1,
distance: 0,
max: 100,
min: 0,
orientation: "horizontal",
range: !1,
step: 1,
value: 0,
values: null
},
_create: function() {
var t = this,
r = this.options,
i = this.element.find(".ui-slider-handle").addClass("ui-state-default ui-corner-all"),
s = "<a class='ui-slider-handle ui-state-default ui-corner-all' href='#'></a>",
o = r.values && r.values.length || 1,
u = [];
this._keySliding = !1, this._mouseSliding = !1, this._animateOff = !0, this._handleIndex = null, this._detectOrientation(), this._mouseInit(), this.element.addClass("ui-slider ui-slider-" + this.orientation + " ui-widget" + " ui-widget-content" + " ui-corner-all" + (r.disabled ? " ui-slider-disabled ui-disabled" : "")), this.range = e([]), r.range && (r.range === !0 && (r.values || (r.values = [this._valueMin(), this._valueMin()]), r.values.length && r.values.length !== 2 && (r.values = [r.values[0], r.values[0]])), this.range = e("<div></div>").appendTo(this.element).addClass("ui-slider-range ui-widget-header" + (r.range === "min" || r.range === "max" ? " ui-slider-range-" + r.range : "")));
for (var a = i.length; a < o; a += 1) u.push(s);
this.handles = i.add(e(u.join("")).appendTo(t.element)), this.handle = this.handles.eq(0), this.handles.add(this.range).filter("a").click(function(e) {
e.preventDefault()
}).hover(function() {
r.disabled || e(this).addClass("ui-state-hover")
}, function() {
e(this).removeClass("ui-state-hover")
}).focus(function() {
r.disabled ? e(this).blur() : (e(".ui-slider .ui-state-focus").removeClass("ui-state-focus"), e(this).addClass("ui-state-focus"))
}).blur(function() {
e(this).removeClass("ui-state-focus")
}), this.handles.each(function(t) {
e(this).data("index.ui-slider-handle", t)
}), this.handles.keydown(function(r) {
var i = e(this).data("index.ui-slider-handle"),
s, o, u, a;
if (t.options.disabled) return;
switch (r.keyCode) {
case e.ui.keyCode.HOME:
case e.ui.keyCode.END:
case e.ui.keyCode.PAGE_UP:
case e.ui.keyCode.PAGE_DOWN:
case e.ui.keyCode.UP:
case e.ui.keyCode.RIGHT:
case e.ui.keyCode.DOWN:
case e.ui.keyCode.LEFT:
r.preventDefault();
if (!t._keySliding) {
t._keySliding = !0, e(this).addClass("ui-state-active"), s = t._start(r, i);
if (s === !1) return
}
}
a = t.options.step, t.options.values && t.options.values.length ? o = u = t.values(i) : o = u = t.value();
switch (r.keyCode) {
case e.ui.keyCode.HOME:
u = t._valueMin();
break;
case e.ui.keyCode.END:
u = t._valueMax();
break;
case e.ui.keyCode.PAGE_UP:
u = t._trimAlignValue(o + (t._valueMax() - t._valueMin()) / n);
break;
case e.ui.keyCode.PAGE_DOWN:
u = t._trimAlignValue(o - (t._valueMax() - t._valueMin()) / n);
break;
case e.ui.keyCode.UP:
case e.ui.keyCode.RIGHT:
if (o === t._valueMax()) return;
u = t._trimAlignValue(o + a);
break;
case e.ui.keyCode.DOWN:
case e.ui.keyCode.LEFT:
if (o === t._valueMin()) return;
u = t._trimAlignValue(o - a)
}
t._slide(r, i, u)
}).keyup(function(n) {
var r = e(this).data("index.ui-slider-handle");
t._keySliding && (t._keySliding = !1, t._stop(n, r), t._change(n, r), e(this).removeClass("ui-state-active"))
}), this._refreshValue(), this._animateOff = !1
},
destroy: function() {
return this.handles.remove(), this.range.remove(), this.element.removeClass("ui-slider ui-slider-horizontal ui-slider-vertical ui-slider-disabled ui-widget ui-widget-content ui-corner-all").removeData("slider").unbind(".slider"), this._mouseDestroy(), this
},
_mouseCapture: function(t) {
var n = this.options,
r, i, s, o, u, a, f, l, c;
return n.disabled ? !1 : (this.elementSize = {
width: this.element.outerWidth(),
height: this.element.outerHeight()
}, this.elementOffset = this.element.offset(), r = {
x: t.pageX,
y: t.pageY
}, i = this._normValueFromMouse(r), s = this._valueMax() - this._valueMin() + 1, u = this, this.handles.each(function(t) {
var n = Math.abs(i - u.values(t));
s > n && (s = n, o = e(this), a = t)
}), n.range === !0 && this.values(1) === n.min && (a += 1, o = e(this.handles[a])), f = this._start(t, a), f === !1 ? !1 : (this._mouseSliding = !0, u._handleIndex = a, o.addClass("ui-state-active").focus(), l = o.offset(), c = !e(t.target).parents().andSelf().is(".ui-slider-handle"), this._clickOffset = c ? {
left: 0,
top: 0
} : {
left: t.pageX - l.left - o.width() / 2,
top: t.pageY - l.top - o.height() / 2 - (parseInt(o.css("borderTopWidth"), 10) || 0) - (parseInt(o.css("borderBottomWidth"), 10) || 0) + (parseInt(o.css("marginTop"), 10) || 0)
}, this.handles.hasClass("ui-state-hover") || this._slide(t, a, i), this._animateOff = !0, !0))
},
_mouseStart: function(e) {
return !0
},
_mouseDrag: function(e) {
var t = {
x: e.pageX,
y: e.pageY
},
n = this._normValueFromMouse(t);
return this._slide(e, this._handleIndex, n), !1
},
_mouseStop: function(e) {
return this.handles.removeClass("ui-state-active"), this._mouseSliding = !1, this._stop(e, this._handleIndex), this._change(e, this._handleIndex), this._handleIndex = null, this._clickOffset = null, this._animateOff = !1, !1
},
_detectOrientation: function() {
this.orientation = this.options.orientation === "vertical" ? "vertical" : "horizontal"
},
_normValueFromMouse: function(e) {
var t, n, r, i, s;
return this.orientation === "horizontal" ? (t = this.elementSize.width, n = e.x - this.elementOffset.left - (this._clickOffset ? this._clickOffset.left : 0)) : (t = this.elementSize.height, n = e.y - this.elementOffset.top - (this._clickOffset ? this._clickOffset.top : 0)), r = n / t, r > 1 && (r = 1), r < 0 && (r = 0), this.orientation === "vertical" && (r = 1 - r), i = this._valueMax() - this._valueMin(), s = this._valueMin() + r * i, this._trimAlignValue(s)
},
_start: function(e, t) {
var n = {
handle: this.handles[t],
value: this.value()
};
return this.options.values && this.options.values.length && (n.value = this.values(t), n.values = this.values()), this._trigger("start", e, n)
},
_slide: function(e, t, n) {
var r, i, s;
this.options.values && this.options.values.length ? (r = this.values(t ? 0 : 1), this.options.values.length === 2 && this.options.range === !0 && (t === 0 && n > r || t === 1 && n < r) && (n = r), n !== this.values(t) && (i = this.values(), i[t] = n, s = this._trigger("slide", e, {
handle: this.handles[t],
value: n,
values: i
}), r = this.values(t ? 0 : 1), s !== !1 && this.values(t, n, !0))) : n !== this.value() && (s = this._trigger("slide", e, {
handle: this.handles[t],
value: n
}), s !== !1 && this.value(n))
},
_stop: function(e, t) {
var n = {
handle: this.handles[t],
value: this.value()
};
this.options.values && this.options.values.length && (n.value = this.values(t), n.values = this.values()), this._trigger("stop", e, n)
},
_change: function(e, t) {
if (!this._keySliding && !this._mouseSliding) {
var n = {
handle: this.handles[t],
value: this.value()
};
this.options.values && this.options.values.length && (n.value = this.values(t), n.values = this.values()), this._trigger("change", e, n)
}
},
value: function(e) {
if (arguments.length) {
this.options.value = this._trimAlignValue(e), this._refreshValue(), this._change(null, 0);
return
}
return this._value()
},
values: function(t, n) {
var r, i, s;
if (arguments.length > 1) {
this.options.values[t] = this._trimAlignValue(n), this._refreshValue(), this._change(null, t);
return
}
if (!arguments.length) return this._values();
if (!e.isArray(arguments[0])) return this.options.values && this.options.values.length ? this._values(t) : this.value();
r = this.options.values, i = arguments[0];
for (s = 0; s < r.length; s += 1) r[s] = this._trimAlignValue(i[s]), this._change(null, s);
this._refreshValue()
},
_setOption: function(t, n) {
var r, i = 0;
e.isArray(this.options.values) && (i = this.options.values.length), e.Widget.prototype._setOption.apply(this, arguments);
switch (t) {
case "disabled":
n ? (this.handles.filter(".ui-state-focus").blur(), this.handles.removeClass("ui-state-hover"), this.handles.propAttr("disabled", !0), this.element.addClass("ui-disabled")) : (this.handles.propAttr("disabled", !1), this.element.removeClass("ui-disabled"));
break;
case "orientation":
this._detectOrientation(), this.element.removeClass("ui-slider-horizontal ui-slider-vertical").addClass("ui-slider-" + this.orientation), this._refreshValue();
break;
case "value":
this._animateOff = !0, this._refreshValue(), this._change(null, 0), this._animateOff = !1;
break;
case "values":
this._animateOff = !0, this._refreshValue();
for (r = 0; r < i; r += 1) this._change(null, r);
this._animateOff = !1
}
},
_value: function() {
var e = this.options.value;
return e = this._trimAlignValue(e), e
},
_values: function(e) {
var t, n, r;
if (arguments.length) return t = this.options.values[e], t = this._trimAlignValue(t), t;
n = this.options.values.slice();
for (r = 0; r < n.length; r += 1) n[r] = this._trimAlignValue(n[r]);
return n
},
_trimAlignValue: function(e) {
if (e <= this._valueMin()) return this._valueMin();
if (e >= this._valueMax()) return this._valueMax();
var t = this.options.step > 0 ? this.options.step : 1,
n = (e - this._valueMin()) % t,
r = e - n;
return Math.abs(n) * 2 >= t && (r += n > 0 ? t : -t), parseFloat(r.toFixed(5))
},
_valueMin: function() {
return this.options.min
},
_valueMax: function() {
return this.options.max
},
_refreshValue: function() {
var t = this.options.range,
n = this.options,
r = this,
i = this._animateOff ? !1 : n.animate,
s, o = {},
u, a, f, l;
this.options.values && this.options.values.length ? this.handles.each(function(t, a) {
s = (r.values(t) - r._valueMin()) / (r._valueMax() - r._valueMin()) * 100, o[r.orientation === "horizontal" ? "left" : "bottom"] = s + "%", e(this).stop(1, 1)[i ? "animate" : "css"](o, n.animate), r.options.range === !0 && (r.orientation === "horizontal" ? (t === 0 && r.range.stop(1, 1)[i ? "animate" : "css"]({
left: s + "%"
}, n.animate), t === 1 && r.range[i ? "animate" : "css"]({
width: s - u + "%"
}, {
queue: !1,
duration: n.animate
})) : (t === 0 && r.range.stop(1, 1)[i ? "animate" : "css"]({
bottom: s + "%"
}, n.animate), t === 1 && r.range[i ? "animate" : "css"]({
height: s - u + "%"
}, {
queue: !1,
duration: n.animate
}))), u = s
}) : (a = this.value(), f = this._valueMin(), l = this._valueMax(), s = l !== f ? (a - f) / (l - f) * 100 : 0, o[r.orientation === "horizontal" ? "left" : "bottom"] = s + "%", this.handle.stop(1, 1)[i ? "animate" : "css"](o, n.animate), t === "min" && this.orientation === "horizontal" && this.range.stop(1, 1)[i ? "animate" : "css"]({
width: s + "%"
}, n.animate), t === "max" && this.orientation === "horizontal" && this.range[i ? "animate" : "css"]({
width: 100 - s + "%"
}, {
queue: !1,
duration: n.animate
}), t === "min" && this.orientation === "vertical" && this.range.stop(1, 1)[i ? "animate" : "css"]({
height: s + "%"
}, n.animate), t === "max" && this.orientation === "vertical" && this.range[i ? "animate" : "css"]({
height: 100 - s + "%"
}, {
queue: !1,
duration: n.animate
}))
}
}), e.extend(e.ui.slider, {
version: "1.8.22"
})
}(jQuery);
var JSON;
JSON || (JSON = {}),
function() {
"use strict";
function f(e) {
return e < 10 ? "0" + e : e
}
function quote(e) {
return escapable.lastIndex = 0, escapable.test(e) ? '"' + e.replace(escapable, function(e) {
var t = meta[e];
return typeof t == "string" ? t : "\\u" + ("0000" + e.charCodeAt(0).toString(16)).slice(-4)
}) + '"' : '"' + e + '"'
}
function str(e, t) {
var n, r, i, s, o = gap,
u, a = t[e];
a && typeof a == "object" && typeof a.toJSON == "function" && (a = a.toJSON(e)), typeof rep == "function" && (a = rep.call(t, e, a));
switch (typeof a) {
case "string":
return quote(a);
case "number":
return isFinite(a) ? String(a) : "null";
case "boolean":
case "null":
return String(a);
case "object":
if (!a) return "null";
gap += indent, u = [];
if (Object.prototype.toString.apply(a) === "[object Array]") {
s = a.length;
for (n = 0; n < s; n += 1) u[n] = str(n, a) || "null";
return i = u.length === 0 ? "[]" : gap ? "[\n" + gap + u.join(",\n" + gap) + "\n" + o + "]" : "[" + u.join(",") + "]", gap = o, i
}
if (rep && typeof rep == "object") {
s = rep.length;
for (n = 0; n < s; n += 1) typeof rep[n] == "string" && (r = rep[n], i = str(r, a), i && u.push(quote(r) + (gap ? ": " : ":") + i))
} else
for (r in a) Object.prototype.hasOwnProperty.call(a, r) && (i = str(r, a), i && u.push(quote(r) + (gap ? ": " : ":") + i));
return i = u.length === 0 ? "{}" : gap ? "{\n" + gap + u.join(",\n" + gap) + "\n" + o + "}" : "{" + u.join(",") + "}", gap = o, i
}
}
typeof Date.prototype.toJSON != "function" && (Date.prototype.toJSON = function(e) {
return isFinite(this.valueOf()) ? this.getUTCFullYear() + "-" + f(this.getUTCMonth() + 1) + "-" + f(this.getUTCDate()) + "T" + f(this.getUTCHours()) + ":" + f(this.getUTCMinutes()) + ":" + f(this.getUTCSeconds()) + "Z" : null
}, String.prototype.toJSON = Number.prototype.toJSON = Boolean.prototype.toJSON = function(e) {
return this.valueOf()
});
var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
gap, indent, meta = {
"\b": "\\b",
" ": "\\t",
"\n": "\\n",
"\f": "\\f",
"\r": "\\r",
'"': '\\"',
"\\": "\\\\"
},
rep;
typeof JSON.stringify != "function" && (JSON.stringify = function(e, t, n) {
var r;
gap = "", indent = "";
if (typeof n == "number")
for (r = 0; r < n; r += 1) indent += " ";
else typeof n == "string" && (indent = n);
rep = t;
if (!t || typeof t == "function" || typeof t == "object" && typeof t.length == "number") return str("", {
"": e
});
throw new Error("JSON.stringify")
}), typeof JSON.parse != "function" && (JSON.parse = function(text, reviver) {
function walk(e, t) {
var n, r, i = e[t];
if (i && typeof i == "object")
for (n in i) Object.prototype.hasOwnProperty.call(i, n) && (r = walk(i, n), r !== undefined ? i[n] = r : delete i[n]);
return reviver.call(e, t, i)
}
var j;
text = String(text), cx.lastIndex = 0, cx.test(text) && (text = text.replace(cx, function(e) {
return "\\u" + ("0000" + e.charCodeAt(0).toString(16)).slice(-4)
}));
if (/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, "@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, "]").replace(/(?:^|:|,)(?:\s*\[)+/g, ""))) return j = eval("(" + text + ")"), typeof reviver == "function" ? walk({
"": j
}, "") : j;
throw new SyntaxError("JSON.parse")
})
}();
var hexcase = 0,
b64pad = "",
chrsz = 8;
(function() {}).call(this), $(function() {
$(".required").live("change", function() {
validateAlignmentForm()
})
}), $(function() {
$("#ageRange").change(function() {
updateItemEducationTab("ageRange", "ageRangeOther")
})
}), $(function() {
$("#ageRangeOther").change(function() {
updateItemEducationTab("ageRange", "ageRangeOther")
})
}), $(function() {
$("#alignmentType").change(function(e) {})
}), $(function() {
var e = "createdBy";
$("#" + e).change(function(t) {
var n = $(t.target).val();
$("#multiItemSelector input[type=checkbox]:checked").each(function(t, r) {
items[r.id][e] = n
}), updateTextArea()
})
}), $(function() {
var e = "tagDescription";
$("#" + e).change(function(t) {
var n = $(t.target).val();
$("#multiItemSelector input[type=checkbox]:checked").each(function(t, r) {
items[r.id][e] = n
}), updateTextArea()
})
}), $(function() {
$("#dotNotation").change(function(e) {
if (e.target.value != previousDotValue) {
previousDotValue = $("#dotNotation").val(), document.getElementById("description").value = "";
var t = $.inArray(e.target.value, dotNotationDisplayArray);
if (t == -1) $("#description").attr("value", "Error: The Dot Notation you entered doesn't appear to be valid.");
else {
document.getElementById("description").value = "Loading (please wait)....";
for (i = 0; i < alignmentArray.length; i++) $("#dotNotation").val() == alignmentArray[i].title && (document.getElementById("itemGUID").value = alignmentArray[i].guid, $.ajax({
async: !1,
url: "http://anyorigin.com/get?url=" + alignmentArray[i].description + "&callback=?",
dataType: "json",
success: function(e) {
var t = $(e.contents).filter("title").text().replace(" | Achievement Standards Network", "");
if (t != "") {
var n = t.length;
document.getElementById("description").value = t
}
t == "" && (document.getElementById("description").value = "No Description Available"), validateAlignmentForm()
}
}))
}
}
})
}), $(function() {
$("#educationalUse").change(function() {
updateItemEducationTab("educationalUse", "educationalUseOther")
})
}), $(function() {
$("#educationalAlignment").change(function(e) {})
}), $(function() {
$("#educationalUseOther").change(function() {
updateItemEducationTab("educationalUse", "educationalUseOther")
})
}), $(function() {
$("#endUser").change(function() {
updateItemEducationTab("endUser", "endUserOther")
})
}), $(function() {
$("#endUserOther").change(function() {
updateItemEducationTab("endUser", "endUserOther")
})
}), $(function() {
$("#groupType").change(function() {
updateItemEducationTab("groupType", "groupTypeOther")
})
}), $(function() {
$("#groupTypeOther").change(function() {
updateItemEducationTab("groupType", "groupTypeOther")
})
}), $(function() {
$("#files").change(function(e) {
importedFiles = e.target.files;
for (var t = 0, n; n = importedFiles[t]; t++) reader = new FileReader, reader.onload = function(e) {
return itemCounter = 0, jQuery("#multiItemSelector input[type=checkbox]").each(function(e, t) {
t.checked = !1, itemCounter++
}),
function(e) {
$("#loadModal").modal("hide"), fileHasErrors = !1, fileErrors = [], jQuery("#multiItemSelector input[type=checkbox]").each(function(e, t) {
t.checked = !1
}), updateInputFields(), itemCounter == 0 && jQuery("#multiItemSelector").empty();
var t = e.target.result;
if (t[0] == "{") {
var n = JSON.parse(t);
for (u in n) {
if (n[u] == undefined || n[u].length == 0) continue;
n[u].id = itemCounter, items["itemTag" + itemCounter] = n[u];
var r = n[u].title != "" ? n[u].title.length > 25 ? n[u].title.substr(0, 25) + "…" : n[u].title : "New Item " + itemCounter,
i = n[u].url;
for (v in n[u].educationalAlignments) alignments[v] == undefined && ($(".noAlignmentsYet").hide(), alignments[v] = n[u].educationalAlignments[v], $("#currentAlignmentTable > tbody:last").append('<tr><td><label class="checkbox"><input type="checkbox" class="alignment-checkbox" value="' + v + '" />' + n[u].educationalAlignments[v].dotNotation + "</label></td><td>" + capitalize(n[u].educationalAlignments[v].alignmentType) + "</td></tr>"));
$("#multiItemSelector").append($("<a href='#itemTag" + itemCounter + "' class='pull-right delete-tag'><i class='icon-remove'></i></a> <a href='#itemTag" + itemCounter + "' id='itemTag" + itemCounter + "URL' " + (i != "" ? "" : "style='display:none;'") + " class='pull-right render-tag'><i class='icon-share'></i> </a> <label id='itemTag" + itemCounter + "Label' class='checkbox'><input id='itemTag" + itemCounter + "' type='checkbox' name='tagItem'/><span>" + r + "</span></label>")), itemCounter++
}
}
if (t[0] != "{") {
var s = [],
o = t.replace(/\r/g, "\r\n").replace(/\n\n/, "\n"),
n = $.csv.toArrays(o);
validateImportHeaders(n), fileHasErrors || validateImportColumns(n), fileHasErrors && showFileHasErrorsMessage("File Format Error");
for (var u = 1; u < n.length; u++) {
if (fileHasErrors) continue;
if (n[u] == undefined || n[u].length < 25) continue;
var r = n[u][1] != "" && n[u][1] != undefined ? n[u][1].length > 25 ? n[u][1].substr(0, 25) + "…" : n[u][1] : "New Item " + itemCounter,
i = n[u][2],
a = n[u][17].split(","),
f = n[u][18].split(","),
l = n[u][19].split(","),
c = n[u][21].split(","),
h = n[u][20].split(","),
p = {};
for (ea = 0; ea < a.length; ea++) {
if (l[ea] == "") continue;
var d = validateImportEducationalAlignment({
educationalAlignment: a[ea],
alignmentType: f[ea],
dotNotation: l[ea],
description: c[ea],
itemURL: h[ea]
});
if (!fileHasErrors) {
var v = objectToHash(d);
alignments[v] == undefined && ($(".noAlignmentsYet").hide(), alignments[v] = d, $("#currentAlignmentTable > tbody:last").append('<tr><td><label class="checkbox"><input type="checkbox" class="alignment-checkbox" value="' + v + '" />' + l[ea] + "</label></td><td>" + capitalize(f[ea]) + "</td></tr>")), p[v] = d
}
}
tempItem = {
id: itemCounter,
title: validateImportField("title", n[u][1]),
language: validateImportField("language", n[u][8]),
thumbnail: validateImportField("thumbnail", n[u][23]),
url: validateImportField("url", i),
tagDescription: validateImportField("tagDescription", n[u][24]),
createdOn: validateImportField("createdOn", n[u][5]),
topic: validateImportField("topic", n[u][4]),
createdBy: validateImportField("createdBy", n[u][6]),
usageRightsURL: validateImportField("usageRightsURL", n[u][10]),
publisher: validateImportField("publisher", n[u][7]),
isBasedOnURL: validateImportField("isBasedOnURL", n[u][11]),
endUser: validateImportField("endUser", n[u][12]),
ageRange: validateImportField("ageRange", n[u][14]),
educationalUse: validateImportField("educationalUse", n[u][13]),
interactivityType: validateImportField("interactivityType", n[u][15]),
learningResourceType: validateImportField("learningResourceType", n[u][16]),
mediaType: validateImportField("mediaType", n[u][9]),
groupType: validateImportField("groupType", n[u][22]),
timeRequired: validateImportField("timeRequired", n[u][3]),
educationalAlignments: p
}, fileHasErrors ? showFileHasErrorsMessage("Errors found in row #" + u) : (items["itemTag" + itemCounter] = tempItem, $("#multiItemSelector").append($("<a href='#itemTag" + itemCounter + "' class='pull-right delete-tag'><i class='icon-remove'></i></a> <a href='#itemTag" + itemCounter + "' id='itemTag" + itemCounter + "URL' " + (i != "" ? "" : "style='display:none;'") + " class='pull-right render-tag'><i class='icon-share'></i> </a> <label id='itemTag" + itemCounter + "Label' class='checkbox'><input id='itemTag" + itemCounter + "' type='checkbox' name='tagItem'/><span>" + r + "</span></label>")), itemCounter++)
}
}
updateResourceCount(), $("#pleasewait").hide()
}
}(n), /(csv|json)$/.test(n.name.toLowerCase()) ? ($("#pleasewait").show(), reader.readAsText(n), $("#fileForm")[0].reset()) : (alert("Please select a .CSV file"), $("#fileForm")[0].reset())
})
}), $(function() {
$("#interactivityType").change(function() {
updateItemEducationTab("interactivityType", "interactivityTypeOther")
})
}), $(function() {
$("#interactivityTypeOther").change(function() {
updateItemEducationTab("interactivityType", "interactivityTypeOther")
})
}), $(function() {
var e = "isBasedOnURL";
$("#" + e).change(function(t) {
var n = $(t.target).val();
$("#multiItemSelector input[type=checkbox]:checked").each(function(t, r) {
items[r.id][e] = n
}), updateTextArea()
})
}), $(function() {
$("#itemURL").change(function(e) {})
}), $(function() {
var e = "language";
$("#" + e).change(function(t) {
var n = $(t.target).val();
$("#multiItemSelector input[type=checkbox]:checked").each(function(t, r) {
items[r.id][e] = n
}), updateTextArea()
})
}), $(function() {
$("#learningResourceType").change(function() {
updateItemEducationTab("learningResourceType", "learningResourceTypeOther")
})
}), $(function() {
$("#learningResourceTypeOther").change(function() {
updateItemEducationTab("learningResourceType", "learningResourceTypeOther")
})
}), $(function() {
$("#mediaType").change(function() {
updateItemEducationTab("mediaType", "mediaTypeOther")
})
}), $(function() {
$("#mediaTypeOther").change(function() {
updateItemEducationTab("mediaType", "mediaTypeOther")
})
}), $(function() {
$("#multiItemSelector").change(function() {
updateInputFields(), updateTextArea()
})
}), $(function() {
var e = "publisher";
$("#" + e).change(function(t) {
var n = $(t.target).val();
$("#multiItemSelector input[type=checkbox]:checked").each(function(t, r) {
items[r.id][e] = n
}), updateTextArea()
})
}), $(function() {
var e = "title";
$("#" + e).change(function(t) {
var n = $(t.target).val();
$("#multiItemSelector input[type=checkbox]:checked").each(function(t, r) {
items[r.id][e] = n;
var i = n.length > 25 ? n.substr(0, 25) + "…" : n;
$("#" + r.id + "Label span")[0].innerHTML = i
}), updateTextArea()
})
}), $(function() {
var e = "topic";
$("#" + e).change(function(t) {
var n = $(t.target).val();
$("#multiItemSelector input[type=checkbox]:checked").each(function(t, r) {
items[r.id][e] = n
}), updateTextArea()
})
}), $(function() {
var e = "url";
$("#" + e).change(function(t) {
var n = $(t.target).val();
$("#multiItemSelector input[type=checkbox]:checked").each(function(t, r) {
items[r.id][e] = n, n != "" ? $("#" + r.id + "URL").show() : $("#" + r.id + "URL").hide()
}), updateTextArea(), updateMainContentBottom(n)
})
}), $(function() {
var e = "usageRightsURL";
$("#" + e).change(function(t) {
var n = $(t.target).val();
$("#multiItemSelector input[type=checkbox]:checked").each(function(t, r) {
items[r.id][e] = n
}), updateTextArea()
})
}), $(function() {
$(".add-alignment").click(function(e) {
return $("#alignmentsModal").modal("show"), !1
}), document.onkeypress = function(e) {
if (e.which == 13) return !1
}
}), $(function() {
$("#addButton").click(function() {
$("#alignmentsModal").modal("hide"), $(".noAlignmentsYet").hide();
var e = $("#educationalAlignment").val(),
t = $("#alignmentType").val(),
n = $("#dotNotation").val(),
r = $("#description").val(),
i = $("#itemURL").val(),
s = {
educationalAlignment: e,
alignmentType: t,
dotNotation: n,
description: r,
itemURL: i
},
o = objectToHash(s);
return alignments[o] == undefined && (alignments[o] = s, n == "" && (n = "N/A"), $("#currentAlignmentTable > tbody:last").append('<tr><td><label class="checkbox"><input type="checkbox" class="alignment-checkbox" value="' + o + '" />' + n + "</label></td><td>" + capitalize(t) + "</td></tr>")), updateTextArea(), $("#alignmentType").val(""), $("#dotNotation").val(""), $("#description").val(""), $("#itemURL").val(""), $("#itemGUID").val(""), !1
})
}), $(function() {
$("#addThumbnailButton").click(function() {
return $(this).hasClass("disabled") || $("#thumbModal").modal("show"), !1
})
}), $(function() {
$(".alignment-checkbox").live("click", function(e) {
checkbox = e.target, objectHash = $(checkbox).attr("value"), $("#multiItemSelector input[type=checkbox]:checked").each(function(e, t) {
$(checkbox).is(":checked") ? items[t.id].educationalAlignments[objectHash] = alignments[objectHash] : delete items[t.id].educationalAlignments[objectHash]
}), updateTextArea()
})
}), $(function() {
$("#closeModalButton").click(function() {
jQuery("#mainContentTopLeft").show(), jQuery("#mainContentTopRight").show(), jQuery("#mainContentBottom").show()
})
}), $(function() {
$(".delete-tag").live("click", function(e) {
var t = $(e.target).parent().attr("href").substr(1);
return $("#deleteModal .btn-danger").attr("onclick", "deleteTag('" + t + "');").attr("href", "#"), $("#deleteModal").modal("show"), !1
})
}), $(function() {
$("#exportCsvButton").click(function() {
var e = processCSVOutput(!0);
saveAndExport(e, ".csv")
})
}), $(function() {
$("#exportHtmlButton").click(function() {
var e = processHTMLOutput(!0);
saveAndExport(e, ".html")
})
}), $(function() {
$("#exportJsonButton").click(function() {
var e = processJSONOutput(!0);
saveAndExport(e, ".json")
})
}), $(function() {
$("#history a").live("click", function(e) {
var t = $(this).attr("href").substr(1);
return $("#resetModal .btn-success").attr("onclick", "resetResource('" + t + "');").attr("href", "#"), $("#resetModal").modal("show"), !1
})
}), $(function() {
$("#loadButton").click(function() {})
}), $(function() {
$("#newbutton").click(function() {
toggleForm()
})
}), $(function() {
$("#publishButton").click(function() {
if (!$(this).hasClass("disabled")) {
showPleaseWait("Publishing... (This can take some time depending on the number of resources you have selected..)");
var e = processJSONOutput();
saveDraft(e);
var e = processJSONOutput(!0);
saveRemote(e, "LR")
}
})
}), $(function() {
$("#removeThumbnailButton").click(function() {
return $("#thumbnail").attr("value", ""), $("#thumbnailImage").attr("src", ""), $("#removeThumbnailButton").hide(), $("#thumbnailImage").hide(), $("#multiItemSelector input[type=checkbox]:checked").each(function(e, t) {
items[t.id].thumbnail = ""
}), !1
})
}), $(function() {
$(".render-tag").live("click", function(e) {
var t = $(e.target).first().parent().attr("href").substr(1);
return updateMainContentBottom(items[t].url), !1
})
}), $(function() {
$("#saveDraftButton").click(function() {
var e = processJSONOutput();
saveDraft(e)
})
}), $(function() {
$("#saveLoadModalButton").click(function() {
if (document.getElementById("loadModalTextArea").value != "") {
itemCounter = 0, jQuery("#multiItemSelector input[type=checkbox]").each(function(e, t) {
t.checked = !1, itemCounter++
}), document.getElementById("loadModalTextArea").value = document.getElementById("loadModalTextArea").value.replace(/^\s+|\s+$/g, "");
var e = document.getElementById("loadModalTextArea").value.split("\n");
for (var t = 0; t < e.length; t++) {
var n = e[t].split(",");
items["itemTag" + itemCounter] = {
id: itemCounter,
title: n[0],
language: "",
thumbnail: "",
url: n[1],
tagDescription: "",
createdOn: "",
topic: "",
createdBy: "",
usageRightsURL: "",
publisher: "",
isBasedOnURL: "",
endUser: "",
ageRange: "",
educationalUse: "",
interactivityType: "",
learningResourceType: "",
mediaType: "",
groupType: "",
timeRequired: "P0Y0M0W0DT0H0M0S",
educationalAlignments: {}
}, itemCounter++
}
document.getElementById("loadModalTextArea").value = ""
} else document.getElementById("files").value != "";
redrawResourcesBasedOnItems()
})
}), $(function() {
$("#selectDeselectAllResources").click(function() {
checked = $(this).attr("checked"), $("#multiItemSelector input[type=checkbox]").each(function() {
checked ? ($(this).attr("checked", !0), $("#publishButton").removeClass("disabled")) : ($(this).removeAttr("checked"), $("#publishButton").addClass("disabled"))
}), updateResourceCount()
})
}), $(function() {
$("#description").keypress(function(e) {})
}), $(function() {
$("#dotNotation").keypress(function(e) {
e.keyCode == 13 && $("#dotNotation").blur()
})
}), $(function() {
$("#itemURL").keypress(function(e) {})
}); | Javascript reduction.
| public/appmain-expanded.js | Javascript reduction. | <ide><path>ublic/appmain-expanded.js
<ide> })
<ide> }
<ide>
<del>function clearTimeRequired() {
<del> $("#slideryears").slider({
<del> value: 0
<del> }), $("#slidermonths").slider({
<del> value: 0
<del> }), $("#sliderweeks").slider({
<del> value: 0
<del> }), $("#sliderdays").slider({
<del> value: 0
<del> }), $("#sliderhours").slider({
<del> value: 0
<del> }), $("#sliderminutes").slider({
<del> value: 0
<del> }), $("#sliderseconds").slider({
<del> value: 0
<del> }), $("#amountyears").html("Year"), $("#amountmonths").html("Month"), $("#amountweeks").html("Week"), $("#amountdays").html("Day"), $("#amounthours").html("Hour"), $("#amountminutes").html("Minute"), $("#amountseconds").html("Second")
<del>}
<del>
<ide> function csvPreprocess(e) {
<ide> return (e + "").replace(/^([a-z])|\s+([a-z])|,+([a-z])/g, function(e) {
<ide> return e.toUpperCase()
<ide> }), dotNotationDisplayArray.push(r[2])
<ide> }
<ide> }
<del>
<del>
<del>
<del>function saveAndExport(e, t) {
<del> var n = new Date,
<del> r = location.protocol + "//" + location.host + "/tagger/save_export/";
<del> $("<form></form>", {
<del> action: r,
<del> method: "POST"
<del> }).append($("<input></input>", {
<del> name: "filename",
<del> type: "hidden",
<del> value: t + "_" + n.toISOString() + t
<del> })).append($("<input></input>", {
<del> name: "data",
<del> type: "hidden",
<del> value: e
<del> })).appendTo("body").submit()
<del>}
<del>
<ide>
<ide> function redrawResourcesBasedOnItems() {
<ide> $("#multiItemSelector").empty(), $("#multiItemSelector input[type=checkbox]").each(function(e, t) {
<ide> }
<ide> }
<ide>
<del>function showMessage(e, t) {
<del> $("#pleaseWaitModal").modal("hide"), t == undefined && (t = "System Message"), $("#messageModal .header-text").html(t), $("#messageModal .body-text").html(e), $("#messageModal").modal("show")
<del>}
<del>
<del>function showPleaseWait(e) {
<del> $("#pleaseWaitModal .body-text").html(e), $("#pleaseWaitModal").modal("show")
<del>}
<del>
<ide> function toggleForm() {
<ide> $("#multiItemSelector input[type=checkbox]:checked").length > 0 ? ($("#LRMIData input,#LRMIData select,#LRMIData textarea").removeAttr("disabled"), $("#educationTab,#alignmentTab").removeClass("disabled"), $("#educationTab a,#alignmentTab a").attr("data-toggle", "tab")) : ($("#generalTab a").click(), $("#LRMIData input,#LRMIData select,#LRMIData textarea").attr("disabled", "disabled"), $("#educationTab,#alignmentTab").addClass("disabled"), $("#educationTab a,#alignmentTab a").removeAttr("data-toggle"))
<ide> }
<ide> for (j in items[n.id].educationalAlignments) items[n.id].educationalAlignments[j].educationalAlignment != undefined && items[n.id].educationalAlignments[j].educationalAlignment != "" && (e += "Educational Alignment:\n" + items[n.id].educationalAlignments[j].educationalAlignment + "\n"), items[n.id].educationalAlignments[j].alignmentType != undefined && items[n.id].educationalAlignments[j].alignmentType != "" && (e += "Alignment Type:\n" + items[n.id].educationalAlignments[j].alignmentType + "\n"), items[n.id].educationalAlignments[j].dotNotation != undefined && items[n.id].educationalAlignments[j].dotNotation != "" && (e += "Dot Notation:\n" + items[n.id].educationalAlignments[j].dotNotation + "\n"), items[n.id].educationalAlignments[j].itemURL != undefined && items[n.id].educationalAlignments[j].itemURL != "" && (e += "Item URL:\n" + items[n.id].educationalAlignments[j].itemURL + "\n"), items[n.id].educationalAlignments[j].description != undefined && items[n.id].educationalAlignments[j].description != "" && (e += "Description:\n" + items[n.id].educationalAlignments[j].description + "\n");
<ide> e += "\n-----------------------\n\n"
<ide> }), $("#textarea").val(e)
<del>}
<del>
<del>function updateTimeRequired(e) {
<del> if (e != undefined) {
<del> var t = "timeRequired";
<del> $("#multiItemSelector input[type=checkbox]:checked").each(function(n, r) {
<del> var i = items[r.id][t].match(/(\d+)/g);
<del> items[r.id][t] = "P" + (e == "Year" ? $("#slideryears").slider("value") : i[0]) + "Y" + (e == "Month" ? $("#slidermonths").slider("value") : i[1]) + "M" + (e == "Week" ? $("#sliderweeks").slider("value") : i[2]) + "W" + (e == "Day" ? $("#sliderdays").slider("value") : i[3]) + "DT" + (e == "Hour" ? $("#sliderhours").slider("value") : i[4]) + "H" + (e == "Minute" ? $("#sliderminutes").slider("value") : i[5]) + "M" + (e == "Second" ? $("#sliderseconds").slider("value") : i[6]) + "S"
<del> }), updateTextArea()
<del> }
<del>}
<del>
<del>function validateAlignmentForm() {
<del> default_values = new Array, $(".required").each(function(e, t) {
<del> default_values[e] = t.value
<del> }), req_all = default_values.length, filled_out_values = $.grep(default_values, function(e) {
<del> return e
<del> }), filled_out_values = $.grep(filled_out_values, function(e) {
<del> return e != "Alignment Type..."
<del> }), filled_out_values = $.grep(filled_out_values, function(e) {
<del> return e != "Loading (please wait)...."
<del> }), req_filled = filled_out_values.length, req_filled > 0 && req_all == req_filled ? $("#addButton").removeAttr("disabled") : $("#addButton").attr("disabled", "disabled")
<del>}
<del>
<del>function validateImportHeaders(e) {
<del> var t = e[0],
<del> n = t[0];
<del> n == "Metadata:" ? (validValues = ["Metadata:", "Title", "URL", "Time Required (FORMAT: P0Y0M0W0DT0H0M0S) ISO8601", "Topic", "Created (FORMAT: YYYY-MM-DD)", "Creator", "Publisher", "Language", "Mediatype", "Use Rights URL", "Is based on URL", "Intended End User Role", "Educational Use", "Typical Age Range", "Interactivity Type", "Learning Resource Type", "Educational Alignment", "Alignment Type", "Dot Notation", "Target URL", "Target Description", "Group Type", "Thumbnail URL", "Tag Description"], compareValueEquals(t, validValues, "There appears to be a value comparison error in the firstRow headers preventing Tagger from knowing if this is a valid file")) : (fileHasErrors = !0, fileErrors.push("<strong>Invalid file imported</strong><br /> The file you attempted to import doesn't appear to have the correct header identifier ('" + n + "' was sent, it should be 'Metadata:') for this version of Tagger (v1.1).<br /><br />"))
<del>}
<del>
<del>function validateImportColumns(e) {
<del> var t = e[0],
<del> n = t[0];
<del> if (n == "Metadata:")
<del> if (e.length > 1)
<del> for (i in e) e[i].length != 25 && e[i].length > 1 && (fileHasErrors = !0, fileErrors.push("<strong>Invalid file imported</strong><br /> The file you attempted to import doesn't appear to have the correct number of columns in row #" + i + " (There appear to be '" + e[i].length + "', it should be '25') for this version of Tagger (v1.1).<br /><br />"));
<del> else fileHasErrors = !0, fileErrors.push("<strong>Empty file imported</strong><br /> The file you attempted to import doesn't appear to have any content in it.<br /><br />")
<del>}
<del>
<del>function validateImportField(e, t) {
<del> t == undefined && (t = "");
<del> var n = "";
<del> switch (e) {
<del> case "title":
<del> case "topic":
<del> case "tagDescription":
<del> case "thumbnail":
<del> case "url":
<del> case "usageRightsURL":
<del> case "isBasedOnURL":
<del> case "publisher":
<del> case "createdBy":
<del> n = t;
<del> break;
<del> case "language":
<del> t != undefined && t != "" && (tValue = t.toLowerCase(), tValue = tValue.replace(/^en$/, "EN_US"), tValue = tValue.replace(/^english$/, "EN_US"), tValue = tValue.replace(/^engrish$/, "EN_US"), tValue = tValue.replace(/^spanish$/, "ES_ES"), tValue = tValue.replace(/^es$/, "ES_ES"), tValue = tValue.replace(/^espanol$/, "ES_ES"), tValue = tValue.replace(/^español$/, "ES_ES"), validOptions = ["EN_US", "ES_ES"], tValue = tValue.toUpperCase(), tValue = tValue.replace("-", "_"), $.inArray(tValue, validOptions) == -1 ? (fileHasErrors = !0, fileErrors.push('<strong>Invalid file imported -- <em>"Language"</em></strong><br /> It appears the sent language value is incorrect: "' + tValue + '" -- Valid Options: "' + validOptions.join() + '"<br /><br />')) : n = tValue);
<del> break;
<del> case "createdOn":
<del> if (t != undefined && t != "") {
<del> var r = 216e5,
<del> i = Date.parse(t),
<del> s = new Date(i + r);
<del> isNaN(s) || s.getMonth() + 1 == 0 || s.getDate() == 0 || s.getFullYear() == 0 ? (fileHasErrors = !0, fileErrors.push("<strong>Invalid file imported -- <em>"Created On"</em></strong><br /> It would appear you're attempting to import a file that is containing a "Created On" date that is an invalid ISO8601 value. Value sent: "" + t + ""<br /><br />")) : n = (s.getMonth() + 1 < 10 ? "0" + (s.getMonth() + 1) : s.getMonth() + 1) + "-" + (s.getDate() < 10 ? "0" + s.getDate() : s.getDate()) + "-" + s.getFullYear()
<del> }
<del> break;
<del> case "endUser":
<del> t != undefined && t != "" && (validOptions = ["Administrator", "Mentor", "Parent", "Peer Tutor", "Specialist", "Student", "Teacher", "Team"], n = checkCSVValuesForValidOptions("End User", validOptions, t));
<del> break;
<del> case "ageRange":
<del> t != undefined && t != "" && (validOptions = ["0-2", "3-5", "5-8", "8-10", "10-12", "12-14", "14-16", "16-18", "18+"], n = checkCSVValuesForValidOptions("Age Range", validOptions, t));
<del> break;
<del> case "educationalUse":
<del> t != undefined && t != "" && (validOptions = ["Activity", "Analogies", "Assessment", "Auditory", "Brainstorming", "Classifying", "Comparing", "Cooperative Learning", "Creative Response", "Demonstration", "Differentiation", "Discovery Learning", "Discussion/Debate", "Drill & Practice", "Experiential", "Field Trip", "Game", "Generating Hypotheses", "Guided Questions", "Hands-on", "Homework", "Identify Similarities & Differences", "Inquiry", "Interactive", "Interview/Survey", "Interviews", "Introduction", "Journaling", "Kinesthetic", "Laboratory", "Lecture", "Metaphors", "Model & Simulation", "Musical", "Nonlinguistic", "Note Taking", "Peer Coaching", "Peer Response", "Play", "Presentation", "Problem Solving", "Problem Based", "Project", "Questioning", "Reading", "Reciprocal Teaching", "Reflection", "Reinforcement", "Research", "Review", "Role Playing", "Service Learning", "Simulations", "Summarizing", "Technology", "Testing Hypotheses", "Thematic Instruction", "Visual/Spatial", "Word Association", "Writing"], n = checkCSVValuesForValidOptions("Educational Use", validOptions, t));
<del> break;
<del> case "interactivityType":
<del> t != undefined && t != "" && (validOptions = ["Active", "Expositive", "Mixed"], n = checkCSVValuesForValidOptions("Interactivity Type", validOptions, t));
<del> break;
<del> case "learningResourceType":
<del> t != undefined && t != "" && (validOptions = ["Activity", "Assessment", "Audio", "Broadcast", "Calculator", "Discussion", "E-Mail", "Field Trip", "Hands-on", "In-person/Speaker", "Kinesthetic", "Lab Material", "Lesson Plan", "Manipulative", "MBL (Microcomputer Based)", "Model", "On-Line", "Podcast", "Presentation", "Printed", "Quiz", "Robotics", "Still Image", "Test", "Video", "Wiki", "Worksheet"], n = checkCSVValuesForValidOptions("Learning Resource Type", validOptions, t));
<del> break;
<del> case "mediaType":
<del> t != undefined && t != "" && (validOptions = ["Audio CD", "Audiotape", "Calculator", "CD-I", "CD-ROM", "Diskette", "Duplication Master", "DVD/Blu-ray", "E-Mail", "Electronic Slides", "Field Trip", "Filmstrip", "Flash", "Image", "In-person/Speaker", "Interactive Whiteboard", "Manipulative", "MBL (Microcomputer Based)", "Microfiche", "Overhead", "Pamphlet", "PDF", "Person-to-Person", "Phonograph Record", "Photo", "Podcast", "Printed", "Radio", "Robotics", "Satellite", "Slides", "Television", "Transparency", "Video Conference", "Videodisc", "Webpage", "Wiki"], n = checkCSVValuesForValidOptions("Media Type", validOptions, t));
<del> break;
<del> case "groupType":
<del> t != undefined && t != "" && (validOptions = ["Class", "Community", "Grade", "Group Large (6+ Members)", "Group Small (3-5 Members)", "Individual", "Inter-generational", "Multiple Class", "Pair", "School", "State/Province", "World"], n = checkCSVValuesForValidOptions("Group Type", validOptions, t));
<del> break;
<del> case "timeRequired":
<del> t != undefined && t != "" ? nezasa.iso8601.Period.isValid(t) ? (parsedTimeRequired = nezasa.iso8601.Period.parse(t), parsedTimeRequired[0] = "P" + parsedTimeRequired[0] + "Y", parsedTimeRequired[1] = parsedTimeRequired[1] + "M", parsedTimeRequired[2] = parsedTimeRequired[2] + "W", parsedTimeRequired[3] = parsedTimeRequired[3] + "D", parsedTimeRequired[4] = "T" + parsedTimeRequired[4] + "H", parsedTimeRequired[5] = parsedTimeRequired[5] + "M", parsedTimeRequired[6] = parsedTimeRequired[6] + "S", n = parsedTimeRequired.join("")) : (n = "", fileHasErrors = !0, fileErrors.push("<strong>Invalid file imported -- <em>"Time Required"</em></strong><br /> It would appear you're attempting to import a file with an invalid ISO8601 "Time Required" value. Value sent "" + t + ""<br /><br />")) : n = "P0Y0M0W0DT0H0M0S"
<del> }
<del> return n
<del>}
<del>
<del>function validateImportEducationalAlignment(e) {
<del> var t = ["Teaches", "Assesses", "Requires"];
<del> checkCSVValuesForValidOptions("Alignment Type", t, e.alignmentType, !0);
<del> var n = $.inArray(e.dotNotation, dotNotationDisplayArray);
<del> if (n != -1) {
<del> var r = e.dotNotation.split(".");
<del> r[0].toUpperCase() == "CCSS" && (e.educationalAlignment = "Common Core State Standards")
<del> }
<del> return e
<del>}
<del>
<del>function checkCSVValuesForValidOptions(e, n, r, i) {
<del> r == undefined && i == 1 && (fileHasErrors = !0, fileErrors.push('<strong>Invalid file imported -- <em>"' + e + '"</em></strong><br /> Value set: "undefined" -- Valid Options: "' + n.join() + '"<br /><br />'));
<del> if (r == undefined) return "";
<del> resValues = [], tValues = r.toLowerCase(), tValues = tValues.split(",");
<del> for (t in tValues) tValue = $.trim(tValues[t]), tValue = toCorrectCase(tValue), $.inArray(tValue, n) == -1 && i == 1 ? (fileHasErrors = !0, fileErrors.push('<strong>Invalid file imported -- <em>"' + e + '"</em></strong><br /> Value set: "' + tValue + '" -- Valid Options: "' + n.join() + '"<br /><br />')) : resValues.push(tValue);
<del> return resValues.join(",")
<ide> }
<ide>
<ide> function toCorrectCase(e) { |
|
Java | epl-1.0 | bc69f2fa9de9bebfe9f5cfcf78ac620aa9546bc5 | 0 | opendaylight/bgpcep | /*
* Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
/**
* Generated file
* Generated from: yang module name: bgp-rib-impl yang module local name: bgp-peer
* Generated by: org.opendaylight.controller.config.yangjmxgenerator.plugin.JMXGenerator
* Generated at: Sat Jan 25 11:00:14 CET 2014
*
* Do not modify this file unless it is present under src/main directory
*/
package org.opendaylight.controller.config.yang.bgp.rib.impl;
import com.google.common.base.Charsets;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.net.InetAddresses;
import io.netty.util.concurrent.Future;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.opendaylight.controller.config.api.JmxAttributeValidationException;
import org.opendaylight.protocol.bgp.openconfig.spi.BGPConfigModuleTracker;
import org.opendaylight.protocol.bgp.openconfig.spi.BGPOpenConfigProvider;
import org.opendaylight.protocol.bgp.openconfig.spi.BGPOpenconfigMapper;
import org.opendaylight.protocol.bgp.openconfig.spi.InstanceConfigurationIdentifier;
import org.opendaylight.protocol.bgp.openconfig.spi.pojo.BGPPeerInstanceConfiguration;
import org.opendaylight.protocol.bgp.parser.BgpTableTypeImpl;
import org.opendaylight.protocol.bgp.parser.spi.MultiprotocolCapabilitiesUtil;
import org.opendaylight.protocol.bgp.rib.impl.BGPPeer;
import org.opendaylight.protocol.bgp.rib.impl.StrictBGPPeerRegistry;
import org.opendaylight.protocol.bgp.rib.impl.spi.BGPPeerRegistry;
import org.opendaylight.protocol.bgp.rib.impl.spi.BGPSessionPreferences;
import org.opendaylight.protocol.bgp.rib.impl.spi.RIB;
import org.opendaylight.protocol.util.Ipv6Util;
import org.opendaylight.tcpmd5.api.KeyMapping;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.AsNumber;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpAddress;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.message.BgpParameters;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.message.BgpParametersBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.message.bgp.parameters.OptionalCapabilities;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.message.bgp.parameters.OptionalCapabilitiesBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.message.bgp.parameters.optional.capabilities.CParametersBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.message.bgp.parameters.optional.capabilities.c.parameters.As4BytesCapabilityBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.BgpTableType;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.CParameters1;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.CParameters1Builder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.open.bgp.parameters.optional.capabilities.c.parameters.AddPathCapabilityBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.open.bgp.parameters.optional.capabilities.c.parameters.GracefulRestartCapabilityBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.open.bgp.parameters.optional.capabilities.c.parameters.MultiprotocolCapabilityBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.open.bgp.parameters.optional.capabilities.c.parameters.add.path.capability.AddressFamilies;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.PeerRole;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.tcpmd5.cfg.rev140427.Rfc2385Key;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
*/
public final class BGPPeerModule extends org.opendaylight.controller.config.yang.bgp.rib.impl.AbstractBGPPeerModule {
private static final Logger LOG = LoggerFactory.getLogger(BGPPeerModule.class);
public BGPPeerModule(final org.opendaylight.controller.config.api.ModuleIdentifier identifier,
final org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) {
super(identifier, dependencyResolver);
}
public BGPPeerModule(final org.opendaylight.controller.config.api.ModuleIdentifier identifier,
final org.opendaylight.controller.config.api.DependencyResolver dependencyResolver, final BGPPeerModule oldModule,
final java.lang.AutoCloseable oldInstance) {
super(identifier, dependencyResolver, oldModule, oldInstance);
}
@Override
protected void customValidation() {
final IpAddress host = getHost();
JmxAttributeValidationException.checkNotNull(host, "value is not set.", hostJmxAttribute);
JmxAttributeValidationException.checkCondition(host.getIpv4Address() != null || host.getIpv6Address() != null,
"Unexpected host", hostJmxAttribute);
JmxAttributeValidationException.checkNotNull(getPort(), "value is not set.", portJmxAttribute);
if (getOptionaPassword(getPassword()).isPresent()) {
/*
* This is a nasty hack, but we don't have another clean solution. We cannot allow
* password being set if the injected dispatcher does not have the optional
* md5-server-channel-factory set.
*
* FIXME: this is a use case for Module interfaces, e.g. RibImplModule
* should something like isMd5ServerSupported()
*/
final RIBImplModuleMXBean ribProxy = this.dependencyResolver.newMXBeanProxy(getRib(), RIBImplModuleMXBean.class);
final BGPDispatcherImplModuleMXBean bgpDispatcherProxy = this.dependencyResolver.newMXBeanProxy(
ribProxy.getBgpDispatcher(), BGPDispatcherImplModuleMXBean.class);
final boolean isMd5Supported = bgpDispatcherProxy.getMd5ChannelFactory() != null;
JmxAttributeValidationException.checkCondition(isMd5Supported,
"Underlying dispatcher does not support MD5 clients", passwordJmxAttribute);
}
if (getPeerRole() != null) {
final boolean isNotPeerRoleInternal= getPeerRole() != PeerRole.Internal;
JmxAttributeValidationException.checkCondition(isNotPeerRoleInternal,
"Internal Peer Role is reserved for Application Peer use.", peerRoleJmxAttribute);
}
}
private InetSocketAddress createAddress() {
final IpAddress ip = getHost();
Preconditions.checkArgument(ip.getIpv4Address() != null || ip.getIpv6Address() != null, "Failed to handle host %s", ip);
if (ip.getIpv4Address() != null) {
return new InetSocketAddress(InetAddresses.forString(ip.getIpv4Address().getValue()), getPort().getValue());
}
return new InetSocketAddress(InetAddresses.forString(ip.getIpv6Address().getValue()), getPort().getValue());
}
@Override
public java.lang.AutoCloseable createInstance() {
final RIB r = getRibDependency();
final List<BgpParameters> tlvs = getTlvs(r);
final AsNumber remoteAs = getAsOrDefault(r);
final BGPSessionPreferences prefs = new BGPSessionPreferences(r.getLocalAs(), getHoldtimer(), r.getBgpIdentifier(), remoteAs, tlvs);
final BGPPeer bgpClientPeer;
final IpAddress host = getNormalizedHost();
if (getPeerRole() != null) {
bgpClientPeer = new BGPPeer(peerName(host), r, getPeerRole());
} else {
bgpClientPeer = new BGPPeer(peerName(host), r, PeerRole.Ibgp);
}
bgpClientPeer.registerRootRuntimeBean(getRootRuntimeBeanRegistratorWrapper());
getPeerRegistryBackwards().addPeer(host, bgpClientPeer, prefs);
final BGPPeerModuleTracker moduleTracker = new BGPPeerModuleTracker(r.getOpenConfigProvider());
moduleTracker.onInstanceCreate();
final CloseableNoEx peerCloseable = new CloseableNoEx() {
@Override
public void close() {
bgpClientPeer.close();
getPeerRegistryBackwards().removePeer(host);
moduleTracker.onInstanceClose();
}
};
// Initiate connection
if(getInitiateConnection()) {
final Future<Void> cf = initiateConnection(createAddress(), getOptionaPassword(getPassword()), getPeerRegistryBackwards());
return new CloseableNoEx() {
@Override
public void close() {
cf.cancel(true);
peerCloseable.close();
}
};
} else {
return peerCloseable;
}
}
private interface CloseableNoEx extends AutoCloseable {
@Override
void close();
}
private AsNumber getAsOrDefault(final RIB r) {
// Remote AS number defaults to our local AS
final AsNumber remoteAs;
if (getRemoteAs() != null) {
remoteAs = new AsNumber(getRemoteAs());
} else {
remoteAs = r.getLocalAs();
}
return remoteAs;
}
private List<BgpParameters> getTlvs(final RIB r) {
final List<BgpParameters> tlvs = new ArrayList<>();
final List<OptionalCapabilities> caps = new ArrayList<>();
caps.add(new OptionalCapabilitiesBuilder().setCParameters(new CParametersBuilder().setAs4BytesCapability(
new As4BytesCapabilityBuilder().setAsNumber(r.getLocalAs()).build()).build()).build());
caps.add(new OptionalCapabilitiesBuilder().setCParameters(new CParametersBuilder().addAugmentation(CParameters1.class,
new CParameters1Builder().setGracefulRestartCapability(new GracefulRestartCapabilityBuilder().build()).build()).build()).build());
if (getRouteRefresh()) {
caps.add(new OptionalCapabilitiesBuilder().setCParameters(MultiprotocolCapabilitiesUtil.RR_CAPABILITY).build());
}
if (!getAddPathDependency().isEmpty()) {
final List<AddressFamilies> addPathFamilies = filterAddPathDependency(getAddPathDependency());
caps.add(new OptionalCapabilitiesBuilder().setCParameters(new CParametersBuilder().addAugmentation(CParameters1.class,
new CParameters1Builder().setAddPathCapability(new AddPathCapabilityBuilder().setAddressFamilies(addPathFamilies).build()).build()).build()).build());
}
for (final BgpTableType t : getAdvertizedTableDependency()) {
if (!r.getLocalTables().contains(t)) {
LOG.info("RIB instance does not list {} in its local tables. Incoming data will be dropped.", t);
}
caps.add(new OptionalCapabilitiesBuilder().setCParameters(new CParametersBuilder().addAugmentation(CParameters1.class,
new CParameters1Builder().setMultiprotocolCapability(new MultiprotocolCapabilityBuilder(t).build()).build()).build()).build());
}
tlvs.add(new BgpParametersBuilder().setOptionalCapabilities(caps).build());
return tlvs;
}
private List<AddressFamilies> filterAddPathDependency(final List<AddressFamilies> addPathDependency) {
final Map<BgpTableType, AddressFamilies> filteredFamilies = new HashMap<BgpTableType, AddressFamilies>();
for (final AddressFamilies family : addPathDependency) {
final BgpTableType key = new BgpTableTypeImpl(family.getAfi(), family.getSafi());
if (!filteredFamilies.containsKey(key)) {
filteredFamilies.put(key, family);
} else {
LOG.info("Ignoring Add-path dependency {}", family);
}
}
return new ArrayList<AddressFamilies>(filteredFamilies.values());
}
public IpAddress getNormalizedHost() {
final IpAddress host = getHost();
if(host.getIpv6Address() != null){
return new IpAddress(Ipv6Util.getFullForm(host.getIpv6Address()));
}
return host;
}
private io.netty.util.concurrent.Future<Void> initiateConnection(final InetSocketAddress address, final Optional<Rfc2385Key> password, final BGPPeerRegistry registry) {
KeyMapping keys = null;
if (password.isPresent()) {
keys = new KeyMapping();
keys.put(address.getAddress(), password.get().getValue().getBytes(Charsets.US_ASCII));
}
final RIB rib = getRibDependency();
final Optional<KeyMapping> optionalKey = Optional.fromNullable(keys);
return rib.getDispatcher().createReconnectingClient(address, registry, rib.getTcpStrategyFactory(), optionalKey);
}
private BGPPeerRegistry getPeerRegistryBackwards() {
return getPeerRegistry() == null ? StrictBGPPeerRegistry.GLOBAL : getPeerRegistryDependency();
}
private static String peerName(final IpAddress host) {
if (host.getIpv4Address() != null) {
return host.getIpv4Address().getValue();
}
if (host.getIpv6Address() != null) {
return host.getIpv6Address().getValue();
}
return null;
}
private final class BGPPeerModuleTracker implements BGPConfigModuleTracker {
private final BGPOpenconfigMapper<BGPPeerInstanceConfiguration> neighborProvider;
private final BGPPeerInstanceConfiguration bgpPeerInstanceConfiguration;
public BGPPeerModuleTracker(final Optional<BGPOpenConfigProvider> openconfigProvider) {
if (openconfigProvider.isPresent()) {
this.neighborProvider = openconfigProvider.get().getOpenConfigMapper(BGPPeerInstanceConfiguration.class);
} else {
this.neighborProvider = null;
}
final InstanceConfigurationIdentifier identifier = new InstanceConfigurationIdentifier(getIdentifier().getInstanceName());
this.bgpPeerInstanceConfiguration = new BGPPeerInstanceConfiguration(identifier, Rev130715Util.getIpvAddress(getNormalizedHost()),
Rev130715Util.getPort(getPort().getValue()), getHoldtimer(), getPeerRole(), getInitiateConnection(),
getAdvertizedTableDependency(), Rev130715Util.getASNumber(getAsOrDefault(getRibDependency()).getValue()),
getOptionaPassword(getPassword()));
}
@Override
public void onInstanceCreate() {
if (this.neighborProvider != null) {
this.neighborProvider.writeConfiguration(this.bgpPeerInstanceConfiguration);
}
}
@Override
public void onInstanceClose() {
if (this.neighborProvider != null) {
this.neighborProvider.removeConfiguration(this.bgpPeerInstanceConfiguration);
}
}
}
private Optional<Rfc2385Key> getOptionaPassword(final Rfc2385Key password) {
return password != null && ! password.getValue().isEmpty() ? Optional.of(password) : Optional.<Rfc2385Key>absent();
}
}
| bgp/rib-impl/src/main/java/org/opendaylight/controller/config/yang/bgp/rib/impl/BGPPeerModule.java | /*
* Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
/**
* Generated file
* Generated from: yang module name: bgp-rib-impl yang module local name: bgp-peer
* Generated by: org.opendaylight.controller.config.yangjmxgenerator.plugin.JMXGenerator
* Generated at: Sat Jan 25 11:00:14 CET 2014
*
* Do not modify this file unless it is present under src/main directory
*/
package org.opendaylight.controller.config.yang.bgp.rib.impl;
import com.google.common.base.Charsets;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.net.InetAddresses;
import io.netty.util.concurrent.Future;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.opendaylight.controller.config.api.JmxAttributeValidationException;
import org.opendaylight.protocol.bgp.openconfig.spi.BGPConfigModuleTracker;
import org.opendaylight.protocol.bgp.openconfig.spi.BGPOpenConfigProvider;
import org.opendaylight.protocol.bgp.openconfig.spi.BGPOpenconfigMapper;
import org.opendaylight.protocol.bgp.openconfig.spi.InstanceConfigurationIdentifier;
import org.opendaylight.protocol.bgp.openconfig.spi.pojo.BGPPeerInstanceConfiguration;
import org.opendaylight.protocol.bgp.parser.spi.MultiprotocolCapabilitiesUtil;
import org.opendaylight.protocol.bgp.rib.impl.BGPPeer;
import org.opendaylight.protocol.bgp.rib.impl.StrictBGPPeerRegistry;
import org.opendaylight.protocol.bgp.rib.impl.spi.BGPPeerRegistry;
import org.opendaylight.protocol.bgp.rib.impl.spi.BGPSessionPreferences;
import org.opendaylight.protocol.bgp.rib.impl.spi.RIB;
import org.opendaylight.protocol.util.Ipv6Util;
import org.opendaylight.tcpmd5.api.KeyMapping;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.AsNumber;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpAddress;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.message.BgpParameters;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.message.BgpParametersBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.message.bgp.parameters.OptionalCapabilities;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.message.bgp.parameters.OptionalCapabilitiesBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.message.bgp.parameters.optional.capabilities.CParametersBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.message.bgp.parameters.optional.capabilities.c.parameters.As4BytesCapabilityBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.BgpTableType;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.CParameters1;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.CParameters1Builder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.open.bgp.parameters.optional.capabilities.c.parameters.AddPathCapabilityBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.open.bgp.parameters.optional.capabilities.c.parameters.GracefulRestartCapabilityBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.open.bgp.parameters.optional.capabilities.c.parameters.MultiprotocolCapabilityBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.open.bgp.parameters.optional.capabilities.c.parameters.add.path.capability.AddressFamilies;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.PeerRole;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bmp.monitor.rev150512.afi.safi.route.counter.AfiSafiKey;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.tcpmd5.cfg.rev140427.Rfc2385Key;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
*/
public final class BGPPeerModule extends org.opendaylight.controller.config.yang.bgp.rib.impl.AbstractBGPPeerModule {
private static final Logger LOG = LoggerFactory.getLogger(BGPPeerModule.class);
public BGPPeerModule(final org.opendaylight.controller.config.api.ModuleIdentifier identifier,
final org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) {
super(identifier, dependencyResolver);
}
public BGPPeerModule(final org.opendaylight.controller.config.api.ModuleIdentifier identifier,
final org.opendaylight.controller.config.api.DependencyResolver dependencyResolver, final BGPPeerModule oldModule,
final java.lang.AutoCloseable oldInstance) {
super(identifier, dependencyResolver, oldModule, oldInstance);
}
@Override
protected void customValidation() {
final IpAddress host = getHost();
JmxAttributeValidationException.checkNotNull(host, "value is not set.", hostJmxAttribute);
JmxAttributeValidationException.checkCondition(host.getIpv4Address() != null || host.getIpv6Address() != null,
"Unexpected host", hostJmxAttribute);
JmxAttributeValidationException.checkNotNull(getPort(), "value is not set.", portJmxAttribute);
if (getOptionaPassword(getPassword()).isPresent()) {
/*
* This is a nasty hack, but we don't have another clean solution. We cannot allow
* password being set if the injected dispatcher does not have the optional
* md5-server-channel-factory set.
*
* FIXME: this is a use case for Module interfaces, e.g. RibImplModule
* should something like isMd5ServerSupported()
*/
final RIBImplModuleMXBean ribProxy = this.dependencyResolver.newMXBeanProxy(getRib(), RIBImplModuleMXBean.class);
final BGPDispatcherImplModuleMXBean bgpDispatcherProxy = this.dependencyResolver.newMXBeanProxy(
ribProxy.getBgpDispatcher(), BGPDispatcherImplModuleMXBean.class);
final boolean isMd5Supported = bgpDispatcherProxy.getMd5ChannelFactory() != null;
JmxAttributeValidationException.checkCondition(isMd5Supported,
"Underlying dispatcher does not support MD5 clients", passwordJmxAttribute);
}
if (getPeerRole() != null) {
final boolean isNotPeerRoleInternal= getPeerRole() != PeerRole.Internal;
JmxAttributeValidationException.checkCondition(isNotPeerRoleInternal,
"Internal Peer Role is reserved for Application Peer use.", peerRoleJmxAttribute);
}
}
private InetSocketAddress createAddress() {
final IpAddress ip = getHost();
Preconditions.checkArgument(ip.getIpv4Address() != null || ip.getIpv6Address() != null, "Failed to handle host %s", ip);
if (ip.getIpv4Address() != null) {
return new InetSocketAddress(InetAddresses.forString(ip.getIpv4Address().getValue()), getPort().getValue());
}
return new InetSocketAddress(InetAddresses.forString(ip.getIpv6Address().getValue()), getPort().getValue());
}
@Override
public java.lang.AutoCloseable createInstance() {
final RIB r = getRibDependency();
final List<BgpParameters> tlvs = getTlvs(r);
final AsNumber remoteAs = getAsOrDefault(r);
final BGPSessionPreferences prefs = new BGPSessionPreferences(r.getLocalAs(), getHoldtimer(), r.getBgpIdentifier(), remoteAs, tlvs);
final BGPPeer bgpClientPeer;
final IpAddress host = getNormalizedHost();
if (getPeerRole() != null) {
bgpClientPeer = new BGPPeer(peerName(host), r, getPeerRole());
} else {
bgpClientPeer = new BGPPeer(peerName(host), r, PeerRole.Ibgp);
}
bgpClientPeer.registerRootRuntimeBean(getRootRuntimeBeanRegistratorWrapper());
getPeerRegistryBackwards().addPeer(host, bgpClientPeer, prefs);
final BGPPeerModuleTracker moduleTracker = new BGPPeerModuleTracker(r.getOpenConfigProvider());
moduleTracker.onInstanceCreate();
final CloseableNoEx peerCloseable = new CloseableNoEx() {
@Override
public void close() {
bgpClientPeer.close();
getPeerRegistryBackwards().removePeer(host);
moduleTracker.onInstanceClose();
}
};
// Initiate connection
if(getInitiateConnection()) {
final Future<Void> cf = initiateConnection(createAddress(), getOptionaPassword(getPassword()), getPeerRegistryBackwards());
return new CloseableNoEx() {
@Override
public void close() {
cf.cancel(true);
peerCloseable.close();
}
};
} else {
return peerCloseable;
}
}
private interface CloseableNoEx extends AutoCloseable {
@Override
void close();
}
private AsNumber getAsOrDefault(final RIB r) {
// Remote AS number defaults to our local AS
final AsNumber remoteAs;
if (getRemoteAs() != null) {
remoteAs = new AsNumber(getRemoteAs());
} else {
remoteAs = r.getLocalAs();
}
return remoteAs;
}
private List<BgpParameters> getTlvs(final RIB r) {
final List<BgpParameters> tlvs = new ArrayList<>();
final List<OptionalCapabilities> caps = new ArrayList<>();
caps.add(new OptionalCapabilitiesBuilder().setCParameters(new CParametersBuilder().setAs4BytesCapability(
new As4BytesCapabilityBuilder().setAsNumber(r.getLocalAs()).build()).build()).build());
caps.add(new OptionalCapabilitiesBuilder().setCParameters(new CParametersBuilder().addAugmentation(CParameters1.class,
new CParameters1Builder().setGracefulRestartCapability(new GracefulRestartCapabilityBuilder().build()).build()).build()).build());
if (getRouteRefresh()) {
caps.add(new OptionalCapabilitiesBuilder().setCParameters(MultiprotocolCapabilitiesUtil.RR_CAPABILITY).build());
}
if (!getAddPathDependency().isEmpty()) {
final List<AddressFamilies> addPathFamilies = filterAddPathDependency(getAddPathDependency());
caps.add(new OptionalCapabilitiesBuilder().setCParameters(new CParametersBuilder().addAugmentation(CParameters1.class,
new CParameters1Builder().setAddPathCapability(new AddPathCapabilityBuilder().setAddressFamilies(addPathFamilies).build()).build()).build()).build());
}
for (final BgpTableType t : getAdvertizedTableDependency()) {
if (!r.getLocalTables().contains(t)) {
LOG.info("RIB instance does not list {} in its local tables. Incoming data will be dropped.", t);
}
caps.add(new OptionalCapabilitiesBuilder().setCParameters(new CParametersBuilder().addAugmentation(CParameters1.class,
new CParameters1Builder().setMultiprotocolCapability(new MultiprotocolCapabilityBuilder(t).build()).build()).build()).build());
}
tlvs.add(new BgpParametersBuilder().setOptionalCapabilities(caps).build());
return tlvs;
}
private List<AddressFamilies> filterAddPathDependency(final List<AddressFamilies> addPathDependency) {
final Map<AfiSafiKey, AddressFamilies> filteredFamilies = new HashMap<AfiSafiKey, AddressFamilies>();
for (final AddressFamilies family : addPathDependency) {
final AfiSafiKey key = new AfiSafiKey(family.getAfi(), family.getSafi());
if (!filteredFamilies.containsKey(key)) {
filteredFamilies.put(key, family);
} else {
LOG.info("Ignoring Add-path dependency {}", family);
}
}
return new ArrayList<AddressFamilies>(filteredFamilies.values());
}
public IpAddress getNormalizedHost() {
final IpAddress host = getHost();
if(host.getIpv6Address() != null){
return new IpAddress(Ipv6Util.getFullForm(host.getIpv6Address()));
}
return host;
}
private io.netty.util.concurrent.Future<Void> initiateConnection(final InetSocketAddress address, final Optional<Rfc2385Key> password, final BGPPeerRegistry registry) {
KeyMapping keys = null;
if (password.isPresent()) {
keys = new KeyMapping();
keys.put(address.getAddress(), password.get().getValue().getBytes(Charsets.US_ASCII));
}
final RIB rib = getRibDependency();
final Optional<KeyMapping> optionalKey = Optional.fromNullable(keys);
return rib.getDispatcher().createReconnectingClient(address, registry, rib.getTcpStrategyFactory(), optionalKey);
}
private BGPPeerRegistry getPeerRegistryBackwards() {
return getPeerRegistry() == null ? StrictBGPPeerRegistry.GLOBAL : getPeerRegistryDependency();
}
private static String peerName(final IpAddress host) {
if (host.getIpv4Address() != null) {
return host.getIpv4Address().getValue();
}
if (host.getIpv6Address() != null) {
return host.getIpv6Address().getValue();
}
return null;
}
private final class BGPPeerModuleTracker implements BGPConfigModuleTracker {
private final BGPOpenconfigMapper<BGPPeerInstanceConfiguration> neighborProvider;
private final BGPPeerInstanceConfiguration bgpPeerInstanceConfiguration;
public BGPPeerModuleTracker(final Optional<BGPOpenConfigProvider> openconfigProvider) {
if (openconfigProvider.isPresent()) {
this.neighborProvider = openconfigProvider.get().getOpenConfigMapper(BGPPeerInstanceConfiguration.class);
} else {
this.neighborProvider = null;
}
final InstanceConfigurationIdentifier identifier = new InstanceConfigurationIdentifier(getIdentifier().getInstanceName());
this.bgpPeerInstanceConfiguration = new BGPPeerInstanceConfiguration(identifier, Rev130715Util.getIpvAddress(getNormalizedHost()),
Rev130715Util.getPort(getPort().getValue()), getHoldtimer(), getPeerRole(), getInitiateConnection(),
getAdvertizedTableDependency(), Rev130715Util.getASNumber(getAsOrDefault(getRibDependency()).getValue()),
getOptionaPassword(getPassword()));
}
@Override
public void onInstanceCreate() {
if (this.neighborProvider != null) {
this.neighborProvider.writeConfiguration(this.bgpPeerInstanceConfiguration);
}
}
@Override
public void onInstanceClose() {
if (this.neighborProvider != null) {
this.neighborProvider.removeConfiguration(this.bgpPeerInstanceConfiguration);
}
}
}
private Optional<Rfc2385Key> getOptionaPassword(final Rfc2385Key password) {
return password != null && ! password.getValue().isEmpty() ? Optional.of(password) : Optional.<Rfc2385Key>absent();
}
}
| BGPPeerModule type change
AfiSafiKey -> BgpTableType
Change-Id: I341dcdf01fc3e4919207844e93fcb7b679947f0a
Signed-off-by: Iveta Halanova <[email protected]>
| bgp/rib-impl/src/main/java/org/opendaylight/controller/config/yang/bgp/rib/impl/BGPPeerModule.java | BGPPeerModule type change | <ide><path>gp/rib-impl/src/main/java/org/opendaylight/controller/config/yang/bgp/rib/impl/BGPPeerModule.java
<ide> import org.opendaylight.protocol.bgp.openconfig.spi.BGPOpenconfigMapper;
<ide> import org.opendaylight.protocol.bgp.openconfig.spi.InstanceConfigurationIdentifier;
<ide> import org.opendaylight.protocol.bgp.openconfig.spi.pojo.BGPPeerInstanceConfiguration;
<add>import org.opendaylight.protocol.bgp.parser.BgpTableTypeImpl;
<ide> import org.opendaylight.protocol.bgp.parser.spi.MultiprotocolCapabilitiesUtil;
<ide> import org.opendaylight.protocol.bgp.rib.impl.BGPPeer;
<ide> import org.opendaylight.protocol.bgp.rib.impl.StrictBGPPeerRegistry;
<ide> import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.open.bgp.parameters.optional.capabilities.c.parameters.MultiprotocolCapabilityBuilder;
<ide> import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.open.bgp.parameters.optional.capabilities.c.parameters.add.path.capability.AddressFamilies;
<ide> import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.PeerRole;
<del>import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bmp.monitor.rev150512.afi.safi.route.counter.AfiSafiKey;
<ide> import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.tcpmd5.cfg.rev140427.Rfc2385Key;
<ide> import org.slf4j.Logger;
<ide> import org.slf4j.LoggerFactory;
<ide> }
<ide>
<ide> private List<AddressFamilies> filterAddPathDependency(final List<AddressFamilies> addPathDependency) {
<del> final Map<AfiSafiKey, AddressFamilies> filteredFamilies = new HashMap<AfiSafiKey, AddressFamilies>();
<add> final Map<BgpTableType, AddressFamilies> filteredFamilies = new HashMap<BgpTableType, AddressFamilies>();
<ide> for (final AddressFamilies family : addPathDependency) {
<del> final AfiSafiKey key = new AfiSafiKey(family.getAfi(), family.getSafi());
<add> final BgpTableType key = new BgpTableTypeImpl(family.getAfi(), family.getSafi());
<ide> if (!filteredFamilies.containsKey(key)) {
<ide> filteredFamilies.put(key, family);
<ide> } else { |
|
Java | apache-2.0 | 29dc5589a66e6f20603ea94a281398304717fcb1 | 0 | SyncFree/SwiftCloud,SyncFree/SwiftCloud,SyncFree/SwiftCloud,SyncFree/SwiftCloud | package sys.utils;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
/**
* A collection of convenience methods for dealing with threads.
*
* @author smduarte ([email protected])
*
*/
final public class Threading {
protected Threading() {
}
static public Thread newThread(boolean daemon, Runnable r) {
Thread res = new Thread(r);
res.setDaemon(daemon);
return res;
}
static public Thread newThread(Runnable r, boolean daemon) {
Thread res = new Thread(r);
res.setDaemon(daemon);
return res;
}
static public Thread newThread(String name, boolean daemon, Runnable r) {
Thread res = new Thread(r);
res.setName(Thread.currentThread() + "." + name);
res.setDaemon(daemon);
return res;
}
static public Thread newThread(String name, Runnable r, boolean daemon) {
Thread res = new Thread(r);
res.setName(Thread.currentThread() + "." + name);
res.setDaemon(daemon);
return res;
}
static public void sleep(long ms) {
try {
if (ms > 0)
Thread.sleep(ms);
} catch (InterruptedException x) {
x.printStackTrace();
}
}
static public void sleep(long ms, int ns) {
try {
if (ms > 0 || ns > 0)
Thread.sleep(ms, ns);
} catch (InterruptedException x) {
x.printStackTrace();
}
}
static public void waitOn(Object o) {
try {
o.wait();
} catch (InterruptedException x) {
x.printStackTrace();
}
}
static public void waitOn(Object o, long ms) {
try {
if (ms > 0)
o.wait(ms);
} catch (InterruptedException x) {
x.printStackTrace();
}
}
static public void notifyOn(Object o) {
o.notify();
}
static public void notifyAllOn(Object o) {
o.notifyAll();
}
static public void synchronizedWaitOn(Object o) {
synchronized (o) {
try {
o.wait();
} catch (InterruptedException x) {
x.printStackTrace();
}
}
}
static public void synchronizedWaitOn(Object o, long ms) {
synchronized (o) {
try {
o.wait(ms);
} catch (InterruptedException x) {
x.printStackTrace();
}
}
}
static public void synchronizedNotifyOn(Object o) {
synchronized (o) {
o.notify();
}
}
static public void synchronizedNotifyAllOn(Object o) {
synchronized (o) {
o.notifyAll();
}
}
synchronized public static void dumpAllThreadsTraces() {
Map<Thread, StackTraceElement[]> traces = Thread.getAllStackTraces();
loop: for (StackTraceElement[] trace : traces.values()) {
for (int j = 0; j < trace.length; j++)
if (trace[j].getClassName().startsWith("swift")) {
for (int k = j; k < trace.length; k++)
System.err.print(">>" + trace[k] + " ");
System.err.println();
continue loop;
}
}
}
static public ThreadFactory factory(final String name) {
return new ThreadFactory() {
int counter = 0;
String callerName = Thread.currentThread().getName();
@Override
public Thread newThread(Runnable target) {
Thread t = new Thread(target, callerName + "." + name + "-" + counter++);
t.setDaemon(true);
return t;
}
};
}
static public void awaitTermination(ExecutorService pool, int seconds) {
try {
pool.shutdown();
pool.awaitTermination(seconds, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void lock(Object id) {
ReentrantLock lock = locks.get(id), newLock;
if (lock == null) {
lock = locks.putIfAbsent(id, newLock = new ReentrantLock(true));
if (lock == null)
lock = newLock;
}
lock.lock();
}
public static void unlock(Object id) {
ReentrantLock lock = locks.get(id);
if (lock == null)
throw new RuntimeException("Unbalanced unlock for :" + id);
lock.unlock();
}
static ConcurrentHashMap<Object, ReentrantLock> locks = new ConcurrentHashMap<Object, ReentrantLock>();
}
| src-core/sys/utils/Threading.java | package sys.utils;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
/**
* A collection of convenience methods for dealing with threads.
*
* @author smduarte ([email protected])
*
*/
final public class Threading {
protected Threading() {
}
static public Thread newThread(boolean daemon, Runnable r) {
Thread res = new Thread(r);
res.setDaemon(daemon);
return res;
}
static public Thread newThread(Runnable r, boolean daemon) {
Thread res = new Thread(r);
res.setDaemon(daemon);
return res;
}
static public Thread newThread(String name, boolean daemon, Runnable r) {
Thread res = new Thread(r);
res.setName(Thread.currentThread() + "." + name);
res.setDaemon(daemon);
return res;
}
static public Thread newThread(String name, Runnable r, boolean daemon) {
Thread res = new Thread(r);
res.setName(Thread.currentThread() + "." + name);
res.setDaemon(daemon);
return res;
}
static public void sleep(long ms) {
try {
if (ms > 0)
Thread.sleep(ms);
} catch (InterruptedException x) {
x.printStackTrace();
}
}
static public void sleep(long ms, int ns) {
try {
if (ms > 0 || ns > 0)
Thread.sleep(ms, ns);
} catch (InterruptedException x) {
x.printStackTrace();
}
}
static public void waitOn(Object o) {
try {
o.wait();
} catch (InterruptedException x) {
x.printStackTrace();
}
}
static public void waitOn(Object o, long ms) {
try {
if (ms > 0)
o.wait(ms);
} catch (InterruptedException x) {
x.printStackTrace();
}
}
static public void notifyOn(Object o) {
o.notify();
}
static public void notifyAllOn(Object o) {
o.notifyAll();
}
static public void synchronizedWaitOn(Object o) {
synchronized (o) {
try {
o.wait();
} catch (InterruptedException x) {
x.printStackTrace();
}
}
}
static public void synchronizedWaitOn(Object o, long ms) {
synchronized (o) {
try {
o.wait(ms);
} catch (InterruptedException x) {
x.printStackTrace();
}
}
}
static public void synchronizedNotifyOn(Object o) {
synchronized (o) {
o.notify();
}
}
static public void synchronizedNotifyAllOn(Object o) {
synchronized (o) {
o.notifyAll();
}
}
synchronized public static void dumpAllThreadsTraces() {
Map<Thread, StackTraceElement[]> traces = Thread.getAllStackTraces();
loop: for (StackTraceElement[] trace : traces.values()) {
for (int j = 0; j < trace.length; j++)
if (trace[j].getClassName().startsWith("swift")) {
for (int k = j; k < trace.length; k++)
System.err.print(">>" + trace[k] + " ");
System.err.println();
continue loop;
}
}
}
static public ThreadFactory factory(final String name) {
return new ThreadFactory() {
int counter = 0;
String callerName = Thread.currentThread().getName();
@Override
public Thread newThread(Runnable target) {
Thread t = new Thread(target, callerName + "." + name + "-" + counter++);
t.setDaemon(true);
return t;
}
};
}
static public void awaitTermination(ExecutorService pool, int seconds) {
try {
pool.shutdown();
pool.awaitTermination(seconds, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void lock(Object id) {
ReentrantLock lock;
synchronized (locks) {
lock = locks.get(id);
if (lock == null)
locks.put(id, lock = new ReentrantLock(true));
}
lock.lock();
}
public static void unlock(Object id) {
ReentrantLock lock;
do {
synchronized (locks) {
lock = locks.get(id);
if (lock == null) {
Threading.sleep(100);
throw new RuntimeException("Unbalanced unlock for :" + id);
}
}
} while (lock == null);
lock.unlock();
}
static Map<Object, ReentrantLock> locks = new HashMap<Object, ReentrantLock>();
}
| Re-implements Locking support in sys.utils to use ConcurrentHashMap | src-core/sys/utils/Threading.java | Re-implements Locking support in sys.utils to use ConcurrentHashMap | <ide><path>rc-core/sys/utils/Threading.java
<ide> package sys.utils;
<ide>
<del>import java.util.HashMap;
<ide> import java.util.Map;
<add>import java.util.concurrent.ConcurrentHashMap;
<ide> import java.util.concurrent.ExecutorService;
<ide> import java.util.concurrent.ThreadFactory;
<ide> import java.util.concurrent.TimeUnit;
<ide> }
<ide>
<ide> public static void lock(Object id) {
<del> ReentrantLock lock;
<del> synchronized (locks) {
<del> lock = locks.get(id);
<add> ReentrantLock lock = locks.get(id), newLock;
<add> if (lock == null) {
<add> lock = locks.putIfAbsent(id, newLock = new ReentrantLock(true));
<ide> if (lock == null)
<del> locks.put(id, lock = new ReentrantLock(true));
<add> lock = newLock;
<ide> }
<ide> lock.lock();
<ide> }
<ide>
<ide> public static void unlock(Object id) {
<del> ReentrantLock lock;
<del> do {
<del> synchronized (locks) {
<del> lock = locks.get(id);
<del> if (lock == null) {
<del> Threading.sleep(100);
<del> throw new RuntimeException("Unbalanced unlock for :" + id);
<del> }
<del> }
<del> } while (lock == null);
<add> ReentrantLock lock = locks.get(id);
<add> if (lock == null)
<add> throw new RuntimeException("Unbalanced unlock for :" + id);
<add>
<ide> lock.unlock();
<ide> }
<ide>
<del> static Map<Object, ReentrantLock> locks = new HashMap<Object, ReentrantLock>();
<add> static ConcurrentHashMap<Object, ReentrantLock> locks = new ConcurrentHashMap<Object, ReentrantLock>();
<ide> } |
|
Java | apache-2.0 | 9e0496bb27e0d111d781cb02ebb4ac1eeb4fb41a | 0 | linkedin/pinot,linkedin/pinot,linkedin/pinot,linkedin/pinot,linkedin/pinot | /**
* 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.pinot.broker.requesthandler;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yammer.metrics.core.MetricsRegistry;
import java.util.Random;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.pinot.broker.api.RequestStatistics;
import org.apache.pinot.common.metrics.BrokerMetrics;
import org.apache.pinot.common.response.broker.BrokerResponseNative;
import org.apache.pinot.common.utils.DataSchema;
import org.apache.pinot.spi.utils.BytesUtils;
import org.apache.pinot.sql.parsers.CalciteSqlCompiler;
import org.testng.Assert;
import org.testng.annotations.Test;
public class LiteralOnlyBrokerRequestTest {
private static final Random RANDOM = new Random(System.currentTimeMillis());
private static final CalciteSqlCompiler SQL_COMPILER = new CalciteSqlCompiler();
@Test
public void testStringLiteralBrokerRequestFromSQL() {
Assert.assertTrue(BaseBrokerRequestHandler.isLiteralOnlyQuery(SQL_COMPILER.compileToBrokerRequest("SELECT 'a'")));
Assert.assertTrue(
BaseBrokerRequestHandler.isLiteralOnlyQuery(SQL_COMPILER.compileToBrokerRequest("SELECT 'a', 'b'")));
Assert.assertTrue(
BaseBrokerRequestHandler.isLiteralOnlyQuery(SQL_COMPILER.compileToBrokerRequest("SELECT 'a' FROM myTable")));
Assert.assertTrue(BaseBrokerRequestHandler
.isLiteralOnlyQuery(SQL_COMPILER.compileToBrokerRequest("SELECT 'a', 'b' FROM myTable")));
}
@Test
public void testSelectStarBrokerRequestFromSQL() {
Assert.assertTrue(BaseBrokerRequestHandler.isLiteralOnlyQuery(SQL_COMPILER.compileToBrokerRequest("SELECT '*'")));
Assert.assertTrue(
BaseBrokerRequestHandler.isLiteralOnlyQuery(SQL_COMPILER.compileToBrokerRequest("SELECT '*' FROM myTable")));
Assert.assertFalse(BaseBrokerRequestHandler.isLiteralOnlyQuery(SQL_COMPILER.compileToBrokerRequest("SELECT *")));
Assert.assertFalse(
BaseBrokerRequestHandler.isLiteralOnlyQuery(SQL_COMPILER.compileToBrokerRequest("SELECT * FROM myTable")));
}
@Test
public void testNumberLiteralBrokerRequestFromSQL() {
Assert.assertTrue(BaseBrokerRequestHandler.isLiteralOnlyQuery(SQL_COMPILER.compileToBrokerRequest("SELECT 1")));
Assert.assertTrue(
BaseBrokerRequestHandler.isLiteralOnlyQuery(SQL_COMPILER.compileToBrokerRequest("SELECT 1, '2', 3")));
Assert.assertTrue(
BaseBrokerRequestHandler.isLiteralOnlyQuery(SQL_COMPILER.compileToBrokerRequest("SELECT 1 FROM myTable")));
Assert.assertTrue(BaseBrokerRequestHandler
.isLiteralOnlyQuery(SQL_COMPILER.compileToBrokerRequest("SELECT 1, '2', 3 FROM myTable")));
}
@Test
public void testLiteralOnlyTransformBrokerRequestFromSQL() {
Assert.assertTrue(BaseBrokerRequestHandler.isLiteralOnlyQuery(SQL_COMPILER.compileToBrokerRequest("SELECT now()")));
Assert.assertTrue(BaseBrokerRequestHandler.isLiteralOnlyQuery(
SQL_COMPILER.compileToBrokerRequest("SELECT now(), fromDateTime('2020-01-01 UTC', 'yyyy-MM-dd z')")));
Assert.assertTrue(
BaseBrokerRequestHandler.isLiteralOnlyQuery(SQL_COMPILER.compileToBrokerRequest("SELECT now() FROM myTable")));
Assert.assertTrue(BaseBrokerRequestHandler.isLiteralOnlyQuery(SQL_COMPILER
.compileToBrokerRequest("SELECT now(), fromDateTime('2020-01-01 UTC', 'yyyy-MM-dd z') FROM myTable")));
}
@Test
public void testLiteralOnlyWithAsBrokerRequestFromSQL() {
Assert.assertTrue(BaseBrokerRequestHandler.isLiteralOnlyQuery(SQL_COMPILER.compileToBrokerRequest(
"SELECT now() AS currentTs, fromDateTime('2020-01-01 UTC', 'yyyy-MM-dd z') AS firstDayOf2020")));
}
@Test
public void testBrokerRequestHandler()
throws Exception {
SingleConnectionBrokerRequestHandler requestHandler =
new SingleConnectionBrokerRequestHandler(new PropertiesConfiguration(), null, null, null,
new BrokerMetrics("", new MetricsRegistry(), false), null);
long randNum = RANDOM.nextLong();
byte[] randBytes = new byte[12];
RANDOM.nextBytes(randBytes);
String ranStr = BytesUtils.toHexString(randBytes);
JsonNode request = new ObjectMapper().readTree(String.format("{\"sql\":\"SELECT %d, '%s'\"}", randNum, ranStr));
RequestStatistics requestStats = new RequestStatistics();
BrokerResponseNative brokerResponse =
(BrokerResponseNative) requestHandler.handleRequest(request, null, requestStats);
Assert.assertEquals(brokerResponse.getResultTable().getDataSchema().getColumnName(0), String.format("%d", randNum));
Assert.assertEquals(brokerResponse.getResultTable().getDataSchema().getColumnDataType(0),
DataSchema.ColumnDataType.LONG);
Assert.assertEquals(brokerResponse.getResultTable().getDataSchema().getColumnName(1), ranStr);
Assert.assertEquals(brokerResponse.getResultTable().getDataSchema().getColumnDataType(1),
DataSchema.ColumnDataType.STRING);
Assert.assertEquals(brokerResponse.getResultTable().getRows().size(), 1);
Assert.assertEquals(brokerResponse.getResultTable().getRows().get(0).length, 2);
Assert.assertEquals(brokerResponse.getResultTable().getRows().get(0)[0], randNum);
Assert.assertEquals(brokerResponse.getResultTable().getRows().get(0)[1], ranStr);
Assert.assertEquals(brokerResponse.getTotalDocs(), 0);
}
@Test
public void testBrokerRequestHandlerWithAsFunction()
throws Exception {
SingleConnectionBrokerRequestHandler requestHandler =
new SingleConnectionBrokerRequestHandler(new PropertiesConfiguration(), null, null, null,
new BrokerMetrics("", new MetricsRegistry(), false), null);
long currentTsMin = System.currentTimeMillis();
JsonNode request = new ObjectMapper().readTree(
"{\"sql\":\"SELECT now() as currentTs, fromDateTime('2020-01-01 UTC', 'yyyy-MM-dd z') as firstDayOf2020\"}");
RequestStatistics requestStats = new RequestStatistics();
BrokerResponseNative brokerResponse =
(BrokerResponseNative) requestHandler.handleRequest(request, null, requestStats);
long currentTsMax = System.currentTimeMillis();
Assert.assertEquals(brokerResponse.getResultTable().getDataSchema().getColumnName(0), "currentTs");
Assert.assertEquals(brokerResponse.getResultTable().getDataSchema().getColumnDataType(0),
DataSchema.ColumnDataType.LONG);
Assert.assertEquals(brokerResponse.getResultTable().getDataSchema().getColumnName(1), "firstDayOf2020");
Assert.assertEquals(brokerResponse.getResultTable().getDataSchema().getColumnDataType(1),
DataSchema.ColumnDataType.LONG);
Assert.assertEquals(brokerResponse.getResultTable().getRows().size(), 1);
Assert.assertEquals(brokerResponse.getResultTable().getRows().get(0).length, 2);
Assert.assertTrue(Long.parseLong(brokerResponse.getResultTable().getRows().get(0)[0].toString()) > currentTsMin);
Assert.assertTrue(Long.parseLong(brokerResponse.getResultTable().getRows().get(0)[0].toString()) < currentTsMax);
Assert.assertEquals(brokerResponse.getResultTable().getRows().get(0)[1], 1577836800000L);
Assert.assertEquals(brokerResponse.getTotalDocs(), 0);
}
}
| pinot-broker/src/test/java/org/apache/pinot/broker/requesthandler/LiteralOnlyBrokerRequestTest.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.pinot.broker.requesthandler;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yammer.metrics.core.MetricsRegistry;
import java.util.Random;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.pinot.broker.api.RequestStatistics;
import org.apache.pinot.common.metrics.BrokerMetrics;
import org.apache.pinot.common.response.broker.BrokerResponseNative;
import org.apache.pinot.common.utils.DataSchema;
import org.apache.pinot.spi.utils.BytesUtils;
import org.apache.pinot.sql.parsers.CalciteSqlCompiler;
import org.testng.Assert;
import org.testng.annotations.Test;
public class LiteralOnlyBrokerRequestTest {
private static final Random RANDOM = new Random(System.currentTimeMillis());
private static final CalciteSqlCompiler SQL_COMPILER = new CalciteSqlCompiler();
@Test
public void testStringLiteralBrokerRequestFromSQL() {
Assert.assertTrue(BaseBrokerRequestHandler.isLiteralOnlyQuery(SQL_COMPILER.compileToBrokerRequest("SELECT 'a'")));
Assert.assertTrue(
BaseBrokerRequestHandler.isLiteralOnlyQuery(SQL_COMPILER.compileToBrokerRequest("SELECT 'a', 'b'")));
Assert.assertTrue(
BaseBrokerRequestHandler.isLiteralOnlyQuery(SQL_COMPILER.compileToBrokerRequest("SELECT 'a' FROM myTable")));
Assert.assertTrue(BaseBrokerRequestHandler
.isLiteralOnlyQuery(SQL_COMPILER.compileToBrokerRequest("SELECT 'a', 'b' FROM myTable")));
}
@Test
public void testSelectStarBrokerRequestFromSQL() {
Assert.assertTrue(BaseBrokerRequestHandler.isLiteralOnlyQuery(SQL_COMPILER.compileToBrokerRequest("SELECT '*'")));
Assert.assertTrue(BaseBrokerRequestHandler
.isLiteralOnlyQuery(SQL_COMPILER.compileToBrokerRequest("SELECT '*' FROM myTable")));
Assert.assertFalse(
BaseBrokerRequestHandler.isLiteralOnlyQuery(SQL_COMPILER.compileToBrokerRequest("SELECT *")));
Assert.assertFalse(
BaseBrokerRequestHandler.isLiteralOnlyQuery(SQL_COMPILER.compileToBrokerRequest("SELECT * FROM myTable")));
}
@Test
public void testNumberLiteralBrokerRequestFromSQL() {
Assert.assertTrue(BaseBrokerRequestHandler.isLiteralOnlyQuery(SQL_COMPILER.compileToBrokerRequest("SELECT 1")));
Assert.assertTrue(
BaseBrokerRequestHandler.isLiteralOnlyQuery(SQL_COMPILER.compileToBrokerRequest("SELECT 1, '2', 3")));
Assert.assertTrue(
BaseBrokerRequestHandler.isLiteralOnlyQuery(SQL_COMPILER.compileToBrokerRequest("SELECT 1 FROM myTable")));
Assert.assertTrue(BaseBrokerRequestHandler
.isLiteralOnlyQuery(SQL_COMPILER.compileToBrokerRequest("SELECT 1, '2', 3 FROM myTable")));
}
@Test
public void testLiteralOnlyTransformBrokerRequestFromSQL() {
Assert.assertTrue(BaseBrokerRequestHandler.isLiteralOnlyQuery(SQL_COMPILER.compileToBrokerRequest("SELECT now()")));
Assert.assertTrue(BaseBrokerRequestHandler.isLiteralOnlyQuery(
SQL_COMPILER.compileToBrokerRequest("SELECT now(), fromDateTime('2020-01-01 UTC', 'yyyy-MM-dd z')")));
Assert.assertTrue(
BaseBrokerRequestHandler.isLiteralOnlyQuery(SQL_COMPILER.compileToBrokerRequest("SELECT now() FROM myTable")));
Assert.assertTrue(BaseBrokerRequestHandler.isLiteralOnlyQuery(SQL_COMPILER
.compileToBrokerRequest("SELECT now(), fromDateTime('2020-01-01 UTC', 'yyyy-MM-dd z') FROM myTable")));
}
@Test
public void testLiteralOnlyWithAsBrokerRequestFromSQL() {
Assert.assertTrue(BaseBrokerRequestHandler.isLiteralOnlyQuery(SQL_COMPILER.compileToBrokerRequest(
"SELECT now() AS currentTs, fromDateTime('2020-01-01 UTC', 'yyyy-MM-dd z') AS firstDayOf2020")));
}
@Test
public void testBrokerRequestHandler()
throws Exception {
SingleConnectionBrokerRequestHandler requestHandler =
new SingleConnectionBrokerRequestHandler(new PropertiesConfiguration(), null, null, null,
new BrokerMetrics("", new MetricsRegistry(), false), null);
long randNum = RANDOM.nextLong();
byte[] randBytes = new byte[12];
RANDOM.nextBytes(randBytes);
String ranStr = BytesUtils.toHexString(randBytes);
JsonNode request = new ObjectMapper().readTree(String.format("{\"sql\":\"SELECT %d, '%s'\"}", randNum, ranStr));
RequestStatistics requestStats = new RequestStatistics();
BrokerResponseNative brokerResponse =
(BrokerResponseNative) requestHandler.handleRequest(request, null, requestStats);
System.out.println("brokerResponse = " + brokerResponse.toJsonString());
Assert.assertEquals(brokerResponse.getResultTable().getDataSchema().getColumnName(0), String.format("%d", randNum));
Assert.assertEquals(brokerResponse.getResultTable().getDataSchema().getColumnDataType(0),
DataSchema.ColumnDataType.LONG);
Assert.assertEquals(brokerResponse.getResultTable().getDataSchema().getColumnName(1), ranStr);
Assert.assertEquals(brokerResponse.getResultTable().getDataSchema().getColumnDataType(1),
DataSchema.ColumnDataType.STRING);
Assert.assertEquals(brokerResponse.getResultTable().getRows().size(), 1);
Assert.assertEquals(brokerResponse.getResultTable().getRows().get(0).length, 2);
Assert.assertEquals(brokerResponse.getResultTable().getRows().get(0)[0], randNum);
Assert.assertEquals(brokerResponse.getResultTable().getRows().get(0)[1], ranStr);
Assert.assertEquals(brokerResponse.getTotalDocs(), 0);
}
@Test
public void testBrokerRequestHandlerWithAsFunction()
throws Exception {
SingleConnectionBrokerRequestHandler requestHandler =
new SingleConnectionBrokerRequestHandler(new PropertiesConfiguration(), null, null, null,
new BrokerMetrics("", new MetricsRegistry(), false), null);
long currentTsMin = System.currentTimeMillis();
JsonNode request = new ObjectMapper().readTree(
"{\"sql\":\"SELECT now() as currentTs, fromDateTime('2020-01-01 UTC', 'yyyy-MM-dd z') as firstDayOf2020\"}");
RequestStatistics requestStats = new RequestStatistics();
BrokerResponseNative brokerResponse =
(BrokerResponseNative) requestHandler.handleRequest(request, null, requestStats);
long currentTsMax = System.currentTimeMillis();
System.out.println("brokerResponse = " + brokerResponse.toJsonString());
Assert.assertEquals(brokerResponse.getResultTable().getDataSchema().getColumnName(0), "currentTs");
Assert.assertEquals(brokerResponse.getResultTable().getDataSchema().getColumnDataType(0),
DataSchema.ColumnDataType.LONG);
Assert.assertEquals(brokerResponse.getResultTable().getDataSchema().getColumnName(1), "firstDayOf2020");
Assert.assertEquals(brokerResponse.getResultTable().getDataSchema().getColumnDataType(1),
DataSchema.ColumnDataType.LONG);
Assert.assertEquals(brokerResponse.getResultTable().getRows().size(), 1);
Assert.assertEquals(brokerResponse.getResultTable().getRows().get(0).length, 2);
Assert.assertTrue(Long.parseLong(brokerResponse.getResultTable().getRows().get(0)[0].toString()) > currentTsMin);
Assert.assertTrue(Long.parseLong(brokerResponse.getResultTable().getRows().get(0)[0].toString()) < currentTsMax);
Assert.assertEquals(brokerResponse.getResultTable().getRows().get(0)[1], 1577836800000L);
Assert.assertEquals(brokerResponse.getTotalDocs(), 0);
}
}
| (Minor) Remove the console output in LiteralOnlyBrokerRequestTest (#5585)
| pinot-broker/src/test/java/org/apache/pinot/broker/requesthandler/LiteralOnlyBrokerRequestTest.java | (Minor) Remove the console output in LiteralOnlyBrokerRequestTest (#5585) | <ide><path>inot-broker/src/test/java/org/apache/pinot/broker/requesthandler/LiteralOnlyBrokerRequestTest.java
<ide> @Test
<ide> public void testSelectStarBrokerRequestFromSQL() {
<ide> Assert.assertTrue(BaseBrokerRequestHandler.isLiteralOnlyQuery(SQL_COMPILER.compileToBrokerRequest("SELECT '*'")));
<del> Assert.assertTrue(BaseBrokerRequestHandler
<del> .isLiteralOnlyQuery(SQL_COMPILER.compileToBrokerRequest("SELECT '*' FROM myTable")));
<del> Assert.assertFalse(
<del> BaseBrokerRequestHandler.isLiteralOnlyQuery(SQL_COMPILER.compileToBrokerRequest("SELECT *")));
<add> Assert.assertTrue(
<add> BaseBrokerRequestHandler.isLiteralOnlyQuery(SQL_COMPILER.compileToBrokerRequest("SELECT '*' FROM myTable")));
<add> Assert.assertFalse(BaseBrokerRequestHandler.isLiteralOnlyQuery(SQL_COMPILER.compileToBrokerRequest("SELECT *")));
<ide> Assert.assertFalse(
<ide> BaseBrokerRequestHandler.isLiteralOnlyQuery(SQL_COMPILER.compileToBrokerRequest("SELECT * FROM myTable")));
<ide> }
<ide> RequestStatistics requestStats = new RequestStatistics();
<ide> BrokerResponseNative brokerResponse =
<ide> (BrokerResponseNative) requestHandler.handleRequest(request, null, requestStats);
<del> System.out.println("brokerResponse = " + brokerResponse.toJsonString());
<ide> Assert.assertEquals(brokerResponse.getResultTable().getDataSchema().getColumnName(0), String.format("%d", randNum));
<ide> Assert.assertEquals(brokerResponse.getResultTable().getDataSchema().getColumnDataType(0),
<ide> DataSchema.ColumnDataType.LONG);
<ide> BrokerResponseNative brokerResponse =
<ide> (BrokerResponseNative) requestHandler.handleRequest(request, null, requestStats);
<ide> long currentTsMax = System.currentTimeMillis();
<del> System.out.println("brokerResponse = " + brokerResponse.toJsonString());
<ide> Assert.assertEquals(brokerResponse.getResultTable().getDataSchema().getColumnName(0), "currentTs");
<ide> Assert.assertEquals(brokerResponse.getResultTable().getDataSchema().getColumnDataType(0),
<ide> DataSchema.ColumnDataType.LONG); |
|
Java | apache-2.0 | 3d71d764d186ee194ce5864fde2f706c6e0821e8 | 0 | apache/isis,apache/isis,apache/isis,apache/isis,apache/isis,apache/isis | /*
* 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.isis.extensions.secman.model.facets;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.inject.Inject;
import javax.inject.Provider;
import org.springframework.stereotype.Component;
import org.apache.isis.applib.services.inject.ServiceInjector;
import org.apache.isis.applib.services.queryresultscache.QueryResultsCache;
import org.apache.isis.applib.services.registry.ServiceRegistry;
import org.apache.isis.applib.services.user.UserService;
import org.apache.isis.core.metamodel.facetapi.FacetHolder;
import org.apache.isis.core.metamodel.facetapi.FacetUtil;
import org.apache.isis.core.metamodel.facetapi.MetaModelRefiner;
import org.apache.isis.core.metamodel.postprocessors.ObjectSpecificationPostProcessorAbstract;
import org.apache.isis.core.metamodel.progmodel.ProgrammingModel;
import org.apache.isis.core.metamodel.spec.ObjectSpecification;
import org.apache.isis.core.metamodel.spec.feature.ObjectAction;
import org.apache.isis.core.metamodel.spec.feature.ObjectActionParameter;
import org.apache.isis.core.metamodel.spec.feature.ObjectFeature;
import org.apache.isis.core.metamodel.spec.feature.OneToManyAssociation;
import org.apache.isis.core.metamodel.spec.feature.OneToOneAssociation;
import org.apache.isis.extensions.secman.api.tenancy.ApplicationTenancyEvaluator;
import org.apache.isis.extensions.secman.api.user.ApplicationUserRepository;
import lombok.Getter;
import lombok.val;
public class TenantedAuthorizationPostProcessor
extends ObjectSpecificationPostProcessorAbstract {
@Component
public static class Register implements MetaModelRefiner {
@Override
public void refineProgrammingModel(ProgrammingModel programmingModel) {
programmingModel.addPostProcessor(
ProgrammingModel.PostProcessingOrder.A2_AFTER_BUILTIN,
TenantedAuthorizationPostProcessor.class);
}
}
@Override
public void doPostProcess(ObjectSpecification objectSpecification) {
FacetUtil.addFacet(createFacet(objectSpecification.getCorrespondingClass(), objectSpecification));
}
@Override
protected void doPostProcess(ObjectSpecification objectSpecification, ObjectAction act) {
addFacetTo(objectSpecification, act);
}
@Override
protected void doPostProcess(ObjectSpecification objectSpecification, ObjectAction objectAction, ObjectActionParameter param) {
// no-op
}
@Override
protected void doPostProcess(ObjectSpecification objectSpecification, OneToOneAssociation prop) {
addFacetTo(objectSpecification, prop);
}
@Override
protected void doPostProcess(ObjectSpecification objectSpecification, OneToManyAssociation coll) {
addFacetTo(objectSpecification, coll);
}
private void addFacetTo(ObjectSpecification specification, ObjectFeature objectFeature) {
FacetUtil.addFacet(createFacet(specification.getCorrespondingClass(), objectFeature));
}
public static class QueryResultsCacheProviderHolder {
@Inject @Getter private Provider<QueryResultsCache> queryResultsCacheProvider;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private TenantedAuthorizationFacetDefault createFacet(
final Class<?> cls,
final FacetHolder holder) {
val evaluators = serviceRegistry
.select(ApplicationTenancyEvaluator.class)
.stream()
.filter(evaluator -> evaluator.handles(cls))
.collect(Collectors.<ApplicationTenancyEvaluator>toList());
if(evaluators.isEmpty()) {
return null;
}
val queryResultsCacheProvider =
serviceInjector
.injectServicesInto(new QueryResultsCacheProviderHolder())
.getQueryResultsCacheProvider();
final Optional<TenantedAuthorizationFacetDefault> facetIfAny = serviceRegistry.lookupService(ApplicationUserRepository.class)
.map(userRepository ->
new TenantedAuthorizationFacetDefault(
evaluators, userRepository,
queryResultsCacheProvider, userService,
holder));
return facetIfAny
.orElse(null);
}
@Inject ServiceRegistry serviceRegistry;
@Inject ServiceInjector serviceInjector;
@Inject UserService userService;
}
| extensions/security/secman/model/src/main/java/org/apache/isis/extensions/secman/model/facets/TenantedAuthorizationPostProcessor.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.isis.extensions.secman.model.facets;
import java.util.stream.Collectors;
import javax.inject.Inject;
import javax.inject.Provider;
import org.springframework.stereotype.Component;
import org.apache.isis.applib.services.inject.ServiceInjector;
import org.apache.isis.applib.services.queryresultscache.QueryResultsCache;
import org.apache.isis.applib.services.registry.ServiceRegistry;
import org.apache.isis.applib.services.user.UserService;
import org.apache.isis.core.metamodel.facetapi.FacetHolder;
import org.apache.isis.core.metamodel.facetapi.FacetUtil;
import org.apache.isis.core.metamodel.facetapi.MetaModelRefiner;
import org.apache.isis.core.metamodel.postprocessors.ObjectSpecificationPostProcessorAbstract;
import org.apache.isis.core.metamodel.progmodel.ProgrammingModel;
import org.apache.isis.core.metamodel.spec.ObjectSpecification;
import org.apache.isis.core.metamodel.spec.feature.ObjectAction;
import org.apache.isis.core.metamodel.spec.feature.ObjectActionParameter;
import org.apache.isis.core.metamodel.spec.feature.ObjectFeature;
import org.apache.isis.core.metamodel.spec.feature.OneToManyAssociation;
import org.apache.isis.core.metamodel.spec.feature.OneToOneAssociation;
import org.apache.isis.extensions.secman.api.tenancy.ApplicationTenancyEvaluator;
import org.apache.isis.extensions.secman.api.user.ApplicationUserRepository;
import lombok.Getter;
import lombok.val;
public class TenantedAuthorizationPostProcessor
extends ObjectSpecificationPostProcessorAbstract {
@Component
public static class Register implements MetaModelRefiner {
@Override
public void refineProgrammingModel(ProgrammingModel programmingModel) {
programmingModel.addPostProcessor(
ProgrammingModel.PostProcessingOrder.A2_AFTER_BUILTIN,
TenantedAuthorizationPostProcessor.class);
}
}
@Override
public void doPostProcess(ObjectSpecification objectSpecification) {
FacetUtil.addFacet(createFacet(objectSpecification.getCorrespondingClass(), objectSpecification));
}
@Override
protected void doPostProcess(ObjectSpecification objectSpecification, ObjectAction act) {
addFacetTo(objectSpecification, act);
}
@Override
protected void doPostProcess(ObjectSpecification objectSpecification, ObjectAction objectAction, ObjectActionParameter param) {
// no-op
}
@Override
protected void doPostProcess(ObjectSpecification objectSpecification, OneToOneAssociation prop) {
addFacetTo(objectSpecification, prop);
}
@Override
protected void doPostProcess(ObjectSpecification objectSpecification, OneToManyAssociation coll) {
addFacetTo(objectSpecification, coll);
}
private void addFacetTo(ObjectSpecification specification, ObjectFeature objectFeature) {
FacetUtil.addFacet(createFacet(specification.getCorrespondingClass(), objectFeature));
}
public static class QueryResultsCacheProviderHolder {
@Inject @Getter private Provider<QueryResultsCache> queryResultsCacheProvider;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private TenantedAuthorizationFacetDefault createFacet(
final Class<?> cls,
final FacetHolder holder) {
val evaluators = serviceRegistry
.select(ApplicationTenancyEvaluator.class)
.stream()
.filter(evaluator -> evaluator.handles(cls))
.collect(Collectors.<ApplicationTenancyEvaluator>toList());
if(evaluators.isEmpty()) {
return null;
}
val queryResultsCacheProvider =
serviceInjector
.injectServicesInto(new QueryResultsCacheProviderHolder())
.getQueryResultsCacheProvider();
return serviceRegistry.lookupService(ApplicationUserRepository.class)
.map(userRepository ->
new TenantedAuthorizationFacetDefault(
evaluators, userRepository,
queryResultsCacheProvider, userService,
holder))
.orElse(null);
}
@Inject ServiceRegistry serviceRegistry;
@Inject ServiceInjector serviceInjector;
@Inject UserService userService;
}
| ISIS-2619: fixes code compilation issue
| extensions/security/secman/model/src/main/java/org/apache/isis/extensions/secman/model/facets/TenantedAuthorizationPostProcessor.java | ISIS-2619: fixes code compilation issue | <ide><path>xtensions/security/secman/model/src/main/java/org/apache/isis/extensions/secman/model/facets/TenantedAuthorizationPostProcessor.java
<ide> */
<ide> package org.apache.isis.extensions.secman.model.facets;
<ide>
<add>import java.util.Optional;
<ide> import java.util.stream.Collectors;
<ide>
<ide> import javax.inject.Inject;
<ide> .injectServicesInto(new QueryResultsCacheProviderHolder())
<ide> .getQueryResultsCacheProvider();
<ide>
<del> return serviceRegistry.lookupService(ApplicationUserRepository.class)
<add> final Optional<TenantedAuthorizationFacetDefault> facetIfAny = serviceRegistry.lookupService(ApplicationUserRepository.class)
<ide> .map(userRepository ->
<ide> new TenantedAuthorizationFacetDefault(
<ide> evaluators, userRepository,
<ide> queryResultsCacheProvider, userService,
<del> holder))
<add> holder));
<add> return facetIfAny
<ide> .orElse(null);
<ide> }
<ide> |
|
JavaScript | bsd-3-clause | 90403154a21c654e4f0bc7258a3655ce9c1ae3c5 | 0 | foghina/react-native,ndejesus1227/react-native,arbesfeld/react-native,exponentjs/react-native,Guardiannw/react-native,pandiaraj44/react-native,csatf/react-native,htc2u/react-native,nathanajah/react-native,Purii/react-native,htc2u/react-native,jeffchienzabinet/react-native,csatf/react-native,MattFoley/react-native,jasonnoahchoi/react-native,nathanajah/react-native,apprennet/react-native,MattFoley/react-native,Bhullnatik/react-native,ptomasroos/react-native,ultralame/react-native,philikon/react-native,jaggs6/react-native,dubert/react-native,happypancake/react-native,jhen0409/react-native,makadaw/react-native,tarkus/react-native-appletv,luqin/react-native,Guardiannw/react-native,negativetwelve/react-native,DerayGa/react-native,htc2u/react-native,myntra/react-native,hammerandchisel/react-native,callstack-io/react-native,a2/react-native,DannyvanderJagt/react-native,shrutic/react-native,cdlewis/react-native,skatpgusskat/react-native,tsjing/react-native,dabit3/react-native,Andreyco/react-native,machard/react-native,janicduplessis/react-native,thotegowda/react-native,lelandrichardson/react-native,dikaiosune/react-native,DannyvanderJagt/react-native,lprhodes/react-native,jeffchienzabinet/react-native,hammerandchisel/react-native,shrutic123/react-native,makadaw/react-native,urvashi01/react-native,Bhullnatik/react-native,aaron-goshine/react-native,cdlewis/react-native,rebeccahughes/react-native,gilesvangruisen/react-native,tszajna0/react-native,rebeccahughes/react-native,Tredsite/react-native,forcedotcom/react-native,philikon/react-native,pandiaraj44/react-native,tszajna0/react-native,myntra/react-native,happypancake/react-native,iodine/react-native,CntChen/react-native,mrspeaker/react-native,htc2u/react-native,nickhudkins/react-native,happypancake/react-native,Tredsite/react-native,farazs/react-native,imDangerous/react-native,orenklein/react-native,imjerrybao/react-native,htc2u/react-native,mironiasty/react-native,tszajna0/react-native,cdlewis/react-native,aaron-goshine/react-native,skevy/react-native,DerayGa/react-native,happypancake/react-native,dabit3/react-native,clozr/react-native,formatlos/react-native,brentvatne/react-native,lprhodes/react-native,mrspeaker/react-native,iodine/react-native,hammerandchisel/react-native,wesley1001/react-native,tgoldenberg/react-native,arbesfeld/react-native,wenpkpk/react-native,rickbeerendonk/react-native,InterfaceInc/react-native,CodeLinkIO/react-native,orenklein/react-native,BretJohnson/react-native,formatlos/react-native,machard/react-native,skevy/react-native,tszajna0/react-native,pglotov/react-native,luqin/react-native,peterp/react-native,aljs/react-native,jevakallio/react-native,naoufal/react-native,arthuralee/react-native,christopherdro/react-native,a2/react-native,myntra/react-native,myntra/react-native,MattFoley/react-native,eduardinni/react-native,ndejesus1227/react-native,Maxwell2022/react-native,makadaw/react-native,martinbigio/react-native,satya164/react-native,pglotov/react-native,tszajna0/react-native,jeffchienzabinet/react-native,tgoldenberg/react-native,salanki/react-native,shrutic123/react-native,catalinmiron/react-native,CodeLinkIO/react-native,Swaagie/react-native,doochik/react-native,chirag04/react-native,doochik/react-native,hoangpham95/react-native,cosmith/react-native,Purii/react-native,BretJohnson/react-native,chirag04/react-native,browniefed/react-native,christopherdro/react-native,lelandrichardson/react-native,chnfeeeeeef/react-native,ptmt/react-native-macos,CodeLinkIO/react-native,gitim/react-native,lprhodes/react-native,facebook/react-native,adamjmcgrath/react-native,imjerrybao/react-native,philikon/react-native,dabit3/react-native,DerayGa/react-native,BretJohnson/react-native,mironiasty/react-native,philikon/react-native,jhen0409/react-native,xiayz/react-native,callstack-io/react-native,esauter5/react-native,jaggs6/react-native,ptomasroos/react-native,wesley1001/react-native,jadbox/react-native,CodeLinkIO/react-native,xiayz/react-native,foghina/react-native,dubert/react-native,catalinmiron/react-native,Maxwell2022/react-native,shrutic123/react-native,frantic/react-native,peterp/react-native,jadbox/react-native,ndejesus1227/react-native,ptmt/react-native-macos,chirag04/react-native,hoangpham95/react-native,Purii/react-native,shrutic123/react-native,wesley1001/react-native,jaggs6/react-native,lelandrichardson/react-native,jevakallio/react-native,CntChen/react-native,exponent/react-native,hayeah/react-native,CntChen/react-native,alin23/react-native,skatpgusskat/react-native,machard/react-native,tadeuzagallo/react-native,cosmith/react-native,tarkus/react-native-appletv,philikon/react-native,tgoldenberg/react-native,ptomasroos/react-native,tsjing/react-native,exponentjs/react-native,CodeLinkIO/react-native,aaron-goshine/react-native,facebook/react-native,DerayGa/react-native,xiayz/react-native,hoangpham95/react-native,imjerrybao/react-native,farazs/react-native,thotegowda/react-native,janicduplessis/react-native,pandiaraj44/react-native,cosmith/react-native,javache/react-native,corbt/react-native,hoastoolshop/react-native,farazs/react-native,ultralame/react-native,tarkus/react-native-appletv,urvashi01/react-native,adamjmcgrath/react-native,esauter5/react-native,Andreyco/react-native,rebeccahughes/react-native,browniefed/react-native,lprhodes/react-native,MattFoley/react-native,esauter5/react-native,InterfaceInc/react-native,Andreyco/react-native,gitim/react-native,aaron-goshine/react-native,hammerandchisel/react-native,ptomasroos/react-native,gitim/react-native,philikon/react-native,callstack-io/react-native,rebeccahughes/react-native,alin23/react-native,callstack-io/react-native,naoufal/react-native,InterfaceInc/react-native,jhen0409/react-native,gilesvangruisen/react-native,forcedotcom/react-native,skatpgusskat/react-native,wenpkpk/react-native,ankitsinghania94/react-native,iodine/react-native,cpunion/react-native,DerayGa/react-native,cpunion/react-native,myntra/react-native,Livyli/react-native,myntra/react-native,Tredsite/react-native,nathanajah/react-native,martinbigio/react-native,exponent/react-native,dubert/react-native,cosmith/react-native,catalinmiron/react-native,urvashi01/react-native,jevakallio/react-native,shrutic123/react-native,aljs/react-native,csatf/react-native,satya164/react-native,gre/react-native,Ehesp/react-native,Guardiannw/react-native,machard/react-native,Tredsite/react-native,imjerrybao/react-native,DannyvanderJagt/react-native,negativetwelve/react-native,iodine/react-native,catalinmiron/react-native,MattFoley/react-native,aljs/react-native,christopherdro/react-native,skevy/react-native,exponentjs/react-native,esauter5/react-native,corbt/react-native,skatpgusskat/react-native,htc2u/react-native,charlesvinette/react-native,dabit3/react-native,pglotov/react-native,chnfeeeeeef/react-native,happypancake/react-native,frantic/react-native,peterp/react-native,lprhodes/react-native,Bhullnatik/react-native,Guardiannw/react-native,PlexChat/react-native,shrutic123/react-native,ultralame/react-native,cdlewis/react-native,peterp/react-native,ndejesus1227/react-native,DanielMSchmidt/react-native,shrutic/react-native,alin23/react-native,BretJohnson/react-native,nickhudkins/react-native,exponent/react-native,callstack-io/react-native,doochik/react-native,aaron-goshine/react-native,compulim/react-native,Emilios1995/react-native,brentvatne/react-native,charlesvinette/react-native,Maxwell2022/react-native,ptomasroos/react-native,rebeccahughes/react-native,compulim/react-native,hoastoolshop/react-native,jaggs6/react-native,callstack-io/react-native,apprennet/react-native,arthuralee/react-native,dubert/react-native,mironiasty/react-native,csatf/react-native,mironiasty/react-native,charlesvinette/react-native,hoangpham95/react-native,mironiasty/react-native,jaggs6/react-native,Andreyco/react-native,jasonnoahchoi/react-native,javache/react-native,MattFoley/react-native,doochik/react-native,chirag04/react-native,ankitsinghania94/react-native,salanki/react-native,hayeah/react-native,hoangpham95/react-native,brentvatne/react-native,mrspeaker/react-native,lprhodes/react-native,nathanajah/react-native,jhen0409/react-native,ultralame/react-native,adamjmcgrath/react-native,satya164/react-native,rickbeerendonk/react-native,satya164/react-native,imjerrybao/react-native,cdlewis/react-native,Emilios1995/react-native,cpunion/react-native,facebook/react-native,DanielMSchmidt/react-native,jadbox/react-native,arbesfeld/react-native,arbesfeld/react-native,mrspeaker/react-native,DannyvanderJagt/react-native,lelandrichardson/react-native,aaron-goshine/react-native,miracle2k/react-native,shrutic/react-native,shrutic123/react-native,doochik/react-native,ankitsinghania94/react-native,christopherdro/react-native,myntra/react-native,janicduplessis/react-native,csatf/react-native,dabit3/react-native,exponentjs/react-native,jeffchienzabinet/react-native,DerayGa/react-native,facebook/react-native,Andreyco/react-native,miracle2k/react-native,ankitsinghania94/react-native,exponentjs/react-native,facebook/react-native,esauter5/react-native,alin23/react-native,Purii/react-native,lelandrichardson/react-native,salanki/react-native,Livyli/react-native,orenklein/react-native,Andreyco/react-native,dubert/react-native,pandiaraj44/react-native,esauter5/react-native,martinbigio/react-native,tarkus/react-native-appletv,foghina/react-native,machard/react-native,chirag04/react-native,Ehesp/react-native,forcedotcom/react-native,DannyvanderJagt/react-native,ptomasroos/react-native,hoastoolshop/react-native,csatf/react-native,nickhudkins/react-native,Swaagie/react-native,shrutic/react-native,facebook/react-native,forcedotcom/react-native,naoufal/react-native,dubert/react-native,a2/react-native,Maxwell2022/react-native,thotegowda/react-native,tarkus/react-native-appletv,apprennet/react-native,gilesvangruisen/react-native,wenpkpk/react-native,Maxwell2022/react-native,eduardinni/react-native,ptomasroos/react-native,rickbeerendonk/react-native,gitim/react-native,makadaw/react-native,mironiasty/react-native,janicduplessis/react-native,martinbigio/react-native,tadeuzagallo/react-native,formatlos/react-native,tarkus/react-native-appletv,alin23/react-native,adamjmcgrath/react-native,jasonnoahchoi/react-native,Andreyco/react-native,tgoldenberg/react-native,negativetwelve/react-native,alin23/react-native,Maxwell2022/react-native,orenklein/react-native,BretJohnson/react-native,hoastoolshop/react-native,ultralame/react-native,urvashi01/react-native,tsjing/react-native,jhen0409/react-native,gitim/react-native,DanielMSchmidt/react-native,jevakallio/react-native,tgoldenberg/react-native,gitim/react-native,jevakallio/react-native,corbt/react-native,wenpkpk/react-native,DanielMSchmidt/react-native,exponentjs/react-native,miracle2k/react-native,eduardinni/react-native,PlexChat/react-native,adamjmcgrath/react-native,luqin/react-native,browniefed/react-native,CodeLinkIO/react-native,lprhodes/react-native,jeffchienzabinet/react-native,DannyvanderJagt/react-native,tszajna0/react-native,DanielMSchmidt/react-native,Andreyco/react-native,tgoldenberg/react-native,satya164/react-native,Livyli/react-native,pglotov/react-native,tadeuzagallo/react-native,esauter5/react-native,myntra/react-native,callstack-io/react-native,imjerrybao/react-native,javache/react-native,Tredsite/react-native,farazs/react-native,salanki/react-native,DerayGa/react-native,mrspeaker/react-native,facebook/react-native,machard/react-native,adamjmcgrath/react-native,exponent/react-native,chnfeeeeeef/react-native,mrspeaker/react-native,wesley1001/react-native,naoufal/react-native,ndejesus1227/react-native,hoastoolshop/react-native,Tredsite/react-native,CntChen/react-native,jaggs6/react-native,compulim/react-native,dikaiosune/react-native,aaron-goshine/react-native,PlexChat/react-native,wenpkpk/react-native,chnfeeeeeef/react-native,tsjing/react-native,cdlewis/react-native,doochik/react-native,gre/react-native,a2/react-native,mironiasty/react-native,cosmith/react-native,jasonnoahchoi/react-native,cosmith/react-native,orenklein/react-native,gre/react-native,farazs/react-native,martinbigio/react-native,compulim/react-native,DanielMSchmidt/react-native,a2/react-native,rickbeerendonk/react-native,Ehesp/react-native,myntra/react-native,jasonnoahchoi/react-native,foghina/react-native,htc2u/react-native,kesha-antonov/react-native,alin23/react-native,hammerandchisel/react-native,tszajna0/react-native,cpunion/react-native,ptmt/react-native-macos,tadeuzagallo/react-native,Swaagie/react-native,CntChen/react-native,hammerandchisel/react-native,christopherdro/react-native,lprhodes/react-native,PlexChat/react-native,naoufal/react-native,callstack-io/react-native,a2/react-native,imDangerous/react-native,charlesvinette/react-native,jeffchienzabinet/react-native,negativetwelve/react-native,clozr/react-native,kesha-antonov/react-native,Bhullnatik/react-native,xiayz/react-native,gilesvangruisen/react-native,ndejesus1227/react-native,tsjing/react-native,DanielMSchmidt/react-native,CodeLinkIO/react-native,clozr/react-native,gilesvangruisen/react-native,foghina/react-native,PlexChat/react-native,dikaiosune/react-native,jasonnoahchoi/react-native,farazs/react-native,Bhullnatik/react-native,salanki/react-native,martinbigio/react-native,arbesfeld/react-native,doochik/react-native,frantic/react-native,iodine/react-native,ptmt/react-native-macos,negativetwelve/react-native,csatf/react-native,MattFoley/react-native,tszajna0/react-native,browniefed/react-native,CntChen/react-native,Livyli/react-native,jasonnoahchoi/react-native,jadbox/react-native,Tredsite/react-native,dikaiosune/react-native,miracle2k/react-native,InterfaceInc/react-native,janicduplessis/react-native,peterp/react-native,javache/react-native,Bhullnatik/react-native,hoastoolshop/react-native,kesha-antonov/react-native,Bhullnatik/react-native,Ehesp/react-native,hayeah/react-native,wesley1001/react-native,pglotov/react-native,eduardinni/react-native,vjeux/react-native,formatlos/react-native,luqin/react-native,aaron-goshine/react-native,cosmith/react-native,frantic/react-native,janicduplessis/react-native,hoastoolshop/react-native,skatpgusskat/react-native,happypancake/react-native,catalinmiron/react-native,clozr/react-native,cosmith/react-native,jadbox/react-native,makadaw/react-native,cdlewis/react-native,aljs/react-native,brentvatne/react-native,pandiaraj44/react-native,gitim/react-native,compulim/react-native,cdlewis/react-native,apprennet/react-native,browniefed/react-native,CntChen/react-native,apprennet/react-native,philikon/react-native,brentvatne/react-native,martinbigio/react-native,imDangerous/react-native,jadbox/react-native,Maxwell2022/react-native,corbt/react-native,christopherdro/react-native,tgoldenberg/react-native,Purii/react-native,a2/react-native,Emilios1995/react-native,farazs/react-native,adamjmcgrath/react-native,foghina/react-native,skevy/react-native,happypancake/react-native,brentvatne/react-native,xiayz/react-native,forcedotcom/react-native,skatpgusskat/react-native,ndejesus1227/react-native,chirag04/react-native,negativetwelve/react-native,Ehesp/react-native,negativetwelve/react-native,Livyli/react-native,wesley1001/react-native,exponentjs/react-native,nickhudkins/react-native,Ehesp/react-native,dabit3/react-native,formatlos/react-native,Ehesp/react-native,formatlos/react-native,BretJohnson/react-native,skatpgusskat/react-native,Guardiannw/react-native,imjerrybao/react-native,chnfeeeeeef/react-native,javache/react-native,imDangerous/react-native,luqin/react-native,jaggs6/react-native,CntChen/react-native,BretJohnson/react-native,Swaagie/react-native,gilesvangruisen/react-native,nathanajah/react-native,brentvatne/react-native,luqin/react-native,nathanajah/react-native,shrutic123/react-native,facebook/react-native,gre/react-native,tsjing/react-native,Emilios1995/react-native,foghina/react-native,shrutic/react-native,tsjing/react-native,catalinmiron/react-native,wenpkpk/react-native,gre/react-native,dikaiosune/react-native,csatf/react-native,jhen0409/react-native,luqin/react-native,PlexChat/react-native,corbt/react-native,foghina/react-native,cpunion/react-native,farazs/react-native,makadaw/react-native,jasonnoahchoi/react-native,a2/react-native,urvashi01/react-native,lelandrichardson/react-native,orenklein/react-native,satya164/react-native,nickhudkins/react-native,jadbox/react-native,iodine/react-native,brentvatne/react-native,dubert/react-native,salanki/react-native,frantic/react-native,ptmt/react-native-macos,imDangerous/react-native,dabit3/react-native,ankitsinghania94/react-native,InterfaceInc/react-native,xiayz/react-native,browniefed/react-native,formatlos/react-native,lelandrichardson/react-native,charlesvinette/react-native,vjeux/react-native,thotegowda/react-native,thotegowda/react-native,kesha-antonov/react-native,nickhudkins/react-native,peterp/react-native,urvashi01/react-native,chnfeeeeeef/react-native,arthuralee/react-native,negativetwelve/react-native,Emilios1995/react-native,Ehesp/react-native,hoastoolshop/react-native,Maxwell2022/react-native,shrutic/react-native,miracle2k/react-native,DannyvanderJagt/react-native,jevakallio/react-native,shrutic/react-native,thotegowda/react-native,InterfaceInc/react-native,InterfaceInc/react-native,arbesfeld/react-native,clozr/react-native,miracle2k/react-native,imDangerous/react-native,gre/react-native,wenpkpk/react-native,PlexChat/react-native,forcedotcom/react-native,miracle2k/react-native,Purii/react-native,Swaagie/react-native,salanki/react-native,kesha-antonov/react-native,Swaagie/react-native,thotegowda/react-native,kesha-antonov/react-native,janicduplessis/react-native,eduardinni/react-native,christopherdro/react-native,rickbeerendonk/react-native,vjeux/react-native,tadeuzagallo/react-native,tarkus/react-native-appletv,clozr/react-native,mrspeaker/react-native,dikaiosune/react-native,hammerandchisel/react-native,ankitsinghania94/react-native,hayeah/react-native,imjerrybao/react-native,urvashi01/react-native,browniefed/react-native,hoangpham95/react-native,alin23/react-native,machard/react-native,machard/react-native,dikaiosune/react-native,ptmt/react-native-macos,browniefed/react-native,satya164/react-native,doochik/react-native,MattFoley/react-native,Tredsite/react-native,gre/react-native,Livyli/react-native,Guardiannw/react-native,pandiaraj44/react-native,pglotov/react-native,tadeuzagallo/react-native,dikaiosune/react-native,makadaw/react-native,htc2u/react-native,corbt/react-native,exponentjs/react-native,corbt/react-native,mironiasty/react-native,naoufal/react-native,aljs/react-native,eduardinni/react-native,cdlewis/react-native,forcedotcom/react-native,lelandrichardson/react-native,hayeah/react-native,tarkus/react-native-appletv,arthuralee/react-native,pglotov/react-native,kesha-antonov/react-native,nathanajah/react-native,philikon/react-native,facebook/react-native,ptmt/react-native-macos,apprennet/react-native,charlesvinette/react-native,vjeux/react-native,peterp/react-native,wesley1001/react-native,Bhullnatik/react-native,clozr/react-native,arthuralee/react-native,peterp/react-native,pglotov/react-native,tgoldenberg/react-native,arbesfeld/react-native,happypancake/react-native,javache/react-native,formatlos/react-native,kesha-antonov/react-native,jevakallio/react-native,Guardiannw/react-native,ankitsinghania94/react-native,esauter5/react-native,tadeuzagallo/react-native,Purii/react-native,chnfeeeeeef/react-native,Livyli/react-native,jevakallio/react-native,salanki/react-native,forcedotcom/react-native,doochik/react-native,jeffchienzabinet/react-native,xiayz/react-native,ndejesus1227/react-native,orenklein/react-native,gilesvangruisen/react-native,imDangerous/react-native,catalinmiron/react-native,janicduplessis/react-native,iodine/react-native,exponent/react-native,BretJohnson/react-native,Emilios1995/react-native,exponent/react-native,vjeux/react-native,cpunion/react-native,aljs/react-native,naoufal/react-native,naoufal/react-native,imDangerous/react-native,catalinmiron/react-native,iodine/react-native,arbesfeld/react-native,cpunion/react-native,martinbigio/react-native,CodeLinkIO/react-native,shrutic/react-native,nathanajah/react-native,ankitsinghania94/react-native,apprennet/react-native,chirag04/react-native,nickhudkins/react-native,DannyvanderJagt/react-native,aljs/react-native,makadaw/react-native,brentvatne/react-native,adamjmcgrath/react-native,orenklein/react-native,javache/react-native,tsjing/react-native,DanielMSchmidt/react-native,kesha-antonov/react-native,charlesvinette/react-native,nickhudkins/react-native,tadeuzagallo/react-native,eduardinni/react-native,javache/react-native,chnfeeeeeef/react-native,mironiasty/react-native,hoangpham95/react-native,apprennet/react-native,corbt/react-native,hammerandchisel/react-native,javache/react-native,negativetwelve/react-native,rickbeerendonk/react-native,gilesvangruisen/react-native,luqin/react-native,xiayz/react-native,dabit3/react-native,pandiaraj44/react-native,InterfaceInc/react-native,charlesvinette/react-native,PlexChat/react-native,wesley1001/react-native,farazs/react-native,DerayGa/react-native,exponent/react-native,satya164/react-native,jhen0409/react-native,rickbeerendonk/react-native,aljs/react-native,Livyli/react-native,formatlos/react-native,mrspeaker/react-native,Swaagie/react-native,ptmt/react-native-macos,skevy/react-native,Guardiannw/react-native,exponent/react-native,jeffchienzabinet/react-native,Emilios1995/react-native,miracle2k/react-native,Swaagie/react-native,jadbox/react-native,eduardinni/react-native,ptomasroos/react-native,pandiaraj44/react-native,wenpkpk/react-native,rickbeerendonk/react-native,jhen0409/react-native,thotegowda/react-native,clozr/react-native,jevakallio/react-native,skevy/react-native,urvashi01/react-native,christopherdro/react-native,hoangpham95/react-native,jaggs6/react-native,Purii/react-native,makadaw/react-native,gre/react-native,cpunion/react-native,Emilios1995/react-native,dubert/react-native,rickbeerendonk/react-native,skevy/react-native,skevy/react-native,gitim/react-native,chirag04/react-native,skatpgusskat/react-native | /**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule BackAndroid
*/
'use strict';
var DeviceEventManager = require('NativeModules').DeviceEventManager;
var RCTDeviceEventEmitter = require('RCTDeviceEventEmitter');
var DEVICE_BACK_EVENT = 'hardwareBackPress';
type BackPressEventName = $Enum<{
backPress: string;
}>;
var _backPressSubscriptions = new Set();
RCTDeviceEventEmitter.addListener(DEVICE_BACK_EVENT, function() {
var backPressSubscriptions = new Set(_backPressSubscriptions);
var invokeDefault = true;
backPressSubscriptions.forEach((subscription) => {
if (subscription()) {
invokeDefault = false;
}
});
if (invokeDefault) {
BackAndroid.exitApp();
}
});
/**
* Detect hardware back button presses, and programmatically invoke the default back button
* functionality to exit the app if there are no listeners or if none of the listeners return true.
*
* Example:
*
* ```js
* BackAndroid.addEventListener('hardwareBackPress', function() {
* if (!this.onMainScreen()) {
* this.goBack();
* return true;
* }
* return false;
* });
* ```
*/
var BackAndroid = {
exitApp: function() {
DeviceEventManager.invokeDefaultBackPressHandler();
},
addEventListener: function (
eventName: BackPressEventName,
handler: Function
): {remove: () => void} {
_backPressSubscriptions.add(handler);
return {
remove: () => BackAndroid.removeEventListener(eventName, handler),
};
},
removeEventListener: function(
eventName: BackPressEventName,
handler: Function
): void {
_backPressSubscriptions.delete(handler);
},
};
module.exports = BackAndroid;
| Libraries/Utilities/BackAndroid.android.js | /**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule BackAndroid
*/
'use strict';
var DeviceEventManager = require('NativeModules').DeviceEventManager;
var RCTDeviceEventEmitter = require('RCTDeviceEventEmitter');
var DEVICE_BACK_EVENT = 'hardwareBackPress';
type BackPressEventName = $Enum<{
backPress: string;
}>;
var _backPressSubscriptions = new Set();
RCTDeviceEventEmitter.addListener(DEVICE_BACK_EVENT, function() {
var invokeDefault = true;
_backPressSubscriptions.forEach((subscription) => {
if (subscription()) {
invokeDefault = false;
}
});
if (invokeDefault) {
BackAndroid.exitApp();
}
});
/**
* Detect hardware back button presses, and programmatically invoke the default back button
* functionality to exit the app if there are no listeners or if none of the listeners return true.
*
* Example:
*
* ```js
* BackAndroid.addEventListener('hardwareBackPress', function() {
* if (!this.onMainScreen()) {
* this.goBack();
* return true;
* }
* return false;
* });
* ```
*/
var BackAndroid = {
exitApp: function() {
DeviceEventManager.invokeDefaultBackPressHandler();
},
addEventListener: function (
eventName: BackPressEventName,
handler: Function
): {remove: () => void} {
_backPressSubscriptions.add(handler);
return {
remove: () => BackAndroid.removeEventListener(eventName, handler),
};
},
removeEventListener: function(
eventName: BackPressEventName,
handler: Function
): void {
_backPressSubscriptions.delete(handler);
},
};
module.exports = BackAndroid;
| Snapshot the Set of listeners when dispatching a BackAndroid event
Summary:
…while an event is dispatched
While it is guarded, a copy of the Set is created before listeners are added or removed. The event dispatch loop continues with the old Set of listeners.
This PR modifies `BackAndroid` to match the proposal at the end of #5781.
Closes https://github.com/facebook/react-native/pull/5783
Reviewed By: svcscm
Differential Revision: D2911282
Pulled By: foghina
fb-gh-sync-id: 34964ec3414af85eb9574bbcef081238fc67ffaf
| Libraries/Utilities/BackAndroid.android.js | Snapshot the Set of listeners when dispatching a BackAndroid event | <ide><path>ibraries/Utilities/BackAndroid.android.js
<ide> var _backPressSubscriptions = new Set();
<ide>
<ide> RCTDeviceEventEmitter.addListener(DEVICE_BACK_EVENT, function() {
<add> var backPressSubscriptions = new Set(_backPressSubscriptions);
<ide> var invokeDefault = true;
<del> _backPressSubscriptions.forEach((subscription) => {
<add> backPressSubscriptions.forEach((subscription) => {
<ide> if (subscription()) {
<ide> invokeDefault = false;
<ide> } |
|
Java | bsd-3-clause | f98144088022dfba624ce1ba6e495920d1317fba | 0 | lrytz/asm,lrytz/asm | /***
* ASM: a very small and fast Java bytecode manipulation framework
* Copyright (c) 2000,2002,2003 INRIA, France Telecom
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*
* Contact: [email protected]
*
* Author: Eric Bruneton
*/
package org.objectweb.asm;
import java.io.InputStream;
import java.io.IOException;
/**
* A Java class parser to make a {@link ClassVisitor ClassVisitor} visit an
* existing class. This class parses a byte array conforming to the Java class
* file format and calls the appropriate visit methods of a given class visitor
* for each field, method and bytecode instruction encountered.
*/
public class ClassReader {
/**
* The class to be parsed. <i>The content of this array must not be
* modified. This field is intended for {@link Attribute} sub classes, and is
* normally not needed by class generators or adapters.</i>
*/
public final byte[] b;
/**
* The start index of each constant pool item in {@link #b b}, plus one. The
* one byte offset skips the constant pool item tag that indicates its type.
*/
private int[] items;
/**
* The String objects corresponding to the CONSTANT_Utf8 items. This cache
* avoids multiple parsing of a given CONSTANT_Utf8 constant pool item, which
* GREATLY improves performances (by a factor 2 to 3). This caching strategy
* could be extended to all constant pool items, but its benefit would not be
* so great for these items (because they are much less expensive to parse
* than CONSTANT_Utf8 items).
*/
private String[] strings;
/**
* Maximum length of the strings contained in the constant pool of the class.
*/
private int maxStringLength;
/**
* Start index of the class header information (access, name...) in {@link #b
* b}.
*/
private int header;
// --------------------------------------------------------------------------
// Constructors
// --------------------------------------------------------------------------
/**
* Constructs a new {@link ClassReader ClassReader} object.
*
* @param b the bytecode of the class to be read.
*/
public ClassReader (final byte[] b) {
this(b, 0, b.length);
}
/**
* Constructs a new {@link ClassReader ClassReader} object.
*
* @param b the bytecode of the class to be read.
* @param off the start offset of the class data.
* @param len the length of the class data.
*/
public ClassReader (final byte[] b, final int off, final int len) {
this.b = b;
// parses the constant pool
items = new int[readUnsignedShort(off + 8)];
strings = new String[items.length];
int max = 0;
int index = off + 10;
for (int i = 1; i < items.length; ++i) {
items[i] = index + 1;
int tag = b[index];
int size;
switch (tag) {
case ClassWriter.FIELD:
case ClassWriter.METH:
case ClassWriter.IMETH:
case ClassWriter.INT:
case ClassWriter.FLOAT:
case ClassWriter.NAME_TYPE:
size = 5;
break;
case ClassWriter.LONG:
case ClassWriter.DOUBLE:
size = 9;
++i;
break;
case ClassWriter.UTF8:
size = 3 + readUnsignedShort(index + 1);
max = (size > max ? size : max);
break;
//case ClassWriter.CLASS:
//case ClassWriter.STR:
default:
size = 3;
break;
}
index += size;
}
maxStringLength = max;
// the class header information starts just after the constant pool
header = index;
}
/**
* Constructs a new {@link ClassReader ClassReader} object.
*
* @param is an input stream from which to read the class.
* @throws IOException if a problem occurs during reading.
*/
public ClassReader (final InputStream is) throws IOException {
this(readClass(is));
}
/**
* Constructs a new {@link ClassReader ClassReader} object.
*
* @param name the fully qualified name of the class to be read.
* @throws IOException if an exception occurs during reading.
*/
public ClassReader (final String name) throws IOException {
this((ClassReader.class.getClassLoader() == null
? ClassLoader.getSystemClassLoader()
: ClassReader.class.getClassLoader())
.getSystemResourceAsStream(name.replace('.','/') + ".class"));
}
/**
* Reads the bytecode of a class.
*
* @param is an input stream from which to read the class.
* @return the bytecode read from the given input stream.
* @throws IOException if a problem occurs during reading.
*/
private static byte[] readClass (final InputStream is) throws IOException {
if (is == null) {
throw new IOException("Class not found");
}
byte[] b = new byte[is.available()];
int len = 0;
while (true) {
int n = is.read(b, len, b.length - len);
if (n == -1) {
if (len < b.length) {
byte[] c = new byte[len];
System.arraycopy(b, 0, c, 0, len);
b = c;
}
return b;
} else {
len += n;
if (len == b.length) {
byte[] c = new byte[b.length + 1000];
System.arraycopy(b, 0, c, 0, len);
b = c;
}
}
}
}
// --------------------------------------------------------------------------
// Public methods
// --------------------------------------------------------------------------
/**
* Makes the given visitor visit the Java class of this {@link ClassReader
* ClassReader}. This class is the one specified in the constructor (see
* {@link #ClassReader ClassReader}).
*
* @param classVisitor the visitor that must visit this class.
* @param skipDebug <tt>true</tt> if the debug information of the class must
* not be visited. In this case the {@link CodeVisitor#visitLocalVariable
* visitLocalVariable} and {@link CodeVisitor#visitLineNumber
* visitLineNumber} methods will not be called.
*/
public void accept (
final ClassVisitor classVisitor,
final boolean skipDebug)
{
accept(classVisitor, new Attribute[0], skipDebug);
}
/**
* Makes the given visitor visit the Java class of this {@link ClassReader
* ClassReader}. This class is the one specified in the constructor (see
* {@link #ClassReader ClassReader}).
*
* @param classVisitor the visitor that must visit this class.
* @param attrs prototypes of the attributes that must be parsed during the
* visit of the class. Any attribute whose type is not equal to the type
* of one the prototypes will be ignored.
* @param skipDebug <tt>true</tt> if the debug information of the class must
* not be visited. In this case the {@link CodeVisitor#visitLocalVariable
* visitLocalVariable} and {@link CodeVisitor#visitLineNumber
* visitLineNumber} methods will not be called.
*/
public void accept (
final ClassVisitor classVisitor,
final Attribute[] attrs,
final boolean skipDebug)
{
byte[] b = this.b; // the bytecode array
char[] c = new char[maxStringLength]; // buffer used to read strings
int i, j, k; // loop variables
int u, v, w; // indexes in b
Attribute attr;
// visits the header
u = header;
int access = readUnsignedShort(u);
String className = readClass(u + 2, c);
v = items[readUnsignedShort(u + 4)];
String superClassName = v == 0 ? null : readUTF8(v, c);
String[] implementedItfs = new String[readUnsignedShort(u + 6)];
String sourceFile = null;
Attribute clattrs = null;
w = 0;
u += 8;
for (i = 0; i < implementedItfs.length; ++i) {
implementedItfs[i] = readClass(u, c); u += 2;
}
// skips fields and methods
v = u;
i = readUnsignedShort(v); v += 2;
for ( ; i > 0; --i) {
j = readUnsignedShort(v + 6);
v += 8;
for ( ; j > 0; --j) {
v += 6 + readInt(v + 2);
}
}
i = readUnsignedShort(v); v += 2;
for ( ; i > 0; --i) {
j = readUnsignedShort(v + 6);
v += 8;
for ( ; j > 0; --j) {
v += 6 + readInt(v + 2);
}
}
// reads the class's attributes
i = readUnsignedShort(v); v += 2;
for ( ; i > 0; --i) {
String attrName = readUTF8(v, c);
if (attrName.equals("SourceFile")) {
sourceFile = readUTF8(v + 6, c);
} else if (attrName.equals("Deprecated")) {
access |= Constants.ACC_DEPRECATED;
} else if (attrName.equals("InnerClasses")) {
w = v + 6;
} else {
attr = readAttribute(
attrs, attrName, v + 6, readInt(v + 2), c, -1, null);
if (attr != null) {
attr.next = clattrs;
clattrs = attr;
}
}
v += 6 + readInt(v + 2);
}
// calls the visit method
classVisitor.visit(
access, className, superClassName, implementedItfs, sourceFile);
// visits the inner classes info
if (w != 0) {
i = readUnsignedShort(w); w += 2;
for ( ; i > 0; --i) {
classVisitor.visitInnerClass(
readUnsignedShort(w) == 0 ? null : readClass(w, c),
readUnsignedShort(w + 2) == 0 ? null : readClass(w + 2, c),
readUnsignedShort(w + 4) == 0 ? null : readUTF8(w + 4, c),
readUnsignedShort(w + 6));
w += 8;
}
}
// visits the fields
i = readUnsignedShort(u); u += 2;
for ( ; i > 0; --i) {
access = readUnsignedShort(u);
String fieldName = readUTF8(u + 2, c);
String fieldDesc = readUTF8(u + 4, c);
Attribute fattrs = null;
// visits the field's attributes and looks for a ConstantValue attribute
int fieldValueItem = 0;
j = readUnsignedShort(u + 6);
u += 8;
for ( ; j > 0; --j) {
String attrName = readUTF8(u, c);
if (attrName.equals("ConstantValue")) {
fieldValueItem = readUnsignedShort(u + 6);
} else if (attrName.equals("Synthetic")) {
access |= Constants.ACC_SYNTHETIC;
} else if (attrName.equals("Deprecated")) {
access |= Constants.ACC_DEPRECATED;
} else {
attr = readAttribute(
attrs, attrName, u + 6, readInt(u + 2), c, -1, null);
if (attr != null) {
attr.next = fattrs;
fattrs = attr;
}
}
u += 6 + readInt(u + 2);
}
// reads the field's value, if any
Object value = (fieldValueItem == 0 ? null : readConst(fieldValueItem, c));
// visits the field
classVisitor.visitField(access, fieldName, fieldDesc, value, fattrs);
}
// visits the methods
i = readUnsignedShort(u); u += 2;
for ( ; i > 0; --i) {
access = readUnsignedShort(u);
String methName = readUTF8(u + 2, c);
String methDesc = readUTF8(u + 4, c);
Attribute mattrs = null;
Attribute cattrs = null;
v = 0;
w = 0;
// looks for Code and Exceptions attributes
j = readUnsignedShort(u + 6);
u += 8;
for ( ; j > 0; --j) {
String attrName = readUTF8(u, c); u += 2;
int attrSize = readInt(u); u += 4;
if (attrName.equals("Code")) {
v = u;
} else if (attrName.equals("Exceptions")) {
w = u;
} else if (attrName.equals("Synthetic")) {
access |= Constants.ACC_SYNTHETIC;
} else if (attrName.equals("Deprecated")) {
access |= Constants.ACC_DEPRECATED;
} else {
attr = readAttribute(attrs, attrName, u, attrSize, c, -1, null);
if (attr != null) {
attr.next = mattrs;
mattrs = attr;
}
}
u += attrSize;
}
// reads declared exceptions
String[] exceptions;
if (w == 0) {
exceptions = null;
} else {
exceptions = new String[readUnsignedShort(w)]; w += 2;
for (j = 0; j < exceptions.length; ++j) {
exceptions[j] = readClass(w, c); w += 2;
}
}
// visits the method's code, if any
CodeVisitor cv;
cv = classVisitor.visitMethod(
access, methName, methDesc, exceptions, mattrs);
if (cv != null && v != 0) {
int maxStack = readUnsignedShort(v);
int maxLocals = readUnsignedShort(v + 2);
int codeLength = readInt(v + 4);
v += 8;
int codeStart = v;
int codeEnd = v + codeLength;
// 1st phase: finds the labels
int label;
Label[] labels = new Label[codeLength + 1];
while (v < codeEnd) {
int opcode = b[v] & 0xFF;
switch (ClassWriter.TYPE[opcode]) {
case ClassWriter.NOARG_INSN:
case ClassWriter.IMPLVAR_INSN:
v += 1;
break;
case ClassWriter.LABEL_INSN:
label = v - codeStart + readShort(v + 1);
if (labels[label] == null) {
labels[label] = new Label();
}
v += 3;
break;
case ClassWriter.LABELW_INSN:
label = v - codeStart + readInt(v + 1);
if (labels[label] == null) {
labels[label] = new Label();
}
v += 5;
break;
case ClassWriter.WIDE_INSN:
opcode = b[v + 1] & 0xFF;
if (opcode == Constants.IINC) {
v += 6;
} else {
v += 4;
}
break;
case ClassWriter.TABL_INSN:
// skips 0 to 3 padding bytes
w = v - codeStart;
v = v + 4 - (w & 3);
// reads instruction
label = w + readInt(v); v += 4;
if (labels[label] == null) {
labels[label] = new Label();
}
j = readInt(v); v += 4;
j = readInt(v) - j + 1; v += 4;
for ( ; j > 0; --j) {
label = w + readInt(v); v += 4;
if (labels[label] == null) {
labels[label] = new Label();
}
}
break;
case ClassWriter.LOOK_INSN:
// skips 0 to 3 padding bytes
w = v - codeStart;
v = v + 4 - (w & 3);
// reads instruction
label = w + readInt(v); v += 4;
if (labels[label] == null) {
labels[label] = new Label();
}
j = readInt(v); v += 4;
for ( ; j > 0; --j) {
v += 4; // skips key
label = w + readInt(v); v += 4;
if (labels[label] == null) {
labels[label] = new Label();
}
}
break;
case ClassWriter.VAR_INSN:
case ClassWriter.SBYTE_INSN:
case ClassWriter.LDC_INSN:
v += 2;
break;
case ClassWriter.SHORT_INSN:
case ClassWriter.LDCW_INSN:
case ClassWriter.FIELDORMETH_INSN:
case ClassWriter.TYPE_INSN:
case ClassWriter.IINC_INSN:
v += 3;
break;
case ClassWriter.ITFMETH_INSN:
v += 5;
break;
// case MANA_INSN:
default:
v += 4;
break;
}
}
// parses the try catch entries
j = readUnsignedShort(v); v += 2;
for ( ; j > 0; --j) {
label = readUnsignedShort(v);
if (labels[label] == null) {
labels[label] = new Label();
}
label = readUnsignedShort(v + 2);
if (labels[label] == null) {
labels[label] = new Label();
}
label = readUnsignedShort(v + 4);
if (labels[label] == null) {
labels[label] = new Label();
}
v += 8;
}
// parses the local variable, line number tables, and code attributes
j = readUnsignedShort(v); v += 2;
for ( ; j > 0; --j) {
String attrName = readUTF8(v, c);
if (attrName.equals("LocalVariableTable")) {
if (!skipDebug) {
k = readUnsignedShort(v + 6);
w = v + 8;
for ( ; k > 0; --k) {
label = readUnsignedShort(w);
if (labels[label] == null) {
labels[label] = new Label();
}
label += readUnsignedShort(w + 2);
if (labels[label] == null) {
labels[label] = new Label();
}
w += 10;
}
}
} else if (attrName.equals("LineNumberTable")) {
if (!skipDebug) {
k = readUnsignedShort(v + 6);
w = v + 8;
for ( ; k > 0; --k) {
label = readUnsignedShort(w);
if (labels[label] == null) {
labels[label] = new Label();
}
w += 4;
}
}
} else {
for (k = 0; k < attrs.length; ++k) {
if (attrs[k].type.equals(attrName)) {
attr = attrs[k].read(
this, v + 6, readInt(v + 2), c, codeStart - 8, labels);
if (attr != null) {
attr.next = cattrs;
cattrs = attr;
}
}
}
}
v += 6 + readInt(v + 2);
}
// 2nd phase: visits each instruction
v = codeStart;
Label l;
while (v < codeEnd) {
w = v - codeStart;
l = labels[w];
if (l != null) {
cv.visitLabel(l);
}
int opcode = b[v] & 0xFF;
switch (ClassWriter.TYPE[opcode]) {
case ClassWriter.NOARG_INSN:
cv.visitInsn(opcode);
v += 1;
break;
case ClassWriter.IMPLVAR_INSN:
if (opcode > Constants.ISTORE) {
opcode -= 59; //ISTORE_0
cv.visitVarInsn(Constants.ISTORE + (opcode >> 2), opcode & 0x3);
} else {
opcode -= 26; //ILOAD_0
cv.visitVarInsn(Constants.ILOAD + (opcode >> 2), opcode & 0x3);
}
v += 1;
break;
case ClassWriter.LABEL_INSN:
cv.visitJumpInsn(opcode, labels[w + readShort(v + 1)]);
v += 3;
break;
case ClassWriter.LABELW_INSN:
cv.visitJumpInsn(opcode, labels[w + readInt(v + 1)]);
v += 5;
break;
case ClassWriter.WIDE_INSN:
opcode = b[v + 1] & 0xFF;
if (opcode == Constants.IINC) {
cv.visitIincInsn(readUnsignedShort(v + 2), readShort(v + 4));
v += 6;
} else {
cv.visitVarInsn(opcode, readUnsignedShort(v + 2));
v += 4;
}
break;
case ClassWriter.TABL_INSN:
// skips 0 to 3 padding bytes
v = v + 4 - (w & 3);
// reads instruction
label = w + readInt(v); v += 4;
int min = readInt(v); v += 4;
int max = readInt(v); v += 4;
Label[] table = new Label[max - min + 1];
for (j = 0; j < table.length; ++j) {
table[j] = labels[w + readInt(v)];
v += 4;
}
cv.visitTableSwitchInsn(min, max, labels[label], table);
break;
case ClassWriter.LOOK_INSN:
// skips 0 to 3 padding bytes
v = v + 4 - (w & 3);
// reads instruction
label = w + readInt(v); v += 4;
j = readInt(v); v += 4;
int[] keys = new int[j];
Label[] values = new Label[j];
for (j = 0; j < keys.length; ++j) {
keys[j] = readInt(v); v += 4;
values[j] = labels[w + readInt(v)]; v += 4;
}
cv.visitLookupSwitchInsn(labels[label], keys, values);
break;
case ClassWriter.VAR_INSN:
cv.visitVarInsn(opcode, b[v + 1] & 0xFF);
v += 2;
break;
case ClassWriter.SBYTE_INSN:
cv.visitIntInsn(opcode, b[v + 1]);
v += 2;
break;
case ClassWriter.SHORT_INSN:
cv.visitIntInsn(opcode, readShort(v + 1));
v += 3;
break;
case ClassWriter.LDC_INSN:
cv.visitLdcInsn(readConst(b[v + 1] & 0xFF, c));
v += 2;
break;
case ClassWriter.LDCW_INSN:
cv.visitLdcInsn(readConst(readUnsignedShort(v + 1), c));
v += 3;
break;
case ClassWriter.FIELDORMETH_INSN:
case ClassWriter.ITFMETH_INSN:
int cpIndex = items[readUnsignedShort(v + 1)];
String iowner = readClass(cpIndex, c);
cpIndex = items[readUnsignedShort(cpIndex + 2)];
String iname = readUTF8(cpIndex, c);
String idesc = readUTF8(cpIndex + 2, c);
if (opcode < Constants.INVOKEVIRTUAL) {
cv.visitFieldInsn(opcode, iowner, iname, idesc);
} else {
cv.visitMethodInsn(opcode, iowner, iname, idesc);
}
if (opcode == Constants.INVOKEINTERFACE) {
v += 5;
} else {
v += 3;
}
break;
case ClassWriter.TYPE_INSN:
cv.visitTypeInsn(opcode, readClass(v + 1, c));
v += 3;
break;
case ClassWriter.IINC_INSN:
cv.visitIincInsn(b[v + 1] & 0xFF, b[v + 2]);
v += 3;
break;
// case MANA_INSN:
default:
cv.visitMultiANewArrayInsn(readClass(v + 1, c), b[v + 3] & 0xFF);
v += 4;
break;
}
}
l = labels[codeEnd - codeStart];
if (l != null) {
cv.visitLabel(l);
}
// visits the try catch entries
j = readUnsignedShort(v); v += 2;
for ( ; j > 0; --j) {
Label start = labels[readUnsignedShort(v)];
Label end = labels[readUnsignedShort(v + 2)];
Label handler = labels[readUnsignedShort(v + 4)];
int type = readUnsignedShort(v + 6);
if (type == 0) {
cv.visitTryCatchBlock(start, end, handler, null);
} else {
cv.visitTryCatchBlock(start, end, handler, readUTF8(items[type], c));
}
v += 8;
}
// visits the local variable and line number tables
j = readUnsignedShort(v); v += 2;
if (!skipDebug) {
for ( ; j > 0; --j) {
String attrName = readUTF8(v, c);
if (attrName.equals("LocalVariableTable")) {
k = readUnsignedShort(v + 6);
w = v + 8;
for ( ; k > 0; --k) {
label = readUnsignedShort(w);
Label start = labels[label];
label += readUnsignedShort(w + 2);
Label end = labels[label];
cv.visitLocalVariable(
readUTF8(w + 4, c),
readUTF8(w + 6, c),
start,
end,
readUnsignedShort(w + 8));
w += 10;
}
} else if (attrName.equals("LineNumberTable")) {
k = readUnsignedShort(v + 6);
w = v + 8;
for ( ; k > 0; --k) {
cv.visitLineNumber(
readUnsignedShort(w + 2),
labels[readUnsignedShort(w)]);
w += 4;
}
}
v += 6 + readInt(v + 2);
}
}
// visits the other attributes
while (cattrs != null) {
attr = cattrs.next;
cattrs.next = null;
cv.visitAttribute(cattrs);
cattrs = attr;
}
// visits the max stack and max locals values
cv.visitMaxs(maxStack, maxLocals);
}
}
// visits the class attributes
while (clattrs != null) {
classVisitor.visitAttribute(clattrs);
clattrs = clattrs.next;
}
// visits the end of the class
classVisitor.visitEnd();
}
// --------------------------------------------------------------------------
// Utility methods: low level parsing
// --------------------------------------------------------------------------
/**
* Reads a byte value in {@link #b b}. <i>This method is intended
* for {@link Attribute} sub classes, and is normally not needed by class
* generators or adapters.</i>
*
* @param index the start index of the value to be read in {@link #b b}.
* @return the read value.
*/
public int readByte (final int index) {
return b[index] & 0xFF;
}
/**
* Reads an unsigned short value in {@link #b b}. <i>This method is intended
* for {@link Attribute} sub classes, and is normally not needed by class
* generators or adapters.</i>
*
* @param index the start index of the value to be read in {@link #b b}.
* @return the read value.
*/
public int readUnsignedShort (final int index) {
byte[] b = this.b;
return ((b[index] & 0xFF) << 8) | (b[index + 1] & 0xFF);
}
/**
* Reads a signed short value in {@link #b b}. <i>This method is intended
* for {@link Attribute} sub classes, and is normally not needed by class
* generators or adapters.</i>
*
* @param index the start index of the value to be read in {@link #b b}.
* @return the read value.
*/
public short readShort (final int index) {
byte[] b = this.b;
return (short)(((b[index] & 0xFF) << 8) | (b[index + 1] & 0xFF));
}
/**
* Reads a signed int value in {@link #b b}. <i>This method is intended
* for {@link Attribute} sub classes, and is normally not needed by class
* generators or adapters.</i>
*
* @param index the start index of the value to be read in {@link #b b}.
* @return the read value.
*/
public int readInt (final int index) {
byte[] b = this.b;
return ((b[index] & 0xFF) << 24) |
((b[index + 1] & 0xFF) << 16) |
((b[index + 2] & 0xFF) << 8) |
(b[index + 3] & 0xFF);
}
/**
* Reads a signed long value in {@link #b b}. <i>This method is intended
* for {@link Attribute} sub classes, and is normally not needed by class
* generators or adapters.</i>
*
* @param index the start index of the value to be read in {@link #b b}.
* @return the read value.
*/
public long readLong (final int index) {
long l1 = readInt(index);
long l0 = readInt(index + 4) & 0xFFFFFFFFL;
return (l1 << 32) | l0;
}
/**
* Reads an UTF8 string constant pool item in {@link #b b}. <i>This method is
* intended for {@link Attribute} sub classes, and is normally not needed by
* class generators or adapters.</i>
*
* @param index the start index of an unsigned short value in {@link #b b},
* whose value is the index of an UTF8 constant pool item.
* @param buf buffer to be used to read the item. This buffer must be
* sufficiently large. It is not automatically resized.
* @return the String corresponding to the specified UTF8 item.
*/
public String readUTF8 (int index, final char[] buf) {
// consults cache
int item = readUnsignedShort(index);
String s = strings[item];
if (s != null) {
return s;
}
// computes the start index of the CONSTANT_Utf8 item in b
index = items[item];
// reads the length of the string (in bytes, not characters)
int utfLen = readUnsignedShort(index);
index += 2;
// parses the string bytes
int endIndex = index + utfLen;
byte[] b = this.b;
int strLen = 0;
int c, d, e;
while (index < endIndex) {
c = b[index++] & 0xFF;
switch (c >> 4) {
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
// 0xxxxxxx
buf[strLen++] = (char)c;
break;
case 12:
case 13:
// 110x xxxx 10xx xxxx
d = b[index++];
buf[strLen++] = (char)(((c & 0x1F) << 6) | (d & 0x3F));
break;
default:
// 1110 xxxx 10xx xxxx 10xx xxxx
d = b[index++];
e = b[index++];
buf[strLen++] =
(char)(((c & 0x0F) << 12) | ((d & 0x3F) << 6) | (e & 0x3F));
break;
}
}
s = new String(buf, 0, strLen);
strings[item] = s;
return s;
}
/**
* Reads a class constant pool item in {@link #b b}. <i>This method is
* intended for {@link Attribute} sub classes, and is normally not needed by
* class generators or adapters.</i>
*
* @param index the start index of an unsigned short value in {@link #b b},
* whose value is the index of a class constant pool item.
* @param buf buffer to be used to read the item. This buffer must be
* sufficiently large. It is not automatically resized.
* @return the String corresponding to the specified class item.
*/
public String readClass (final int index, final char[] buf) {
// computes the start index of the CONSTANT_Class item in b
// and reads the CONSTANT_Utf8 item designated by
// the first two bytes of this CONSTANT_Class item
return readUTF8(items[readUnsignedShort(index)], buf);
}
/**
* Reads a numeric or string constant pool item in {@link #b b}. <i>This
* method is intended for {@link Attribute} sub classes, and is normally not
* needed by class generators or adapters.</i>
*
* @param item the index of a constant pool item.
* @param buf buffer to be used to read the item. This buffer must be
* sufficiently large. It is not automatically resized.
* @return the {@link java.lang.Integer Integer}, {@link java.lang.Float
* Float}, {@link java.lang.Long Long}, {@link java.lang.Double Double}
* or {@link String String} corresponding to the given constant pool
* item.
*/
public Object readConst (final int item, final char[] buf) {
int index = items[item];
switch (b[index - 1]) {
case ClassWriter.INT:
return new Integer(readInt(index));
case ClassWriter.FLOAT:
return new Float(Float.intBitsToFloat(readInt(index)));
case ClassWriter.LONG:
return new Long(readLong(index));
case ClassWriter.DOUBLE:
return new Double(Double.longBitsToDouble(readLong(index)));
//case ClassWriter.STR:
default:
return readUTF8(index, buf);
}
}
/**
* Reads an attribute in {@link #b b}. The default implementation of this
* method returns <tt>null</tt> for all attributes.
*
* @param attrs prototypes of the attributes that must be parsed during the
* visit of the class. Any attribute whose type is not equal to the type
* of one the prototypes will be ignored.
* @param type the type of the attribute.
* @param off index of the first byte of the attribute's content in {@link #b
* b}. The 6 attribute header bytes, containing the type and the length
* of the attribute, are not taken into account here (they have already
* been read).
* @param len the length of the attribute's content.
* @param buf buffer to be used to call {@link #readUTF8 readUTF8}, {@link
* #readClass readClass} or {@link #readConst readConst}.
* @param codeOff index of the first byte of code's attribute content in
* {@link #b b}, or -1 if the attribute to be read is not a code
* attribute. The 6 attribute header bytes, containing the type and the
* length of the attribute, are not taken into account here.
* @param labels the labels of the method's code, or <tt>null</tt> if the
* attribute to be read is not a code attribute.
* @return the attribute that has been read, or <tt>null</tt> to skip this
* attribute.
*/
protected Attribute readAttribute (
final Attribute[] attrs,
final String type,
final int off,
final int len,
final char[] buf,
final int codeOff,
final Label[] labels)
{
for (int i = 0; i < attrs.length; ++i) {
if (attrs[i].type.equals(type)) {
return attrs[i].read(this, off, len, buf, codeOff, labels);
}
}
return null;
}
}
| src/org/objectweb/asm/ClassReader.java | /***
* ASM: a very small and fast Java bytecode manipulation framework
* Copyright (c) 2000,2002,2003 INRIA, France Telecom
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*
* Contact: [email protected]
*
* Author: Eric Bruneton
*/
package org.objectweb.asm;
import java.io.InputStream;
import java.io.IOException;
/**
* A Java class parser to make a {@link ClassVisitor ClassVisitor} visit an
* existing class. This class parses a byte array conforming to the Java class
* file format and calls the appropriate visit methods of a given class visitor
* for each field, method and bytecode instruction encountered.
*/
public class ClassReader {
/**
* The class to be parsed. <i>The content of this array must not be
* modified. This field is intended for {@link Attribute} sub classes, and is
* normally not needed by class generators or adapters.</i>
*/
public final byte[] b;
/**
* The start index of each constant pool item in {@link #b b}, plus one. The
* one byte offset skips the constant pool item tag that indicates its type.
*/
private int[] items;
/**
* The String objects corresponding to the CONSTANT_Utf8 items. This cache
* avoids multiple parsing of a given CONSTANT_Utf8 constant pool item, which
* GREATLY improves performances (by a factor 2 to 3). This caching strategy
* could be extended to all constant pool items, but its benefit would not be
* so great for these items (because they are much less expensive to parse
* than CONSTANT_Utf8 items).
*/
private String[] strings;
/**
* Maximum length of the strings contained in the constant pool of the class.
*/
private int maxStringLength;
/**
* Start index of the class header information (access, name...) in {@link #b
* b}.
*/
private int header;
// --------------------------------------------------------------------------
// Constructors
// --------------------------------------------------------------------------
/**
* Constructs a new {@link ClassReader ClassReader} object.
*
* @param b the bytecode of the class to be read.
*/
public ClassReader (final byte[] b) {
this(b, 0, b.length);
}
/**
* Constructs a new {@link ClassReader ClassReader} object.
*
* @param b the bytecode of the class to be read.
* @param off the start offset of the class data.
* @param len the length of the class data.
*/
public ClassReader (final byte[] b, final int off, final int len) {
this.b = b;
// parses the constant pool
items = new int[readUnsignedShort(off + 8)];
strings = new String[items.length];
int max = 0;
int index = off + 10;
for (int i = 1; i < items.length; ++i) {
items[i] = index + 1;
int tag = b[index];
int size;
switch (tag) {
case ClassWriter.FIELD:
case ClassWriter.METH:
case ClassWriter.IMETH:
case ClassWriter.INT:
case ClassWriter.FLOAT:
case ClassWriter.NAME_TYPE:
size = 5;
break;
case ClassWriter.LONG:
case ClassWriter.DOUBLE:
size = 9;
++i;
break;
case ClassWriter.UTF8:
size = 3 + readUnsignedShort(index + 1);
max = (size > max ? size : max);
break;
//case ClassWriter.CLASS:
//case ClassWriter.STR:
default:
size = 3;
break;
}
index += size;
}
maxStringLength = max;
// the class header information starts just after the constant pool
header = index;
}
/**
* Constructs a new {@link ClassReader ClassReader} object.
*
* @param is an input stream from which to read the class.
* @throws IOException if a problem occurs during reading.
*/
public ClassReader (final InputStream is) throws IOException {
this(readClass(is));
}
/**
* Constructs a new {@link ClassReader ClassReader} object.
*
* @param name the fully qualified name of the class to be read.
* @throws IOException if an exception occurs during reading.
*/
public ClassReader (final String name) throws IOException {
this((ClassReader.class.getClassLoader() == null
? ClassLoader.getSystemClassLoader()
: ClassReader.class.getClassLoader())
.getSystemResourceAsStream(name.replace('.','/') + ".class"));
}
/**
* Reads the bytecode of a class.
*
* @param is an input stream from which to read the class.
* @return the bytecode read from the given input stream.
* @throws IOException if a problem occurs during reading.
*/
private static byte[] readClass (final InputStream is) throws IOException {
if (is == null) {
throw new IOException("Class not found");
}
byte[] b = new byte[is.available()];
int len = 0;
while (true) {
int n = is.read(b, len, b.length - len);
if (n == -1) {
if (len < b.length) {
byte[] c = new byte[len];
System.arraycopy(b, 0, c, 0, len);
b = c;
}
return b;
} else {
len += n;
if (len == b.length) {
byte[] c = new byte[b.length + 1000];
System.arraycopy(b, 0, c, 0, len);
b = c;
}
}
}
}
// --------------------------------------------------------------------------
// Public methods
// --------------------------------------------------------------------------
/**
* Makes the given visitor visit the Java class of this {@link ClassReader
* ClassReader}. This class is the one specified in the constructor (see
* {@link #ClassReader ClassReader}).
*
* @param classVisitor the visitor that must visit this class.
* @param skipDebug <tt>true</tt> if the debug information of the class must
* not be visited. In this case the {@link CodeVisitor#visitLocalVariable
* visitLocalVariable} and {@link CodeVisitor#visitLineNumber
* visitLineNumber} methods will not be called.
*/
public void accept (
final ClassVisitor classVisitor,
final boolean skipDebug)
{
accept(classVisitor, new Attribute[0], skipDebug);
}
/**
* Makes the given visitor visit the Java class of this {@link ClassReader
* ClassReader}. This class is the one specified in the constructor (see
* {@link #ClassReader ClassReader}).
*
* @param classVisitor the visitor that must visit this class.
* @param attrs prototypes of the attributes that must be parsed during the
* visit of the class. Any attribute whose type is not equal to the type
* of one the prototypes will be ignored.
* @param skipDebug <tt>true</tt> if the debug information of the class must
* not be visited. In this case the {@link CodeVisitor#visitLocalVariable
* visitLocalVariable} and {@link CodeVisitor#visitLineNumber
* visitLineNumber} methods will not be called.
*/
public void accept (
final ClassVisitor classVisitor,
final Attribute[] attrs,
final boolean skipDebug)
{
byte[] b = this.b; // the bytecode array
char[] c = new char[maxStringLength]; // buffer used to read strings
int i, j, k; // loop variables
int u, v, w; // indexes in b
Attribute attr;
// visits the header
u = header;
int access = readUnsignedShort(u);
String className = readClass(u + 2, c);
v = items[readUnsignedShort(u + 4)];
String superClassName = v == 0 ? null : readUTF8(v, c);
String[] implementedItfs = new String[readUnsignedShort(u + 6)];
String sourceFile = null;
Attribute clattrs = null;
w = 0;
u += 8;
for (i = 0; i < implementedItfs.length; ++i) {
implementedItfs[i] = readClass(u, c); u += 2;
}
// skips fields and methods
v = u;
i = readUnsignedShort(v); v += 2;
for ( ; i > 0; --i) {
j = readUnsignedShort(v + 6);
v += 8;
for ( ; j > 0; --j) {
v += 6 + readInt(v + 2);
}
}
i = readUnsignedShort(v); v += 2;
for ( ; i > 0; --i) {
j = readUnsignedShort(v + 6);
v += 8;
for ( ; j > 0; --j) {
v += 6 + readInt(v + 2);
}
}
// reads the class's attributes
i = readUnsignedShort(v); v += 2;
for ( ; i > 0; --i) {
String attrName = readUTF8(v, c);
if (attrName.equals("SourceFile")) {
sourceFile = readUTF8(v + 6, c);
} else if (attrName.equals("Deprecated")) {
access |= Constants.ACC_DEPRECATED;
} else if (attrName.equals("InnerClasses")) {
w = v + 6;
} else {
attr = readAttribute(
attrs, attrName, v + 6, readInt(v + 2), c, -1, null);
if (attr != null) {
attr.next = clattrs;
clattrs = attr;
}
}
v += 6 + readInt(v + 2);
}
// calls the visit method
classVisitor.visit(
access, className, superClassName, implementedItfs, sourceFile);
// visits the inner classes info
if (w != 0) {
i = readUnsignedShort(w); w += 2;
for ( ; i > 0; --i) {
classVisitor.visitInnerClass(
readUnsignedShort(w) == 0 ? null : readClass(w, c),
readUnsignedShort(w + 2) == 0 ? null : readClass(w + 2, c),
readUnsignedShort(w + 4) == 0 ? null : readUTF8(w + 4, c),
readUnsignedShort(w + 6));
w += 8;
}
}
// visits the fields
i = readUnsignedShort(u); u += 2;
for ( ; i > 0; --i) {
access = readUnsignedShort(u);
String fieldName = readUTF8(u + 2, c);
String fieldDesc = readUTF8(u + 4, c);
Attribute fattrs = null;
// visits the field's attributes and looks for a ConstantValue attribute
int fieldValueItem = 0;
j = readUnsignedShort(u + 6);
u += 8;
for ( ; j > 0; --j) {
String attrName = readUTF8(u, c);
if (attrName.equals("ConstantValue")) {
fieldValueItem = readUnsignedShort(u + 6);
} else if (attrName.equals("Synthetic")) {
access |= Constants.ACC_SYNTHETIC;
} else if (attrName.equals("Deprecated")) {
access |= Constants.ACC_DEPRECATED;
} else {
attr = readAttribute(
attrs, attrName, u + 6, readInt(u + 2), c, -1, null);
if (attr != null) {
attr.next = fattrs;
fattrs = attr;
}
}
u += 6 + readInt(u + 2);
}
// reads the field's value, if any
Object value = (fieldValueItem == 0 ? null : readConst(fieldValueItem, c));
// visits the field
classVisitor.visitField(access, fieldName, fieldDesc, value, fattrs);
}
// visits the methods
i = readUnsignedShort(u); u += 2;
for ( ; i > 0; --i) {
access = readUnsignedShort(u);
String methName = readUTF8(u + 2, c);
String methDesc = readUTF8(u + 4, c);
Attribute mattrs = null;
Attribute cattrs = null;
v = 0;
w = 0;
// looks for Code and Exceptions attributes
j = readUnsignedShort(u + 6);
u += 8;
for ( ; j > 0; --j) {
String attrName = readUTF8(u, c); u += 2;
int attrSize = readInt(u); u += 4;
if (attrName.equals("Code")) {
v = u;
} else if (attrName.equals("Exceptions")) {
w = u;
} else if (attrName.equals("Synthetic")) {
access |= Constants.ACC_SYNTHETIC;
} else if (attrName.equals("Deprecated")) {
access |= Constants.ACC_DEPRECATED;
} else {
attr = readAttribute(attrs, attrName, u, attrSize, c, -1, null);
if (attr != null) {
attr.next = mattrs;
mattrs = attr;
}
}
u += attrSize;
}
// reads declared exceptions
String[] exceptions;
if (w == 0) {
exceptions = null;
} else {
exceptions = new String[readUnsignedShort(w)]; w += 2;
for (j = 0; j < exceptions.length; ++j) {
exceptions[j] = readClass(w, c); w += 2;
}
}
// visits the method's code, if any
CodeVisitor cv;
cv = classVisitor.visitMethod(
access, methName, methDesc, exceptions, mattrs);
if (cv != null && v != 0) {
int maxStack = readUnsignedShort(v);
int maxLocals = readUnsignedShort(v + 2);
int codeLength = readInt(v + 4);
v += 8;
int codeStart = v;
int codeEnd = v + codeLength;
// 1st phase: finds the labels
int label;
Label[] labels = new Label[codeLength + 1];
while (v < codeEnd) {
int opcode = b[v] & 0xFF;
switch (ClassWriter.TYPE[opcode]) {
case ClassWriter.NOARG_INSN:
case ClassWriter.IMPLVAR_INSN:
v += 1;
break;
case ClassWriter.LABEL_INSN:
label = v - codeStart + readShort(v + 1);
if (labels[label] == null) {
labels[label] = new Label();
}
v += 3;
break;
case ClassWriter.LABELW_INSN:
label = v - codeStart + readInt(v + 1);
if (labels[label] == null) {
labels[label] = new Label();
}
v += 5;
break;
case ClassWriter.WIDE_INSN:
opcode = b[v + 1] & 0xFF;
if (opcode == Constants.IINC) {
v += 6;
} else {
v += 4;
}
break;
case ClassWriter.TABL_INSN:
// skips 0 to 3 padding bytes
w = v - codeStart;
v = v + 4 - (w & 3);
// reads instruction
label = w + readInt(v); v += 4;
if (labels[label] == null) {
labels[label] = new Label();
}
j = readInt(v); v += 4;
j = readInt(v) - j + 1; v += 4;
for ( ; j > 0; --j) {
label = w + readInt(v); v += 4;
if (labels[label] == null) {
labels[label] = new Label();
}
}
break;
case ClassWriter.LOOK_INSN:
// skips 0 to 3 padding bytes
w = v - codeStart;
v = v + 4 - (w & 3);
// reads instruction
label = w + readInt(v); v += 4;
if (labels[label] == null) {
labels[label] = new Label();
}
j = readInt(v); v += 4;
for ( ; j > 0; --j) {
v += 4; // skips key
label = w + readInt(v); v += 4;
if (labels[label] == null) {
labels[label] = new Label();
}
}
break;
case ClassWriter.VAR_INSN:
case ClassWriter.SBYTE_INSN:
case ClassWriter.LDC_INSN:
v += 2;
break;
case ClassWriter.SHORT_INSN:
case ClassWriter.LDCW_INSN:
case ClassWriter.FIELDORMETH_INSN:
case ClassWriter.TYPE_INSN:
case ClassWriter.IINC_INSN:
v += 3;
break;
case ClassWriter.ITFMETH_INSN:
v += 5;
break;
// case MANA_INSN:
default:
v += 4;
break;
}
}
// parses the try catch entries
j = readUnsignedShort(v); v += 2;
for ( ; j > 0; --j) {
label = readUnsignedShort(v);
if (labels[label] == null) {
labels[label] = new Label();
}
label = readUnsignedShort(v + 2);
if (labels[label] == null) {
labels[label] = new Label();
}
label = readUnsignedShort(v + 4);
if (labels[label] == null) {
labels[label] = new Label();
}
v += 8;
}
// parses the local variable, line number tables, and code attributes
j = readUnsignedShort(v); v += 2;
for ( ; j > 0; --j) {
String attrName = readUTF8(v, c);
if (attrName.equals("LocalVariableTable")) {
if (!skipDebug) {
k = readUnsignedShort(v + 6);
w = v + 8;
for ( ; k > 0; --k) {
label = readUnsignedShort(w);
if (labels[label] == null) {
labels[label] = new Label();
}
label += readUnsignedShort(w + 2);
if (labels[label] == null) {
labels[label] = new Label();
}
w += 10;
}
}
} else if (attrName.equals("LineNumberTable")) {
if (!skipDebug) {
k = readUnsignedShort(v + 6);
w = v + 8;
for ( ; k > 0; --k) {
label = readUnsignedShort(w);
if (labels[label] == null) {
labels[label] = new Label();
}
w += 4;
}
}
} else {
for (k = 0; k < attrs.length; ++k) {
if (attrs[k].type.equals(attrName)) {
attr = attrs[k].read(
this, v + 6, readInt(v + 2), c, codeStart - 8, labels);
if (attr != null) {
attr.next = cattrs;
cattrs = attr;
}
}
}
}
v += 6 + readInt(v + 2);
}
// 2nd phase: visits each instruction
v = codeStart;
Label l;
while (v < codeEnd) {
w = v - codeStart;
l = labels[w];
if (l != null) {
cv.visitLabel(l);
}
int opcode = b[v] & 0xFF;
switch (ClassWriter.TYPE[opcode]) {
case ClassWriter.NOARG_INSN:
cv.visitInsn(opcode);
v += 1;
break;
case ClassWriter.IMPLVAR_INSN:
if (opcode > Constants.ISTORE) {
opcode -= 59; //ISTORE_0
cv.visitVarInsn(Constants.ISTORE + (opcode >> 2), opcode & 0x3);
} else {
opcode -= 26; //ILOAD_0
cv.visitVarInsn(Constants.ILOAD + (opcode >> 2), opcode & 0x3);
}
v += 1;
break;
case ClassWriter.LABEL_INSN:
cv.visitJumpInsn(opcode, labels[w + readShort(v + 1)]);
v += 3;
break;
case ClassWriter.LABELW_INSN:
cv.visitJumpInsn(opcode, labels[w + readInt(v + 1)]);
v += 5;
break;
case ClassWriter.WIDE_INSN:
opcode = b[v + 1] & 0xFF;
if (opcode == Constants.IINC) {
cv.visitIincInsn(readUnsignedShort(v + 2), readShort(v + 4));
v += 6;
} else {
cv.visitVarInsn(opcode, readUnsignedShort(v + 2));
v += 4;
}
break;
case ClassWriter.TABL_INSN:
// skips 0 to 3 padding bytes
v = v + 4 - (w & 3);
// reads instruction
label = w + readInt(v); v += 4;
int min = readInt(v); v += 4;
int max = readInt(v); v += 4;
Label[] table = new Label[max - min + 1];
for (j = 0; j < table.length; ++j) {
table[j] = labels[w + readInt(v)];
v += 4;
}
cv.visitTableSwitchInsn(min, max, labels[label], table);
break;
case ClassWriter.LOOK_INSN:
// skips 0 to 3 padding bytes
v = v + 4 - (w & 3);
// reads instruction
label = w + readInt(v); v += 4;
j = readInt(v); v += 4;
int[] keys = new int[j];
Label[] values = new Label[j];
for (j = 0; j < keys.length; ++j) {
keys[j] = readInt(v); v += 4;
values[j] = labels[w + readInt(v)]; v += 4;
}
cv.visitLookupSwitchInsn(labels[label], keys, values);
break;
case ClassWriter.VAR_INSN:
cv.visitVarInsn(opcode, b[v + 1] & 0xFF);
v += 2;
break;
case ClassWriter.SBYTE_INSN:
cv.visitIntInsn(opcode, b[v + 1]);
v += 2;
break;
case ClassWriter.SHORT_INSN:
cv.visitIntInsn(opcode, readShort(v + 1));
v += 3;
break;
case ClassWriter.LDC_INSN:
cv.visitLdcInsn(readConst(b[v + 1] & 0xFF, c));
v += 2;
break;
case ClassWriter.LDCW_INSN:
cv.visitLdcInsn(readConst(readUnsignedShort(v + 1), c));
v += 3;
break;
case ClassWriter.FIELDORMETH_INSN:
case ClassWriter.ITFMETH_INSN:
int cpIndex = items[readUnsignedShort(v + 1)];
String iowner = readClass(cpIndex, c);
cpIndex = items[readUnsignedShort(cpIndex + 2)];
String iname = readUTF8(cpIndex, c);
String idesc = readUTF8(cpIndex + 2, c);
if (opcode < Constants.INVOKEVIRTUAL) {
cv.visitFieldInsn(opcode, iowner, iname, idesc);
} else {
cv.visitMethodInsn(opcode, iowner, iname, idesc);
}
if (opcode == Constants.INVOKEINTERFACE) {
v += 5;
} else {
v += 3;
}
break;
case ClassWriter.TYPE_INSN:
cv.visitTypeInsn(opcode, readClass(v + 1, c));
v += 3;
break;
case ClassWriter.IINC_INSN:
cv.visitIincInsn(b[v + 1] & 0xFF, b[v + 2]);
v += 3;
break;
// case MANA_INSN:
default:
cv.visitMultiANewArrayInsn(readClass(v + 1, c), b[v + 3] & 0xFF);
v += 4;
break;
}
}
l = labels[codeEnd - codeStart];
if (l != null) {
cv.visitLabel(l);
}
// visits the try catch entries
j = readUnsignedShort(v); v += 2;
for ( ; j > 0; --j) {
Label start = labels[readUnsignedShort(v)];
Label end = labels[readUnsignedShort(v + 2)];
Label handler = labels[readUnsignedShort(v + 4)];
int type = readUnsignedShort(v + 6);
if (type == 0) {
cv.visitTryCatchBlock(start, end, handler, null);
} else {
cv.visitTryCatchBlock(start, end, handler, readUTF8(items[type], c));
}
v += 8;
}
// visits the local variable and line number tables
j = readUnsignedShort(v); v += 2;
if (!skipDebug) {
for ( ; j > 0; --j) {
String attrName = readUTF8(v, c);
if (attrName.equals("LocalVariableTable")) {
k = readUnsignedShort(v + 6);
w = v + 8;
for ( ; k > 0; --k) {
label = readUnsignedShort(w);
Label start = labels[label];
label += readUnsignedShort(w + 2);
Label end = labels[label];
cv.visitLocalVariable(
readUTF8(w + 4, c),
readUTF8(w + 6, c),
start,
end,
readUnsignedShort(w + 8));
w += 10;
}
} else if (attrName.equals("LineNumberTable")) {
k = readUnsignedShort(v + 6);
w = v + 8;
for ( ; k > 0; --k) {
cv.visitLineNumber(
readUnsignedShort(w + 2),
labels[readUnsignedShort(w)]);
w += 4;
}
}
v += 6 + readInt(v + 2);
}
}
// visits the other attributes
while (cattrs != null) {
attr = cattrs.next;
cattrs.next = null;
cv.visitAttribute(cattrs);
cattrs = attr;
}
// visits the max stack and max locals values
cv.visitMaxs(maxStack, maxLocals);
}
}
// visits the class attributes
while (clattrs != null) {
classVisitor.visitAttribute(clattrs);
clattrs = clattrs.next;
}
// visits the end of the class
classVisitor.visitEnd();
}
// --------------------------------------------------------------------------
// Utility methods: low level parsing
// --------------------------------------------------------------------------
/**
* Reads an unsigned short value in {@link #b b}. <i>This method is intended
* for {@link Attribute} sub classes, and is normally not needed by class
* generators or adapters.</i>
*
* @param index the start index of the value to be read in {@link #b b}.
* @return the read value.
*/
public int readUnsignedShort (final int index) {
byte[] b = this.b;
return ((b[index] & 0xFF) << 8) | (b[index + 1] & 0xFF);
}
/**
* Reads a signed short value in {@link #b b}. <i>This method is intended
* for {@link Attribute} sub classes, and is normally not needed by class
* generators or adapters.</i>
*
* @param index the start index of the value to be read in {@link #b b}.
* @return the read value.
*/
public short readShort (final int index) {
byte[] b = this.b;
return (short)(((b[index] & 0xFF) << 8) | (b[index + 1] & 0xFF));
}
/**
* Reads a signed int value in {@link #b b}. <i>This method is intended
* for {@link Attribute} sub classes, and is normally not needed by class
* generators or adapters.</i>
*
* @param index the start index of the value to be read in {@link #b b}.
* @return the read value.
*/
public int readInt (final int index) {
byte[] b = this.b;
return ((b[index] & 0xFF) << 24) |
((b[index + 1] & 0xFF) << 16) |
((b[index + 2] & 0xFF) << 8) |
(b[index + 3] & 0xFF);
}
/**
* Reads a signed long value in {@link #b b}. <i>This method is intended
* for {@link Attribute} sub classes, and is normally not needed by class
* generators or adapters.</i>
*
* @param index the start index of the value to be read in {@link #b b}.
* @return the read value.
*/
public long readLong (final int index) {
long l1 = readInt(index);
long l0 = readInt(index + 4) & 0xFFFFFFFFL;
return (l1 << 32) | l0;
}
/**
* Reads an UTF8 string constant pool item in {@link #b b}. <i>This method is
* intended for {@link Attribute} sub classes, and is normally not needed by
* class generators or adapters.</i>
*
* @param index the start index of an unsigned short value in {@link #b b},
* whose value is the index of an UTF8 constant pool item.
* @param buf buffer to be used to read the item. This buffer must be
* sufficiently large. It is not automatically resized.
* @return the String corresponding to the specified UTF8 item.
*/
public String readUTF8 (int index, final char[] buf) {
// consults cache
int item = readUnsignedShort(index);
String s = strings[item];
if (s != null) {
return s;
}
// computes the start index of the CONSTANT_Utf8 item in b
index = items[item];
// reads the length of the string (in bytes, not characters)
int utfLen = readUnsignedShort(index);
index += 2;
// parses the string bytes
int endIndex = index + utfLen;
byte[] b = this.b;
int strLen = 0;
int c, d, e;
while (index < endIndex) {
c = b[index++] & 0xFF;
switch (c >> 4) {
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
// 0xxxxxxx
buf[strLen++] = (char)c;
break;
case 12:
case 13:
// 110x xxxx 10xx xxxx
d = b[index++];
buf[strLen++] = (char)(((c & 0x1F) << 6) | (d & 0x3F));
break;
default:
// 1110 xxxx 10xx xxxx 10xx xxxx
d = b[index++];
e = b[index++];
buf[strLen++] =
(char)(((c & 0x0F) << 12) | ((d & 0x3F) << 6) | (e & 0x3F));
break;
}
}
s = new String(buf, 0, strLen);
strings[item] = s;
return s;
}
/**
* Reads a class constant pool item in {@link #b b}. <i>This method is
* intended for {@link Attribute} sub classes, and is normally not needed by
* class generators or adapters.</i>
*
* @param index the start index of an unsigned short value in {@link #b b},
* whose value is the index of a class constant pool item.
* @param buf buffer to be used to read the item. This buffer must be
* sufficiently large. It is not automatically resized.
* @return the String corresponding to the specified class item.
*/
public String readClass (final int index, final char[] buf) {
// computes the start index of the CONSTANT_Class item in b
// and reads the CONSTANT_Utf8 item designated by
// the first two bytes of this CONSTANT_Class item
return readUTF8(items[readUnsignedShort(index)], buf);
}
/**
* Reads a numeric or string constant pool item in {@link #b b}. <i>This
* method is intended for {@link Attribute} sub classes, and is normally not
* needed by class generators or adapters.</i>
*
* @param item the index of a constant pool item.
* @param buf buffer to be used to read the item. This buffer must be
* sufficiently large. It is not automatically resized.
* @return the {@link java.lang.Integer Integer}, {@link java.lang.Float
* Float}, {@link java.lang.Long Long}, {@link java.lang.Double Double}
* or {@link String String} corresponding to the given constant pool
* item.
*/
public Object readConst (final int item, final char[] buf) {
int index = items[item];
switch (b[index - 1]) {
case ClassWriter.INT:
return new Integer(readInt(index));
case ClassWriter.FLOAT:
return new Float(Float.intBitsToFloat(readInt(index)));
case ClassWriter.LONG:
return new Long(readLong(index));
case ClassWriter.DOUBLE:
return new Double(Double.longBitsToDouble(readLong(index)));
//case ClassWriter.STR:
default:
return readUTF8(index, buf);
}
}
/**
* Reads an attribute in {@link #b b}. The default implementation of this
* method returns <tt>null</tt> for all attributes.
*
* @param attrs prototypes of the attributes that must be parsed during the
* visit of the class. Any attribute whose type is not equal to the type
* of one the prototypes will be ignored.
* @param type the type of the attribute.
* @param off index of the first byte of the attribute's content in {@link #b
* b}. The 6 attribute header bytes, containing the type and the length
* of the attribute, are not taken into account here (they have already
* been read).
* @param len the length of the attribute's content.
* @param buf buffer to be used to call {@link #readUTF8 readUTF8}, {@link
* #readClass readClass} or {@link #readConst readConst}.
* @param codeOff index of the first byte of code's attribute content in
* {@link #b b}, or -1 if the attribute to be read is not a code
* attribute. The 6 attribute header bytes, containing the type and the
* length of the attribute, are not taken into account here.
* @param labels the labels of the method's code, or <tt>null</tt> if the
* attribute to be read is not a code attribute.
* @return the attribute that has been read, or <tt>null</tt> to skip this
* attribute.
*/
protected Attribute readAttribute (
final Attribute[] attrs,
final String type,
final int off,
final int len,
final char[] buf,
final int codeOff,
final Label[] labels)
{
for (int i = 0; i < attrs.length; ++i) {
if (attrs[i].type.equals(type)) {
return attrs[i].read(this, off, len, buf, codeOff, labels);
}
}
return null;
}
}
| added readByte method
| src/org/objectweb/asm/ClassReader.java | added readByte method | <ide><path>rc/org/objectweb/asm/ClassReader.java
<ide> // --------------------------------------------------------------------------
<ide> // Utility methods: low level parsing
<ide> // --------------------------------------------------------------------------
<add>
<add> /**
<add> * Reads a byte value in {@link #b b}. <i>This method is intended
<add> * for {@link Attribute} sub classes, and is normally not needed by class
<add> * generators or adapters.</i>
<add> *
<add> * @param index the start index of the value to be read in {@link #b b}.
<add> * @return the read value.
<add> */
<add>
<add> public int readByte (final int index) {
<add> return b[index] & 0xFF;
<add> }
<ide>
<ide> /**
<ide> * Reads an unsigned short value in {@link #b b}. <i>This method is intended |
|
Java | mit | 919aa3c4d8884c5f6497809b8a6e12f8590a3266 | 0 | yeyu456/Data-Structures-And-Algorithms | package com.algorithms.sort.insertion;
import com.algorithms.sort.Sort;
/**
* Shell Sort Implement
* 希尔排序实现
*/
public class ShellSort extends InsertionSort {
/**
* By Donald L. Shell, 1959
* @param data 待排序数组
*/
@Override
public void sort(int[] data) {
if (!valid(data)) {
return;
}
for (int i = 2; data.length / i > 0; i*=2) {
sortByGap(data, data.length / i);
}
}
/**
* By Frank & Lazarus, 1960
* @param data 待排序数组
*/
public void fl60(int[] data) {
if (!valid(data)) {
return;
}
for (int i = 4; data.length / i * 2 + 1 > 0; i*=2) {
sortByGap(data, data.length / i * 2 + 1);
}
}
/**
* By Hibbard, 1963
* @param data 待排序数组
*/
public void hi63(int[] data) {
if (!valid(data)) {
return;
}
int k = 1;
while (((2 << k) - 1) < data.length) {
k++;
}
while (k > 0) {
sortByGap(data, (2 << k) - 1);
k--;
}
}
/**
* By Papernov & Stasevich, 1965
* @param data 待排序数组
*/
public void ps65(int[] data) {
if (!valid(data)) {
return;
}
int k = 1;
while (((2 << k) + 1) < data.length) {
k++;
}
while (k > 0) {
sortByGap(data, (2 << k) + 1);
k--;
}
sortByGap(data, 1);
}
/**
* By Pratt, 1971
* @param data 待排序数组
*/
public void pr71(int[] data) {
if (!valid(data)) {
return;
}
}
/**
* By Donald Ervin Knuth, 1973
* @param data 待排序数组
*/
public void kn73(int[] data) {
if (!valid(data)) {
return;
}
int k = 1;
while ((((3 << k) - 1) / 2) < data.length) {
k++;
}
while (k > 0) {
sortByGap(data, ((3 << k) - 1) / 2);
k--;
}
}
/**
* By Sedgewick, 1982
* @param data 待排序数组
*/
public void se82(int[] data) {
if (!valid(data)) {
return;
}
int k = 1;
while (((4 << k) + 3 * (2 << k - 1) + 1) < data.length) {
k++;
}
while (k > 0) {
sortByGap(data, ((4 << k) + 3 * (2 << k - 1) + 1));
k--;
}
sortByGap(data, 1);
}
/**
* By Sedgewick, 1986
* @param data 待排序数组
*/
public void se86(int[] data) {
if (!valid(data)) {
return;
}
int k = -1;
int gap;
do {
k++;
if (k % 2 == 1) {
gap = 8 * (2 << k) - 6 * (2 << ((k + 1) / 2)) + 1;
} else {
gap = 9 * (2 << k) - 9 * (2 << (k / 2)) + 1;
}
} while (gap < data.length);
while (k >= 0) {
if (k % 2 == 1) {
gap = 8 * (2 << k) - 6 * (2 << ((k + 1) / 2)) + 1;
} else {
gap = 9 * (2 << k) - 9 * (2 << (k / 2)) + 1;
}
sortByGap(data, gap);
k--;
}
}
/**
* By Gonnet & Baeza-Yates, 1991
* @param data 待排序数组
*/
public void gb91(int[] data) {
}
/**
* By Tokuda, 1992
* @param data 待排序数组
*/
public void to92(int[] data) {
}
/**
*
* @param data 待排序数组
*/
public void ci01(int[] data) {
}
}
| src/com/algorithms/sort/insertion/ShellSort.java | package com.algorithms.sort.insertion;
import com.algorithms.sort.Sort;
/**
* Shell Sort Implement
* 希尔排序实现
*/
public class ShellSort extends InsertionSort {
/**
* By Donald L. Shell, 1959
* @param data 待排序数组
*/
@Override
public void sort(int[] data) {
if (!valid(data)) {
return;
}
for (int i = 2; data.length / i > 0; i*=2) {
sortByGap(data, data.length / i);
}
}
/**
* By Frank & Lazarus, 1960
* @param data 待排序数组
*/
public void fl60(int[] data) {
if (!valid(data)) {
return;
}
for (int i = 4; data.length / i * 2 + 1 > 0; i*=2) {
sortByGap(data, data.length / i * 2 + 1);
}
}
/**
* By Hibbard, 1963
* @param data 待排序数组
*/
public void hi63(int[] data) {
if (!valid(data)) {
return;
}
int k = 1;
while (((2 << k) - 1) < data.length) {
k++;
}
while (k > 0) {
sortByGap(data, (2 << k) - 1);
k--;
}
}
/**
* By Papernov & Stasevich, 1965
* @param data 待排序数组
*/
public void ps65(int[] data) {
if (!valid(data)) {
return;
}
int k = 1;
while (((2 << k) + 1) < data.length) {
k++;
}
while (k > 0) {
sortByGap(data, (2 << k) + 1);
k--;
}
sortByGap(data, 1);
}
/**
* By Vaughan Pratt, 1971
* @param data 待排序数组
*/
public void pt71(int[] data) {
if (!valid(data)) {
return;
}
int k = 1;
while ((((3 << k) - 1) / 2) < data.length) {
k++;
}
while (k > 0) {
sortByGap(data, ((3 << k) - 1) / 2);
k--;
}
}
/**
* By Sedgewick, 1986
* @param data 待排序数组
*/
public void se86(int[] data) {
if (!valid(data)) {
return;
}
}
public void se98(int[] data) {
if (!valid(data)) {
return;
}
int k = 1;
while (((4 << k) + 3 * (2 << k - 1) + 1) < data.length) {
k++;
}
while (k > 0) {
sortByGap(data, ((4 << k) + 3 * (2 << k - 1) + 1));
k--;
}
sortByGap(data, 1);
}
}
| add variant shell sort
| src/com/algorithms/sort/insertion/ShellSort.java | add variant shell sort | <ide><path>rc/com/algorithms/sort/insertion/ShellSort.java
<ide> }
<ide>
<ide> /**
<del> * By Vaughan Pratt, 1971
<add> * By Pratt, 1971
<ide> * @param data 待排序数组
<ide> */
<del> public void pt71(int[] data) {
<add> public void pr71(int[] data) {
<add> if (!valid(data)) {
<add> return;
<add> }
<add> }
<add>
<add> /**
<add> * By Donald Ervin Knuth, 1973
<add> * @param data 待排序数组
<add> */
<add> public void kn73(int[] data) {
<ide> if (!valid(data)) {
<ide> return;
<ide> }
<ide> }
<ide>
<ide> /**
<del> * By Sedgewick, 1986
<add> * By Sedgewick, 1982
<ide> * @param data 待排序数组
<ide> */
<del> public void se86(int[] data) {
<del> if (!valid(data)) {
<del> return;
<del> }
<del> }
<del>
<del> public void se98(int[] data) {
<add> public void se82(int[] data) {
<ide> if (!valid(data)) {
<ide> return;
<ide> }
<ide> }
<ide> sortByGap(data, 1);
<ide> }
<add>
<add> /**
<add> * By Sedgewick, 1986
<add> * @param data 待排序数组
<add> */
<add> public void se86(int[] data) {
<add> if (!valid(data)) {
<add> return;
<add> }
<add> int k = -1;
<add> int gap;
<add> do {
<add> k++;
<add> if (k % 2 == 1) {
<add> gap = 8 * (2 << k) - 6 * (2 << ((k + 1) / 2)) + 1;
<add> } else {
<add> gap = 9 * (2 << k) - 9 * (2 << (k / 2)) + 1;
<add> }
<add> } while (gap < data.length);
<add>
<add> while (k >= 0) {
<add> if (k % 2 == 1) {
<add> gap = 8 * (2 << k) - 6 * (2 << ((k + 1) / 2)) + 1;
<add> } else {
<add> gap = 9 * (2 << k) - 9 * (2 << (k / 2)) + 1;
<add> }
<add> sortByGap(data, gap);
<add> k--;
<add> }
<add> }
<add>
<add> /**
<add> * By Gonnet & Baeza-Yates, 1991
<add> * @param data 待排序数组
<add> */
<add> public void gb91(int[] data) {
<add>
<add> }
<add>
<add> /**
<add> * By Tokuda, 1992
<add> * @param data 待排序数组
<add> */
<add> public void to92(int[] data) {
<add>
<add> }
<add>
<add> /**
<add> *
<add> * @param data 待排序数组
<add> */
<add> public void ci01(int[] data) {
<add>
<add> }
<ide> } |
|
Java | agpl-3.0 | 13af995e8c28dd52280787f77af339c76487f780 | 0 | Peergos/Peergos,Peergos/Peergos,ianopolous/Peergos,ianopolous/Peergos,ianopolous/Peergos,Peergos/Peergos | package peergos.server;
import peergos.shared.*;
import peergos.shared.corenode.*;
import peergos.shared.crypto.hash.*;
import peergos.shared.io.ipfs.multihash.*;
import peergos.shared.user.*;
import java.io.*;
import java.net.*;
import java.nio.file.*;
import java.time.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.*;
public class UserStats {
public static void main(String[] args) throws Exception {
Crypto crypto = Main.initCrypto();
NetworkAccess network = Builder.buildJavaNetworkAccess(new URL("https://beta.peergos.net"), true).get();
List<String> usernames = network.coreNode.getUsernames("").get();
ForkJoinPool pool = new ForkJoinPool(20);
List<String> errors = Collections.synchronizedList(new ArrayList<>());
List<Summary> summaries = pool.submit(() -> usernames.stream().parallel().flatMap(username -> {
List<Multihash> hosts = Collections.emptyList();
try {
List<UserPublicKeyLink> chain = network.coreNode.getChain(username).get();
UserPublicKeyLink last = chain.get(chain.size() - 1);
LocalDate expiry = last.claim.expiry;
hosts = last.claim.storageProviders;
PublicKeyHash owner = last.owner;
Set<PublicKeyHash> ownedKeysRecursive =
WriterData.getOwnedKeysRecursive(username, network.coreNode, network.mutable,
network.dhtClient, network.hasher).join();
long total = 0;
for (PublicKeyHash writer : ownedKeysRecursive) {
MaybeMultihash target = network.mutable.getPointerTarget(owner, writer, network.dhtClient).get();
if (target.isPresent())
total += network.dhtClient.getRecursiveBlockSize(target.get()).get();
}
String summary = "User: " + username + ", expiry: " + expiry + " usage: " + total
+ ", owned keys: " + ownedKeysRecursive.size() + "\n";
System.out.println(summary);
return Stream.of(new Summary(username, expiry, total, hosts, ownedKeysRecursive));
} catch (Exception e) {
String host = hosts.stream().findFirst().map(Object::toString).orElse("");
errors.add(username + ": " + host);
System.err.println("Error for " + username + " on host " + host);
e.printStackTrace();
return Stream.empty();
}
}).collect(Collectors.toList())).join();
System.out.println("Errors: " + errors.size());
errors.forEach(System.out::println);
// Sort by usage
sortAndPrint(summaries, (a, b) -> Long.compare(b.usage, a.usage), "usage.txt");
// Sort by expiry
sortAndPrint(summaries, (a, b) -> a.expiry.compareTo(b.expiry), "expiry.txt");
// Sort by host
sortAndPrint(summaries, Comparator.comparing(s -> s.storageProviders.stream()
.findFirst()
.map(Object::toString)
.orElse("")), "host.txt");
pool.shutdownNow();
}
private static void sortAndPrint(List<Summary> stats,
Comparator<Summary> order,
String filename) throws Exception {
stats.sort(order);
ByteArrayOutputStream bout = new ByteArrayOutputStream();
stats.stream()
.map(s -> (s.toString() + "\n").getBytes())
.forEach(bytes -> bout.write(bytes, 0, bytes.length));
Files.write(Paths.get(filename), bout.toByteArray());
}
private static class Summary {
public final String username;
public final LocalDate expiry;
public final long usage;
public final List<Multihash> storageProviders;
public final Set<PublicKeyHash> ownedKeys;
public Summary(String username, LocalDate expiry, long usage, List<Multihash> storageProviders, Set<PublicKeyHash> ownedKeys) {
this.username = username;
this.expiry = expiry;
this.usage = usage;
this.storageProviders = storageProviders;
this.ownedKeys = ownedKeys;
}
public String toString() {
return "User: " + username + ", expiry: " + expiry + ", usage: " + usage
+ ", hosts: " + storageProviders + ", owned keys: " + ownedKeys.size();
}
}
}
| src/peergos/server/UserStats.java | package peergos.server;
import peergos.shared.*;
import peergos.shared.corenode.*;
import peergos.shared.crypto.hash.*;
import peergos.shared.io.ipfs.multihash.*;
import peergos.shared.user.*;
import java.io.*;
import java.net.*;
import java.nio.file.*;
import java.time.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.*;
public class UserStats {
public static void main(String[] args) throws Exception {
Crypto crypto = Main.initCrypto();
NetworkAccess network = Builder.buildJavaNetworkAccess(new URL("https://beta.peergos.net"), true).get();
List<String> usernames = network.coreNode.getUsernames("").get();
ForkJoinPool pool = new ForkJoinPool(20);
List<Summary> summaries = pool.submit(() -> usernames.stream().parallel().flatMap(username -> {
try {
List<UserPublicKeyLink> chain = network.coreNode.getChain(username).get();
UserPublicKeyLink last = chain.get(chain.size() - 1);
LocalDate expiry = last.claim.expiry;
List<Multihash> hosts = last.claim.storageProviders;
PublicKeyHash owner = last.owner;
Set<PublicKeyHash> ownedKeysRecursive =
WriterData.getOwnedKeysRecursive(username, network.coreNode, network.mutable,
network.dhtClient, network.hasher).join();
long total = 0;
for (PublicKeyHash writer : ownedKeysRecursive) {
MaybeMultihash target = network.mutable.getPointerTarget(owner, writer, network.dhtClient).get();
if (target.isPresent())
total += network.dhtClient.getRecursiveBlockSize(target.get()).get();
}
String summary = "User: " + username + ", expiry: " + expiry + " usage: " + total
+ ", owned keys: " + ownedKeysRecursive.size() + "\n";
System.out.println(summary);
return Stream.of(new Summary(username, expiry, total, hosts, ownedKeysRecursive));
} catch (Exception e) {
System.err.println("Error for " + username);
e.printStackTrace();
return Stream.empty();
}
}).collect(Collectors.toList())).join();
// Sort by usage
sortAndPrint(summaries, (a, b) -> Long.compare(b.usage, a.usage), "usage.txt");
// Sort by expiry
sortAndPrint(summaries, (a, b) -> a.expiry.compareTo(b.expiry), "expiry.txt");
// Sort by host
sortAndPrint(summaries, Comparator.comparing(s -> s.storageProviders.stream()
.findFirst()
.map(Object::toString)
.orElse("")), "host.txt");
pool.shutdownNow();
}
private static void sortAndPrint(List<Summary> stats,
Comparator<Summary> order,
String filename) throws Exception {
stats.sort(order);
ByteArrayOutputStream bout = new ByteArrayOutputStream();
stats.stream()
.map(s -> (s.toString() + "\n").getBytes())
.forEach(bytes -> bout.write(bytes, 0, bytes.length));
Files.write(Paths.get(filename), bout.toByteArray());
}
private static class Summary {
public final String username;
public final LocalDate expiry;
public final long usage;
public final List<Multihash> storageProviders;
public final Set<PublicKeyHash> ownedKeys;
public Summary(String username, LocalDate expiry, long usage, List<Multihash> storageProviders, Set<PublicKeyHash> ownedKeys) {
this.username = username;
this.expiry = expiry;
this.usage = usage;
this.storageProviders = storageProviders;
this.ownedKeys = ownedKeys;
}
public String toString() {
return "User: " + username + ", expiry: " + expiry + ", usage: " + usage
+ ", hosts: " + storageProviders + ", owned keys: " + ownedKeys.size();
}
}
}
| Improve error logging in stats
| src/peergos/server/UserStats.java | Improve error logging in stats | <ide><path>rc/peergos/server/UserStats.java
<ide> NetworkAccess network = Builder.buildJavaNetworkAccess(new URL("https://beta.peergos.net"), true).get();
<ide> List<String> usernames = network.coreNode.getUsernames("").get();
<ide> ForkJoinPool pool = new ForkJoinPool(20);
<add> List<String> errors = Collections.synchronizedList(new ArrayList<>());
<ide> List<Summary> summaries = pool.submit(() -> usernames.stream().parallel().flatMap(username -> {
<add> List<Multihash> hosts = Collections.emptyList();
<ide> try {
<ide> List<UserPublicKeyLink> chain = network.coreNode.getChain(username).get();
<ide> UserPublicKeyLink last = chain.get(chain.size() - 1);
<ide> LocalDate expiry = last.claim.expiry;
<del> List<Multihash> hosts = last.claim.storageProviders;
<add> hosts = last.claim.storageProviders;
<ide> PublicKeyHash owner = last.owner;
<ide> Set<PublicKeyHash> ownedKeysRecursive =
<ide> WriterData.getOwnedKeysRecursive(username, network.coreNode, network.mutable,
<ide> System.out.println(summary);
<ide> return Stream.of(new Summary(username, expiry, total, hosts, ownedKeysRecursive));
<ide> } catch (Exception e) {
<del> System.err.println("Error for " + username);
<add> String host = hosts.stream().findFirst().map(Object::toString).orElse("");
<add> errors.add(username + ": " + host);
<add> System.err.println("Error for " + username + " on host " + host);
<ide> e.printStackTrace();
<ide> return Stream.empty();
<ide> }
<ide> }).collect(Collectors.toList())).join();
<add>
<add> System.out.println("Errors: " + errors.size());
<add> errors.forEach(System.out::println);
<ide>
<ide> // Sort by usage
<ide> sortAndPrint(summaries, (a, b) -> Long.compare(b.usage, a.usage), "usage.txt"); |
|
Java | apache-2.0 | a41c4f04bcee2ff72de100209823f7a1d5e5cebe | 0 | SpiralsSeminaire/openwayback,zubairkhatri/openwayback,bitzl/openwayback,efundamentals/openwayback,MohammedElsayyed/openwayback,kris-sigur/openwayback,kris-sigur/openwayback,iipc/openwayback,iipc/openwayback,JesseWeinstein/openwayback,nla/openwayback,SpiralsSeminaire/openwayback,sul-dlss/openwayback,kris-sigur/openwayback,nla/openwayback,zubairkhatri/openwayback,nla/openwayback,JesseWeinstein/openwayback,iipc/openwayback,JesseWeinstein/openwayback,nlnwa/openwayback,sul-dlss/openwayback,chasehd/openwayback,SpiralsSeminaire/openwayback,nla/openwayback,emijrp/openwayback,bitzl/openwayback,bitzl/openwayback,kris-sigur/openwayback,JesseWeinstein/openwayback,zubairkhatri/openwayback,SpiralsSeminaire/openwayback,JesseWeinstein/openwayback,nlnwa/openwayback,nla/openwayback,emijrp/openwayback,chasehd/openwayback,zubairkhatri/openwayback,emijrp/openwayback,kris-sigur/openwayback,emijrp/openwayback,ukwa/openwayback,MohammedElsayyed/openwayback,bitzl/openwayback,nlnwa/openwayback,SpiralsSeminaire/openwayback,nlnwa/openwayback,MohammedElsayyed/openwayback,efundamentals/openwayback,ukwa/openwayback,emijrp/openwayback,efundamentals/openwayback,nlnwa/openwayback,ukwa/openwayback,efundamentals/openwayback,sul-dlss/openwayback,efundamentals/openwayback,chasehd/openwayback,bitzl/openwayback | /* BaseReplayRenderer
*
* $Id$
*
* Created on 12:35:07 PM Apr 24, 2006.
*
* Copyright (C) 2006 Internet Archive.
*
* This file is part of wayback.
*
* wayback is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* any later version.
*
* wayback 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 Public License for more details.
*
* You should have received a copy of the GNU Lesser Public License
* along with wayback; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.archive.wayback.replay;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.archive.wayback.ReplayRenderer;
import org.archive.wayback.ResultURIConverter;
import org.archive.wayback.WaybackConstants;
import org.archive.wayback.archivalurl.TagMagix;
//import org.archive.wayback.core.PropertyConfiguration;
import org.archive.wayback.core.Resource;
import org.archive.wayback.core.SearchResult;
import org.archive.wayback.core.UIResults;
import org.archive.wayback.core.WaybackRequest;
import org.archive.wayback.exception.ConfigurationException;
import org.archive.wayback.exception.WaybackException;
import org.mozilla.universalchardet.UniversalDetector;
/**
*
*
* @author brad
* @version $Date$, $Revision$
*/
public class BaseReplayRenderer implements ReplayRenderer {
// in several places, this class defers generation of client responses
// to a .jsp file, once the business logic of replaying is done.
private String errorJsp = "/jsp/HTMLError.jsp";
private String imageErrorJsp = "/jsp/HTMLError.jsp";
private String javascriptErrorJsp = "/jsp/JavaScriptError.jsp";
private String cssErrorJsp = "/jsp/CSSError.jsp";
// if documents are marked up before sending to clients, the data is
// decoded into a String in chunks. This is how big a chunk to decode with.
private final static int C_BUFFER_SIZE = 4096;
// hand off this many bytes to the chardet library
private final static int MAX_CHARSET_READAHEAD = 65536;
// ...and if the chardet library fails, use the Content-Type header
private final static String HTTP_CONTENT_TYPE_HEADER = "Content-Type";
// ...if it also includes "charset="
private final static String CHARSET_TOKEN = "charset=";
private final static int BYTE_BUFFER_SIZE = 4096;
protected final Pattern IMAGE_REGEX = Pattern
.compile(".*\\.(jpg|jpeg|gif|png|bmp|tiff|tif)$");
/* INITIALIZATION: */
public void init(Properties p) throws ConfigurationException {
// PropertyConfiguration pc = new PropertyConfiguration(p);
// jspPath = pc.getString(JSP_PATH);
}
/* ERROR HANDLING RESPONSES: */
private boolean requestIsEmbedded(HttpServletRequest httpRequest,
WaybackRequest wbRequest) {
// without a wbRequest, assume it is not embedded: send back HTML
if(wbRequest == null) {
return false;
}
String referer = wbRequest.get(WaybackConstants.REQUEST_REFERER_URL);
return (referer != null && referer.length() > 0);
}
private boolean requestIsImage(HttpServletRequest httpRequest,
WaybackRequest wbRequest) {
String requestUrl = wbRequest.get(WaybackConstants.REQUEST_URL);
if (requestUrl == null)
return false;
Matcher matcher = IMAGE_REGEX.matcher(requestUrl);
return (matcher != null && matcher.matches());
}
private boolean requestIsJavascript(HttpServletRequest httpRequest,
WaybackRequest wbRequest) {
String requestUrl = wbRequest.get(WaybackConstants.REQUEST_URL);
return (requestUrl != null) && requestUrl.endsWith(".js");
}
private boolean requestIsCSS(HttpServletRequest httpRequest,
WaybackRequest wbRequest) {
String requestUrl = wbRequest.get(WaybackConstants.REQUEST_URL);
return (requestUrl != null) && requestUrl.endsWith(".css");
}
public void renderException(HttpServletRequest httpRequest,
HttpServletResponse httpResponse, WaybackRequest wbRequest,
WaybackException exception) throws ServletException, IOException {
// the "standard HTML" response handler:
String finalJspPath = errorJsp;
// try to not cause client errors by sending the HTML response if
// this request is ebedded, and is obviously one of the special types:
if (requestIsEmbedded(httpRequest, wbRequest)) {
if (requestIsJavascript(httpRequest, wbRequest)) {
finalJspPath = javascriptErrorJsp;
} else if (requestIsCSS(httpRequest, wbRequest)) {
finalJspPath = cssErrorJsp;
} else if (requestIsImage(httpRequest, wbRequest)) {
finalJspPath = imageErrorJsp;
}
}
httpRequest.setAttribute("exception", exception);
UIResults uiResults = new UIResults(wbRequest);
uiResults.storeInRequest(httpRequest, finalJspPath);
RequestDispatcher dispatcher = httpRequest
.getRequestDispatcher(finalJspPath);
dispatcher.forward(httpRequest, httpResponse);
}
/* GENERIC RESPONSE HELPER METHODS: */
/**
* Send the raw bytes from is (presumably the Resource/ARCRecord) to
* os (presumably the clients/HTTPResponse's OutputStream) with no
* decoding. Send them all as-is.
*
* @param is
* @param os
* @throws IOException
*/
protected void copy(InputStream is, OutputStream os) throws IOException {
byte[] buffer = new byte[BYTE_BUFFER_SIZE];
for (int r = -1; (r = is.read(buffer, 0, BYTE_BUFFER_SIZE)) != -1;) {
os.write(buffer, 0, r);
}
}
protected boolean isExactVersionRequested(WaybackRequest wbRequest,
SearchResult result) {
String reqDateStr = wbRequest.get(WaybackConstants.REQUEST_EXACT_DATE);
String resDateStr = result.get(WaybackConstants.RESULT_CAPTURE_DATE);
// some capture dates are not 14 digits, only compare as many
// digits as are in the result date:
return resDateStr.equals(reqDateStr.substring(0, resDateStr.length()));
}
/**
* test if the Resource and SearchResult should be replayed raw, without
* any markup.
*
* This version always indicates that the document should be returned raw,
* but is intended to be overriden.
*
* @param resource
* @param result
* @return boolean, true if the document should be returned raw.
*/
protected boolean isRawReplayResult(Resource resource,
SearchResult result) {
return true;
}
/**
* callback function for each HTTP header. If null is returned, header is
* omitted from final response to client, otherwise, the possibly modified
* http header value is returned to the client.
*
* This version just hands back all headers transparently, but is intended
* to be overriden.
*
* @param key
* @param value
* @param uriConverter
* @param result
* @return String
*/
protected String filterHeader(final String key, final String value,
final ResultURIConverter uriConverter, SearchResult result) {
return value;
}
/**
* Iterate over all HTTP headers in resource, possibly sending them on
* to the client. The determination as to omit, send as-is, or send modified
* is handled thru the overridable filterHeader() method.
*
* @param response
* @param resource
* @param uriConverter
* @param result
* @throws IOException
*/
protected void copyRecordHttpHeader(HttpServletResponse response,
Resource resource, ResultURIConverter uriConverter,
SearchResult result) throws IOException {
Properties headers = resource.getHttpHeaders();
int code = resource.getStatusCode();
// Only return legit status codes -- don't return any minus
// codes, etc.
if (code <= HttpServletResponse.SC_CONTINUE) {
String identifier = "";
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
"Bad status code " + code + " (" + identifier + ").");
return;
}
response.setStatus(code);
if (headers != null) {
for (Enumeration e = headers.keys(); e.hasMoreElements();) {
String key = (String) e.nextElement();
String value = (String) headers.get(key);
String finalValue = value;
if (value != null) {
finalValue = filterHeader(key, value, uriConverter, result);
if (finalValue == null) {
continue;
}
}
response.setHeader(key, (finalValue == null) ? "" : finalValue);
}
}
}
private String contentTypeToCharset(final String contentType) {
int offset = contentType.indexOf(CHARSET_TOKEN);
if (offset != -1) {
return contentType.substring(offset + CHARSET_TOKEN.length());
}
return null;
}
/**
* Attempt to divine the character encoding of the document from the
* Content-Type HTTP header (with a "charset=")
*
* @param resource
* @return String character set found or null if the header was not present
* @throws IOException
*/
protected String getCharsetFromHeaders(Resource resource)
throws IOException {
String charsetName = null;
Properties httpHeaders = resource.getHttpHeaders();
String ctype = httpHeaders.getProperty(HTTP_CONTENT_TYPE_HEADER);
if (ctype != null) {
charsetName = contentTypeToCharset(ctype);
}
return charsetName;
}
/**
* Attempt to find a META tag in the HTML that hints at the character set
* used to write the document.
*
* @param resource
* @return String character set found from META tags in the HTML
* @throws IOException
*/
protected String getCharsetFromMeta(Resource resource) throws IOException {
String charsetName = null;
byte[] bbuffer = new byte[MAX_CHARSET_READAHEAD];
resource.mark(MAX_CHARSET_READAHEAD);
resource.read(bbuffer, 0, MAX_CHARSET_READAHEAD);
resource.reset();
// convert to UTF-8 String -- which hopefully will not mess up the
// characters we're interested in...
StringBuilder sb = new StringBuilder(new String(bbuffer,"UTF-8"));
String metaContentType = TagMagix.getTagAttrWhere(sb, "META",
"content", "http-equiv", "Content-Type");
if(metaContentType != null) {
charsetName = contentTypeToCharset(metaContentType);
}
return charsetName;
}
/**
* Attempts to figure out the character set of the document using
* the excellent juniversalchardet library.
*
* @param resource
* @return String character encoding found, or null if nothing looked good.
* @throws IOException
*/
protected String getCharsetFromBytes(Resource resource) throws IOException {
String charsetName = null;
byte[] bbuffer = new byte[MAX_CHARSET_READAHEAD];
// (1)
UniversalDetector detector = new UniversalDetector(null);
// (2)
resource.mark(MAX_CHARSET_READAHEAD);
int len = resource.read(bbuffer, 0, MAX_CHARSET_READAHEAD);
resource.reset();
detector.handleData(bbuffer, 0, len);
// (3)
detector.dataEnd();
// (4)
charsetName = detector.getDetectedCharset();
// (5)
detector.reset();
return charsetName;
}
/**
* Use META tags, byte-character-detection, HTTP headers, hope, and prayer
* to figure out what character encoding is being used for the document.
* If nothing else works, assumes UTF-8 for now.
*
* @param resource
* @return String charset for Resource
* @throws IOException
*/
protected String getCharset(Resource resource) throws IOException {
String charSet = getCharsetFromMeta(resource);
if(charSet == null) {
charSet = getCharsetFromBytes(resource);
if(charSet == null) {
charSet = getCharsetFromHeaders(resource);
if(charSet == null) {
charSet = "UTF-8";
}
}
}
return charSet;
}
/**
* Do "stuff" to the StringBuilder page argument.
*
* This version does nothing at all, but is intended to be overridden.
*
* @param page
* @param httpRequest
* @param httpResponse
* @param wbRequest
* @param result
* @param resource
* @param uriConverter
*/
protected void markUpPage(StringBuilder page,
HttpServletRequest httpRequest, HttpServletResponse httpResponse,
WaybackRequest wbRequest, SearchResult result, Resource resource,
ResultURIConverter uriConverter) {
}
/* (non-Javadoc)
* @see org.archive.wayback.ReplayRenderer#renderResource(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, org.archive.wayback.core.WaybackRequest, org.archive.wayback.core.SearchResult, org.archive.wayback.core.Resource, org.archive.wayback.ResultURIConverter)
*/
public void renderResource(HttpServletRequest httpRequest,
HttpServletResponse httpResponse, WaybackRequest wbRequest,
SearchResult result, Resource resource,
ResultURIConverter uriConverter) throws ServletException,
IOException {
if (resource == null) {
throw new IllegalArgumentException("No resource");
}
if (result == null) {
throw new IllegalArgumentException("No result");
}
if (isRawReplayResult(resource,result)) {
resource.parseHeaders();
copyRecordHttpHeader(httpResponse, resource, uriConverter, result);
copy(resource, httpResponse.getOutputStream());
} else {
// We're going to do some markup on the page.
// first we'll need to convert the bytes to a String, which
// includes character encoding detection, then we'll call into the
// overridable markUpPage(), then we'll convert back to bytes and
// return them to the client
resource.parseHeaders();
copyRecordHttpHeader(httpResponse, resource, uriConverter, result);
int recordLength = (int) resource.getRecordLength();
// get the charset:
String charSet = getCharset(resource);
// convert bytes to characters for charset:
InputStreamReader isr = new InputStreamReader(resource, charSet);
char[] cbuffer = new char[C_BUFFER_SIZE];
// slurp the whole thing into RAM:
StringBuilder sbuffer = new StringBuilder(recordLength);
for (int r = -1; (r = isr.read(cbuffer, 0, C_BUFFER_SIZE)) != -1;) {
sbuffer.append(cbuffer, 0, r);
}
// do the "usual" markup:
markUpPage(sbuffer, httpRequest, httpResponse, wbRequest, result,
resource, uriConverter);
// back to bytes...
byte[] ba = sbuffer.toString().getBytes(charSet);
// inform browser how much is coming back:
httpResponse.setHeader("Content-Length", String.valueOf(ba.length));
// and send it out the door...
ServletOutputStream out = httpResponse.getOutputStream();
out.write(ba);
}
}
/**
* @return the errorJsp
*/
public String getErrorJsp() {
return errorJsp;
}
/**
* @param errorJsp the errorJsp to set
*/
public void setErrorJsp(String errorJsp) {
this.errorJsp = errorJsp;
}
/**
* @return the imageErrorJsp
*/
public String getImageErrorJsp() {
return imageErrorJsp;
}
/**
* @param imageErrorJsp the imageErrorJsp to set
*/
public void setImageErrorJsp(String imageErrorJsp) {
this.imageErrorJsp = imageErrorJsp;
}
/**
* @return the javascriptErrorJsp
*/
public String getJavascriptErrorJsp() {
return javascriptErrorJsp;
}
/**
* @param javascriptErrorJsp the javascriptErrorJsp to set
*/
public void setJavascriptErrorJsp(String javascriptErrorJsp) {
this.javascriptErrorJsp = javascriptErrorJsp;
}
/**
* @return the cssErrorJsp
*/
public String getCssErrorJsp() {
return cssErrorJsp;
}
/**
* @param cssErrorJsp the cssErrorJsp to set
*/
public void setCssErrorJsp(String cssErrorJsp) {
this.cssErrorJsp = cssErrorJsp;
}
}
| wayback-core/src/main/java/org/archive/wayback/replay/BaseReplayRenderer.java | /* BaseReplayRenderer
*
* $Id$
*
* Created on 12:35:07 PM Apr 24, 2006.
*
* Copyright (C) 2006 Internet Archive.
*
* This file is part of wayback.
*
* wayback is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* any later version.
*
* wayback 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 Public License for more details.
*
* You should have received a copy of the GNU Lesser Public License
* along with wayback; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.archive.wayback.replay;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.archive.wayback.ReplayRenderer;
import org.archive.wayback.ResultURIConverter;
import org.archive.wayback.WaybackConstants;
import org.archive.wayback.archivalurl.TagMagix;
import org.archive.wayback.core.PropertyConfiguration;
import org.archive.wayback.core.Resource;
import org.archive.wayback.core.SearchResult;
import org.archive.wayback.core.UIResults;
import org.archive.wayback.core.WaybackRequest;
import org.archive.wayback.exception.ConfigurationException;
import org.archive.wayback.exception.WaybackException;
import org.mozilla.universalchardet.UniversalDetector;
/**
*
*
* @author brad
* @version $Date$, $Revision$
*/
public class BaseReplayRenderer implements ReplayRenderer {
// in several places, this class defers generation of client responses
// to a .jsp file, once the business logic of replaying is done.
// this constant indicates the name of the configuration in the web.xml
// where the directory holding all the .jsps is found:
private final static String JSP_PATH = "replayui.jsppath";
// and this variable stores the .jsp directory configuration found
// at init() time
protected String jspPath;
// if documents are marked up before sending to clients, the data is
// decoded into a String in chunks. This is how big a chunk to decode with.
private final static int C_BUFFER_SIZE = 4096;
// hand off this many bytes to the chardet library
private final static int MAX_CHARSET_READAHEAD = 65536;
// ...and if the chardet library fails, use the Content-Type header
private final static String HTTP_CONTENT_TYPE_HEADER = "Content-Type";
// ...if it also includes "charset="
private final static String CHARSET_TOKEN = "charset=";
private final static int BYTE_BUFFER_SIZE = 4096;
protected final Pattern IMAGE_REGEX = Pattern
.compile(".*\\.(jpg|jpeg|gif|png|bmp|tiff|tif)$");
private final String ERROR_JSP = "ErrorResult.jsp";
private final String ERROR_JAVASCRIPT = "ErrorJavascript.jsp";
private final String ERROR_CSS = "ErrorCSS.jsp";
// Showing the 1 pixel gif actually blocks the alt text.. better to return
// a normal error page
// private final String ERROR_IMAGE = "error_image.gif";
private final String ERROR_IMAGE = "ErrorResult.jsp";
/* INITIALIZATION: */
public void init(Properties p) throws ConfigurationException {
PropertyConfiguration pc = new PropertyConfiguration(p);
jspPath = pc.getString(JSP_PATH);
}
/* ERROR HANDLING RESPONSES: */
private boolean requestIsEmbedded(HttpServletRequest httpRequest,
WaybackRequest wbRequest) {
// without a wbRequest, assume it is not embedded: send back HTML
if(wbRequest == null) {
return false;
}
String referer = wbRequest.get(WaybackConstants.REQUEST_REFERER_URL);
return (referer != null && referer.length() > 0);
}
private boolean requestIsImage(HttpServletRequest httpRequest,
WaybackRequest wbRequest) {
String requestUrl = wbRequest.get(WaybackConstants.REQUEST_URL);
if (requestUrl == null)
return false;
Matcher matcher = IMAGE_REGEX.matcher(requestUrl);
return (matcher != null && matcher.matches());
}
private boolean requestIsJavascript(HttpServletRequest httpRequest,
WaybackRequest wbRequest) {
String requestUrl = wbRequest.get(WaybackConstants.REQUEST_URL);
return (requestUrl != null) && requestUrl.endsWith(".js");
}
private boolean requestIsCSS(HttpServletRequest httpRequest,
WaybackRequest wbRequest) {
String requestUrl = wbRequest.get(WaybackConstants.REQUEST_URL);
return (requestUrl != null) && requestUrl.endsWith(".css");
}
public void renderException(HttpServletRequest httpRequest,
HttpServletResponse httpResponse, WaybackRequest wbRequest,
WaybackException exception) throws ServletException, IOException {
// the "standard HTML" response handler:
String finalJspPath = jspPath + "/" + ERROR_JSP;
// try to not cause client errors by sending the HTML response if
// this request is ebedded, and is obviously one of the special types:
if (requestIsEmbedded(httpRequest, wbRequest)) {
if (requestIsJavascript(httpRequest, wbRequest)) {
finalJspPath = jspPath + "/" + ERROR_JAVASCRIPT;
} else if (requestIsCSS(httpRequest, wbRequest)) {
finalJspPath = jspPath + "/" + ERROR_CSS;
} else if (requestIsImage(httpRequest, wbRequest)) {
finalJspPath = jspPath + "/" + ERROR_IMAGE;
}
}
httpRequest.setAttribute("exception", exception);
UIResults uiResults = new UIResults(wbRequest);
uiResults.storeInRequest(httpRequest);
RequestDispatcher dispatcher = httpRequest
.getRequestDispatcher(finalJspPath);
dispatcher.forward(httpRequest, httpResponse);
}
/* GENERIC RESPONSE HELPER METHODS: */
/**
* Send the raw bytes from is (presumably the Resource/ARCRecord) to
* os (presumably the clients/HTTPResponse's OutputStream) with no
* decoding. Send them all as-is.
*
* @param is
* @param os
* @throws IOException
*/
protected void copy(InputStream is, OutputStream os) throws IOException {
byte[] buffer = new byte[BYTE_BUFFER_SIZE];
for (int r = -1; (r = is.read(buffer, 0, BYTE_BUFFER_SIZE)) != -1;) {
os.write(buffer, 0, r);
}
}
protected boolean isExactVersionRequested(WaybackRequest wbRequest,
SearchResult result) {
String reqDateStr = wbRequest.get(WaybackConstants.REQUEST_EXACT_DATE);
String resDateStr = result.get(WaybackConstants.RESULT_CAPTURE_DATE);
// some capture dates are not 14 digits, only compare as many
// digits as are in the result date:
return resDateStr.equals(reqDateStr.substring(0, resDateStr.length()));
}
/**
* test if the Resource and SearchResult should be replayed raw, without
* any markup.
*
* This version always indicates that the document should be returned raw,
* but is intended to be overriden.
*
* @param resource
* @param result
* @return boolean, true if the document should be returned raw.
*/
protected boolean isRawReplayResult(Resource resource,
SearchResult result) {
return true;
}
/**
* callback function for each HTTP header. If null is returned, header is
* omitted from final response to client, otherwise, the possibly modified
* http header value is returned to the client.
*
* This version just hands back all headers transparently, but is intended
* to be overriden.
*
* @param key
* @param value
* @param uriConverter
* @param result
* @return String
*/
protected String filterHeader(final String key, final String value,
final ResultURIConverter uriConverter, SearchResult result) {
return value;
}
/**
* Iterate over all HTTP headers in resource, possibly sending them on
* to the client. The determination as to omit, send as-is, or send modified
* is handled thru the overridable filterHeader() method.
*
* @param response
* @param resource
* @param uriConverter
* @param result
* @throws IOException
*/
protected void copyRecordHttpHeader(HttpServletResponse response,
Resource resource, ResultURIConverter uriConverter,
SearchResult result) throws IOException {
Properties headers = resource.getHttpHeaders();
int code = resource.getStatusCode();
// Only return legit status codes -- don't return any minus
// codes, etc.
if (code <= HttpServletResponse.SC_CONTINUE) {
String identifier = "";
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
"Bad status code " + code + " (" + identifier + ").");
return;
}
response.setStatus(code);
if (headers != null) {
for (Enumeration e = headers.keys(); e.hasMoreElements();) {
String key = (String) e.nextElement();
String value = (String) headers.get(key);
String finalValue = value;
if (value != null) {
finalValue = filterHeader(key, value, uriConverter, result);
if (finalValue == null) {
continue;
}
}
response.setHeader(key, (finalValue == null) ? "" : finalValue);
}
}
}
private String contentTypeToCharset(final String contentType) {
int offset = contentType.indexOf(CHARSET_TOKEN);
if (offset != -1) {
return contentType.substring(offset + CHARSET_TOKEN.length());
}
return null;
}
/**
* Attempt to divine the character encoding of the document from the
* Content-Type HTTP header (with a "charset=")
*
* @param resource
* @return String character set found or null if the header was not present
* @throws IOException
*/
protected String getCharsetFromHeaders(Resource resource)
throws IOException {
String charsetName = null;
Properties httpHeaders = resource.getHttpHeaders();
String ctype = httpHeaders.getProperty(HTTP_CONTENT_TYPE_HEADER);
if (ctype != null) {
charsetName = contentTypeToCharset(ctype);
}
return charsetName;
}
/**
* Attempt to find a META tag in the HTML that hints at the character set
* used to write the document.
*
* @param resource
* @return String character set found from META tags in the HTML
* @throws IOException
*/
protected String getCharsetFromMeta(Resource resource) throws IOException {
String charsetName = null;
byte[] bbuffer = new byte[MAX_CHARSET_READAHEAD];
resource.mark(MAX_CHARSET_READAHEAD);
resource.read(bbuffer, 0, MAX_CHARSET_READAHEAD);
resource.reset();
// convert to UTF-8 String -- which hopefully will not mess up the
// characters we're interested in...
StringBuilder sb = new StringBuilder(new String(bbuffer,"UTF-8"));
String metaContentType = TagMagix.getTagAttrWhere(sb, "META",
"content", "http-equiv", "Content-Type");
if(metaContentType != null) {
charsetName = contentTypeToCharset(metaContentType);
}
return charsetName;
}
/**
* Attempts to figure out the character set of the document using
* the excellent juniversalchardet library.
*
* @param resource
* @return String character encoding found, or null if nothing looked good.
* @throws IOException
*/
protected String getCharsetFromBytes(Resource resource) throws IOException {
String charsetName = null;
byte[] bbuffer = new byte[MAX_CHARSET_READAHEAD];
// (1)
UniversalDetector detector = new UniversalDetector(null);
// (2)
resource.mark(MAX_CHARSET_READAHEAD);
int len = resource.read(bbuffer, 0, MAX_CHARSET_READAHEAD);
resource.reset();
detector.handleData(bbuffer, 0, len);
// (3)
detector.dataEnd();
// (4)
charsetName = detector.getDetectedCharset();
// (5)
detector.reset();
return charsetName;
}
/**
* Use META tags, byte-character-detection, HTTP headers, hope, and prayer
* to figure out what character encoding is being used for the document.
* If nothing else works, assumes UTF-8 for now.
*
* @param resource
* @return String charset for Resource
* @throws IOException
*/
protected String getCharset(Resource resource) throws IOException {
String charSet = getCharsetFromMeta(resource);
if(charSet == null) {
charSet = getCharsetFromBytes(resource);
if(charSet == null) {
charSet = getCharsetFromHeaders(resource);
if(charSet == null) {
charSet = "UTF-8";
}
}
}
return charSet;
}
/**
* Do "stuff" to the StringBuilder page argument.
*
* This version does nothing at all, but is intended to be overridden.
*
* @param page
* @param httpRequest
* @param httpResponse
* @param wbRequest
* @param result
* @param resource
* @param uriConverter
*/
protected void markUpPage(StringBuilder page,
HttpServletRequest httpRequest, HttpServletResponse httpResponse,
WaybackRequest wbRequest, SearchResult result, Resource resource,
ResultURIConverter uriConverter) {
}
/* (non-Javadoc)
* @see org.archive.wayback.ReplayRenderer#renderResource(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, org.archive.wayback.core.WaybackRequest, org.archive.wayback.core.SearchResult, org.archive.wayback.core.Resource, org.archive.wayback.ResultURIConverter)
*/
public void renderResource(HttpServletRequest httpRequest,
HttpServletResponse httpResponse, WaybackRequest wbRequest,
SearchResult result, Resource resource,
ResultURIConverter uriConverter) throws ServletException,
IOException {
if (resource == null) {
throw new IllegalArgumentException("No resource");
}
if (result == null) {
throw new IllegalArgumentException("No result");
}
if (isRawReplayResult(resource,result)) {
resource.parseHeaders();
copyRecordHttpHeader(httpResponse, resource, uriConverter, result);
copy(resource, httpResponse.getOutputStream());
} else {
// We're going to do some markup on the page.
// first we'll need to convert the bytes to a String, which
// includes character encoding detection, then we'll call into the
// overridable markUpPage(), then we'll convert back to bytes and
// return them to the client
resource.parseHeaders();
copyRecordHttpHeader(httpResponse, resource, uriConverter, result);
int recordLength = (int) resource.getRecordLength();
// get the charset:
String charSet = getCharset(resource);
// convert bytes to characters for charset:
InputStreamReader isr = new InputStreamReader(resource, charSet);
char[] cbuffer = new char[C_BUFFER_SIZE];
// slurp the whole thing into RAM:
StringBuilder sbuffer = new StringBuilder(recordLength);
for (int r = -1; (r = isr.read(cbuffer, 0, C_BUFFER_SIZE)) != -1;) {
sbuffer.append(cbuffer, 0, r);
}
// do the "usual" markup:
markUpPage(sbuffer, httpRequest, httpResponse, wbRequest, result,
resource, uriConverter);
// back to bytes...
byte[] ba = sbuffer.toString().getBytes(charSet);
// inform browser how much is coming back:
httpResponse.setHeader("Content-Length", String.valueOf(ba.length));
// and send it out the door...
ServletOutputStream out = httpResponse.getOutputStream();
out.write(ba);
}
}
/**
* @return the jspPath
*/
public String getJspPath() {
return jspPath;
}
/**
* @param jspPath the jspPath to set
*/
public void setJspPath(String jspPath) {
this.jspPath = jspPath;
}
}
| FEATURE: added getters/setters for Spring configuration of the various error rendering .jsps
git-svn-id: ca6d9ebf75caaf710f0e3a4ee74a890c456d4c90@1812 69e27eb3-6e27-0410-b9c6-fffd7e226fab
| wayback-core/src/main/java/org/archive/wayback/replay/BaseReplayRenderer.java | FEATURE: added getters/setters for Spring configuration of the various error rendering .jsps | <ide><path>ayback-core/src/main/java/org/archive/wayback/replay/BaseReplayRenderer.java
<ide> import org.archive.wayback.ResultURIConverter;
<ide> import org.archive.wayback.WaybackConstants;
<ide> import org.archive.wayback.archivalurl.TagMagix;
<del>import org.archive.wayback.core.PropertyConfiguration;
<add>//import org.archive.wayback.core.PropertyConfiguration;
<ide> import org.archive.wayback.core.Resource;
<ide> import org.archive.wayback.core.SearchResult;
<ide> import org.archive.wayback.core.UIResults;
<ide> // in several places, this class defers generation of client responses
<ide> // to a .jsp file, once the business logic of replaying is done.
<ide>
<del> // this constant indicates the name of the configuration in the web.xml
<del> // where the directory holding all the .jsps is found:
<del> private final static String JSP_PATH = "replayui.jsppath";
<del>
<del> // and this variable stores the .jsp directory configuration found
<del> // at init() time
<del> protected String jspPath;
<del>
<add> private String errorJsp = "/jsp/HTMLError.jsp";
<add> private String imageErrorJsp = "/jsp/HTMLError.jsp";
<add> private String javascriptErrorJsp = "/jsp/JavaScriptError.jsp";
<add> private String cssErrorJsp = "/jsp/CSSError.jsp";
<add>
<ide> // if documents are marked up before sending to clients, the data is
<ide> // decoded into a String in chunks. This is how big a chunk to decode with.
<ide> private final static int C_BUFFER_SIZE = 4096;
<ide> private final static String CHARSET_TOKEN = "charset=";
<ide>
<ide> private final static int BYTE_BUFFER_SIZE = 4096;
<del>
<ide>
<del>
<ide> protected final Pattern IMAGE_REGEX = Pattern
<ide> .compile(".*\\.(jpg|jpeg|gif|png|bmp|tiff|tif)$");
<ide>
<del> private final String ERROR_JSP = "ErrorResult.jsp";
<del>
<del> private final String ERROR_JAVASCRIPT = "ErrorJavascript.jsp";
<del>
<del> private final String ERROR_CSS = "ErrorCSS.jsp";
<del>
<del> // Showing the 1 pixel gif actually blocks the alt text.. better to return
<del> // a normal error page
<del>// private final String ERROR_IMAGE = "error_image.gif";
<del> private final String ERROR_IMAGE = "ErrorResult.jsp";
<del>
<ide> /* INITIALIZATION: */
<ide>
<ide> public void init(Properties p) throws ConfigurationException {
<del> PropertyConfiguration pc = new PropertyConfiguration(p);
<del> jspPath = pc.getString(JSP_PATH);
<add>// PropertyConfiguration pc = new PropertyConfiguration(p);
<add>// jspPath = pc.getString(JSP_PATH);
<ide> }
<ide>
<ide> /* ERROR HANDLING RESPONSES: */
<ide> WaybackException exception) throws ServletException, IOException {
<ide>
<ide> // the "standard HTML" response handler:
<del> String finalJspPath = jspPath + "/" + ERROR_JSP;
<add> String finalJspPath = errorJsp;
<ide>
<ide> // try to not cause client errors by sending the HTML response if
<ide> // this request is ebedded, and is obviously one of the special types:
<ide>
<ide> if (requestIsJavascript(httpRequest, wbRequest)) {
<ide>
<del> finalJspPath = jspPath + "/" + ERROR_JAVASCRIPT;
<add> finalJspPath = javascriptErrorJsp;
<ide>
<ide> } else if (requestIsCSS(httpRequest, wbRequest)) {
<ide>
<del> finalJspPath = jspPath + "/" + ERROR_CSS;
<add> finalJspPath = cssErrorJsp;
<ide>
<ide> } else if (requestIsImage(httpRequest, wbRequest)) {
<ide>
<del> finalJspPath = jspPath + "/" + ERROR_IMAGE;
<add> finalJspPath = imageErrorJsp;
<ide>
<ide> }
<ide> }
<ide>
<ide> httpRequest.setAttribute("exception", exception);
<ide> UIResults uiResults = new UIResults(wbRequest);
<del> uiResults.storeInRequest(httpRequest);
<add> uiResults.storeInRequest(httpRequest, finalJspPath);
<ide>
<ide> RequestDispatcher dispatcher = httpRequest
<ide> .getRequestDispatcher(finalJspPath);
<ide> }
<ide>
<ide> /**
<del> * @return the jspPath
<del> */
<del> public String getJspPath() {
<del> return jspPath;
<del> }
<del>
<del> /**
<del> * @param jspPath the jspPath to set
<del> */
<del> public void setJspPath(String jspPath) {
<del> this.jspPath = jspPath;
<add> * @return the errorJsp
<add> */
<add> public String getErrorJsp() {
<add> return errorJsp;
<add> }
<add>
<add> /**
<add> * @param errorJsp the errorJsp to set
<add> */
<add> public void setErrorJsp(String errorJsp) {
<add> this.errorJsp = errorJsp;
<add> }
<add>
<add> /**
<add> * @return the imageErrorJsp
<add> */
<add> public String getImageErrorJsp() {
<add> return imageErrorJsp;
<add> }
<add>
<add> /**
<add> * @param imageErrorJsp the imageErrorJsp to set
<add> */
<add> public void setImageErrorJsp(String imageErrorJsp) {
<add> this.imageErrorJsp = imageErrorJsp;
<add> }
<add>
<add> /**
<add> * @return the javascriptErrorJsp
<add> */
<add> public String getJavascriptErrorJsp() {
<add> return javascriptErrorJsp;
<add> }
<add>
<add> /**
<add> * @param javascriptErrorJsp the javascriptErrorJsp to set
<add> */
<add> public void setJavascriptErrorJsp(String javascriptErrorJsp) {
<add> this.javascriptErrorJsp = javascriptErrorJsp;
<add> }
<add>
<add> /**
<add> * @return the cssErrorJsp
<add> */
<add> public String getCssErrorJsp() {
<add> return cssErrorJsp;
<add> }
<add>
<add> /**
<add> * @param cssErrorJsp the cssErrorJsp to set
<add> */
<add> public void setCssErrorJsp(String cssErrorJsp) {
<add> this.cssErrorJsp = cssErrorJsp;
<ide> }
<ide> } |
|
JavaScript | mit | d4354cc908db8ad7e9d32fe79bf03b0d3596f89b | 0 | RobLoach/kss-node,RobLoach/kss-node,RobLoach/kss-node | /* eslint-disable max-nested-callbacks */
'use strict';
describe('KssStyleGuide object API', function() {
before(function() {
return Promise.all([
helperUtils.traverseFixtures({mask: /(sections\-queries|sections\-order|property\-styleguide\-word\-keys)\.less/}).then(styleGuide => {
this.styleGuide = styleGuide;
}),
helperUtils.traverseFixtures({mask: /.*\-word\-phrases\.less/}).then(styleGuide => {
this.styleGuideWordPhrases = styleGuide;
}),
helperUtils.traverseFixtures({mask: /sections\-queries\.less/}).then(styleGuide => {
this.styleGuideNumeric = styleGuide;
})
]);
});
/* eslint-disable guard-for-in,no-loop-func */
['toJSON',
'autoInit',
'init',
'customPropertyNames',
'hasNumericReferences',
'referenceDelimiter',
'sections'
].forEach(function(method) {
it('has ' + method + '() method', function(done) {
expect(new kss.KssStyleGuide({})).to.respondTo(method);
done();
});
});
/* eslint-enable guard-for-in,no-loop-func */
describe('KssStyleGuide constructor', function() {
it('should initialize the data', function(done) {
let obj = new kss.KssStyleGuide();
expect(obj).to.have.property('meta');
expect(obj.meta).to.have.property('autoInit');
expect(obj.meta).to.have.property('files');
expect(obj.meta).to.have.property('hasNumericReferences');
expect(obj.meta).to.have.property('needsDepth');
expect(obj.meta).to.have.property('needsReferenceNumber');
expect(obj.meta).to.have.property('needsSort');
expect(obj.meta).to.have.property('referenceDelimiter');
expect(obj.meta).to.have.property('referenceMap');
expect(obj.meta).to.have.property('weightMap');
expect(obj).to.have.property('data');
expect(obj.data).to.have.property('customPropertyNames');
expect(obj.data).to.have.property('sections');
done();
});
});
describe('.toJSON()', function() {
it('should return valid JSON object', function(done) {
expect(this.styleGuide.toJSON()).to.be.an.instanceOf(Object);
// Verify it converts to a JSON string.
let str = JSON.stringify(this.styleGuide.toJSON());
expect(str).to.be.string;
// Compare JSON string to original.
expect(JSON.parse(str)).to.deep.equal(this.styleGuide.toJSON());
done();
});
it('should output the same data given to constructor', function(done) {
let data = {
customPropertyNames: ['custom1', 'custom2'],
hasNumericReferences: true,
referenceDelimiter: '.',
sections: [
{
deprecated: false,
depth: 2,
description: 'lorem ipsum',
experimental: false,
header: 'example',
markup: '<div class="example">lorem ipsum</div>',
modifiers: [],
parameters: [],
reference: '1.1',
referenceNumber: '1.1',
referenceURI: '1-1',
weight: 0
}
]
};
let styleGuide = new kss.KssStyleGuide(data);
expect(styleGuide.toJSON()).to.deep.equal(data);
done();
});
});
describe('.autoInit()', function() {
it('should update meta.autoInit if given true', function(done) {
let styleGuide = new kss.KssStyleGuide({autoInit: false});
styleGuide.autoInit(true);
expect(styleGuide.meta.autoInit).to.be.true;
done();
});
it('should update meta.autoInit if given false', function(done) {
let styleGuide = new kss.KssStyleGuide();
styleGuide.autoInit(false);
expect(styleGuide.meta.autoInit).to.be.false;
done();
});
it('should return itself', function(done) {
let styleGuide = new kss.KssStyleGuide({autoInit: false});
expect(styleGuide.autoInit(true)).to.deep.equal(styleGuide);
done();
});
});
describe('.init()', function() {
it('it should re-sort the style guide when new sections are added', function() {
let styleGuide = new kss.KssStyleGuide({
sections: [
{header: 'Section 1.3', reference: '1.3'},
{header: 'Section 1.1', reference: '1.1'}
],
autoInit: false
});
styleGuide.sections({header: 'Section 1.2', reference: '1.2'});
expect(styleGuide.data.sections.map(section => section.reference())).to.deep.equal(['1.3', '1.1', '1.2']);
styleGuide.init();
expect(styleGuide.data.sections.map(section => section.reference())).to.deep.equal(['1.1', '1.2', '1.3']);
});
it('it should auto-increment sections in the style guide', function() {
let styleGuide = new kss.KssStyleGuide({
sections: [
{header: 'Section 1.1', reference: 'section.1'},
{header: 'Section 1.2', reference: 'section.2'},
{header: 'Section 1.3', reference: 'section.3'}
],
autoInit: false
});
styleGuide.sections();
expect(styleGuide.data.sections.map(section => section.referenceNumber())).to.deep.equal(['', '', '']);
styleGuide.meta.needsSort = false;
styleGuide.init();
expect(styleGuide.data.sections.map(section => section.referenceNumber())).to.deep.equal(['1.1', '1.2', '1.3']);
});
});
describe('.customPropertyNames()', function() {
it('should return data.customPropertyNames', function(done) {
expect(this.styleGuide.customPropertyNames()).to.equal(this.styleGuide.data.customPropertyNames);
done();
});
it('should update data.customPropertyNames if given a string', function(done) {
let styleGuide = new kss.KssStyleGuide({customPropertyNames: ['original']});
styleGuide.customPropertyNames('new');
expect(styleGuide.data.customPropertyNames).to.deep.equal(['original', 'new']);
done();
});
it('should update data.customPropertyNames if given an array', function(done) {
let styleGuide = new kss.KssStyleGuide({customPropertyNames: ['original']});
styleGuide.customPropertyNames(['new', 'new2']);
expect(styleGuide.data.customPropertyNames).to.deep.equal(['original', 'new', 'new2']);
done();
});
it('should return itself if given a value', function(done) {
let styleGuide = new kss.KssStyleGuide({customPropertyNames: ['original']});
expect(styleGuide.customPropertyNames('new')).to.deep.equal(styleGuide);
done();
});
});
describe('.hasNumericReferences()', function() {
it('should return meta.hasNumericReferences', function(done) {
expect(this.styleGuide.hasNumericReferences()).to.equal(this.styleGuide.meta.hasNumericReferences).and.to.be.false;
expect(this.styleGuideNumeric.hasNumericReferences()).to.equal(this.styleGuideNumeric.meta.hasNumericReferences).and.to.be.true;
expect(this.styleGuideWordPhrases.hasNumericReferences()).to.equal(this.styleGuideWordPhrases.meta.hasNumericReferences).and.to.be.false;
done();
});
});
describe('.referenceDelimiter()', function() {
it('should return meta.referenceDelimiter', function(done) {
expect(this.styleGuide.referenceDelimiter()).to.equal(this.styleGuide.meta.referenceDelimiter).and.to.equal('.');
expect(this.styleGuideNumeric.referenceDelimiter()).to.equal(this.styleGuideNumeric.meta.referenceDelimiter).and.to.equal('.');
expect(this.styleGuideWordPhrases.referenceDelimiter()).to.equal(this.styleGuideWordPhrases.meta.referenceDelimiter).and.to.equal(' - ');
done();
});
});
describe('.sections()', function() {
context('given new sections', function() {
it('it should add a JSON section to the style guide', function() {
let styleGuide = new kss.KssStyleGuide({
sections: [
{header: 'Section 1.3', reference: '1.3'},
{header: 'Section 1.1', reference: '1.1'}
]
});
styleGuide.sections({header: 'Section 1.2', reference: '1.2'});
expect(styleGuide.data.sections.map(section => section.reference())).to.deep.equal(['1.1', '1.2', '1.3']);
expect(styleGuide.meta.referenceMap['1.2'].header()).to.equal('Section 1.2');
});
it('it should add a KssSection to the style guide', function() {
let styleGuide = new kss.KssStyleGuide({
sections: [
{header: 'Section 1.3', reference: '1.3'},
{header: 'Section 1.1', reference: '1.1'}
]
});
let section = new kss.KssSection({header: 'Section 1.2', reference: '1.2'});
styleGuide.sections(section);
expect(styleGuide.data.sections.map(section => section.reference())).to.deep.equal(['1.1', '1.2', '1.3']);
expect(styleGuide.meta.referenceMap['1.2']).to.deep.equal(section);
});
});
context('given no arguments', function() {
it('should return all referenced sections', function(done) {
let results = [],
expected = [
'4', '4.1',
'4.1.1', '4.1.1.1', '4.1.1.2',
'4.1.2', '4.1.2.2',
'8',
'9', '9.1', '9.1.1', '9.2', '9.3', '9.4', '9.5', '9.10', '9.11', '9.100',
'alpha', 'alpha.alpha', 'alpha.alpha.alpha', 'alpha.beta', 'alpha.delta', 'alpha.epsilon', 'alpha.gamma', 'alpha-bet',
'WordKeys.Base.Link', 'WordKeys.Components', 'WordKeys.Components.Message', 'WordKeys.Components.Tabs', 'WordKeys.Forms.Button', 'WordKeys.Forms.Input'
];
this.styleGuide.sections().map(function(section) {
results.push(section.reference());
});
expect(results).to.deep.equal(expected);
done();
});
});
context('given exact references', function() {
it('should find a reference with depth 1', function(done) {
let section = this.styleGuide.sections('4');
expect(section.header()).to.equal('DEPTH OF 1');
expect(section.depth()).to.equal(1);
expect(section.reference()).to.equal('4');
done();
});
it('should find a reference with depth 3 and no modifiers', function(done) {
let section = this.styleGuide.sections('4.1.1');
expect(section.header()).to.equal('DEPTH OF 3, NO MODIFIERS');
expect(section.reference()).to.equal('4.1.1');
expect(section.depth()).to.equal(3);
done();
});
it('should find a reference with depth 3 and modifiers', function(done) {
let section = this.styleGuide.sections('4.1.2');
expect(section.header()).to.equal('DEPTH OF 3, MODIFIERS');
expect(section.depth()).to.equal(3);
expect(section.reference()).to.equal('4.1.2');
done();
});
it('should not find a reference with depth 3 that does not exist', function(done) {
expect(this.styleGuide.sections('4.1.3')).to.be.false;
done();
});
it('should find a reference with depth 4 (A)', function(done) {
let section = this.styleGuide.sections('4.1.1.1');
expect(section.header()).to.equal('DEPTH OF 4 (A)');
expect(section.depth()).to.equal(4);
expect(section.reference()).to.equal('4.1.1.1');
done();
});
it('should find a reference with depth 4 (B)', function(done) {
let section = this.styleGuide.sections('4.1.1.2');
expect(section.header()).to.equal('DEPTH OF 4 (B)');
expect(section.depth()).to.equal(4);
expect(section.reference()).to.equal('4.1.1.2');
done();
});
it('should find a reference with depth 4 (C)', function(done) {
let section = this.styleGuide.sections('4.1.2.2');
expect(section.header()).to.equal('DEPTH OF 4 (C)');
expect(section.depth()).to.equal(4);
expect(section.reference()).to.equal('4.1.2.2');
done();
});
});
context('given string queries', function() {
it('should return 1 level of descendants when given "4.x"', function(done) {
let sections = this.styleGuide.sections('4.x');
sections.map(function(section) {
expect(section.reference()).to.equal('4.1');
expect(section.header()).to.equal('DEPTH OF 2');
});
expect(sections.length).to.equal(1);
done();
});
it('should return 1 level of descendants when given "4.1.x"', function(done) {
let expected = ['4.1.1', '4.1.2'];
let results = this.styleGuide.sections('4.1.x').map(function(section) {
return section.reference();
});
expect(results).to.deep.equal(expected);
done();
});
it('should return 2 levels of descendants when given "4.x.x"', function(done) {
let expected = ['4.1', '4.1.1', '4.1.2'];
let results = this.styleGuide.sections('4.x.x').map(function(section) {
return section.reference();
});
expect(results).to.deep.equal(expected);
done();
});
it('should return "4.1" and all levels of descendants when given "4.1.*"', function(done) {
let results,
expected = ['4.1', '4.1.1', '4.1.1.1', '4.1.1.2', '4.1.2', '4.1.2.2'];
results = this.styleGuide.sections('4.1.*').map(function(section) {
return section.reference();
});
expect(results).to.deep.equal(expected);
done();
});
it('should not find "alpha" section when given a query for "alp.*"', function(done) {
expect(this.styleGuide.sections('alp.*')).to.be.an.instanceOf(Array);
expect(this.styleGuide.sections('alp.*')).to.have.length(0);
done();
});
it('should not find "alpha" section when given a query for "alp.x"', function(done) {
expect(this.styleGuide.sections('alp.x')).to.be.an.instanceOf(Array);
expect(this.styleGuide.sections('alp.x')).to.have.length(0);
done();
});
it('should return numeric sections in order', function(done) {
let expected = ['9.1', '9.2', '9.3', '9.4', '9.5', '9.10', '9.11', '9.100'];
let results = this.styleGuide.sections('9.x').map(function(section) {
return section.reference();
});
expect(results).to.deep.equal(expected);
done();
});
it('should return "word key" sections in order', function(done) {
let expected = ['alpha.alpha', 'alpha.beta', 'alpha.delta', 'alpha.epsilon', 'alpha.gamma'];
let results = this.styleGuide.sections('alpha.x').map(function(section) {
return section.reference();
});
expect(results).to.deep.equal(expected);
done();
});
it('should return "word key" sections with dashes in the name', function(done) {
let sections = this.styleGuide.sections('alpha-bet.*');
sections.map(function(section) {
expect(section.reference()).to.equal('alpha-bet');
});
expect(sections.length).to.equal(1);
done();
});
it('should return "word phrase" sections in order', function(done) {
let expected = ['beta - alpha', 'beta - beta', 'beta - delta', 'beta - epsilon', 'beta - gamma'];
let results = this.styleGuideWordPhrases.sections('beta.x').map(function(section) {
return section.reference();
});
expect(results).to.deep.equal(expected);
done();
});
});
context('given regex queries', function() {
it('should return an empty array when query does not match', function(done) {
expect(this.styleGuide.sections(/__does_not_match__.*/)).to.be.an.instanceOf(Array).and.empty;
done();
});
it('should return "4" and all levels of descendants when given /4.*/', function(done) {
let expected = ['4', '4.1', '4.1.1', '4.1.1.1', '4.1.1.2', '4.1.2', '4.1.2.2'];
let results = this.styleGuide.sections(/4.*/).map(function(section) {
return section.reference();
});
expect(results).to.deep.equal(expected);
done();
});
it('should return "4" when given /4/', function(done) {
let sections = this.styleGuide.sections(/4/);
sections.map(function(section) {
expect(section.reference()).to.equal('4');
});
expect(sections.length).to.equal(1);
done();
});
it('should return numeric sections in order', function(done) {
let expected = ['9', '9.1', '9.1.1', '9.2', '9.3', '9.4', '9.5', '9.10', '9.11', '9.100'];
let results = this.styleGuide.sections(/9.*/).map(function(section) {
return section.reference();
});
expect(results).to.deep.equal(expected);
done();
});
it('should return "word key" sections in order', function(done) {
let expected = ['alpha.alpha', 'alpha.alpha.alpha', 'alpha.beta', 'alpha.delta', 'alpha.epsilon', 'alpha.gamma'];
let results = this.styleGuide.sections(/alpha\..*/).map(function(section) {
return section.reference();
});
expect(results).to.deep.equal(expected);
done();
});
it('should return "word phrase" sections in order', function(done) {
let expected = ['beta - alpha', 'beta - alpha - alpha', 'beta - beta', 'beta - delta', 'beta - epsilon', 'beta - gamma'];
let results = this.styleGuideWordPhrases.sections(/beta - .*/).map(function(section) {
return section.reference();
});
expect(results).to.deep.equal(expected);
done();
});
it('should return weighted "word phrase" sections in order', function(done) {
let expected = ['gamma - alpha', 'gamma - alpha - delta', 'gamma - alpha - gamma', 'gamma - alpha - beta', 'gamma - alpha - alpha', 'gamma - beta', 'gamma - gamma', 'gamma - delta', 'gamma - epsilon'];
let results = this.styleGuideWordPhrases.sections(/gamma - .*/).map(function(section) {
return section.reference();
});
expect(results).to.deep.equal(expected);
done();
});
it('should return referenceNumber values for "word phrase" sections in order', function(done) {
let expected = ['2.1', '2.1.1', '2.1.2', '2.1.3', '2.1.4', '2.2', '2.3', '2.4', '2.5'];
let results = this.styleGuideWordPhrases.sections(/gamma - .*/).map(function(section) {
return section.referenceNumber();
});
expect(results).to.deep.equal(expected);
done();
});
});
});
});
| test/test_kss_styleguide.js | /* eslint-disable max-nested-callbacks */
'use strict';
describe('KssStyleGuide object API', function() {
before(function() {
return Promise.all([
helperUtils.traverseFixtures({mask: /(sections\-queries|sections\-order|property\-styleguide\-word\-keys)\.less/}).then(styleGuide => {
this.styleGuide = styleGuide;
}),
helperUtils.traverseFixtures({mask: /.*\-word\-phrases\.less/}).then(styleGuide => {
this.styleGuideWordPhrases = styleGuide;
}),
helperUtils.traverseFixtures({mask: /sections\-queries\.less/}).then(styleGuide => {
this.styleGuideNumeric = styleGuide;
})
]);
});
/* eslint-disable guard-for-in,no-loop-func */
['toJSON',
'autoInit',
'init',
'customPropertyNames',
'hasNumericReferences',
'referenceDelimiter',
'sections'
].forEach(function(method) {
it('has ' + method + '() method', function(done) {
expect(new kss.KssStyleGuide({})).to.respondTo(method);
done();
});
});
/* eslint-enable guard-for-in,no-loop-func */
describe('KssStyleGuide constructor', function() {
it('should initialize the data', function(done) {
let obj = new kss.KssStyleGuide();
expect(obj).to.have.property('meta');
expect(obj.meta).to.have.property('autoInit');
expect(obj.meta).to.have.property('files');
expect(obj.meta).to.have.property('hasNumericReferences');
expect(obj.meta).to.have.property('needsDepth');
expect(obj.meta).to.have.property('needsReferenceNumber');
expect(obj.meta).to.have.property('needsSort');
expect(obj.meta).to.have.property('referenceDelimiter');
expect(obj.meta).to.have.property('referenceMap');
expect(obj.meta).to.have.property('weightMap');
expect(obj).to.have.property('data');
expect(obj.data).to.have.property('customPropertyNames');
expect(obj.data).to.have.property('sections');
done();
});
});
describe('.toJSON()', function() {
it('should return valid JSON object', function(done) {
expect(this.styleGuide.toJSON()).to.be.an.instanceOf(Object);
// Verify it converts to a JSON string.
let str = JSON.stringify(this.styleGuide.toJSON());
expect(str).to.be.string;
// Compare JSON string to original.
expect(JSON.parse(str)).to.deep.equal(this.styleGuide.toJSON());
done();
});
it('should output the same data given to constructor', function(done) {
let data = {
customPropertyNames: ['custom1', 'custom2'],
hasNumericReferences: true,
referenceDelimiter: '.',
sections: [
{
deprecated: false,
depth: 2,
description: 'lorem ipsum',
experimental: false,
header: 'example',
markup: '<div class="example">lorem ipsum</div>',
modifiers: [],
parameters: [],
reference: '1.1',
referenceNumber: '1.1',
referenceURI: '1-1',
weight: 0
}
]
};
let styleGuide = new kss.KssStyleGuide(data);
expect(styleGuide.toJSON()).to.deep.equal(data);
done();
});
});
describe('.autoInit()', function() {
it('should update meta.autoInit if given true', function(done) {
let styleGuide = new kss.KssStyleGuide({autoInit: false});
styleGuide.autoInit(true);
expect(styleGuide.meta.autoInit).to.be.true;
done();
});
it('should update meta.autoInit if given false', function(done) {
let styleGuide = new kss.KssStyleGuide();
styleGuide.autoInit(false);
expect(styleGuide.meta.autoInit).to.be.false;
done();
});
it('should return itself', function(done) {
let styleGuide = new kss.KssStyleGuide({autoInit: false});
expect(styleGuide.autoInit(true)).to.deep.equal(styleGuide);
done();
});
});
describe('.init()', function() {
it('should do things');
});
describe('.customPropertyNames()', function() {
it('should return data.customPropertyNames', function(done) {
expect(this.styleGuide.customPropertyNames()).to.equal(this.styleGuide.data.customPropertyNames);
done();
});
it('should update data.customPropertyNames if given a string', function(done) {
let styleGuide = new kss.KssStyleGuide({customPropertyNames: ['original']});
styleGuide.customPropertyNames('new');
expect(styleGuide.data.customPropertyNames).to.deep.equal(['original', 'new']);
done();
});
it('should update data.customPropertyNames if given an array', function(done) {
let styleGuide = new kss.KssStyleGuide({customPropertyNames: ['original']});
styleGuide.customPropertyNames(['new', 'new2']);
expect(styleGuide.data.customPropertyNames).to.deep.equal(['original', 'new', 'new2']);
done();
});
it('should return itself if given a value', function(done) {
let styleGuide = new kss.KssStyleGuide({customPropertyNames: ['original']});
expect(styleGuide.customPropertyNames('new')).to.deep.equal(styleGuide);
done();
});
});
describe('.hasNumericReferences()', function() {
it('should return meta.hasNumericReferences', function(done) {
expect(this.styleGuide.hasNumericReferences()).to.equal(this.styleGuide.meta.hasNumericReferences).and.to.be.false;
expect(this.styleGuideNumeric.hasNumericReferences()).to.equal(this.styleGuideNumeric.meta.hasNumericReferences).and.to.be.true;
expect(this.styleGuideWordPhrases.hasNumericReferences()).to.equal(this.styleGuideWordPhrases.meta.hasNumericReferences).and.to.be.false;
done();
});
});
describe('.referenceDelimiter()', function() {
it('should return meta.referenceDelimiter', function(done) {
expect(this.styleGuide.referenceDelimiter()).to.equal(this.styleGuide.meta.referenceDelimiter).and.to.equal('.');
expect(this.styleGuideNumeric.referenceDelimiter()).to.equal(this.styleGuideNumeric.meta.referenceDelimiter).and.to.equal('.');
expect(this.styleGuideWordPhrases.referenceDelimiter()).to.equal(this.styleGuideWordPhrases.meta.referenceDelimiter).and.to.equal(' - ');
done();
});
});
describe('.sections()', function() {
context('given new sections', function() {
it('should do things');
});
context('given no arguments', function() {
it('should return all referenced sections', function(done) {
let results = [],
expected = [
'4', '4.1',
'4.1.1', '4.1.1.1', '4.1.1.2',
'4.1.2', '4.1.2.2',
'8',
'9', '9.1', '9.1.1', '9.2', '9.3', '9.4', '9.5', '9.10', '9.11', '9.100',
'alpha', 'alpha.alpha', 'alpha.alpha.alpha', 'alpha.beta', 'alpha.delta', 'alpha.epsilon', 'alpha.gamma', 'alpha-bet',
'WordKeys.Base.Link', 'WordKeys.Components', 'WordKeys.Components.Message', 'WordKeys.Components.Tabs', 'WordKeys.Forms.Button', 'WordKeys.Forms.Input'
];
this.styleGuide.sections().map(function(section) {
results.push(section.reference());
});
expect(results).to.deep.equal(expected);
done();
});
});
context('given exact references', function() {
it('should find a reference with depth 1', function(done) {
let section = this.styleGuide.sections('4');
expect(section.header()).to.equal('DEPTH OF 1');
expect(section.depth()).to.equal(1);
expect(section.reference()).to.equal('4');
done();
});
it('should find a reference with depth 3 and no modifiers', function(done) {
let section = this.styleGuide.sections('4.1.1');
expect(section.header()).to.equal('DEPTH OF 3, NO MODIFIERS');
expect(section.reference()).to.equal('4.1.1');
expect(section.depth()).to.equal(3);
done();
});
it('should find a reference with depth 3 and modifiers', function(done) {
let section = this.styleGuide.sections('4.1.2');
expect(section.header()).to.equal('DEPTH OF 3, MODIFIERS');
expect(section.depth()).to.equal(3);
expect(section.reference()).to.equal('4.1.2');
done();
});
it('should not find a reference with depth 3 that does not exist', function(done) {
expect(this.styleGuide.sections('4.1.3')).to.be.false;
done();
});
it('should find a reference with depth 4 (A)', function(done) {
let section = this.styleGuide.sections('4.1.1.1');
expect(section.header()).to.equal('DEPTH OF 4 (A)');
expect(section.depth()).to.equal(4);
expect(section.reference()).to.equal('4.1.1.1');
done();
});
it('should find a reference with depth 4 (B)', function(done) {
let section = this.styleGuide.sections('4.1.1.2');
expect(section.header()).to.equal('DEPTH OF 4 (B)');
expect(section.depth()).to.equal(4);
expect(section.reference()).to.equal('4.1.1.2');
done();
});
it('should find a reference with depth 4 (C)', function(done) {
let section = this.styleGuide.sections('4.1.2.2');
expect(section.header()).to.equal('DEPTH OF 4 (C)');
expect(section.depth()).to.equal(4);
expect(section.reference()).to.equal('4.1.2.2');
done();
});
});
context('given string queries', function() {
it('should return 1 level of descendants when given "4.x"', function(done) {
let sections = this.styleGuide.sections('4.x');
sections.map(function(section) {
expect(section.reference()).to.equal('4.1');
expect(section.header()).to.equal('DEPTH OF 2');
});
expect(sections.length).to.equal(1);
done();
});
it('should return 1 level of descendants when given "4.1.x"', function(done) {
let expected = ['4.1.1', '4.1.2'];
let results = this.styleGuide.sections('4.1.x').map(function(section) {
return section.reference();
});
expect(results).to.deep.equal(expected);
done();
});
it('should return 2 levels of descendants when given "4.x.x"', function(done) {
let expected = ['4.1', '4.1.1', '4.1.2'];
let results = this.styleGuide.sections('4.x.x').map(function(section) {
return section.reference();
});
expect(results).to.deep.equal(expected);
done();
});
it('should return "4.1" and all levels of descendants when given "4.1.*"', function(done) {
let results,
expected = ['4.1', '4.1.1', '4.1.1.1', '4.1.1.2', '4.1.2', '4.1.2.2'];
results = this.styleGuide.sections('4.1.*').map(function(section) {
return section.reference();
});
expect(results).to.deep.equal(expected);
done();
});
it('should not find "alpha" section when given a query for "alp.*"', function(done) {
expect(this.styleGuide.sections('alp.*')).to.be.an.instanceOf(Array);
expect(this.styleGuide.sections('alp.*')).to.have.length(0);
done();
});
it('should not find "alpha" section when given a query for "alp.x"', function(done) {
expect(this.styleGuide.sections('alp.x')).to.be.an.instanceOf(Array);
expect(this.styleGuide.sections('alp.x')).to.have.length(0);
done();
});
it('should return numeric sections in order', function(done) {
let expected = ['9.1', '9.2', '9.3', '9.4', '9.5', '9.10', '9.11', '9.100'];
let results = this.styleGuide.sections('9.x').map(function(section) {
return section.reference();
});
expect(results).to.deep.equal(expected);
done();
});
it('should return "word key" sections in order', function(done) {
let expected = ['alpha.alpha', 'alpha.beta', 'alpha.delta', 'alpha.epsilon', 'alpha.gamma'];
let results = this.styleGuide.sections('alpha.x').map(function(section) {
return section.reference();
});
expect(results).to.deep.equal(expected);
done();
});
it('should return "word key" sections with dashes in the name', function(done) {
let sections = this.styleGuide.sections('alpha-bet.*');
sections.map(function(section) {
expect(section.reference()).to.equal('alpha-bet');
});
expect(sections.length).to.equal(1);
done();
});
it('should return "word phrase" sections in order', function(done) {
let expected = ['beta - alpha', 'beta - beta', 'beta - delta', 'beta - epsilon', 'beta - gamma'];
let results = this.styleGuideWordPhrases.sections('beta.x').map(function(section) {
return section.reference();
});
expect(results).to.deep.equal(expected);
done();
});
});
context('given regex queries', function() {
it('should return an empty array when query does not match', function(done) {
expect(this.styleGuide.sections(/__does_not_match__.*/)).to.be.an.instanceOf(Array).and.empty;
done();
});
it('should return "4" and all levels of descendants when given /4.*/', function(done) {
let expected = ['4', '4.1', '4.1.1', '4.1.1.1', '4.1.1.2', '4.1.2', '4.1.2.2'];
let results = this.styleGuide.sections(/4.*/).map(function(section) {
return section.reference();
});
expect(results).to.deep.equal(expected);
done();
});
it('should return "4" when given /4/', function(done) {
let sections = this.styleGuide.sections(/4/);
sections.map(function(section) {
expect(section.reference()).to.equal('4');
});
expect(sections.length).to.equal(1);
done();
});
it('should return numeric sections in order', function(done) {
let expected = ['9', '9.1', '9.1.1', '9.2', '9.3', '9.4', '9.5', '9.10', '9.11', '9.100'];
let results = this.styleGuide.sections(/9.*/).map(function(section) {
return section.reference();
});
expect(results).to.deep.equal(expected);
done();
});
it('should return "word key" sections in order', function(done) {
let expected = ['alpha.alpha', 'alpha.alpha.alpha', 'alpha.beta', 'alpha.delta', 'alpha.epsilon', 'alpha.gamma'];
let results = this.styleGuide.sections(/alpha\..*/).map(function(section) {
return section.reference();
});
expect(results).to.deep.equal(expected);
done();
});
it('should return "word phrase" sections in order', function(done) {
let expected = ['beta - alpha', 'beta - alpha - alpha', 'beta - beta', 'beta - delta', 'beta - epsilon', 'beta - gamma'];
let results = this.styleGuideWordPhrases.sections(/beta - .*/).map(function(section) {
return section.reference();
});
expect(results).to.deep.equal(expected);
done();
});
it('should return weighted "word phrase" sections in order', function(done) {
let expected = ['gamma - alpha', 'gamma - alpha - delta', 'gamma - alpha - gamma', 'gamma - alpha - beta', 'gamma - alpha - alpha', 'gamma - beta', 'gamma - gamma', 'gamma - delta', 'gamma - epsilon'];
let results = this.styleGuideWordPhrases.sections(/gamma - .*/).map(function(section) {
return section.reference();
});
expect(results).to.deep.equal(expected);
done();
});
it('should return referenceNumber values for "word phrase" sections in order', function(done) {
let expected = ['2.1', '2.1.1', '2.1.2', '2.1.3', '2.1.4', '2.2', '2.3', '2.4', '2.5'];
let results = this.styleGuideWordPhrases.sections(/gamma - .*/).map(function(section) {
return section.referenceNumber();
});
expect(results).to.deep.equal(expected);
done();
});
});
});
});
| Add 100% test coverage for kss_styleguide. #267
| test/test_kss_styleguide.js | Add 100% test coverage for kss_styleguide. #267 | <ide><path>est/test_kss_styleguide.js
<ide> });
<ide>
<ide> describe('.init()', function() {
<del> it('should do things');
<add> it('it should re-sort the style guide when new sections are added', function() {
<add> let styleGuide = new kss.KssStyleGuide({
<add> sections: [
<add> {header: 'Section 1.3', reference: '1.3'},
<add> {header: 'Section 1.1', reference: '1.1'}
<add> ],
<add> autoInit: false
<add> });
<add> styleGuide.sections({header: 'Section 1.2', reference: '1.2'});
<add> expect(styleGuide.data.sections.map(section => section.reference())).to.deep.equal(['1.3', '1.1', '1.2']);
<add> styleGuide.init();
<add> expect(styleGuide.data.sections.map(section => section.reference())).to.deep.equal(['1.1', '1.2', '1.3']);
<add> });
<add>
<add> it('it should auto-increment sections in the style guide', function() {
<add> let styleGuide = new kss.KssStyleGuide({
<add> sections: [
<add> {header: 'Section 1.1', reference: 'section.1'},
<add> {header: 'Section 1.2', reference: 'section.2'},
<add> {header: 'Section 1.3', reference: 'section.3'}
<add> ],
<add> autoInit: false
<add> });
<add> styleGuide.sections();
<add> expect(styleGuide.data.sections.map(section => section.referenceNumber())).to.deep.equal(['', '', '']);
<add> styleGuide.meta.needsSort = false;
<add> styleGuide.init();
<add> expect(styleGuide.data.sections.map(section => section.referenceNumber())).to.deep.equal(['1.1', '1.2', '1.3']);
<add> });
<ide> });
<ide>
<ide> describe('.customPropertyNames()', function() {
<ide>
<ide> describe('.sections()', function() {
<ide> context('given new sections', function() {
<del> it('should do things');
<add> it('it should add a JSON section to the style guide', function() {
<add> let styleGuide = new kss.KssStyleGuide({
<add> sections: [
<add> {header: 'Section 1.3', reference: '1.3'},
<add> {header: 'Section 1.1', reference: '1.1'}
<add> ]
<add> });
<add> styleGuide.sections({header: 'Section 1.2', reference: '1.2'});
<add> expect(styleGuide.data.sections.map(section => section.reference())).to.deep.equal(['1.1', '1.2', '1.3']);
<add> expect(styleGuide.meta.referenceMap['1.2'].header()).to.equal('Section 1.2');
<add> });
<add>
<add> it('it should add a KssSection to the style guide', function() {
<add> let styleGuide = new kss.KssStyleGuide({
<add> sections: [
<add> {header: 'Section 1.3', reference: '1.3'},
<add> {header: 'Section 1.1', reference: '1.1'}
<add> ]
<add> });
<add> let section = new kss.KssSection({header: 'Section 1.2', reference: '1.2'});
<add> styleGuide.sections(section);
<add> expect(styleGuide.data.sections.map(section => section.reference())).to.deep.equal(['1.1', '1.2', '1.3']);
<add> expect(styleGuide.meta.referenceMap['1.2']).to.deep.equal(section);
<add> });
<ide> });
<ide>
<ide> context('given no arguments', function() { |
|
Java | apache-2.0 | 20f9910f6ab61dd9244ca9b485161892e6c9120b | 0 | optimizely/android-sdk,optimizely/android-sdk,optimizely/android-sdk | /****************************************************************************
* Copyright 2017, Optimizely, Inc. and 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 com.optimizely.ab.android.test_app;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Build;
import android.support.annotation.NonNull;
import com.optimizely.ab.android.sdk.OptimizelyManager;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
public class MyApplication extends Application {
// Project ID owned by [email protected]
// if you'd like to configure your own experiment please check out https://developers.optimizely.com/x/solutions/sdks/getting-started/index.html?language=android&platform=mobile
// to create your own project and experiment. Then just replace your project ID below.
public static final String PROJECT_ID = "8136462271";
private OptimizelyManager optimizelyManager;
public OptimizelyManager getOptimizelyManager() {
return optimizelyManager;
}
public Map<String,String> getAttributes() {
Map<String,String> attributes = new HashMap<>();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
attributes.put("locale", getResources().getConfiguration().getLocales().get(0).toString());
} else {
attributes.put("locale", getResources().getConfiguration().locale.toString());
}
return attributes;
}
@NonNull
public String getAnonUserId() {
// this is a convenience method that creates and persists an anonymous user id,
// which we need to pass into the activate and track calls
SharedPreferences sharedPreferences = getSharedPreferences("user", Context.MODE_PRIVATE);
String id = sharedPreferences.getString("userId", null);
if (id == null) {
id = UUID.randomUUID().toString();
// comment this out to get a brand new user id every time this function is called.
// useful for incrementing results page count for QA purposes
sharedPreferences.edit().putString("userId", id).apply();
}
return id;
}
@Override
public void onCreate() {
super.onCreate();
// This app is built against a real Optimizely project with real experiments set. Automated
// espresso tests are run against this project id. Changing it will make the Optimizely
// tests setup not work and the Espresso tests will fail. Also, the project id passed here
// must match the project id of the compiled in Optimizely data file in rest/raw/data_file.json.
optimizelyManager = OptimizelyManager.builder(PROJECT_ID)
.withEventHandlerDispatchInterval(3, TimeUnit.MINUTES)
.withDataFileDownloadInterval(30, TimeUnit.MINUTES)
.build();
}
}
| test-app/src/main/java/com/optimizely/ab/android/test_app/MyApplication.java | /****************************************************************************
* Copyright 2017, Optimizely, Inc. and 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 com.optimizely.ab.android.test_app;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Build;
import android.support.annotation.NonNull;
import com.optimizely.ab.android.sdk.OptimizelyManager;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
public class MyApplication extends Application {
// Project ID owned by [email protected]
// if you'd like to configure your own experiment please check out https://developers.optimizely.com/x/solutions/sdks/getting-started/index.html?language=android&platform=mobile
// to create your own project and experiment. Then just replace your project ID below.
public static final String PROJECT_ID = "8136462271";
private OptimizelyManager optimizelyManager;
public OptimizelyManager getOptimizelyManager() {
return optimizelyManager;
}
public Map<String,String> getAttributes() {
Map<String,String> attributes = new HashMap<>();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
attributes.put("locale", getResources().getConfiguration().getLocales().get(0).toString());
} else {
attributes.put("locale", getResources().getConfiguration().locale.toString());
}
return attributes;
}
@NonNull
public String getAnonUserId() {
// this is a convenience method that creates and persists an anonymous user id,
// which we need to pass into the activate and track calls
SharedPreferences sharedPreferences = getSharedPreferences("user", Context.MODE_PRIVATE);
String id = sharedPreferences.getString("userId", null);
if (id == null) {
id = UUID.randomUUID().toString();
sharedPreferences.edit().putString("userId", id).apply();
}
return id;
}
@Override
public void onCreate() {
super.onCreate();
// This app is built against a real Optimizely project with real experiments set. Automated
// espresso tests are run against this project id. Changing it will make the Optimizely
// tests setup not work and the Espresso tests will fail. Also, the project id passed here
// must match the project id of the compiled in Optimizely data file in rest/raw/data_file.json.
optimizelyManager = OptimizelyManager.builder(PROJECT_ID)
.withEventHandlerDispatchInterval(3, TimeUnit.MINUTES)
.withDataFileDownloadInterval(30, TimeUnit.MINUTES)
.build();
}
}
| Add documentation for not persisting userId in teset app for QA purposes.
| test-app/src/main/java/com/optimizely/ab/android/test_app/MyApplication.java | Add documentation for not persisting userId in teset app for QA purposes. | <ide><path>est-app/src/main/java/com/optimizely/ab/android/test_app/MyApplication.java
<ide> String id = sharedPreferences.getString("userId", null);
<ide> if (id == null) {
<ide> id = UUID.randomUUID().toString();
<add>
<add> // comment this out to get a brand new user id every time this function is called.
<add> // useful for incrementing results page count for QA purposes
<ide> sharedPreferences.edit().putString("userId", id).apply();
<ide> }
<ide> return id; |
|
Java | agpl-3.0 | b6541e4d8f59be13fdf0cf17ce2c47a0497b1e52 | 0 | geothomasp/kcmit,geothomasp/kcmit,geothomasp/kcmit,geothomasp/kcmit,geothomasp/kcmit | /*
* Kuali Coeus, a comprehensive research administration system for higher education.
*
* Copyright 2005-2015 Kuali, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kuali.kra.award.awardhierarchy;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.integration.junit4.JUnit4Mockery;
import org.jmock.lib.concurrent.Synchroniser;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.kuali.coeus.sys.framework.util.CollectionUtils;
import org.kuali.kra.award.AwardForm;
import org.kuali.kra.award.document.AwardDocument;
import org.kuali.kra.award.home.Award;
import org.kuali.rice.kew.api.exception.WorkflowException;
import org.kuali.rice.krad.bo.DocumentHeader;
import org.kuali.rice.krad.service.DocumentService;
import org.kuali.rice.krad.service.LegacyDataAdapter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Map;
public class AwardHierarchyBeanTest {
private static final String ROOT_AWARD_NUMBER = "100001-00001";
private static final String UNKNOWN_TARGET_NODE_AWARD_NUMBER = "123456-78901";
private AwardHierarchyBean bean;
private AwardHierarchyServiceImpl service;
private Award rootAward;
private Mockery context = new JUnit4Mockery() {{ setThreadingPolicy(new Synchroniser()); }};
@Before
public void setUp() throws Exception {
service = new AwardHierarchyServiceImpl() {
@Override
AwardDocument createPlaceholderDocument() throws WorkflowException {
return null;
}
};
service.setLegacyDataAdapter(getMockBusinessObjectService());
service.setDocumentService(getMockDocumentService());
rootAward = new Award();
rootAward.setAwardNumber(ROOT_AWARD_NUMBER);
createAwardHierarchyBean();
}
@After
public void tearDown() {
bean = null;
}
@Test
public void testSaveHierarchyChanges_NoError() {
Assert.assertTrue(bean.saveHierarchyChanges());
}
@Test(expected=MissingHierarchyException.class)
public void testCreatingNewChildAwardBasedOnAnotherAwardInHierarchy_BadInput() {
String targetAwardNumber = bean.getRootNode().getAwardNumber();
String awardNumberOfAwardToBeUsedAsTemplate = UNKNOWN_TARGET_NODE_AWARD_NUMBER;
bean.createNewChildAwardBasedOnAnotherAwardInHierarchy(targetAwardNumber, awardNumberOfAwardToBeUsedAsTemplate);
}
@Test
public void testGettingNodeForCurrentAward() {
Assert.assertEquals(rootAward.getAwardNumber(), bean.getCurrentAwardHierarchyNode().getAwardNumber());
}
private void createAwardHierarchyBean() {
bean = new AwardHierarchyBeanForUnitTest(null, service);
bean.getRootNodes().put(rootAward.getAwardNumber(), AwardHierarchy.createRootNode(rootAward));
}
private class AwardHierarchyBeanForUnitTest extends AwardHierarchyBean {
Award award;
AwardHierarchyBeanForUnitTest(AwardForm awardForm, AwardHierarchyService service) { super(awardForm, service); }
@Override
Award getAward() { // since we can't create AwardDocument in unit test, override this method to provide Award
return award != null ? award : rootAward;
}
}
private LegacyDataAdapter getMockBusinessObjectService() {
final LegacyDataAdapter service = context.mock(LegacyDataAdapter.class);
context.checking(new Expectations() {{
Map<String, Object> fieldValues = Collections.<String,Object>singletonMap("documentDescription", AwardDocument.PLACEHOLDER_DOC_DESCRIPTION);
one(service).findMatching(DocumentHeader.class, fieldValues);
will(returnValue(new ArrayList<DocumentHeader>()));
Map<String, Object> primaryKeys = CollectionUtils.zipMap(new String[]{"awardNumber", "active"}, new Object[]{ROOT_AWARD_NUMBER, Boolean.TRUE});
allowing(service).findByPrimaryKey(AwardHierarchy.class, primaryKeys);
will(returnValue(null));
}});
return service;
}
private DocumentService getMockDocumentService() throws WorkflowException {
final DocumentService service = context.mock(DocumentService.class);
context.checking(new Expectations() {{
one(service).getNewDocument(AwardDocument.class);
will(returnValue(null));
}});
return service;
}
}
| coeus-impl/src/test/java/org/kuali/kra/award/awardhierarchy/AwardHierarchyBeanTest.java | /*
* Kuali Coeus, a comprehensive research administration system for higher education.
*
* Copyright 2005-2015 Kuali, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kuali.kra.award.awardhierarchy;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.integration.junit4.JUnit4Mockery;
import org.jmock.lib.concurrent.Synchroniser;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.kuali.coeus.sys.framework.util.CollectionUtils;
import org.kuali.kra.award.AwardForm;
import org.kuali.kra.award.document.AwardDocument;
import org.kuali.kra.award.home.Award;
import org.kuali.rice.kew.api.exception.WorkflowException;
import org.kuali.rice.krad.bo.DocumentHeader;
import org.kuali.rice.krad.service.DocumentService;
import org.kuali.rice.krad.service.LegacyDataAdapter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Map;
public class AwardHierarchyBeanTest {
private static final String ROOT_AWARD_NUMBER = "100001-00001";
private static final String UNKNOWN_TARGET_NODE_AWARD_NUMBER = "123456-78901";
private AwardHierarchyBean bean;
private AwardHierarchyServiceImpl service;
private Award rootAward;
private Mockery context = new JUnit4Mockery() {{ setThreadingPolicy(new Synchroniser()); }};
@Before
public void setUp() throws Exception {
service = new AwardHierarchyServiceImpl();
service.setLegacyDataAdapter(getMockBusinessObjectService());
service.setDocumentService(getMockDocumentService());
rootAward = new Award();
rootAward.setAwardNumber(ROOT_AWARD_NUMBER);
createAwardHierarchyBean();
}
@After
public void tearDown() {
bean = null;
}
@Test
public void testSaveHierarchyChanges_NoError() {
Assert.assertTrue(bean.saveHierarchyChanges());
}
@Test(expected=MissingHierarchyException.class)
public void testCreatingNewChildAwardBasedOnAnotherAwardInHierarchy_BadInput() {
String targetAwardNumber = bean.getRootNode().getAwardNumber();
String awardNumberOfAwardToBeUsedAsTemplate = UNKNOWN_TARGET_NODE_AWARD_NUMBER;
bean.createNewChildAwardBasedOnAnotherAwardInHierarchy(targetAwardNumber, awardNumberOfAwardToBeUsedAsTemplate);
}
@Test
public void testGettingNodeForCurrentAward() {
Assert.assertEquals(rootAward.getAwardNumber(), bean.getCurrentAwardHierarchyNode().getAwardNumber());
}
private void createAwardHierarchyBean() {
bean = new AwardHierarchyBeanForUnitTest(null, service);
bean.getRootNodes().put(rootAward.getAwardNumber(), AwardHierarchy.createRootNode(rootAward));
}
private class AwardHierarchyBeanForUnitTest extends AwardHierarchyBean {
Award award;
AwardHierarchyBeanForUnitTest(AwardForm awardForm, AwardHierarchyService service) { super(awardForm, service); }
@Override
Award getAward() { // since we can't create AwardDocument in unit test, override this method to provide Award
return award != null ? award : rootAward;
}
}
private LegacyDataAdapter getMockBusinessObjectService() {
final LegacyDataAdapter service = context.mock(LegacyDataAdapter.class);
context.checking(new Expectations() {{
Map<String, Object> fieldValues = Collections.<String,Object>singletonMap("documentDescription", AwardDocument.PLACEHOLDER_DOC_DESCRIPTION);
one(service).findMatching(DocumentHeader.class, fieldValues);
will(returnValue(new ArrayList<DocumentHeader>()));
Map<String, Object> primaryKeys = CollectionUtils.zipMap(new String[]{"awardNumber", "active"}, new Object[]{ROOT_AWARD_NUMBER, Boolean.TRUE});
allowing(service).findByPrimaryKey(AwardHierarchy.class, primaryKeys);
will(returnValue(null));
}});
return service;
}
private DocumentService getMockDocumentService() throws WorkflowException {
final DocumentService service = context.mock(DocumentService.class);
context.checking(new Expectations() {{
one(service).getNewDocument(AwardDocument.class);
will(returnValue(null));
}});
return service;
}
}
| RESOPS-126:Fix up unit test to avoid globalVariableService #norelease
Recent change caused a unit test failure due to a switch to using globalVariableService and removing an old workaround that allowed the unit test to work.
| coeus-impl/src/test/java/org/kuali/kra/award/awardhierarchy/AwardHierarchyBeanTest.java | RESOPS-126:Fix up unit test to avoid globalVariableService #norelease | <ide><path>oeus-impl/src/test/java/org/kuali/kra/award/awardhierarchy/AwardHierarchyBeanTest.java
<ide>
<ide> @Before
<ide> public void setUp() throws Exception {
<del> service = new AwardHierarchyServiceImpl();
<add> service = new AwardHierarchyServiceImpl() {
<add> @Override
<add> AwardDocument createPlaceholderDocument() throws WorkflowException {
<add> return null;
<add> }
<add> };
<ide> service.setLegacyDataAdapter(getMockBusinessObjectService());
<ide> service.setDocumentService(getMockDocumentService());
<ide> rootAward = new Award(); |
|
Java | apache-2.0 | 4774c1cb15fe58606fe2722748c64f6c268969cf | 0 | NareshkumarCIET/Cinder,krishnabrucelee/Library-Management,MonaCIET/cinder,CIETstudents/openstack-maven-CIET-students,vmturbo/openstack-java-sdk,MonaCIET/cinder,krishnabrucelee/Cinder-Krishna,zhimin711/openstack-java-sdk,KizuRos/openstack-java-sdk,krishnabrucelee/Library-Management,krishnabrucelee/ceilometerModel-Krishna,woorea/openstack-java-sdk,NareshkumarCIET/Cinder,krishnabrucelee/Library-Management,OnePaaS/openstack-java-sdk,krishnabrucelee/Cloud-stack-Api,zhimin711/openstack-java-sdk,CIETstudents/Swift-Model-Mona,OnePaaS/openstack-java-sdk,krishnabrucelee/Cloud-stack-Api,vmturbo/openstack-java-sdk,krishnabrucelee/ceilometerModel-Krishna,krishnabrucelee/OpenStack-Nova-Client,CIETstudents/Cinder-Krishna-Mona,krishnabrucelee/Cinder-Krishna,krishnabrucelee/OpenStack-Nova-Client,KizuRos/openstack-java-sdk,CIETstudents/Cinder-Krishna-Mona,CIETstudents/Swift-Model-Mona,CIETstudents/openstack-maven-CIET-students,woorea/openstack-java-sdk | package com.woorea.openstack.nova.model;
import java.io.Serializable;
import java.util.Iterator;
import java.util.List;
import org.codehaus.jackson.annotate.JsonProperty;
public class Hosts implements Iterable<Hosts.Host>, Serializable {
public static final class Host {
private String zone;
@JsonProperty("host_name")
private String hostName;
private String service;
/**
* @return the hostName
*/
public String getHostName() {
return hostName;
}
/**
* @return the service
*/
public String getService() {
return service;
}
public String getZone() {
return zone;
}
public void setZone(String zone) {
this.zone = zone;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "Host [hostName=" + hostName + ", service=" + service + "]";
}
}
@JsonProperty("hosts")
private List<Host> list;
/**
* @return the list
*/
public List<Host> getList() {
return list;
}
@Override
public Iterator<Hosts.Host> iterator() {
return list.iterator();
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "Hosts [list=" + list + "]";
}
}
| nova-model/src/main/java/com/woorea/openstack/nova/model/Hosts.java | package com.woorea.openstack.nova.model;
import java.io.Serializable;
import java.util.Iterator;
import java.util.List;
import org.codehaus.jackson.annotate.JsonProperty;
public class Hosts implements Iterable<Hosts.Host>, Serializable {
public static final class Host {
@JsonProperty("host_name")
private String hostName;
private String service;
/**
* @return the hostName
*/
public String getHostName() {
return hostName;
}
/**
* @return the service
*/
public String getService() {
return service;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "Host [hostName=" + hostName + ", service=" + service + "]";
}
}
@JsonProperty("hosts")
private List<Host> list;
/**
* @return the list
*/
public List<Host> getList() {
return list;
}
@Override
public Iterator<Hosts.Host> iterator() {
return list.iterator();
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "Hosts [list=" + list + "]";
}
}
| adding zone in model
openstack api returns "zone" in response | nova-model/src/main/java/com/woorea/openstack/nova/model/Hosts.java | adding zone in model | <ide><path>ova-model/src/main/java/com/woorea/openstack/nova/model/Hosts.java
<ide> public class Hosts implements Iterable<Hosts.Host>, Serializable {
<ide>
<ide> public static final class Host {
<add>
<add> private String zone;
<ide>
<ide> @JsonProperty("host_name")
<ide> private String hostName;
<ide> */
<ide> public String getService() {
<ide> return service;
<add> }
<add>
<add> public String getZone() {
<add> return zone;
<add> }
<add>
<add> public void setZone(String zone) {
<add> this.zone = zone;
<ide> }
<ide>
<ide> /* (non-Javadoc) |
|
Java | apache-2.0 | d5bd55f969fd274bd50803856220904175fc086a | 0 | realityforge/arez,realityforge/arez,realityforge/arez | package arez.processor;
import com.squareup.javapoet.ParameterizedTypeName;
import com.squareup.javapoet.TypeName;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.AnnotationValue;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.ExecutableType;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.Elements;
import javax.lang.model.util.Types;
@SuppressWarnings( "WeakerAccess" )
final class ProcessorUtil
{
private ProcessorUtil()
{
}
@SuppressWarnings( "unchecked" )
static boolean isWarningSuppressed( @Nonnull final Element element,
@Nonnull final String warning,
@Nullable final String alternativeSuppressWarnings )
{
if ( null != alternativeSuppressWarnings )
{
final AnnotationMirror suppress = AnnotationsUtil.findAnnotationByType( element, alternativeSuppressWarnings );
if ( null != suppress )
{
final AnnotationValue value = AnnotationsUtil.findAnnotationValueNoDefaults( suppress, "value" );
if ( null != value )
{
final List<AnnotationValue> warnings = (List<AnnotationValue>) value.getValue();
for ( final AnnotationValue suppression : warnings )
{
if ( warning.equals( suppression.getValue() ) )
{
return true;
}
}
}
}
}
final SuppressWarnings annotation = element.getAnnotation( SuppressWarnings.class );
if ( null != annotation )
{
for ( final String suppression : annotation.value() )
{
if ( warning.equals( suppression ) )
{
return true;
}
}
}
final Element enclosingElement = element.getEnclosingElement();
return null != enclosingElement && isWarningSuppressed( enclosingElement, warning, alternativeSuppressWarnings );
}
@Nonnull
static List<TypeElement> getSuperTypes( @Nonnull final TypeElement element )
{
final List<TypeElement> superTypes = new ArrayList<>();
enumerateSuperTypes( element, superTypes );
return superTypes;
}
private static void enumerateSuperTypes( @Nonnull final TypeElement element,
@Nonnull final List<TypeElement> superTypes )
{
final TypeMirror superclass = element.getSuperclass();
if ( TypeKind.NONE != superclass.getKind() )
{
final TypeElement superclassElement = (TypeElement) ( (DeclaredType) superclass ).asElement();
superTypes.add( superclassElement );
enumerateSuperTypes( superclassElement, superTypes );
}
for ( final TypeMirror interfaceType : element.getInterfaces() )
{
final TypeElement interfaceElement = (TypeElement) ( (DeclaredType) interfaceType ).asElement();
enumerateSuperTypes( interfaceElement, superTypes );
}
}
@Nonnull
static List<TypeElement> getInterfaces( @Nonnull final TypeElement element )
{
final List<TypeElement> superTypes = new ArrayList<>();
enumerateInterfaces( element, superTypes );
return superTypes;
}
private static void enumerateInterfaces( @Nonnull final TypeElement element,
@Nonnull final List<TypeElement> superTypes )
{
final TypeMirror superclass = element.getSuperclass();
if ( TypeKind.NONE != superclass.getKind() )
{
final TypeElement superclassElement = (TypeElement) ( (DeclaredType) superclass ).asElement();
enumerateInterfaces( superclassElement, superTypes );
}
for ( final TypeMirror interfaceType : element.getInterfaces() )
{
final TypeElement interfaceElement = (TypeElement) ( (DeclaredType) interfaceType ).asElement();
superTypes.add( interfaceElement );
enumerateInterfaces( interfaceElement, superTypes );
}
}
@Nonnull
static List<VariableElement> getFieldElements( @Nonnull final TypeElement element )
{
final Map<String, VariableElement> methodMap = new LinkedHashMap<>();
enumerateFieldElements( element, methodMap );
return new ArrayList<>( methodMap.values() );
}
private static void enumerateFieldElements( @Nonnull final TypeElement element,
@Nonnull final Map<String, VariableElement> fields )
{
final TypeMirror superclass = element.getSuperclass();
if ( TypeKind.NONE != superclass.getKind() )
{
enumerateFieldElements( (TypeElement) ( (DeclaredType) superclass ).asElement(), fields );
}
for ( final Element member : element.getEnclosedElements() )
{
if ( member.getKind() == ElementKind.FIELD )
{
fields.put( member.getSimpleName().toString(), (VariableElement) member );
}
}
}
@Nonnull
static List<ExecutableElement> getMethods( @Nonnull final TypeElement element,
@Nonnull final Elements elementUtils,
@Nonnull final Types typeUtils )
{
final Map<String, ArrayList<ExecutableElement>> methodMap = new LinkedHashMap<>();
enumerateMethods( element, elementUtils, typeUtils, element, methodMap );
return methodMap.values().stream().flatMap( Collection::stream ).collect( Collectors.toList() );
}
private static void enumerateMethods( @Nonnull final TypeElement scope,
@Nonnull final Elements elementUtils,
@Nonnull final Types typeUtils,
@Nonnull final TypeElement element,
@Nonnull final Map<String, ArrayList<ExecutableElement>> methods )
{
final TypeMirror superclass = element.getSuperclass();
if ( TypeKind.NONE != superclass.getKind() )
{
final TypeElement superclassElement = (TypeElement) ( (DeclaredType) superclass ).asElement();
enumerateMethods( scope, elementUtils, typeUtils, superclassElement, methods );
}
for ( final TypeMirror interfaceType : element.getInterfaces() )
{
final TypeElement interfaceElement = (TypeElement) ( (DeclaredType) interfaceType ).asElement();
enumerateMethods( scope, elementUtils, typeUtils, interfaceElement, methods );
}
for ( final Element member : element.getEnclosedElements() )
{
if ( member.getKind() == ElementKind.METHOD )
{
final ExecutableElement method = (ExecutableElement) member;
processMethod( elementUtils, typeUtils, scope, methods, method );
}
}
}
private static void processMethod( @Nonnull final Elements elementUtils,
@Nonnull final Types typeUtils,
@Nonnull final TypeElement typeElement,
@Nonnull final Map<String, ArrayList<ExecutableElement>> methods,
@Nonnull final ExecutableElement method )
{
final ExecutableType methodType =
(ExecutableType) typeUtils.asMemberOf( (DeclaredType) typeElement.asType(), method );
final String key = method.getSimpleName().toString();
final ArrayList<ExecutableElement> elements = methods.computeIfAbsent( key, k -> new ArrayList<>() );
boolean found = false;
final int size = elements.size();
for ( int i = 0; i < size; i++ )
{
final ExecutableElement executableElement = elements.get( i );
if ( method.equals( executableElement ) )
{
found = true;
break;
}
else if ( isSubsignature( typeUtils, typeElement, methodType, executableElement ) )
{
if ( !isAbstractInterfaceMethod( method ) )
{
elements.set( i, method );
}
found = true;
break;
}
else if ( elementUtils.overrides( method, executableElement, typeElement ) )
{
elements.set( i, method );
found = true;
break;
}
}
if ( !found )
{
elements.add( method );
}
}
private static boolean isAbstractInterfaceMethod( final @Nonnull ExecutableElement method )
{
return method.getModifiers().contains( Modifier.ABSTRACT ) &&
ElementKind.INTERFACE == method.getEnclosingElement().getKind();
}
private static boolean isSubsignature( @Nonnull final Types typeUtils,
@Nonnull final TypeElement typeElement,
@Nonnull final ExecutableType methodType,
@Nonnull final ExecutableElement candidate )
{
final ExecutableType candidateType =
(ExecutableType) typeUtils.asMemberOf( (DeclaredType) typeElement.asType(), candidate );
final boolean isEqual = methodType.equals( candidateType );
final boolean isSubsignature = typeUtils.isSubsignature( methodType, candidateType );
return isSubsignature || isEqual;
}
@Nonnull
static List<ExecutableElement> getConstructors( @Nonnull final TypeElement element )
{
return element.getEnclosedElements().stream().
filter( m -> m.getKind() == ElementKind.CONSTRUCTOR ).
map( m -> (ExecutableElement) m ).
collect( Collectors.toList() );
}
@Nullable
static String deriveName( @Nonnull final ExecutableElement method,
@Nonnull final Pattern pattern,
@Nonnull final String name )
throws ProcessorException
{
if ( Constants.SENTINEL.equals( name ) )
{
final String methodName = method.getSimpleName().toString();
final Matcher matcher = pattern.matcher( methodName );
if ( matcher.find() )
{
final String candidate = matcher.group( 1 );
return firstCharacterToLowerCase( candidate );
}
else
{
return null;
}
}
else
{
return name;
}
}
@Nonnull
static String firstCharacterToLowerCase( @Nonnull final String name )
{
return Character.toLowerCase( name.charAt( 0 ) ) + name.substring( 1 );
}
static boolean hasNonnullAnnotation( @Nonnull final Element element )
{
return AnnotationsUtil.hasAnnotationOfType( element, Constants.NONNULL_ANNOTATION_CLASSNAME );
}
static boolean isDisposableTrackableRequired( @Nonnull final Element element )
{
final VariableElement variableElement = (VariableElement)
AnnotationsUtil.getAnnotationValue( element,
Constants.COMPONENT_ANNOTATION_CLASSNAME,
"disposeNotifier" ).getValue();
switch ( variableElement.getSimpleName().toString() )
{
case "ENABLE":
return true;
case "DISABLE":
return false;
default:
return !AnnotationsUtil.hasAnnotationOfType( element, Constants.SINGLETON_ANNOTATION_CLASSNAME );
}
}
static boolean doesMethodOverrideInterfaceMethod( @Nonnull final Types typeUtils,
@Nonnull final TypeElement typeElement,
@Nonnull final ExecutableElement method )
{
return getInterfaces( typeElement ).stream()
.flatMap( i -> i.getEnclosedElements().stream() )
.filter( e1 -> e1 instanceof ExecutableElement )
.map( e1 -> (ExecutableElement) e1 )
.collect(
Collectors.toList() ).stream()
.anyMatch( e -> isSubsignature( typeUtils,
typeElement,
(ExecutableType) typeUtils.asMemberOf( (DeclaredType) typeElement.asType(), e ),
method ) );
}
@Nonnull
static TypeName toRawType( @Nonnull final TypeMirror type )
{
final TypeName typeName = TypeName.get( type );
if ( typeName instanceof ParameterizedTypeName )
{
return ( (ParameterizedTypeName) typeName ).rawType;
}
else
{
return typeName;
}
}
static boolean anyParametersNamed( @Nonnull final ExecutableElement element, @Nonnull final String name )
{
return element.getParameters().stream().anyMatch( p -> p.getSimpleName().toString().equals( name ) );
}
}
| processor/src/main/java/arez/processor/ProcessorUtil.java | package arez.processor;
import com.squareup.javapoet.ParameterizedTypeName;
import com.squareup.javapoet.TypeName;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.AnnotationValue;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.ExecutableType;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.Elements;
import javax.lang.model.util.Types;
final class ProcessorUtil
{
private ProcessorUtil()
{
}
@SuppressWarnings( "unchecked" )
static boolean isWarningSuppressed( @Nonnull final Element element,
@Nonnull final String warning,
@Nullable final String alternativeSuppressWarnings )
{
if ( null != alternativeSuppressWarnings )
{
final AnnotationMirror suppress = AnnotationsUtil.findAnnotationByType( element, alternativeSuppressWarnings );
if ( null != suppress )
{
final AnnotationValue value = AnnotationsUtil.findAnnotationValueNoDefaults( suppress, "value" );
if ( null != value )
{
final List<AnnotationValue> warnings = (List<AnnotationValue>) value.getValue();
for ( final AnnotationValue suppression : warnings )
{
if ( warning.equals( suppression.getValue() ) )
{
return true;
}
}
}
}
}
final SuppressWarnings annotation = element.getAnnotation( SuppressWarnings.class );
if ( null != annotation )
{
for ( final String suppression : annotation.value() )
{
if ( warning.equals( suppression ) )
{
return true;
}
}
}
final Element enclosingElement = element.getEnclosingElement();
return null != enclosingElement && isWarningSuppressed( enclosingElement, warning, alternativeSuppressWarnings );
}
@Nonnull
static List<TypeElement> getSuperTypes( @Nonnull final TypeElement element )
{
final List<TypeElement> superTypes = new ArrayList<>();
enumerateSuperTypes( element, superTypes );
return superTypes;
}
private static void enumerateSuperTypes( @Nonnull final TypeElement element,
@Nonnull final List<TypeElement> superTypes )
{
final TypeMirror superclass = element.getSuperclass();
if ( TypeKind.NONE != superclass.getKind() )
{
final TypeElement superclassElement = (TypeElement) ( (DeclaredType) superclass ).asElement();
superTypes.add( superclassElement );
enumerateSuperTypes( superclassElement, superTypes );
}
for ( final TypeMirror interfaceType : element.getInterfaces() )
{
final TypeElement interfaceElement = (TypeElement) ( (DeclaredType) interfaceType ).asElement();
enumerateSuperTypes( interfaceElement, superTypes );
}
}
@Nonnull
static List<TypeElement> getInterfaces( @Nonnull final TypeElement element )
{
final List<TypeElement> superTypes = new ArrayList<>();
enumerateInterfaces( element, superTypes );
return superTypes;
}
private static void enumerateInterfaces( @Nonnull final TypeElement element,
@Nonnull final List<TypeElement> superTypes )
{
final TypeMirror superclass = element.getSuperclass();
if ( TypeKind.NONE != superclass.getKind() )
{
final TypeElement superclassElement = (TypeElement) ( (DeclaredType) superclass ).asElement();
enumerateInterfaces( superclassElement, superTypes );
}
for ( final TypeMirror interfaceType : element.getInterfaces() )
{
final TypeElement interfaceElement = (TypeElement) ( (DeclaredType) interfaceType ).asElement();
superTypes.add( interfaceElement );
enumerateInterfaces( interfaceElement, superTypes );
}
}
@Nonnull
static List<VariableElement> getFieldElements( @Nonnull final TypeElement element )
{
final Map<String, VariableElement> methodMap = new LinkedHashMap<>();
enumerateFieldElements( element, methodMap );
return new ArrayList<>( methodMap.values() );
}
private static void enumerateFieldElements( @Nonnull final TypeElement element,
@Nonnull final Map<String, VariableElement> fields )
{
final TypeMirror superclass = element.getSuperclass();
if ( TypeKind.NONE != superclass.getKind() )
{
enumerateFieldElements( (TypeElement) ( (DeclaredType) superclass ).asElement(), fields );
}
for ( final Element member : element.getEnclosedElements() )
{
if ( member.getKind() == ElementKind.FIELD )
{
fields.put( member.getSimpleName().toString(), (VariableElement) member );
}
}
}
@Nonnull
static List<ExecutableElement> getMethods( @Nonnull final TypeElement element,
@Nonnull final Elements elementUtils,
@Nonnull final Types typeUtils )
{
final Map<String, ArrayList<ExecutableElement>> methodMap = new LinkedHashMap<>();
enumerateMethods( element, elementUtils, typeUtils, element, methodMap );
return methodMap.values().stream().flatMap( Collection::stream ).collect( Collectors.toList() );
}
private static void enumerateMethods( @Nonnull final TypeElement scope,
@Nonnull final Elements elementUtils,
@Nonnull final Types typeUtils,
@Nonnull final TypeElement element,
@Nonnull final Map<String, ArrayList<ExecutableElement>> methods )
{
final TypeMirror superclass = element.getSuperclass();
if ( TypeKind.NONE != superclass.getKind() )
{
final TypeElement superclassElement = (TypeElement) ( (DeclaredType) superclass ).asElement();
enumerateMethods( scope, elementUtils, typeUtils, superclassElement, methods );
}
for ( final TypeMirror interfaceType : element.getInterfaces() )
{
final TypeElement interfaceElement = (TypeElement) ( (DeclaredType) interfaceType ).asElement();
enumerateMethods( scope, elementUtils, typeUtils, interfaceElement, methods );
}
for ( final Element member : element.getEnclosedElements() )
{
if ( member.getKind() == ElementKind.METHOD )
{
final ExecutableElement method = (ExecutableElement) member;
processMethod( elementUtils, typeUtils, scope, methods, method );
}
}
}
private static void processMethod( @Nonnull final Elements elementUtils,
@Nonnull final Types typeUtils,
@Nonnull final TypeElement typeElement,
@Nonnull final Map<String, ArrayList<ExecutableElement>> methods,
@Nonnull final ExecutableElement method )
{
final ExecutableType methodType =
(ExecutableType) typeUtils.asMemberOf( (DeclaredType) typeElement.asType(), method );
final String key = method.getSimpleName().toString();
final ArrayList<ExecutableElement> elements = methods.computeIfAbsent( key, k -> new ArrayList<>() );
boolean found = false;
final int size = elements.size();
for ( int i = 0; i < size; i++ )
{
final ExecutableElement executableElement = elements.get( i );
if ( method.equals( executableElement ) )
{
found = true;
break;
}
else if ( isSubsignature( typeUtils, typeElement, methodType, executableElement ) )
{
if ( !isAbstractInterfaceMethod( method ) )
{
elements.set( i, method );
}
found = true;
break;
}
else if ( elementUtils.overrides( method, executableElement, typeElement ) )
{
elements.set( i, method );
found = true;
break;
}
}
if ( !found )
{
elements.add( method );
}
}
private static boolean isAbstractInterfaceMethod( final @Nonnull ExecutableElement method )
{
return method.getModifiers().contains( Modifier.ABSTRACT ) &&
ElementKind.INTERFACE == method.getEnclosingElement().getKind();
}
private static boolean isSubsignature( @Nonnull final Types typeUtils,
@Nonnull final TypeElement typeElement,
@Nonnull final ExecutableType methodType,
@Nonnull final ExecutableElement candidate )
{
final ExecutableType candidateType =
(ExecutableType) typeUtils.asMemberOf( (DeclaredType) typeElement.asType(), candidate );
final boolean isEqual = methodType.equals( candidateType );
final boolean isSubsignature = typeUtils.isSubsignature( methodType, candidateType );
return isSubsignature || isEqual;
}
@Nonnull
static List<ExecutableElement> getConstructors( @Nonnull final TypeElement element )
{
return element.getEnclosedElements().stream().
filter( m -> m.getKind() == ElementKind.CONSTRUCTOR ).
map( m -> (ExecutableElement) m ).
collect( Collectors.toList() );
}
@Nullable
static String deriveName( @Nonnull final ExecutableElement method,
@Nonnull final Pattern pattern,
@Nonnull final String name )
throws ProcessorException
{
if ( Constants.SENTINEL.equals( name ) )
{
final String methodName = method.getSimpleName().toString();
final Matcher matcher = pattern.matcher( methodName );
if ( matcher.find() )
{
final String candidate = matcher.group( 1 );
return firstCharacterToLowerCase( candidate );
}
else
{
return null;
}
}
else
{
return name;
}
}
@Nonnull
static String firstCharacterToLowerCase( @Nonnull final String name )
{
return Character.toLowerCase( name.charAt( 0 ) ) + name.substring( 1 );
}
static boolean hasNonnullAnnotation( @Nonnull final Element element )
{
return AnnotationsUtil.hasAnnotationOfType( element, Constants.NONNULL_ANNOTATION_CLASSNAME );
}
static boolean isDisposableTrackableRequired( @Nonnull final Element element )
{
final VariableElement variableElement = (VariableElement)
AnnotationsUtil.getAnnotationValue( element,
Constants.COMPONENT_ANNOTATION_CLASSNAME,
"disposeNotifier" ).getValue();
switch ( variableElement.getSimpleName().toString() )
{
case "ENABLE":
return true;
case "DISABLE":
return false;
default:
return !AnnotationsUtil.hasAnnotationOfType( element, Constants.SINGLETON_ANNOTATION_CLASSNAME );
}
}
static boolean doesMethodOverrideInterfaceMethod( @Nonnull final Types typeUtils,
@Nonnull final TypeElement typeElement,
@Nonnull final ExecutableElement method )
{
return getInterfaces( typeElement ).stream()
.flatMap( i -> i.getEnclosedElements().stream() )
.filter( e1 -> e1 instanceof ExecutableElement )
.map( e1 -> (ExecutableElement) e1 )
.collect(
Collectors.toList() ).stream()
.anyMatch( e -> isSubsignature( typeUtils,
typeElement,
(ExecutableType) typeUtils.asMemberOf( (DeclaredType) typeElement.asType(), e ),
method ) );
}
@Nonnull
static TypeName toRawType( @Nonnull final TypeMirror type )
{
final TypeName typeName = TypeName.get( type );
if ( typeName instanceof ParameterizedTypeName )
{
return ( (ParameterizedTypeName) typeName ).rawType;
}
else
{
return typeName;
}
}
static boolean anyParametersNamed( @Nonnull final ExecutableElement element, @Nonnull final String name )
{
return element.getParameters().stream().anyMatch( p -> p.getSimpleName().toString().equals( name ) );
}
}
| Suppress a warning
| processor/src/main/java/arez/processor/ProcessorUtil.java | Suppress a warning | <ide><path>rocessor/src/main/java/arez/processor/ProcessorUtil.java
<ide> import javax.lang.model.util.Elements;
<ide> import javax.lang.model.util.Types;
<ide>
<add>@SuppressWarnings( "WeakerAccess" )
<ide> final class ProcessorUtil
<ide> {
<ide> private ProcessorUtil() |
|
JavaScript | mit | 2fd480aaed6f77a38469c8bb616b151010ac22fd | 0 | jnhuynh/ember-enforcer,jnhuynh/ember-enforcer | import Ember from 'ember';
const _supportedAttrTypes = {
'bool': () => {
},
'function': () => {
},
'number': (value) => {
return Ember.isPresent(value) && Ember.typeOf(value) === 'number';
},
'object': () => {
},
'string': (value) => {
return Ember.isPresent(value) && Ember.typeOf(value) === 'string';
},
};
function _defaultAssertMessage(attrName, attrType) {
if (Ember.isPresent(attrType)) {
return ['Component', attrName, 'of type', attrType, 'is required'].join(' ');
} else {
return ['Component', attrName, 'is required'].join(' ');
}
}
function _enforceAttrMixin(attrName, errorMessage) {
return Ember.Mixin.create({
init() {
this._super(...arguments);
if (Ember.isEmpty(errorMessage)) {
errorMessage = _defaultAssertMessage(attrName);
}
Ember.assert(errorMessage, this.get('attrs').hasOwnProperty(attrName));
}
});
}
function _enforceAttrWithTypeMixin(attrName, attrType, errorMessage) {
return Ember.Mixin.create({
init() {
this._super(...arguments);
if (Ember.isEmpty(errorMessage)) {
errorMessage = _defaultAssertMessage(attrName, attrType);
}
const attrs = this.get('attrs');
Ember.assert(errorMessage, attrs.hasOwnProperty(attrName));
Ember.assert(errorMessage, _supportedAttrTypes[attrType](attrs[attrName]));
}
});
}
export default function required(attrName, options) {
Ember.assert('Enforcer.required() requires an attrName as the first argument',
Ember.isPresent(attrName));
let type;
let message;
if (Ember.isPresent(options)) {
type = options.type;
message = options.message;
}
let mixin;
if (Ember.isPresent(type)) {
let errorMessage = 'Enforcer.required() only accepts ' +
'options.type of the following values: ' +
Object.keys(_supportedAttrTypes).join(', ');
Ember.assert(errorMessage, _supportedAttrTypes.hasOwnProperty(type));
mixin = _enforceAttrWithTypeMixin(attrName, type, message);
} else {
mixin = _enforceAttrMixin(attrName, message);
}
return mixin;
}
| addon/required.js | import Ember from 'ember';
const _supportedAttrTypes = {
'bool': () => {
},
'function': () => {
},
'number': (value) => {
return Ember.isPresent(value) && typeof value === 'number';
},
'object': () => {
},
'string': (value) => {
return Ember.isPresent(value) && typeof value === 'string';
},
};
function _defaultAssertMessage(attrName, attrType) {
if (Ember.isPresent(attrType)) {
return ['Component', attrName, 'of type', attrType, 'is required'].join(' ');
} else {
return ['Component', attrName, 'is required'].join(' ');
}
}
function _enforceAttrMixin(attrName, errorMessage) {
return Ember.Mixin.create({
init() {
this._super(...arguments);
if (Ember.isEmpty(errorMessage)) {
errorMessage = _defaultAssertMessage(attrName);
}
Ember.assert(errorMessage, this.get('attrs').hasOwnProperty(attrName));
}
});
}
function _enforceAttrWithTypeMixin(attrName, attrType, errorMessage) {
return Ember.Mixin.create({
init() {
this._super(...arguments);
if (Ember.isEmpty(errorMessage)) {
errorMessage = _defaultAssertMessage(attrName, attrType);
}
const attrs = this.get('attrs');
Ember.assert(errorMessage, attrs.hasOwnProperty(attrName));
Ember.assert(errorMessage, _supportedAttrTypes[attrType](attrs[attrName]));
}
});
}
export default function required(attrName, options) {
Ember.assert('Enforcer.required() requires an attrName as the first argument',
Ember.isPresent(attrName));
let type;
let message;
if (Ember.isPresent(options)) {
type = options.type;
message = options.message;
}
let mixin;
if (Ember.isPresent(type)) {
let errorMessage = 'Enforcer.required() only accepts ' +
'options.type of the following values: ' +
Object.keys(_supportedAttrTypes).join(', ');
Ember.assert(errorMessage, _supportedAttrTypes.hasOwnProperty(type));
mixin = _enforceAttrWithTypeMixin(attrName, type, message);
} else {
mixin = _enforceAttrMixin(attrName, message);
}
return mixin;
}
| Use Ember.typeOf for consistent type check.
| addon/required.js | Use Ember.typeOf for consistent type check. | <ide><path>ddon/required.js
<ide> 'function': () => {
<ide> },
<ide> 'number': (value) => {
<del> return Ember.isPresent(value) && typeof value === 'number';
<add> return Ember.isPresent(value) && Ember.typeOf(value) === 'number';
<ide> },
<ide> 'object': () => {
<ide> },
<ide> 'string': (value) => {
<del> return Ember.isPresent(value) && typeof value === 'string';
<add> return Ember.isPresent(value) && Ember.typeOf(value) === 'string';
<ide> },
<ide> };
<ide> |
|
JavaScript | mit | a1881e0799bd1f6fea590641511a24eaabf88664 | 0 | lukecfairchild/MCJS | 'use strict';
/**
* @namespace
*/
var File = function () {};
/**
* Allows you to read and return the value of a file.
* @implements File
* @param {String} path - Specify a target text file to read.
* @return {String}
*/
File.prototype.read = function ( filePath ) {
var path = java.nio.file.Paths.get( PATH, filePath ).toString();
var contents = [];
var line = undefined;
var file = new java.io.File( PATH + filePath );
if ( file.exists() ) {
var fileReader = new java.io.FileReader( PATH + filePath );
var bufferReader = new java.io.BufferedReader( fileReader );
while ( ( line = bufferReader.readLine() ) !== null ) {
contents.push( line );
}
bufferReader.close();
fileReader.close();
return contents.join( '\n' );
} else {
console.log( '[ERROR]'.orange() + ' File not found:\n' + path + ':' + '\n' );
}
};
/**
* Allows you to write data to a file.
* @implements File
* @param {String} path - Specify a target file path.
* @param {String} data - The data to be written to the file.
*/
File.prototype.write = function ( filePath, data ) {
var FileWriter = Java.type( 'java.io.FileWriter' );
var file = new FileWriter( PATH + filePath );
file.write( data );
file.close();
};
/**
* Allows you to append data to a value.
* @implements File
* @param {String} path - Specify a target file path.
* @param {String} data - The data to be appended to the file.
*/
File.prototype.append = function ( filePath, data ) {
var FileWriter = Java.type( 'java.io.FileWriter' );
var file = new FileWriter( PATH + filePath, true );
file.write( data );
file.close();
};
/**
* Allows you to delete a file at the specified path.
* @implements File
* @param {String} path - Specify a target file path for deletion.
*/
File.prototype.delete = function ( filePath ) {
new java.io.File( PATH + filePath ).delete();
};
module.exports = new File();
| MCJS/lib/globals/File.js | 'use strict';
/**
* @namespace
*/
var File = function () {};
/**
* @implements File
* @param {String} path - Specify a target text file to read.
* @return {String}
*/
File.prototype.read = function ( filePath ) {
var path = java.nio.file.Paths.get( PATH, filePath ).toString();
var contents = [];
var line = undefined;
var file = new java.io.File( PATH + filePath );
if ( file.exists() ) {
var fileReader = new java.io.FileReader( PATH + filePath );
var bufferReader = new java.io.BufferedReader( fileReader );
while ( ( line = bufferReader.readLine() ) !== null ) {
contents.push( line );
}
bufferReader.close();
fileReader.close();
return contents.join( '\n' );
} else {
console.log( '[ERROR]'.orange() + ' File not found:\n' + path + ':' + '\n' );
}
};
/**
* @implements File
* @param {String} path - Specify a target file path.
* @param {String} data - The data to be written to the file.
*/
File.prototype.write = function ( filePath, data ) {
var FileWriter = Java.type( 'java.io.FileWriter' );
var file = new FileWriter( PATH + filePath );
file.write( data );
file.close();
};
/**
* @implements File
* @param {String} path - Specify a target file path.
* @param {String} data - The data to be appended to the file.
*/
File.prototype.append = function ( filePath, data ) {
var FileWriter = Java.type( 'java.io.FileWriter' );
var file = new FileWriter( PATH + filePath, true );
file.write( data );
file.close();
};
/**
* @implements File
* @param {String} path - Specify a target file path for deletion.
*/
File.prototype.delete = function ( filePath ) {
new java.io.File( PATH + filePath ).delete();
};
module.exports = new File();
| JSDoc comments
| MCJS/lib/globals/File.js | JSDoc comments | <ide><path>CJS/lib/globals/File.js
<ide>
<ide>
<ide> /**
<add> * Allows you to read and return the value of a file.
<ide> * @implements File
<ide> * @param {String} path - Specify a target text file to read.
<ide> * @return {String}
<ide>
<ide>
<ide> /**
<add> * Allows you to write data to a file.
<ide> * @implements File
<ide> * @param {String} path - Specify a target file path.
<ide> * @param {String} data - The data to be written to the file.
<ide>
<ide>
<ide> /**
<add> * Allows you to append data to a value.
<ide> * @implements File
<ide> * @param {String} path - Specify a target file path.
<ide> * @param {String} data - The data to be appended to the file.
<ide>
<ide>
<ide> /**
<add> * Allows you to delete a file at the specified path.
<ide> * @implements File
<ide> * @param {String} path - Specify a target file path for deletion.
<ide> */ |
|
Java | apache-2.0 | error: pathspec 'forge-addons/camel/src/main/java/io/fabric8/forge/camel/commands/jolokia/ContextInflightCommand.java' did not match any file(s) known to git
| da711ce9520e07fa1833a1575262d03066bc81e8 | 1 | jimmidyson/fabric8,christian-posta/fabric8,dhirajsb/fabric8,EricWittmann/fabric8,rajdavies/fabric8,rhuss/fabric8,zmhassan/fabric8,KurtStam/fabric8,PhilHardwick/fabric8,migue/fabric8,sobkowiak/fabric8,EricWittmann/fabric8,rnc/fabric8,gashcrumb/fabric8,dhirajsb/fabric8,sobkowiak/fabric8,christian-posta/fabric8,gashcrumb/fabric8,zmhassan/fabric8,KurtStam/fabric8,rnc/fabric8,chirino/fabric8v2,sobkowiak/fabric8,jimmidyson/fabric8,migue/fabric8,mwringe/fabric8,gashcrumb/fabric8,mwringe/fabric8,jimmidyson/fabric8,chirino/fabric8v2,hekonsek/fabric8,mwringe/fabric8,rajdavies/fabric8,rhuss/fabric8,dhirajsb/fabric8,KurtStam/fabric8,hekonsek/fabric8,dhirajsb/fabric8,sobkowiak/fabric8,rhuss/fabric8,jimmidyson/fabric8,EricWittmann/fabric8,EricWittmann/fabric8,PhilHardwick/fabric8,hekonsek/fabric8,christian-posta/fabric8,rnc/fabric8,gashcrumb/fabric8,rajdavies/fabric8,chirino/fabric8v2,rhuss/fabric8,zmhassan/fabric8,jimmidyson/fabric8,rajdavies/fabric8,KurtStam/fabric8,hekonsek/fabric8,migue/fabric8,hekonsek/fabric8,PhilHardwick/fabric8,chirino/fabric8v2,mwringe/fabric8,rnc/fabric8,rnc/fabric8,christian-posta/fabric8,PhilHardwick/fabric8,zmhassan/fabric8,migue/fabric8 | /**
* Copyright 2005-2014 Red Hat, Inc.
*
* Red Hat 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.fabric8.forge.camel.commands.jolokia;
import javax.inject.Inject;
import org.jboss.forge.addon.ui.context.UIBuilder;
import org.jboss.forge.addon.ui.context.UIContext;
import org.jboss.forge.addon.ui.context.UIExecutionContext;
import org.jboss.forge.addon.ui.input.UIInput;
import org.jboss.forge.addon.ui.metadata.UICommandMetadata;
import org.jboss.forge.addon.ui.metadata.WithAttributes;
import org.jboss.forge.addon.ui.result.Result;
import org.jboss.forge.addon.ui.result.Results;
import org.jboss.forge.addon.ui.util.Categories;
import org.jboss.forge.addon.ui.util.Metadata;
public class ContextInflightCommand extends AbstractJolokiaCommand {
@Inject
@WithAttributes(label = "name", required = true, description = "The name of the Camel context")
private UIInput<String> name;
@Inject
@WithAttributes(label = "limit", required = false, defaultValue = "0", description = "To limit the number of exchanges shown")
private UIInput<Integer> limit;
@Inject
@WithAttributes(label = "sortByLongestDuration", required = false, defaultValue = "false", description = "true = sort by longest duration, false = sort by exchange id")
private UIInput<Boolean> sortByLongestDuration;
@Override
public UICommandMetadata getMetadata(UIContext context) {
return Metadata.forCommand(ConnectCommand.class).name(
"camel-context-inflight").category(Categories.create(CATEGORY))
.description("List inflight exchanges.");
}
@Override
public void initializeUI(UIBuilder builder) throws Exception {
name.setCompleter(new CamelContextCompleter(getController()));
builder.add(name).add(limit).add(sortByLongestDuration);
}
@Override
public Result execute(UIExecutionContext context) throws Exception {
String url = getJolokiaUrl();
if (url == null) {
return Results.fail("Not connected to remote jolokia agent. Use camel-connect command first");
}
org.apache.camel.commands.ContextInflightCommand command = new org.apache.camel.commands.ContextInflightCommand(name.getValue(), limit.getValue(), sortByLongestDuration.getValue());
command.execute(getController(), getOutput(context), getError(context));
return Results.success();
}
}
| forge-addons/camel/src/main/java/io/fabric8/forge/camel/commands/jolokia/ContextInflightCommand.java | #3025: reusing camel commands in forge.
| forge-addons/camel/src/main/java/io/fabric8/forge/camel/commands/jolokia/ContextInflightCommand.java | #3025: reusing camel commands in forge. | <ide><path>orge-addons/camel/src/main/java/io/fabric8/forge/camel/commands/jolokia/ContextInflightCommand.java
<add>/**
<add> * Copyright 2005-2014 Red Hat, Inc.
<add> *
<add> * Red Hat licenses this file to you under the Apache License, version
<add> * 2.0 (the "License"); you may not use this file except in compliance
<add> * with the License. You may obtain a copy 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,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
<add> * implied. See the License for the specific language governing
<add> * permissions and limitations under the License.
<add> */
<add>package io.fabric8.forge.camel.commands.jolokia;
<add>
<add>import javax.inject.Inject;
<add>
<add>import org.jboss.forge.addon.ui.context.UIBuilder;
<add>import org.jboss.forge.addon.ui.context.UIContext;
<add>import org.jboss.forge.addon.ui.context.UIExecutionContext;
<add>import org.jboss.forge.addon.ui.input.UIInput;
<add>import org.jboss.forge.addon.ui.metadata.UICommandMetadata;
<add>import org.jboss.forge.addon.ui.metadata.WithAttributes;
<add>import org.jboss.forge.addon.ui.result.Result;
<add>import org.jboss.forge.addon.ui.result.Results;
<add>import org.jboss.forge.addon.ui.util.Categories;
<add>import org.jboss.forge.addon.ui.util.Metadata;
<add>
<add>public class ContextInflightCommand extends AbstractJolokiaCommand {
<add>
<add> @Inject
<add> @WithAttributes(label = "name", required = true, description = "The name of the Camel context")
<add> private UIInput<String> name;
<add>
<add> @Inject
<add> @WithAttributes(label = "limit", required = false, defaultValue = "0", description = "To limit the number of exchanges shown")
<add> private UIInput<Integer> limit;
<add>
<add> @Inject
<add> @WithAttributes(label = "sortByLongestDuration", required = false, defaultValue = "false", description = "true = sort by longest duration, false = sort by exchange id")
<add> private UIInput<Boolean> sortByLongestDuration;
<add>
<add> @Override
<add> public UICommandMetadata getMetadata(UIContext context) {
<add> return Metadata.forCommand(ConnectCommand.class).name(
<add> "camel-context-inflight").category(Categories.create(CATEGORY))
<add> .description("List inflight exchanges.");
<add> }
<add>
<add> @Override
<add> public void initializeUI(UIBuilder builder) throws Exception {
<add> name.setCompleter(new CamelContextCompleter(getController()));
<add> builder.add(name).add(limit).add(sortByLongestDuration);
<add> }
<add>
<add> @Override
<add> public Result execute(UIExecutionContext context) throws Exception {
<add> String url = getJolokiaUrl();
<add> if (url == null) {
<add> return Results.fail("Not connected to remote jolokia agent. Use camel-connect command first");
<add> }
<add>
<add> org.apache.camel.commands.ContextInflightCommand command = new org.apache.camel.commands.ContextInflightCommand(name.getValue(), limit.getValue(), sortByLongestDuration.getValue());
<add>
<add> command.execute(getController(), getOutput(context), getError(context));
<add> return Results.success();
<add> }
<add>} |
|
Java | agpl-3.0 | c11ea791fb6c21b89d177eff707dbc404c7d08eb | 0 | roskens/opennms-pre-github,roskens/opennms-pre-github,roskens/opennms-pre-github,aihua/opennms,aihua/opennms,roskens/opennms-pre-github,tdefilip/opennms,tdefilip/opennms,aihua/opennms,roskens/opennms-pre-github,aihua/opennms,aihua/opennms,tdefilip/opennms,roskens/opennms-pre-github,rdkgit/opennms,tdefilip/opennms,rdkgit/opennms,rdkgit/opennms,rdkgit/opennms,aihua/opennms,roskens/opennms-pre-github,roskens/opennms-pre-github,aihua/opennms,aihua/opennms,roskens/opennms-pre-github,tdefilip/opennms,tdefilip/opennms,rdkgit/opennms,tdefilip/opennms,roskens/opennms-pre-github,roskens/opennms-pre-github,rdkgit/opennms,aihua/opennms,tdefilip/opennms,tdefilip/opennms,rdkgit/opennms,rdkgit/opennms,rdkgit/opennms,rdkgit/opennms | /*
* This file is part of the OpenNMS(R) Application.
*
* OpenNMS(R) is Copyright (C) 2005-2007 The OpenNMS Group, Inc. All rights reserved.
* OpenNMS(R) is a derivative work, containing both original code, included code and modified
* code that was published under the GNU General Public License. Copyrights for modified
* and included code are below.
*
* OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
*
* Modifications:
*
* 2010 Feb 11: Added support for attachments from input stream - [email protected].
* 2008 Jan 06: Indent. - [email protected]
* 2008 Jan 06: Moved initialization of the mailer session to constructor so
* that properties can be overridden by the implementer.
* - [email protected]
* 2007 Jun 13: Added support for SSL, proper auth, ports, content-type, and
* charsets.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* For more information contact:
* OpenNMS Licensing <[email protected]>
* http://www.opennms.org/
* http://www.opennms.com/
*/
package org.opennms.javamail;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Part;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.event.TransportEvent;
import javax.mail.event.TransportListener;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
import org.opennms.core.utils.PropertiesUtils;
import org.opennms.core.utils.ThreadCategory;
import org.springframework.util.StringUtils;
/**
* Sends an email message using the Java Mail API
*
* @author <A HREF="mailto:[email protected]">David Hustace </A>
*/
public class JavaMailer {
private static final String DEFAULT_FROM_ADDRESS = "root@[127.0.0.1]";
// private static final String DEFAULT_TO_ADDRESS = "root@[127.0.0.1]";
private static final String DEFAULT_MAIL_HOST = "127.0.0.1";
private static final boolean DEFAULT_AUTHENTICATE = false;
private static final String DEFAULT_AUTHENTICATE_USER = "opennms";
private static final String DEFAULT_AUTHENTICATE_PASSWORD = "opennms";
private static final String DEFAULT_MAILER = "smtpsend";
private static final String DEFAULT_TRANSPORT = "smtp";
private static final boolean DEFAULT_MAILER_DEBUG = false;
private static final boolean DEFAULT_USE_JMTA = true;
private static final String DEFAULT_CONTENT_TYPE = "text/plain";
private static final String DEFAULT_CHARSET = "us-ascii";
private static final String DEFAULT_ENCODING = "Q"; // I think this means quoted-printable encoding, see bug 2825
private static final boolean DEFAULT_STARTTLS_ENABLE = false;
private static final boolean DEFAULT_QUIT_WAIT = true;
private static final int DEFAULT_SMTP_PORT = 25;
private static final boolean DEFAULT_SMTP_SSL_ENABLE = false;
private Session m_session = null;
/*
* properties from configuration
*/
private Properties m_mailProps;
/*
* fields from properties used for deterministic behavior of the mailer
*/
private boolean m_debug;
private String m_mailHost;
private boolean m_useJMTA;
private String m_mailer;
private String m_transport;
private String m_from;
private boolean m_authenticate;
private String m_user;
private String m_password;
private String m_contentType;
private String m_charSet;
private String m_encoding;
private boolean m_startTlsEnabled;
private boolean m_quitWait;
private int m_smtpPort;
private boolean m_smtpSsl;
/*
* Basic messaging fields
*/
private String m_to;
private String m_subject;
private String m_messageText;
private String m_fileName;
private InputStream m_inputStream;
private String m_inputStreamName;
private String m_inputStreamContentType;
public JavaMailer(Properties javamailProps) throws JavaMailerException {
try {
configureProperties(javamailProps);
} catch (IOException e) {
throw new JavaMailerException("Failed to construct mailer", e);
}
//Now set the properties into the session
m_session = Session.getInstance(getMailProps(), createAuthenticator());
}
/**
* Default constructor. Default properties from javamailer-properties are set into session. To change these
* properties, retrieve the current properties from the session and override as needed.
* @throws IOException
*/
public JavaMailer() throws JavaMailerException {
this(new Properties());
}
/**
* This method uses a properties file reader to pull in opennms styled javamail properties and sets
* the actual javamail properties. This is here to preserve the backwards compatibility but configuration
* will probably change soon.
*
* @throws IOException
*/
private void configureProperties(Properties javamailProps) throws IOException {
//this loads the opennms defined properties
m_mailProps = JavaMailerConfig.getProperties();
//this sets any javamail defined properties sent in to the constructor
m_mailProps.putAll(javamailProps);
/*
* fields from properties used for deterministic behavior of the mailer
*/
m_debug = PropertiesUtils.getProperty(m_mailProps, "org.opennms.core.utils.debug", DEFAULT_MAILER_DEBUG);
m_mailHost = PropertiesUtils.getProperty(m_mailProps, "org.opennms.core.utils.mailHost", DEFAULT_MAIL_HOST);
m_useJMTA = PropertiesUtils.getProperty(m_mailProps, "org.opennms.core.utils.useJMTA", DEFAULT_USE_JMTA);
m_mailer = PropertiesUtils.getProperty(m_mailProps, "org.opennms.core.utils.mailer", DEFAULT_MAILER);
m_transport = PropertiesUtils.getProperty(m_mailProps, "org.opennms.core.utils.transport", DEFAULT_TRANSPORT);
m_from = PropertiesUtils.getProperty(m_mailProps, "org.opennms.core.utils.fromAddress", DEFAULT_FROM_ADDRESS);
m_authenticate = PropertiesUtils.getProperty(m_mailProps, "org.opennms.core.utils.authenticate", DEFAULT_AUTHENTICATE);
m_user = PropertiesUtils.getProperty(m_mailProps, "org.opennms.core.utils.authenticateUser", DEFAULT_AUTHENTICATE_USER);
m_password = PropertiesUtils.getProperty(m_mailProps, "org.opennms.core.utils.authenticatePassword", DEFAULT_AUTHENTICATE_PASSWORD);
m_contentType = PropertiesUtils.getProperty(m_mailProps, "org.opennms.core.utils.messageContentType", DEFAULT_CONTENT_TYPE);
m_charSet = PropertiesUtils.getProperty(m_mailProps, "org.opennms.core.utils.charset", DEFAULT_CHARSET);
m_encoding = PropertiesUtils.getProperty(m_mailProps, "org.opennms.core.utils.encoding", DEFAULT_ENCODING);
m_startTlsEnabled = PropertiesUtils.getProperty(m_mailProps, "org.opennms.core.utils.starttls.enable", DEFAULT_STARTTLS_ENABLE);
m_quitWait = PropertiesUtils.getProperty(m_mailProps, "org.opennms.core.utils.quitwait", DEFAULT_QUIT_WAIT);
m_smtpPort = PropertiesUtils.getProperty(m_mailProps, "org.opennms.core.utils.smtpport", DEFAULT_SMTP_PORT);
m_smtpSsl = PropertiesUtils.getProperty(m_mailProps, "org.opennms.core.utils.smtpssl.enable", DEFAULT_SMTP_SSL_ENABLE);
//Set the actual JavaMailProperties... any that are defined in the file will not be overridden
//Eventually, all configuration will be defined in properties and this strange parsing will not happen
//TODO: fix this craziness!
if (!m_mailProps.containsKey("mail.smtp.auth")) {
m_mailProps.setProperty("mail.smtp.auth", String.valueOf(isAuthenticate()));
}
if (!m_mailProps.containsKey("mail.smtp.starttls.enable")) {
m_mailProps.setProperty("mail.smtp.starttls.enable", String.valueOf(isStartTlsEnabled()));
}
if (!m_mailProps.containsKey("mail.smtp.quitwait")) {
m_mailProps.setProperty("mail.smtp.quitwait", String.valueOf(isQuitWait()));
}
if (!m_mailProps.containsKey("mail.smtp.port")) {
m_mailProps.setProperty("mail.smtp.port", String.valueOf(getSmtpPort()));
}
if (isSmtpSsl()) {
if (!m_mailProps.containsKey("mail.smtps.auth")) {
m_mailProps.setProperty("mail.smtps.auth", String.valueOf(isAuthenticate()));
}
if (!m_mailProps.containsKey("mail.smtps.socketFactory.class")) {
m_mailProps.setProperty("mail.smtps.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
}
if (!m_mailProps.containsKey("mail.smtps.socketFactory.port")) {
m_mailProps.setProperty("mail.smtps.socketFactory.port", String.valueOf(getSmtpPort()));
}
// if (!getMailProps().containsKey("mail.smtp.socketFactory.fallback")) {
// getMailProps().setProperty("mail.smtp.socketFactory.fallback", "false");
// }
}
if (!m_mailProps.containsKey("mail.smtp.quitwait")) {
m_mailProps.setProperty("mail.smtp.quitwait", "true");
}
//getMailProps().setProperty("mail.store.protocol", "pop3");
}
/**
* Sends a message based on properties set on this bean.
*/
public void mailSend() throws JavaMailerException {
log().debug(createSendLogMsg());
sendMessage(buildMessage());
}
/**
* Helper method to create an Authenticator based on Password Authentication
* @return
*/
public Authenticator createAuthenticator() {
Authenticator auth;
if (isAuthenticate()) {
auth = new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(getUser(), getPassword());
}
};
} else {
auth = null;
}
return auth;
}
/**
* Build a complete message ready for sending.
*
* @param session session to use to create a new MimeMessage
* @return completed message, ready to be passed to Transport.sendMessage
* @throws JavaMailerException if any of the underlying operations fail
*/
public Message buildMessage() throws JavaMailerException {
try {
checkEnvelopeAndContents();
Message message = initializeMessage();
String encodedText = MimeUtility.encodeText(getMessageText(), m_charSet, m_encoding);
if ((getFileName() == null) && (getInputStream() == null)) {
message.setContent(encodedText, m_contentType+"; charset="+m_charSet);
} else if (getFileName() == null) {
BodyPart streamBodyPart = new MimeBodyPart();
streamBodyPart.setDataHandler(new DataHandler(new InputStreamDataSource(m_inputStreamName, m_inputStreamContentType, m_inputStream)));
streamBodyPart.setFileName(m_inputStreamName);
streamBodyPart.setHeader("Content-Transfer-Encoding", "base64");
streamBodyPart.setDisposition(Part.ATTACHMENT);
MimeMultipart mp = new MimeMultipart();
mp.addBodyPart(streamBodyPart);
message.setContent(mp);
} else {
BodyPart bp = new MimeBodyPart();
bp.setContent(encodedText, m_contentType+"; charset="+m_charSet);
MimeMultipart mp = new MimeMultipart();
mp.addBodyPart(bp);
mp = new MimeMultipart();
mp.addBodyPart(createFileAttachment(new File(getFileName())));
message.setContent(mp);
}
message.setHeader("X-Mailer", getMailer());
message.setSentDate(new Date());
message.saveChanges();
return message;
} catch (AddressException e) {
log().error("Java Mailer Addressing exception: ", e);
throw new JavaMailerException("Java Mailer Addressing exception: ", e);
} catch (MessagingException e) {
log().error("Java Mailer messaging exception: ", e);
throw new JavaMailerException("Java Mailer messaging exception: ", e);
} catch (UnsupportedEncodingException e) {
log().error("Java Mailer messaging exception: ", e);
throw new JavaMailerException("Java Mailer encoding exception: ", e);
}
}
/**
* Helper method to that creates a MIME message.
* @param session
* @return
* @throws MessagingException
* @throws AddressException
*/
private Message initializeMessage() throws MessagingException, AddressException {
Message message;
message = new MimeMessage(getSession());
message.setFrom(new InternetAddress(getFrom()));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(getTo(), false));
message.setSubject(getSubject());
return message;
}
/**
* @return
*/
private String createSendLogMsg() {
StringBuffer sb = new StringBuffer();
sb.append("\n\tTo: ");
sb.append(getTo());
sb.append("\n\tFrom: ");
sb.append(getFrom());
sb.append("\n\tSubject is: ");
sb.append(getSubject());
sb.append("\n\tFile: ");
sb.append(getFileName()!=null ? getFileName() : "no file attached");
sb.append("\n\n");
sb.append(getMessageText());
sb.append("\n");
return sb.toString();
}
/**
* Create a file attachment as a MimeBodyPart, checking to see if the file
* exists before we create the attachment.
*
* @param file file to attach
* @return attachment body part
* @throws MessagingException if we can't set the data handler or
* the file name on the MimeBodyPart
* @throws JavaMailerException if the file does not exist or is not
* readable
*/
public MimeBodyPart createFileAttachment(final File file) throws MessagingException, JavaMailerException {
if (!file.exists()) {
log().error("File attachment '" + file.getAbsolutePath() + "' does not exist.");
throw new JavaMailerException("File attachment '" + file.getAbsolutePath() + "' does not exist.");
}
if (!file.canRead()) {
log().error("File attachment '" + file.getAbsolutePath() + "' is not readable.");
throw new JavaMailerException("File attachment '" + file.getAbsolutePath() + "' is not readable.");
}
MimeBodyPart bodyPart = new MimeBodyPart();
FileDataSource fds = new FileDataSource(file);
bodyPart.setDataHandler(new DataHandler(fds));
bodyPart.setFileName(fds.getName());
return bodyPart;
}
/**
* Check that required envelope and message contents properties have been
* set.
*
* @throws JavaMailerException if any of the required properties have not
* been set
*/
private void checkEnvelopeAndContents() throws JavaMailerException {
if (getFrom() == null) {
throw new JavaMailerException("Cannot have a null from address.");
}
if ("".equals(getFrom())) {
throw new JavaMailerException("Cannot have an empty from address.");
}
if (getTo() == null) {
throw new JavaMailerException("Cannot have a null to address.");
}
if ("".equals(getTo())) {
throw new JavaMailerException("Cannot have an empty to address.");
}
if (getSubject() == null) {
throw new JavaMailerException("Cannot have a null subject.");
}
if ("".equals(getSubject())) {
throw new JavaMailerException("Cannot have an empty subject.");
}
if (getMessageText() == null) {
throw new JavaMailerException("Cannot have a null messageText.");
}
if ("".equals(getMessageText())) {
throw new JavaMailerException("Cannot have an empty messageText.");
}
}
/**
* Send message.
*
* @param session
* @param message
* @throws JavaMailerException
*/
public void sendMessage(Message message) throws JavaMailerException {
Transport t = null;
try {
t = getSession().getTransport(getTransport());
log().debug("for transport name '" + getTransport() + "' got: " + t.getClass().getName() + "@" + Integer.toHexString(t.hashCode()));
LoggingTransportListener listener = new LoggingTransportListener(log());
t.addTransportListener(listener);
if (t.getURLName().getProtocol().equals("mta")) {
// JMTA throws an AuthenticationFailedException if we call connect()
log().debug("transport is 'mta', not trying to connect()");
} else if (isAuthenticate()) {
log().debug("authenticating to " + getMailHost());
t.connect(getMailHost(), getSmtpPort(), getUser(), getPassword());
} else {
log().debug("not authenticating to " + getMailHost());
t.connect(getMailHost(), getSmtpPort(), null, null);
}
t.sendMessage(message, message.getAllRecipients());
listener.assertAllMessagesDelivered();
} catch (NoSuchProviderException e) {
log().error("Couldn't get a transport: " + e, e);
throw new JavaMailerException("Couldn't get a transport: " + e, e);
} catch (MessagingException e) {
log().error("Java Mailer messaging exception: " + e, e);
throw new JavaMailerException("Java Mailer messaging exception: " + e, e);
} finally {
try {
if (t != null && t.isConnected()) {
t.close();
}
} catch (MessagingException e) {
throw new JavaMailerException("Java Mailer messaging exception on transport close: " + e, e);
}
}
}
private class InputStreamDataSource implements DataSource {
private String name;
private String contentType;
private ByteArrayOutputStream baos;
InputStreamDataSource(String name, String contentType, InputStream inputStream) throws JavaMailerException {
this.name = name;
this.contentType = contentType;
log().debug("setting contentType " + this.contentType);
baos = new ByteArrayOutputStream();
int read;
byte[] buff = new byte[256];
try {
while((read = inputStream.read(buff)) != -1) {
baos.write(buff, 0, read);
}
} catch (IOException e) {
log().error("Could not read attachment from input stream: " + e, e);
throw new JavaMailerException("Could not read attachment from input stream: " + e, e);
}
}
public String getContentType() {
log().debug("getContentType: " + contentType);
return contentType;
}
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(baos.toByteArray());
}
public String getName() {
return name;
}
public OutputStream getOutputStream() throws IOException {
throw new IOException("Cannot write to this read-only resource");
}
}
/**
* @return Returns the password.
*/
public String getPassword() {
return m_password;
}
/**
* @param password
* The password to set.
*/
public void setPassword(String password) {
m_password = password;
}
/**
* @return Returns the user.
*/
public String getUser() {
return m_user;
}
/**
* @param user
* The user to set.
*/
public void setUser(String user) {
m_user = user;
}
/**
* @return Returns the _useMailHost.
*/
public boolean isUseJMTA() {
return m_useJMTA;
}
/**
* @param mailHost The _useMailHost to set.
*/
public void setUseJMTA(boolean useMTA) {
m_useJMTA = useMTA;
}
/**
* @return Returns the from address.
*/
public String getFrom() {
return m_from;
}
/**
* @param from
* The from address to set.
*/
public void setFrom(String from) {
m_from = from;
}
/**
* @return Returns the authenticate boolean.
*/
public boolean isAuthenticate() {
return m_authenticate;
}
/**
* @param authenticate
* The authenticate boolean to set.
*/
public void setAuthenticate(boolean authenticate) {
m_authenticate = authenticate;
}
/**
* @return Returns the file name attachment.
*/
public String getFileName() {
return m_fileName;
}
/**
* @param file
* Sets the file name to be attached to the messaget.
*/
public void setFileName(String fileName) {
m_fileName = fileName;
}
/**
* @return Returns the input stream attachment.
*/
public InputStream getInputStream() {
return m_inputStream;
}
/**
* @param inputStream
* Sets the input stream to be attached to the message.
*/
public void setInputStream(InputStream inputStream) {
m_inputStream = inputStream;
}
/**
* @return Returns the name to use for stream attachments..
*/
public String getInputStreamName() {
return m_inputStreamName;
}
/**
* @param inputStreamName
* Sets the name to use for stream attachments.
*/
public void setInputStreamName(String inputStreamName) {
m_inputStreamName = inputStreamName;
}
/**
* @return Returns the name to use for stream attachments..
*/
public String getInputStreamContentType() {
return m_inputStreamContentType;
}
/**
* @param inputStreamName
* Sets the name to use for stream attachments.
*/
public void setInputStreamContentType(String inputStreamContentType) {
m_inputStreamContentType = inputStreamContentType;
}
/**
* @return Returns the mail host.
*/
public String getMailHost() {
return m_mailHost;
}
/**
* @param mail_host
* Sets the mail host.
*/
public void setMailHost(String mail_host) {
m_mailHost = mail_host;
}
/**
* @return Returns the mailer.
*/
public String getMailer() {
return m_mailer;
}
/**
* @param mailer
* Sets the mailer.
*/
public void setMailer(String mailer) {
m_mailer = mailer;
}
/**
* @return Returns the message text.
*/
public String getMessageText() {
return m_messageText;
}
/**
* @param messageText
* Sets the message text.
*/
public void setMessageText(String messageText) {
m_messageText = messageText;
}
/**
* @return Returns the message Subject.
*/
public String getSubject() {
return m_subject;
}
/**
* @param subject
* Sets the message Subject.
*/
public void setSubject(String subject) {
m_subject = subject;
}
/**
* @return Returns the To address.
*/
public String getTo() {
return m_to;
}
/**
* @param to
* Sets the To address.
*/
public void setTo(String to) {
m_to = to;
}
public String getTransport() {
if (isUseJMTA()) {
return "mta";
} else {
return m_transport;
}
}
public void setTransport(String transport) {
m_transport = transport;
}
public boolean isDebug() {
return m_debug;
}
public void setDebug(boolean debug) {
m_debug = debug;
if (isDebug()) {
m_session.setDebugOut(new PrintStream(new LoggingByteArrayOutputStream(log()), true));
}
m_session.setDebug(isDebug());
}
/**
* @return log4j Category
*/
private ThreadCategory log() {
return ThreadCategory.getInstance(getClass());
}
public static class LoggingByteArrayOutputStream extends ByteArrayOutputStream {
private ThreadCategory m_category;
public LoggingByteArrayOutputStream(ThreadCategory threadCategory) {
m_category = threadCategory;
}
@Override
public void flush() throws IOException {
super.flush();
String buffer = toString().replaceAll("\n", "");
if (buffer.length() > 0) {
m_category.debug(buffer);
}
reset();
}
}
public static class LoggingTransportListener implements TransportListener {
private ThreadCategory m_category;
private List<Address> m_invalidAddresses = new ArrayList<Address>();
private List<Address> m_validSentAddresses = new ArrayList<Address>();
private List<Address> m_validUnsentAddresses = new ArrayList<Address>();
public LoggingTransportListener(ThreadCategory threadCategory) {
m_category = threadCategory;
}
public void messageDelivered(TransportEvent event) {
logEvent("message delivered", event);
}
public void messageNotDelivered(TransportEvent event) {
logEvent("message not delivered", event);
}
public void messagePartiallyDelivered(TransportEvent event) {
logEvent("message partially delivered", event);
}
private void logEvent(String message, TransportEvent event) {
if (event.getInvalidAddresses() != null && event.getInvalidAddresses().length > 0) {
m_invalidAddresses.addAll(Arrays.asList(event.getInvalidAddresses()));
m_category.error(message + ": invalid addresses: " + StringUtils.arrayToDelimitedString(event.getInvalidAddresses(), ", "));
}
if (event.getValidSentAddresses() != null && event.getValidSentAddresses().length > 0) {
m_validSentAddresses.addAll(Arrays.asList(event.getValidSentAddresses()));
m_category.debug(message + ": valid sent addresses: " + StringUtils.arrayToDelimitedString(event.getValidSentAddresses(), ", "));
}
if (event.getValidUnsentAddresses() != null && event.getValidUnsentAddresses().length > 0) {
m_validUnsentAddresses.addAll(Arrays.asList(event.getValidUnsentAddresses()));
m_category.error(message + ": valid unsent addresses: " + StringUtils.arrayToDelimitedString(event.getValidUnsentAddresses(), ", "));
}
}
public boolean hasAnythingBeenReceived() {
return m_invalidAddresses.size() != 0 || m_validSentAddresses.size() != 0 || m_validUnsentAddresses.size() != 0;
}
/**
* We sleep up to ten times for 10ms, checking to see if anything has
* been received because the notifications are done by a separate
* thread. We also wait another 50ms after we see the first
* notification come in, just to see if anything else trickles in.
* This isn't perfect, but it's somewhat of a shot in the dark to
* hope that we catch most things, to try to catch as many errors
* as possible so we can fairly reliably report if anything had
* problems.
*
* @throws JavaMailerException
*/
public void assertAllMessagesDelivered() throws JavaMailerException {
for (int i = 0; i < 10; i++) {
if (hasAnythingBeenReceived()) {
break;
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// Do nothing
}
}
try {
Thread.sleep(50);
} catch (InterruptedException e) {
// Do nothing
}
if (m_invalidAddresses.size() == 0 && m_validUnsentAddresses.size() == 0) {
// Nothing failed, so just return
return;
}
throw new JavaMailerException("Not all messages delivered:\n"
+ "\t" + m_validSentAddresses.size() + " messages were sent to valid addresses: " + StringUtils.collectionToDelimitedString(m_validSentAddresses, ", ") + "\n"
+ "\t" + m_validUnsentAddresses.size() + " messages were not sent to valid addresses: " + StringUtils.collectionToDelimitedString(m_validUnsentAddresses, ", ") + "\n"
+ "\t" + m_invalidAddresses.size() + " messages had invalid addresses: " + StringUtils.collectionToDelimitedString(m_invalidAddresses, ", "));
}
}
/**
* @return the session
*/
public Session getSession() {
return m_session;
}
/**
* @param session the session to set
*/
public void setSession(Session session) {
m_session = session;
}
/**
* @return the contentType
*/
public String getContentType() {
return m_contentType;
}
/**
* @param contentType the contentType to set
*/
public void setContentType(String contentType) {
m_contentType = contentType;
}
/**
* @return the charSet
*/
public String getCharSet() {
return m_charSet;
}
/**
* @param charSet the charSet to set
*/
public void setCharSet(String charSet) {
m_charSet = charSet;
}
/**
* @return the encoding
*/
public String getEncoding() {
return m_encoding;
}
/**
* @param encoding the encoding to set
*/
public void setEncoding(String encoding) {
m_encoding = encoding;
}
/**
* @return the startTlsEnabled
*/
public boolean isStartTlsEnabled() {
return m_startTlsEnabled;
}
/**
* @param startTlsEnabled the startTlsEnabled to set
*/
public void setStartTlsEnabled(boolean startTlsEnabled) {
m_startTlsEnabled = startTlsEnabled;
}
/**
* @return the quitWait
*/
public boolean isQuitWait() {
return m_quitWait;
}
/**
* @param quitWait the quitWait to set
*/
public void setQuitWait(boolean quitWait) {
m_quitWait = quitWait;
}
/**
* @return the smtpPort
*/
public int getSmtpPort() {
return m_smtpPort;
}
/**
* @param smtpPort the smtpPort to set
*/
public void setSmtpPort(int smtpPort) {
m_smtpPort = smtpPort;
}
/**
* @return the smtpSsl
*/
public boolean isSmtpSsl() {
return m_smtpSsl;
}
/**
* @param smtpSsl the smtpSsl to set
*/
public void setSmtpSsl(boolean smtpSsl) {
m_smtpSsl = smtpSsl;
}
/**
* This returns the properties configured in the javamail-configuration.properties file.
* @return
*/
public Properties getMailProps() {
return m_mailProps;
}
}
| opennms-javamail/opennms-javamail-api/src/main/java/org/opennms/javamail/JavaMailer.java | /*
* This file is part of the OpenNMS(R) Application.
*
* OpenNMS(R) is Copyright (C) 2005-2007 The OpenNMS Group, Inc. All rights reserved.
* OpenNMS(R) is a derivative work, containing both original code, included code and modified
* code that was published under the GNU General Public License. Copyrights for modified
* and included code are below.
*
* OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
*
* Modifications:
*
* 2010 Feb 11: Added support for attachments from input stream - [email protected].
* 2008 Jan 06: Indent. - [email protected]
* 2008 Jan 06: Moved initialization of the mailer session to constructor so
* that properties can be overridden by the implementer.
* - [email protected]
* 2007 Jun 13: Added support for SSL, proper auth, ports, content-type, and
* charsets.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* For more information contact:
* OpenNMS Licensing <[email protected]>
* http://www.opennms.org/
* http://www.opennms.com/
*/
package org.opennms.javamail;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Part;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.event.TransportEvent;
import javax.mail.event.TransportListener;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
import org.opennms.core.utils.PropertiesUtils;
import org.opennms.core.utils.ThreadCategory;
import org.springframework.util.StringUtils;
/**
* Sends an email message using the Java Mail API
*
* @author <A HREF="mailto:[email protected]">David Hustace </A>
*/
public class JavaMailer {
private static final String DEFAULT_FROM_ADDRESS = "root@[127.0.0.1]";
// private static final String DEFAULT_TO_ADDRESS = "root@[127.0.0.1]";
private static final String DEFAULT_MAIL_HOST = "127.0.0.1";
private static final boolean DEFAULT_AUTHENTICATE = false;
private static final String DEFAULT_AUTHENTICATE_USER = "opennms";
private static final String DEFAULT_AUTHENTICATE_PASSWORD = "opennms";
private static final String DEFAULT_MAILER = "smtpsend";
private static final String DEFAULT_TRANSPORT = "smtp";
private static final boolean DEFAULT_MAILER_DEBUG = true;
private static final boolean DEFAULT_USE_JMTA = true;
private static final String DEFAULT_CONTENT_TYPE = "text/plain";
private static final String DEFAULT_CHARSET = "us-ascii";
private static final String DEFAULT_ENCODING = "Q"; // I think this means quoted-printable encoding, see bug 2825
private static final boolean DEFAULT_STARTTLS_ENABLE = false;
private static final boolean DEFAULT_QUIT_WAIT = true;
private static final int DEFAULT_SMTP_PORT = 25;
private static final boolean DEFAULT_SMTP_SSL_ENABLE = false;
private Session m_session = null;
/*
* properties from configuration
*/
private Properties m_mailProps;
/*
* fields from properties used for deterministic behavior of the mailer
*/
private boolean m_debug;
private String m_mailHost;
private boolean m_useJMTA;
private String m_mailer;
private String m_transport;
private String m_from;
private boolean m_authenticate;
private String m_user;
private String m_password;
private String m_contentType;
private String m_charSet;
private String m_encoding;
private boolean m_startTlsEnabled;
private boolean m_quitWait;
private int m_smtpPort;
private boolean m_smtpSsl;
/*
* Basic messaging fields
*/
private String m_to;
private String m_subject;
private String m_messageText;
private String m_fileName;
private InputStream m_inputStream;
private String m_inputStreamName;
private String m_inputStreamContentType;
public JavaMailer(Properties javamailProps) throws JavaMailerException {
try {
configureProperties(javamailProps);
} catch (IOException e) {
throw new JavaMailerException("Failed to construct mailer", e);
}
//Now set the properties into the session
m_session = Session.getInstance(getMailProps(), createAuthenticator());
}
/**
* Default constructor. Default properties from javamailer-properties are set into session. To change these
* properties, retrieve the current properties from the session and override as needed.
* @throws IOException
*/
public JavaMailer() throws JavaMailerException {
this(new Properties());
}
/**
* This method uses a properties file reader to pull in opennms styled javamail properties and sets
* the actual javamail properties. This is here to preserve the backwards compatibility but configuration
* will probably change soon.
*
* @throws IOException
*/
private void configureProperties(Properties javamailProps) throws IOException {
//this loads the opennms defined properties
m_mailProps = JavaMailerConfig.getProperties();
//this sets any javamail defined properties sent in to the constructor
m_mailProps.putAll(javamailProps);
/*
* fields from properties used for deterministic behavior of the mailer
*/
m_debug = PropertiesUtils.getProperty(m_mailProps, "org.opennms.core.utils.debug", DEFAULT_MAILER_DEBUG);
m_mailHost = PropertiesUtils.getProperty(m_mailProps, "org.opennms.core.utils.mailHost", DEFAULT_MAIL_HOST);
m_useJMTA = PropertiesUtils.getProperty(m_mailProps, "org.opennms.core.utils.useJMTA", DEFAULT_USE_JMTA);
m_mailer = PropertiesUtils.getProperty(m_mailProps, "org.opennms.core.utils.mailer", DEFAULT_MAILER);
m_transport = PropertiesUtils.getProperty(m_mailProps, "org.opennms.core.utils.transport", DEFAULT_TRANSPORT);
m_from = PropertiesUtils.getProperty(m_mailProps, "org.opennms.core.utils.fromAddress", DEFAULT_FROM_ADDRESS);
m_authenticate = PropertiesUtils.getProperty(m_mailProps, "org.opennms.core.utils.authenticate", DEFAULT_AUTHENTICATE);
m_user = PropertiesUtils.getProperty(m_mailProps, "org.opennms.core.utils.authenticateUser", DEFAULT_AUTHENTICATE_USER);
m_password = PropertiesUtils.getProperty(m_mailProps, "org.opennms.core.utils.authenticatePassword", DEFAULT_AUTHENTICATE_PASSWORD);
m_contentType = PropertiesUtils.getProperty(m_mailProps, "org.opennms.core.utils.messageContentType", DEFAULT_CONTENT_TYPE);
m_charSet = PropertiesUtils.getProperty(m_mailProps, "org.opennms.core.utils.charset", DEFAULT_CHARSET);
m_encoding = PropertiesUtils.getProperty(m_mailProps, "org.opennms.core.utils.encoding", DEFAULT_ENCODING);
m_startTlsEnabled = PropertiesUtils.getProperty(m_mailProps, "org.opennms.core.utils.starttls.enable", DEFAULT_STARTTLS_ENABLE);
m_quitWait = PropertiesUtils.getProperty(m_mailProps, "org.opennms.core.utils.quitwait", DEFAULT_QUIT_WAIT);
m_smtpPort = PropertiesUtils.getProperty(m_mailProps, "org.opennms.core.utils.smtpport", DEFAULT_SMTP_PORT);
m_smtpSsl = PropertiesUtils.getProperty(m_mailProps, "org.opennms.core.utils.smtpssl.enable", DEFAULT_SMTP_SSL_ENABLE);
//Set the actual JavaMailProperties... any that are defined in the file will not be overridden
//Eventually, all configuration will be defined in properties and this strange parsing will not happen
//TODO: fix this craziness!
if (!m_mailProps.containsKey("mail.smtp.auth")) {
m_mailProps.setProperty("mail.smtp.auth", String.valueOf(isAuthenticate()));
}
if (!m_mailProps.containsKey("mail.smtp.starttls.enable")) {
m_mailProps.setProperty("mail.smtp.starttls.enable", String.valueOf(isStartTlsEnabled()));
}
if (!m_mailProps.containsKey("mail.smtp.quitwait")) {
m_mailProps.setProperty("mail.smtp.quitwait", String.valueOf(isQuitWait()));
}
if (!m_mailProps.containsKey("mail.smtp.port")) {
m_mailProps.setProperty("mail.smtp.port", String.valueOf(getSmtpPort()));
}
if (isSmtpSsl()) {
if (!m_mailProps.containsKey("mail.smtps.auth")) {
m_mailProps.setProperty("mail.smtps.auth", String.valueOf(isAuthenticate()));
}
if (!m_mailProps.containsKey("mail.smtps.socketFactory.class")) {
m_mailProps.setProperty("mail.smtps.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
}
if (!m_mailProps.containsKey("mail.smtps.socketFactory.port")) {
m_mailProps.setProperty("mail.smtps.socketFactory.port", String.valueOf(getSmtpPort()));
}
// if (!getMailProps().containsKey("mail.smtp.socketFactory.fallback")) {
// getMailProps().setProperty("mail.smtp.socketFactory.fallback", "false");
// }
}
if (!m_mailProps.containsKey("mail.smtp.quitwait")) {
m_mailProps.setProperty("mail.smtp.quitwait", "true");
}
//getMailProps().setProperty("mail.store.protocol", "pop3");
}
/**
* Sends a message based on properties set on this bean.
*/
public void mailSend() throws JavaMailerException {
log().debug(createSendLogMsg());
sendMessage(buildMessage());
}
/**
* Helper method to create an Authenticator based on Password Authentication
* @return
*/
public Authenticator createAuthenticator() {
Authenticator auth;
if (isAuthenticate()) {
auth = new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(getUser(), getPassword());
}
};
} else {
auth = null;
}
return auth;
}
/**
* Build a complete message ready for sending.
*
* @param session session to use to create a new MimeMessage
* @return completed message, ready to be passed to Transport.sendMessage
* @throws JavaMailerException if any of the underlying operations fail
*/
public Message buildMessage() throws JavaMailerException {
try {
checkEnvelopeAndContents();
Message message = initializeMessage();
String encodedText = MimeUtility.encodeText(getMessageText(), m_charSet, m_encoding);
if ((getFileName() == null) && (getInputStream() == null)) {
message.setContent(encodedText, m_contentType+"; charset="+m_charSet);
} else if (getFileName() == null) {
BodyPart streamBodyPart = new MimeBodyPart();
streamBodyPart.setDataHandler(new DataHandler(new InputStreamDataSource(m_inputStreamName, m_inputStreamContentType, m_inputStream)));
streamBodyPart.setFileName(m_inputStreamName);
streamBodyPart.setHeader("Content-Transfer-Encoding", "base64");
streamBodyPart.setDisposition(Part.ATTACHMENT);
MimeMultipart mp = new MimeMultipart();
mp.addBodyPart(streamBodyPart);
message.setContent(mp);
} else {
BodyPart bp = new MimeBodyPart();
bp.setContent(encodedText, m_contentType+"; charset="+m_charSet);
MimeMultipart mp = new MimeMultipart();
mp.addBodyPart(bp);
mp = new MimeMultipart();
mp.addBodyPart(createFileAttachment(new File(getFileName())));
message.setContent(mp);
}
message.setHeader("X-Mailer", getMailer());
message.setSentDate(new Date());
message.saveChanges();
return message;
} catch (AddressException e) {
log().error("Java Mailer Addressing exception: ", e);
throw new JavaMailerException("Java Mailer Addressing exception: ", e);
} catch (MessagingException e) {
log().error("Java Mailer messaging exception: ", e);
throw new JavaMailerException("Java Mailer messaging exception: ", e);
} catch (UnsupportedEncodingException e) {
log().error("Java Mailer messaging exception: ", e);
throw new JavaMailerException("Java Mailer encoding exception: ", e);
}
}
/**
* Helper method to that creates a MIME message.
* @param session
* @return
* @throws MessagingException
* @throws AddressException
*/
private Message initializeMessage() throws MessagingException, AddressException {
Message message;
message = new MimeMessage(getSession());
message.setFrom(new InternetAddress(getFrom()));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(getTo(), false));
message.setSubject(getSubject());
return message;
}
/**
* @return
*/
private String createSendLogMsg() {
StringBuffer sb = new StringBuffer();
sb.append("\n\tTo: ");
sb.append(getTo());
sb.append("\n\tFrom: ");
sb.append(getFrom());
sb.append("\n\tSubject is: ");
sb.append(getSubject());
sb.append("\n\tFile: ");
sb.append(getFileName()!=null ? getFileName() : "no file attached");
sb.append("\n\n");
sb.append(getMessageText());
sb.append("\n");
return sb.toString();
}
/**
* Create a file attachment as a MimeBodyPart, checking to see if the file
* exists before we create the attachment.
*
* @param file file to attach
* @return attachment body part
* @throws MessagingException if we can't set the data handler or
* the file name on the MimeBodyPart
* @throws JavaMailerException if the file does not exist or is not
* readable
*/
public MimeBodyPart createFileAttachment(final File file) throws MessagingException, JavaMailerException {
if (!file.exists()) {
log().error("File attachment '" + file.getAbsolutePath() + "' does not exist.");
throw new JavaMailerException("File attachment '" + file.getAbsolutePath() + "' does not exist.");
}
if (!file.canRead()) {
log().error("File attachment '" + file.getAbsolutePath() + "' is not readable.");
throw new JavaMailerException("File attachment '" + file.getAbsolutePath() + "' is not readable.");
}
MimeBodyPart bodyPart = new MimeBodyPart();
FileDataSource fds = new FileDataSource(file);
bodyPart.setDataHandler(new DataHandler(fds));
bodyPart.setFileName(fds.getName());
return bodyPart;
}
/**
* Check that required envelope and message contents properties have been
* set.
*
* @throws JavaMailerException if any of the required properties have not
* been set
*/
private void checkEnvelopeAndContents() throws JavaMailerException {
if (getFrom() == null) {
throw new JavaMailerException("Cannot have a null from address.");
}
if ("".equals(getFrom())) {
throw new JavaMailerException("Cannot have an empty from address.");
}
if (getTo() == null) {
throw new JavaMailerException("Cannot have a null to address.");
}
if ("".equals(getTo())) {
throw new JavaMailerException("Cannot have an empty to address.");
}
if (getSubject() == null) {
throw new JavaMailerException("Cannot have a null subject.");
}
if ("".equals(getSubject())) {
throw new JavaMailerException("Cannot have an empty subject.");
}
if (getMessageText() == null) {
throw new JavaMailerException("Cannot have a null messageText.");
}
if ("".equals(getMessageText())) {
throw new JavaMailerException("Cannot have an empty messageText.");
}
}
/**
* Send message.
*
* @param session
* @param message
* @throws JavaMailerException
*/
public void sendMessage(Message message) throws JavaMailerException {
Transport t = null;
try {
t = getSession().getTransport(getTransport());
log().debug("for transport name '" + getTransport() + "' got: " + t.getClass().getName() + "@" + Integer.toHexString(t.hashCode()));
LoggingTransportListener listener = new LoggingTransportListener(log());
t.addTransportListener(listener);
if (t.getURLName().getProtocol().equals("mta")) {
// JMTA throws an AuthenticationFailedException if we call connect()
log().debug("transport is 'mta', not trying to connect()");
} else if (isAuthenticate()) {
log().debug("authenticating to " + getMailHost());
t.connect(getMailHost(), getSmtpPort(), getUser(), getPassword());
} else {
log().debug("not authenticating to " + getMailHost());
t.connect(getMailHost(), getSmtpPort(), null, null);
}
t.sendMessage(message, message.getAllRecipients());
listener.assertAllMessagesDelivered();
} catch (NoSuchProviderException e) {
log().error("Couldn't get a transport: " + e, e);
throw new JavaMailerException("Couldn't get a transport: " + e, e);
} catch (MessagingException e) {
log().error("Java Mailer messaging exception: " + e, e);
throw new JavaMailerException("Java Mailer messaging exception: " + e, e);
} finally {
try {
if (t != null && t.isConnected()) {
t.close();
}
} catch (MessagingException e) {
throw new JavaMailerException("Java Mailer messaging exception on transport close: " + e, e);
}
}
}
private class InputStreamDataSource implements DataSource {
private String name;
private String contentType;
private ByteArrayOutputStream baos;
InputStreamDataSource(String name, String contentType, InputStream inputStream) throws JavaMailerException {
this.name = name;
this.contentType = contentType;
log().debug("setting contentType " + this.contentType);
baos = new ByteArrayOutputStream();
int read;
byte[] buff = new byte[256];
try {
while((read = inputStream.read(buff)) != -1) {
baos.write(buff, 0, read);
}
} catch (IOException e) {
log().error("Could not read attachment from input stream: " + e, e);
throw new JavaMailerException("Could not read attachment from input stream: " + e, e);
}
}
public String getContentType() {
log().debug("getContentType: " + contentType);
return contentType;
}
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(baos.toByteArray());
}
public String getName() {
return name;
}
public OutputStream getOutputStream() throws IOException {
throw new IOException("Cannot write to this read-only resource");
}
}
/**
* @return Returns the password.
*/
public String getPassword() {
return m_password;
}
/**
* @param password
* The password to set.
*/
public void setPassword(String password) {
m_password = password;
}
/**
* @return Returns the user.
*/
public String getUser() {
return m_user;
}
/**
* @param user
* The user to set.
*/
public void setUser(String user) {
m_user = user;
}
/**
* @return Returns the _useMailHost.
*/
public boolean isUseJMTA() {
return m_useJMTA;
}
/**
* @param mailHost The _useMailHost to set.
*/
public void setUseJMTA(boolean useMTA) {
m_useJMTA = useMTA;
}
/**
* @return Returns the from address.
*/
public String getFrom() {
return m_from;
}
/**
* @param from
* The from address to set.
*/
public void setFrom(String from) {
m_from = from;
}
/**
* @return Returns the authenticate boolean.
*/
public boolean isAuthenticate() {
return m_authenticate;
}
/**
* @param authenticate
* The authenticate boolean to set.
*/
public void setAuthenticate(boolean authenticate) {
m_authenticate = authenticate;
}
/**
* @return Returns the file name attachment.
*/
public String getFileName() {
return m_fileName;
}
/**
* @param file
* Sets the file name to be attached to the messaget.
*/
public void setFileName(String fileName) {
m_fileName = fileName;
}
/**
* @return Returns the input stream attachment.
*/
public InputStream getInputStream() {
return m_inputStream;
}
/**
* @param inputStream
* Sets the input stream to be attached to the message.
*/
public void setInputStream(InputStream inputStream) {
m_inputStream = inputStream;
}
/**
* @return Returns the name to use for stream attachments..
*/
public String getInputStreamName() {
return m_inputStreamName;
}
/**
* @param inputStreamName
* Sets the name to use for stream attachments.
*/
public void setInputStreamName(String inputStreamName) {
m_inputStreamName = inputStreamName;
}
/**
* @return Returns the name to use for stream attachments..
*/
public String getInputStreamContentType() {
return m_inputStreamContentType;
}
/**
* @param inputStreamName
* Sets the name to use for stream attachments.
*/
public void setInputStreamContentType(String inputStreamContentType) {
m_inputStreamContentType = inputStreamContentType;
}
/**
* @return Returns the mail host.
*/
public String getMailHost() {
return m_mailHost;
}
/**
* @param mail_host
* Sets the mail host.
*/
public void setMailHost(String mail_host) {
m_mailHost = mail_host;
}
/**
* @return Returns the mailer.
*/
public String getMailer() {
return m_mailer;
}
/**
* @param mailer
* Sets the mailer.
*/
public void setMailer(String mailer) {
m_mailer = mailer;
}
/**
* @return Returns the message text.
*/
public String getMessageText() {
return m_messageText;
}
/**
* @param messageText
* Sets the message text.
*/
public void setMessageText(String messageText) {
m_messageText = messageText;
}
/**
* @return Returns the message Subject.
*/
public String getSubject() {
return m_subject;
}
/**
* @param subject
* Sets the message Subject.
*/
public void setSubject(String subject) {
m_subject = subject;
}
/**
* @return Returns the To address.
*/
public String getTo() {
return m_to;
}
/**
* @param to
* Sets the To address.
*/
public void setTo(String to) {
m_to = to;
}
public String getTransport() {
if (isUseJMTA()) {
return "mta";
} else {
return m_transport;
}
}
public void setTransport(String transport) {
m_transport = transport;
}
public boolean isDebug() {
return m_debug;
}
public void setDebug(boolean debug) {
m_debug = debug;
if (isDebug()) {
m_session.setDebugOut(new PrintStream(new LoggingByteArrayOutputStream(log()), true));
}
m_session.setDebug(isDebug());
}
/**
* @return log4j Category
*/
private ThreadCategory log() {
return ThreadCategory.getInstance(getClass());
}
public static class LoggingByteArrayOutputStream extends ByteArrayOutputStream {
private ThreadCategory m_category;
public LoggingByteArrayOutputStream(ThreadCategory threadCategory) {
m_category = threadCategory;
}
@Override
public void flush() throws IOException {
super.flush();
String buffer = toString().replaceAll("\n", "");
if (buffer.length() > 0) {
m_category.debug(buffer);
}
reset();
}
}
public static class LoggingTransportListener implements TransportListener {
private ThreadCategory m_category;
private List<Address> m_invalidAddresses = new ArrayList<Address>();
private List<Address> m_validSentAddresses = new ArrayList<Address>();
private List<Address> m_validUnsentAddresses = new ArrayList<Address>();
public LoggingTransportListener(ThreadCategory threadCategory) {
m_category = threadCategory;
}
public void messageDelivered(TransportEvent event) {
logEvent("message delivered", event);
}
public void messageNotDelivered(TransportEvent event) {
logEvent("message not delivered", event);
}
public void messagePartiallyDelivered(TransportEvent event) {
logEvent("message partially delivered", event);
}
private void logEvent(String message, TransportEvent event) {
if (event.getInvalidAddresses() != null && event.getInvalidAddresses().length > 0) {
m_invalidAddresses.addAll(Arrays.asList(event.getInvalidAddresses()));
m_category.error(message + ": invalid addresses: " + StringUtils.arrayToDelimitedString(event.getInvalidAddresses(), ", "));
}
if (event.getValidSentAddresses() != null && event.getValidSentAddresses().length > 0) {
m_validSentAddresses.addAll(Arrays.asList(event.getValidSentAddresses()));
m_category.debug(message + ": valid sent addresses: " + StringUtils.arrayToDelimitedString(event.getValidSentAddresses(), ", "));
}
if (event.getValidUnsentAddresses() != null && event.getValidUnsentAddresses().length > 0) {
m_validUnsentAddresses.addAll(Arrays.asList(event.getValidUnsentAddresses()));
m_category.error(message + ": valid unsent addresses: " + StringUtils.arrayToDelimitedString(event.getValidUnsentAddresses(), ", "));
}
}
public boolean hasAnythingBeenReceived() {
return m_invalidAddresses.size() != 0 || m_validSentAddresses.size() != 0 || m_validUnsentAddresses.size() != 0;
}
/**
* We sleep up to ten times for 10ms, checking to see if anything has
* been received because the notifications are done by a separate
* thread. We also wait another 50ms after we see the first
* notification come in, just to see if anything else trickles in.
* This isn't perfect, but it's somewhat of a shot in the dark to
* hope that we catch most things, to try to catch as many errors
* as possible so we can fairly reliably report if anything had
* problems.
*
* @throws JavaMailerException
*/
public void assertAllMessagesDelivered() throws JavaMailerException {
for (int i = 0; i < 10; i++) {
if (hasAnythingBeenReceived()) {
break;
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// Do nothing
}
}
try {
Thread.sleep(50);
} catch (InterruptedException e) {
// Do nothing
}
if (m_invalidAddresses.size() == 0 && m_validUnsentAddresses.size() == 0) {
// Nothing failed, so just return
return;
}
throw new JavaMailerException("Not all messages delivered:\n"
+ "\t" + m_validSentAddresses.size() + " messages were sent to valid addresses: " + StringUtils.collectionToDelimitedString(m_validSentAddresses, ", ") + "\n"
+ "\t" + m_validUnsentAddresses.size() + " messages were not sent to valid addresses: " + StringUtils.collectionToDelimitedString(m_validUnsentAddresses, ", ") + "\n"
+ "\t" + m_invalidAddresses.size() + " messages had invalid addresses: " + StringUtils.collectionToDelimitedString(m_invalidAddresses, ", "));
}
}
/**
* @return the session
*/
public Session getSession() {
return m_session;
}
/**
* @param session the session to set
*/
public void setSession(Session session) {
m_session = session;
}
/**
* @return the contentType
*/
public String getContentType() {
return m_contentType;
}
/**
* @param contentType the contentType to set
*/
public void setContentType(String contentType) {
m_contentType = contentType;
}
/**
* @return the charSet
*/
public String getCharSet() {
return m_charSet;
}
/**
* @param charSet the charSet to set
*/
public void setCharSet(String charSet) {
m_charSet = charSet;
}
/**
* @return the encoding
*/
public String getEncoding() {
return m_encoding;
}
/**
* @param encoding the encoding to set
*/
public void setEncoding(String encoding) {
m_encoding = encoding;
}
/**
* @return the startTlsEnabled
*/
public boolean isStartTlsEnabled() {
return m_startTlsEnabled;
}
/**
* @param startTlsEnabled the startTlsEnabled to set
*/
public void setStartTlsEnabled(boolean startTlsEnabled) {
m_startTlsEnabled = startTlsEnabled;
}
/**
* @return the quitWait
*/
public boolean isQuitWait() {
return m_quitWait;
}
/**
* @param quitWait the quitWait to set
*/
public void setQuitWait(boolean quitWait) {
m_quitWait = quitWait;
}
/**
* @return the smtpPort
*/
public int getSmtpPort() {
return m_smtpPort;
}
/**
* @param smtpPort the smtpPort to set
*/
public void setSmtpPort(int smtpPort) {
m_smtpPort = smtpPort;
}
/**
* @return the smtpSsl
*/
public boolean isSmtpSsl() {
return m_smtpSsl;
}
/**
* @param smtpSsl the smtpSsl to set
*/
public void setSmtpSsl(boolean smtpSsl) {
m_smtpSsl = smtpSsl;
}
/**
* This returns the properties configured in the javamail-configuration.properties file.
* @return
*/
public Properties getMailProps() {
return m_mailProps;
}
}
| fix for bug #3795
javamail spits out an insane amount of debug info, default to debug=false.
| opennms-javamail/opennms-javamail-api/src/main/java/org/opennms/javamail/JavaMailer.java | fix for bug #3795 | <ide><path>pennms-javamail/opennms-javamail-api/src/main/java/org/opennms/javamail/JavaMailer.java
<ide> private static final String DEFAULT_AUTHENTICATE_PASSWORD = "opennms";
<ide> private static final String DEFAULT_MAILER = "smtpsend";
<ide> private static final String DEFAULT_TRANSPORT = "smtp";
<del> private static final boolean DEFAULT_MAILER_DEBUG = true;
<add> private static final boolean DEFAULT_MAILER_DEBUG = false;
<ide> private static final boolean DEFAULT_USE_JMTA = true;
<ide> private static final String DEFAULT_CONTENT_TYPE = "text/plain";
<ide> private static final String DEFAULT_CHARSET = "us-ascii"; |
|
Java | apache-2.0 | ef88bb17d0cbd5e0cb7b38d618e08230e3ce2179 | 0 | Flowdalic/Smack,igniterealtime/Smack,Flowdalic/Smack,igniterealtime/Smack,igniterealtime/Smack,vanitasvitae/Smack,vanitasvitae/Smack,Flowdalic/Smack,vanitasvitae/Smack | /**
*
* Copyright 2003-2007 Jive Software.
*
* 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.jivesoftware.smackx.disco.packet;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.util.EqualsUtil;
import org.jivesoftware.smack.util.HashCode;
import org.jivesoftware.smack.util.StringUtils;
import org.jivesoftware.smack.util.TypedCloneable;
import org.jivesoftware.smack.util.XmlStringBuilder;
import org.jxmpp.util.XmppStringUtils;
/**
* A DiscoverInfo IQ packet, which is used by XMPP clients to request and receive information
* to/from other XMPP entities.<p>
*
* The received information may contain one or more identities of the requested XMPP entity, and
* a list of supported features by the requested XMPP entity.
*
* @author Gaston Dombiak
*/
public class DiscoverInfo extends IQ implements TypedCloneable<DiscoverInfo> {
public static final String ELEMENT = QUERY_ELEMENT;
public static final String NAMESPACE = "http://jabber.org/protocol/disco#info";
private final List<Feature> features = new LinkedList<>();
private final Set<Feature> featuresSet = new HashSet<>();
private final List<Identity> identities = new LinkedList<>();
private final Set<String> identitiesSet = new HashSet<>();
private String node;
private boolean containsDuplicateFeatures;
public DiscoverInfo() {
super(ELEMENT, NAMESPACE);
}
/**
* Copy constructor.
*
* @param d
*/
public DiscoverInfo(DiscoverInfo d) {
super(d);
// Set node
setNode(d.getNode());
// Copy features
for (Feature f : d.features) {
addFeature(f.clone());
}
// Copy identities
for (Identity i : d.identities) {
addIdentity(i.clone());
}
}
/**
* Adds a new feature to the discovered information.
*
* @param feature the discovered feature
* @return true if the feature did not already exist.
*/
public boolean addFeature(String feature) {
return addFeature(new Feature(feature));
}
/**
* Adds a collection of features to the packet. Does noting if featuresToAdd is null.
*
* @param featuresToAdd
*/
public void addFeatures(Collection<String> featuresToAdd) {
if (featuresToAdd == null) return;
for (String feature : featuresToAdd) {
addFeature(feature);
}
}
public boolean addFeature(Feature feature) {
features.add(feature);
boolean featureIsNew = featuresSet.add(feature);
if (!featureIsNew) {
containsDuplicateFeatures = true;
}
return featureIsNew;
}
/**
* Returns the discovered features of an XMPP entity.
*
* @return an unmodifiable list of the discovered features of an XMPP entity
*/
public List<Feature> getFeatures() {
return Collections.unmodifiableList(features);
}
/**
* Adds a new identity of the requested entity to the discovered information.
*
* @param identity the discovered entity's identity
*/
public void addIdentity(Identity identity) {
identities.add(identity);
identitiesSet.add(identity.getKey());
}
/**
* Adds identities to the DiscoverInfo stanza.
*
* @param identitiesToAdd
*/
public void addIdentities(Collection<Identity> identitiesToAdd) {
if (identitiesToAdd == null) return;
for (Identity identity : identitiesToAdd) {
addIdentity(identity);
}
}
/**
* Returns the discovered identities of an XMPP entity.
*
* @return an unmodifiable list of the discovered identities
*/
public List<Identity> getIdentities() {
return Collections.unmodifiableList(identities);
}
/**
* Returns true if this DiscoverInfo contains at least one Identity of the given category and type.
*
* @param category the category to look for.
* @param type the type to look for.
* @return true if this DiscoverInfo contains a Identity of the given category and type.
*/
public boolean hasIdentity(String category, String type) {
String key = XmppStringUtils.generateKey(category, type);
return identitiesSet.contains(key);
}
/**
* Returns all Identities of the given category and type of this DiscoverInfo.
*
* @param category category the category to look for.
* @param type type the type to look for.
* @return a list of Identites with the given category and type.
*/
public List<Identity> getIdentities(String category, String type) {
List<Identity> res = new ArrayList<>(identities.size());
for (Identity identity : identities) {
if (identity.getCategory().equals(category) && identity.getType().equals(type)) {
res.add(identity);
}
}
return res;
}
/**
* Returns the node attribute that supplements the 'jid' attribute. A node is merely
* something that is associated with a JID and for which the JID can provide information.<p>
*
* Node attributes SHOULD be used only when trying to provide or query information which
* is not directly addressable.
*
* @return the node attribute that supplements the 'jid' attribute
*/
public String getNode() {
return node;
}
/**
* Sets the node attribute that supplements the 'jid' attribute. A node is merely
* something that is associated with a JID and for which the JID can provide information.<p>
*
* Node attributes SHOULD be used only when trying to provide or query information which
* is not directly addressable.
*
* @param node the node attribute that supplements the 'jid' attribute
*/
public void setNode(String node) {
this.node = StringUtils.requireNullOrNotEmpty(node, "The node can not be the empty string");
}
/**
* Returns true if the specified feature is part of the discovered information.
*
* @param feature the feature to check
* @return true if the requests feature has been discovered
*/
public boolean containsFeature(CharSequence feature) {
return features.contains(new Feature(feature));
}
@Override
protected IQChildElementXmlStringBuilder getIQChildElementBuilder(IQChildElementXmlStringBuilder xml) {
xml.optAttribute("node", getNode());
xml.rightAngleBracket();
for (Identity identity : identities) {
xml.append(identity.toXML());
}
for (Feature feature : features) {
xml.append(feature.toXML());
}
return xml;
}
/**
* Test if a DiscoverInfo response contains duplicate identities.
*
* @return true if duplicate identities where found, otherwise false
*/
public boolean containsDuplicateIdentities() {
List<Identity> checkedIdentities = new LinkedList<>();
for (Identity i : identities) {
for (Identity i2 : checkedIdentities) {
if (i.equals(i2))
return true;
}
checkedIdentities.add(i);
}
return false;
}
/**
* Test if a DiscoverInfo response contains duplicate features.
*
* @return true if duplicate identities where found, otherwise false
*/
public boolean containsDuplicateFeatures() {
return containsDuplicateFeatures;
}
@Override
public DiscoverInfo clone() {
return new DiscoverInfo(this);
}
/**
* Represents the identity of a given XMPP entity. An entity may have many identities but all
* the identities SHOULD have the same name.<p>
*
* Refer to <a href="https://xmpp.org/registrar/disco-categories.html">XMPP Registry for Service Discovery Identities</a>
* in order to get the official registry of values for the <i>category</i> and <i>type</i>
* attributes.
*
*/
public static final class Identity implements Comparable<Identity>, TypedCloneable<Identity> {
private final String category;
private final String type;
private final String key;
private final String name;
private final String lang; // 'xml:lang;
public Identity(Identity identity) {
this.category = identity.category;
this.type = identity.type;
this.key = identity.type;
this.name = identity.name;
this.lang = identity.lang;
}
/**
* Creates a new identity for an XMPP entity.
*
* @param category the entity's category (required as per XEP-30).
* @param type the entity's type (required as per XEP-30).
*/
public Identity(String category, String type) {
this(category, type, null, null);
}
/**
* Creates a new identity for an XMPP entity.
* 'category' and 'type' are required by
* <a href="http://xmpp.org/extensions/xep-0030.html#schemas">XEP-30 XML Schemas</a>
*
* @param category the entity's category (required as per XEP-30).
* @param name the entity's name.
* @param type the entity's type (required as per XEP-30).
*/
public Identity(String category, String name, String type) {
this(category, type, name, null);
}
/**
* Creates a new identity for an XMPP entity.
* 'category' and 'type' are required by
* <a href="http://xmpp.org/extensions/xep-0030.html#schemas">XEP-30 XML Schemas</a>
*
* @param category the entity's category (required as per XEP-30).
* @param type the entity's type (required as per XEP-30).
* @param name the entity's name.
* @param lang the entity's lang.
*/
public Identity(String category, String type, String name, String lang) {
this.category = StringUtils.requireNotNullNorEmpty(category, "category cannot be null");
this.type = StringUtils.requireNotNullNorEmpty(type, "type cannot be null");
this.key = XmppStringUtils.generateKey(category, type);
this.name = name;
this.lang = lang;
}
/**
* Returns the entity's category. To get the official registry of values for the
* 'category' attribute refer to <a href="https://xmpp.org/registrar/disco-categories.html">XMPP Registry for Service Discovery Identities</a>.
*
* @return the entity's category.
*/
public String getCategory() {
return category;
}
/**
* Returns the identity's name.
*
* @return the identity's name.
*/
public String getName() {
return name;
}
/**
* Returns the entity's type. To get the official registry of values for the
* 'type' attribute refer to <a href="https://xmpp.org/registrar/disco-categories.html">XMPP Registry for Service Discovery Identities</a>.
*
* @return the entity's type.
*/
public String getType() {
return type;
}
/**
* Returns the identities natural language if one is set.
*
* @return the value of xml:lang of this Identity
*/
public String getLanguage() {
return lang;
}
private String getKey() {
return key;
}
/**
* Returns true if this identity is of the given category and type.
*
* @param category the category.
* @param type the type.
* @return true if this identity is of the given category and type.
*/
public boolean isOfCategoryAndType(String category, String type) {
return this.category.equals(category) && this.type.equals(type);
}
public XmlStringBuilder toXML() {
XmlStringBuilder xml = new XmlStringBuilder();
xml.halfOpenElement("identity");
xml.xmllangAttribute(lang);
xml.attribute("category", category);
xml.optAttribute("name", name);
xml.optAttribute("type", type);
xml.closeEmptyElement();
return xml;
}
/**
* Check equality for Identity for category, type, lang and name
* in that order as defined by
* <a href="http://xmpp.org/extensions/xep-0115.html#ver-proc">XEP-0015 5.4 Processing Method (Step 3.3)</a>.
*
*/
@Override
public boolean equals(Object obj) {
return EqualsUtil.equals(this, obj, (e, o) -> {
e.append(key, o.key)
.append(lang, o.lang)
.append(name, o.name);
});
}
private final HashCode.Cache hashCodeCache = new HashCode.Cache();
@Override
public int hashCode() {
return hashCodeCache.getHashCode(c ->
c.append(key)
.append(lang)
.append(name)
);
}
/**
* Compares this identity with another one. The comparison order is: Category, Type, Lang.
* If all three are identical the other Identity is considered equal. Name is not used for
* comparison, as defined by XEP-0115
*
* @param other
* @return a negative integer, zero, or a positive integer as this object is less than,
* equal to, or greater than the specified object.
*/
@Override
public int compareTo(DiscoverInfo.Identity other) {
String otherLang = other.lang == null ? "" : other.lang;
String thisLang = lang == null ? "" : lang;
// This can be removed once the deprecated constructor is removed.
String otherType = other.type == null ? "" : other.type;
String thisType = type == null ? "" : type;
if (category.equals(other.category)) {
if (thisType.equals(otherType)) {
if (thisLang.equals(otherLang)) {
// Don't compare on name, XEP-30 says that name SHOULD
// be equals for all identities of an entity
return 0;
} else {
return thisLang.compareTo(otherLang);
}
} else {
return thisType.compareTo(otherType);
}
} else {
return category.compareTo(other.category);
}
}
@Override
public Identity clone() {
return new Identity(this);
}
@Override
public String toString() {
return toXML().toString();
}
}
/**
* Represents the features offered by the item. This information helps the requester to determine
* what actions are possible with regard to this item (registration, search, join, etc.)
* as well as specific feature types of interest, if any (e.g., for the purpose of feature
* negotiation).
*/
public static final class Feature implements TypedCloneable<Feature> {
private final String variable;
public Feature(Feature feature) {
this.variable = feature.variable;
}
public Feature(CharSequence variable) {
this(variable.toString());
}
/**
* Creates a new feature offered by an XMPP entity or item.
*
* @param variable the feature's variable.
*/
public Feature(String variable) {
this.variable = StringUtils.requireNotNullNorEmpty(variable, "variable cannot be null");
}
/**
* Returns the feature's variable.
*
* @return the feature's variable.
*/
public String getVar() {
return variable;
}
public XmlStringBuilder toXML() {
XmlStringBuilder xml = new XmlStringBuilder();
xml.halfOpenElement("feature");
xml.attribute("var", variable);
xml.closeEmptyElement();
return xml;
}
@Override
public boolean equals(Object obj) {
return EqualsUtil.equals(this, obj, (e, o) -> {
e.append(variable, o.variable);
});
}
@Override
public int hashCode() {
return variable.hashCode();
}
@Override
public Feature clone() {
return new Feature(this);
}
@Override
public String toString() {
return toXML().toString();
}
}
}
| smack-extensions/src/main/java/org/jivesoftware/smackx/disco/packet/DiscoverInfo.java | /**
*
* Copyright 2003-2007 Jive Software.
*
* 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.jivesoftware.smackx.disco.packet;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.util.EqualsUtil;
import org.jivesoftware.smack.util.HashCode;
import org.jivesoftware.smack.util.StringUtils;
import org.jivesoftware.smack.util.TypedCloneable;
import org.jivesoftware.smack.util.XmlStringBuilder;
import org.jxmpp.util.XmppStringUtils;
/**
* A DiscoverInfo IQ packet, which is used by XMPP clients to request and receive information
* to/from other XMPP entities.<p>
*
* The received information may contain one or more identities of the requested XMPP entity, and
* a list of supported features by the requested XMPP entity.
*
* @author Gaston Dombiak
*/
public class DiscoverInfo extends IQ implements TypedCloneable<DiscoverInfo> {
public static final String ELEMENT = QUERY_ELEMENT;
public static final String NAMESPACE = "http://jabber.org/protocol/disco#info";
private final List<Feature> features = new LinkedList<>();
private final Set<Feature> featuresSet = new HashSet<>();
private final List<Identity> identities = new LinkedList<>();
private final Set<String> identitiesSet = new HashSet<>();
private String node;
private boolean containsDuplicateFeatures;
public DiscoverInfo() {
super(ELEMENT, NAMESPACE);
}
/**
* Copy constructor.
*
* @param d
*/
public DiscoverInfo(DiscoverInfo d) {
super(d);
// Set node
setNode(d.getNode());
// Copy features
for (Feature f : d.features) {
addFeature(f.clone());
}
// Copy identities
for (Identity i : d.identities) {
addIdentity(i.clone());
}
}
/**
* Adds a new feature to the discovered information.
*
* @param feature the discovered feature
* @return true if the feature did not already exist.
*/
public boolean addFeature(String feature) {
return addFeature(new Feature(feature));
}
/**
* Adds a collection of features to the packet. Does noting if featuresToAdd is null.
*
* @param featuresToAdd
*/
public void addFeatures(Collection<String> featuresToAdd) {
if (featuresToAdd == null) return;
for (String feature : featuresToAdd) {
addFeature(feature);
}
}
public boolean addFeature(Feature feature) {
features.add(feature);
boolean featureIsNew = featuresSet.add(feature);
if (!featureIsNew) {
containsDuplicateFeatures = true;
}
return featureIsNew;
}
/**
* Returns the discovered features of an XMPP entity.
*
* @return an unmodifiable list of the discovered features of an XMPP entity
*/
public List<Feature> getFeatures() {
return Collections.unmodifiableList(features);
}
/**
* Adds a new identity of the requested entity to the discovered information.
*
* @param identity the discovered entity's identity
*/
public void addIdentity(Identity identity) {
identities.add(identity);
identitiesSet.add(identity.getKey());
}
/**
* Adds identities to the DiscoverInfo stanza.
*
* @param identitiesToAdd
*/
public void addIdentities(Collection<Identity> identitiesToAdd) {
if (identitiesToAdd == null) return;
for (Identity identity : identitiesToAdd) {
addIdentity(identity);
}
}
/**
* Returns the discovered identities of an XMPP entity.
*
* @return an unmodifiable list of the discovered identities
*/
public List<Identity> getIdentities() {
return Collections.unmodifiableList(identities);
}
/**
* Returns true if this DiscoverInfo contains at least one Identity of the given category and type.
*
* @param category the category to look for.
* @param type the type to look for.
* @return true if this DiscoverInfo contains a Identity of the given category and type.
*/
public boolean hasIdentity(String category, String type) {
String key = XmppStringUtils.generateKey(category, type);
return identitiesSet.contains(key);
}
/**
* Returns all Identities of the given category and type of this DiscoverInfo.
*
* @param category category the category to look for.
* @param type type the type to look for.
* @return a list of Identites with the given category and type.
*/
public List<Identity> getIdentities(String category, String type) {
List<Identity> res = new ArrayList<>(identities.size());
for (Identity identity : identities) {
if (identity.getCategory().equals(category) && identity.getType().equals(type)) {
res.add(identity);
}
}
return res;
}
/**
* Returns the node attribute that supplements the 'jid' attribute. A node is merely
* something that is associated with a JID and for which the JID can provide information.<p>
*
* Node attributes SHOULD be used only when trying to provide or query information which
* is not directly addressable.
*
* @return the node attribute that supplements the 'jid' attribute
*/
public String getNode() {
return node;
}
/**
* Sets the node attribute that supplements the 'jid' attribute. A node is merely
* something that is associated with a JID and for which the JID can provide information.<p>
*
* Node attributes SHOULD be used only when trying to provide or query information which
* is not directly addressable.
*
* @param node the node attribute that supplements the 'jid' attribute
*/
public void setNode(String node) {
this.node = node;
}
/**
* Returns true if the specified feature is part of the discovered information.
*
* @param feature the feature to check
* @return true if the requests feature has been discovered
*/
public boolean containsFeature(CharSequence feature) {
return features.contains(new Feature(feature));
}
@Override
protected IQChildElementXmlStringBuilder getIQChildElementBuilder(IQChildElementXmlStringBuilder xml) {
xml.optAttribute("node", getNode());
xml.rightAngleBracket();
for (Identity identity : identities) {
xml.append(identity.toXML());
}
for (Feature feature : features) {
xml.append(feature.toXML());
}
return xml;
}
/**
* Test if a DiscoverInfo response contains duplicate identities.
*
* @return true if duplicate identities where found, otherwise false
*/
public boolean containsDuplicateIdentities() {
List<Identity> checkedIdentities = new LinkedList<>();
for (Identity i : identities) {
for (Identity i2 : checkedIdentities) {
if (i.equals(i2))
return true;
}
checkedIdentities.add(i);
}
return false;
}
/**
* Test if a DiscoverInfo response contains duplicate features.
*
* @return true if duplicate identities where found, otherwise false
*/
public boolean containsDuplicateFeatures() {
return containsDuplicateFeatures;
}
@Override
public DiscoverInfo clone() {
return new DiscoverInfo(this);
}
/**
* Represents the identity of a given XMPP entity. An entity may have many identities but all
* the identities SHOULD have the same name.<p>
*
* Refer to <a href="https://xmpp.org/registrar/disco-categories.html">XMPP Registry for Service Discovery Identities</a>
* in order to get the official registry of values for the <i>category</i> and <i>type</i>
* attributes.
*
*/
public static final class Identity implements Comparable<Identity>, TypedCloneable<Identity> {
private final String category;
private final String type;
private final String key;
private final String name;
private final String lang; // 'xml:lang;
public Identity(Identity identity) {
this.category = identity.category;
this.type = identity.type;
this.key = identity.type;
this.name = identity.name;
this.lang = identity.lang;
}
/**
* Creates a new identity for an XMPP entity.
*
* @param category the entity's category (required as per XEP-30).
* @param type the entity's type (required as per XEP-30).
*/
public Identity(String category, String type) {
this(category, type, null, null);
}
/**
* Creates a new identity for an XMPP entity.
* 'category' and 'type' are required by
* <a href="http://xmpp.org/extensions/xep-0030.html#schemas">XEP-30 XML Schemas</a>
*
* @param category the entity's category (required as per XEP-30).
* @param name the entity's name.
* @param type the entity's type (required as per XEP-30).
*/
public Identity(String category, String name, String type) {
this(category, type, name, null);
}
/**
* Creates a new identity for an XMPP entity.
* 'category' and 'type' are required by
* <a href="http://xmpp.org/extensions/xep-0030.html#schemas">XEP-30 XML Schemas</a>
*
* @param category the entity's category (required as per XEP-30).
* @param type the entity's type (required as per XEP-30).
* @param name the entity's name.
* @param lang the entity's lang.
*/
public Identity(String category, String type, String name, String lang) {
this.category = StringUtils.requireNotNullNorEmpty(category, "category cannot be null");
this.type = StringUtils.requireNotNullNorEmpty(type, "type cannot be null");
this.key = XmppStringUtils.generateKey(category, type);
this.name = name;
this.lang = lang;
}
/**
* Returns the entity's category. To get the official registry of values for the
* 'category' attribute refer to <a href="https://xmpp.org/registrar/disco-categories.html">XMPP Registry for Service Discovery Identities</a>.
*
* @return the entity's category.
*/
public String getCategory() {
return category;
}
/**
* Returns the identity's name.
*
* @return the identity's name.
*/
public String getName() {
return name;
}
/**
* Returns the entity's type. To get the official registry of values for the
* 'type' attribute refer to <a href="https://xmpp.org/registrar/disco-categories.html">XMPP Registry for Service Discovery Identities</a>.
*
* @return the entity's type.
*/
public String getType() {
return type;
}
/**
* Returns the identities natural language if one is set.
*
* @return the value of xml:lang of this Identity
*/
public String getLanguage() {
return lang;
}
private String getKey() {
return key;
}
/**
* Returns true if this identity is of the given category and type.
*
* @param category the category.
* @param type the type.
* @return true if this identity is of the given category and type.
*/
public boolean isOfCategoryAndType(String category, String type) {
return this.category.equals(category) && this.type.equals(type);
}
public XmlStringBuilder toXML() {
XmlStringBuilder xml = new XmlStringBuilder();
xml.halfOpenElement("identity");
xml.xmllangAttribute(lang);
xml.attribute("category", category);
xml.optAttribute("name", name);
xml.optAttribute("type", type);
xml.closeEmptyElement();
return xml;
}
/**
* Check equality for Identity for category, type, lang and name
* in that order as defined by
* <a href="http://xmpp.org/extensions/xep-0115.html#ver-proc">XEP-0015 5.4 Processing Method (Step 3.3)</a>.
*
*/
@Override
public boolean equals(Object obj) {
return EqualsUtil.equals(this, obj, (e, o) -> {
e.append(key, o.key)
.append(lang, o.lang)
.append(name, o.name);
});
}
private final HashCode.Cache hashCodeCache = new HashCode.Cache();
@Override
public int hashCode() {
return hashCodeCache.getHashCode(c ->
c.append(key)
.append(lang)
.append(name)
);
}
/**
* Compares this identity with another one. The comparison order is: Category, Type, Lang.
* If all three are identical the other Identity is considered equal. Name is not used for
* comparison, as defined by XEP-0115
*
* @param other
* @return a negative integer, zero, or a positive integer as this object is less than,
* equal to, or greater than the specified object.
*/
@Override
public int compareTo(DiscoverInfo.Identity other) {
String otherLang = other.lang == null ? "" : other.lang;
String thisLang = lang == null ? "" : lang;
// This can be removed once the deprecated constructor is removed.
String otherType = other.type == null ? "" : other.type;
String thisType = type == null ? "" : type;
if (category.equals(other.category)) {
if (thisType.equals(otherType)) {
if (thisLang.equals(otherLang)) {
// Don't compare on name, XEP-30 says that name SHOULD
// be equals for all identities of an entity
return 0;
} else {
return thisLang.compareTo(otherLang);
}
} else {
return thisType.compareTo(otherType);
}
} else {
return category.compareTo(other.category);
}
}
@Override
public Identity clone() {
return new Identity(this);
}
@Override
public String toString() {
return toXML().toString();
}
}
/**
* Represents the features offered by the item. This information helps the requester to determine
* what actions are possible with regard to this item (registration, search, join, etc.)
* as well as specific feature types of interest, if any (e.g., for the purpose of feature
* negotiation).
*/
public static final class Feature implements TypedCloneable<Feature> {
private final String variable;
public Feature(Feature feature) {
this.variable = feature.variable;
}
public Feature(CharSequence variable) {
this(variable.toString());
}
/**
* Creates a new feature offered by an XMPP entity or item.
*
* @param variable the feature's variable.
*/
public Feature(String variable) {
this.variable = StringUtils.requireNotNullNorEmpty(variable, "variable cannot be null");
}
/**
* Returns the feature's variable.
*
* @return the feature's variable.
*/
public String getVar() {
return variable;
}
public XmlStringBuilder toXML() {
XmlStringBuilder xml = new XmlStringBuilder();
xml.halfOpenElement("feature");
xml.attribute("var", variable);
xml.closeEmptyElement();
return xml;
}
@Override
public boolean equals(Object obj) {
return EqualsUtil.equals(this, obj, (e, o) -> {
e.append(variable, o.variable);
});
}
@Override
public int hashCode() {
return variable.hashCode();
}
@Override
public Feature clone() {
return new Feature(this);
}
@Override
public String toString() {
return toXML().toString();
}
}
}
| Disallow empty string as node in DiscoverInfo
| smack-extensions/src/main/java/org/jivesoftware/smackx/disco/packet/DiscoverInfo.java | Disallow empty string as node in DiscoverInfo | <ide><path>mack-extensions/src/main/java/org/jivesoftware/smackx/disco/packet/DiscoverInfo.java
<ide> * @param node the node attribute that supplements the 'jid' attribute
<ide> */
<ide> public void setNode(String node) {
<del> this.node = node;
<add> this.node = StringUtils.requireNullOrNotEmpty(node, "The node can not be the empty string");
<ide> }
<ide>
<ide> /** |
|
Java | apache-2.0 | ef22ff0c9c41577caf83737fe48fe9194c36c47f | 0 | Sargul/dbeaver,dbeaver/dbeaver,Sargul/dbeaver,Sargul/dbeaver,dbeaver/dbeaver,Sargul/dbeaver,dbeaver/dbeaver,dbeaver/dbeaver,Sargul/dbeaver | /*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2022 DBeaver Corp and others
*
* 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.jkiss.dbeaver.ui.editors.sql;
import org.eclipse.core.filesystem.EFS;
import org.eclipse.core.filesystem.IFileStore;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFileState;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.runtime.*;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.action.*;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.text.*;
import org.eclipse.jface.text.source.SourceViewer;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.*;
import org.eclipse.swt.events.*;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.*;
import org.eclipse.ui.*;
import org.eclipse.ui.actions.CompoundContributionItem;
import org.eclipse.ui.ide.FileStoreEditorInput;
import org.eclipse.ui.menus.CommandContributionItem;
import org.eclipse.ui.menus.IMenuService;
import org.eclipse.ui.texteditor.DefaultRangeIndicator;
import org.eclipse.ui.texteditor.ITextEditorActionConstants;
import org.eclipse.ui.texteditor.rulers.IColumnSupport;
import org.eclipse.ui.texteditor.rulers.RulerColumnDescriptor;
import org.eclipse.ui.texteditor.rulers.RulerColumnRegistry;
import org.jkiss.code.NotNull;
import org.jkiss.code.Nullable;
import org.jkiss.dbeaver.DBException;
import org.jkiss.dbeaver.ModelPreferences;
import org.jkiss.dbeaver.model.*;
import org.jkiss.dbeaver.model.app.DBPPlatformDesktop;
import org.jkiss.dbeaver.model.app.DBPProject;
import org.jkiss.dbeaver.model.app.DBPWorkspaceDesktop;
import org.jkiss.dbeaver.model.data.DBDAttributeBinding;
import org.jkiss.dbeaver.model.data.DBDDataFilter;
import org.jkiss.dbeaver.model.data.DBDDataReceiver;
import org.jkiss.dbeaver.model.exec.*;
import org.jkiss.dbeaver.model.exec.plan.DBCPlan;
import org.jkiss.dbeaver.model.exec.plan.DBCPlanStyle;
import org.jkiss.dbeaver.model.exec.plan.DBCQueryPlanner;
import org.jkiss.dbeaver.model.exec.plan.DBCQueryPlannerConfiguration;
import org.jkiss.dbeaver.model.impl.DefaultServerOutputReader;
import org.jkiss.dbeaver.model.impl.sql.SQLQueryTransformerCount;
import org.jkiss.dbeaver.model.messages.ModelMessages;
import org.jkiss.dbeaver.model.navigator.DBNUtils;
import org.jkiss.dbeaver.model.preferences.DBPPreferenceStore;
import org.jkiss.dbeaver.model.qm.QMUtils;
import org.jkiss.dbeaver.model.rm.RMConstants;
import org.jkiss.dbeaver.model.runtime.AbstractJob;
import org.jkiss.dbeaver.model.runtime.DBRProgressListener;
import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor;
import org.jkiss.dbeaver.model.runtime.DBRRunnableWithProgress;
import org.jkiss.dbeaver.model.sql.*;
import org.jkiss.dbeaver.model.sql.data.SQLQueryDataContainer;
import org.jkiss.dbeaver.model.struct.DBSDataContainer;
import org.jkiss.dbeaver.model.struct.DBSInstance;
import org.jkiss.dbeaver.model.struct.DBSObject;
import org.jkiss.dbeaver.registry.DataSourceUtils;
import org.jkiss.dbeaver.runtime.DBWorkbench;
import org.jkiss.dbeaver.runtime.sql.SQLResultsConsumer;
import org.jkiss.dbeaver.runtime.ui.UIServiceConnections;
import org.jkiss.dbeaver.tools.transfer.IDataTransferProducer;
import org.jkiss.dbeaver.tools.transfer.database.DatabaseTransferProducer;
import org.jkiss.dbeaver.tools.transfer.ui.wizard.DataTransferWizard;
import org.jkiss.dbeaver.ui.*;
import org.jkiss.dbeaver.ui.controls.*;
import org.jkiss.dbeaver.ui.controls.resultset.*;
import org.jkiss.dbeaver.ui.controls.resultset.internal.ResultSetMessages;
import org.jkiss.dbeaver.ui.css.CSSUtils;
import org.jkiss.dbeaver.ui.css.DBStyles;
import org.jkiss.dbeaver.ui.dialogs.ConfirmationDialog;
import org.jkiss.dbeaver.ui.dialogs.EnterNameDialog;
import org.jkiss.dbeaver.ui.editors.*;
import org.jkiss.dbeaver.ui.editors.sql.execute.SQLQueryJob;
import org.jkiss.dbeaver.ui.editors.sql.handlers.SQLEditorVariablesResolver;
import org.jkiss.dbeaver.ui.editors.sql.handlers.SQLNavigatorContext;
import org.jkiss.dbeaver.ui.editors.sql.internal.SQLEditorMessages;
import org.jkiss.dbeaver.ui.editors.sql.log.SQLLogPanel;
import org.jkiss.dbeaver.ui.editors.sql.plan.ExplainPlanViewer;
import org.jkiss.dbeaver.ui.editors.sql.registry.SQLPresentationDescriptor;
import org.jkiss.dbeaver.ui.editors.sql.registry.SQLPresentationPanelDescriptor;
import org.jkiss.dbeaver.ui.editors.sql.registry.SQLPresentationRegistry;
import org.jkiss.dbeaver.ui.editors.sql.scripts.ScriptsHandlerImpl;
import org.jkiss.dbeaver.ui.editors.sql.variables.AssignVariableAction;
import org.jkiss.dbeaver.ui.editors.sql.variables.SQLVariablesPanel;
import org.jkiss.dbeaver.ui.editors.text.ScriptPositionColumn;
import org.jkiss.dbeaver.ui.navigator.INavigatorModelView;
import org.jkiss.dbeaver.utils.GeneralUtils;
import org.jkiss.dbeaver.utils.PrefUtils;
import org.jkiss.dbeaver.utils.ResourceUtils;
import org.jkiss.dbeaver.utils.RuntimeUtils;
import org.jkiss.utils.ArrayUtils;
import org.jkiss.utils.CommonUtils;
import java.io.*;
import java.net.URI;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* SQL Executor
*/
public class SQLEditor extends SQLEditorBase implements
IDataSourceContainerProviderEx,
DBPEventListener,
ISaveablePart2,
DBPDataSourceTask,
DBPDataSourceAcquirer,
IResultSetProvider,
ISmartTransactionManager
{
private static final long SCRIPT_UI_UPDATE_PERIOD = 100;
private static final int MAX_PARALLEL_QUERIES_NO_WARN = 1;
private static final int SQL_EDITOR_CONTROL_INDEX = 1;
private static final int EXTRA_CONTROL_INDEX = 0;
private static final String PANEL_ITEM_PREFIX = "SQLPanelToggle:";
private static final String EMBEDDED_BINDING_PREFIX = "-- CONNECTION: ";
private static final Pattern EMBEDDED_BINDING_PREFIX_PATTERN = Pattern.compile("--\\s*CONNECTION:\\s*(.+)", Pattern.CASE_INSENSITIVE);
private static final Image IMG_DATA_GRID = DBeaverIcons.getImage(UIIcon.SQL_PAGE_DATA_GRID);
private static final Image IMG_DATA_GRID_LOCKED = DBeaverIcons.getImage(UIIcon.SQL_PAGE_DATA_GRID_LOCKED);
private static final Image IMG_EXPLAIN_PLAN = DBeaverIcons.getImage(UIIcon.SQL_PAGE_EXPLAIN_PLAN);
private static final Image IMG_LOG = DBeaverIcons.getImage(UIIcon.SQL_PAGE_LOG);
private static final Image IMG_VARIABLES = DBeaverIcons.getImage(UIIcon.SQL_VARIABLE);
private static final Image IMG_OUTPUT = DBeaverIcons.getImage(UIIcon.SQL_PAGE_OUTPUT);
private static final Image IMG_OUTPUT_ALERT = DBeaverIcons.getImage(UIIcon.SQL_PAGE_OUTPUT_ALERT);
private static final String SIDE_TOOLBAR_CONTRIBUTION_ID = "toolbar:org.jkiss.dbeaver.ui.editors.sql.toolbar.side";
// private static final String TOOLBAR_GROUP_TOP = "top";
private static final String TOOLBAR_GROUP_ADDITIONS = IWorkbenchActionConstants.MB_ADDITIONS;
// private static final String TOOLBAR_GROUP_PANELS = "panelToggles";
public static final String VIEW_PART_PROP_NAME = "org.jkiss.dbeaver.ui.editors.sql.SQLEditor";
public static final String DEFAULT_TITLE_PATTERN = "<${" + SQLPreferenceConstants.VAR_CONNECTION_NAME + "}> ${" + SQLPreferenceConstants.VAR_FILE_NAME + "}";
public static final String DEFAULT_SCRIPT_FILE_NAME = "Script";
private ResultSetOrientation resultSetOrientation = ResultSetOrientation.HORIZONTAL;
private CustomSashForm resultsSash;
private Composite sqlEditorPanel;
@Nullable
private Composite presentationStack;
private SashForm sqlExtraPanelSash;
private CTabFolder sqlExtraPanelFolder;
private ToolBarManager sqlExtraPanelToolbar;
private CTabFolder resultTabs;
private TabFolderReorder resultTabsReorder;
private CTabItem activeResultsTab;
private SQLLogPanel logViewer;
private SQLEditorOutputConsoleViewer outputViewer;
private SQLVariablesPanel variablesViewer;
private volatile QueryProcessor curQueryProcessor;
private final List<QueryProcessor> queryProcessors = new ArrayList<>();
private DBPDataSourceContainer dataSourceContainer;
private DBPDataSource curDataSource;
private volatile DBCExecutionContext executionContext;
private volatile DBCExecutionContext lastExecutionContext;
private volatile DBPContextProvider executionContextProvider;
private SQLScriptContext globalScriptContext;
private volatile boolean syntaxLoaded = false;
private FindReplaceTarget findReplaceTarget = new FindReplaceTarget();
private final List<SQLQuery> runningQueries = new ArrayList<>();
private QueryResultsContainer curResultsContainer;
private Image editorImage;
private Composite leftToolPanel;
private ToolBarManager topBarMan;
private ToolBarManager bottomBarMan;
private SQLPresentationDescriptor extraPresentationDescriptor;
private SQLEditorPresentation extraPresentation;
private final Map<SQLPresentationPanelDescriptor, SQLEditorPresentationPanel> extraPresentationPanels = new HashMap<>();
private SQLEditorPresentationPanel extraPresentationCurrentPanel;
private VerticalFolder presentationSwitchFolder;
private final List<SQLEditorListener> listeners = new ArrayList<>();
private final List<ServerOutputInfo> serverOutputs = new ArrayList<>();
private ScriptAutoSaveJob scriptAutoSavejob;
private boolean isResultSetAutoFocusEnabled = true;
private static class ServerOutputInfo {
private final DBCServerOutputReader outputReader;
private final DBCExecutionContext executionContext;
private final DBCExecutionResult result;
ServerOutputInfo(DBCServerOutputReader outputReader, DBCExecutionContext executionContext, DBCExecutionResult result) {
this.outputReader = outputReader;
this.executionContext = executionContext;
this.result = result;
}
}
private final DisposeListener resultTabDisposeListener = new DisposeListener() {
@Override
public void widgetDisposed(DisposeEvent e) {
Object data = e.widget.getData();
if (data instanceof QueryResultsContainer) {
QueryProcessor processor = ((QueryResultsContainer) data).queryProcessor;
List<QueryResultsContainer> containers = processor.getResultContainers();
for (int index = containers.indexOf(data) + 1; index < containers.size(); index++) {
QueryResultsContainer container = containers.get(index);
// Make sure that resultSetNumber equals to current loop index.
// This must be true for every container of this query processor
if (container.resultSetNumber == index) {
container.resultSetNumber--;
}
}
}
if (resultTabs.getItemCount() == 0) {
if (resultsSash.getMaximizedControl() == null) {
// Hide results
toggleResultPanel(false, true);
}
}
}
};
private VerticalButton switchPresentationSQLButton;
private VerticalButton switchPresentationExtraButton;
public SQLEditor()
{
super();
this.extraPresentationDescriptor = SQLPresentationRegistry.getInstance().getPresentation(this);
}
public void setConsoleViewOutputEnabled(boolean value) {
isResultSetAutoFocusEnabled = !value;
}
@Override
protected String[] getKeyBindingContexts() {
return new String[]{
TEXT_EDITOR_CONTEXT,
SQLEditorContributions.SQL_EDITOR_CONTEXT,
SQLEditorContributions.SQL_EDITOR_SCRIPT_CONTEXT,
IResultSetController.RESULTS_CONTEXT_ID};
}
@Override
public DBPDataSource getDataSource() {
DBPDataSourceContainer container = getDataSourceContainer();
return container == null ? null : container.getDataSource();
}
@Override
public DBCExecutionContext getExecutionContext() {
if (executionContext != null) {
return executionContext;
}
if (executionContextProvider != null) {
return executionContextProvider.getExecutionContext();
}
if (dataSourceContainer != null && !SQLEditorUtils.isOpenSeparateConnection(dataSourceContainer)) {
return DBUtils.getDefaultContext(getDataSource(), false);
}
return null;
}
public SQLScriptContext getGlobalScriptContext() {
return globalScriptContext;
}
@Nullable
public DBPProject getProject()
{
IFile file = EditorUtils.getFileFromInput(getEditorInput());
return file == null ?
DBWorkbench.getPlatform().getWorkspace().getActiveProject() : DBPPlatformDesktop.getInstance().getWorkspace().getProject(file.getProject());
}
private boolean isProjectResourceEditable() {
if (getEditorInput() instanceof IFileEditorInput) {
DBPProject project = this.getProject();
return project == null || project.hasRealmPermission(RMConstants.PERMISSION_PROJECT_RESOURCE_EDIT);
}
return true;
}
@Override
protected boolean isReadOnly() {
return super.isReadOnly() || !this.isProjectResourceEditable();
}
@Override
public boolean isEditable() {
return super.isEditable() && this.isProjectResourceEditable();
}
@Nullable
@Override
public int[] getCurrentLines()
{
synchronized (runningQueries) {
IDocument document = getDocument();
if (document == null || runningQueries.isEmpty()) {
return null;
}
List<Integer> lines = new ArrayList<>(runningQueries.size() * 2);
for (SQLQuery statementInfo : runningQueries) {
try {
int firstLine = document.getLineOfOffset(statementInfo.getOffset());
int lastLine = document.getLineOfOffset(statementInfo.getOffset() + statementInfo.getLength());
for (int k = firstLine; k <= lastLine; k++) {
lines.add(k);
}
} catch (BadLocationException e) {
// ignore - this may happen if SQL was edited after execution start
}
}
if (lines.isEmpty()) {
return null;
}
int[] results = new int[lines.size()];
for (int i = 0; i < lines.size(); i++) {
results[i] = lines.get(i);
}
return results;
}
}
@Nullable
@Override
public DBPDataSourceContainer getDataSourceContainer()
{
return dataSourceContainer;
}
@Override
public boolean setDataSourceContainer(@Nullable DBPDataSourceContainer container)
{
if (container == dataSourceContainer) {
return true;
}
// Release ds container
releaseContainer();
closeAllJobs();
dataSourceContainer = container;
if (dataSourceContainer != null) {
dataSourceContainer.getPreferenceStore().addPropertyChangeListener(this);
dataSourceContainer.getRegistry().addDataSourceListener(this);
}
IEditorInput input = getEditorInput();
if (input != null) {
DBPDataSourceContainer savedContainer = EditorUtils.getInputDataSource(input);
if (savedContainer != container) {
// Container was changed. Reset context provider and update input settings
DBCExecutionContext newExecutionContext = DBUtils.getDefaultContext(container, false);
EditorUtils.setInputDataSource(input, new SQLNavigatorContext(container, newExecutionContext));
this.executionContextProvider = null;
} else {
DBCExecutionContext iec = EditorUtils.getInputExecutionContext(input);
if (iec != null) {
this.executionContextProvider = () -> iec;
}
}
IFile file = EditorUtils.getFileFromInput(input);
if (file != null) {
DBNUtils.refreshNavigatorResource(file, container);
} else {
// FIXME: this is a hack. We can't fire event on resource change so editor's state won't be updated in UI.
// FIXME: To update main toolbar and other controls we hade and show this editor
IWorkbenchPage page = getSite().getPage();
for (IEditorReference er : page.getEditorReferences()) {
if (er.getEditor(false) == this) {
page.hideEditor(er);
page.showEditor(er);
break;
}
}
//page.activate(this);
}
}
checkConnected(false, status -> UIUtils.asyncExec(() -> {
if (!status.isOK()) {
DBWorkbench.getPlatformUI().showError("Can't connect to database", "Error connecting to datasource", status);
}
setFocus();
}));
setPartName(getEditorName());
fireDataSourceChange();
if (dataSourceContainer != null) {
dataSourceContainer.acquire(this);
}
if (SQLEditorBase.isWriteEmbeddedBinding()) {
// Patch connection reference
UIUtils.syncExec(this::embedDataSourceAssociation);
}
return true;
}
private void updateDataSourceContainer() {
DBPDataSourceContainer inputDataSource = null;
if (SQLEditorBase.isReadEmbeddedBinding()) {
// Try to get datasource from contents (always, no matter what )
inputDataSource = getDataSourceFromContent();
}
if (inputDataSource == null) {
inputDataSource = EditorUtils.getInputDataSource(getEditorInput());
}
if (inputDataSource == null) {
// No datasource. Try to get one from active part
IWorkbenchPart activePart = getSite().getWorkbenchWindow().getActivePage().getActivePart();
if (activePart != this && activePart instanceof IDataSourceContainerProvider) {
inputDataSource = ((IDataSourceContainerProvider) activePart).getDataSourceContainer();
}
}
setDataSourceContainer(inputDataSource);
}
private void updateExecutionContext(Runnable onSuccess) {
if (dataSourceContainer == null) {
releaseExecutionContext();
} else {
// Get/open context
final DBPDataSource dataSource = dataSourceContainer.getDataSource();
if (dataSource == null) {
releaseExecutionContext();
} else if (curDataSource != dataSource) {
// Datasource was changed or instance was changed (PG)
releaseExecutionContext();
curDataSource = dataSource;
if (executionContextProvider == null) {
DBPDataSourceContainer container = dataSource.getContainer();
if (SQLEditorUtils.isOpenSeparateConnection(container)) {
initSeparateConnection(dataSource, onSuccess);
} else {
if (onSuccess != null) {
onSuccess.run();
}
}
}
}
}
UIUtils.asyncExec(() -> fireDataSourceChanged(null));
}
private void initSeparateConnection(@NotNull DBPDataSource dataSource, Runnable onSuccess) {
DBSInstance dsInstance = dataSource.getDefaultInstance();
String[] contextDefaults = isRestoreActiveSchemaFromScript() ?
EditorUtils.getInputContextDefaults(dataSource.getContainer(), getEditorInput()) : null;
if (!ArrayUtils.isEmpty(contextDefaults) && contextDefaults[0] != null) {
DBSInstance selectedInstance = DBUtils.findObject(dataSource.getAvailableInstances(), contextDefaults[0]);
if (selectedInstance != null) {
dsInstance = selectedInstance;
}
}
{
final OpenContextJob job = new OpenContextJob(dsInstance, onSuccess);
job.schedule();
}
}
private void releaseExecutionContext() {
if (executionContext != null && executionContext.isConnected()) {
// Close context in separate job (otherwise it can block UI)
new CloseContextJob(executionContext).schedule();
}
executionContext = null;
curDataSource = null;
}
private void releaseContainer() {
releaseExecutionContext();
if (dataSourceContainer != null) {
dataSourceContainer.getPreferenceStore().removePropertyChangeListener(this);
dataSourceContainer.getRegistry().removeDataSourceListener(this);
dataSourceContainer.release(this);
dataSourceContainer = null;
}
}
private DBPDataSourceContainer getDataSourceFromContent() {
DBPProject project = getProject();
IDocument document = getDocument();
if (project == null || document == null || document.getNumberOfLines() == 0) {
return null;
}
try {
IRegion region = document.getLineInformation(0);
String line = document.get(region.getOffset(), region.getLength());
Matcher matcher = EMBEDDED_BINDING_PREFIX_PATTERN.matcher(line);
if (matcher.matches()) {
String connSpec = matcher.group(1).trim();
if (!CommonUtils.isEmpty(connSpec)) {
final DBPDataSourceContainer dataSource = DataSourceUtils.getDataSourceBySpec(
project,
connSpec,
null,
true,
false);
if (dataSource != null) {
return dataSource;
}
}
}
} catch (Throwable e) {
log.debug("Error extracting datasource info from script's content", e);
}
return null;
}
private void embedDataSourceAssociation() {
if (getDataSourceFromContent() == dataSourceContainer) {
return;
}
IDocument document = getDocument();
if (document == null) {
log.error("Document is null");
return;
}
try {
int totalLines = document.getNumberOfLines();
IRegion region = null;
if (totalLines > 0) {
region = document.getLineInformation(0);
String line = document.get(region.getOffset(), region.getLength());
Matcher matcher = EMBEDDED_BINDING_PREFIX_PATTERN.matcher(line);
if (!matcher.matches()) {
// Update existing association
region = null;
}
}
if (dataSourceContainer == null) {
if (region == null) {
return;
}
// Remove connection association
document.replace(region.getOffset(), region.getLength(), "");
} else {
SQLScriptBindingType bindingType = SQLScriptBindingType.valueOf(DBWorkbench.getPlatform().getPreferenceStore().getString(SQLPreferenceConstants.SCRIPT_BIND_COMMENT_TYPE));
StringBuilder assocSpecLine = new StringBuilder(EMBEDDED_BINDING_PREFIX);
bindingType.appendSpec(dataSourceContainer, assocSpecLine);
assocSpecLine.append(GeneralUtils.getDefaultLineSeparator());
if (region != null) {
// Remove connection association
document.replace(region.getOffset(), region.getLength(), assocSpecLine.toString());
} else {
document.replace(0, 0, assocSpecLine.toString());
}
}
} catch (Throwable e) {
log.debug("Error extracting datasource info from script's content", e);
}
UIUtils.asyncExec(() -> {
TextViewer textViewer = getTextViewer();
if (textViewer != null) {
textViewer.refresh();
}
});
}
public void addListener(SQLEditorListener listener) {
synchronized (listeners) {
listeners.add(listener);
}
}
public void removeListener(SQLEditorListener listener) {
synchronized (listeners) {
listeners.remove(listener);
}
}
@Override
public boolean isActiveTask() {
return getTotalQueryRunning() > 0;
}
@Override
public boolean isSmartAutoCommit() {
return getActivePreferenceStore().getBoolean(ModelPreferences.TRANSACTIONS_SMART_COMMIT);
}
@Override
public void setSmartAutoCommit(boolean smartAutoCommit) {
getActivePreferenceStore().setValue(ModelPreferences.TRANSACTIONS_SMART_COMMIT, smartAutoCommit);
try {
getActivePreferenceStore().save();
} catch (IOException e) {
log.error("Error saving smart auto-commit option", e);
}
}
public void refreshActions() {
// Redraw toolbar to refresh action sets
topBarMan.getControl().redraw();
bottomBarMan.getControl().redraw();
}
private class OpenContextJob extends AbstractJob {
private final DBSInstance instance;
private final Runnable onSuccess;
private Throwable error;
OpenContextJob(DBSInstance instance, Runnable onSuccess) {
super("Open connection to " + instance.getDataSource().getContainer().getName());
this.instance = instance;
this.onSuccess = onSuccess;
setUser(true);
}
@Override
protected IStatus run(DBRProgressMonitor monitor) {
monitor.beginTask("Open SQLEditor isolated connection", 1);
try {
String title = "SQLEditor <" + getEditorInput().getName() + ">";
monitor.subTask("Open context " + title);
DBCExecutionContext newContext = instance.openIsolatedContext(monitor, title, instance.getDefaultContext(monitor, false));
// Set context defaults
String[] contextDefaultNames = isRestoreActiveSchemaFromScript() ?
EditorUtils.getInputContextDefaults(instance.getDataSource().getContainer(), getEditorInput()) : null;
if (contextDefaultNames != null && contextDefaultNames.length > 1 &&
(!CommonUtils.isEmpty(contextDefaultNames[0]) || !CommonUtils.isEmpty(contextDefaultNames[1])))
{
try {
DBExecUtils.setExecutionContextDefaults(monitor, newContext.getDataSource(), newContext, contextDefaultNames[0], null, contextDefaultNames[1]);
} catch (DBException e) {
DBWorkbench.getPlatformUI().showError("New connection default", "Error setting default catalog/schema for new connection", e);
}
}
SQLEditor.this.executionContext = newContext;
// Needed to update main toolbar
// FIXME: silly workaround. Command state update doesn't happen in some cases
// FIXME: but it works after short pause. Seems to be a bug in E4 command framework
new AbstractJob("Notify context change") {
@Override
protected IStatus run(DBRProgressMonitor monitor) {
DBUtils.fireObjectSelect(instance, true);
return Status.OK_STATUS;
}
}.schedule(200);
} catch (DBException e) {
error = e;
} finally {
monitor.done();
}
updateContext();
return Status.OK_STATUS;
}
private void updateContext() {
if (error != null) {
releaseExecutionContext();
DBWorkbench.getPlatformUI().showError("Open context", "Can't open editor connection", error);
} else {
if (onSuccess != null) {
onSuccess.run();
}
fireDataSourceChange();
}
}
}
private boolean isRestoreActiveSchemaFromScript() {
return getActivePreferenceStore().getBoolean(SQLPreferenceConstants.AUTO_SAVE_ACTIVE_SCHEMA) &&
getActivePreferenceStore().getBoolean(SQLPreferenceConstants.EDITOR_SEPARATE_CONNECTION) &&
(this.getDataSourceContainer() == null || !this.getDataSourceContainer().isForceUseSingleConnection());
}
private static class CloseContextJob extends AbstractJob {
private final DBCExecutionContext context;
CloseContextJob(DBCExecutionContext context) {
super("Close context " + context.getContextName());
this.context = context;
setUser(true);
}
@Override
protected IStatus run(DBRProgressMonitor monitor) {
monitor.beginTask("Close SQLEditor isolated connection", 1);
try {
if (QMUtils.isTransactionActive(context)) {
UIServiceConnections serviceConnections = DBWorkbench.getService(UIServiceConnections.class);
if (serviceConnections != null) {
serviceConnections.closeActiveTransaction(monitor, context, false);
}
}
monitor.subTask("Close context " + context.getContextName());
context.close();
} finally {
monitor.done();
}
return Status.OK_STATUS;
}
}
@Override
public boolean isDirty()
{
for (QueryProcessor queryProcessor : queryProcessors) {
if (queryProcessor.isDirty() || queryProcessor.curJobRunning.get() > 0) {
return true;
}
}
if (QMUtils.isTransactionActive(executionContext)) {
return true;
}
if (isNonPersistentEditor()) {
// Console is never dirty
return false;
}
if (extraPresentation instanceof ISaveablePart && ((ISaveablePart) extraPresentation).isDirty()) {
return true;
}
return super.isDirty();
}
@Nullable
@Override
public IResultSetController getResultSetController() {
if (resultTabs != null && !resultTabs.isDisposed()) {
CTabItem activeResultsTab = getActiveResultsTab();
if (activeResultsTab != null && UIUtils.isUIThread()) {
Object tabControl = activeResultsTab.getData();
if (tabControl instanceof QueryResultsContainer) {
return ((QueryResultsContainer) tabControl).viewer;
}
}
}
return null;
}
@Nullable
@Override
public <T> T getAdapter(Class<T> required)
{
if (required == INavigatorModelView.class) {
return null;
}
if (required == IResultSetController.class || required == ResultSetViewer.class) {
return required.cast(getResultSetController());
}
if (resultTabs != null && !resultTabs.isDisposed()) {
if (required == IFindReplaceTarget.class) {
return required.cast(findReplaceTarget);
}
CTabItem activeResultsTab = getActiveResultsTab();
if (activeResultsTab != null && UIUtils.isUIThread()) {
Object tabControl = activeResultsTab.getData();
if (tabControl instanceof QueryResultsContainer) {
tabControl = ((QueryResultsContainer) tabControl).viewer;
}
if (tabControl instanceof IAdaptable) {
T adapter = ((IAdaptable) tabControl).getAdapter(required);
if (adapter != null) {
return adapter;
}
}
}
}
return super.getAdapter(required);
}
private boolean checkConnected(boolean forceConnect, DBRProgressListener onFinish)
{
// Connect to datasource
final DBPDataSourceContainer dataSourceContainer = getDataSourceContainer();
boolean doConnect = dataSourceContainer != null &&
(forceConnect || dataSourceContainer.getPreferenceStore().getBoolean(SQLPreferenceConstants.EDITOR_CONNECT_ON_ACTIVATE));
if (doConnect) {
if (!dataSourceContainer.isConnected()) {
UIServiceConnections serviceConnections = DBWorkbench.getService(UIServiceConnections.class);
if (serviceConnections != null) {
serviceConnections.connectDataSource(dataSourceContainer, onFinish);
}
}
}
return dataSourceContainer != null && dataSourceContainer.isConnected();
}
@Override
public void createPartControl(Composite parent)
{
setRangeIndicator(new DefaultRangeIndicator());
// divides editor area and results/panels area
resultsSash = UIUtils.createPartDivider(
this,
parent,
resultSetOrientation.getSashOrientation() | SWT.SMOOTH);
CSSUtils.setCSSClass(resultsSash, DBStyles.COLORED_BY_CONNECTION_TYPE);
resultsSash.setSashWidth(8);
UIUtils.setHelp(resultsSash, IHelpContextIds.CTX_SQL_EDITOR);
Composite editorContainer;
sqlEditorPanel = UIUtils.createPlaceholder(resultsSash, 3, 0);
// Create left vertical toolbar
createControlsBar(sqlEditorPanel);
sqlExtraPanelSash = new SashForm(sqlEditorPanel, SWT.HORIZONTAL);
GridData gd = new GridData(GridData.FILL_BOTH);
gd.verticalIndent = 5;
sqlExtraPanelSash.setLayoutData(gd);
// Create editor presentations sash
Composite pPlaceholder = null;
StackLayout presentationStackLayout = null;
if (extraPresentationDescriptor != null) {
presentationStack = new Composite(sqlExtraPanelSash, SWT.NONE);
presentationStack.setLayoutData(new GridData(GridData.FILL_BOTH));
presentationStackLayout = new StackLayout();
presentationStack.setLayout(presentationStackLayout);
editorContainer = presentationStack;
pPlaceholder = new Composite(presentationStack, SWT.NONE);
pPlaceholder.setLayout(new FillLayout());
} else {
editorContainer = sqlExtraPanelSash;
}
super.createPartControl(editorContainer);
getEditorControlWrapper().setLayoutData(new GridData(GridData.FILL_BOTH));
sqlExtraPanelFolder = new CTabFolder(sqlExtraPanelSash, SWT.TOP | SWT.CLOSE | SWT.FLAT);
sqlExtraPanelFolder.setSelection(0);
sqlExtraPanelFolder.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
CTabItem item = sqlExtraPanelFolder.getSelection();
if (item != null) {
IActionContributor ac = (IActionContributor) item.getData("actionContributor");
updateExtraViewToolbar(ac);
}
}
});
sqlExtraPanelToolbar = new ToolBarManager();
sqlExtraPanelToolbar.createControl(sqlExtraPanelFolder);
sqlExtraPanelFolder.setTopRight(sqlExtraPanelToolbar.getControl());
restoreSashRatio(sqlExtraPanelSash, SQLPreferenceConstants.EXTRA_PANEL_RATIO);
sqlExtraPanelSash.setMaximizedControl(sqlExtraPanelSash.getChildren()[0]);
this.addSashRatioSaveListener(sqlExtraPanelSash, SQLPreferenceConstants.EXTRA_PANEL_RATIO);
// Create right vertical toolbar
createPresentationSwitchBar(sqlEditorPanel);
if (pPlaceholder != null) {
switch (extraPresentationDescriptor.getActivationType()) {
case HIDDEN:
presentationStackLayout.topControl = presentationStack.getChildren()[SQL_EDITOR_CONTROL_INDEX];
break;
case MAXIMIZED:
case VISIBLE:
extraPresentation.createPresentation(pPlaceholder, this);
if (extraPresentationDescriptor.getActivationType() == SQLEditorPresentation.ActivationType.MAXIMIZED) {
if (presentationStack.getChildren()[EXTRA_CONTROL_INDEX] != null) {
presentationStackLayout.topControl = pPlaceholder;
}
}
break;
}
}
getSite().setSelectionProvider(new DynamicSelectionProvider());
DBPProject project = getProject();
if (project != null && project.isRegistryLoaded()) {
createResultTabs();
} else {
UIExecutionQueue.queueExec(this::createResultTabs);
}
setAction(ITextEditorActionConstants.SHOW_INFORMATION, null);
SourceViewer viewer = getViewer();
if (viewer != null) {
StyledText textWidget = viewer.getTextWidget();
if (textWidget != null) {
textWidget.addModifyListener(this::onTextChange);
textWidget.addFocusListener(new FocusAdapter() {
@Override
public void focusGained(FocusEvent e) {
refreshActions();
}
});
}
}
SQLEditorFeatures.SQL_EDITOR_OPEN.use();
// Start output reader
new ServerOutputReader().schedule();
updateExecutionContext(null);
// Update controls
UIExecutionQueue.queueExec(this::onDataSourceChange);
}
private void onTextChange(ModifyEvent e) {
if (getActivePreferenceStore().getBoolean(SQLPreferenceConstants.AUTO_SAVE_ON_CHANGE)) {
doScriptAutoSave();
}
}
private void createControlsBar(Composite sqlEditorPanel) {
leftToolPanel = new Composite(sqlEditorPanel, SWT.LEFT);
GridLayout panelsLayout = new GridLayout(1, true);
panelsLayout.marginHeight = 2;
panelsLayout.marginWidth = 1;
panelsLayout.marginTop = 1;
panelsLayout.marginBottom = 7;
panelsLayout.verticalSpacing = 1;
leftToolPanel.setLayout(panelsLayout);
leftToolPanel.setLayoutData(new GridData(GridData.FILL_VERTICAL));
ToolBar topBar = new ToolBar(leftToolPanel, SWT.VERTICAL | SWT.FLAT);
topBar.setData(VIEW_PART_PROP_NAME, this);
topBarMan = new ToolBarManager(topBar);
topBarMan.add(ActionUtils.makeCommandContribution(getSite(), SQLEditorCommands.CMD_EXECUTE_STATEMENT));
topBarMan.add(ActionUtils.makeCommandContribution(getSite(), SQLEditorCommands.CMD_EXECUTE_STATEMENT_NEW));
topBarMan.add(ActionUtils.makeCommandContribution(getSite(), SQLEditorCommands.CMD_EXECUTE_SCRIPT));
topBarMan.add(ActionUtils.makeCommandContribution(getSite(), SQLEditorCommands.CMD_EXPLAIN_PLAN));
topBarMan.add(new GroupMarker(TOOLBAR_GROUP_ADDITIONS));
final IMenuService menuService = getSite().getService(IMenuService.class);
if (menuService != null) {
int prevSize = topBarMan.getSize();
menuService.populateContributionManager(topBarMan, SIDE_TOOLBAR_CONTRIBUTION_ID);
if (prevSize != topBarMan.getSize()) {
topBarMan.insertBefore(TOOLBAR_GROUP_ADDITIONS, new ToolbarSeparatorContribution(false));
}
}
topBar.setLayoutData(new GridData(SWT.CENTER, SWT.TOP, true, false));
CSSUtils.setCSSClass(topBar, DBStyles.COLORED_BY_CONNECTION_TYPE);
topBarMan.update(true);
topBar.pack();
UIUtils.createEmptyLabel(leftToolPanel, 1, 1).setLayoutData(new GridData(SWT.CENTER, SWT.FILL, true, true));
bottomBarMan = new ToolBarManager(SWT.VERTICAL | SWT.FLAT);
bottomBarMan.add(ActionUtils.makeActionContribution(new ShowPreferencesAction(), false));
bottomBarMan.add(new ToolbarSeparatorContribution(false));
bottomBarMan.add(ActionUtils.makeCommandContribution(
getSite(),
SQLEditorCommands.CMD_SQL_SHOW_OUTPUT,
CommandContributionItem.STYLE_CHECK
));
bottomBarMan.add(ActionUtils.makeCommandContribution(
getSite(),
SQLEditorCommands.CMD_SQL_SHOW_LOG,
CommandContributionItem.STYLE_CHECK
));
bottomBarMan.add(ActionUtils.makeCommandContribution(
getSite(),
SQLEditorCommands.CMD_SQL_SHOW_VARIABLES,
CommandContributionItem.STYLE_CHECK
));
ToolBar bottomBar = bottomBarMan.createControl(leftToolPanel);
bottomBar.setLayoutData(new GridData(SWT.CENTER, SWT.BOTTOM, true, false));
CSSUtils.setCSSClass(bottomBar, DBStyles.COLORED_BY_CONNECTION_TYPE);
bottomBar.pack();
bottomBarMan.update(true);
}
private void createPresentationSwitchBar(Composite sqlEditorPanel) {
if (extraPresentationDescriptor == null) {
return;
}
presentationSwitchFolder = new VerticalFolder(sqlEditorPanel, SWT.RIGHT);
presentationSwitchFolder.setLayoutData(new GridData(GridData.FILL_VERTICAL));
switchPresentationSQLButton = new VerticalButton(presentationSwitchFolder, SWT.RIGHT | SWT.CHECK);
switchPresentationSQLButton.setText(SQLEditorMessages.editors_sql_description);
switchPresentationSQLButton.setImage(DBeaverIcons.getImage(UIIcon.SQL_SCRIPT));
switchPresentationExtraButton = new VerticalButton(presentationSwitchFolder, SWT.RIGHT | SWT.CHECK);
switchPresentationExtraButton.setData(extraPresentationDescriptor);
switchPresentationExtraButton.setText(extraPresentationDescriptor.getLabel());
switchPresentationExtraButton.setImage(DBeaverIcons.getImage(extraPresentationDescriptor.getIcon()));
String toolTip = ActionUtils.findCommandDescription(extraPresentationDescriptor.getToggleCommandId(), getSite(), false);
if (CommonUtils.isEmpty(toolTip)) {
toolTip = extraPresentationDescriptor.getDescription();
}
if (!CommonUtils.isEmpty(toolTip)) {
switchPresentationExtraButton.setToolTipText(toolTip);
}
switchPresentationSQLButton.setChecked(true);
// We use single switch handler. It must be provided by presentation itself
// Presentation switch may require some additional action so we can't just switch visible controls
SelectionListener switchListener = new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (((VerticalButton)e.item).isChecked() || presentationSwitchFolder.getSelection() == e.item) {
return;
}
String toggleCommandId = extraPresentationDescriptor.getToggleCommandId();
ActionUtils.runCommand(toggleCommandId, getSite());
}
};
switchPresentationSQLButton.addSelectionListener(switchListener);
switchPresentationExtraButton.addSelectionListener(switchListener);
// Stretch
UIUtils.createEmptyLabel(presentationSwitchFolder, 1, 1).setLayoutData(new GridData(GridData.FILL_VERTICAL));
createToggleLayoutButton();
}
/**
* Sets focus in current editor.
* This function is called on drag-n-drop and some other operations
*/
@Override
public boolean validateEditorInputState() {
boolean res = super.validateEditorInputState();
if (res) {
SourceViewer viewer = getViewer();
if (viewer != null) {
StyledText textWidget = viewer.getTextWidget();
if (textWidget != null && !textWidget.isDisposed()) {
textWidget.setFocus();
}
}
}
return res;
}
private void createResultTabs()
{
resultTabs = new CTabFolder(resultsSash, SWT.TOP | SWT.FLAT);
CSSUtils.setCSSClass(resultTabs, DBStyles.COLORED_BY_CONNECTION_TYPE);
resultTabsReorder = new TabFolderReorder(resultTabs);
resultTabs.setLayoutData(new GridData(GridData.FILL_BOTH));
resultTabs.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (extraPresentationCurrentPanel != null) {
extraPresentationCurrentPanel.deactivatePanel();
}
extraPresentationCurrentPanel = null;
Object data = e.item.getData();
if (data instanceof QueryResultsContainer) {
setActiveResultsContainer((QueryResultsContainer) data);
} else if (data instanceof SQLEditorPresentationPanel) {
extraPresentationCurrentPanel = ((SQLEditorPresentationPanel) data);
extraPresentationCurrentPanel.activatePanel();
} else if (data instanceof ExplainPlanViewer) {
SQLQuery planQuery = ((ExplainPlanViewer) data).getQuery();
if (planQuery != null) {
getSelectionProvider().setSelection(new TextSelection(planQuery.getOffset(), 0));
}
}
}
});
this.addSashRatioSaveListener(resultsSash, SQLPreferenceConstants.RESULTS_PANEL_RATIO);
this.resultTabs.addListener(TabFolderReorder.ITEM_MOVE_EVENT, event -> {
CTabItem item = (CTabItem) event.item;
if (item.getData() instanceof QueryResultsContainer) {
((QueryResultsContainer) item.getData()).resultsTab = item;
}
});
restoreSashRatio(resultsSash, SQLPreferenceConstants.RESULTS_PANEL_RATIO);
TextViewer textViewer = getTextViewer();
if (textViewer != null) {
textViewer.getTextWidget().addTraverseListener(e -> {
if (e.detail == SWT.TRAVERSE_TAB_NEXT && e.stateMask == SWT.MOD1) {
ResultSetViewer viewer = getActiveResultSetViewer();
if (viewer != null && viewer.getActivePresentation().getControl().isVisible()) {
viewer.getActivePresentation().getControl().setFocus();
e.detail = SWT.TRAVERSE_NONE;
}
}
});
}
resultTabs.setSimple(true);
resultTabs.addMouseListener(new MouseAdapter() {
@Override
public void mouseUp(MouseEvent e) {
if (e.button == 2) {
CTabItem item = resultTabs.getItem(new Point(e.x, e.y));
if (item != null && item.getShowClose()) {
item.dispose();
}
}
}
});
resultTabs.addListener(SWT.MouseDoubleClick, event -> {
if (event.button != 1) {
return;
}
CTabItem selectedItem = resultTabs.getItem(new Point(event.getBounds().x, event.getBounds().y));
if (selectedItem != null && selectedItem == resultTabs.getSelection()) {
toggleEditorMaximize();
}
});
// Extra views
createExtraViewControls();
// Create results tab
createQueryProcessor(true, true);
resultsSash.setMaximizedControl(sqlEditorPanel);
{
resultTabs.addMouseListener(new MouseAdapter() {
@Override
public void mouseDown(MouseEvent e) {
activeResultsTab = resultTabs.getItem(new Point(e.x, e.y));
}
});
MenuManager menuMgr = new MenuManager();
Menu menu = menuMgr.createContextMenu(resultTabs);
menuMgr.addMenuListener(manager -> {
final CTabItem activeTab = getActiveResultsTab();
if (activeTab != null && activeTab.getData() instanceof QueryResultsContainer) {
final QueryResultsContainer container = (QueryResultsContainer) activeTab.getData();
int pinnedTabsCount = 0;
int resultTabsCount = 0;
for (CTabItem item : resultTabs.getItems()) {
if (item.getData() instanceof QueryResultsContainer) {
resultTabsCount++;
if (((QueryResultsContainer) item.getData()).isPinned()) {
pinnedTabsCount++;
}
}
}
if (activeTab.getShowClose()) {
manager.add(ActionUtils.makeCommandContribution(getSite(), SQLEditorCommands.CMD_SQL_EDITOR_CLOSE_TAB));
if (resultTabsCount - pinnedTabsCount > 1) {
manager.add(new Action(SQLEditorMessages.action_result_tabs_close_all_tabs) {
@Override
public void run() {
closeExtraResultTabs(null, false, false);
}
});
manager.add(new Action(SQLEditorMessages.action_result_tabs_close_query_tabs) {
@Override
public void run() {
final QueryProcessor processor = ((QueryResultsContainer) activeTab.getData()).queryProcessor;
final List<CTabItem> tabs = new ArrayList<>();
for (QueryResultsContainer container : processor.getResultContainers()) {
if (!container.isPinned() && container.queryProcessor == processor) {
tabs.add(container.getTabItem());
}
}
for (CTabItem tab : tabs) {
tab.dispose();
}
}
});
manager.add(new Action(SQLEditorMessages.action_result_tabs_close_other_tabs) {
@Override
public void run() {
final List<CTabItem> tabs = new ArrayList<>();
for (CTabItem tab : resultTabs.getItems()) {
if (tab.getShowClose() && tab != activeTab) {
tabs.add(tab);
}
}
for (CTabItem tab : tabs) {
tab.dispose();
}
setActiveResultsContainer((QueryResultsContainer) activeTab.getData());
}
});
if (resultTabs.indexOf(activeTab) - pinnedTabsCount > 0) {
manager.add(new Action(SQLEditorMessages.action_result_tabs_close_tabs_to_the_left) {
@Override
public void run() {
final List<CTabItem> tabs = new ArrayList<>();
for (int i = 0, last = resultTabs.indexOf(activeTab); i < last; i++) {
tabs.add(resultTabs.getItem(i));
}
for (CTabItem tab : tabs) {
tab.dispose();
}
}
});
}
if (resultTabs.indexOf(activeTab) < resultTabsCount - pinnedTabsCount - 1) {
manager.add(new Action(SQLEditorMessages.action_result_tabs_close_tabs_to_the_right) {
@Override
public void run() {
final List<CTabItem> tabs = new ArrayList<>();
for (int i = resultTabs.indexOf(activeTab) + 1; i < resultTabs.getItemCount(); i++) {
tabs.add(resultTabs.getItem(i));
}
for (CTabItem tab : tabs) {
tab.dispose();
}
}
});
}
}
}
if (container.hasData()) {
final boolean isPinned = container.isPinned();
manager.add(new Separator());
manager.add(new Action(isPinned ? SQLEditorMessages.action_result_tabs_unpin_tab : SQLEditorMessages.action_result_tabs_pin_tab) {
@Override
public void run() {
container.setPinned(!isPinned);
CTabItem currTabItem = activeTab;
CTabItem nextTabItem;
if (isPinned) {
for (int i = resultTabs.indexOf(activeTab) + 1; i < resultTabs.getItemCount(); i++) {
nextTabItem = resultTabs.getItem(i);
if (nextTabItem.getShowClose()) {
break;
}
resultTabsReorder.swapTabs(currTabItem, nextTabItem);
currTabItem = nextTabItem;
}
} else {
for (int i = resultTabs.indexOf(activeTab) - 1; i >= 0; i--) {
nextTabItem = resultTabs.getItem(i);
if (!nextTabItem.getShowClose()) {
break;
}
resultTabsReorder.swapTabs(currTabItem, nextTabItem);
currTabItem = nextTabItem;
}
}
}
});
if (isPinned && pinnedTabsCount > 1) {
manager.add(new Action(SQLEditorMessages.action_result_tabs_unpin_all_tabs) {
@Override
public void run() {
for (CTabItem item : resultTabs.getItems()) {
if (item.getData() instanceof QueryResultsContainer) {
if (((QueryResultsContainer) item.getData()).isPinned()) {
((QueryResultsContainer) item.getData()).setPinned(false);
}
}
}
}
});
}
manager.add(new Action(SQLEditorMessages.action_result_tabs_set_name) {
@Override
public void run() {
EnterNameDialog dialog = new EnterNameDialog(resultTabs.getShell(), SQLEditorMessages.action_result_tabs_set_name_title, activeTab.getText());
if (dialog.open() == IDialogConstants.OK_ID) {
container.setTabName(dialog.getResult());
}
}
});
if (container.getQuery() != null) {
manager.add(new Separator());
AssignVariableAction action = new AssignVariableAction(SQLEditor.this, container.getQuery().getText());
action.setEditable(false);
manager.add(action);
}
}
}
manager.add(new Separator());
manager.add(ActionUtils.makeCommandContribution(getSite(), SQLEditorCommands.CMD_SQL_EDITOR_MAXIMIZE_PANEL));
});
menuMgr.setRemoveAllWhenShown(true);
resultTabs.setMenu(menu);
}
}
private void addSashRatioSaveListener(SashForm sash, String prefId) {
Control control = sash.getChildren()[0];
control.addListener(SWT.Resize, event -> {
if (!control.isDisposed()) {
int[] weights = sash.getWeights();
IPreferenceStore prefs = getPreferenceStore();
if (prefs != null && weights.length == 2) {
prefs.setValue(prefId, weights[0] + "-" + weights[1]);
}
}
});
}
private void restoreSashRatio(SashForm sash, String prefId) {
String resultsPanelRatio = getPreferenceStore().getString(prefId);
if (!CommonUtils.isEmpty(resultsPanelRatio)) {
String[] weightsStr = resultsPanelRatio.split("-");
if (weightsStr.length > 1) {
int[] weights = {
CommonUtils.toInt(weightsStr[0]),
CommonUtils.toInt(weightsStr[1]),
};
// If weight of one of controls less than 5% of weight of another - restore default wqeights
if (weights[1] < weights[0] / 15 || weights[0] < weights[1] / 15) {
log.debug("Restore default sash weights");
} else {
sash.setWeights(weights);
}
}
}
}
private void setActiveResultsContainer(QueryResultsContainer data) {
curResultsContainer = data;
curQueryProcessor = curResultsContainer.queryProcessor;
}
/////////////////////////////////////////////////////////////
// Panels
public void toggleExtraPanelsLayout() {
CTabItem outTab = getExtraViewTab(outputViewer.getControl());
CTabItem logTab = getExtraViewTab(logViewer);
CTabItem varTab = getExtraViewTab(variablesViewer);
if (outTab != null) outTab.dispose();
if (logTab != null) logTab.dispose();
if (varTab != null) varTab.dispose();
IPreferenceStore preferenceStore = getPreferenceStore();
String epLocation = getExtraPanelsLocation();
if (SQLPreferenceConstants.LOCATION_RESULTS.equals(epLocation)) {
epLocation = SQLPreferenceConstants.LOCATION_RIGHT;
} else {
epLocation = SQLPreferenceConstants.LOCATION_RESULTS;
}
preferenceStore.setValue(SQLPreferenceConstants.EXTRA_PANEL_LOCATION, epLocation);
createExtraViewControls();
if (outTab != null) showOutputPanel();
if (logTab != null) showExecutionLogPanel();
if (varTab != null) showVariablesPanel();
}
public String getExtraPanelsLocation() {
return getPreferenceStore().getString(SQLPreferenceConstants.EXTRA_PANEL_LOCATION);
}
private void createExtraViewControls() {
if (logViewer != null) {
logViewer.dispose();
logViewer = null;
}
if (variablesViewer != null) {
variablesViewer.dispose();
variablesViewer = null;
}
if (outputViewer != null) {
outputViewer.dispose();
outputViewer = null;
}
if (sqlExtraPanelFolder != null) {
for (CTabItem ti : sqlExtraPanelFolder.getItems()) {
ti.dispose();
}
}
//planView = new ExplainPlanViewer(this, resultTabs);
CTabFolder folder = getFolderForExtraPanels();
logViewer = new SQLLogPanel(folder, this);
variablesViewer = new SQLVariablesPanel(folder, this);
outputViewer = new SQLEditorOutputConsoleViewer(getSite(), folder, SWT.NONE);
if (getFolderForExtraPanels() != sqlExtraPanelFolder) {
sqlExtraPanelSash.setMaximizedControl(sqlExtraPanelSash.getChildren()[0]);
}
}
public CTabFolder getResultTabsContainer() {
return resultTabs;
}
private CTabFolder getFolderForExtraPanels() {
CTabFolder folder = this.sqlExtraPanelFolder;
String epLocation = getExtraPanelsLocation();
if (SQLPreferenceConstants.LOCATION_RESULTS.equals(epLocation)) {
folder = resultTabs;
}
return folder;
}
private CTabItem getExtraViewTab(Control control) {
CTabFolder tabFolder = this.getFolderForExtraPanels();
for (CTabItem item : tabFolder.getItems()) {
if (item.getData() == control) {
return item;
}
}
return null;
}
private void showExtraView(final String commandId, String name, String toolTip, Image image, Control view, IActionContributor actionContributor) {
ToolItem viewItem = getViewToolItem(commandId);
if (viewItem == null) {
log.warn("Tool item for command " + commandId + " not found");
return;
}
CTabFolder tabFolder = this.getFolderForExtraPanels();
CTabItem curItem = getExtraViewTab(view);
if (curItem != null) {
// Close tab if it is already open
viewItem.setSelection(false);
curItem.dispose();
return;
}
boolean isTabsToTheRight = tabFolder == sqlExtraPanelFolder;
if (isTabsToTheRight) {
if (sqlExtraPanelSash.getMaximizedControl() != null) {
sqlExtraPanelSash.setMaximizedControl(null);
}
} else {
sqlExtraPanelSash.setMaximizedControl(sqlExtraPanelSash.getChildren()[0]);
// Show results
showResultsPanel(true);
}
if (view == outputViewer.getControl()) {
updateOutputViewerIcon(false);
outputViewer.resetNewOutput();
}
// Create new tab
viewItem.setSelection(true);
CTabItem item = new CTabItem(tabFolder, SWT.CLOSE);
item.setControl(view);
item.setText(name);
item.setToolTipText(toolTip);
item.setImage(image);
item.setData(view);
item.setData("actionContributor", actionContributor);
// De-select tool item on tab close
item.addDisposeListener(e -> {
if (!viewItem.isDisposed()) {
viewItem.setSelection(false);
}
if (tabFolder.getItemCount() == 0) {
sqlExtraPanelSash.setMaximizedControl(sqlExtraPanelSash.getChildren()[0]);
}
});
tabFolder.setSelection(item);
if (isTabsToTheRight) {
updateExtraViewToolbar(actionContributor);
}
}
private void updateExtraViewToolbar(IActionContributor actionContributor) {
// Update toolbar
sqlExtraPanelToolbar.removeAll();
if (actionContributor != null) {
actionContributor.contributeActions(sqlExtraPanelToolbar);
}
sqlExtraPanelToolbar.add(ActionUtils.makeCommandContribution(
getSite(),
"org.jkiss.dbeaver.ui.editors.sql.toggle.extraPanels",
CommandContributionItem.STYLE_CHECK,
UIIcon.ARROW_DOWN));
sqlExtraPanelToolbar.update(true);
}
private ToolItem getViewToolItem(String commandId) {
ToolItem viewItem = null;
for (ToolItem item : topBarMan.getControl().getItems()) {
Object data = item.getData();
if (data instanceof CommandContributionItem) {
if (((CommandContributionItem) data).getCommand() != null
&& commandId.equals(((CommandContributionItem) data).getCommand().getId())
) {
viewItem = item;
break;
}
}
}
for (ToolItem item : bottomBarMan.getControl().getItems()) {
Object data = item.getData();
if (data instanceof CommandContributionItem) {
if (((CommandContributionItem) data).getCommand() != null
&& commandId.equals(((CommandContributionItem) data).getCommand().getId())
) {
viewItem = item;
break;
}
}
}
return viewItem;
}
private CTabItem getActiveResultsTab() {
return activeResultsTab == null || activeResultsTab.isDisposed() ?
(resultTabs == null ? null : resultTabs.getSelection()) : activeResultsTab;
}
public void closeActiveTab() {
CTabItem tabItem = getActiveResultsTab();
if (tabItem != null && tabItem.getShowClose()) {
tabItem.dispose();
activeResultsTab = null;
}
}
public void showOutputPanel() {
showExtraView(
SQLEditorCommands.CMD_SQL_SHOW_OUTPUT,
SQLEditorMessages.editors_sql_output,
SQLEditorMessages.editors_sql_output_tip,
IMG_OUTPUT,
outputViewer.getControl(),
manager -> manager.add(new OutputAutoShowToggleAction()));
}
public void showExecutionLogPanel() {
showExtraView(
SQLEditorCommands.CMD_SQL_SHOW_LOG,
SQLEditorMessages.editors_sql_execution_log,
SQLEditorMessages.editors_sql_execution_log_tip,
IMG_LOG,
logViewer,
null);
}
public void showVariablesPanel() {
showExtraView(
SQLEditorCommands.CMD_SQL_SHOW_VARIABLES,
SQLEditorMessages.editors_sql_variables,
SQLEditorMessages.editors_sql_variables_tip,
IMG_VARIABLES,
variablesViewer,
null);
UIUtils.asyncExec(() -> variablesViewer.refreshVariables());
}
public <T> T getExtraPresentationPanel(Class<T> panelClass) {
for (CTabItem tabItem : resultTabs.getItems()) {
if (tabItem.getData() instanceof SQLEditorPresentationPanel && tabItem.getData().getClass() == panelClass) {
return panelClass.cast(tabItem.getData());
}
}
return null;
}
public boolean showPresentationPanel(SQLEditorPresentationPanel panel) {
for (CTabItem item : resultTabs.getItems()) {
if (item.getData() == panel) {
setResultTabSelection(item);
return true;
}
}
return false;
}
private void setResultTabSelection(CTabItem item) {
if (isResultSetAutoFocusEnabled || !(item.getData() instanceof QueryResultsContainer)) {
resultTabs.setSelection(item);
}
}
public SQLEditorPresentationPanel showPresentationPanel(String panelID) {
for (IContributionItem contributionItem : topBarMan.getItems()) {
if (contributionItem instanceof ActionContributionItem) {
IAction action = ((ActionContributionItem) contributionItem).getAction();
if (action instanceof PresentationPanelToggleAction
&& ((PresentationPanelToggleAction) action).panel.getId().equals(panelID)
) {
action.run();
return extraPresentationCurrentPanel;
}
}
}
for (IContributionItem contributionItem : bottomBarMan.getItems()) {
if (contributionItem instanceof ActionContributionItem) {
IAction action = ((ActionContributionItem) contributionItem).getAction();
if (action instanceof PresentationPanelToggleAction
&& ((PresentationPanelToggleAction) action).panel.getId().equals(panelID)
) {
action.run();
return extraPresentationCurrentPanel;
}
}
}
return null;
}
public boolean hasMaximizedControl() {
return resultsSash.getMaximizedControl() != null;
}
public SQLEditorPresentation getExtraPresentation() {
return extraPresentation;
}
public SQLEditorPresentation.ActivationType getExtraPresentationState() {
if (extraPresentation == null || presentationStack == null) {
return SQLEditorPresentation.ActivationType.HIDDEN;
}
Control maximizedControl = ((StackLayout)presentationStack.getLayout()).topControl;
if (maximizedControl == getExtraPresentationControl()) {
return SQLEditorPresentation.ActivationType.MAXIMIZED;
} else if (maximizedControl == getEditorControlWrapper()) {
return SQLEditorPresentation.ActivationType.HIDDEN;
} else {
return SQLEditorPresentation.ActivationType.VISIBLE;
}
}
public void showExtraPresentation(boolean show, boolean maximize) {
if (extraPresentationDescriptor == null || presentationStack == null) {
return;
}
resultsSash.setRedraw(false);
try {
StackLayout stackLayout = (StackLayout) presentationStack.getLayout();
if (!show) {
//boolean epHasFocus = UIUtils.hasFocus(getExtraPresentationControl());
stackLayout.topControl = presentationStack.getChildren()[SQL_EDITOR_CONTROL_INDEX];
//if (epHasFocus) {
getEditorControlWrapper().setFocus();
//}
// Set selection provider back to the editor
getSite().setSelectionProvider(new DynamicSelectionProvider());
} else {
if (extraPresentation == null) {
// Lazy activation
try {
extraPresentation = extraPresentationDescriptor.createPresentation();
extraPresentation.createPresentation((Composite) getExtraPresentationControl(), this);
} catch (DBException e) {
log.error("Error creating presentation", e);
}
}
getSite().setSelectionProvider(extraPresentation.getSelectionProvider());
if (maximize) {
stackLayout.topControl = getExtraPresentationControl();
getExtraPresentationControl().setFocus();
} else {
stackLayout.topControl = null;
}
}
// Show presentation panels
boolean sideBarChanged = false;
if (getExtraPresentationState() == SQLEditorPresentation.ActivationType.HIDDEN) {
// Remove all presentation panel toggles
//for (SQLPresentationPanelDescriptor panelDescriptor : extraPresentationDescriptor.getPanels()) {
for (Control vb : presentationSwitchFolder.getChildren()) {
if (vb.getData() instanceof SQLPresentationPanelDescriptor) { // || vb instanceof Label
vb.dispose();
sideBarChanged = true;
}
}
//}
// Close all panels
for (CTabItem tabItem : resultTabs.getItems()) {
if (tabItem.getData() instanceof SQLEditorPresentationPanel) {
tabItem.dispose();
}
}
extraPresentationCurrentPanel = null;
} else {
// Check and add presentation panel toggles
UIUtils.createEmptyLabel(presentationSwitchFolder, 1, 1).setLayoutData(new GridData(GridData.FILL_VERTICAL));
for (SQLPresentationPanelDescriptor panelDescriptor : extraPresentationDescriptor.getPanels()) {
removeToggleLayoutButton();
sideBarChanged = true;
PresentationPanelToggleAction toggleAction = new PresentationPanelToggleAction(panelDescriptor);
VerticalButton panelButton = new VerticalButton(presentationSwitchFolder, SWT.RIGHT);
panelButton.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_END));
panelButton.setAction(toggleAction, true);
panelButton.setData(panelDescriptor);
if (panelDescriptor.isAutoActivate()) {
//panelButton.setChecked(true);
toggleAction.run();
}
createToggleLayoutButton();
}
}
boolean isExtra = getExtraPresentationState() == SQLEditorPresentation.ActivationType.MAXIMIZED;
switchPresentationSQLButton.setChecked(!isExtra);
switchPresentationExtraButton.setChecked(isExtra);
presentationSwitchFolder.redraw();
if (sideBarChanged) {
topBarMan.update(true);
bottomBarMan.update(true);
topBarMan.getControl().getParent().layout(true);
bottomBarMan.getControl().getParent().layout(true);
}
presentationStack.layout(true, true);
} finally {
resultsSash.setRedraw(true);
}
}
private void createToggleLayoutButton() {
VerticalButton.create(presentationSwitchFolder, SWT.RIGHT | SWT.CHECK, getSite(), SQLEditorCommands.CMD_TOGGLE_LAYOUT, false);
}
private void removeToggleLayoutButton() {
for (VerticalButton vButton : presentationSwitchFolder.getItems()) {
if (vButton.getCommandId() != null && vButton.getCommandId().equals(SQLEditorCommands.CMD_TOGGLE_LAYOUT)) {
vButton.dispose();
}
}
}
private Control getExtraPresentationControl() {
return presentationStack == null ? null : presentationStack.getChildren()[EXTRA_CONTROL_INDEX];
}
public void toggleResultPanel(boolean switchFocus, boolean createQueryProcessor) {
UIUtils.syncExec(() -> {
if (resultsSash.getMaximizedControl() == null) {
resultsSash.setMaximizedControl(sqlEditorPanel);
switchFocus(false);
} else {
// Show both editor and results
// Check for existing query processors (maybe all result tabs were closed)
if (resultTabs.getItemCount() == 0 && createQueryProcessor) {
createQueryProcessor(true, true);
}
resultsSash.setMaximizedControl(null);
if (switchFocus) {
switchFocus(true);
}
}
});
}
public void toggleEditorMaximize()
{
if (resultsSash.getMaximizedControl() == null) {
resultsSash.setMaximizedControl(resultTabs);
switchFocus(true);
} else {
resultsSash.setMaximizedControl(null);
switchFocus(false);
}
}
private void switchFocus(boolean results) {
if (results) {
ResultSetViewer activeRS = getActiveResultSetViewer();
if (activeRS != null && activeRS.getActivePresentation() != null) {
activeRS.getActivePresentation().getControl().setFocus();
} else {
CTabItem activeTab = resultTabs.getSelection();
if (activeTab != null && activeTab.getControl() != null) {
activeTab.getControl().setFocus();
}
}
} else {
getEditorControlWrapper().setFocus();
}
}
public void toggleActivePanel() {
if (resultsSash.getMaximizedControl() == null) {
if (UIUtils.hasFocus(resultTabs)) {
switchFocus(false);
} else {
switchFocus(true);
}
}
}
private void updateResultSetOrientation() {
try {
resultSetOrientation = ResultSetOrientation.valueOf(DBWorkbench.getPlatform().getPreferenceStore().getString(SQLPreferenceConstants.RESULT_SET_ORIENTATION));
} catch (IllegalArgumentException e) {
resultSetOrientation = ResultSetOrientation.HORIZONTAL;
}
if (resultsSash != null) {
resultsSash.setOrientation(resultSetOrientation.getSashOrientation());
}
}
private class PresentationPanelToggleAction extends Action {
private SQLPresentationPanelDescriptor panel;
private CTabItem tabItem;
public PresentationPanelToggleAction(SQLPresentationPanelDescriptor panel) {
super(panel.getLabel(), Action.AS_CHECK_BOX);
setId(PANEL_ITEM_PREFIX + panel.getId());
if (panel.getIcon() != null) {
setImageDescriptor(DBeaverIcons.getImageDescriptor(panel.getIcon()));
}
if (panel.getDescription() != null) {
setToolTipText(panel.getDescription());
}
this.panel = panel;
}
@Override
public void run() {
if (resultsSash.getMaximizedControl() != null) {
resultsSash.setMaximizedControl(null);
}
setChecked(!isChecked());
SQLEditorPresentationPanel panelInstance = extraPresentationPanels.get(panel);
if (panelInstance != null && !isChecked()) {
// Hide panel
for (CTabItem tabItem : resultTabs.getItems()) {
if (tabItem.getData() == panelInstance) {
tabItem.dispose();
return;
}
}
}
if (panelInstance == null) {
Control panelControl;
try {
panelInstance = panel.createPanel();
panelControl = panelInstance.createPanel(resultTabs, SQLEditor.this, extraPresentation);
} catch (DBException e) {
DBWorkbench.getPlatformUI().showError("Panel opening error", "Can't create panel " + panel.getLabel(), e);
return;
}
extraPresentationPanels.put(panel, panelInstance);
tabItem = new CTabItem(resultTabs, SWT.CLOSE);
tabItem.setControl(panelControl);
tabItem.setText(panel.getLabel());
tabItem.setToolTipText(panel.getDescription());
tabItem.setImage(DBeaverIcons.getImage(panel.getIcon()));
tabItem.setData(panelInstance);
// De-select tool item on tab close
tabItem.addDisposeListener(e -> {
PresentationPanelToggleAction.this.setChecked(false);
panelControl.dispose();
extraPresentationPanels.remove(panel);
extraPresentationCurrentPanel = null;
resultTabDisposeListener.widgetDisposed(e);
});
extraPresentationCurrentPanel = panelInstance;
setResultTabSelection(tabItem);
} else {
for (CTabItem tabItem : resultTabs.getItems()) {
if (tabItem.getData() == panelInstance) {
setResultTabSelection(tabItem);
break;
}
}
}
}
}
/////////////////////////////////////////////////////////////
// Initialization
@Override
public void init(IEditorSite site, IEditorInput editorInput)
throws PartInitException
{
super.init(site, editorInput);
updateResultSetOrientation();
SQLScriptContext parentContext = null;
{
DatabaseEditorContext parentEditorContext = EditorUtils.getEditorContext(editorInput);
if (parentEditorContext instanceof SQLNavigatorContext) {
parentContext = ((SQLNavigatorContext) parentEditorContext).getScriptContext();
}
}
this.globalScriptContext = new SQLScriptContext(
parentContext,
this,
EditorUtils.getLocalFileFromInput(getEditorInput()),
new OutputLogWriter(),
new SQLEditorParametersProvider(getSite()));
this.globalScriptContext.addListener(new DBCScriptContextListener() {
@Override
public void variableChanged(ContextAction action, DBCScriptContext.VariableInfo variable) {
saveContextVariables();
}
@Override
public void parameterChanged(ContextAction action, String name, Object value) {
saveContextVariables();
}
private void saveContextVariables() {
new AbstractJob("Save variables") {
@Override
protected IStatus run(DBRProgressMonitor monitor) {
DBPDataSourceContainer ds = getDataSourceContainer();
if (ds != null) {
globalScriptContext.saveVariables(ds.getDriver(), null);
}
return Status.OK_STATUS;
}
}.schedule(200);
}
});
}
@Override
protected void doSetInput(IEditorInput editorInput)
{
// Check for file existence
try {
if (editorInput instanceof IFileEditorInput) {
final IFile file = ((IFileEditorInput) editorInput).getFile();
if (!file.exists()) {
file.create(new ByteArrayInputStream(new byte[]{}), true, new NullProgressMonitor());
}
}
} catch (Exception e) {
log.error("Error checking SQL file", e);
}
try {
super.doSetInput(editorInput);
} catch (Throwable e) {
// Something bad may happen. E.g. OutOfMemory error in case of too big input file.
StringWriter out = new StringWriter();
e.printStackTrace(new PrintWriter(out, true));
editorInput = new StringEditorInput("Error", CommonUtils.truncateString(out.toString(), 10000), true, GeneralUtils.UTF8_ENCODING);
doSetInput(editorInput);
log.error("Error loading input SQL file", e);
}
syntaxLoaded = false;
Runnable inputinitializer = () -> {
DBPDataSourceContainer oldDataSource = SQLEditor.this.getDataSourceContainer();
DBPDataSourceContainer newDataSource = EditorUtils.getInputDataSource(SQLEditor.this.getEditorInput());
if (oldDataSource != newDataSource) {
SQLEditor.this.dataSourceContainer = null;
SQLEditor.this.updateDataSourceContainer();
} else {
SQLEditor.this.reloadSyntaxRules();
}
};
if (isNonPersistentEditor()) {
inputinitializer.run();
} else {
// Run in queue - for app startup
UIExecutionQueue.queueExec(inputinitializer);
}
setPartName(getEditorName());
if (isNonPersistentEditor()) {
setTitleImage(DBeaverIcons.getImage(UIIcon.SQL_CONSOLE));
}
editorImage = getTitleImage();
}
@Override
public String getTitleToolTip() {
if (!DBWorkbench.getPlatform().getApplication().isStandalone()) {
// For Eclipse plugins return just title because it is used in main window title.
return getTitle();
}
DBPDataSourceContainer dataSourceContainer = getDataSourceContainer();
if (dataSourceContainer == null) {
return super.getTitleToolTip();
}
final IEditorInput editorInput = getEditorInput();
String scriptPath;
if (editorInput instanceof IFileEditorInput) {
scriptPath = ((IFileEditorInput) editorInput).getFile().getFullPath().toString();
} else if (editorInput instanceof IPathEditorInput) {
scriptPath = ((IPathEditorInput) editorInput).getPath().toString();
} else if (editorInput instanceof IURIEditorInput) {
final URI uri = ((IURIEditorInput) editorInput).getURI();
if ("file".equals(uri.getScheme())) {
scriptPath = new File(uri).getAbsolutePath();
} else {
scriptPath = uri.toString();
}
} else if (editorInput instanceof INonPersistentEditorInput) {
scriptPath = "SQL Console";
} else {
scriptPath = editorInput.getName();
if (CommonUtils.isEmpty(scriptPath)) {
scriptPath = "<not a file>";
}
}
StringBuilder tip = new StringBuilder();
tip
.append(NLS.bind(SQLEditorMessages.sql_editor_title_tooltip_path, scriptPath))
.append(" \n").append(NLS.bind(SQLEditorMessages.sql_editor_title_tooltip_connecton, dataSourceContainer.getName()))
.append(" \n").append(NLS.bind(SQLEditorMessages.sql_editor_title_tooltip_type, dataSourceContainer.getDriver().getFullName()))
.append(" \n").append(NLS.bind(SQLEditorMessages.sql_editor_title_tooltip_url, dataSourceContainer.getConnectionConfiguration().getUrl()));
SQLEditorVariablesResolver scriptNameResolver = new SQLEditorVariablesResolver(dataSourceContainer,
dataSourceContainer.getConnectionConfiguration(),
getExecutionContext(),
scriptPath,
null,
getProject());
if (scriptNameResolver.get(SQLPreferenceConstants.VAR_ACTIVE_DATABASE) != null) {
tip.append(" \n").append(NLS.bind(SQLEditorMessages.sql_editor_title_tooltip_database, scriptNameResolver.get(SQLPreferenceConstants.VAR_ACTIVE_DATABASE)));
}
if (scriptNameResolver.get(SQLPreferenceConstants.VAR_ACTIVE_SCHEMA) != null) {
tip.append(" \n").append(NLS.bind(SQLEditorMessages.sql_editor_title_tooltip_schema, scriptNameResolver.get(SQLPreferenceConstants.VAR_ACTIVE_SCHEMA)));
}
return tip.toString();
}
private String getEditorName() {
final IFile file = EditorUtils.getFileFromInput(getEditorInput());
String scriptName;
if (file != null) {
scriptName = file.getFullPath().removeFileExtension().lastSegment();
} else {
File localFile = EditorUtils.getLocalFileFromInput(getEditorInput());
if (localFile != null) {
scriptName = localFile.getName();
} else {
scriptName = getEditorInput().getName();
}
}
DBPPreferenceStore preferenceStore = getActivePreferenceStore();
String pattern = preferenceStore.getString(SQLPreferenceConstants.SCRIPT_TITLE_PATTERN);
return GeneralUtils.replaceVariables(pattern, new SQLEditorVariablesResolver(
dataSourceContainer,
null,
getExecutionContext(),
scriptName,
file,
getProject()));
}
@Override
public void setFocus() {
super.setFocus();
}
public void loadQueryPlan() {
DBCQueryPlanner planner = GeneralUtils.adapt(getDataSource(), DBCQueryPlanner.class);
ExplainPlanViewer planView = getPlanView(null, planner);
if (planView != null) {
if (!planView.loadQueryPlan(planner, planView)) {
closeActiveTab();
}
}
}
public void explainQueryPlan() {
// Notify listeners
synchronized (listeners) {
for (SQLEditorListener listener : listeners) {
listener.beforeQueryPlanExplain();
}
}
final SQLScriptElement scriptElement = extractActiveQuery();
if (scriptElement == null) {
setStatus(SQLEditorMessages.editors_sql_status_empty_query_string, DBPMessageType.ERROR);
return;
}
if (!(scriptElement instanceof SQLQuery)) {
setStatus("Can't explain plan for command", DBPMessageType.ERROR);
return;
}
explainQueryPlan((SQLQuery) scriptElement);
}
private void explainQueryPlan(SQLQuery sqlQuery) {
showResultsPanel(false);
DBCQueryPlanner planner = GeneralUtils.adapt(getDataSource(), DBCQueryPlanner.class);
DBCPlanStyle planStyle = planner.getPlanStyle();
if (planStyle == DBCPlanStyle.QUERY) {
explainPlanFromQuery(planner, sqlQuery);
} else if (planStyle == DBCPlanStyle.OUTPUT) {
explainPlanFromQuery(planner, sqlQuery);
showOutputPanel();
} else {
ExplainPlanViewer planView = getPlanView(sqlQuery, planner);
if (planView != null) {
planView.explainQueryPlan(sqlQuery, planner);
}
}
}
private void showResultsPanel(boolean createQueryProcessor) {
if (resultsSash.getMaximizedControl() != null) {
toggleResultPanel(false, createQueryProcessor);
}
UIUtils.syncExec(() -> {
if (resultsSash.isDownHidden()) {
resultsSash.showDown();
}
});
}
private ExplainPlanViewer getPlanView(SQLQuery sqlQuery, DBCQueryPlanner planner) {
// 1. Determine whether planner supports plan extraction
if (planner == null) {
DBWorkbench.getPlatformUI().showError("Execution plan", "Execution plan explain isn't supported by current datasource");
return null;
}
// Transform query parameters
if (sqlQuery != null) {
if (!transformQueryWithParameters(sqlQuery)) {
return null;
}
}
ExplainPlanViewer planView = null;
if (sqlQuery != null) {
for (CTabItem item : resultTabs.getItems()) {
if (item.getData() instanceof ExplainPlanViewer) {
ExplainPlanViewer pv = (ExplainPlanViewer) item.getData();
if (pv.getQuery() != null && pv.getQuery().equals(sqlQuery)) {
setResultTabSelection(item);
planView = pv;
break;
}
}
}
}
if (planView == null) {
int maxPlanNumber = 0;
for (CTabItem item : resultTabs.getItems()) {
if (item.getData() instanceof ExplainPlanViewer) {
maxPlanNumber = Math.max(maxPlanNumber, ((ExplainPlanViewer) item.getData()).getPlanNumber());
}
}
maxPlanNumber++;
planView = new ExplainPlanViewer(this, this, resultTabs, maxPlanNumber);
final CTabItem item = new CTabItem(resultTabs, SWT.CLOSE);
item.setControl(planView.getControl());
item.setText(SQLEditorMessages.editors_sql_error_execution_plan_title + " - " + maxPlanNumber);
if (sqlQuery != null) {
// Prepare query for tooltip
String preparedText = sqlQuery.getText().replaceAll("[\n\r\t]{3,}", "");
if (preparedText.length() > 300) {
item.setToolTipText(preparedText.substring(0, 300) + "...");
} else {
item.setToolTipText(preparedText);
}
}
item.setImage(IMG_EXPLAIN_PLAN);
item.setData(planView);
item.addDisposeListener(resultTabDisposeListener);
UIUtils.disposeControlOnItemDispose(item);
setResultTabSelection(item);
}
return planView;
}
private void explainPlanFromQuery(final DBCQueryPlanner planner, final SQLQuery sqlQuery) {
final String[] planQueryString = new String[1];
DBRRunnableWithProgress queryObtainTask = monitor -> {
DBCQueryPlannerConfiguration configuration = ExplainPlanViewer.makeExplainPlanConfiguration(monitor, planner);
if (configuration == null) {
return;
}
try (DBCSession session = getExecutionContext().openSession(monitor, DBCExecutionPurpose.UTIL, "Prepare plan query")) {
DBCPlan plan = planner.planQueryExecution(session, sqlQuery.getText(), configuration);
planQueryString[0] = plan.getPlanQueryString();
} catch (Exception e) {
log.error(e);
}
};
if (RuntimeUtils.runTask(queryObtainTask, "Retrieve plan query", 5000) && !CommonUtils.isEmpty(planQueryString[0])) {
SQLQuery planQuery = new SQLQuery(getDataSource(), planQueryString[0]);
processQueries(Collections.singletonList(planQuery), false, true, false, true, null, null);
}
}
public void processSQL(boolean newTab, boolean script) {
processSQL(newTab, script, null, null);
}
public boolean processSQL(boolean newTab, boolean script, SQLQueryTransformer transformer, @Nullable SQLQueryListener queryListener) {
return processSQL(newTab, script, false, transformer, queryListener);
}
public boolean processSQL(boolean newTab, boolean script, boolean executeFromPosition) {
return processSQL(newTab, script, executeFromPosition, null, null);
}
public boolean processSQL(boolean newTab, boolean script, boolean executeFromPosition, SQLQueryTransformer transformer,
@Nullable SQLQueryListener queryListener
) {
IDocument document = getDocument();
if (document == null) {
setStatus(SQLEditorMessages.editors_sql_status_cant_obtain_document, DBPMessageType.ERROR);
return false;
}
// Notify listeners
synchronized (listeners) {
for (SQLEditorListener listener : listeners) {
listener.beforeQueryExecute(script, newTab);
}
}
List<SQLScriptElement> elements;
if (script) {
if (executeFromPosition) {
// Get all queries from the current position
ITextSelection selection = (ITextSelection) getSelectionProvider().getSelection();
elements = extractScriptQueries(selection.getOffset(), document.getLength(), true, false, true);
// Replace first query with query under cursor for case if the cursor is in the middle of the query
elements.remove(0);
elements.add(0, extractActiveQuery());
} else {
// Execute all SQL statements consequently
ITextSelection selection = (ITextSelection) getSelectionProvider().getSelection();
if (selection.getLength() > 1) {
elements = extractScriptQueries(selection.getOffset(), selection.getLength(), true, false, true);
} else {
elements = extractScriptQueries(0, document.getLength(), true, false, true);
}
}
} else {
// Execute statement under cursor or selected text (if selection present)
SQLScriptElement sqlQuery = extractActiveQuery();
if (sqlQuery == null) {
ResultSetViewer activeViewer = getActiveResultSetViewer();
if (activeViewer != null) {
activeViewer.setStatus(SQLEditorMessages.editors_sql_status_empty_query_string, DBPMessageType.ERROR);
}
return false;
} else {
elements = Collections.singletonList(sqlQuery);
}
}
try {
if (transformer != null) {
DBPDataSource dataSource = getDataSource();
if (dataSource != null) {
List<SQLScriptElement> xQueries = new ArrayList<>(elements.size());
for (SQLScriptElement element : elements) {
if (element instanceof SQLQuery) {
SQLQuery query = transformer.transformQuery(dataSource, getSyntaxManager(), (SQLQuery) element);
if (!CommonUtils.isEmpty(query.getParameters())) {
query.setParameters(parseQueryParameters(query));
}
xQueries.add(query);
} else {
xQueries.add(element);
}
}
elements = xQueries;
}
}
}
catch (DBException e) {
DBWorkbench.getPlatformUI().showError("Bad query", "Can't execute query", e);
return false;
}
if (!CommonUtils.isEmpty(elements)) {
return processQueries(elements, script, newTab, false, true, queryListener, null);
} else {
return false;
}
}
public void exportDataFromQuery(@Nullable SQLScriptContext sqlScriptContext)
{
List<SQLScriptElement> elements;
ITextSelection selection = (ITextSelection) getSelectionProvider().getSelection();
if (selection.getLength() > 1) {
elements = extractScriptQueries(selection.getOffset(), selection.getLength(), true, false, true);
} else {
elements = new ArrayList<>();
elements.add(extractActiveQuery());
}
if (!elements.isEmpty()) {
processQueries(elements, false, false, true, true, null, sqlScriptContext);
} else {
DBWorkbench.getPlatformUI().showError(
"Extract data",
"Choose one or more queries to export from");
}
}
public boolean processQueries(@NotNull final List<SQLScriptElement> queries, final boolean forceScript,
boolean newTab, final boolean export, final boolean checkSession,
@Nullable final SQLQueryListener queryListener, @Nullable final SQLScriptContext context
) {
if (queries.isEmpty()) {
// Nothing to process
return false;
}
final DBPDataSourceContainer container = getDataSourceContainer();
if (checkSession) {
try {
boolean finalNewTab = newTab;
DBRProgressListener connectListener = status -> {
if (!status.isOK() || container == null || !container.isConnected()) {
DBWorkbench.getPlatformUI().showError(
SQLEditorMessages.editors_sql_error_cant_obtain_session,
null,
status);
return;
}
updateExecutionContext(() -> UIUtils.syncExec(() ->
processQueries(queries, forceScript, finalNewTab, export, false, queryListener, context)));
};
if (!checkSession(connectListener)) {
return false;
}
} catch (DBException ex) {
ResultSetViewer viewer = getActiveResultSetViewer();
if (viewer != null) {
viewer.setStatus(ex.getMessage(), DBPMessageType.ERROR);
}
DBWorkbench.getPlatformUI().showError(
SQLEditorMessages.editors_sql_error_cant_obtain_session,
ex.getMessage());
return false;
}
}
if (dataSourceContainer == null) {
return false;
}
if (!dataSourceContainer.hasModifyPermission(DBPDataSourcePermission.PERMISSION_EXECUTE_SCRIPTS)) {
DBWorkbench.getPlatformUI().showError(
SQLEditorMessages.editors_sql_error_cant_execute_query_title,
"Query execution was restricted by connection configuration");
return false;
}
SQLScriptContext scriptContext = context;
if (scriptContext == null) {
scriptContext = createScriptContext();
}
final boolean isSingleQuery = !forceScript && (queries.size() == 1);
if (isSingleQuery && queries.get(0) instanceof SQLQuery) {
SQLQuery query = (SQLQuery) queries.get(0);
boolean isDropTable = query.isDropTableDangerous();
if (query.isDeleteUpdateDangerous() || isDropTable) {
String targetName = "multiple tables";
if (query.getEntityMetadata(false) != null) {
targetName = query.getEntityMetadata(false).getEntityName();
}
if (ConfirmationDialog.showConfirmDialogEx(
ResourceBundle.getBundle(SQLEditorMessages.BUNDLE_NAME),
getSite().getShell(),
isDropTable ? SQLPreferenceConstants.CONFIRM_DROP_SQL : SQLPreferenceConstants.CONFIRM_DANGER_SQL,
ConfirmationDialog.CONFIRM,
ConfirmationDialog.WARNING,
query.getType().name(),
targetName) != IDialogConstants.OK_ID)
{
return false;
}
}
} else if (newTab && queries.size() > MAX_PARALLEL_QUERIES_NO_WARN) {
if (ConfirmationDialog.showConfirmDialogEx(
ResourceBundle.getBundle(SQLEditorMessages.BUNDLE_NAME),
getSite().getShell(),
SQLPreferenceConstants.CONFIRM_MASS_PARALLEL_SQL,
ConfirmationDialog.CONFIRM,
ConfirmationDialog.WARNING,
queries.size()) != IDialogConstants.OK_ID)
{
return false;
}
}
if (resultsSash.getMaximizedControl() != null) {
resultsSash.setMaximizedControl(null);
}
// Save editor
if (getActivePreferenceStore().getBoolean(SQLPreferenceConstants.AUTO_SAVE_ON_EXECUTE) && isDirty()) {
doSave(new NullProgressMonitor());
}
// Clear server console output
if (getActivePreferenceStore().getBoolean(SQLPreferenceConstants.CLEAR_OUTPUT_BEFORE_EXECUTE)) {
outputViewer.clearOutput();
}
boolean replaceCurrentTab = getActivePreferenceStore().getBoolean(SQLPreferenceConstants.RESULT_SET_REPLACE_CURRENT_TAB);
if (!export) {
// We only need to prompt user to close extra (unpinned) tabs if:
// 1. The user is not executing query in a new tab
// 2. The user is executing script that may open several result sets
// and replace current tab on single query execution option is not set
if (isResultSetAutoFocusEnabled && !newTab && (!isSingleQuery || (isSingleQuery && !replaceCurrentTab))) {
int tabsClosed = closeExtraResultTabs(null, true, false);
if (tabsClosed == IDialogConstants.CANCEL_ID) {
return false;
} else if (tabsClosed == IDialogConstants.NO_ID) {
newTab = true;
}
}
// Create new query processor if:
// 1. New tab is explicitly requested
// 1. Or all tabs are closed and no query processors are present
// 2. Or current query processor has pinned tabs
// 3. Or current query processor has running jobs
if (newTab || queryProcessors.isEmpty() || curQueryProcessor.hasPinnedTabs() || curQueryProcessor.getRunningJobs() > 0) {
boolean foundSuitableTab = false;
// Try to find suitable query processor among exiting ones if:
// 1. New tab is not required
// 2. The user is executing only single query
if (!newTab && isSingleQuery) {
for (QueryProcessor processor : queryProcessors) {
if (!processor.hasPinnedTabs() && processor.getRunningJobs() == 0) {
foundSuitableTab = true;
curQueryProcessor = processor;
break;
}
}
}
// Just create a new query processor
if (!foundSuitableTab) {
createQueryProcessor(true, false);
}
}
// Close all extra tabs of this query processor
// if the user is executing only single query
if (!newTab && isSingleQuery && curQueryProcessor.getResultContainers().size() > 1) {
closeExtraResultTabs(curQueryProcessor, false, true);
}
CTabItem tabItem = curQueryProcessor.getFirstResults().getTabItem();
if (tabItem != null) {
// Do not switch tab if Output tab is active
CTabItem selectedTab = resultTabs.getSelection();
if (selectedTab == null || selectedTab.getData() != outputViewer.getControl()) {
setResultTabSelection(tabItem);
}
}
}
if (curQueryProcessor == null) {
createQueryProcessor(true, true);
}
return curQueryProcessor.processQueries(
scriptContext,
queries,
forceScript,
false,
export,
!export && getActivePreferenceStore().getBoolean(SQLPreferenceConstants.RESULT_SET_CLOSE_ON_ERROR),
queryListener);
}
public boolean isActiveQueryRunning() {
return curQueryProcessor != null && curQueryProcessor.curJobRunning.get() > 0;
}
public void cancelActiveQuery() {
if (isActiveQueryRunning()) {
curQueryProcessor.cancelJob();
}
}
@NotNull
private SQLScriptContext createScriptContext() {
File localFile = EditorUtils.getLocalFileFromInput(getEditorInput());
return new SQLScriptContext(globalScriptContext, SQLEditor.this, localFile, new OutputLogWriter(), new SQLEditorParametersProvider(getSite()));
}
private void setStatus(String status, DBPMessageType messageType)
{
ResultSetViewer resultsView = getActiveResultSetViewer();
if (resultsView != null) {
resultsView.setStatus(status, messageType);
}
}
private int closeExtraResultTabs(@Nullable QueryProcessor queryProcessor, boolean confirmClose, boolean keepFirstTab) {
List<CTabItem> tabsToClose = new ArrayList<>();
for (CTabItem item : resultTabs.getItems()) {
if (item.getData() instanceof QueryResultsContainer && item.getShowClose()) {
QueryResultsContainer resultsProvider = (QueryResultsContainer)item.getData();
if (queryProcessor != null && queryProcessor != resultsProvider.queryProcessor) {
continue;
}
if (queryProcessor != null && queryProcessor.resultContainers.size() < 2 && keepFirstTab) {
// Do not remove first tab for this processor
continue;
}
tabsToClose.add(item);
} else if (item.getData() instanceof ExplainPlanViewer) {
tabsToClose.add(item);
}
}
if (tabsToClose.size() > 1 || (tabsToClose.size() == 1 && keepFirstTab)) {
int confirmResult = IDialogConstants.YES_ID;
if (confirmClose) {
confirmResult = ConfirmationDialog.showConfirmDialog(
ResourceBundle.getBundle(SQLEditorMessages.BUNDLE_NAME),
getSite().getShell(),
SQLPreferenceConstants.CONFIRM_RESULT_TABS_CLOSE,
ConfirmationDialog.QUESTION_WITH_CANCEL,
tabsToClose.size());
if (confirmResult == IDialogConstants.CANCEL_ID || confirmResult < 0) {
return IDialogConstants.CANCEL_ID;
}
}
if (confirmResult == IDialogConstants.YES_ID) {
for (int i = 0; i < tabsToClose.size(); i++) {
if (i == 0 && keepFirstTab) {
continue;
}
tabsToClose.get(i).dispose();
}
}
return confirmResult;
}
// No need to close anything
return IDialogConstants.IGNORE_ID;
}
public boolean transformQueryWithParameters(SQLQuery query) {
return createScriptContext().fillQueryParameters(query, false);
}
private boolean checkSession(DBRProgressListener onFinish)
throws DBException
{
DBPDataSourceContainer ds = getDataSourceContainer();
if (ds == null) {
throw new DBException("No active connection");
}
if (!ds.isConnected()) {
boolean doConnect = ds.getPreferenceStore().getBoolean(SQLPreferenceConstants.EDITOR_CONNECT_ON_EXECUTE);
if (doConnect) {
return checkConnected(true, onFinish);
} else {
throw new DBException("Disconnected from database");
}
}
DBPDataSource dataSource = ds.getDataSource();
if (dataSource != null && executionContextProvider == null && SQLEditorUtils.isOpenSeparateConnection(ds) && executionContext == null) {
initSeparateConnection(dataSource, () -> onFinish.onTaskFinished(Status.OK_STATUS));
return executionContext != null;
}
return true;
}
/**
* Handles datasource change action in UI
*/
private void fireDataSourceChange()
{
updateExecutionContext(null);
UIUtils.syncExec(this::onDataSourceChange);
}
private void onDataSourceChange()
{
if (resultsSash == null || resultsSash.isDisposed()) {
reloadSyntaxRules();
return;
}
DBPDataSourceContainer dsContainer = getDataSourceContainer();
if (resultTabs != null) {
DatabaseEditorUtils.setPartBackground(this, resultTabs);
Color bgColor = dsContainer == null ? null : UIUtils.getConnectionColor(dsContainer.getConnectionConfiguration());
resultsSash.setBackground(bgColor);
topBarMan.getControl().setBackground(bgColor);
bottomBarMan.getControl().setBackground(bgColor);
}
if (getSourceViewerConfiguration() instanceof SQLEditorSourceViewerConfiguration) {
((SQLEditorSourceViewerConfiguration) getSourceViewerConfiguration()).onDataSourceChange();
}
DBCExecutionContext executionContext = getExecutionContext();
if (executionContext != null) {
EditorUtils.setInputDataSource(getEditorInput(), new SQLNavigatorContext(executionContext));
}
refreshActions();
if (syntaxLoaded && lastExecutionContext == executionContext) {
return;
}
if (curResultsContainer != null) {
ResultSetViewer rsv = curResultsContainer.getResultSetController();
if (rsv != null) {
if (executionContext == null) {
rsv.setStatus(ModelMessages.error_not_connected_to_database);
} else {
rsv.setStatus(SQLEditorMessages.editors_sql_staus_connected_to + executionContext.getDataSource().getContainer().getName() + "'"); //$NON-NLS-2$
}
}
}
if (lastExecutionContext == null || executionContext == null || lastExecutionContext.getDataSource() != executionContext.getDataSource()) {
// Update command states
SQLEditorPropertyTester.firePropertyChange(SQLEditorPropertyTester.PROP_CAN_EXECUTE);
SQLEditorPropertyTester.firePropertyChange(SQLEditorPropertyTester.PROP_CAN_EXPLAIN);
reloadSyntaxRules();
}
if (dsContainer == null) {
resultsSash.setMaximizedControl(sqlEditorPanel);
} else {
if (curQueryProcessor != null && curQueryProcessor.getFirstResults().hasData()) {
resultsSash.setMaximizedControl(null);
}
}
lastExecutionContext = executionContext;
syntaxLoaded = true;
loadActivePreferenceSettings();
if (dsContainer != null) {
globalScriptContext.loadVariables(dsContainer.getDriver(), null);
} else {
globalScriptContext.clearVariables();
}
setPartName(getEditorName());
}
@Override
public void beforeConnect()
{
}
@Override
public void beforeDisconnect()
{
closeAllJobs();
}
@Override
public void dispose()
{
if (extraPresentation != null) {
extraPresentation.dispose();
extraPresentation = null;
}
// Release ds container
releaseContainer();
closeAllJobs();
final IEditorInput editorInput = getEditorInput();
IFile sqlFile = EditorUtils.getFileFromInput(editorInput);
logViewer = null;
outputViewer = null;
queryProcessors.clear();
curResultsContainer = null;
curQueryProcessor = null;
super.dispose();
if (sqlFile != null && !PlatformUI.getWorkbench().isClosing()) {
deleteFileIfEmpty(sqlFile);
}
}
private void deleteFileIfEmpty(IFile sqlFile) {
if (sqlFile == null || !sqlFile.exists()) {
return;
}
SQLPreferenceConstants.EmptyScriptCloseBehavior emptyScriptCloseBehavior = SQLPreferenceConstants.EmptyScriptCloseBehavior.getByName(
getActivePreferenceStore().getString(SQLPreferenceConstants.SCRIPT_DELETE_EMPTY));
if (emptyScriptCloseBehavior == SQLPreferenceConstants.EmptyScriptCloseBehavior.NOTHING) {
return;
}
if (!sqlFile.exists() || ResourceUtils.getFileLength(sqlFile) != 0) {
// Not empty
return;
}
try {
IProgressMonitor monitor = new NullProgressMonitor();
if (emptyScriptCloseBehavior == SQLPreferenceConstants.EmptyScriptCloseBehavior.DELETE_NEW) {
IFileState[] fileHistory = sqlFile.getHistory(monitor);
if (!ArrayUtils.isEmpty(fileHistory)) {
for (IFileState historyItem : fileHistory) {
try (InputStream contents = historyItem.getContents()) {
int cValue = contents.read();
if (cValue != -1) {
// At least once there was some content saved
return;
}
}
}
}
}
// This file is empty and never (at least during this session) had any contents.
// Drop it.
if (sqlFile.exists()) {
log.debug("Delete empty SQL script '" + sqlFile.getFullPath().toOSString() + "'");
sqlFile.delete(true, monitor);
}
} catch (Exception e) {
log.error("Error deleting empty script file", e); //$NON-NLS-1$
}
}
private void closeAllJobs()
{
for (QueryProcessor queryProcessor : queryProcessors) {
queryProcessor.closeJob();
}
}
private int getTotalQueryRunning() {
int jobsRunning = 0;
for (QueryProcessor queryProcessor : queryProcessors) {
jobsRunning += queryProcessor.curJobRunning.get();
}
return jobsRunning;
}
@Override
public void handleDataSourceEvent(final DBPEvent event)
{
final boolean dsEvent = event.getObject() == getDataSourceContainer();
final boolean objectEvent = event.getObject().getDataSource() == getDataSource();
if (dsEvent || objectEvent) {
UIUtils.asyncExec(
() -> {
switch (event.getAction()) {
case OBJECT_REMOVE:
if (dsEvent) {
setDataSourceContainer(null);
}
break;
case OBJECT_UPDATE:
case OBJECT_SELECT:
if (objectEvent) {
setPartName(getEditorName());
// Active schema was changed? Update title and tooltip
firePropertyChange(IWorkbenchPartConstants.PROP_TITLE);
}
break;
default:
break;
}
updateExecutionContext(null);
onDataSourceChange();
}
);
}
}
@Override
public void doSave(IProgressMonitor monitor) {
if (!EditorUtils.isInAutoSaveJob()) {
monitor.beginTask("Save data changes...", 1);
try {
monitor.subTask("Save '" + getPartName() + "' changes...");
SaveJob saveJob = new SaveJob();
saveJob.schedule();
// Wait until job finished
UIUtils.waitJobCompletion(saveJob);
if (!saveJob.success) {
monitor.setCanceled(true);
return;
}
} finally {
monitor.done();
}
}
if (extraPresentation instanceof ISaveablePart) {
((ISaveablePart) extraPresentation).doSave(monitor);
}
super.doSave(monitor);
updateDataSourceContainer();
}
@Override
public boolean isSaveAsAllowed()
{
return true;
}
@Override
public void doSaveAs()
{
saveToExternalFile();
}
private synchronized void doScriptAutoSave() {
if (scriptAutoSavejob == null) {
scriptAutoSavejob = new ScriptAutoSaveJob();
} else {
scriptAutoSavejob.cancel();
}
scriptAutoSavejob.schedule(1000);
}
@Override
public int promptToSaveOnClose()
{
int jobsRunning = getTotalQueryRunning();
if (jobsRunning > 0) {
log.warn("There are " + jobsRunning + " SQL job(s) still running in the editor");
if (ConfirmationDialog.showConfirmDialog(
ResourceBundle.getBundle(SQLEditorMessages.BUNDLE_NAME),
null,
SQLPreferenceConstants.CONFIRM_RUNNING_QUERY_CLOSE,
ConfirmationDialog.QUESTION,
jobsRunning) != IDialogConstants.YES_ID)
{
return ISaveablePart2.CANCEL;
}
}
for (QueryProcessor queryProcessor : queryProcessors) {
for (QueryResultsContainer resultsProvider : queryProcessor.getResultContainers()) {
ResultSetViewer rsv = resultsProvider.getResultSetController();
if (rsv != null && rsv.isDirty()) {
return rsv.promptToSaveOnClose();
}
}
}
// Cancel running jobs (if any) and close results tabs
for (QueryProcessor queryProcessor : queryProcessors) {
queryProcessor.cancelJob();
// FIXME: it is a hack (to avoid asking "Save script?" because editor is marked as dirty while queries are running)
// FIXME: make it better
queryProcessor.curJobRunning.set(0);
}
// End transaction
if (executionContext != null) {
UIServiceConnections serviceConnections = DBWorkbench.getService(UIServiceConnections.class);
if (serviceConnections != null && !serviceConnections.checkAndCloseActiveTransaction(new DBCExecutionContext[] {executionContext})) {
return ISaveablePart2.CANCEL;
}
}
// That's fine
if (isNonPersistentEditor()) {
return ISaveablePart2.NO;
}
updateDirtyFlag();
if (getActivePreferenceStore().getBoolean(SQLPreferenceConstants.AUTO_SAVE_ON_CLOSE)) {
return ISaveablePart2.YES;
}
if (super.isDirty() || (extraPresentation instanceof ISaveablePart && ((ISaveablePart) extraPresentation).isDirty())) {
return ISaveablePart2.DEFAULT;
}
return ISaveablePart2.YES;
}
protected void afterSaveToFile(File saveFile) {
try {
IFileStore fileStore = EFS.getStore(saveFile.toURI());
IEditorInput input = new FileStoreEditorInput(fileStore);
EditorUtils.setInputDataSource(input, new SQLNavigatorContext(getDataSourceContainer(), getExecutionContext()));
setInput(input);
} catch (CoreException e) {
DBWorkbench.getPlatformUI().showError("File save", "Can't open SQL editor from external file", e);
}
}
@Override
public void saveToExternalFile() {
saveToExternalFile(getScriptDirectory());
}
@Nullable
private String getScriptDirectory() {
final File inputFile = EditorUtils.getLocalFileFromInput(getEditorInput());
if (inputFile != null) {
return inputFile.getParent();
}
final DBPWorkspaceDesktop workspace = DBPPlatformDesktop.getInstance().getWorkspace();
final IFolder root = workspace.getResourceDefaultRoot(workspace.getActiveProject(), ScriptsHandlerImpl.class, false);
if (root != null) {
URI locationURI = root.getLocationURI();
if (locationURI.getScheme().equals("file")) {
return new File(locationURI).toString();
}
}
return null;
}
@Nullable
private ResultSetViewer getActiveResultSetViewer()
{
if (curResultsContainer != null) {
return curResultsContainer.getResultSetController();
}
return null;
}
private void showScriptPositionRuler(boolean show)
{
IColumnSupport columnSupport = getAdapter(IColumnSupport.class);
if (columnSupport != null) {
RulerColumnDescriptor positionColumn = RulerColumnRegistry.getDefault().getColumnDescriptor(ScriptPositionColumn.ID);
columnSupport.setColumnVisible(positionColumn, show);
}
}
private void showStatementInEditor(final SQLQuery query, final boolean select)
{
UIUtils.runUIJob("Select SQL query in editor", monitor -> {
if (isDisposed()) {
return;
}
if (select) {
selectAndReveal(query.getOffset(), query.getLength());
setStatus(query.getText(), DBPMessageType.INFORMATION);
} else {
getSourceViewer().revealRange(query.getOffset(), query.getLength());
}
});
}
@Override
public void reloadSyntaxRules() {
super.reloadSyntaxRules();
if (outputViewer != null) {
outputViewer.refreshStyles();
}
}
private QueryProcessor createQueryProcessor(boolean setSelection, boolean makeDefault)
{
final QueryProcessor queryProcessor = new QueryProcessor(makeDefault);
curQueryProcessor = queryProcessor;
curResultsContainer = queryProcessor.getFirstResults();
if (setSelection) {
CTabItem tabItem = curResultsContainer.getTabItem();
if (tabItem != null) {
setResultTabSelection(tabItem);
}
}
return queryProcessor;
}
@Override
public void preferenceChange(PreferenceChangeEvent event) {
switch (event.getProperty()) {
case ModelPreferences.SCRIPT_STATEMENT_DELIMITER:
case ModelPreferences.SCRIPT_IGNORE_NATIVE_DELIMITER:
case ModelPreferences.SCRIPT_STATEMENT_DELIMITER_BLANK:
case ModelPreferences.SQL_PARAMETERS_ENABLED:
case ModelPreferences.SQL_ANONYMOUS_PARAMETERS_MARK:
case ModelPreferences.SQL_ANONYMOUS_PARAMETERS_ENABLED:
case ModelPreferences.SQL_VARIABLES_ENABLED:
case ModelPreferences.SQL_NAMED_PARAMETERS_PREFIX:
case ModelPreferences.SQL_CONTROL_COMMAND_PREFIX:
reloadSyntaxRules();
return;
case SQLPreferenceConstants.RESULT_SET_ORIENTATION:
updateResultSetOrientation();
return;
case SQLPreferenceConstants.EDITOR_SEPARATE_CONNECTION: {
// Save current datasource (we want to keep it here)
DBPDataSource dataSource = curDataSource;
releaseExecutionContext();
// Restore cur data source (as it is reset in releaseExecutionContext)
curDataSource = dataSource;
if (dataSource != null && SQLEditorUtils.isOpenSeparateConnection(dataSource.getContainer())) {
initSeparateConnection(dataSource, null);
}
return;
}
case SQLPreferenceConstants.SCRIPT_TITLE_PATTERN:
setPartName(getEditorName());
return;
}
fireDataSourceChanged(event);
super.preferenceChange(event);
}
private void fireDataSourceChanged(PreferenceChangeEvent event) {
// Notify listeners
synchronized (listeners) {
for (SQLEditorListener listener : listeners) {
try {
listener.onDataSourceChanged(event);
} catch (Throwable ex) {
ex.printStackTrace();
}
}
}
}
public enum ResultSetOrientation {
HORIZONTAL(SWT.VERTICAL, SQLEditorMessages.sql_editor_result_set_orientation_horizontal, SQLEditorMessages.sql_editor_result_set_orientation_horizontal_tip, true),
VERTICAL(SWT.HORIZONTAL, SQLEditorMessages.sql_editor_result_set_orientation_vertical, SQLEditorMessages.sql_editor_result_set_orientation_vertical_tip, true),
DETACHED(SWT.VERTICAL, SQLEditorMessages.sql_editor_result_set_orientation_detached, SQLEditorMessages.sql_editor_result_set_orientation_detached_tip, false);
private final int sashOrientation;
private final String label;
private final String description;
private final boolean supported;
ResultSetOrientation(int sashOrientation, String label, String description, boolean supported) {
this.sashOrientation = sashOrientation;
this.label = label;
this.description = description;
this.supported = supported;
}
public int getSashOrientation() {
return sashOrientation;
}
public String getLabel() {
return label;
}
public String getDescription() {
return description;
}
public boolean isSupported() {
return supported;
}
}
public static class ResultSetOrientationMenuContributor extends CompoundContributionItem
{
@Override
protected IContributionItem[] getContributionItems() {
IEditorPart activeEditor = UIUtils.getActiveWorkbenchWindow().getActivePage().getActiveEditor();
if (!(activeEditor instanceof SQLEditorBase)) {
return new IContributionItem[0];
}
final DBPPreferenceStore preferenceStore = DBWorkbench.getPlatform().getPreferenceStore();
String curPresentation = preferenceStore.getString(SQLPreferenceConstants.RESULT_SET_ORIENTATION);
ResultSetOrientation[] orientations = ResultSetOrientation.values();
List<IContributionItem> items = new ArrayList<>(orientations.length);
for (final ResultSetOrientation orientation : orientations) {
Action action = new Action(orientation.getLabel(), Action.AS_RADIO_BUTTON) {
@Override
public void run() {
preferenceStore.setValue(SQLPreferenceConstants.RESULT_SET_ORIENTATION, orientation.name());
PrefUtils.savePreferenceStore(preferenceStore);
}
};
action.setDescription(orientation.getDescription());
if (!orientation.isSupported()) {
action.setEnabled(false);
}
if (orientation.name().equals(curPresentation)) {
action.setChecked(true);
}
items.add(new ActionContributionItem(action));
}
return items.toArray(new IContributionItem[0]);
}
}
public class QueryProcessor implements SQLResultsConsumer, ISmartTransactionManager {
private volatile SQLQueryJob curJob;
private AtomicInteger curJobRunning = new AtomicInteger(0);
private final List<QueryResultsContainer> resultContainers = new ArrayList<>();
private volatile DBDDataReceiver curDataReceiver = null;
QueryProcessor(boolean makeDefault) {
// Create first (default) results provider
if (makeDefault) {
queryProcessors.add(0, this);
} else {
queryProcessors.add(this);
}
createResultsProvider(0, makeDefault);
}
int getRunningJobs() {
return curJobRunning.get();
}
private QueryResultsContainer createResultsProvider(int resultSetNumber, boolean makeDefault) {
QueryResultsContainer resultsProvider = new QueryResultsContainer(this, resultSetNumber, getMaxResultsTabIndex() + 1, makeDefault);
resultContainers.add(resultsProvider);
return resultsProvider;
}
private QueryResultsContainer createResultsProvider(DBSDataContainer dataContainer) {
QueryResultsContainer resultsProvider = new QueryResultsContainer(this, resultContainers.size(), getMaxResultsTabIndex(), dataContainer);
resultContainers.add(resultsProvider);
return resultsProvider;
}
public boolean hasPinnedTabs() {
for (QueryResultsContainer container : resultContainers) {
if (container.isPinned()) {
return true;
}
}
return false;
}
@NotNull
QueryResultsContainer getFirstResults()
{
return resultContainers.get(0);
}
@Nullable
QueryResultsContainer getResults(SQLQuery query) {
for (QueryResultsContainer provider : resultContainers) {
if (provider.query == query) {
return provider;
}
}
return null;
}
List<QueryResultsContainer> getResultContainers() {
return resultContainers;
}
private void closeJob()
{
final SQLQueryJob job = curJob;
if (job != null) {
if (job.getState() == Job.RUNNING) {
job.cancel();
}
curJob = null;
if (job.isJobOpen()) {
RuntimeUtils.runTask(monitor -> {
job.closeJob();
}, "Close SQL job", 2000, true);
}
}
}
public void cancelJob() {
for (QueryResultsContainer rc : resultContainers) {
rc.viewer.cancelJobs();
}
final SQLQueryJob job = curJob;
if (job != null) {
if (job.getState() == Job.RUNNING) {
job.cancel();
}
}
}
boolean processQueries(SQLScriptContext scriptContext, final List<SQLScriptElement> queries, boolean forceScript, final boolean fetchResults, boolean export, boolean closeTabOnError, SQLQueryListener queryListener)
{
if (queries.isEmpty()) {
// Nothing to process
return false;
}
if (curJobRunning.get() > 0) {
DBWorkbench.getPlatformUI().showError(
SQLEditorMessages.editors_sql_error_cant_execute_query_title,
SQLEditorMessages.editors_sql_error_cant_execute_query_message);
return false;
}
final DBCExecutionContext executionContext = getExecutionContext();
if (executionContext == null) {
DBWorkbench.getPlatformUI().showError(
SQLEditorMessages.editors_sql_error_cant_execute_query_title,
ModelMessages.error_not_connected_to_database);
return false;
}
final boolean isSingleQuery = !forceScript && (queries.size() == 1);
// Prepare execution job
{
showScriptPositionRuler(true);
QueryResultsContainer resultsContainer = getFirstResults();
SQLEditorQueryListener listener = new SQLEditorQueryListener(this, closeTabOnError);
if (queryListener != null) {
listener.setExtListener(queryListener);
}
if (export) {
List<IDataTransferProducer<?>> producers = new ArrayList<>();
for (int i = 0; i < queries.size(); i++) {
SQLScriptElement element = queries.get(i);
if (element instanceof SQLControlCommand) {
try {
scriptContext.executeControlCommand((SQLControlCommand) element);
} catch (DBException e) {
DBWorkbench.getPlatformUI().showError("Command error", "Error processing control command", e);
}
} else {
SQLQuery query = (SQLQuery) element;
scriptContext.fillQueryParameters(query, false);
SQLQueryDataContainer dataContainer = new SQLQueryDataContainer(SQLEditor.this, query, scriptContext, log);
producers.add(new DatabaseTransferProducer(dataContainer, null));
}
}
DataTransferWizard.openWizard(
getSite().getWorkbenchWindow(),
producers,
null,
new StructuredSelection(this));
} else {
final SQLQueryJob job = new SQLQueryJob(
getSite(),
isSingleQuery ? SQLEditorMessages.editors_sql_job_execute_query : SQLEditorMessages.editors_sql_job_execute_script,
executionContext,
resultsContainer,
queries,
scriptContext,
this,
listener);
if (isSingleQuery) {
resultsContainer.query = queries.get(0);
closeJob();
curJob = job;
ResultSetViewer rsv = resultsContainer.getResultSetController();
if (rsv != null) {
rsv.resetDataFilter(false);
rsv.resetHistory();
rsv.refresh();
}
} else {
if (fetchResults) {
job.setFetchResultSets(true);
}
job.schedule();
curJob = job;
}
}
}
return true;
}
public boolean isDirty() {
for (QueryResultsContainer resultsProvider : resultContainers) {
ResultSetViewer rsv = resultsProvider.getResultSetController();
if (rsv != null && rsv.isDirty()) {
return true;
}
}
return false;
}
void removeResults(QueryResultsContainer resultsContainer) {
resultContainers.remove(resultsContainer);
if (resultContainers.isEmpty()) {
queryProcessors.remove(this);
if (curQueryProcessor == this) {
if (queryProcessors.isEmpty()) {
curQueryProcessor = null;
curResultsContainer = null;
} else {
curQueryProcessor = queryProcessors.get(0);
curResultsContainer = curQueryProcessor.getFirstResults();
}
}
}
}
@Nullable
@Override
public DBDDataReceiver getDataReceiver(final SQLQuery statement, final int resultSetNumber) {
if (curDataReceiver != null) {
return curDataReceiver;
}
final boolean isStatsResult = (statement != null && statement.getData() == SQLQueryJob.STATS_RESULTS);
// if (isStatsResult) {
// // Maybe it was already open
// for (QueryResultsProvider provider : resultContainers) {
// if (provider.query != null && provider.query.getData() == SQLQueryJob.STATS_RESULTS) {
// resultSetNumber = provider.resultSetNumber;
// break;
// }
// }
// }
if (resultSetNumber >= resultContainers.size() && !isDisposed()) {
// Open new results processor in UI thread
UIUtils.syncExec(() -> createResultsProvider(resultSetNumber, false));
}
if (resultSetNumber >= resultContainers.size()) {
// Editor seems to be disposed - no data receiver
return null;
}
final QueryResultsContainer resultsProvider = resultContainers.get(resultSetNumber);
if (statement != null && !resultTabs.isDisposed()) {
resultsProvider.query = statement;
resultsProvider.lastGoodQuery = statement;
String tabName = null;
String queryText = CommonUtils.truncateString(statement.getText(), 1000);
DBPDataSourceContainer dataSourceContainer = getDataSourceContainer();
String toolTip =
"Connection: " + (dataSourceContainer == null ? "N/A" : dataSourceContainer.getName()) + GeneralUtils.getDefaultLineSeparator() +
"Time: " + new SimpleDateFormat(DBConstants.DEFAULT_TIMESTAMP_FORMAT).format(new Date()) + GeneralUtils.getDefaultLineSeparator() +
"Query: " + (CommonUtils.isEmpty(queryText) ? "N/A" : queryText);
// Special statements (not real statements) have their name in data
if (isStatsResult) {
tabName = SQLEditorMessages.editors_sql_statistics;
int queryIndex = queryProcessors.indexOf(QueryProcessor.this);
tabName += " " + (queryIndex + 1);
}
String finalTabName = tabName;
UIUtils.asyncExec(() -> resultsProvider.updateResultsName(finalTabName, toolTip));
}
ResultSetViewer rsv = resultsProvider.getResultSetController();
return rsv == null ? null : rsv.getDataReceiver();
}
@Override
public boolean isSmartAutoCommit() {
return SQLEditor.this.isSmartAutoCommit();
}
@Override
public void setSmartAutoCommit(boolean smartAutoCommit) {
SQLEditor.this.setSmartAutoCommit(smartAutoCommit);
}
}
public class QueryResultsContainer implements
DBSDataContainer,
IResultSetContainer,
IResultSetValueReflector,
IResultSetListener,
IResultSetContainerExt,
SQLQueryContainer,
ISmartTransactionManager,
IQueryExecuteController {
private final QueryProcessor queryProcessor;
private final ResultSetViewer viewer;
private int resultSetNumber;
private final int resultSetIndex;
private SQLScriptElement query = null;
private SQLScriptElement lastGoodQuery = null;
// Data container and filter are non-null only in case of associations navigation
private DBSDataContainer dataContainer;
private CTabItem resultsTab;
private String tabName;
private QueryResultsContainer(QueryProcessor queryProcessor, int resultSetNumber, int resultSetIndex, boolean makeDefault) {
this.queryProcessor = queryProcessor;
this.resultSetNumber = resultSetNumber;
this.resultSetIndex = resultSetIndex;
boolean detachedViewer = false;
SQLResultsView sqlView = null;
if (detachedViewer) {
try {
sqlView = (SQLResultsView) getSite().getPage().showView(SQLResultsView.VIEW_ID, null, IWorkbenchPage.VIEW_CREATE);
} catch (Throwable e) {
DBWorkbench.getPlatformUI().showError("Detached results", "Can't open results view", e);
}
}
if (sqlView != null) {
// Detached results viewer
sqlView.setContainer(this);
this.viewer = sqlView.getViewer();
} else {
// Embedded results viewer
this.viewer = new ResultSetViewer(resultTabs, getSite(), this);
this.viewer.addListener(this);
int tabCount = resultTabs.getItemCount();
int tabIndex = 0;
if (!makeDefault) {
for (int i = tabCount; i > 0; i--) {
if (resultTabs.getItem(i - 1).getData() instanceof QueryResultsContainer) {
tabIndex = i;
break;
}
}
}
resultsTab = new CTabItem(resultTabs, SWT.NONE, tabIndex);
resultsTab.setImage(IMG_DATA_GRID);
resultsTab.setData(this);
resultsTab.setShowClose(true);
resultsTab.setText(getResultsTabName(resultSetNumber, getQueryIndex(), null));
CSSUtils.setCSSClass(resultsTab, DBStyles.COLORED_BY_CONNECTION_TYPE);
resultsTab.setControl(viewer.getControl());
resultsTab.addDisposeListener(resultTabDisposeListener);
UIUtils.disposeControlOnItemDispose(resultsTab);
}
viewer.getControl().addDisposeListener(e -> {
QueryResultsContainer.this.queryProcessor.removeResults(QueryResultsContainer.this);
if (QueryResultsContainer.this == curResultsContainer) {
curResultsContainer = null;
}
});
}
QueryResultsContainer(QueryProcessor queryProcessor, int resultSetNumber, int resultSetIndex, DBSDataContainer dataContainer) {
this(queryProcessor, resultSetNumber, resultSetIndex, false);
this.dataContainer = dataContainer;
updateResultsName(getResultsTabName(resultSetNumber, 0, dataContainer.getName()), null);
}
private CTabItem getTabItem() {
return resultsTab;
}
public int getResultSetIndex() {
return resultSetIndex;
}
public int getQueryIndex() {
return queryProcessors.indexOf(queryProcessor);
}
void updateResultsName(String resultSetName, String toolTip) {
if (resultTabs == null || resultTabs.isDisposed()) {
return;
}
if (CommonUtils.isEmpty(resultSetName)) {
resultSetName = tabName;
}
CTabItem tabItem = getTabItem();
if (tabItem != null && !tabItem.isDisposed()) {
if (!CommonUtils.isEmpty(resultSetName)) {
tabItem.setText(resultSetName);
}
if (toolTip != null) {
tabItem.setToolTipText(toolTip);
}
}
}
boolean isPinned() {
CTabItem tabItem = getTabItem();
return tabItem != null && !tabItem.isDisposed() && !tabItem.getShowClose();
}
void setPinned(boolean pinned) {
CTabItem tabItem = getTabItem();
if (tabItem != null) {
tabItem.setShowClose(!pinned);
tabItem.setImage(pinned ? IMG_DATA_GRID_LOCKED : IMG_DATA_GRID);
}
}
@NotNull
@Override
public DBPProject getProject() {
return SQLEditor.this.getProject();
}
@Override
public DBCExecutionContext getExecutionContext() {
return SQLEditor.this.getExecutionContext();
}
@Nullable
@Override
public ResultSetViewer getResultSetController()
{
return viewer;
}
boolean hasData() {
return viewer != null && viewer.hasData();
}
@Nullable
@Override
public DBSDataContainer getDataContainer()
{
return this;
}
@Override
public boolean isReadyToRun()
{
return queryProcessor.curJob == null || queryProcessor.curJobRunning.get() <= 0;
}
@Override
public void openNewContainer(DBRProgressMonitor monitor, @NotNull DBSDataContainer dataContainer, @NotNull DBDDataFilter newFilter) {
UIUtils.syncExec(() -> {
QueryResultsContainer resultsProvider = queryProcessor.createResultsProvider(dataContainer);
CTabItem tabItem = resultsProvider.getTabItem();
if (tabItem != null) {
tabItem.getParent().setSelection(tabItem);
}
setActiveResultsContainer(resultsProvider);
resultsProvider.viewer.refreshWithFilter(newFilter);
});
}
@Override
public IResultSetDecorator createResultSetDecorator() {
return new QueryResultsDecorator() {
@Override
public String getEmptyDataDescription() {
String execQuery = ActionUtils.findCommandDescription(SQLEditorCommands.CMD_EXECUTE_STATEMENT, getSite(), true);
String execScript = ActionUtils.findCommandDescription(SQLEditorCommands.CMD_EXECUTE_SCRIPT, getSite(), true);
return NLS.bind(ResultSetMessages.sql_editor_resultset_filter_panel_control_execute_to_see_reslut, execQuery, execScript);
}
};
}
@Override
public String[] getSupportedFeatures()
{
if (dataContainer != null) {
return dataContainer.getSupportedFeatures();
}
List<String> features = new ArrayList<>(3);
features.add(FEATURE_DATA_SELECT);
if (query instanceof SQLQuery && ((SQLQuery) query).isModifiyng()) {
features.add(FEATURE_DATA_MODIFIED_ON_REFRESH);
}
features.add(FEATURE_DATA_COUNT);
if (getQueryResultCounts() <= 1) {
features.add(FEATURE_DATA_FILTER);
}
return features.toArray(new String[0]);
}
@NotNull
@Override
public DBCStatistics readData(@NotNull DBCExecutionSource source, @NotNull DBCSession session, @NotNull DBDDataReceiver dataReceiver, DBDDataFilter dataFilter, long firstRow, long maxRows, long flags, int fetchSize) throws DBCException
{
if (dataContainer != null) {
return dataContainer.readData(source, session, dataReceiver, dataFilter, firstRow, maxRows, flags, fetchSize);
}
final SQLQueryJob job = queryProcessor.curJob;
if (job == null) {
throw new DBCException("No active query - can't read data");
}
if (this.query instanceof SQLQuery) {
SQLQuery query = (SQLQuery) this.query;
if (query.getResultsMaxRows() >= 0) {
firstRow = query.getResultsOffset();
maxRows = query.getResultsMaxRows();
}
}
try {
if (dataReceiver != viewer.getDataReceiver()) {
// Some custom receiver. Probably data export
queryProcessor.curDataReceiver = dataReceiver;
} else {
queryProcessor.curDataReceiver = null;
}
// Count number of results for this query. If > 1 then we will refresh them all at once
int resultCounts = getQueryResultCounts();
if (resultCounts <= 1 && resultSetNumber > 0) {
job.setFetchResultSetNumber(resultSetNumber);
} else {
job.setFetchResultSetNumber(-1);
}
job.setResultSetLimit(firstRow, maxRows);
job.setDataFilter(dataFilter);
job.setFetchSize(fetchSize);
job.setFetchFlags(flags);
job.extractData(session, this.query, resultCounts > 1 ? 0 : resultSetNumber);
lastGoodQuery = job.getLastGoodQuery();
return job.getStatistics();
} finally {
// Nullify custom data receiver
queryProcessor.curDataReceiver = null;
}
}
private int getQueryResultCounts() {
int resultCounts = 0;
for (QueryResultsContainer qrc : queryProcessor.resultContainers) {
if (qrc.query == query) {
resultCounts++;
}
}
return resultCounts;
}
@Override
public long countData(@NotNull DBCExecutionSource source, @NotNull DBCSession session, @Nullable DBDDataFilter dataFilter, long flags)
throws DBCException
{
if (dataContainer != null) {
return dataContainer.countData(source, session, dataFilter, DBSDataContainer.FLAG_NONE);
}
DBPDataSource dataSource = getDataSource();
if (dataSource == null) {
throw new DBCException("Query transform is not supported by datasource");
}
if (!(query instanceof SQLQuery)) {
throw new DBCException("Can't count rows for control command");
}
try {
SQLQuery countQuery = new SQLQueryTransformerCount().transformQuery(dataSource, getSyntaxManager(), (SQLQuery) query);
if (!CommonUtils.isEmpty(countQuery.getParameters())) {
countQuery.setParameters(parseQueryParameters(countQuery));
}
try (DBCStatement dbStatement = DBUtils.makeStatement(source, session, DBCStatementType.SCRIPT, countQuery, 0, 0)) {
if (dbStatement.executeStatement()) {
try (DBCResultSet rs = dbStatement.openResultSet()) {
if (rs.nextRow()) {
List<DBCAttributeMetaData> resultAttrs = rs.getMeta().getAttributes();
Object countValue = null;
if (resultAttrs.size() == 1) {
countValue = rs.getAttributeValue(0);
} else {
// In some databases (Influx?) SELECT count(*) produces multiple columns. Try to find first one with 'count' in its name.
for (int i = 0; i < resultAttrs.size(); i++) {
DBCAttributeMetaData ma = resultAttrs.get(i);
if (ma.getName().toLowerCase(Locale.ENGLISH).contains("count")) {
countValue = rs.getAttributeValue(i);
break;
}
}
}
if (countValue instanceof Map && ((Map<?, ?>) countValue).size() == 1) {
// For document-based DBs
Object singleValue = ((Map<?, ?>) countValue).values().iterator().next();
if (singleValue instanceof Number) {
countValue = singleValue;
}
}
if (countValue instanceof Number) {
return ((Number) countValue).longValue();
} else {
throw new DBCException("Unexpected row count value: " + countValue);
}
} else {
throw new DBCException("Row count result is empty");
}
}
} else {
throw new DBCException("Row count query didn't return any value");
}
}
} catch (DBException e) {
throw new DBCException("Error executing row count", e);
}
}
@Nullable
@Override
public String getDescription()
{
if (dataContainer != null) {
return dataContainer.getDescription();
} else {
return SQLEditorMessages.editors_sql_description;
}
}
@Nullable
@Override
public DBSObject getParentObject()
{
return getDataSource();
}
@Nullable
@Override
public DBPDataSource getDataSource()
{
return SQLEditor.this.getDataSource();
}
@Override
public boolean isPersisted() {
return dataContainer == null || dataContainer.isPersisted();
}
@NotNull
@Override
public String getName()
{
if (dataContainer != null) {
return dataContainer.getName();
}
String name = lastGoodQuery != null ?
lastGoodQuery.getOriginalText() :
(query == null ? null : query.getOriginalText());
if (name == null) {
name = "SQL";
}
return name;
}
@Nullable
@Override
public DBPDataSourceContainer getDataSourceContainer() {
return SQLEditor.this.getDataSourceContainer();
}
@Override
public String toString() {
if (dataContainer != null) {
return dataContainer.toString();
}
return query == null ?
"SQL Query / " + SQLEditor.this.getEditorInput().getName() :
query.getOriginalText();
}
@Override
public void handleResultSetLoad() {
}
@Override
public void handleResultSetChange() {
updateDirtyFlag();
}
@Override
public void handleResultSetSelectionChange(SelectionChangedEvent event) {
}
@Override
public void onModelPrepared() {
notifyOnDataListeners(this);
}
@Override
public SQLScriptContext getScriptContext() {
return SQLEditor.this.getGlobalScriptContext();
}
@Override
public SQLScriptElement getQuery() {
return query;
}
@Override
public Map<String, Object> getQueryParameters() {
return globalScriptContext.getAllParameters();
}
@Override
public boolean isSmartAutoCommit() {
return SQLEditor.this.isSmartAutoCommit();
}
@Override
public void setSmartAutoCommit(boolean smartAutoCommit) {
SQLEditor.this.setSmartAutoCommit(smartAutoCommit);
}
public void setTabName(String tabName) {
this.tabName = tabName;
resultsTab.setText(tabName);
}
@Override
public void insertCurrentCellValue(DBDAttributeBinding attributeBinding, Object cellValue, String stringValue) {
StyledText textWidget = getTextViewer() == null ? null : getTextViewer().getTextWidget();
if (textWidget != null) {
String sqlValue;
if (getDataSource() != null) {
sqlValue = SQLUtils.convertValueToSQL(getDataSource(), attributeBinding, cellValue);
} else {
sqlValue = stringValue;
}
textWidget.insert(sqlValue);
textWidget.setCaretOffset(textWidget.getCaretOffset() + sqlValue.length());
textWidget.setFocus();
}
}
@Override
public void forceDataReadCancel(Throwable error) {
for (QueryProcessor processor : queryProcessors) {
SQLQueryJob job = processor.curJob;
if (job != null) {
SQLQueryResult currentQueryResult = job.getCurrentQueryResult();
if (currentQueryResult == null) {
currentQueryResult = new SQLQueryResult(new SQLQuery(null, ""));
}
currentQueryResult.setError(error);
job.notifyQueryExecutionEnd(currentQueryResult);
}
}
}
@Override
public void handleExecuteResult(DBCExecutionResult result) {
dumpQueryServerOutput(result);
}
@Override
public void showCurrentError() {
if (getLastQueryErrorPosition() > -1) {
getSelectionProvider().setSelection(new TextSelection(getLastQueryErrorPosition(), 0));
setFocus();
}
}
}
private int getMaxResultsTabIndex() {
int maxIndex = 0;
for (CTabItem tab : resultTabs.getItems()) {
if (tab.getData() instanceof QueryResultsContainer) {
maxIndex = Math.max(maxIndex, ((QueryResultsContainer) tab.getData()).getResultSetIndex());
}
}
return maxIndex;
}
private String getResultsTabName(int resultSetNumber, int queryIndex, String name) {
String tabName = name;
if (CommonUtils.isEmpty(tabName)) {
tabName = SQLEditorMessages.editors_sql_data_grid;
}
tabName += " " + (queryIndex + 1);
if (resultSetNumber > 0) {
tabName += " (" + (resultSetNumber + 1) + ")";
}
return tabName;
}
private class SQLEditorQueryListener implements SQLQueryListener {
private final QueryProcessor queryProcessor;
private boolean scriptMode;
private long lastUIUpdateTime;
private final ITextSelection originalSelection = (ITextSelection) getSelectionProvider().getSelection();
private int topOffset, visibleLength;
private boolean closeTabOnError;
private SQLQueryListener extListener;
private SQLEditorQueryListener(QueryProcessor queryProcessor, boolean closeTabOnError) {
this.queryProcessor = queryProcessor;
this.closeTabOnError = closeTabOnError;
}
public SQLQueryListener getExtListener() {
return extListener;
}
public void setExtListener(SQLQueryListener extListener) {
this.extListener = extListener;
}
@Override
public void onStartScript() {
try {
lastUIUpdateTime = -1;
scriptMode = true;
UIUtils.asyncExec(() -> {
if (isDisposed()) {
return;
}
if (getActivePreferenceStore().getBoolean(SQLPreferenceConstants.MAXIMIZE_EDITOR_ON_SCRIPT_EXECUTE)
&& isResultSetAutoFocusEnabled) {
resultsSash.setMaximizedControl(sqlEditorPanel);
}
clearProblems(null);
});
} finally {
if (extListener != null) extListener.onStartScript();
}
}
@Override
public void onStartQuery(DBCSession session, final SQLQuery query) {
try {
boolean isInExecute = getTotalQueryRunning() > 0;
if (!isInExecute) {
UIUtils.asyncExec(() -> {
setTitleImage(DBeaverIcons.getImage(UIIcon.SQL_SCRIPT_EXECUTE));
updateDirtyFlag();
if (!scriptMode) {
clearProblems(query);
}
});
}
queryProcessor.curJobRunning.incrementAndGet();
synchronized (runningQueries) {
runningQueries.add(query);
}
if (lastUIUpdateTime < 0 || System.currentTimeMillis() - lastUIUpdateTime > SCRIPT_UI_UPDATE_PERIOD) {
UIUtils.asyncExec(() -> {
TextViewer textViewer = getTextViewer();
if (textViewer != null) {
topOffset = textViewer.getTopIndexStartOffset();
visibleLength = textViewer.getBottomIndexEndOffset() - topOffset;
}
});
if (scriptMode) {
showStatementInEditor(query, false);
}
lastUIUpdateTime = System.currentTimeMillis();
}
} finally {
if (extListener != null) extListener.onStartQuery(session, query);
}
}
@Override
public void onEndQuery(final DBCSession session, final SQLQueryResult result, DBCStatistics statistics) {
try {
synchronized (runningQueries) {
runningQueries.remove(result.getStatement());
}
queryProcessor.curJobRunning.decrementAndGet();
if (getTotalQueryRunning() <= 0) {
UIUtils.asyncExec(() -> {
if (isDisposed()) {
return;
}
setTitleImage(editorImage);
updateDirtyFlag();
});
}
if (isDisposed()) {
return;
}
UIUtils.runUIJob("Process SQL query result", monitor -> {
if (isDisposed()) {
return;
}
// Finish query
processQueryResult(monitor, result, statistics);
// Update dirty flag
updateDirtyFlag();
refreshActions();
});
} finally {
if (extListener != null) {
extListener.onEndQuery(session, result, statistics);
}
}
}
private void processQueryResult(DBRProgressMonitor monitor, SQLQueryResult result, DBCStatistics statistics) {
dumpQueryServerOutput(result);
if (!scriptMode) {
runPostExecuteActions(result);
}
SQLQuery query = result.getStatement();
Throwable error = result.getError();
ISelectionProvider selectionProvider = getSelectionProvider();
if (selectionProvider == null) {
// Disposed?
return;
}
if (error != null) {
setStatus(GeneralUtils.getFirstMessage(error), DBPMessageType.ERROR);
SQLQuery originalQuery = curResultsContainer.query instanceof SQLQuery ? (SQLQuery) curResultsContainer.query : null; // SQLQueryResult stores modified query
if (!visualizeQueryErrors(monitor, query, error, originalQuery)) {
int errorQueryOffset = query.getOffset();
int errorQueryLength = query.getLength();
if (errorQueryOffset >= 0 && errorQueryLength > 0) {
if (!addProblem(GeneralUtils.getFirstMessage(error), new Position(errorQueryOffset, errorQueryLength))) {
if (scriptMode) {
selectionProvider.setSelection(new TextSelection(errorQueryOffset, errorQueryLength));
} else {
selectionProvider.setSelection(originalSelection);
}
}
setLastQueryErrorPosition(errorQueryOffset);
}
}
} else if (!scriptMode && getActivePreferenceStore().getBoolean(SQLPreferenceConstants.RESET_CURSOR_ON_EXECUTE)) {
selectionProvider.setSelection(originalSelection);
}
notifyOnQueryResultListeners(curResultsContainer, result);
// Get results window (it is possible that it was closed till that moment
{
for (QueryResultsContainer cr : queryProcessor.resultContainers) {
cr.viewer.updateFiltersText(false);
}
if (!result.hasError() && !queryProcessor.resultContainers.isEmpty()) {
if (activeResultsTab != null && !activeResultsTab.isDisposed()) {
setResultTabSelection(activeResultsTab);
} else {
setResultTabSelection(queryProcessor.resultContainers.get(0).resultsTab);
}
}
// Set tab names by query results names
if (scriptMode || queryProcessor.getResultContainers().size() > 0) {
int queryIndex = queryProcessors.indexOf(queryProcessor);
int resultsIndex = 0;
for (QueryResultsContainer results : queryProcessor.resultContainers) {
if (results.query != query) {
// This happens when query results is statistics tab
// in that case we need to update tab selection and
// select new statistics tab
// see #16605
setResultTabSelection(results.resultsTab);
continue;
}
if (resultsIndex < result.getExecuteResults().size()) {
SQLQueryResult.ExecuteResult executeResult = result.getExecuteResults(resultsIndex, true);
String resultSetName = results.tabName;
if (CommonUtils.isEmpty(resultSetName)) {
resultSetName = getResultsTabName(results.resultSetNumber, queryIndex, executeResult.getResultSetName());
results.updateResultsName(resultSetName, null);
setResultTabSelection(results.resultsTab);
}
ResultSetViewer resultSetViewer = results.getResultSetController();
if (resultSetViewer != null) {
resultSetViewer.getModel().setStatistics(statistics);
}
}
resultsIndex++;
}
}
}
// Close tab on error
if (closeTabOnError && error != null) {
CTabItem tabItem = queryProcessor.getFirstResults().getTabItem();
if (tabItem != null && tabItem.getShowClose()) {
tabItem.dispose();
}
}
// Beep
if (dataSourceContainer != null && !scriptMode && getActivePreferenceStore().getBoolean(SQLPreferenceConstants.BEEP_ON_QUERY_END)) {
Display.getCurrent().beep();
}
// Notify agent
if (result.getQueryTime() > DBWorkbench.getPlatformUI().getLongOperationTimeout() * 1000) {
DBWorkbench.getPlatformUI().notifyAgent(
"Query completed [" + getEditorInput().getName() + "]" + GeneralUtils.getDefaultLineSeparator() +
CommonUtils.truncateString(query.getText(), 200), !result.hasError() ? IStatus.INFO : IStatus.ERROR);
}
}
@Override
public void onEndScript(final DBCStatistics statistics, final boolean hasErrors) {
try {
if (isDisposed()) {
return;
}
runPostExecuteActions(null);
UIUtils.asyncExec(() -> {
if (isDisposed()) {
// Editor closed
return;
}
resultsSash.setMaximizedControl(null);
if (!hasErrors) {
getSelectionProvider().setSelection(originalSelection);
}
QueryResultsContainer results = queryProcessor.getFirstResults();
ResultSetViewer viewer = results.getResultSetController();
if (viewer != null) {
viewer.getModel().setStatistics(statistics);
viewer.updateStatusMessage();
}
});
} finally {
if (extListener != null) extListener.onEndScript(statistics, hasErrors);
}
}
}
public void updateDirtyFlag() {
firePropertyChange(IWorkbenchPartConstants.PROP_DIRTY);
}
private class FindReplaceTarget extends DynamicFindReplaceTarget {
private IFindReplaceTarget previousTarget = null;
@Override
public IFindReplaceTarget getTarget() {
//getTarget determines current composite used for find/replace
//We should update it, when we focus on the other panels or output view
ResultSetViewer rsv = getActiveResultSetViewer();
TextViewer textViewer = getTextViewer();
boolean focusInEditor = textViewer != null && textViewer.getTextWidget() != null && textViewer.getTextWidget().isFocusControl();
if (!focusInEditor) {
if (rsv == null && !outputViewer.getText().isFocusControl() && previousTarget != null) {
focusInEditor = textViewer != null && previousTarget.equals(textViewer.getFindReplaceTarget());
}
}
if (!focusInEditor) {
//Focus is on presentation we need to find a class for it
if (rsv != null && rsv.getActivePresentation().getControl().isFocusControl()) {
previousTarget = rsv.getAdapter(IFindReplaceTarget.class);
} else if (outputViewer.getControl().isFocusControl()) {
//Output viewer is just StyledText we use StyledTextFindReplace
previousTarget = new StyledTextFindReplaceTarget(outputViewer.getText());
}
} else {
previousTarget = textViewer.getFindReplaceTarget();
}
return previousTarget;
}
}
private class DynamicSelectionProvider extends CompositeSelectionProvider {
private boolean lastFocusInEditor = true;
@Override
public ISelectionProvider getProvider() {
if (extraPresentation != null && getExtraPresentationState() == SQLEditorPresentation.ActivationType.VISIBLE) {
if (getExtraPresentationControl().isFocusControl()) {
ISelectionProvider selectionProvider = extraPresentation.getSelectionProvider();
if (selectionProvider != null) {
return selectionProvider;
}
}
}
ResultSetViewer rsv = getActiveResultSetViewer();
TextViewer textViewer = getTextViewer();
boolean focusInEditor = textViewer != null && textViewer.getTextWidget().isFocusControl();
if (!focusInEditor) {
if (rsv != null && rsv.getActivePresentation().getControl().isFocusControl()) {
focusInEditor = false;
} else {
focusInEditor = lastFocusInEditor;
}
}
lastFocusInEditor = focusInEditor;
if (!focusInEditor && rsv != null) {
return rsv;
} else if (textViewer != null) {
return textViewer.getSelectionProvider();
} else {
return null;
}
}
}
private void dumpQueryServerOutput(@Nullable DBCExecutionResult result) {
final DBCExecutionContext executionContext = getExecutionContext();
if (executionContext != null) {
final DBPDataSource dataSource = executionContext.getDataSource();
// Dump server output
DBCServerOutputReader outputReader = DBUtils.getAdapter(DBCServerOutputReader.class, dataSource);
if (outputReader == null && result != null) {
outputReader = new DefaultServerOutputReader();
}
if (outputReader != null && outputReader.isServerOutputEnabled()) {
synchronized (serverOutputs) {
serverOutputs.add(new ServerOutputInfo(outputReader, executionContext, result));
}
}
}
}
private void runPostExecuteActions(@Nullable SQLQueryResult result) {
showResultsPanel(true);
final DBCExecutionContext executionContext = getExecutionContext();
if (executionContext != null) {
// Refresh active object
if (result == null || !result.hasError() && getActivePreferenceStore().getBoolean(SQLPreferenceConstants.REFRESH_DEFAULTS_AFTER_EXECUTE)) {
DBCExecutionContextDefaults<?,?> contextDefaults = executionContext.getContextDefaults();
if (contextDefaults != null) {
new AbstractJob("Refresh default object") {
@Override
protected IStatus run(DBRProgressMonitor monitor) {
monitor.beginTask("Refresh default objects", 1);
try {
DBUtils.refreshContextDefaultsAndReflect(monitor, contextDefaults);
} finally {
monitor.done();
}
return Status.OK_STATUS;
}
}.schedule();
}
}
}
}
private void updateOutputViewerIcon(boolean alert) {
Image image = alert ? IMG_OUTPUT_ALERT : IMG_OUTPUT;
CTabItem outputItem = UIUtils.getTabItem(resultTabs, outputViewer.getControl());
if (outputItem != null && outputItem != resultTabs.getSelection()) {
outputItem.setImage(image);
} else {
ToolItem viewItem = getViewToolItem(SQLEditorCommands.CMD_SQL_SHOW_OUTPUT);
if (viewItem != null) {
viewItem.setImage(image);
}
// TODO: make icon update. Can't call setImage because this will break contract f VerticalButton
/*
VerticalButton viewItem = getViewToolItem(SQLEditorCommands.CMD_SQL_SHOW_OUTPUT);
if (viewItem != null) {
viewItem.setImage(image);
}
*/
}
}
private class ScriptAutoSaveJob extends AbstractJob {
ScriptAutoSaveJob() {
super("Save '" + getPartName() + "' script");
setSystem(true);
}
@Override
protected IStatus run(DBRProgressMonitor monitor) {
if (EditorUtils.isInAutoSaveJob()) {
return Status.CANCEL_STATUS;
}
monitor.beginTask("Auto-save SQL script", 1);
try {
UIUtils.asyncExec(() ->
SQLEditor.this.doTextEditorSave(monitor));
} catch (Throwable e) {
log.debug(e);
} finally {
monitor.done();
}
return Status.OK_STATUS;
}
}
private class SaveJob extends AbstractJob {
private transient Boolean success = null;
SaveJob() {
super("Save '" + getPartName() + "' data changes...");
setUser(true);
}
@Override
protected IStatus run(DBRProgressMonitor monitor) {
monitor.beginTask("Save query processors", queryProcessors.size());
try {
for (QueryProcessor queryProcessor : queryProcessors) {
for (QueryResultsContainer resultsProvider : queryProcessor.getResultContainers()) {
ResultSetViewer rsv = resultsProvider.getResultSetController();
if (rsv != null && rsv.isDirty()) {
rsv.doSave(monitor);
}
}
monitor.worked(1);
}
success = true;
return Status.OK_STATUS;
} catch (Throwable e) {
success = false;
log.error(e);
return GeneralUtils.makeExceptionStatus(e);
} finally {
if (success == null) {
success = true;
}
monitor.done();
}
}
}
private class OutputLogWriter extends Writer {
@Override
public void write(@NotNull final char[] cbuf, final int off, final int len) {
UIUtils.syncExec(() -> {
if (!outputViewer.isDisposed()) {
outputViewer.getOutputWriter().write(cbuf, off, len);
outputViewer.scrollToEnd();
if (!outputViewer.isVisible()) {
updateOutputViewerIcon(true);
}
}
});
}
@Override
public void flush() {
outputViewer.getOutputWriter().flush();
}
@Override
public void close() {
}
}
private class ServerOutputReader extends AbstractJob {
ServerOutputReader() {
super("Dump server output");
setSystem(true);
}
@Override
protected IStatus run(DBRProgressMonitor monitor) {
if (!DBWorkbench.getPlatform().isShuttingDown() && resultsSash != null && !resultsSash.isDisposed()) {
dumpOutput(monitor);
schedule(200);
}
return Status.OK_STATUS;
}
private void dumpOutput(DBRProgressMonitor monitor) {
if (outputViewer == null) {
return;
}
List<ServerOutputInfo> outputs;
synchronized (serverOutputs) {
outputs = new ArrayList<>(serverOutputs);
serverOutputs.clear();
}
PrintWriter outputWriter = outputViewer.getOutputWriter();
if (!outputs.isEmpty()) {
for (ServerOutputInfo info : outputs) {
if (monitor.isCanceled()) {
break;
}
try {
info.outputReader.readServerOutput(monitor, info.executionContext, info.result, null, outputWriter);
} catch (Exception e) {
log.error(e);
}
}
}
if (!monitor.isCanceled()) {
// Check running queries for async output
DBCServerOutputReader outputReader = null;
final DBCExecutionContext executionContext = getExecutionContext();
if (executionContext != null) {
final DBPDataSource dataSource = executionContext.getDataSource();
// Dump server output
outputReader = DBUtils.getAdapter(DBCServerOutputReader.class, dataSource);
}
if (outputReader != null && outputReader.isAsyncOutputReadSupported()) {
for (QueryProcessor qp : queryProcessors) {
SQLQueryJob queryJob = qp.curJob;
if (queryJob != null) {
DBCStatement statement = queryJob.getCurrentStatement();
try {
if (statement != null && !statement.isStatementClosed()) {
outputReader.readServerOutput(monitor, executionContext, null, statement, outputWriter);
}
} catch (DBCException e) {
log.error(e);
}
}
}
}
}
outputWriter.flush();
if (!outputViewer.isHasNewOutput()) {
return;
}
outputViewer.resetNewOutput();
// Show output log view if needed
UIUtils.asyncExec(() -> {
outputViewer.scrollToEnd();
if (getActivePreferenceStore().getBoolean(SQLPreferenceConstants.OUTPUT_PANEL_AUTO_SHOW)) {
if (!getViewToolItem(SQLEditorCommands.CMD_SQL_SHOW_OUTPUT).getSelection()) {
showOutputPanel();
}
}
/*
if (outputViewer!=null) {
if (outputViewer.getControl()!=null) {
if (!outputViewer.isDisposed()) {
outputViewer.scrollToEnd();
updateOutputViewerIcon(true);
}
}
}
*/
});
}
}
private class OutputAutoShowToggleAction extends Action {
OutputAutoShowToggleAction() {
super(SQLEditorMessages.pref_page_sql_editor_label_auto_open_output_view, AS_CHECK_BOX);
setImageDescriptor(DBeaverIcons.getImageDescriptor(UIIcon.SHOW_ALL_DETAILS));
setChecked(getActivePreferenceStore().getBoolean(SQLPreferenceConstants.OUTPUT_PANEL_AUTO_SHOW));
}
@Override
public void run() {
getActivePreferenceStore().setValue(SQLPreferenceConstants.OUTPUT_PANEL_AUTO_SHOW, isChecked());
try {
getActivePreferenceStore().save();
} catch (IOException e) {
log.error(e);
}
}
}
private void notifyOnDataListeners(@NotNull QueryResultsContainer container) {
// Notify listeners
synchronized (listeners) {
for (SQLEditorListener listener : listeners) {
try {
listener.onDataReceived(
getContextPrefStore(container),
container.getResultSetController().getModel(),
container.getQuery().getOriginalText()
);
} catch (Throwable ex) {
log.error(ex);
}
}
}
}
private void notifyOnQueryResultListeners(@NotNull QueryResultsContainer container, @NotNull SQLQueryResult result) {
// Notify listeners
synchronized (listeners) {
for (SQLEditorListener listener : listeners) {
try {
listener.onQueryResult(getContextPrefStore(container), result);
} catch (Throwable ex) {
log.error(ex);
}
}
}
}
@NotNull
private DBPPreferenceStore getContextPrefStore(@NotNull QueryResultsContainer container) {
DBCExecutionContext context = container.getExecutionContext();
DBPPreferenceStore contextPrefStore = context != null
? context.getDataSource().getContainer().getPreferenceStore()
: DBWorkbench.getPlatform().getPreferenceStore();
return contextPrefStore;
}
}
| plugins/org.jkiss.dbeaver.ui.editors.sql/src/org/jkiss/dbeaver/ui/editors/sql/SQLEditor.java | /*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2022 DBeaver Corp and others
*
* 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.jkiss.dbeaver.ui.editors.sql;
import org.eclipse.core.filesystem.EFS;
import org.eclipse.core.filesystem.IFileStore;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFileState;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.runtime.*;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.action.*;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.text.*;
import org.eclipse.jface.text.source.SourceViewer;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.*;
import org.eclipse.swt.events.*;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.*;
import org.eclipse.ui.*;
import org.eclipse.ui.actions.CompoundContributionItem;
import org.eclipse.ui.ide.FileStoreEditorInput;
import org.eclipse.ui.menus.CommandContributionItem;
import org.eclipse.ui.menus.IMenuService;
import org.eclipse.ui.texteditor.DefaultRangeIndicator;
import org.eclipse.ui.texteditor.ITextEditorActionConstants;
import org.eclipse.ui.texteditor.rulers.IColumnSupport;
import org.eclipse.ui.texteditor.rulers.RulerColumnDescriptor;
import org.eclipse.ui.texteditor.rulers.RulerColumnRegistry;
import org.jkiss.code.NotNull;
import org.jkiss.code.Nullable;
import org.jkiss.dbeaver.DBException;
import org.jkiss.dbeaver.ModelPreferences;
import org.jkiss.dbeaver.model.*;
import org.jkiss.dbeaver.model.app.DBPPlatformDesktop;
import org.jkiss.dbeaver.model.app.DBPProject;
import org.jkiss.dbeaver.model.app.DBPWorkspaceDesktop;
import org.jkiss.dbeaver.model.data.DBDAttributeBinding;
import org.jkiss.dbeaver.model.data.DBDDataFilter;
import org.jkiss.dbeaver.model.data.DBDDataReceiver;
import org.jkiss.dbeaver.model.exec.*;
import org.jkiss.dbeaver.model.exec.plan.DBCPlan;
import org.jkiss.dbeaver.model.exec.plan.DBCPlanStyle;
import org.jkiss.dbeaver.model.exec.plan.DBCQueryPlanner;
import org.jkiss.dbeaver.model.exec.plan.DBCQueryPlannerConfiguration;
import org.jkiss.dbeaver.model.impl.DefaultServerOutputReader;
import org.jkiss.dbeaver.model.impl.sql.SQLQueryTransformerCount;
import org.jkiss.dbeaver.model.messages.ModelMessages;
import org.jkiss.dbeaver.model.navigator.DBNUtils;
import org.jkiss.dbeaver.model.preferences.DBPPreferenceStore;
import org.jkiss.dbeaver.model.qm.QMUtils;
import org.jkiss.dbeaver.model.rm.RMConstants;
import org.jkiss.dbeaver.model.runtime.AbstractJob;
import org.jkiss.dbeaver.model.runtime.DBRProgressListener;
import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor;
import org.jkiss.dbeaver.model.runtime.DBRRunnableWithProgress;
import org.jkiss.dbeaver.model.sql.*;
import org.jkiss.dbeaver.model.sql.data.SQLQueryDataContainer;
import org.jkiss.dbeaver.model.struct.DBSDataContainer;
import org.jkiss.dbeaver.model.struct.DBSInstance;
import org.jkiss.dbeaver.model.struct.DBSObject;
import org.jkiss.dbeaver.registry.DataSourceUtils;
import org.jkiss.dbeaver.runtime.DBWorkbench;
import org.jkiss.dbeaver.runtime.sql.SQLResultsConsumer;
import org.jkiss.dbeaver.runtime.ui.UIServiceConnections;
import org.jkiss.dbeaver.tools.transfer.IDataTransferProducer;
import org.jkiss.dbeaver.tools.transfer.database.DatabaseTransferProducer;
import org.jkiss.dbeaver.tools.transfer.ui.wizard.DataTransferWizard;
import org.jkiss.dbeaver.ui.*;
import org.jkiss.dbeaver.ui.controls.*;
import org.jkiss.dbeaver.ui.controls.resultset.*;
import org.jkiss.dbeaver.ui.controls.resultset.internal.ResultSetMessages;
import org.jkiss.dbeaver.ui.css.CSSUtils;
import org.jkiss.dbeaver.ui.css.DBStyles;
import org.jkiss.dbeaver.ui.dialogs.ConfirmationDialog;
import org.jkiss.dbeaver.ui.dialogs.EnterNameDialog;
import org.jkiss.dbeaver.ui.editors.*;
import org.jkiss.dbeaver.ui.editors.sql.execute.SQLQueryJob;
import org.jkiss.dbeaver.ui.editors.sql.handlers.SQLEditorVariablesResolver;
import org.jkiss.dbeaver.ui.editors.sql.handlers.SQLNavigatorContext;
import org.jkiss.dbeaver.ui.editors.sql.internal.SQLEditorMessages;
import org.jkiss.dbeaver.ui.editors.sql.log.SQLLogPanel;
import org.jkiss.dbeaver.ui.editors.sql.plan.ExplainPlanViewer;
import org.jkiss.dbeaver.ui.editors.sql.registry.SQLPresentationDescriptor;
import org.jkiss.dbeaver.ui.editors.sql.registry.SQLPresentationPanelDescriptor;
import org.jkiss.dbeaver.ui.editors.sql.registry.SQLPresentationRegistry;
import org.jkiss.dbeaver.ui.editors.sql.scripts.ScriptsHandlerImpl;
import org.jkiss.dbeaver.ui.editors.sql.variables.AssignVariableAction;
import org.jkiss.dbeaver.ui.editors.sql.variables.SQLVariablesPanel;
import org.jkiss.dbeaver.ui.editors.text.ScriptPositionColumn;
import org.jkiss.dbeaver.ui.navigator.INavigatorModelView;
import org.jkiss.dbeaver.utils.GeneralUtils;
import org.jkiss.dbeaver.utils.PrefUtils;
import org.jkiss.dbeaver.utils.ResourceUtils;
import org.jkiss.dbeaver.utils.RuntimeUtils;
import org.jkiss.utils.ArrayUtils;
import org.jkiss.utils.CommonUtils;
import java.io.*;
import java.net.URI;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* SQL Executor
*/
public class SQLEditor extends SQLEditorBase implements
IDataSourceContainerProviderEx,
DBPEventListener,
ISaveablePart2,
DBPDataSourceTask,
DBPDataSourceAcquirer,
IResultSetProvider,
ISmartTransactionManager
{
private static final long SCRIPT_UI_UPDATE_PERIOD = 100;
private static final int MAX_PARALLEL_QUERIES_NO_WARN = 1;
private static final int SQL_EDITOR_CONTROL_INDEX = 1;
private static final int EXTRA_CONTROL_INDEX = 0;
private static final String PANEL_ITEM_PREFIX = "SQLPanelToggle:";
private static final String EMBEDDED_BINDING_PREFIX = "-- CONNECTION: ";
private static final Pattern EMBEDDED_BINDING_PREFIX_PATTERN = Pattern.compile("--\\s*CONNECTION:\\s*(.+)", Pattern.CASE_INSENSITIVE);
private static final Image IMG_DATA_GRID = DBeaverIcons.getImage(UIIcon.SQL_PAGE_DATA_GRID);
private static final Image IMG_DATA_GRID_LOCKED = DBeaverIcons.getImage(UIIcon.SQL_PAGE_DATA_GRID_LOCKED);
private static final Image IMG_EXPLAIN_PLAN = DBeaverIcons.getImage(UIIcon.SQL_PAGE_EXPLAIN_PLAN);
private static final Image IMG_LOG = DBeaverIcons.getImage(UIIcon.SQL_PAGE_LOG);
private static final Image IMG_VARIABLES = DBeaverIcons.getImage(UIIcon.SQL_VARIABLE);
private static final Image IMG_OUTPUT = DBeaverIcons.getImage(UIIcon.SQL_PAGE_OUTPUT);
private static final Image IMG_OUTPUT_ALERT = DBeaverIcons.getImage(UIIcon.SQL_PAGE_OUTPUT_ALERT);
private static final String SIDE_TOOLBAR_CONTRIBUTION_ID = "toolbar:org.jkiss.dbeaver.ui.editors.sql.toolbar.side";
// private static final String TOOLBAR_GROUP_TOP = "top";
private static final String TOOLBAR_GROUP_ADDITIONS = IWorkbenchActionConstants.MB_ADDITIONS;
// private static final String TOOLBAR_GROUP_PANELS = "panelToggles";
public static final String VIEW_PART_PROP_NAME = "org.jkiss.dbeaver.ui.editors.sql.SQLEditor";
public static final String DEFAULT_TITLE_PATTERN = "<${" + SQLPreferenceConstants.VAR_CONNECTION_NAME + "}> ${" + SQLPreferenceConstants.VAR_FILE_NAME + "}";
public static final String DEFAULT_SCRIPT_FILE_NAME = "Script";
private ResultSetOrientation resultSetOrientation = ResultSetOrientation.HORIZONTAL;
private CustomSashForm resultsSash;
private Composite sqlEditorPanel;
@Nullable
private Composite presentationStack;
private SashForm sqlExtraPanelSash;
private CTabFolder sqlExtraPanelFolder;
private ToolBarManager sqlExtraPanelToolbar;
private CTabFolder resultTabs;
private TabFolderReorder resultTabsReorder;
private CTabItem activeResultsTab;
private SQLLogPanel logViewer;
private SQLEditorOutputConsoleViewer outputViewer;
private SQLVariablesPanel variablesViewer;
private volatile QueryProcessor curQueryProcessor;
private final List<QueryProcessor> queryProcessors = new ArrayList<>();
private DBPDataSourceContainer dataSourceContainer;
private DBPDataSource curDataSource;
private volatile DBCExecutionContext executionContext;
private volatile DBCExecutionContext lastExecutionContext;
private volatile DBPContextProvider executionContextProvider;
private SQLScriptContext globalScriptContext;
private volatile boolean syntaxLoaded = false;
private FindReplaceTarget findReplaceTarget = new FindReplaceTarget();
private final List<SQLQuery> runningQueries = new ArrayList<>();
private QueryResultsContainer curResultsContainer;
private Image editorImage;
private Composite leftToolPanel;
private ToolBarManager topBarMan;
private ToolBarManager bottomBarMan;
private SQLPresentationDescriptor extraPresentationDescriptor;
private SQLEditorPresentation extraPresentation;
private final Map<SQLPresentationPanelDescriptor, SQLEditorPresentationPanel> extraPresentationPanels = new HashMap<>();
private SQLEditorPresentationPanel extraPresentationCurrentPanel;
private VerticalFolder presentationSwitchFolder;
private final List<SQLEditorListener> listeners = new ArrayList<>();
private final List<ServerOutputInfo> serverOutputs = new ArrayList<>();
private ScriptAutoSaveJob scriptAutoSavejob;
private boolean isResultSetAutoFocusEnabled = true;
private static class ServerOutputInfo {
private final DBCServerOutputReader outputReader;
private final DBCExecutionContext executionContext;
private final DBCExecutionResult result;
ServerOutputInfo(DBCServerOutputReader outputReader, DBCExecutionContext executionContext, DBCExecutionResult result) {
this.outputReader = outputReader;
this.executionContext = executionContext;
this.result = result;
}
}
private final DisposeListener resultTabDisposeListener = new DisposeListener() {
@Override
public void widgetDisposed(DisposeEvent e) {
Object data = e.widget.getData();
if (data instanceof QueryResultsContainer) {
QueryProcessor processor = ((QueryResultsContainer) data).queryProcessor;
List<QueryResultsContainer> containers = processor.getResultContainers();
for (int index = containers.indexOf(data) + 1; index < containers.size(); index++) {
QueryResultsContainer container = containers.get(index);
// Make sure that resultSetNumber equals to current loop index.
// This must be true for every container of this query processor
if (container.resultSetNumber == index) {
container.resultSetNumber--;
}
}
}
if (resultTabs.getItemCount() == 0) {
if (resultsSash.getMaximizedControl() == null) {
// Hide results
toggleResultPanel(false, true);
}
}
}
};
private VerticalButton switchPresentationSQLButton;
private VerticalButton switchPresentationExtraButton;
public SQLEditor()
{
super();
this.extraPresentationDescriptor = SQLPresentationRegistry.getInstance().getPresentation(this);
}
public void setConsoleViewOutputEnabled(boolean value) {
isResultSetAutoFocusEnabled = !value;
}
@Override
protected String[] getKeyBindingContexts() {
return new String[]{
TEXT_EDITOR_CONTEXT,
SQLEditorContributions.SQL_EDITOR_CONTEXT,
SQLEditorContributions.SQL_EDITOR_SCRIPT_CONTEXT,
IResultSetController.RESULTS_CONTEXT_ID};
}
@Override
public DBPDataSource getDataSource() {
DBPDataSourceContainer container = getDataSourceContainer();
return container == null ? null : container.getDataSource();
}
@Override
public DBCExecutionContext getExecutionContext() {
if (executionContext != null) {
return executionContext;
}
if (executionContextProvider != null) {
return executionContextProvider.getExecutionContext();
}
if (dataSourceContainer != null && !SQLEditorUtils.isOpenSeparateConnection(dataSourceContainer)) {
return DBUtils.getDefaultContext(getDataSource(), false);
}
return null;
}
public SQLScriptContext getGlobalScriptContext() {
return globalScriptContext;
}
@Nullable
public DBPProject getProject()
{
IFile file = EditorUtils.getFileFromInput(getEditorInput());
return file == null ?
DBWorkbench.getPlatform().getWorkspace().getActiveProject() : DBPPlatformDesktop.getInstance().getWorkspace().getProject(file.getProject());
}
private boolean isProjectResourceEditable() {
DBPProject project = this.getProject();
return project == null || project.hasRealmPermission(RMConstants.PERMISSION_PROJECT_RESOURCE_EDIT);
}
@Override
protected boolean isReadOnly() {
return super.isReadOnly() || !this.isProjectResourceEditable();
}
@Override
public boolean isEditable() {
return super.isEditable() && this.isProjectResourceEditable();
}
@Nullable
@Override
public int[] getCurrentLines()
{
synchronized (runningQueries) {
IDocument document = getDocument();
if (document == null || runningQueries.isEmpty()) {
return null;
}
List<Integer> lines = new ArrayList<>(runningQueries.size() * 2);
for (SQLQuery statementInfo : runningQueries) {
try {
int firstLine = document.getLineOfOffset(statementInfo.getOffset());
int lastLine = document.getLineOfOffset(statementInfo.getOffset() + statementInfo.getLength());
for (int k = firstLine; k <= lastLine; k++) {
lines.add(k);
}
} catch (BadLocationException e) {
// ignore - this may happen if SQL was edited after execution start
}
}
if (lines.isEmpty()) {
return null;
}
int[] results = new int[lines.size()];
for (int i = 0; i < lines.size(); i++) {
results[i] = lines.get(i);
}
return results;
}
}
@Nullable
@Override
public DBPDataSourceContainer getDataSourceContainer()
{
return dataSourceContainer;
}
@Override
public boolean setDataSourceContainer(@Nullable DBPDataSourceContainer container)
{
if (container == dataSourceContainer) {
return true;
}
// Release ds container
releaseContainer();
closeAllJobs();
dataSourceContainer = container;
if (dataSourceContainer != null) {
dataSourceContainer.getPreferenceStore().addPropertyChangeListener(this);
dataSourceContainer.getRegistry().addDataSourceListener(this);
}
IEditorInput input = getEditorInput();
if (input != null) {
DBPDataSourceContainer savedContainer = EditorUtils.getInputDataSource(input);
if (savedContainer != container) {
// Container was changed. Reset context provider and update input settings
DBCExecutionContext newExecutionContext = DBUtils.getDefaultContext(container, false);
EditorUtils.setInputDataSource(input, new SQLNavigatorContext(container, newExecutionContext));
this.executionContextProvider = null;
} else {
DBCExecutionContext iec = EditorUtils.getInputExecutionContext(input);
if (iec != null) {
this.executionContextProvider = () -> iec;
}
}
IFile file = EditorUtils.getFileFromInput(input);
if (file != null) {
DBNUtils.refreshNavigatorResource(file, container);
} else {
// FIXME: this is a hack. We can't fire event on resource change so editor's state won't be updated in UI.
// FIXME: To update main toolbar and other controls we hade and show this editor
IWorkbenchPage page = getSite().getPage();
for (IEditorReference er : page.getEditorReferences()) {
if (er.getEditor(false) == this) {
page.hideEditor(er);
page.showEditor(er);
break;
}
}
//page.activate(this);
}
}
checkConnected(false, status -> UIUtils.asyncExec(() -> {
if (!status.isOK()) {
DBWorkbench.getPlatformUI().showError("Can't connect to database", "Error connecting to datasource", status);
}
setFocus();
}));
setPartName(getEditorName());
fireDataSourceChange();
if (dataSourceContainer != null) {
dataSourceContainer.acquire(this);
}
if (SQLEditorBase.isWriteEmbeddedBinding()) {
// Patch connection reference
UIUtils.syncExec(this::embedDataSourceAssociation);
}
return true;
}
private void updateDataSourceContainer() {
DBPDataSourceContainer inputDataSource = null;
if (SQLEditorBase.isReadEmbeddedBinding()) {
// Try to get datasource from contents (always, no matter what )
inputDataSource = getDataSourceFromContent();
}
if (inputDataSource == null) {
inputDataSource = EditorUtils.getInputDataSource(getEditorInput());
}
if (inputDataSource == null) {
// No datasource. Try to get one from active part
IWorkbenchPart activePart = getSite().getWorkbenchWindow().getActivePage().getActivePart();
if (activePart != this && activePart instanceof IDataSourceContainerProvider) {
inputDataSource = ((IDataSourceContainerProvider) activePart).getDataSourceContainer();
}
}
setDataSourceContainer(inputDataSource);
}
private void updateExecutionContext(Runnable onSuccess) {
if (dataSourceContainer == null) {
releaseExecutionContext();
} else {
// Get/open context
final DBPDataSource dataSource = dataSourceContainer.getDataSource();
if (dataSource == null) {
releaseExecutionContext();
} else if (curDataSource != dataSource) {
// Datasource was changed or instance was changed (PG)
releaseExecutionContext();
curDataSource = dataSource;
if (executionContextProvider == null) {
DBPDataSourceContainer container = dataSource.getContainer();
if (SQLEditorUtils.isOpenSeparateConnection(container)) {
initSeparateConnection(dataSource, onSuccess);
} else {
if (onSuccess != null) {
onSuccess.run();
}
}
}
}
}
UIUtils.asyncExec(() -> fireDataSourceChanged(null));
}
private void initSeparateConnection(@NotNull DBPDataSource dataSource, Runnable onSuccess) {
DBSInstance dsInstance = dataSource.getDefaultInstance();
String[] contextDefaults = isRestoreActiveSchemaFromScript() ?
EditorUtils.getInputContextDefaults(dataSource.getContainer(), getEditorInput()) : null;
if (!ArrayUtils.isEmpty(contextDefaults) && contextDefaults[0] != null) {
DBSInstance selectedInstance = DBUtils.findObject(dataSource.getAvailableInstances(), contextDefaults[0]);
if (selectedInstance != null) {
dsInstance = selectedInstance;
}
}
{
final OpenContextJob job = new OpenContextJob(dsInstance, onSuccess);
job.schedule();
}
}
private void releaseExecutionContext() {
if (executionContext != null && executionContext.isConnected()) {
// Close context in separate job (otherwise it can block UI)
new CloseContextJob(executionContext).schedule();
}
executionContext = null;
curDataSource = null;
}
private void releaseContainer() {
releaseExecutionContext();
if (dataSourceContainer != null) {
dataSourceContainer.getPreferenceStore().removePropertyChangeListener(this);
dataSourceContainer.getRegistry().removeDataSourceListener(this);
dataSourceContainer.release(this);
dataSourceContainer = null;
}
}
private DBPDataSourceContainer getDataSourceFromContent() {
DBPProject project = getProject();
IDocument document = getDocument();
if (project == null || document == null || document.getNumberOfLines() == 0) {
return null;
}
try {
IRegion region = document.getLineInformation(0);
String line = document.get(region.getOffset(), region.getLength());
Matcher matcher = EMBEDDED_BINDING_PREFIX_PATTERN.matcher(line);
if (matcher.matches()) {
String connSpec = matcher.group(1).trim();
if (!CommonUtils.isEmpty(connSpec)) {
final DBPDataSourceContainer dataSource = DataSourceUtils.getDataSourceBySpec(
project,
connSpec,
null,
true,
false);
if (dataSource != null) {
return dataSource;
}
}
}
} catch (Throwable e) {
log.debug("Error extracting datasource info from script's content", e);
}
return null;
}
private void embedDataSourceAssociation() {
if (getDataSourceFromContent() == dataSourceContainer) {
return;
}
IDocument document = getDocument();
if (document == null) {
log.error("Document is null");
return;
}
try {
int totalLines = document.getNumberOfLines();
IRegion region = null;
if (totalLines > 0) {
region = document.getLineInformation(0);
String line = document.get(region.getOffset(), region.getLength());
Matcher matcher = EMBEDDED_BINDING_PREFIX_PATTERN.matcher(line);
if (!matcher.matches()) {
// Update existing association
region = null;
}
}
if (dataSourceContainer == null) {
if (region == null) {
return;
}
// Remove connection association
document.replace(region.getOffset(), region.getLength(), "");
} else {
SQLScriptBindingType bindingType = SQLScriptBindingType.valueOf(DBWorkbench.getPlatform().getPreferenceStore().getString(SQLPreferenceConstants.SCRIPT_BIND_COMMENT_TYPE));
StringBuilder assocSpecLine = new StringBuilder(EMBEDDED_BINDING_PREFIX);
bindingType.appendSpec(dataSourceContainer, assocSpecLine);
assocSpecLine.append(GeneralUtils.getDefaultLineSeparator());
if (region != null) {
// Remove connection association
document.replace(region.getOffset(), region.getLength(), assocSpecLine.toString());
} else {
document.replace(0, 0, assocSpecLine.toString());
}
}
} catch (Throwable e) {
log.debug("Error extracting datasource info from script's content", e);
}
UIUtils.asyncExec(() -> {
TextViewer textViewer = getTextViewer();
if (textViewer != null) {
textViewer.refresh();
}
});
}
public void addListener(SQLEditorListener listener) {
synchronized (listeners) {
listeners.add(listener);
}
}
public void removeListener(SQLEditorListener listener) {
synchronized (listeners) {
listeners.remove(listener);
}
}
@Override
public boolean isActiveTask() {
return getTotalQueryRunning() > 0;
}
@Override
public boolean isSmartAutoCommit() {
return getActivePreferenceStore().getBoolean(ModelPreferences.TRANSACTIONS_SMART_COMMIT);
}
@Override
public void setSmartAutoCommit(boolean smartAutoCommit) {
getActivePreferenceStore().setValue(ModelPreferences.TRANSACTIONS_SMART_COMMIT, smartAutoCommit);
try {
getActivePreferenceStore().save();
} catch (IOException e) {
log.error("Error saving smart auto-commit option", e);
}
}
public void refreshActions() {
// Redraw toolbar to refresh action sets
topBarMan.getControl().redraw();
bottomBarMan.getControl().redraw();
}
private class OpenContextJob extends AbstractJob {
private final DBSInstance instance;
private final Runnable onSuccess;
private Throwable error;
OpenContextJob(DBSInstance instance, Runnable onSuccess) {
super("Open connection to " + instance.getDataSource().getContainer().getName());
this.instance = instance;
this.onSuccess = onSuccess;
setUser(true);
}
@Override
protected IStatus run(DBRProgressMonitor monitor) {
monitor.beginTask("Open SQLEditor isolated connection", 1);
try {
String title = "SQLEditor <" + getEditorInput().getName() + ">";
monitor.subTask("Open context " + title);
DBCExecutionContext newContext = instance.openIsolatedContext(monitor, title, instance.getDefaultContext(monitor, false));
// Set context defaults
String[] contextDefaultNames = isRestoreActiveSchemaFromScript() ?
EditorUtils.getInputContextDefaults(instance.getDataSource().getContainer(), getEditorInput()) : null;
if (contextDefaultNames != null && contextDefaultNames.length > 1 &&
(!CommonUtils.isEmpty(contextDefaultNames[0]) || !CommonUtils.isEmpty(contextDefaultNames[1])))
{
try {
DBExecUtils.setExecutionContextDefaults(monitor, newContext.getDataSource(), newContext, contextDefaultNames[0], null, contextDefaultNames[1]);
} catch (DBException e) {
DBWorkbench.getPlatformUI().showError("New connection default", "Error setting default catalog/schema for new connection", e);
}
}
SQLEditor.this.executionContext = newContext;
// Needed to update main toolbar
// FIXME: silly workaround. Command state update doesn't happen in some cases
// FIXME: but it works after short pause. Seems to be a bug in E4 command framework
new AbstractJob("Notify context change") {
@Override
protected IStatus run(DBRProgressMonitor monitor) {
DBUtils.fireObjectSelect(instance, true);
return Status.OK_STATUS;
}
}.schedule(200);
} catch (DBException e) {
error = e;
} finally {
monitor.done();
}
updateContext();
return Status.OK_STATUS;
}
private void updateContext() {
if (error != null) {
releaseExecutionContext();
DBWorkbench.getPlatformUI().showError("Open context", "Can't open editor connection", error);
} else {
if (onSuccess != null) {
onSuccess.run();
}
fireDataSourceChange();
}
}
}
private boolean isRestoreActiveSchemaFromScript() {
return getActivePreferenceStore().getBoolean(SQLPreferenceConstants.AUTO_SAVE_ACTIVE_SCHEMA) &&
getActivePreferenceStore().getBoolean(SQLPreferenceConstants.EDITOR_SEPARATE_CONNECTION) &&
(this.getDataSourceContainer() == null || !this.getDataSourceContainer().isForceUseSingleConnection());
}
private static class CloseContextJob extends AbstractJob {
private final DBCExecutionContext context;
CloseContextJob(DBCExecutionContext context) {
super("Close context " + context.getContextName());
this.context = context;
setUser(true);
}
@Override
protected IStatus run(DBRProgressMonitor monitor) {
monitor.beginTask("Close SQLEditor isolated connection", 1);
try {
if (QMUtils.isTransactionActive(context)) {
UIServiceConnections serviceConnections = DBWorkbench.getService(UIServiceConnections.class);
if (serviceConnections != null) {
serviceConnections.closeActiveTransaction(monitor, context, false);
}
}
monitor.subTask("Close context " + context.getContextName());
context.close();
} finally {
monitor.done();
}
return Status.OK_STATUS;
}
}
@Override
public boolean isDirty()
{
for (QueryProcessor queryProcessor : queryProcessors) {
if (queryProcessor.isDirty() || queryProcessor.curJobRunning.get() > 0) {
return true;
}
}
if (QMUtils.isTransactionActive(executionContext)) {
return true;
}
if (isNonPersistentEditor()) {
// Console is never dirty
return false;
}
if (extraPresentation instanceof ISaveablePart && ((ISaveablePart) extraPresentation).isDirty()) {
return true;
}
return super.isDirty();
}
@Nullable
@Override
public IResultSetController getResultSetController() {
if (resultTabs != null && !resultTabs.isDisposed()) {
CTabItem activeResultsTab = getActiveResultsTab();
if (activeResultsTab != null && UIUtils.isUIThread()) {
Object tabControl = activeResultsTab.getData();
if (tabControl instanceof QueryResultsContainer) {
return ((QueryResultsContainer) tabControl).viewer;
}
}
}
return null;
}
@Nullable
@Override
public <T> T getAdapter(Class<T> required)
{
if (required == INavigatorModelView.class) {
return null;
}
if (required == IResultSetController.class || required == ResultSetViewer.class) {
return required.cast(getResultSetController());
}
if (resultTabs != null && !resultTabs.isDisposed()) {
if (required == IFindReplaceTarget.class) {
return required.cast(findReplaceTarget);
}
CTabItem activeResultsTab = getActiveResultsTab();
if (activeResultsTab != null && UIUtils.isUIThread()) {
Object tabControl = activeResultsTab.getData();
if (tabControl instanceof QueryResultsContainer) {
tabControl = ((QueryResultsContainer) tabControl).viewer;
}
if (tabControl instanceof IAdaptable) {
T adapter = ((IAdaptable) tabControl).getAdapter(required);
if (adapter != null) {
return adapter;
}
}
}
}
return super.getAdapter(required);
}
private boolean checkConnected(boolean forceConnect, DBRProgressListener onFinish)
{
// Connect to datasource
final DBPDataSourceContainer dataSourceContainer = getDataSourceContainer();
boolean doConnect = dataSourceContainer != null &&
(forceConnect || dataSourceContainer.getPreferenceStore().getBoolean(SQLPreferenceConstants.EDITOR_CONNECT_ON_ACTIVATE));
if (doConnect) {
if (!dataSourceContainer.isConnected()) {
UIServiceConnections serviceConnections = DBWorkbench.getService(UIServiceConnections.class);
if (serviceConnections != null) {
serviceConnections.connectDataSource(dataSourceContainer, onFinish);
}
}
}
return dataSourceContainer != null && dataSourceContainer.isConnected();
}
@Override
public void createPartControl(Composite parent)
{
setRangeIndicator(new DefaultRangeIndicator());
// divides editor area and results/panels area
resultsSash = UIUtils.createPartDivider(
this,
parent,
resultSetOrientation.getSashOrientation() | SWT.SMOOTH);
CSSUtils.setCSSClass(resultsSash, DBStyles.COLORED_BY_CONNECTION_TYPE);
resultsSash.setSashWidth(8);
UIUtils.setHelp(resultsSash, IHelpContextIds.CTX_SQL_EDITOR);
Composite editorContainer;
sqlEditorPanel = UIUtils.createPlaceholder(resultsSash, 3, 0);
// Create left vertical toolbar
createControlsBar(sqlEditorPanel);
sqlExtraPanelSash = new SashForm(sqlEditorPanel, SWT.HORIZONTAL);
GridData gd = new GridData(GridData.FILL_BOTH);
gd.verticalIndent = 5;
sqlExtraPanelSash.setLayoutData(gd);
// Create editor presentations sash
Composite pPlaceholder = null;
StackLayout presentationStackLayout = null;
if (extraPresentationDescriptor != null) {
presentationStack = new Composite(sqlExtraPanelSash, SWT.NONE);
presentationStack.setLayoutData(new GridData(GridData.FILL_BOTH));
presentationStackLayout = new StackLayout();
presentationStack.setLayout(presentationStackLayout);
editorContainer = presentationStack;
pPlaceholder = new Composite(presentationStack, SWT.NONE);
pPlaceholder.setLayout(new FillLayout());
} else {
editorContainer = sqlExtraPanelSash;
}
super.createPartControl(editorContainer);
getEditorControlWrapper().setLayoutData(new GridData(GridData.FILL_BOTH));
sqlExtraPanelFolder = new CTabFolder(sqlExtraPanelSash, SWT.TOP | SWT.CLOSE | SWT.FLAT);
sqlExtraPanelFolder.setSelection(0);
sqlExtraPanelFolder.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
CTabItem item = sqlExtraPanelFolder.getSelection();
if (item != null) {
IActionContributor ac = (IActionContributor) item.getData("actionContributor");
updateExtraViewToolbar(ac);
}
}
});
sqlExtraPanelToolbar = new ToolBarManager();
sqlExtraPanelToolbar.createControl(sqlExtraPanelFolder);
sqlExtraPanelFolder.setTopRight(sqlExtraPanelToolbar.getControl());
restoreSashRatio(sqlExtraPanelSash, SQLPreferenceConstants.EXTRA_PANEL_RATIO);
sqlExtraPanelSash.setMaximizedControl(sqlExtraPanelSash.getChildren()[0]);
this.addSashRatioSaveListener(sqlExtraPanelSash, SQLPreferenceConstants.EXTRA_PANEL_RATIO);
// Create right vertical toolbar
createPresentationSwitchBar(sqlEditorPanel);
if (pPlaceholder != null) {
switch (extraPresentationDescriptor.getActivationType()) {
case HIDDEN:
presentationStackLayout.topControl = presentationStack.getChildren()[SQL_EDITOR_CONTROL_INDEX];
break;
case MAXIMIZED:
case VISIBLE:
extraPresentation.createPresentation(pPlaceholder, this);
if (extraPresentationDescriptor.getActivationType() == SQLEditorPresentation.ActivationType.MAXIMIZED) {
if (presentationStack.getChildren()[EXTRA_CONTROL_INDEX] != null) {
presentationStackLayout.topControl = pPlaceholder;
}
}
break;
}
}
getSite().setSelectionProvider(new DynamicSelectionProvider());
DBPProject project = getProject();
if (project != null && project.isRegistryLoaded()) {
createResultTabs();
} else {
UIExecutionQueue.queueExec(this::createResultTabs);
}
setAction(ITextEditorActionConstants.SHOW_INFORMATION, null);
SourceViewer viewer = getViewer();
if (viewer != null) {
StyledText textWidget = viewer.getTextWidget();
if (textWidget != null) {
textWidget.addModifyListener(this::onTextChange);
textWidget.addFocusListener(new FocusAdapter() {
@Override
public void focusGained(FocusEvent e) {
refreshActions();
}
});
}
}
SQLEditorFeatures.SQL_EDITOR_OPEN.use();
// Start output reader
new ServerOutputReader().schedule();
updateExecutionContext(null);
// Update controls
UIExecutionQueue.queueExec(this::onDataSourceChange);
}
private void onTextChange(ModifyEvent e) {
if (getActivePreferenceStore().getBoolean(SQLPreferenceConstants.AUTO_SAVE_ON_CHANGE)) {
doScriptAutoSave();
}
}
private void createControlsBar(Composite sqlEditorPanel) {
leftToolPanel = new Composite(sqlEditorPanel, SWT.LEFT);
GridLayout panelsLayout = new GridLayout(1, true);
panelsLayout.marginHeight = 2;
panelsLayout.marginWidth = 1;
panelsLayout.marginTop = 1;
panelsLayout.marginBottom = 7;
panelsLayout.verticalSpacing = 1;
leftToolPanel.setLayout(panelsLayout);
leftToolPanel.setLayoutData(new GridData(GridData.FILL_VERTICAL));
ToolBar topBar = new ToolBar(leftToolPanel, SWT.VERTICAL | SWT.FLAT);
topBar.setData(VIEW_PART_PROP_NAME, this);
topBarMan = new ToolBarManager(topBar);
topBarMan.add(ActionUtils.makeCommandContribution(getSite(), SQLEditorCommands.CMD_EXECUTE_STATEMENT));
topBarMan.add(ActionUtils.makeCommandContribution(getSite(), SQLEditorCommands.CMD_EXECUTE_STATEMENT_NEW));
topBarMan.add(ActionUtils.makeCommandContribution(getSite(), SQLEditorCommands.CMD_EXECUTE_SCRIPT));
topBarMan.add(ActionUtils.makeCommandContribution(getSite(), SQLEditorCommands.CMD_EXPLAIN_PLAN));
topBarMan.add(new GroupMarker(TOOLBAR_GROUP_ADDITIONS));
final IMenuService menuService = getSite().getService(IMenuService.class);
if (menuService != null) {
int prevSize = topBarMan.getSize();
menuService.populateContributionManager(topBarMan, SIDE_TOOLBAR_CONTRIBUTION_ID);
if (prevSize != topBarMan.getSize()) {
topBarMan.insertBefore(TOOLBAR_GROUP_ADDITIONS, new ToolbarSeparatorContribution(false));
}
}
topBar.setLayoutData(new GridData(SWT.CENTER, SWT.TOP, true, false));
CSSUtils.setCSSClass(topBar, DBStyles.COLORED_BY_CONNECTION_TYPE);
topBarMan.update(true);
topBar.pack();
UIUtils.createEmptyLabel(leftToolPanel, 1, 1).setLayoutData(new GridData(SWT.CENTER, SWT.FILL, true, true));
bottomBarMan = new ToolBarManager(SWT.VERTICAL | SWT.FLAT);
bottomBarMan.add(ActionUtils.makeActionContribution(new ShowPreferencesAction(), false));
bottomBarMan.add(new ToolbarSeparatorContribution(false));
bottomBarMan.add(ActionUtils.makeCommandContribution(
getSite(),
SQLEditorCommands.CMD_SQL_SHOW_OUTPUT,
CommandContributionItem.STYLE_CHECK
));
bottomBarMan.add(ActionUtils.makeCommandContribution(
getSite(),
SQLEditorCommands.CMD_SQL_SHOW_LOG,
CommandContributionItem.STYLE_CHECK
));
bottomBarMan.add(ActionUtils.makeCommandContribution(
getSite(),
SQLEditorCommands.CMD_SQL_SHOW_VARIABLES,
CommandContributionItem.STYLE_CHECK
));
ToolBar bottomBar = bottomBarMan.createControl(leftToolPanel);
bottomBar.setLayoutData(new GridData(SWT.CENTER, SWT.BOTTOM, true, false));
CSSUtils.setCSSClass(bottomBar, DBStyles.COLORED_BY_CONNECTION_TYPE);
bottomBar.pack();
bottomBarMan.update(true);
}
private void createPresentationSwitchBar(Composite sqlEditorPanel) {
if (extraPresentationDescriptor == null) {
return;
}
presentationSwitchFolder = new VerticalFolder(sqlEditorPanel, SWT.RIGHT);
presentationSwitchFolder.setLayoutData(new GridData(GridData.FILL_VERTICAL));
switchPresentationSQLButton = new VerticalButton(presentationSwitchFolder, SWT.RIGHT | SWT.CHECK);
switchPresentationSQLButton.setText(SQLEditorMessages.editors_sql_description);
switchPresentationSQLButton.setImage(DBeaverIcons.getImage(UIIcon.SQL_SCRIPT));
switchPresentationExtraButton = new VerticalButton(presentationSwitchFolder, SWT.RIGHT | SWT.CHECK);
switchPresentationExtraButton.setData(extraPresentationDescriptor);
switchPresentationExtraButton.setText(extraPresentationDescriptor.getLabel());
switchPresentationExtraButton.setImage(DBeaverIcons.getImage(extraPresentationDescriptor.getIcon()));
String toolTip = ActionUtils.findCommandDescription(extraPresentationDescriptor.getToggleCommandId(), getSite(), false);
if (CommonUtils.isEmpty(toolTip)) {
toolTip = extraPresentationDescriptor.getDescription();
}
if (!CommonUtils.isEmpty(toolTip)) {
switchPresentationExtraButton.setToolTipText(toolTip);
}
switchPresentationSQLButton.setChecked(true);
// We use single switch handler. It must be provided by presentation itself
// Presentation switch may require some additional action so we can't just switch visible controls
SelectionListener switchListener = new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (((VerticalButton)e.item).isChecked() || presentationSwitchFolder.getSelection() == e.item) {
return;
}
String toggleCommandId = extraPresentationDescriptor.getToggleCommandId();
ActionUtils.runCommand(toggleCommandId, getSite());
}
};
switchPresentationSQLButton.addSelectionListener(switchListener);
switchPresentationExtraButton.addSelectionListener(switchListener);
// Stretch
UIUtils.createEmptyLabel(presentationSwitchFolder, 1, 1).setLayoutData(new GridData(GridData.FILL_VERTICAL));
createToggleLayoutButton();
}
/**
* Sets focus in current editor.
* This function is called on drag-n-drop and some other operations
*/
@Override
public boolean validateEditorInputState() {
boolean res = super.validateEditorInputState();
if (res) {
SourceViewer viewer = getViewer();
if (viewer != null) {
StyledText textWidget = viewer.getTextWidget();
if (textWidget != null && !textWidget.isDisposed()) {
textWidget.setFocus();
}
}
}
return res;
}
private void createResultTabs()
{
resultTabs = new CTabFolder(resultsSash, SWT.TOP | SWT.FLAT);
CSSUtils.setCSSClass(resultTabs, DBStyles.COLORED_BY_CONNECTION_TYPE);
resultTabsReorder = new TabFolderReorder(resultTabs);
resultTabs.setLayoutData(new GridData(GridData.FILL_BOTH));
resultTabs.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (extraPresentationCurrentPanel != null) {
extraPresentationCurrentPanel.deactivatePanel();
}
extraPresentationCurrentPanel = null;
Object data = e.item.getData();
if (data instanceof QueryResultsContainer) {
setActiveResultsContainer((QueryResultsContainer) data);
} else if (data instanceof SQLEditorPresentationPanel) {
extraPresentationCurrentPanel = ((SQLEditorPresentationPanel) data);
extraPresentationCurrentPanel.activatePanel();
} else if (data instanceof ExplainPlanViewer) {
SQLQuery planQuery = ((ExplainPlanViewer) data).getQuery();
if (planQuery != null) {
getSelectionProvider().setSelection(new TextSelection(planQuery.getOffset(), 0));
}
}
}
});
this.addSashRatioSaveListener(resultsSash, SQLPreferenceConstants.RESULTS_PANEL_RATIO);
this.resultTabs.addListener(TabFolderReorder.ITEM_MOVE_EVENT, event -> {
CTabItem item = (CTabItem) event.item;
if (item.getData() instanceof QueryResultsContainer) {
((QueryResultsContainer) item.getData()).resultsTab = item;
}
});
restoreSashRatio(resultsSash, SQLPreferenceConstants.RESULTS_PANEL_RATIO);
TextViewer textViewer = getTextViewer();
if (textViewer != null) {
textViewer.getTextWidget().addTraverseListener(e -> {
if (e.detail == SWT.TRAVERSE_TAB_NEXT && e.stateMask == SWT.MOD1) {
ResultSetViewer viewer = getActiveResultSetViewer();
if (viewer != null && viewer.getActivePresentation().getControl().isVisible()) {
viewer.getActivePresentation().getControl().setFocus();
e.detail = SWT.TRAVERSE_NONE;
}
}
});
}
resultTabs.setSimple(true);
resultTabs.addMouseListener(new MouseAdapter() {
@Override
public void mouseUp(MouseEvent e) {
if (e.button == 2) {
CTabItem item = resultTabs.getItem(new Point(e.x, e.y));
if (item != null && item.getShowClose()) {
item.dispose();
}
}
}
});
resultTabs.addListener(SWT.MouseDoubleClick, event -> {
if (event.button != 1) {
return;
}
CTabItem selectedItem = resultTabs.getItem(new Point(event.getBounds().x, event.getBounds().y));
if (selectedItem != null && selectedItem == resultTabs.getSelection()) {
toggleEditorMaximize();
}
});
// Extra views
createExtraViewControls();
// Create results tab
createQueryProcessor(true, true);
resultsSash.setMaximizedControl(sqlEditorPanel);
{
resultTabs.addMouseListener(new MouseAdapter() {
@Override
public void mouseDown(MouseEvent e) {
activeResultsTab = resultTabs.getItem(new Point(e.x, e.y));
}
});
MenuManager menuMgr = new MenuManager();
Menu menu = menuMgr.createContextMenu(resultTabs);
menuMgr.addMenuListener(manager -> {
final CTabItem activeTab = getActiveResultsTab();
if (activeTab != null && activeTab.getData() instanceof QueryResultsContainer) {
final QueryResultsContainer container = (QueryResultsContainer) activeTab.getData();
int pinnedTabsCount = 0;
int resultTabsCount = 0;
for (CTabItem item : resultTabs.getItems()) {
if (item.getData() instanceof QueryResultsContainer) {
resultTabsCount++;
if (((QueryResultsContainer) item.getData()).isPinned()) {
pinnedTabsCount++;
}
}
}
if (activeTab.getShowClose()) {
manager.add(ActionUtils.makeCommandContribution(getSite(), SQLEditorCommands.CMD_SQL_EDITOR_CLOSE_TAB));
if (resultTabsCount - pinnedTabsCount > 1) {
manager.add(new Action(SQLEditorMessages.action_result_tabs_close_all_tabs) {
@Override
public void run() {
closeExtraResultTabs(null, false, false);
}
});
manager.add(new Action(SQLEditorMessages.action_result_tabs_close_query_tabs) {
@Override
public void run() {
final QueryProcessor processor = ((QueryResultsContainer) activeTab.getData()).queryProcessor;
final List<CTabItem> tabs = new ArrayList<>();
for (QueryResultsContainer container : processor.getResultContainers()) {
if (!container.isPinned() && container.queryProcessor == processor) {
tabs.add(container.getTabItem());
}
}
for (CTabItem tab : tabs) {
tab.dispose();
}
}
});
manager.add(new Action(SQLEditorMessages.action_result_tabs_close_other_tabs) {
@Override
public void run() {
final List<CTabItem> tabs = new ArrayList<>();
for (CTabItem tab : resultTabs.getItems()) {
if (tab.getShowClose() && tab != activeTab) {
tabs.add(tab);
}
}
for (CTabItem tab : tabs) {
tab.dispose();
}
setActiveResultsContainer((QueryResultsContainer) activeTab.getData());
}
});
if (resultTabs.indexOf(activeTab) - pinnedTabsCount > 0) {
manager.add(new Action(SQLEditorMessages.action_result_tabs_close_tabs_to_the_left) {
@Override
public void run() {
final List<CTabItem> tabs = new ArrayList<>();
for (int i = 0, last = resultTabs.indexOf(activeTab); i < last; i++) {
tabs.add(resultTabs.getItem(i));
}
for (CTabItem tab : tabs) {
tab.dispose();
}
}
});
}
if (resultTabs.indexOf(activeTab) < resultTabsCount - pinnedTabsCount - 1) {
manager.add(new Action(SQLEditorMessages.action_result_tabs_close_tabs_to_the_right) {
@Override
public void run() {
final List<CTabItem> tabs = new ArrayList<>();
for (int i = resultTabs.indexOf(activeTab) + 1; i < resultTabs.getItemCount(); i++) {
tabs.add(resultTabs.getItem(i));
}
for (CTabItem tab : tabs) {
tab.dispose();
}
}
});
}
}
}
if (container.hasData()) {
final boolean isPinned = container.isPinned();
manager.add(new Separator());
manager.add(new Action(isPinned ? SQLEditorMessages.action_result_tabs_unpin_tab : SQLEditorMessages.action_result_tabs_pin_tab) {
@Override
public void run() {
container.setPinned(!isPinned);
CTabItem currTabItem = activeTab;
CTabItem nextTabItem;
if (isPinned) {
for (int i = resultTabs.indexOf(activeTab) + 1; i < resultTabs.getItemCount(); i++) {
nextTabItem = resultTabs.getItem(i);
if (nextTabItem.getShowClose()) {
break;
}
resultTabsReorder.swapTabs(currTabItem, nextTabItem);
currTabItem = nextTabItem;
}
} else {
for (int i = resultTabs.indexOf(activeTab) - 1; i >= 0; i--) {
nextTabItem = resultTabs.getItem(i);
if (!nextTabItem.getShowClose()) {
break;
}
resultTabsReorder.swapTabs(currTabItem, nextTabItem);
currTabItem = nextTabItem;
}
}
}
});
if (isPinned && pinnedTabsCount > 1) {
manager.add(new Action(SQLEditorMessages.action_result_tabs_unpin_all_tabs) {
@Override
public void run() {
for (CTabItem item : resultTabs.getItems()) {
if (item.getData() instanceof QueryResultsContainer) {
if (((QueryResultsContainer) item.getData()).isPinned()) {
((QueryResultsContainer) item.getData()).setPinned(false);
}
}
}
}
});
}
manager.add(new Action(SQLEditorMessages.action_result_tabs_set_name) {
@Override
public void run() {
EnterNameDialog dialog = new EnterNameDialog(resultTabs.getShell(), SQLEditorMessages.action_result_tabs_set_name_title, activeTab.getText());
if (dialog.open() == IDialogConstants.OK_ID) {
container.setTabName(dialog.getResult());
}
}
});
if (container.getQuery() != null) {
manager.add(new Separator());
AssignVariableAction action = new AssignVariableAction(SQLEditor.this, container.getQuery().getText());
action.setEditable(false);
manager.add(action);
}
}
}
manager.add(new Separator());
manager.add(ActionUtils.makeCommandContribution(getSite(), SQLEditorCommands.CMD_SQL_EDITOR_MAXIMIZE_PANEL));
});
menuMgr.setRemoveAllWhenShown(true);
resultTabs.setMenu(menu);
}
}
private void addSashRatioSaveListener(SashForm sash, String prefId) {
Control control = sash.getChildren()[0];
control.addListener(SWT.Resize, event -> {
if (!control.isDisposed()) {
int[] weights = sash.getWeights();
IPreferenceStore prefs = getPreferenceStore();
if (prefs != null && weights.length == 2) {
prefs.setValue(prefId, weights[0] + "-" + weights[1]);
}
}
});
}
private void restoreSashRatio(SashForm sash, String prefId) {
String resultsPanelRatio = getPreferenceStore().getString(prefId);
if (!CommonUtils.isEmpty(resultsPanelRatio)) {
String[] weightsStr = resultsPanelRatio.split("-");
if (weightsStr.length > 1) {
int[] weights = {
CommonUtils.toInt(weightsStr[0]),
CommonUtils.toInt(weightsStr[1]),
};
// If weight of one of controls less than 5% of weight of another - restore default wqeights
if (weights[1] < weights[0] / 15 || weights[0] < weights[1] / 15) {
log.debug("Restore default sash weights");
} else {
sash.setWeights(weights);
}
}
}
}
private void setActiveResultsContainer(QueryResultsContainer data) {
curResultsContainer = data;
curQueryProcessor = curResultsContainer.queryProcessor;
}
/////////////////////////////////////////////////////////////
// Panels
public void toggleExtraPanelsLayout() {
CTabItem outTab = getExtraViewTab(outputViewer.getControl());
CTabItem logTab = getExtraViewTab(logViewer);
CTabItem varTab = getExtraViewTab(variablesViewer);
if (outTab != null) outTab.dispose();
if (logTab != null) logTab.dispose();
if (varTab != null) varTab.dispose();
IPreferenceStore preferenceStore = getPreferenceStore();
String epLocation = getExtraPanelsLocation();
if (SQLPreferenceConstants.LOCATION_RESULTS.equals(epLocation)) {
epLocation = SQLPreferenceConstants.LOCATION_RIGHT;
} else {
epLocation = SQLPreferenceConstants.LOCATION_RESULTS;
}
preferenceStore.setValue(SQLPreferenceConstants.EXTRA_PANEL_LOCATION, epLocation);
createExtraViewControls();
if (outTab != null) showOutputPanel();
if (logTab != null) showExecutionLogPanel();
if (varTab != null) showVariablesPanel();
}
public String getExtraPanelsLocation() {
return getPreferenceStore().getString(SQLPreferenceConstants.EXTRA_PANEL_LOCATION);
}
private void createExtraViewControls() {
if (logViewer != null) {
logViewer.dispose();
logViewer = null;
}
if (variablesViewer != null) {
variablesViewer.dispose();
variablesViewer = null;
}
if (outputViewer != null) {
outputViewer.dispose();
outputViewer = null;
}
if (sqlExtraPanelFolder != null) {
for (CTabItem ti : sqlExtraPanelFolder.getItems()) {
ti.dispose();
}
}
//planView = new ExplainPlanViewer(this, resultTabs);
CTabFolder folder = getFolderForExtraPanels();
logViewer = new SQLLogPanel(folder, this);
variablesViewer = new SQLVariablesPanel(folder, this);
outputViewer = new SQLEditorOutputConsoleViewer(getSite(), folder, SWT.NONE);
if (getFolderForExtraPanels() != sqlExtraPanelFolder) {
sqlExtraPanelSash.setMaximizedControl(sqlExtraPanelSash.getChildren()[0]);
}
}
public CTabFolder getResultTabsContainer() {
return resultTabs;
}
private CTabFolder getFolderForExtraPanels() {
CTabFolder folder = this.sqlExtraPanelFolder;
String epLocation = getExtraPanelsLocation();
if (SQLPreferenceConstants.LOCATION_RESULTS.equals(epLocation)) {
folder = resultTabs;
}
return folder;
}
private CTabItem getExtraViewTab(Control control) {
CTabFolder tabFolder = this.getFolderForExtraPanels();
for (CTabItem item : tabFolder.getItems()) {
if (item.getData() == control) {
return item;
}
}
return null;
}
private void showExtraView(final String commandId, String name, String toolTip, Image image, Control view, IActionContributor actionContributor) {
ToolItem viewItem = getViewToolItem(commandId);
if (viewItem == null) {
log.warn("Tool item for command " + commandId + " not found");
return;
}
CTabFolder tabFolder = this.getFolderForExtraPanels();
CTabItem curItem = getExtraViewTab(view);
if (curItem != null) {
// Close tab if it is already open
viewItem.setSelection(false);
curItem.dispose();
return;
}
boolean isTabsToTheRight = tabFolder == sqlExtraPanelFolder;
if (isTabsToTheRight) {
if (sqlExtraPanelSash.getMaximizedControl() != null) {
sqlExtraPanelSash.setMaximizedControl(null);
}
} else {
sqlExtraPanelSash.setMaximizedControl(sqlExtraPanelSash.getChildren()[0]);
// Show results
showResultsPanel(true);
}
if (view == outputViewer.getControl()) {
updateOutputViewerIcon(false);
outputViewer.resetNewOutput();
}
// Create new tab
viewItem.setSelection(true);
CTabItem item = new CTabItem(tabFolder, SWT.CLOSE);
item.setControl(view);
item.setText(name);
item.setToolTipText(toolTip);
item.setImage(image);
item.setData(view);
item.setData("actionContributor", actionContributor);
// De-select tool item on tab close
item.addDisposeListener(e -> {
if (!viewItem.isDisposed()) {
viewItem.setSelection(false);
}
if (tabFolder.getItemCount() == 0) {
sqlExtraPanelSash.setMaximizedControl(sqlExtraPanelSash.getChildren()[0]);
}
});
tabFolder.setSelection(item);
if (isTabsToTheRight) {
updateExtraViewToolbar(actionContributor);
}
}
private void updateExtraViewToolbar(IActionContributor actionContributor) {
// Update toolbar
sqlExtraPanelToolbar.removeAll();
if (actionContributor != null) {
actionContributor.contributeActions(sqlExtraPanelToolbar);
}
sqlExtraPanelToolbar.add(ActionUtils.makeCommandContribution(
getSite(),
"org.jkiss.dbeaver.ui.editors.sql.toggle.extraPanels",
CommandContributionItem.STYLE_CHECK,
UIIcon.ARROW_DOWN));
sqlExtraPanelToolbar.update(true);
}
private ToolItem getViewToolItem(String commandId) {
ToolItem viewItem = null;
for (ToolItem item : topBarMan.getControl().getItems()) {
Object data = item.getData();
if (data instanceof CommandContributionItem) {
if (((CommandContributionItem) data).getCommand() != null
&& commandId.equals(((CommandContributionItem) data).getCommand().getId())
) {
viewItem = item;
break;
}
}
}
for (ToolItem item : bottomBarMan.getControl().getItems()) {
Object data = item.getData();
if (data instanceof CommandContributionItem) {
if (((CommandContributionItem) data).getCommand() != null
&& commandId.equals(((CommandContributionItem) data).getCommand().getId())
) {
viewItem = item;
break;
}
}
}
return viewItem;
}
private CTabItem getActiveResultsTab() {
return activeResultsTab == null || activeResultsTab.isDisposed() ?
(resultTabs == null ? null : resultTabs.getSelection()) : activeResultsTab;
}
public void closeActiveTab() {
CTabItem tabItem = getActiveResultsTab();
if (tabItem != null && tabItem.getShowClose()) {
tabItem.dispose();
activeResultsTab = null;
}
}
public void showOutputPanel() {
showExtraView(
SQLEditorCommands.CMD_SQL_SHOW_OUTPUT,
SQLEditorMessages.editors_sql_output,
SQLEditorMessages.editors_sql_output_tip,
IMG_OUTPUT,
outputViewer.getControl(),
manager -> manager.add(new OutputAutoShowToggleAction()));
}
public void showExecutionLogPanel() {
showExtraView(
SQLEditorCommands.CMD_SQL_SHOW_LOG,
SQLEditorMessages.editors_sql_execution_log,
SQLEditorMessages.editors_sql_execution_log_tip,
IMG_LOG,
logViewer,
null);
}
public void showVariablesPanel() {
showExtraView(
SQLEditorCommands.CMD_SQL_SHOW_VARIABLES,
SQLEditorMessages.editors_sql_variables,
SQLEditorMessages.editors_sql_variables_tip,
IMG_VARIABLES,
variablesViewer,
null);
UIUtils.asyncExec(() -> variablesViewer.refreshVariables());
}
public <T> T getExtraPresentationPanel(Class<T> panelClass) {
for (CTabItem tabItem : resultTabs.getItems()) {
if (tabItem.getData() instanceof SQLEditorPresentationPanel && tabItem.getData().getClass() == panelClass) {
return panelClass.cast(tabItem.getData());
}
}
return null;
}
public boolean showPresentationPanel(SQLEditorPresentationPanel panel) {
for (CTabItem item : resultTabs.getItems()) {
if (item.getData() == panel) {
setResultTabSelection(item);
return true;
}
}
return false;
}
private void setResultTabSelection(CTabItem item) {
if (isResultSetAutoFocusEnabled || !(item.getData() instanceof QueryResultsContainer)) {
resultTabs.setSelection(item);
}
}
public SQLEditorPresentationPanel showPresentationPanel(String panelID) {
for (IContributionItem contributionItem : topBarMan.getItems()) {
if (contributionItem instanceof ActionContributionItem) {
IAction action = ((ActionContributionItem) contributionItem).getAction();
if (action instanceof PresentationPanelToggleAction
&& ((PresentationPanelToggleAction) action).panel.getId().equals(panelID)
) {
action.run();
return extraPresentationCurrentPanel;
}
}
}
for (IContributionItem contributionItem : bottomBarMan.getItems()) {
if (contributionItem instanceof ActionContributionItem) {
IAction action = ((ActionContributionItem) contributionItem).getAction();
if (action instanceof PresentationPanelToggleAction
&& ((PresentationPanelToggleAction) action).panel.getId().equals(panelID)
) {
action.run();
return extraPresentationCurrentPanel;
}
}
}
return null;
}
public boolean hasMaximizedControl() {
return resultsSash.getMaximizedControl() != null;
}
public SQLEditorPresentation getExtraPresentation() {
return extraPresentation;
}
public SQLEditorPresentation.ActivationType getExtraPresentationState() {
if (extraPresentation == null || presentationStack == null) {
return SQLEditorPresentation.ActivationType.HIDDEN;
}
Control maximizedControl = ((StackLayout)presentationStack.getLayout()).topControl;
if (maximizedControl == getExtraPresentationControl()) {
return SQLEditorPresentation.ActivationType.MAXIMIZED;
} else if (maximizedControl == getEditorControlWrapper()) {
return SQLEditorPresentation.ActivationType.HIDDEN;
} else {
return SQLEditorPresentation.ActivationType.VISIBLE;
}
}
public void showExtraPresentation(boolean show, boolean maximize) {
if (extraPresentationDescriptor == null || presentationStack == null) {
return;
}
resultsSash.setRedraw(false);
try {
StackLayout stackLayout = (StackLayout) presentationStack.getLayout();
if (!show) {
//boolean epHasFocus = UIUtils.hasFocus(getExtraPresentationControl());
stackLayout.topControl = presentationStack.getChildren()[SQL_EDITOR_CONTROL_INDEX];
//if (epHasFocus) {
getEditorControlWrapper().setFocus();
//}
// Set selection provider back to the editor
getSite().setSelectionProvider(new DynamicSelectionProvider());
} else {
if (extraPresentation == null) {
// Lazy activation
try {
extraPresentation = extraPresentationDescriptor.createPresentation();
extraPresentation.createPresentation((Composite) getExtraPresentationControl(), this);
} catch (DBException e) {
log.error("Error creating presentation", e);
}
}
getSite().setSelectionProvider(extraPresentation.getSelectionProvider());
if (maximize) {
stackLayout.topControl = getExtraPresentationControl();
getExtraPresentationControl().setFocus();
} else {
stackLayout.topControl = null;
}
}
// Show presentation panels
boolean sideBarChanged = false;
if (getExtraPresentationState() == SQLEditorPresentation.ActivationType.HIDDEN) {
// Remove all presentation panel toggles
//for (SQLPresentationPanelDescriptor panelDescriptor : extraPresentationDescriptor.getPanels()) {
for (Control vb : presentationSwitchFolder.getChildren()) {
if (vb.getData() instanceof SQLPresentationPanelDescriptor) { // || vb instanceof Label
vb.dispose();
sideBarChanged = true;
}
}
//}
// Close all panels
for (CTabItem tabItem : resultTabs.getItems()) {
if (tabItem.getData() instanceof SQLEditorPresentationPanel) {
tabItem.dispose();
}
}
extraPresentationCurrentPanel = null;
} else {
// Check and add presentation panel toggles
UIUtils.createEmptyLabel(presentationSwitchFolder, 1, 1).setLayoutData(new GridData(GridData.FILL_VERTICAL));
for (SQLPresentationPanelDescriptor panelDescriptor : extraPresentationDescriptor.getPanels()) {
removeToggleLayoutButton();
sideBarChanged = true;
PresentationPanelToggleAction toggleAction = new PresentationPanelToggleAction(panelDescriptor);
VerticalButton panelButton = new VerticalButton(presentationSwitchFolder, SWT.RIGHT);
panelButton.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_END));
panelButton.setAction(toggleAction, true);
panelButton.setData(panelDescriptor);
if (panelDescriptor.isAutoActivate()) {
//panelButton.setChecked(true);
toggleAction.run();
}
createToggleLayoutButton();
}
}
boolean isExtra = getExtraPresentationState() == SQLEditorPresentation.ActivationType.MAXIMIZED;
switchPresentationSQLButton.setChecked(!isExtra);
switchPresentationExtraButton.setChecked(isExtra);
presentationSwitchFolder.redraw();
if (sideBarChanged) {
topBarMan.update(true);
bottomBarMan.update(true);
topBarMan.getControl().getParent().layout(true);
bottomBarMan.getControl().getParent().layout(true);
}
presentationStack.layout(true, true);
} finally {
resultsSash.setRedraw(true);
}
}
private void createToggleLayoutButton() {
VerticalButton.create(presentationSwitchFolder, SWT.RIGHT | SWT.CHECK, getSite(), SQLEditorCommands.CMD_TOGGLE_LAYOUT, false);
}
private void removeToggleLayoutButton() {
for (VerticalButton vButton : presentationSwitchFolder.getItems()) {
if (vButton.getCommandId() != null && vButton.getCommandId().equals(SQLEditorCommands.CMD_TOGGLE_LAYOUT)) {
vButton.dispose();
}
}
}
private Control getExtraPresentationControl() {
return presentationStack == null ? null : presentationStack.getChildren()[EXTRA_CONTROL_INDEX];
}
public void toggleResultPanel(boolean switchFocus, boolean createQueryProcessor) {
UIUtils.syncExec(() -> {
if (resultsSash.getMaximizedControl() == null) {
resultsSash.setMaximizedControl(sqlEditorPanel);
switchFocus(false);
} else {
// Show both editor and results
// Check for existing query processors (maybe all result tabs were closed)
if (resultTabs.getItemCount() == 0 && createQueryProcessor) {
createQueryProcessor(true, true);
}
resultsSash.setMaximizedControl(null);
if (switchFocus) {
switchFocus(true);
}
}
});
}
public void toggleEditorMaximize()
{
if (resultsSash.getMaximizedControl() == null) {
resultsSash.setMaximizedControl(resultTabs);
switchFocus(true);
} else {
resultsSash.setMaximizedControl(null);
switchFocus(false);
}
}
private void switchFocus(boolean results) {
if (results) {
ResultSetViewer activeRS = getActiveResultSetViewer();
if (activeRS != null && activeRS.getActivePresentation() != null) {
activeRS.getActivePresentation().getControl().setFocus();
} else {
CTabItem activeTab = resultTabs.getSelection();
if (activeTab != null && activeTab.getControl() != null) {
activeTab.getControl().setFocus();
}
}
} else {
getEditorControlWrapper().setFocus();
}
}
public void toggleActivePanel() {
if (resultsSash.getMaximizedControl() == null) {
if (UIUtils.hasFocus(resultTabs)) {
switchFocus(false);
} else {
switchFocus(true);
}
}
}
private void updateResultSetOrientation() {
try {
resultSetOrientation = ResultSetOrientation.valueOf(DBWorkbench.getPlatform().getPreferenceStore().getString(SQLPreferenceConstants.RESULT_SET_ORIENTATION));
} catch (IllegalArgumentException e) {
resultSetOrientation = ResultSetOrientation.HORIZONTAL;
}
if (resultsSash != null) {
resultsSash.setOrientation(resultSetOrientation.getSashOrientation());
}
}
private class PresentationPanelToggleAction extends Action {
private SQLPresentationPanelDescriptor panel;
private CTabItem tabItem;
public PresentationPanelToggleAction(SQLPresentationPanelDescriptor panel) {
super(panel.getLabel(), Action.AS_CHECK_BOX);
setId(PANEL_ITEM_PREFIX + panel.getId());
if (panel.getIcon() != null) {
setImageDescriptor(DBeaverIcons.getImageDescriptor(panel.getIcon()));
}
if (panel.getDescription() != null) {
setToolTipText(panel.getDescription());
}
this.panel = panel;
}
@Override
public void run() {
if (resultsSash.getMaximizedControl() != null) {
resultsSash.setMaximizedControl(null);
}
setChecked(!isChecked());
SQLEditorPresentationPanel panelInstance = extraPresentationPanels.get(panel);
if (panelInstance != null && !isChecked()) {
// Hide panel
for (CTabItem tabItem : resultTabs.getItems()) {
if (tabItem.getData() == panelInstance) {
tabItem.dispose();
return;
}
}
}
if (panelInstance == null) {
Control panelControl;
try {
panelInstance = panel.createPanel();
panelControl = panelInstance.createPanel(resultTabs, SQLEditor.this, extraPresentation);
} catch (DBException e) {
DBWorkbench.getPlatformUI().showError("Panel opening error", "Can't create panel " + panel.getLabel(), e);
return;
}
extraPresentationPanels.put(panel, panelInstance);
tabItem = new CTabItem(resultTabs, SWT.CLOSE);
tabItem.setControl(panelControl);
tabItem.setText(panel.getLabel());
tabItem.setToolTipText(panel.getDescription());
tabItem.setImage(DBeaverIcons.getImage(panel.getIcon()));
tabItem.setData(panelInstance);
// De-select tool item on tab close
tabItem.addDisposeListener(e -> {
PresentationPanelToggleAction.this.setChecked(false);
panelControl.dispose();
extraPresentationPanels.remove(panel);
extraPresentationCurrentPanel = null;
resultTabDisposeListener.widgetDisposed(e);
});
extraPresentationCurrentPanel = panelInstance;
setResultTabSelection(tabItem);
} else {
for (CTabItem tabItem : resultTabs.getItems()) {
if (tabItem.getData() == panelInstance) {
setResultTabSelection(tabItem);
break;
}
}
}
}
}
/////////////////////////////////////////////////////////////
// Initialization
@Override
public void init(IEditorSite site, IEditorInput editorInput)
throws PartInitException
{
super.init(site, editorInput);
updateResultSetOrientation();
SQLScriptContext parentContext = null;
{
DatabaseEditorContext parentEditorContext = EditorUtils.getEditorContext(editorInput);
if (parentEditorContext instanceof SQLNavigatorContext) {
parentContext = ((SQLNavigatorContext) parentEditorContext).getScriptContext();
}
}
this.globalScriptContext = new SQLScriptContext(
parentContext,
this,
EditorUtils.getLocalFileFromInput(getEditorInput()),
new OutputLogWriter(),
new SQLEditorParametersProvider(getSite()));
this.globalScriptContext.addListener(new DBCScriptContextListener() {
@Override
public void variableChanged(ContextAction action, DBCScriptContext.VariableInfo variable) {
saveContextVariables();
}
@Override
public void parameterChanged(ContextAction action, String name, Object value) {
saveContextVariables();
}
private void saveContextVariables() {
new AbstractJob("Save variables") {
@Override
protected IStatus run(DBRProgressMonitor monitor) {
DBPDataSourceContainer ds = getDataSourceContainer();
if (ds != null) {
globalScriptContext.saveVariables(ds.getDriver(), null);
}
return Status.OK_STATUS;
}
}.schedule(200);
}
});
}
@Override
protected void doSetInput(IEditorInput editorInput)
{
// Check for file existence
try {
if (editorInput instanceof IFileEditorInput) {
final IFile file = ((IFileEditorInput) editorInput).getFile();
if (!file.exists()) {
file.create(new ByteArrayInputStream(new byte[]{}), true, new NullProgressMonitor());
}
}
} catch (Exception e) {
log.error("Error checking SQL file", e);
}
try {
super.doSetInput(editorInput);
} catch (Throwable e) {
// Something bad may happen. E.g. OutOfMemory error in case of too big input file.
StringWriter out = new StringWriter();
e.printStackTrace(new PrintWriter(out, true));
editorInput = new StringEditorInput("Error", CommonUtils.truncateString(out.toString(), 10000), true, GeneralUtils.UTF8_ENCODING);
doSetInput(editorInput);
log.error("Error loading input SQL file", e);
}
syntaxLoaded = false;
Runnable inputinitializer = () -> {
DBPDataSourceContainer oldDataSource = SQLEditor.this.getDataSourceContainer();
DBPDataSourceContainer newDataSource = EditorUtils.getInputDataSource(SQLEditor.this.getEditorInput());
if (oldDataSource != newDataSource) {
SQLEditor.this.dataSourceContainer = null;
SQLEditor.this.updateDataSourceContainer();
} else {
SQLEditor.this.reloadSyntaxRules();
}
};
if (isNonPersistentEditor()) {
inputinitializer.run();
} else {
// Run in queue - for app startup
UIExecutionQueue.queueExec(inputinitializer);
}
setPartName(getEditorName());
if (isNonPersistentEditor()) {
setTitleImage(DBeaverIcons.getImage(UIIcon.SQL_CONSOLE));
}
editorImage = getTitleImage();
}
@Override
public String getTitleToolTip() {
if (!DBWorkbench.getPlatform().getApplication().isStandalone()) {
// For Eclipse plugins return just title because it is used in main window title.
return getTitle();
}
DBPDataSourceContainer dataSourceContainer = getDataSourceContainer();
if (dataSourceContainer == null) {
return super.getTitleToolTip();
}
final IEditorInput editorInput = getEditorInput();
String scriptPath;
if (editorInput instanceof IFileEditorInput) {
scriptPath = ((IFileEditorInput) editorInput).getFile().getFullPath().toString();
} else if (editorInput instanceof IPathEditorInput) {
scriptPath = ((IPathEditorInput) editorInput).getPath().toString();
} else if (editorInput instanceof IURIEditorInput) {
final URI uri = ((IURIEditorInput) editorInput).getURI();
if ("file".equals(uri.getScheme())) {
scriptPath = new File(uri).getAbsolutePath();
} else {
scriptPath = uri.toString();
}
} else if (editorInput instanceof INonPersistentEditorInput) {
scriptPath = "SQL Console";
} else {
scriptPath = editorInput.getName();
if (CommonUtils.isEmpty(scriptPath)) {
scriptPath = "<not a file>";
}
}
StringBuilder tip = new StringBuilder();
tip
.append(NLS.bind(SQLEditorMessages.sql_editor_title_tooltip_path, scriptPath))
.append(" \n").append(NLS.bind(SQLEditorMessages.sql_editor_title_tooltip_connecton, dataSourceContainer.getName()))
.append(" \n").append(NLS.bind(SQLEditorMessages.sql_editor_title_tooltip_type, dataSourceContainer.getDriver().getFullName()))
.append(" \n").append(NLS.bind(SQLEditorMessages.sql_editor_title_tooltip_url, dataSourceContainer.getConnectionConfiguration().getUrl()));
SQLEditorVariablesResolver scriptNameResolver = new SQLEditorVariablesResolver(dataSourceContainer,
dataSourceContainer.getConnectionConfiguration(),
getExecutionContext(),
scriptPath,
null,
getProject());
if (scriptNameResolver.get(SQLPreferenceConstants.VAR_ACTIVE_DATABASE) != null) {
tip.append(" \n").append(NLS.bind(SQLEditorMessages.sql_editor_title_tooltip_database, scriptNameResolver.get(SQLPreferenceConstants.VAR_ACTIVE_DATABASE)));
}
if (scriptNameResolver.get(SQLPreferenceConstants.VAR_ACTIVE_SCHEMA) != null) {
tip.append(" \n").append(NLS.bind(SQLEditorMessages.sql_editor_title_tooltip_schema, scriptNameResolver.get(SQLPreferenceConstants.VAR_ACTIVE_SCHEMA)));
}
return tip.toString();
}
private String getEditorName() {
final IFile file = EditorUtils.getFileFromInput(getEditorInput());
String scriptName;
if (file != null) {
scriptName = file.getFullPath().removeFileExtension().lastSegment();
} else {
File localFile = EditorUtils.getLocalFileFromInput(getEditorInput());
if (localFile != null) {
scriptName = localFile.getName();
} else {
scriptName = getEditorInput().getName();
}
}
DBPPreferenceStore preferenceStore = getActivePreferenceStore();
String pattern = preferenceStore.getString(SQLPreferenceConstants.SCRIPT_TITLE_PATTERN);
return GeneralUtils.replaceVariables(pattern, new SQLEditorVariablesResolver(
dataSourceContainer,
null,
getExecutionContext(),
scriptName,
file,
getProject()));
}
@Override
public void setFocus() {
super.setFocus();
}
public void loadQueryPlan() {
DBCQueryPlanner planner = GeneralUtils.adapt(getDataSource(), DBCQueryPlanner.class);
ExplainPlanViewer planView = getPlanView(null, planner);
if (planView != null) {
if (!planView.loadQueryPlan(planner, planView)) {
closeActiveTab();
}
}
}
public void explainQueryPlan() {
// Notify listeners
synchronized (listeners) {
for (SQLEditorListener listener : listeners) {
listener.beforeQueryPlanExplain();
}
}
final SQLScriptElement scriptElement = extractActiveQuery();
if (scriptElement == null) {
setStatus(SQLEditorMessages.editors_sql_status_empty_query_string, DBPMessageType.ERROR);
return;
}
if (!(scriptElement instanceof SQLQuery)) {
setStatus("Can't explain plan for command", DBPMessageType.ERROR);
return;
}
explainQueryPlan((SQLQuery) scriptElement);
}
private void explainQueryPlan(SQLQuery sqlQuery) {
showResultsPanel(false);
DBCQueryPlanner planner = GeneralUtils.adapt(getDataSource(), DBCQueryPlanner.class);
DBCPlanStyle planStyle = planner.getPlanStyle();
if (planStyle == DBCPlanStyle.QUERY) {
explainPlanFromQuery(planner, sqlQuery);
} else if (planStyle == DBCPlanStyle.OUTPUT) {
explainPlanFromQuery(planner, sqlQuery);
showOutputPanel();
} else {
ExplainPlanViewer planView = getPlanView(sqlQuery, planner);
if (planView != null) {
planView.explainQueryPlan(sqlQuery, planner);
}
}
}
private void showResultsPanel(boolean createQueryProcessor) {
if (resultsSash.getMaximizedControl() != null) {
toggleResultPanel(false, createQueryProcessor);
}
UIUtils.syncExec(() -> {
if (resultsSash.isDownHidden()) {
resultsSash.showDown();
}
});
}
private ExplainPlanViewer getPlanView(SQLQuery sqlQuery, DBCQueryPlanner planner) {
// 1. Determine whether planner supports plan extraction
if (planner == null) {
DBWorkbench.getPlatformUI().showError("Execution plan", "Execution plan explain isn't supported by current datasource");
return null;
}
// Transform query parameters
if (sqlQuery != null) {
if (!transformQueryWithParameters(sqlQuery)) {
return null;
}
}
ExplainPlanViewer planView = null;
if (sqlQuery != null) {
for (CTabItem item : resultTabs.getItems()) {
if (item.getData() instanceof ExplainPlanViewer) {
ExplainPlanViewer pv = (ExplainPlanViewer) item.getData();
if (pv.getQuery() != null && pv.getQuery().equals(sqlQuery)) {
setResultTabSelection(item);
planView = pv;
break;
}
}
}
}
if (planView == null) {
int maxPlanNumber = 0;
for (CTabItem item : resultTabs.getItems()) {
if (item.getData() instanceof ExplainPlanViewer) {
maxPlanNumber = Math.max(maxPlanNumber, ((ExplainPlanViewer) item.getData()).getPlanNumber());
}
}
maxPlanNumber++;
planView = new ExplainPlanViewer(this, this, resultTabs, maxPlanNumber);
final CTabItem item = new CTabItem(resultTabs, SWT.CLOSE);
item.setControl(planView.getControl());
item.setText(SQLEditorMessages.editors_sql_error_execution_plan_title + " - " + maxPlanNumber);
if (sqlQuery != null) {
// Prepare query for tooltip
String preparedText = sqlQuery.getText().replaceAll("[\n\r\t]{3,}", "");
if (preparedText.length() > 300) {
item.setToolTipText(preparedText.substring(0, 300) + "...");
} else {
item.setToolTipText(preparedText);
}
}
item.setImage(IMG_EXPLAIN_PLAN);
item.setData(planView);
item.addDisposeListener(resultTabDisposeListener);
UIUtils.disposeControlOnItemDispose(item);
setResultTabSelection(item);
}
return planView;
}
private void explainPlanFromQuery(final DBCQueryPlanner planner, final SQLQuery sqlQuery) {
final String[] planQueryString = new String[1];
DBRRunnableWithProgress queryObtainTask = monitor -> {
DBCQueryPlannerConfiguration configuration = ExplainPlanViewer.makeExplainPlanConfiguration(monitor, planner);
if (configuration == null) {
return;
}
try (DBCSession session = getExecutionContext().openSession(monitor, DBCExecutionPurpose.UTIL, "Prepare plan query")) {
DBCPlan plan = planner.planQueryExecution(session, sqlQuery.getText(), configuration);
planQueryString[0] = plan.getPlanQueryString();
} catch (Exception e) {
log.error(e);
}
};
if (RuntimeUtils.runTask(queryObtainTask, "Retrieve plan query", 5000) && !CommonUtils.isEmpty(planQueryString[0])) {
SQLQuery planQuery = new SQLQuery(getDataSource(), planQueryString[0]);
processQueries(Collections.singletonList(planQuery), false, true, false, true, null, null);
}
}
public void processSQL(boolean newTab, boolean script) {
processSQL(newTab, script, null, null);
}
public boolean processSQL(boolean newTab, boolean script, SQLQueryTransformer transformer, @Nullable SQLQueryListener queryListener) {
return processSQL(newTab, script, false, transformer, queryListener);
}
public boolean processSQL(boolean newTab, boolean script, boolean executeFromPosition) {
return processSQL(newTab, script, executeFromPosition, null, null);
}
public boolean processSQL(boolean newTab, boolean script, boolean executeFromPosition, SQLQueryTransformer transformer,
@Nullable SQLQueryListener queryListener
) {
IDocument document = getDocument();
if (document == null) {
setStatus(SQLEditorMessages.editors_sql_status_cant_obtain_document, DBPMessageType.ERROR);
return false;
}
// Notify listeners
synchronized (listeners) {
for (SQLEditorListener listener : listeners) {
listener.beforeQueryExecute(script, newTab);
}
}
List<SQLScriptElement> elements;
if (script) {
if (executeFromPosition) {
// Get all queries from the current position
ITextSelection selection = (ITextSelection) getSelectionProvider().getSelection();
elements = extractScriptQueries(selection.getOffset(), document.getLength(), true, false, true);
// Replace first query with query under cursor for case if the cursor is in the middle of the query
elements.remove(0);
elements.add(0, extractActiveQuery());
} else {
// Execute all SQL statements consequently
ITextSelection selection = (ITextSelection) getSelectionProvider().getSelection();
if (selection.getLength() > 1) {
elements = extractScriptQueries(selection.getOffset(), selection.getLength(), true, false, true);
} else {
elements = extractScriptQueries(0, document.getLength(), true, false, true);
}
}
} else {
// Execute statement under cursor or selected text (if selection present)
SQLScriptElement sqlQuery = extractActiveQuery();
if (sqlQuery == null) {
ResultSetViewer activeViewer = getActiveResultSetViewer();
if (activeViewer != null) {
activeViewer.setStatus(SQLEditorMessages.editors_sql_status_empty_query_string, DBPMessageType.ERROR);
}
return false;
} else {
elements = Collections.singletonList(sqlQuery);
}
}
try {
if (transformer != null) {
DBPDataSource dataSource = getDataSource();
if (dataSource != null) {
List<SQLScriptElement> xQueries = new ArrayList<>(elements.size());
for (SQLScriptElement element : elements) {
if (element instanceof SQLQuery) {
SQLQuery query = transformer.transformQuery(dataSource, getSyntaxManager(), (SQLQuery) element);
if (!CommonUtils.isEmpty(query.getParameters())) {
query.setParameters(parseQueryParameters(query));
}
xQueries.add(query);
} else {
xQueries.add(element);
}
}
elements = xQueries;
}
}
}
catch (DBException e) {
DBWorkbench.getPlatformUI().showError("Bad query", "Can't execute query", e);
return false;
}
if (!CommonUtils.isEmpty(elements)) {
return processQueries(elements, script, newTab, false, true, queryListener, null);
} else {
return false;
}
}
public void exportDataFromQuery(@Nullable SQLScriptContext sqlScriptContext)
{
List<SQLScriptElement> elements;
ITextSelection selection = (ITextSelection) getSelectionProvider().getSelection();
if (selection.getLength() > 1) {
elements = extractScriptQueries(selection.getOffset(), selection.getLength(), true, false, true);
} else {
elements = new ArrayList<>();
elements.add(extractActiveQuery());
}
if (!elements.isEmpty()) {
processQueries(elements, false, false, true, true, null, sqlScriptContext);
} else {
DBWorkbench.getPlatformUI().showError(
"Extract data",
"Choose one or more queries to export from");
}
}
public boolean processQueries(@NotNull final List<SQLScriptElement> queries, final boolean forceScript,
boolean newTab, final boolean export, final boolean checkSession,
@Nullable final SQLQueryListener queryListener, @Nullable final SQLScriptContext context
) {
if (queries.isEmpty()) {
// Nothing to process
return false;
}
final DBPDataSourceContainer container = getDataSourceContainer();
if (checkSession) {
try {
boolean finalNewTab = newTab;
DBRProgressListener connectListener = status -> {
if (!status.isOK() || container == null || !container.isConnected()) {
DBWorkbench.getPlatformUI().showError(
SQLEditorMessages.editors_sql_error_cant_obtain_session,
null,
status);
return;
}
updateExecutionContext(() -> UIUtils.syncExec(() ->
processQueries(queries, forceScript, finalNewTab, export, false, queryListener, context)));
};
if (!checkSession(connectListener)) {
return false;
}
} catch (DBException ex) {
ResultSetViewer viewer = getActiveResultSetViewer();
if (viewer != null) {
viewer.setStatus(ex.getMessage(), DBPMessageType.ERROR);
}
DBWorkbench.getPlatformUI().showError(
SQLEditorMessages.editors_sql_error_cant_obtain_session,
ex.getMessage());
return false;
}
}
if (dataSourceContainer == null) {
return false;
}
if (!dataSourceContainer.hasModifyPermission(DBPDataSourcePermission.PERMISSION_EXECUTE_SCRIPTS)) {
DBWorkbench.getPlatformUI().showError(
SQLEditorMessages.editors_sql_error_cant_execute_query_title,
"Query execution was restricted by connection configuration");
return false;
}
SQLScriptContext scriptContext = context;
if (scriptContext == null) {
scriptContext = createScriptContext();
}
final boolean isSingleQuery = !forceScript && (queries.size() == 1);
if (isSingleQuery && queries.get(0) instanceof SQLQuery) {
SQLQuery query = (SQLQuery) queries.get(0);
boolean isDropTable = query.isDropTableDangerous();
if (query.isDeleteUpdateDangerous() || isDropTable) {
String targetName = "multiple tables";
if (query.getEntityMetadata(false) != null) {
targetName = query.getEntityMetadata(false).getEntityName();
}
if (ConfirmationDialog.showConfirmDialogEx(
ResourceBundle.getBundle(SQLEditorMessages.BUNDLE_NAME),
getSite().getShell(),
isDropTable ? SQLPreferenceConstants.CONFIRM_DROP_SQL : SQLPreferenceConstants.CONFIRM_DANGER_SQL,
ConfirmationDialog.CONFIRM,
ConfirmationDialog.WARNING,
query.getType().name(),
targetName) != IDialogConstants.OK_ID)
{
return false;
}
}
} else if (newTab && queries.size() > MAX_PARALLEL_QUERIES_NO_WARN) {
if (ConfirmationDialog.showConfirmDialogEx(
ResourceBundle.getBundle(SQLEditorMessages.BUNDLE_NAME),
getSite().getShell(),
SQLPreferenceConstants.CONFIRM_MASS_PARALLEL_SQL,
ConfirmationDialog.CONFIRM,
ConfirmationDialog.WARNING,
queries.size()) != IDialogConstants.OK_ID)
{
return false;
}
}
if (resultsSash.getMaximizedControl() != null) {
resultsSash.setMaximizedControl(null);
}
// Save editor
if (getActivePreferenceStore().getBoolean(SQLPreferenceConstants.AUTO_SAVE_ON_EXECUTE) && isDirty()) {
doSave(new NullProgressMonitor());
}
// Clear server console output
if (getActivePreferenceStore().getBoolean(SQLPreferenceConstants.CLEAR_OUTPUT_BEFORE_EXECUTE)) {
outputViewer.clearOutput();
}
boolean replaceCurrentTab = getActivePreferenceStore().getBoolean(SQLPreferenceConstants.RESULT_SET_REPLACE_CURRENT_TAB);
if (!export) {
// We only need to prompt user to close extra (unpinned) tabs if:
// 1. The user is not executing query in a new tab
// 2. The user is executing script that may open several result sets
// and replace current tab on single query execution option is not set
if (isResultSetAutoFocusEnabled && !newTab && (!isSingleQuery || (isSingleQuery && !replaceCurrentTab))) {
int tabsClosed = closeExtraResultTabs(null, true, false);
if (tabsClosed == IDialogConstants.CANCEL_ID) {
return false;
} else if (tabsClosed == IDialogConstants.NO_ID) {
newTab = true;
}
}
// Create new query processor if:
// 1. New tab is explicitly requested
// 1. Or all tabs are closed and no query processors are present
// 2. Or current query processor has pinned tabs
// 3. Or current query processor has running jobs
if (newTab || queryProcessors.isEmpty() || curQueryProcessor.hasPinnedTabs() || curQueryProcessor.getRunningJobs() > 0) {
boolean foundSuitableTab = false;
// Try to find suitable query processor among exiting ones if:
// 1. New tab is not required
// 2. The user is executing only single query
if (!newTab && isSingleQuery) {
for (QueryProcessor processor : queryProcessors) {
if (!processor.hasPinnedTabs() && processor.getRunningJobs() == 0) {
foundSuitableTab = true;
curQueryProcessor = processor;
break;
}
}
}
// Just create a new query processor
if (!foundSuitableTab) {
createQueryProcessor(true, false);
}
}
// Close all extra tabs of this query processor
// if the user is executing only single query
if (!newTab && isSingleQuery && curQueryProcessor.getResultContainers().size() > 1) {
closeExtraResultTabs(curQueryProcessor, false, true);
}
CTabItem tabItem = curQueryProcessor.getFirstResults().getTabItem();
if (tabItem != null) {
// Do not switch tab if Output tab is active
CTabItem selectedTab = resultTabs.getSelection();
if (selectedTab == null || selectedTab.getData() != outputViewer.getControl()) {
setResultTabSelection(tabItem);
}
}
}
if (curQueryProcessor == null) {
createQueryProcessor(true, true);
}
return curQueryProcessor.processQueries(
scriptContext,
queries,
forceScript,
false,
export,
!export && getActivePreferenceStore().getBoolean(SQLPreferenceConstants.RESULT_SET_CLOSE_ON_ERROR),
queryListener);
}
public boolean isActiveQueryRunning() {
return curQueryProcessor != null && curQueryProcessor.curJobRunning.get() > 0;
}
public void cancelActiveQuery() {
if (isActiveQueryRunning()) {
curQueryProcessor.cancelJob();
}
}
@NotNull
private SQLScriptContext createScriptContext() {
File localFile = EditorUtils.getLocalFileFromInput(getEditorInput());
return new SQLScriptContext(globalScriptContext, SQLEditor.this, localFile, new OutputLogWriter(), new SQLEditorParametersProvider(getSite()));
}
private void setStatus(String status, DBPMessageType messageType)
{
ResultSetViewer resultsView = getActiveResultSetViewer();
if (resultsView != null) {
resultsView.setStatus(status, messageType);
}
}
private int closeExtraResultTabs(@Nullable QueryProcessor queryProcessor, boolean confirmClose, boolean keepFirstTab) {
List<CTabItem> tabsToClose = new ArrayList<>();
for (CTabItem item : resultTabs.getItems()) {
if (item.getData() instanceof QueryResultsContainer && item.getShowClose()) {
QueryResultsContainer resultsProvider = (QueryResultsContainer)item.getData();
if (queryProcessor != null && queryProcessor != resultsProvider.queryProcessor) {
continue;
}
if (queryProcessor != null && queryProcessor.resultContainers.size() < 2 && keepFirstTab) {
// Do not remove first tab for this processor
continue;
}
tabsToClose.add(item);
} else if (item.getData() instanceof ExplainPlanViewer) {
tabsToClose.add(item);
}
}
if (tabsToClose.size() > 1 || (tabsToClose.size() == 1 && keepFirstTab)) {
int confirmResult = IDialogConstants.YES_ID;
if (confirmClose) {
confirmResult = ConfirmationDialog.showConfirmDialog(
ResourceBundle.getBundle(SQLEditorMessages.BUNDLE_NAME),
getSite().getShell(),
SQLPreferenceConstants.CONFIRM_RESULT_TABS_CLOSE,
ConfirmationDialog.QUESTION_WITH_CANCEL,
tabsToClose.size());
if (confirmResult == IDialogConstants.CANCEL_ID || confirmResult < 0) {
return IDialogConstants.CANCEL_ID;
}
}
if (confirmResult == IDialogConstants.YES_ID) {
for (int i = 0; i < tabsToClose.size(); i++) {
if (i == 0 && keepFirstTab) {
continue;
}
tabsToClose.get(i).dispose();
}
}
return confirmResult;
}
// No need to close anything
return IDialogConstants.IGNORE_ID;
}
public boolean transformQueryWithParameters(SQLQuery query) {
return createScriptContext().fillQueryParameters(query, false);
}
private boolean checkSession(DBRProgressListener onFinish)
throws DBException
{
DBPDataSourceContainer ds = getDataSourceContainer();
if (ds == null) {
throw new DBException("No active connection");
}
if (!ds.isConnected()) {
boolean doConnect = ds.getPreferenceStore().getBoolean(SQLPreferenceConstants.EDITOR_CONNECT_ON_EXECUTE);
if (doConnect) {
return checkConnected(true, onFinish);
} else {
throw new DBException("Disconnected from database");
}
}
DBPDataSource dataSource = ds.getDataSource();
if (dataSource != null && executionContextProvider == null && SQLEditorUtils.isOpenSeparateConnection(ds) && executionContext == null) {
initSeparateConnection(dataSource, () -> onFinish.onTaskFinished(Status.OK_STATUS));
return executionContext != null;
}
return true;
}
/**
* Handles datasource change action in UI
*/
private void fireDataSourceChange()
{
updateExecutionContext(null);
UIUtils.syncExec(this::onDataSourceChange);
}
private void onDataSourceChange()
{
if (resultsSash == null || resultsSash.isDisposed()) {
reloadSyntaxRules();
return;
}
DBPDataSourceContainer dsContainer = getDataSourceContainer();
if (resultTabs != null) {
DatabaseEditorUtils.setPartBackground(this, resultTabs);
Color bgColor = dsContainer == null ? null : UIUtils.getConnectionColor(dsContainer.getConnectionConfiguration());
resultsSash.setBackground(bgColor);
topBarMan.getControl().setBackground(bgColor);
bottomBarMan.getControl().setBackground(bgColor);
}
if (getSourceViewerConfiguration() instanceof SQLEditorSourceViewerConfiguration) {
((SQLEditorSourceViewerConfiguration) getSourceViewerConfiguration()).onDataSourceChange();
}
DBCExecutionContext executionContext = getExecutionContext();
if (executionContext != null) {
EditorUtils.setInputDataSource(getEditorInput(), new SQLNavigatorContext(executionContext));
}
refreshActions();
if (syntaxLoaded && lastExecutionContext == executionContext) {
return;
}
if (curResultsContainer != null) {
ResultSetViewer rsv = curResultsContainer.getResultSetController();
if (rsv != null) {
if (executionContext == null) {
rsv.setStatus(ModelMessages.error_not_connected_to_database);
} else {
rsv.setStatus(SQLEditorMessages.editors_sql_staus_connected_to + executionContext.getDataSource().getContainer().getName() + "'"); //$NON-NLS-2$
}
}
}
if (lastExecutionContext == null || executionContext == null || lastExecutionContext.getDataSource() != executionContext.getDataSource()) {
// Update command states
SQLEditorPropertyTester.firePropertyChange(SQLEditorPropertyTester.PROP_CAN_EXECUTE);
SQLEditorPropertyTester.firePropertyChange(SQLEditorPropertyTester.PROP_CAN_EXPLAIN);
reloadSyntaxRules();
}
if (dsContainer == null) {
resultsSash.setMaximizedControl(sqlEditorPanel);
} else {
if (curQueryProcessor != null && curQueryProcessor.getFirstResults().hasData()) {
resultsSash.setMaximizedControl(null);
}
}
lastExecutionContext = executionContext;
syntaxLoaded = true;
loadActivePreferenceSettings();
if (dsContainer != null) {
globalScriptContext.loadVariables(dsContainer.getDriver(), null);
} else {
globalScriptContext.clearVariables();
}
setPartName(getEditorName());
}
@Override
public void beforeConnect()
{
}
@Override
public void beforeDisconnect()
{
closeAllJobs();
}
@Override
public void dispose()
{
if (extraPresentation != null) {
extraPresentation.dispose();
extraPresentation = null;
}
// Release ds container
releaseContainer();
closeAllJobs();
final IEditorInput editorInput = getEditorInput();
IFile sqlFile = EditorUtils.getFileFromInput(editorInput);
logViewer = null;
outputViewer = null;
queryProcessors.clear();
curResultsContainer = null;
curQueryProcessor = null;
super.dispose();
if (sqlFile != null && !PlatformUI.getWorkbench().isClosing()) {
deleteFileIfEmpty(sqlFile);
}
}
private void deleteFileIfEmpty(IFile sqlFile) {
if (sqlFile == null || !sqlFile.exists()) {
return;
}
SQLPreferenceConstants.EmptyScriptCloseBehavior emptyScriptCloseBehavior = SQLPreferenceConstants.EmptyScriptCloseBehavior.getByName(
getActivePreferenceStore().getString(SQLPreferenceConstants.SCRIPT_DELETE_EMPTY));
if (emptyScriptCloseBehavior == SQLPreferenceConstants.EmptyScriptCloseBehavior.NOTHING) {
return;
}
if (!sqlFile.exists() || ResourceUtils.getFileLength(sqlFile) != 0) {
// Not empty
return;
}
try {
IProgressMonitor monitor = new NullProgressMonitor();
if (emptyScriptCloseBehavior == SQLPreferenceConstants.EmptyScriptCloseBehavior.DELETE_NEW) {
IFileState[] fileHistory = sqlFile.getHistory(monitor);
if (!ArrayUtils.isEmpty(fileHistory)) {
for (IFileState historyItem : fileHistory) {
try (InputStream contents = historyItem.getContents()) {
int cValue = contents.read();
if (cValue != -1) {
// At least once there was some content saved
return;
}
}
}
}
}
// This file is empty and never (at least during this session) had any contents.
// Drop it.
if (sqlFile.exists()) {
log.debug("Delete empty SQL script '" + sqlFile.getFullPath().toOSString() + "'");
sqlFile.delete(true, monitor);
}
} catch (Exception e) {
log.error("Error deleting empty script file", e); //$NON-NLS-1$
}
}
private void closeAllJobs()
{
for (QueryProcessor queryProcessor : queryProcessors) {
queryProcessor.closeJob();
}
}
private int getTotalQueryRunning() {
int jobsRunning = 0;
for (QueryProcessor queryProcessor : queryProcessors) {
jobsRunning += queryProcessor.curJobRunning.get();
}
return jobsRunning;
}
@Override
public void handleDataSourceEvent(final DBPEvent event)
{
final boolean dsEvent = event.getObject() == getDataSourceContainer();
final boolean objectEvent = event.getObject().getDataSource() == getDataSource();
if (dsEvent || objectEvent) {
UIUtils.asyncExec(
() -> {
switch (event.getAction()) {
case OBJECT_REMOVE:
if (dsEvent) {
setDataSourceContainer(null);
}
break;
case OBJECT_UPDATE:
case OBJECT_SELECT:
if (objectEvent) {
setPartName(getEditorName());
// Active schema was changed? Update title and tooltip
firePropertyChange(IWorkbenchPartConstants.PROP_TITLE);
}
break;
default:
break;
}
updateExecutionContext(null);
onDataSourceChange();
}
);
}
}
@Override
public void doSave(IProgressMonitor monitor) {
if (!EditorUtils.isInAutoSaveJob()) {
monitor.beginTask("Save data changes...", 1);
try {
monitor.subTask("Save '" + getPartName() + "' changes...");
SaveJob saveJob = new SaveJob();
saveJob.schedule();
// Wait until job finished
UIUtils.waitJobCompletion(saveJob);
if (!saveJob.success) {
monitor.setCanceled(true);
return;
}
} finally {
monitor.done();
}
}
if (extraPresentation instanceof ISaveablePart) {
((ISaveablePart) extraPresentation).doSave(monitor);
}
super.doSave(monitor);
updateDataSourceContainer();
}
@Override
public boolean isSaveAsAllowed()
{
return true;
}
@Override
public void doSaveAs()
{
saveToExternalFile();
}
private synchronized void doScriptAutoSave() {
if (scriptAutoSavejob == null) {
scriptAutoSavejob = new ScriptAutoSaveJob();
} else {
scriptAutoSavejob.cancel();
}
scriptAutoSavejob.schedule(1000);
}
@Override
public int promptToSaveOnClose()
{
int jobsRunning = getTotalQueryRunning();
if (jobsRunning > 0) {
log.warn("There are " + jobsRunning + " SQL job(s) still running in the editor");
if (ConfirmationDialog.showConfirmDialog(
ResourceBundle.getBundle(SQLEditorMessages.BUNDLE_NAME),
null,
SQLPreferenceConstants.CONFIRM_RUNNING_QUERY_CLOSE,
ConfirmationDialog.QUESTION,
jobsRunning) != IDialogConstants.YES_ID)
{
return ISaveablePart2.CANCEL;
}
}
for (QueryProcessor queryProcessor : queryProcessors) {
for (QueryResultsContainer resultsProvider : queryProcessor.getResultContainers()) {
ResultSetViewer rsv = resultsProvider.getResultSetController();
if (rsv != null && rsv.isDirty()) {
return rsv.promptToSaveOnClose();
}
}
}
// Cancel running jobs (if any) and close results tabs
for (QueryProcessor queryProcessor : queryProcessors) {
queryProcessor.cancelJob();
// FIXME: it is a hack (to avoid asking "Save script?" because editor is marked as dirty while queries are running)
// FIXME: make it better
queryProcessor.curJobRunning.set(0);
}
// End transaction
if (executionContext != null) {
UIServiceConnections serviceConnections = DBWorkbench.getService(UIServiceConnections.class);
if (serviceConnections != null && !serviceConnections.checkAndCloseActiveTransaction(new DBCExecutionContext[] {executionContext})) {
return ISaveablePart2.CANCEL;
}
}
// That's fine
if (isNonPersistentEditor()) {
return ISaveablePart2.NO;
}
updateDirtyFlag();
if (getActivePreferenceStore().getBoolean(SQLPreferenceConstants.AUTO_SAVE_ON_CLOSE)) {
return ISaveablePart2.YES;
}
if (super.isDirty() || (extraPresentation instanceof ISaveablePart && ((ISaveablePart) extraPresentation).isDirty())) {
return ISaveablePart2.DEFAULT;
}
return ISaveablePart2.YES;
}
protected void afterSaveToFile(File saveFile) {
try {
IFileStore fileStore = EFS.getStore(saveFile.toURI());
IEditorInput input = new FileStoreEditorInput(fileStore);
EditorUtils.setInputDataSource(input, new SQLNavigatorContext(getDataSourceContainer(), getExecutionContext()));
setInput(input);
} catch (CoreException e) {
DBWorkbench.getPlatformUI().showError("File save", "Can't open SQL editor from external file", e);
}
}
@Override
public void saveToExternalFile() {
saveToExternalFile(getScriptDirectory());
}
@Nullable
private String getScriptDirectory() {
final File inputFile = EditorUtils.getLocalFileFromInput(getEditorInput());
if (inputFile != null) {
return inputFile.getParent();
}
final DBPWorkspaceDesktop workspace = DBPPlatformDesktop.getInstance().getWorkspace();
final IFolder root = workspace.getResourceDefaultRoot(workspace.getActiveProject(), ScriptsHandlerImpl.class, false);
if (root != null) {
URI locationURI = root.getLocationURI();
if (locationURI.getScheme().equals("file")) {
return new File(locationURI).toString();
}
}
return null;
}
@Nullable
private ResultSetViewer getActiveResultSetViewer()
{
if (curResultsContainer != null) {
return curResultsContainer.getResultSetController();
}
return null;
}
private void showScriptPositionRuler(boolean show)
{
IColumnSupport columnSupport = getAdapter(IColumnSupport.class);
if (columnSupport != null) {
RulerColumnDescriptor positionColumn = RulerColumnRegistry.getDefault().getColumnDescriptor(ScriptPositionColumn.ID);
columnSupport.setColumnVisible(positionColumn, show);
}
}
private void showStatementInEditor(final SQLQuery query, final boolean select)
{
UIUtils.runUIJob("Select SQL query in editor", monitor -> {
if (isDisposed()) {
return;
}
if (select) {
selectAndReveal(query.getOffset(), query.getLength());
setStatus(query.getText(), DBPMessageType.INFORMATION);
} else {
getSourceViewer().revealRange(query.getOffset(), query.getLength());
}
});
}
@Override
public void reloadSyntaxRules() {
super.reloadSyntaxRules();
if (outputViewer != null) {
outputViewer.refreshStyles();
}
}
private QueryProcessor createQueryProcessor(boolean setSelection, boolean makeDefault)
{
final QueryProcessor queryProcessor = new QueryProcessor(makeDefault);
curQueryProcessor = queryProcessor;
curResultsContainer = queryProcessor.getFirstResults();
if (setSelection) {
CTabItem tabItem = curResultsContainer.getTabItem();
if (tabItem != null) {
setResultTabSelection(tabItem);
}
}
return queryProcessor;
}
@Override
public void preferenceChange(PreferenceChangeEvent event) {
switch (event.getProperty()) {
case ModelPreferences.SCRIPT_STATEMENT_DELIMITER:
case ModelPreferences.SCRIPT_IGNORE_NATIVE_DELIMITER:
case ModelPreferences.SCRIPT_STATEMENT_DELIMITER_BLANK:
case ModelPreferences.SQL_PARAMETERS_ENABLED:
case ModelPreferences.SQL_ANONYMOUS_PARAMETERS_MARK:
case ModelPreferences.SQL_ANONYMOUS_PARAMETERS_ENABLED:
case ModelPreferences.SQL_VARIABLES_ENABLED:
case ModelPreferences.SQL_NAMED_PARAMETERS_PREFIX:
case ModelPreferences.SQL_CONTROL_COMMAND_PREFIX:
reloadSyntaxRules();
return;
case SQLPreferenceConstants.RESULT_SET_ORIENTATION:
updateResultSetOrientation();
return;
case SQLPreferenceConstants.EDITOR_SEPARATE_CONNECTION: {
// Save current datasource (we want to keep it here)
DBPDataSource dataSource = curDataSource;
releaseExecutionContext();
// Restore cur data source (as it is reset in releaseExecutionContext)
curDataSource = dataSource;
if (dataSource != null && SQLEditorUtils.isOpenSeparateConnection(dataSource.getContainer())) {
initSeparateConnection(dataSource, null);
}
return;
}
case SQLPreferenceConstants.SCRIPT_TITLE_PATTERN:
setPartName(getEditorName());
return;
}
fireDataSourceChanged(event);
super.preferenceChange(event);
}
private void fireDataSourceChanged(PreferenceChangeEvent event) {
// Notify listeners
synchronized (listeners) {
for (SQLEditorListener listener : listeners) {
try {
listener.onDataSourceChanged(event);
} catch (Throwable ex) {
ex.printStackTrace();
}
}
}
}
public enum ResultSetOrientation {
HORIZONTAL(SWT.VERTICAL, SQLEditorMessages.sql_editor_result_set_orientation_horizontal, SQLEditorMessages.sql_editor_result_set_orientation_horizontal_tip, true),
VERTICAL(SWT.HORIZONTAL, SQLEditorMessages.sql_editor_result_set_orientation_vertical, SQLEditorMessages.sql_editor_result_set_orientation_vertical_tip, true),
DETACHED(SWT.VERTICAL, SQLEditorMessages.sql_editor_result_set_orientation_detached, SQLEditorMessages.sql_editor_result_set_orientation_detached_tip, false);
private final int sashOrientation;
private final String label;
private final String description;
private final boolean supported;
ResultSetOrientation(int sashOrientation, String label, String description, boolean supported) {
this.sashOrientation = sashOrientation;
this.label = label;
this.description = description;
this.supported = supported;
}
public int getSashOrientation() {
return sashOrientation;
}
public String getLabel() {
return label;
}
public String getDescription() {
return description;
}
public boolean isSupported() {
return supported;
}
}
public static class ResultSetOrientationMenuContributor extends CompoundContributionItem
{
@Override
protected IContributionItem[] getContributionItems() {
IEditorPart activeEditor = UIUtils.getActiveWorkbenchWindow().getActivePage().getActiveEditor();
if (!(activeEditor instanceof SQLEditorBase)) {
return new IContributionItem[0];
}
final DBPPreferenceStore preferenceStore = DBWorkbench.getPlatform().getPreferenceStore();
String curPresentation = preferenceStore.getString(SQLPreferenceConstants.RESULT_SET_ORIENTATION);
ResultSetOrientation[] orientations = ResultSetOrientation.values();
List<IContributionItem> items = new ArrayList<>(orientations.length);
for (final ResultSetOrientation orientation : orientations) {
Action action = new Action(orientation.getLabel(), Action.AS_RADIO_BUTTON) {
@Override
public void run() {
preferenceStore.setValue(SQLPreferenceConstants.RESULT_SET_ORIENTATION, orientation.name());
PrefUtils.savePreferenceStore(preferenceStore);
}
};
action.setDescription(orientation.getDescription());
if (!orientation.isSupported()) {
action.setEnabled(false);
}
if (orientation.name().equals(curPresentation)) {
action.setChecked(true);
}
items.add(new ActionContributionItem(action));
}
return items.toArray(new IContributionItem[0]);
}
}
public class QueryProcessor implements SQLResultsConsumer, ISmartTransactionManager {
private volatile SQLQueryJob curJob;
private AtomicInteger curJobRunning = new AtomicInteger(0);
private final List<QueryResultsContainer> resultContainers = new ArrayList<>();
private volatile DBDDataReceiver curDataReceiver = null;
QueryProcessor(boolean makeDefault) {
// Create first (default) results provider
if (makeDefault) {
queryProcessors.add(0, this);
} else {
queryProcessors.add(this);
}
createResultsProvider(0, makeDefault);
}
int getRunningJobs() {
return curJobRunning.get();
}
private QueryResultsContainer createResultsProvider(int resultSetNumber, boolean makeDefault) {
QueryResultsContainer resultsProvider = new QueryResultsContainer(this, resultSetNumber, getMaxResultsTabIndex() + 1, makeDefault);
resultContainers.add(resultsProvider);
return resultsProvider;
}
private QueryResultsContainer createResultsProvider(DBSDataContainer dataContainer) {
QueryResultsContainer resultsProvider = new QueryResultsContainer(this, resultContainers.size(), getMaxResultsTabIndex(), dataContainer);
resultContainers.add(resultsProvider);
return resultsProvider;
}
public boolean hasPinnedTabs() {
for (QueryResultsContainer container : resultContainers) {
if (container.isPinned()) {
return true;
}
}
return false;
}
@NotNull
QueryResultsContainer getFirstResults()
{
return resultContainers.get(0);
}
@Nullable
QueryResultsContainer getResults(SQLQuery query) {
for (QueryResultsContainer provider : resultContainers) {
if (provider.query == query) {
return provider;
}
}
return null;
}
List<QueryResultsContainer> getResultContainers() {
return resultContainers;
}
private void closeJob()
{
final SQLQueryJob job = curJob;
if (job != null) {
if (job.getState() == Job.RUNNING) {
job.cancel();
}
curJob = null;
if (job.isJobOpen()) {
RuntimeUtils.runTask(monitor -> {
job.closeJob();
}, "Close SQL job", 2000, true);
}
}
}
public void cancelJob() {
for (QueryResultsContainer rc : resultContainers) {
rc.viewer.cancelJobs();
}
final SQLQueryJob job = curJob;
if (job != null) {
if (job.getState() == Job.RUNNING) {
job.cancel();
}
}
}
boolean processQueries(SQLScriptContext scriptContext, final List<SQLScriptElement> queries, boolean forceScript, final boolean fetchResults, boolean export, boolean closeTabOnError, SQLQueryListener queryListener)
{
if (queries.isEmpty()) {
// Nothing to process
return false;
}
if (curJobRunning.get() > 0) {
DBWorkbench.getPlatformUI().showError(
SQLEditorMessages.editors_sql_error_cant_execute_query_title,
SQLEditorMessages.editors_sql_error_cant_execute_query_message);
return false;
}
final DBCExecutionContext executionContext = getExecutionContext();
if (executionContext == null) {
DBWorkbench.getPlatformUI().showError(
SQLEditorMessages.editors_sql_error_cant_execute_query_title,
ModelMessages.error_not_connected_to_database);
return false;
}
final boolean isSingleQuery = !forceScript && (queries.size() == 1);
// Prepare execution job
{
showScriptPositionRuler(true);
QueryResultsContainer resultsContainer = getFirstResults();
SQLEditorQueryListener listener = new SQLEditorQueryListener(this, closeTabOnError);
if (queryListener != null) {
listener.setExtListener(queryListener);
}
if (export) {
List<IDataTransferProducer<?>> producers = new ArrayList<>();
for (int i = 0; i < queries.size(); i++) {
SQLScriptElement element = queries.get(i);
if (element instanceof SQLControlCommand) {
try {
scriptContext.executeControlCommand((SQLControlCommand) element);
} catch (DBException e) {
DBWorkbench.getPlatformUI().showError("Command error", "Error processing control command", e);
}
} else {
SQLQuery query = (SQLQuery) element;
scriptContext.fillQueryParameters(query, false);
SQLQueryDataContainer dataContainer = new SQLQueryDataContainer(SQLEditor.this, query, scriptContext, log);
producers.add(new DatabaseTransferProducer(dataContainer, null));
}
}
DataTransferWizard.openWizard(
getSite().getWorkbenchWindow(),
producers,
null,
new StructuredSelection(this));
} else {
final SQLQueryJob job = new SQLQueryJob(
getSite(),
isSingleQuery ? SQLEditorMessages.editors_sql_job_execute_query : SQLEditorMessages.editors_sql_job_execute_script,
executionContext,
resultsContainer,
queries,
scriptContext,
this,
listener);
if (isSingleQuery) {
resultsContainer.query = queries.get(0);
closeJob();
curJob = job;
ResultSetViewer rsv = resultsContainer.getResultSetController();
if (rsv != null) {
rsv.resetDataFilter(false);
rsv.resetHistory();
rsv.refresh();
}
} else {
if (fetchResults) {
job.setFetchResultSets(true);
}
job.schedule();
curJob = job;
}
}
}
return true;
}
public boolean isDirty() {
for (QueryResultsContainer resultsProvider : resultContainers) {
ResultSetViewer rsv = resultsProvider.getResultSetController();
if (rsv != null && rsv.isDirty()) {
return true;
}
}
return false;
}
void removeResults(QueryResultsContainer resultsContainer) {
resultContainers.remove(resultsContainer);
if (resultContainers.isEmpty()) {
queryProcessors.remove(this);
if (curQueryProcessor == this) {
if (queryProcessors.isEmpty()) {
curQueryProcessor = null;
curResultsContainer = null;
} else {
curQueryProcessor = queryProcessors.get(0);
curResultsContainer = curQueryProcessor.getFirstResults();
}
}
}
}
@Nullable
@Override
public DBDDataReceiver getDataReceiver(final SQLQuery statement, final int resultSetNumber) {
if (curDataReceiver != null) {
return curDataReceiver;
}
final boolean isStatsResult = (statement != null && statement.getData() == SQLQueryJob.STATS_RESULTS);
// if (isStatsResult) {
// // Maybe it was already open
// for (QueryResultsProvider provider : resultContainers) {
// if (provider.query != null && provider.query.getData() == SQLQueryJob.STATS_RESULTS) {
// resultSetNumber = provider.resultSetNumber;
// break;
// }
// }
// }
if (resultSetNumber >= resultContainers.size() && !isDisposed()) {
// Open new results processor in UI thread
UIUtils.syncExec(() -> createResultsProvider(resultSetNumber, false));
}
if (resultSetNumber >= resultContainers.size()) {
// Editor seems to be disposed - no data receiver
return null;
}
final QueryResultsContainer resultsProvider = resultContainers.get(resultSetNumber);
if (statement != null && !resultTabs.isDisposed()) {
resultsProvider.query = statement;
resultsProvider.lastGoodQuery = statement;
String tabName = null;
String queryText = CommonUtils.truncateString(statement.getText(), 1000);
DBPDataSourceContainer dataSourceContainer = getDataSourceContainer();
String toolTip =
"Connection: " + (dataSourceContainer == null ? "N/A" : dataSourceContainer.getName()) + GeneralUtils.getDefaultLineSeparator() +
"Time: " + new SimpleDateFormat(DBConstants.DEFAULT_TIMESTAMP_FORMAT).format(new Date()) + GeneralUtils.getDefaultLineSeparator() +
"Query: " + (CommonUtils.isEmpty(queryText) ? "N/A" : queryText);
// Special statements (not real statements) have their name in data
if (isStatsResult) {
tabName = SQLEditorMessages.editors_sql_statistics;
int queryIndex = queryProcessors.indexOf(QueryProcessor.this);
tabName += " " + (queryIndex + 1);
}
String finalTabName = tabName;
UIUtils.asyncExec(() -> resultsProvider.updateResultsName(finalTabName, toolTip));
}
ResultSetViewer rsv = resultsProvider.getResultSetController();
return rsv == null ? null : rsv.getDataReceiver();
}
@Override
public boolean isSmartAutoCommit() {
return SQLEditor.this.isSmartAutoCommit();
}
@Override
public void setSmartAutoCommit(boolean smartAutoCommit) {
SQLEditor.this.setSmartAutoCommit(smartAutoCommit);
}
}
public class QueryResultsContainer implements
DBSDataContainer,
IResultSetContainer,
IResultSetValueReflector,
IResultSetListener,
IResultSetContainerExt,
SQLQueryContainer,
ISmartTransactionManager,
IQueryExecuteController {
private final QueryProcessor queryProcessor;
private final ResultSetViewer viewer;
private int resultSetNumber;
private final int resultSetIndex;
private SQLScriptElement query = null;
private SQLScriptElement lastGoodQuery = null;
// Data container and filter are non-null only in case of associations navigation
private DBSDataContainer dataContainer;
private CTabItem resultsTab;
private String tabName;
private QueryResultsContainer(QueryProcessor queryProcessor, int resultSetNumber, int resultSetIndex, boolean makeDefault) {
this.queryProcessor = queryProcessor;
this.resultSetNumber = resultSetNumber;
this.resultSetIndex = resultSetIndex;
boolean detachedViewer = false;
SQLResultsView sqlView = null;
if (detachedViewer) {
try {
sqlView = (SQLResultsView) getSite().getPage().showView(SQLResultsView.VIEW_ID, null, IWorkbenchPage.VIEW_CREATE);
} catch (Throwable e) {
DBWorkbench.getPlatformUI().showError("Detached results", "Can't open results view", e);
}
}
if (sqlView != null) {
// Detached results viewer
sqlView.setContainer(this);
this.viewer = sqlView.getViewer();
} else {
// Embedded results viewer
this.viewer = new ResultSetViewer(resultTabs, getSite(), this);
this.viewer.addListener(this);
int tabCount = resultTabs.getItemCount();
int tabIndex = 0;
if (!makeDefault) {
for (int i = tabCount; i > 0; i--) {
if (resultTabs.getItem(i - 1).getData() instanceof QueryResultsContainer) {
tabIndex = i;
break;
}
}
}
resultsTab = new CTabItem(resultTabs, SWT.NONE, tabIndex);
resultsTab.setImage(IMG_DATA_GRID);
resultsTab.setData(this);
resultsTab.setShowClose(true);
resultsTab.setText(getResultsTabName(resultSetNumber, getQueryIndex(), null));
CSSUtils.setCSSClass(resultsTab, DBStyles.COLORED_BY_CONNECTION_TYPE);
resultsTab.setControl(viewer.getControl());
resultsTab.addDisposeListener(resultTabDisposeListener);
UIUtils.disposeControlOnItemDispose(resultsTab);
}
viewer.getControl().addDisposeListener(e -> {
QueryResultsContainer.this.queryProcessor.removeResults(QueryResultsContainer.this);
if (QueryResultsContainer.this == curResultsContainer) {
curResultsContainer = null;
}
});
}
QueryResultsContainer(QueryProcessor queryProcessor, int resultSetNumber, int resultSetIndex, DBSDataContainer dataContainer) {
this(queryProcessor, resultSetNumber, resultSetIndex, false);
this.dataContainer = dataContainer;
updateResultsName(getResultsTabName(resultSetNumber, 0, dataContainer.getName()), null);
}
private CTabItem getTabItem() {
return resultsTab;
}
public int getResultSetIndex() {
return resultSetIndex;
}
public int getQueryIndex() {
return queryProcessors.indexOf(queryProcessor);
}
void updateResultsName(String resultSetName, String toolTip) {
if (resultTabs == null || resultTabs.isDisposed()) {
return;
}
if (CommonUtils.isEmpty(resultSetName)) {
resultSetName = tabName;
}
CTabItem tabItem = getTabItem();
if (tabItem != null && !tabItem.isDisposed()) {
if (!CommonUtils.isEmpty(resultSetName)) {
tabItem.setText(resultSetName);
}
if (toolTip != null) {
tabItem.setToolTipText(toolTip);
}
}
}
boolean isPinned() {
CTabItem tabItem = getTabItem();
return tabItem != null && !tabItem.isDisposed() && !tabItem.getShowClose();
}
void setPinned(boolean pinned) {
CTabItem tabItem = getTabItem();
if (tabItem != null) {
tabItem.setShowClose(!pinned);
tabItem.setImage(pinned ? IMG_DATA_GRID_LOCKED : IMG_DATA_GRID);
}
}
@NotNull
@Override
public DBPProject getProject() {
return SQLEditor.this.getProject();
}
@Override
public DBCExecutionContext getExecutionContext() {
return SQLEditor.this.getExecutionContext();
}
@Nullable
@Override
public ResultSetViewer getResultSetController()
{
return viewer;
}
boolean hasData() {
return viewer != null && viewer.hasData();
}
@Nullable
@Override
public DBSDataContainer getDataContainer()
{
return this;
}
@Override
public boolean isReadyToRun()
{
return queryProcessor.curJob == null || queryProcessor.curJobRunning.get() <= 0;
}
@Override
public void openNewContainer(DBRProgressMonitor monitor, @NotNull DBSDataContainer dataContainer, @NotNull DBDDataFilter newFilter) {
UIUtils.syncExec(() -> {
QueryResultsContainer resultsProvider = queryProcessor.createResultsProvider(dataContainer);
CTabItem tabItem = resultsProvider.getTabItem();
if (tabItem != null) {
tabItem.getParent().setSelection(tabItem);
}
setActiveResultsContainer(resultsProvider);
resultsProvider.viewer.refreshWithFilter(newFilter);
});
}
@Override
public IResultSetDecorator createResultSetDecorator() {
return new QueryResultsDecorator() {
@Override
public String getEmptyDataDescription() {
String execQuery = ActionUtils.findCommandDescription(SQLEditorCommands.CMD_EXECUTE_STATEMENT, getSite(), true);
String execScript = ActionUtils.findCommandDescription(SQLEditorCommands.CMD_EXECUTE_SCRIPT, getSite(), true);
return NLS.bind(ResultSetMessages.sql_editor_resultset_filter_panel_control_execute_to_see_reslut, execQuery, execScript);
}
};
}
@Override
public String[] getSupportedFeatures()
{
if (dataContainer != null) {
return dataContainer.getSupportedFeatures();
}
List<String> features = new ArrayList<>(3);
features.add(FEATURE_DATA_SELECT);
if (query instanceof SQLQuery && ((SQLQuery) query).isModifiyng()) {
features.add(FEATURE_DATA_MODIFIED_ON_REFRESH);
}
features.add(FEATURE_DATA_COUNT);
if (getQueryResultCounts() <= 1) {
features.add(FEATURE_DATA_FILTER);
}
return features.toArray(new String[0]);
}
@NotNull
@Override
public DBCStatistics readData(@NotNull DBCExecutionSource source, @NotNull DBCSession session, @NotNull DBDDataReceiver dataReceiver, DBDDataFilter dataFilter, long firstRow, long maxRows, long flags, int fetchSize) throws DBCException
{
if (dataContainer != null) {
return dataContainer.readData(source, session, dataReceiver, dataFilter, firstRow, maxRows, flags, fetchSize);
}
final SQLQueryJob job = queryProcessor.curJob;
if (job == null) {
throw new DBCException("No active query - can't read data");
}
if (this.query instanceof SQLQuery) {
SQLQuery query = (SQLQuery) this.query;
if (query.getResultsMaxRows() >= 0) {
firstRow = query.getResultsOffset();
maxRows = query.getResultsMaxRows();
}
}
try {
if (dataReceiver != viewer.getDataReceiver()) {
// Some custom receiver. Probably data export
queryProcessor.curDataReceiver = dataReceiver;
} else {
queryProcessor.curDataReceiver = null;
}
// Count number of results for this query. If > 1 then we will refresh them all at once
int resultCounts = getQueryResultCounts();
if (resultCounts <= 1 && resultSetNumber > 0) {
job.setFetchResultSetNumber(resultSetNumber);
} else {
job.setFetchResultSetNumber(-1);
}
job.setResultSetLimit(firstRow, maxRows);
job.setDataFilter(dataFilter);
job.setFetchSize(fetchSize);
job.setFetchFlags(flags);
job.extractData(session, this.query, resultCounts > 1 ? 0 : resultSetNumber);
lastGoodQuery = job.getLastGoodQuery();
return job.getStatistics();
} finally {
// Nullify custom data receiver
queryProcessor.curDataReceiver = null;
}
}
private int getQueryResultCounts() {
int resultCounts = 0;
for (QueryResultsContainer qrc : queryProcessor.resultContainers) {
if (qrc.query == query) {
resultCounts++;
}
}
return resultCounts;
}
@Override
public long countData(@NotNull DBCExecutionSource source, @NotNull DBCSession session, @Nullable DBDDataFilter dataFilter, long flags)
throws DBCException
{
if (dataContainer != null) {
return dataContainer.countData(source, session, dataFilter, DBSDataContainer.FLAG_NONE);
}
DBPDataSource dataSource = getDataSource();
if (dataSource == null) {
throw new DBCException("Query transform is not supported by datasource");
}
if (!(query instanceof SQLQuery)) {
throw new DBCException("Can't count rows for control command");
}
try {
SQLQuery countQuery = new SQLQueryTransformerCount().transformQuery(dataSource, getSyntaxManager(), (SQLQuery) query);
if (!CommonUtils.isEmpty(countQuery.getParameters())) {
countQuery.setParameters(parseQueryParameters(countQuery));
}
try (DBCStatement dbStatement = DBUtils.makeStatement(source, session, DBCStatementType.SCRIPT, countQuery, 0, 0)) {
if (dbStatement.executeStatement()) {
try (DBCResultSet rs = dbStatement.openResultSet()) {
if (rs.nextRow()) {
List<DBCAttributeMetaData> resultAttrs = rs.getMeta().getAttributes();
Object countValue = null;
if (resultAttrs.size() == 1) {
countValue = rs.getAttributeValue(0);
} else {
// In some databases (Influx?) SELECT count(*) produces multiple columns. Try to find first one with 'count' in its name.
for (int i = 0; i < resultAttrs.size(); i++) {
DBCAttributeMetaData ma = resultAttrs.get(i);
if (ma.getName().toLowerCase(Locale.ENGLISH).contains("count")) {
countValue = rs.getAttributeValue(i);
break;
}
}
}
if (countValue instanceof Map && ((Map<?, ?>) countValue).size() == 1) {
// For document-based DBs
Object singleValue = ((Map<?, ?>) countValue).values().iterator().next();
if (singleValue instanceof Number) {
countValue = singleValue;
}
}
if (countValue instanceof Number) {
return ((Number) countValue).longValue();
} else {
throw new DBCException("Unexpected row count value: " + countValue);
}
} else {
throw new DBCException("Row count result is empty");
}
}
} else {
throw new DBCException("Row count query didn't return any value");
}
}
} catch (DBException e) {
throw new DBCException("Error executing row count", e);
}
}
@Nullable
@Override
public String getDescription()
{
if (dataContainer != null) {
return dataContainer.getDescription();
} else {
return SQLEditorMessages.editors_sql_description;
}
}
@Nullable
@Override
public DBSObject getParentObject()
{
return getDataSource();
}
@Nullable
@Override
public DBPDataSource getDataSource()
{
return SQLEditor.this.getDataSource();
}
@Override
public boolean isPersisted() {
return dataContainer == null || dataContainer.isPersisted();
}
@NotNull
@Override
public String getName()
{
if (dataContainer != null) {
return dataContainer.getName();
}
String name = lastGoodQuery != null ?
lastGoodQuery.getOriginalText() :
(query == null ? null : query.getOriginalText());
if (name == null) {
name = "SQL";
}
return name;
}
@Nullable
@Override
public DBPDataSourceContainer getDataSourceContainer() {
return SQLEditor.this.getDataSourceContainer();
}
@Override
public String toString() {
if (dataContainer != null) {
return dataContainer.toString();
}
return query == null ?
"SQL Query / " + SQLEditor.this.getEditorInput().getName() :
query.getOriginalText();
}
@Override
public void handleResultSetLoad() {
}
@Override
public void handleResultSetChange() {
updateDirtyFlag();
}
@Override
public void handleResultSetSelectionChange(SelectionChangedEvent event) {
}
@Override
public void onModelPrepared() {
notifyOnDataListeners(this);
}
@Override
public SQLScriptContext getScriptContext() {
return SQLEditor.this.getGlobalScriptContext();
}
@Override
public SQLScriptElement getQuery() {
return query;
}
@Override
public Map<String, Object> getQueryParameters() {
return globalScriptContext.getAllParameters();
}
@Override
public boolean isSmartAutoCommit() {
return SQLEditor.this.isSmartAutoCommit();
}
@Override
public void setSmartAutoCommit(boolean smartAutoCommit) {
SQLEditor.this.setSmartAutoCommit(smartAutoCommit);
}
public void setTabName(String tabName) {
this.tabName = tabName;
resultsTab.setText(tabName);
}
@Override
public void insertCurrentCellValue(DBDAttributeBinding attributeBinding, Object cellValue, String stringValue) {
StyledText textWidget = getTextViewer() == null ? null : getTextViewer().getTextWidget();
if (textWidget != null) {
String sqlValue;
if (getDataSource() != null) {
sqlValue = SQLUtils.convertValueToSQL(getDataSource(), attributeBinding, cellValue);
} else {
sqlValue = stringValue;
}
textWidget.insert(sqlValue);
textWidget.setCaretOffset(textWidget.getCaretOffset() + sqlValue.length());
textWidget.setFocus();
}
}
@Override
public void forceDataReadCancel(Throwable error) {
for (QueryProcessor processor : queryProcessors) {
SQLQueryJob job = processor.curJob;
if (job != null) {
SQLQueryResult currentQueryResult = job.getCurrentQueryResult();
if (currentQueryResult == null) {
currentQueryResult = new SQLQueryResult(new SQLQuery(null, ""));
}
currentQueryResult.setError(error);
job.notifyQueryExecutionEnd(currentQueryResult);
}
}
}
@Override
public void handleExecuteResult(DBCExecutionResult result) {
dumpQueryServerOutput(result);
}
@Override
public void showCurrentError() {
if (getLastQueryErrorPosition() > -1) {
getSelectionProvider().setSelection(new TextSelection(getLastQueryErrorPosition(), 0));
setFocus();
}
}
}
private int getMaxResultsTabIndex() {
int maxIndex = 0;
for (CTabItem tab : resultTabs.getItems()) {
if (tab.getData() instanceof QueryResultsContainer) {
maxIndex = Math.max(maxIndex, ((QueryResultsContainer) tab.getData()).getResultSetIndex());
}
}
return maxIndex;
}
private String getResultsTabName(int resultSetNumber, int queryIndex, String name) {
String tabName = name;
if (CommonUtils.isEmpty(tabName)) {
tabName = SQLEditorMessages.editors_sql_data_grid;
}
tabName += " " + (queryIndex + 1);
if (resultSetNumber > 0) {
tabName += " (" + (resultSetNumber + 1) + ")";
}
return tabName;
}
private class SQLEditorQueryListener implements SQLQueryListener {
private final QueryProcessor queryProcessor;
private boolean scriptMode;
private long lastUIUpdateTime;
private final ITextSelection originalSelection = (ITextSelection) getSelectionProvider().getSelection();
private int topOffset, visibleLength;
private boolean closeTabOnError;
private SQLQueryListener extListener;
private SQLEditorQueryListener(QueryProcessor queryProcessor, boolean closeTabOnError) {
this.queryProcessor = queryProcessor;
this.closeTabOnError = closeTabOnError;
}
public SQLQueryListener getExtListener() {
return extListener;
}
public void setExtListener(SQLQueryListener extListener) {
this.extListener = extListener;
}
@Override
public void onStartScript() {
try {
lastUIUpdateTime = -1;
scriptMode = true;
UIUtils.asyncExec(() -> {
if (isDisposed()) {
return;
}
if (getActivePreferenceStore().getBoolean(SQLPreferenceConstants.MAXIMIZE_EDITOR_ON_SCRIPT_EXECUTE)
&& isResultSetAutoFocusEnabled) {
resultsSash.setMaximizedControl(sqlEditorPanel);
}
clearProblems(null);
});
} finally {
if (extListener != null) extListener.onStartScript();
}
}
@Override
public void onStartQuery(DBCSession session, final SQLQuery query) {
try {
boolean isInExecute = getTotalQueryRunning() > 0;
if (!isInExecute) {
UIUtils.asyncExec(() -> {
setTitleImage(DBeaverIcons.getImage(UIIcon.SQL_SCRIPT_EXECUTE));
updateDirtyFlag();
if (!scriptMode) {
clearProblems(query);
}
});
}
queryProcessor.curJobRunning.incrementAndGet();
synchronized (runningQueries) {
runningQueries.add(query);
}
if (lastUIUpdateTime < 0 || System.currentTimeMillis() - lastUIUpdateTime > SCRIPT_UI_UPDATE_PERIOD) {
UIUtils.asyncExec(() -> {
TextViewer textViewer = getTextViewer();
if (textViewer != null) {
topOffset = textViewer.getTopIndexStartOffset();
visibleLength = textViewer.getBottomIndexEndOffset() - topOffset;
}
});
if (scriptMode) {
showStatementInEditor(query, false);
}
lastUIUpdateTime = System.currentTimeMillis();
}
} finally {
if (extListener != null) extListener.onStartQuery(session, query);
}
}
@Override
public void onEndQuery(final DBCSession session, final SQLQueryResult result, DBCStatistics statistics) {
try {
synchronized (runningQueries) {
runningQueries.remove(result.getStatement());
}
queryProcessor.curJobRunning.decrementAndGet();
if (getTotalQueryRunning() <= 0) {
UIUtils.asyncExec(() -> {
if (isDisposed()) {
return;
}
setTitleImage(editorImage);
updateDirtyFlag();
});
}
if (isDisposed()) {
return;
}
UIUtils.runUIJob("Process SQL query result", monitor -> {
if (isDisposed()) {
return;
}
// Finish query
processQueryResult(monitor, result, statistics);
// Update dirty flag
updateDirtyFlag();
refreshActions();
});
} finally {
if (extListener != null) {
extListener.onEndQuery(session, result, statistics);
}
}
}
private void processQueryResult(DBRProgressMonitor monitor, SQLQueryResult result, DBCStatistics statistics) {
dumpQueryServerOutput(result);
if (!scriptMode) {
runPostExecuteActions(result);
}
SQLQuery query = result.getStatement();
Throwable error = result.getError();
ISelectionProvider selectionProvider = getSelectionProvider();
if (selectionProvider == null) {
// Disposed?
return;
}
if (error != null) {
setStatus(GeneralUtils.getFirstMessage(error), DBPMessageType.ERROR);
SQLQuery originalQuery = curResultsContainer.query instanceof SQLQuery ? (SQLQuery) curResultsContainer.query : null; // SQLQueryResult stores modified query
if (!visualizeQueryErrors(monitor, query, error, originalQuery)) {
int errorQueryOffset = query.getOffset();
int errorQueryLength = query.getLength();
if (errorQueryOffset >= 0 && errorQueryLength > 0) {
if (!addProblem(GeneralUtils.getFirstMessage(error), new Position(errorQueryOffset, errorQueryLength))) {
if (scriptMode) {
selectionProvider.setSelection(new TextSelection(errorQueryOffset, errorQueryLength));
} else {
selectionProvider.setSelection(originalSelection);
}
}
setLastQueryErrorPosition(errorQueryOffset);
}
}
} else if (!scriptMode && getActivePreferenceStore().getBoolean(SQLPreferenceConstants.RESET_CURSOR_ON_EXECUTE)) {
selectionProvider.setSelection(originalSelection);
}
notifyOnQueryResultListeners(curResultsContainer, result);
// Get results window (it is possible that it was closed till that moment
{
for (QueryResultsContainer cr : queryProcessor.resultContainers) {
cr.viewer.updateFiltersText(false);
}
if (!result.hasError() && !queryProcessor.resultContainers.isEmpty()) {
if (activeResultsTab != null && !activeResultsTab.isDisposed()) {
setResultTabSelection(activeResultsTab);
} else {
setResultTabSelection(queryProcessor.resultContainers.get(0).resultsTab);
}
}
// Set tab names by query results names
if (scriptMode || queryProcessor.getResultContainers().size() > 0) {
int queryIndex = queryProcessors.indexOf(queryProcessor);
int resultsIndex = 0;
for (QueryResultsContainer results : queryProcessor.resultContainers) {
if (results.query != query) {
// This happens when query results is statistics tab
// in that case we need to update tab selection and
// select new statistics tab
// see #16605
setResultTabSelection(results.resultsTab);
continue;
}
if (resultsIndex < result.getExecuteResults().size()) {
SQLQueryResult.ExecuteResult executeResult = result.getExecuteResults(resultsIndex, true);
String resultSetName = results.tabName;
if (CommonUtils.isEmpty(resultSetName)) {
resultSetName = getResultsTabName(results.resultSetNumber, queryIndex, executeResult.getResultSetName());
results.updateResultsName(resultSetName, null);
setResultTabSelection(results.resultsTab);
}
ResultSetViewer resultSetViewer = results.getResultSetController();
if (resultSetViewer != null) {
resultSetViewer.getModel().setStatistics(statistics);
}
}
resultsIndex++;
}
}
}
// Close tab on error
if (closeTabOnError && error != null) {
CTabItem tabItem = queryProcessor.getFirstResults().getTabItem();
if (tabItem != null && tabItem.getShowClose()) {
tabItem.dispose();
}
}
// Beep
if (dataSourceContainer != null && !scriptMode && getActivePreferenceStore().getBoolean(SQLPreferenceConstants.BEEP_ON_QUERY_END)) {
Display.getCurrent().beep();
}
// Notify agent
if (result.getQueryTime() > DBWorkbench.getPlatformUI().getLongOperationTimeout() * 1000) {
DBWorkbench.getPlatformUI().notifyAgent(
"Query completed [" + getEditorInput().getName() + "]" + GeneralUtils.getDefaultLineSeparator() +
CommonUtils.truncateString(query.getText(), 200), !result.hasError() ? IStatus.INFO : IStatus.ERROR);
}
}
@Override
public void onEndScript(final DBCStatistics statistics, final boolean hasErrors) {
try {
if (isDisposed()) {
return;
}
runPostExecuteActions(null);
UIUtils.asyncExec(() -> {
if (isDisposed()) {
// Editor closed
return;
}
resultsSash.setMaximizedControl(null);
if (!hasErrors) {
getSelectionProvider().setSelection(originalSelection);
}
QueryResultsContainer results = queryProcessor.getFirstResults();
ResultSetViewer viewer = results.getResultSetController();
if (viewer != null) {
viewer.getModel().setStatistics(statistics);
viewer.updateStatusMessage();
}
});
} finally {
if (extListener != null) extListener.onEndScript(statistics, hasErrors);
}
}
}
public void updateDirtyFlag() {
firePropertyChange(IWorkbenchPartConstants.PROP_DIRTY);
}
private class FindReplaceTarget extends DynamicFindReplaceTarget {
private IFindReplaceTarget previousTarget = null;
@Override
public IFindReplaceTarget getTarget() {
//getTarget determines current composite used for find/replace
//We should update it, when we focus on the other panels or output view
ResultSetViewer rsv = getActiveResultSetViewer();
TextViewer textViewer = getTextViewer();
boolean focusInEditor = textViewer != null && textViewer.getTextWidget() != null && textViewer.getTextWidget().isFocusControl();
if (!focusInEditor) {
if (rsv == null && !outputViewer.getText().isFocusControl() && previousTarget != null) {
focusInEditor = textViewer != null && previousTarget.equals(textViewer.getFindReplaceTarget());
}
}
if (!focusInEditor) {
//Focus is on presentation we need to find a class for it
if (rsv != null && rsv.getActivePresentation().getControl().isFocusControl()) {
previousTarget = rsv.getAdapter(IFindReplaceTarget.class);
} else if (outputViewer.getControl().isFocusControl()) {
//Output viewer is just StyledText we use StyledTextFindReplace
previousTarget = new StyledTextFindReplaceTarget(outputViewer.getText());
}
} else {
previousTarget = textViewer.getFindReplaceTarget();
}
return previousTarget;
}
}
private class DynamicSelectionProvider extends CompositeSelectionProvider {
private boolean lastFocusInEditor = true;
@Override
public ISelectionProvider getProvider() {
if (extraPresentation != null && getExtraPresentationState() == SQLEditorPresentation.ActivationType.VISIBLE) {
if (getExtraPresentationControl().isFocusControl()) {
ISelectionProvider selectionProvider = extraPresentation.getSelectionProvider();
if (selectionProvider != null) {
return selectionProvider;
}
}
}
ResultSetViewer rsv = getActiveResultSetViewer();
TextViewer textViewer = getTextViewer();
boolean focusInEditor = textViewer != null && textViewer.getTextWidget().isFocusControl();
if (!focusInEditor) {
if (rsv != null && rsv.getActivePresentation().getControl().isFocusControl()) {
focusInEditor = false;
} else {
focusInEditor = lastFocusInEditor;
}
}
lastFocusInEditor = focusInEditor;
if (!focusInEditor && rsv != null) {
return rsv;
} else if (textViewer != null) {
return textViewer.getSelectionProvider();
} else {
return null;
}
}
}
private void dumpQueryServerOutput(@Nullable DBCExecutionResult result) {
final DBCExecutionContext executionContext = getExecutionContext();
if (executionContext != null) {
final DBPDataSource dataSource = executionContext.getDataSource();
// Dump server output
DBCServerOutputReader outputReader = DBUtils.getAdapter(DBCServerOutputReader.class, dataSource);
if (outputReader == null && result != null) {
outputReader = new DefaultServerOutputReader();
}
if (outputReader != null && outputReader.isServerOutputEnabled()) {
synchronized (serverOutputs) {
serverOutputs.add(new ServerOutputInfo(outputReader, executionContext, result));
}
}
}
}
private void runPostExecuteActions(@Nullable SQLQueryResult result) {
showResultsPanel(true);
final DBCExecutionContext executionContext = getExecutionContext();
if (executionContext != null) {
// Refresh active object
if (result == null || !result.hasError() && getActivePreferenceStore().getBoolean(SQLPreferenceConstants.REFRESH_DEFAULTS_AFTER_EXECUTE)) {
DBCExecutionContextDefaults<?,?> contextDefaults = executionContext.getContextDefaults();
if (contextDefaults != null) {
new AbstractJob("Refresh default object") {
@Override
protected IStatus run(DBRProgressMonitor monitor) {
monitor.beginTask("Refresh default objects", 1);
try {
DBUtils.refreshContextDefaultsAndReflect(monitor, contextDefaults);
} finally {
monitor.done();
}
return Status.OK_STATUS;
}
}.schedule();
}
}
}
}
private void updateOutputViewerIcon(boolean alert) {
Image image = alert ? IMG_OUTPUT_ALERT : IMG_OUTPUT;
CTabItem outputItem = UIUtils.getTabItem(resultTabs, outputViewer.getControl());
if (outputItem != null && outputItem != resultTabs.getSelection()) {
outputItem.setImage(image);
} else {
ToolItem viewItem = getViewToolItem(SQLEditorCommands.CMD_SQL_SHOW_OUTPUT);
if (viewItem != null) {
viewItem.setImage(image);
}
// TODO: make icon update. Can't call setImage because this will break contract f VerticalButton
/*
VerticalButton viewItem = getViewToolItem(SQLEditorCommands.CMD_SQL_SHOW_OUTPUT);
if (viewItem != null) {
viewItem.setImage(image);
}
*/
}
}
private class ScriptAutoSaveJob extends AbstractJob {
ScriptAutoSaveJob() {
super("Save '" + getPartName() + "' script");
setSystem(true);
}
@Override
protected IStatus run(DBRProgressMonitor monitor) {
if (EditorUtils.isInAutoSaveJob()) {
return Status.CANCEL_STATUS;
}
monitor.beginTask("Auto-save SQL script", 1);
try {
UIUtils.asyncExec(() ->
SQLEditor.this.doTextEditorSave(monitor));
} catch (Throwable e) {
log.debug(e);
} finally {
monitor.done();
}
return Status.OK_STATUS;
}
}
private class SaveJob extends AbstractJob {
private transient Boolean success = null;
SaveJob() {
super("Save '" + getPartName() + "' data changes...");
setUser(true);
}
@Override
protected IStatus run(DBRProgressMonitor monitor) {
monitor.beginTask("Save query processors", queryProcessors.size());
try {
for (QueryProcessor queryProcessor : queryProcessors) {
for (QueryResultsContainer resultsProvider : queryProcessor.getResultContainers()) {
ResultSetViewer rsv = resultsProvider.getResultSetController();
if (rsv != null && rsv.isDirty()) {
rsv.doSave(monitor);
}
}
monitor.worked(1);
}
success = true;
return Status.OK_STATUS;
} catch (Throwable e) {
success = false;
log.error(e);
return GeneralUtils.makeExceptionStatus(e);
} finally {
if (success == null) {
success = true;
}
monitor.done();
}
}
}
private class OutputLogWriter extends Writer {
@Override
public void write(@NotNull final char[] cbuf, final int off, final int len) {
UIUtils.syncExec(() -> {
if (!outputViewer.isDisposed()) {
outputViewer.getOutputWriter().write(cbuf, off, len);
outputViewer.scrollToEnd();
if (!outputViewer.isVisible()) {
updateOutputViewerIcon(true);
}
}
});
}
@Override
public void flush() {
outputViewer.getOutputWriter().flush();
}
@Override
public void close() {
}
}
private class ServerOutputReader extends AbstractJob {
ServerOutputReader() {
super("Dump server output");
setSystem(true);
}
@Override
protected IStatus run(DBRProgressMonitor monitor) {
if (!DBWorkbench.getPlatform().isShuttingDown() && resultsSash != null && !resultsSash.isDisposed()) {
dumpOutput(monitor);
schedule(200);
}
return Status.OK_STATUS;
}
private void dumpOutput(DBRProgressMonitor monitor) {
if (outputViewer == null) {
return;
}
List<ServerOutputInfo> outputs;
synchronized (serverOutputs) {
outputs = new ArrayList<>(serverOutputs);
serverOutputs.clear();
}
PrintWriter outputWriter = outputViewer.getOutputWriter();
if (!outputs.isEmpty()) {
for (ServerOutputInfo info : outputs) {
if (monitor.isCanceled()) {
break;
}
try {
info.outputReader.readServerOutput(monitor, info.executionContext, info.result, null, outputWriter);
} catch (Exception e) {
log.error(e);
}
}
}
if (!monitor.isCanceled()) {
// Check running queries for async output
DBCServerOutputReader outputReader = null;
final DBCExecutionContext executionContext = getExecutionContext();
if (executionContext != null) {
final DBPDataSource dataSource = executionContext.getDataSource();
// Dump server output
outputReader = DBUtils.getAdapter(DBCServerOutputReader.class, dataSource);
}
if (outputReader != null && outputReader.isAsyncOutputReadSupported()) {
for (QueryProcessor qp : queryProcessors) {
SQLQueryJob queryJob = qp.curJob;
if (queryJob != null) {
DBCStatement statement = queryJob.getCurrentStatement();
try {
if (statement != null && !statement.isStatementClosed()) {
outputReader.readServerOutput(monitor, executionContext, null, statement, outputWriter);
}
} catch (DBCException e) {
log.error(e);
}
}
}
}
}
outputWriter.flush();
if (!outputViewer.isHasNewOutput()) {
return;
}
outputViewer.resetNewOutput();
// Show output log view if needed
UIUtils.asyncExec(() -> {
outputViewer.scrollToEnd();
if (getActivePreferenceStore().getBoolean(SQLPreferenceConstants.OUTPUT_PANEL_AUTO_SHOW)) {
if (!getViewToolItem(SQLEditorCommands.CMD_SQL_SHOW_OUTPUT).getSelection()) {
showOutputPanel();
}
}
/*
if (outputViewer!=null) {
if (outputViewer.getControl()!=null) {
if (!outputViewer.isDisposed()) {
outputViewer.scrollToEnd();
updateOutputViewerIcon(true);
}
}
}
*/
});
}
}
private class OutputAutoShowToggleAction extends Action {
OutputAutoShowToggleAction() {
super(SQLEditorMessages.pref_page_sql_editor_label_auto_open_output_view, AS_CHECK_BOX);
setImageDescriptor(DBeaverIcons.getImageDescriptor(UIIcon.SHOW_ALL_DETAILS));
setChecked(getActivePreferenceStore().getBoolean(SQLPreferenceConstants.OUTPUT_PANEL_AUTO_SHOW));
}
@Override
public void run() {
getActivePreferenceStore().setValue(SQLPreferenceConstants.OUTPUT_PANEL_AUTO_SHOW, isChecked());
try {
getActivePreferenceStore().save();
} catch (IOException e) {
log.error(e);
}
}
}
private void notifyOnDataListeners(@NotNull QueryResultsContainer container) {
// Notify listeners
synchronized (listeners) {
for (SQLEditorListener listener : listeners) {
try {
listener.onDataReceived(
getContextPrefStore(container),
container.getResultSetController().getModel(),
container.getQuery().getOriginalText()
);
} catch (Throwable ex) {
log.error(ex);
}
}
}
}
private void notifyOnQueryResultListeners(@NotNull QueryResultsContainer container, @NotNull SQLQueryResult result) {
// Notify listeners
synchronized (listeners) {
for (SQLEditorListener listener : listeners) {
try {
listener.onQueryResult(getContextPrefStore(container), result);
} catch (Throwable ex) {
log.error(ex);
}
}
}
}
@NotNull
private DBPPreferenceStore getContextPrefStore(@NotNull QueryResultsContainer container) {
DBCExecutionContext context = container.getExecutionContext();
DBPPreferenceStore contextPrefStore = context != null
? context.getDataSource().getContainer().getPreferenceStore()
: DBWorkbench.getPlatform().getPreferenceStore();
return contextPrefStore;
}
}
| dbeaver/dbeaver-ee#1979 SQL console is not read-only
| plugins/org.jkiss.dbeaver.ui.editors.sql/src/org/jkiss/dbeaver/ui/editors/sql/SQLEditor.java | dbeaver/dbeaver-ee#1979 SQL console is not read-only | <ide><path>lugins/org.jkiss.dbeaver.ui.editors.sql/src/org/jkiss/dbeaver/ui/editors/sql/SQLEditor.java
<ide> }
<ide>
<ide> private boolean isProjectResourceEditable() {
<del> DBPProject project = this.getProject();
<del> return project == null || project.hasRealmPermission(RMConstants.PERMISSION_PROJECT_RESOURCE_EDIT);
<add> if (getEditorInput() instanceof IFileEditorInput) {
<add> DBPProject project = this.getProject();
<add> return project == null || project.hasRealmPermission(RMConstants.PERMISSION_PROJECT_RESOURCE_EDIT);
<add> }
<add> return true;
<ide> }
<ide>
<ide> @Override |
|
Java | apache-2.0 | 46750d9e279ad9c6983d1a7cd0676b41ef634b6e | 0 | DevOps-TangoMe/gcloud-storage-speedtest | package me.tango.devops.google;
import static me.tango.devops.google.CredentialsManager.*;
import com.google.api.client.http.InputStreamContent;
import com.google.api.services.storage.Storage;
import com.google.api.services.storage.model.Bucket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
/** Manage Google Cloud Storage client. */
public final class StorageManager {
/** Available regions, US-WEST2 and EUROPE-WEST1 are not available over API calls yet. */
public static final String[] REGIONS =
new String[] {"ASIA-EAST1", "US-CENTRAL1", "US-CENTRAL2", "US-EAST1", "US-EAST2",
"US-EAST3", "US-WEST1"};
/** Region->Bucket mappings. */
public static final Map<String, String> BUCKETS = new HashMap<String, String>();
/** Buckets' prefix. **/
private static final String BUCKET_PREFIX = "upload-speed-test-a34c4e0c-";
/** log. */
private static final Logger LOGGER = LoggerFactory.getLogger(StorageManager.class);
/** Project ID. */
private static String projectId;
/** Java client to communicate with Google cloud storage. */
private static Storage client;
// Make it a utility class
private StorageManager() {}
/** Configuration. */
public static void setup(final String projectId) throws IOException {
StorageManager.projectId = projectId;
client = new Storage.Builder(httpTransport, JSON_FACTORY, authorize())
.setApplicationName(StorageManager.projectId).build();
}
/** return region->bucket mappings. */
public static Map<String, String> getBuckets() {
return BUCKETS;
}
/** Get all bucket names and create them. */
@SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops")
public static void initBuckets(final boolean create) {
for (final String region : REGIONS) {
final String bucketName = BUCKET_PREFIX + region.toLowerCase(Locale.ENGLISH);
BUCKETS.put(region, bucketName);
if (create) {
try {
LOGGER.debug("Creating bucket '{}'", bucketName);
client.buckets().insert(projectId,
new Bucket().setName(bucketName).setLocation(region)
.setStorageClass("DURABLE_REDUCED_AVAILABILITY")).execute();
} catch (IOException e) {
LOGGER.error("Create bucket exception", e);
}
}
}
}
/** Delete BUCKETS. */
public static void deleteBuckets() {
for (final String bucketName : BUCKETS.values()) {
try {
LOGGER.debug("Deleting bucket " + bucketName);
client.buckets().delete(bucketName).execute();
} catch (IOException e) {
LOGGER.error("Delete bucket exception", e);
}
}
}
/** Upload data. */
public static boolean putBytes(final String bucket, final String key, final byte[] bytes) {
final InputStreamContent mediaContent =
new InputStreamContent("application/octet-stream", new ByteArrayInputStream(bytes));
mediaContent.setLength(bytes.length);
try {
final Storage.Objects.Insert insertObject =
client.objects().insert(bucket, null, mediaContent);
insertObject.setName(key);
if (mediaContent.getLength() > 0
&& mediaContent.getLength() <= 2 * 1000 * 1000 /* 2MB */) {
insertObject.getMediaHttpUploader().setDirectUploadEnabled(true);
}
insertObject.execute();
return true;
} catch (IOException e) {
LOGGER.error("Error uploading data", e);
return false;
}
}
/** Download data. */
public static byte[] getBytes(final String bucket, final String key) {
try {
final Storage.Objects.Get getRequest = client.objects().get(bucket, key);
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
getRequest.executeMediaAndDownloadTo(baos);
return baos.toByteArray();
} catch (IOException e) {
LOGGER.error("Error downloading data", e);
return null;
}
}
/** Delete data. */
public static void deleteBytes(final String bucket, final String key) {
try {
client.objects().delete(bucket, key).execute();
} catch (IOException e) {
LOGGER.error("Error deleting data", e);
}
}
}
| src/main/java/me/tango/devops/google/StorageManager.java | package me.tango.devops.google;
import static me.tango.devops.google.CredentialsManager.*;
import com.google.api.client.http.InputStreamContent;
import com.google.api.services.storage.Storage;
import com.google.api.services.storage.model.Bucket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
/** Manage Google Cloud Storage client. */
public final class StorageManager {
/** Available regions, US-WEST2 is not valid. */
public static final String[] REGIONS =
new String[] {"ASIA-EAST1", "US-CENTRAL1", "US-CENTRAL2", "US-EAST1", "US-EAST2",
"US-EAST3", "US-WEST1"};
/** Region->Bucket mappings. */
public static final Map<String, String> BUCKETS = new HashMap<String, String>();
/** Buckets' prefix. **/
private static final String BUCKET_PREFIX = "upload-speed-test-a34c4e0c-";
/** log. */
private static final Logger LOGGER = LoggerFactory.getLogger(StorageManager.class);
/** Project ID. */
private static String projectId;
/** Java client to communicate with Google cloud storage. */
private static Storage client;
// Make it a utility class
private StorageManager() {}
/** Configuration. */
public static void setup(final String projectId) throws IOException {
StorageManager.projectId = projectId;
client = new Storage.Builder(httpTransport, JSON_FACTORY, authorize())
.setApplicationName(StorageManager.projectId).build();
}
/** return region->bucket mappings. */
public static Map<String, String> getBuckets() {
return BUCKETS;
}
/** Get all bucket names and create them. */
@SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops")
public static void initBuckets(final boolean create) {
for (final String region : REGIONS) {
final String bucketName = BUCKET_PREFIX + region.toLowerCase(Locale.ENGLISH);
BUCKETS.put(region, bucketName);
if (create) {
try {
LOGGER.debug("Creating bucket '{}'", bucketName);
client.buckets().insert(projectId,
new Bucket().setName(bucketName).setLocation(region)
.setStorageClass("DURABLE_REDUCED_AVAILABILITY")).execute();
} catch (IOException e) {
LOGGER.error("Create bucket exception", e);
}
}
}
}
/** Delete BUCKETS. */
public static void deleteBuckets() {
for (final String bucketName : BUCKETS.values()) {
try {
LOGGER.debug("Deleting bucket " + bucketName);
client.buckets().delete(bucketName).execute();
} catch (IOException e) {
LOGGER.error("Delete bucket exception", e);
}
}
}
/** Upload data. */
public static boolean putBytes(final String bucket, final String key, final byte[] bytes) {
final InputStreamContent mediaContent =
new InputStreamContent("application/octet-stream", new ByteArrayInputStream(bytes));
mediaContent.setLength(bytes.length);
try {
final Storage.Objects.Insert insertObject =
client.objects().insert(bucket, null, mediaContent);
insertObject.setName(key);
if (mediaContent.getLength() > 0
&& mediaContent.getLength() <= 2 * 1000 * 1000 /* 2MB */) {
insertObject.getMediaHttpUploader().setDirectUploadEnabled(true);
}
insertObject.execute();
return true;
} catch (IOException e) {
LOGGER.error("Error uploading data", e);
return false;
}
}
/** Download data. */
public static byte[] getBytes(final String bucket, final String key) {
try {
final Storage.Objects.Get getRequest = client.objects().get(bucket, key);
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
getRequest.executeMediaAndDownloadTo(baos);
return baos.toByteArray();
} catch (IOException e) {
LOGGER.error("Error downloading data", e);
return null;
}
}
/** Delete data. */
public static void deleteBytes(final String bucket, final String key) {
try {
client.objects().delete(bucket, key).execute();
} catch (IOException e) {
LOGGER.error("Error deleting data", e);
}
}
}
| Update StorageManager.java
Updating the reason we can not support US-WEST2 and EUROPE-WEST1 regions. After looking at gCloud documentation and gsutil options, those regions are currently not supported. The only option is to manually configure them using the UI. | src/main/java/me/tango/devops/google/StorageManager.java | Update StorageManager.java | <ide><path>rc/main/java/me/tango/devops/google/StorageManager.java
<ide>
<ide> /** Manage Google Cloud Storage client. */
<ide> public final class StorageManager {
<del> /** Available regions, US-WEST2 is not valid. */
<add> /** Available regions, US-WEST2 and EUROPE-WEST1 are not available over API calls yet. */
<ide> public static final String[] REGIONS =
<ide> new String[] {"ASIA-EAST1", "US-CENTRAL1", "US-CENTRAL2", "US-EAST1", "US-EAST2",
<ide> "US-EAST3", "US-WEST1"}; |
|
JavaScript | mpl-2.0 | 7d76790e1c8c8ad203be669c18eb7c0b3566b9e8 | 0 | joyent/sdcadm,joyent/sdcadm,joyent/sdcadm | /*
* 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/.
*/
/*
* Copyright (c) 2014, Joyent, Inc.
*/
/*
* Collecting 'sdcadm experimental ...' CLI commands.
*
* These are temporary, unsupported commands for running SDC updates before
* the grand plan of 'sdcadm update' fully handling updates is complete.
*/
var p = console.log;
var util = require('util'),
format = util.format;
var fs = require('fs');
var cp = require('child_process');
var execFile = cp.execFile;
var spawn = cp.spawn;
var vasync = require('vasync');
var read = require('read');
var assert = require('assert-plus');
var cmdln = require('cmdln'),
Cmdln = cmdln.Cmdln;
var common = require('./common');
var errors = require('./errors');
var DownloadImages = require('./procedures/download-images').DownloadImages;
var shared = require('./procedures/shared');
//---- globals
//---- Experimental CLI class
function ExperimentalCLI(top) {
this.top = top;
Cmdln.call(this, {
name: 'sdcadm experimental',
desc: 'Experimental, unsupported, temporary sdcadm commands.\n' +
'\n' +
'These are unsupported and temporary commands to assist with\n' +
'migration away from incr-upgrade scripts. The eventual\n' +
'general upgrade process will not include any commands under\n' +
'"sdcadm experimental".',
helpOpts: {
minHelpCol: 24 /* line up with option help */
}
});
}
util.inherits(ExperimentalCLI, Cmdln);
ExperimentalCLI.prototype.init = function init(opts, args, callback) {
this.sdcadm = this.top.sdcadm;
this.progress = this.top.progress;
this.log = this.top.log;
Cmdln.prototype.init.apply(this, arguments);
};
/*
* Update agents in datancenter with a given or latest agents installer.
*/
ExperimentalCLI.prototype.do_update_agents =
function do_update_agents(subcmd, opts, args, cb) {
var self = this;
if (!opts.latest && !args[0]) {
return cb(new errors.UsageError(
'must specify installer image UUID or --latest'));
}
return self.sdcadm.updateAgents({
image: (opts.latest) ? 'latest' : args[0],
progress: self.progress,
justDownload: opts.just_download
}, cb);
};
ExperimentalCLI.prototype.do_update_agents.help = (
'Update SDC agents\n' +
'\n' +
'Usage:\n' +
' {{name}} update-agents IMAGE-UUID\n' +
' {{name}} update-agents PATH-TO-INSTALLER\n' +
' {{name}} update-agents --latest\n' +
'\n' +
'{{options}}'
);
ExperimentalCLI.prototype.do_update_agents.options = [
{
names: ['latest'],
type: 'bool',
help: 'Update using the last published agents installer.'
},
{
names: ['just-download'],
type: 'bool',
help: 'Download the agents installer for later usage.'
}
];
ExperimentalCLI.prototype.do_dc_maint =
function do_dc_maint(subcmd, opts, args, cb) {
var self = this;
if (opts.help) {
this.do_help('help', {}, [subcmd], cb);
return;
} else if (args.length > 0) {
return cb(new errors.UsageError('too many args: ' + args));
}
if (opts.start && opts.stop) {
cb(new errors.UsageError('cannot use --start and --stop'));
} else if (opts.start) {
this.sdcadm.dcMaintStart({progress: self.progress}, cb);
} else if (opts.stop) {
this.sdcadm.dcMaintStop({progress: self.progress}, cb);
} else {
this.sdcadm.dcMaintStatus(function (err, status) {
if (err) {
return cb(err);
}
if (opts.json) {
self.progress(JSON.stringify(status, null, 4));
} else if (status.maint) {
if (status.startTime) {
self.progress('DC maintenance: on (since %s)',
status.startTime);
} else {
self.progress('DC maintenance: on');
}
} else {
self.progress('DC maintenance: off');
}
cb();
});
}
cb();
};
ExperimentalCLI.prototype.do_dc_maint.options = [
{
names: ['help', 'h'],
type: 'bool',
help: 'Show this help.'
},
{
names: ['json', 'j'],
type: 'bool',
help: 'Show status as JSON.'
},
{
names: ['start'],
type: 'bool',
help: 'Start maintenance mode.'
},
{
names: ['stop'],
type: 'bool',
help: 'Stop maintenance mode (i.e. restore DC to full operation).'
}
];
ExperimentalCLI.prototype.do_dc_maint.help = (
'Show and modify the DC maintenance mode.\n' +
'\n' +
'"Maintenance mode" for an SDC means that Cloud API is in read-only\n' +
'mode. Modifying requests will return "503 Service Unavailable".\n' +
'Workflow API will be drained on entering maint mode.\n' +
'\n' +
'Limitation: This does not current wait for config changes to be made\n' +
'and cloudapi instances restarted. That means there is a window after\n' +
'starting that new jobs could come in.\n' +
'\n' +
'Usage:\n' +
' {{name}} dc-maint [-j] # show DC maint status\n' +
' {{name}} dc-maint [--start] # start DC maint\n' +
' {{name}} dc-maint [--stop] # stop DC maint\n' +
'\n' +
'{{options}}'
);
/**
* This is the temporary quick replacement for incr-upgrade's
* "upgrade-other.sh".
*/
ExperimentalCLI.prototype.do_update_other =
function do_update_other(subcmd, opts, args, cb) {
var self = this;
var progress = self.progress;
if (opts.help) {
this.do_help('help', {}, [subcmd], cb);
return;
} else if (args.length > 0) {
return cb(new errors.UsageError('too many args: ' + args));
}
var app, caInst, caSvc, domain, regionName, sapiUrl, services;
// Used by history:
var history;
var changes = [];
// Helper functions
function updateService(uuid, svcOpts, next) {
self.sdcadm.sapi.updateService(uuid, svcOpts, function (err, svc) {
if (err) {
return next(new errors.SDCClientError(err, 'sapi'));
}
next();
});
}
function updateApplication(svcOpts, next) {
self.sdcadm.sapi.updateApplication(app.uuid, svcOpts,
function (err, svc) {
if (err) {
return next(new errors.SDCClientError(err, 'sapi'));
}
next();
});
}
function readField(field, default_, cbRead) {
if (cbRead === undefined) {
cbRead = default_;
default_ = undefined;
}
assert.object(field, 'field');
assert.func(cbRead);
var readOpts = {
prompt: field.name + ':',
silent: field.hidden,
default: default_
};
read(readOpts, function (rErr, val) {
if (rErr) {
return cbRead(rErr);
}
val = val.trim();
if (!field.confirm) {
return cbRead(null, val);
}
readOpts.prompt = field.name + ' confirm:';
read(readOpts, function (rErr2, val2) {
if (rErr2) {
return cbRead(rErr2);
}
val2 = val2.trim();
if (val !== val2) {
cbRead(new Error(format(
'%s values do not match', field.name)));
} else {
cbRead(null, val);
}
});
});
}
// TODO move to some place where it can be reused
function mountUsbKey(_, cbMount) {
execFile('/usbkey/scripts/mount-usb.sh', cbMount);
}
// TODO move to some place where it can be reused
function unmountUsbKey(_, cbMount) {
execFile('/usr/sbin/umount', [ '/mnt/usbkey' ], cbMount);
}
// Upgrade pipeline
vasync.pipeline({funcs: [
function getSdcApp(_, next) {
self.sdcadm.sapi.listApplications({ name: 'sdc' },
function (appErr, apps) {
if (appErr) {
return next(new errors.SDCClientError(appErr, 'sapi'));
} else if (!apps.length) {
return next(new errors.SDCClientError(new Error(
'No applications named "sdc"'), 'sapi'));
}
app = apps[0];
domain = app.metadata.datacenter_name + '.' +
app.metadata.dns_domain;
sapiUrl = app.metadata['sapi-url'];
return next();
});
},
function getServices(_, next) {
self.sdcadm.getServices({}, function (err, svcs) {
if (err) {
return next(err);
}
services = svcs;
// Locate CA for later
svcs.forEach(function (svc) {
if (svc.name === 'ca') {
caSvc = svc;
}
});
return next();
});
},
function saveChangesToHistory(_, next) {
services.forEach(function (svc) {
if (svc.type === 'vm') {
changes.push({
service: svc,
type: 'update-service-cfg'
});
}
});
self.sdcadm.history.saveHistory({
changes: changes
}, function (err, hst) {
if (err) {
return next(err);
}
history = hst;
return next();
});
},
function updateMaintainResolvers(_, next) {
progress('Updating maintain_resolvers for all vm services');
function updateSvc(svc, nextSvc) {
if (svc.type === 'vm' && svc.params &&
svc.params.maintain_resolvers !== true) {
updateService(svc.uuid,
{ params: { maintain_resolvers: true } },
nextSvc);
return;
}
return nextSvc();
}
vasync.forEachParallel({
inputs: services,
func: updateSvc
}, next);
},
function updateServiceDomains(_, next) {
var SERVICES = ['papi', 'mahi'];
progress('Updating DNS domain service metadata for %s',
SERVICES.join(', '));
function updateSvc(svc, nextSvc) {
if (SERVICES.indexOf(svc.name) !== -1) {
var svcDomain = svc.name + '.' + domain;
updateService(svc.uuid,
{ metadata: {
SERVICE_DOMAIN: svcDomain,
'sapi-url': sapiUrl
} },
nextSvc);
return;
}
return nextSvc();
}
vasync.forEachParallel({
inputs: services,
func: updateSvc
}, next);
},
function updateAppDomains(_, next) {
var SERVICES = ['papi', 'mahi'];
progress('Updating DNS domain SDC application metadata for %s',
SERVICES.join(', '));
function updateApp(svc, nextSvc) {
if (SERVICES.indexOf(svc.name) !== -1) {
var svcDomain = svc.name + '.' + domain;
var metadata = {};
metadata[svc.name.toUpperCase() + '_SERVICE'] = svcDomain;
metadata[svc.name + '_domain'] = svcDomain;
updateApplication({ metadata: metadata }, nextSvc);
return;
}
return nextSvc();
}
vasync.forEachParallel({
inputs: services,
func: updateApp
}, next);
},
function updateCaParams(_, next) {
function getCaInstance(__, next_) {
var filters = {
state: 'active',
owner_uuid: self.sdcadm.config.ufds_admin_uuid,
alias: 'ca0'
};
self.sdcadm.vmapi.listVms(filters, function (vmsErr, vms) {
if (vmsErr) {
return next_(vmsErr);
}
caInst = vms[0];
return next_();
});
}
function updateCaService(__, next_) {
if (caSvc.params.max_physical_memory >= 4096) {
return next_();
}
progress('Updating CA service\'s max_physical_memory value');
var params = {
max_physical_memory: 4096,
max_locked_memory: 4096,
max_swap: 8192,
zfs_io_priority: 20,
cpu_cap: 400,
package_name: 'sdc_4096'
};
updateService(caSvc.uuid, { params: params }, next_);
}
function updateCaInstance(__, next_) {
if (caInst.max_physical_memory >= 4096) {
return next_();
}
progress('Updating CA\'s ca0 instance ' +
'max_physical_memory value');
var argv = [
'/usr/sbin/vmadm',
'update',
caInst.uuid,
'max_physical_memory=4096',
'max_locked_memory=4096',
'max_swap=8192',
'zfs_io_priority=20',
'cpu_cap=400'
];
common.execFilePlus({argv: argv, log: self.log}, next_);
}
vasync.pipeline({
funcs: [getCaInstance, updateCaService, updateCaInstance]
}, next);
},
function updateRegionName(_, next) {
fs.readFile('/usbkey/config', {
encoding: 'utf8'
}, function (err, data) {
if (err) {
return next(err);
/* JSSTYLED */
} else if (data.search(/region_name=/) !== -1) {
progress('No need to update region_name for ' +
'this data center');
return next();
}
function readRegionName(__, next_) {
progress('Updating region_name for this data center');
var field = {
name: 'region_name',
hidden: false,
confirm: true
};
readField(field, function (err1, value) {
if (err1) {
return next_(err1);
}
regionName = value;
return next_();
});
}
function appendRegionName(__, next_) {
var region = 'region_name=' + regionName + '\n';
fs.appendFile('/mnt/usbkey/config', region,
function (err1) {
if (err1) {
return next_(err1);
}
var argv = [
'/usr/bin/cp',
'/mnt/usbkey/config',
'/usbkey/config'
];
common.execFilePlus({argv: argv, log: self.log}, next_);
});
}
function updateSapiRegionName(__, next_) {
var metadata = { region_name: regionName };
updateApplication({ metadata: metadata }, next_);
}
vasync.pipeline({funcs: [
readRegionName,
mountUsbKey,
appendRegionName,
unmountUsbKey,
updateSapiRegionName
]}, next);
});
},
function addSapiDomainToNodeConfig(_, next) {
var nodeConfig = '/usbkey/extra/joysetup/node.config';
var sapiDomain = 'sapi_domain=\'sapi.' + domain + '\'\n';
fs.readFile(nodeConfig, { encoding: 'utf8' }, function (err, data) {
if (err) {
return next(err);
/* JSSTYLED */
} else if (data.search(/sapi_domain=/) !== -1) {
progress('sapi_domain already present on node.config');
return next();
}
progress('Appending sapi_domain to node.config');
fs.appendFile(nodeConfig, sapiDomain, next);
});
}
]}, function (err) {
if (err) {
history.error = err;
}
self.sdcadm.history.updateHistory(history, function (err2) {
if (err) {
return cb(err);
}
progress('Done.');
if (err2) {
return cb(err2);
} else {
return cb();
}
});
});
};
ExperimentalCLI.prototype.do_update_other.options = [
{
names: ['help', 'h'],
type: 'bool',
help: 'Show this help.'
}
];
ExperimentalCLI.prototype.do_update_other.help = (
'Temporary grabbag for small SDC update steps.\n' +
'The eventual goal is to integrate all of this into "sdcadm update".\n' +
'\n' +
'Usage:\n' +
' {{name}} update-other\n' +
'\n' +
'{{options}}'
);
/**
* This is the temporary quick replacement for incr-upgrade's
* "upgrade-tools.sh".
*/
ExperimentalCLI.prototype.do_update_gz_tools =
function do_update_gz_tools(subcmd, opts, args, cb) {
var self = this;
var progress = self.progress;
var execStart = Date.now();
function finish(err) {
if (err) {
return cb(err);
}
progress('Updated gz-tools successfully (elapsed %ds).',
Math.floor((Date.now() - execStart) / 1000));
return cb();
}
if (!opts.latest && !args[0]) {
return finish(new errors.UsageError(
'must specify installer image UUID or --latest'));
}
self.sdcadm.updateGzTools({
image: opts.latest ? 'latest' : args[0],
progress: progress,
justDownload: opts.just_download
}, finish);
};
ExperimentalCLI.prototype.do_update_gz_tools.options = [
{
names: ['help', 'h'],
type: 'bool',
help: 'Show this help.'
},
{
names: ['latest'],
type: 'bool',
help: 'Update using the last published gz-tools installer.'
},
{
names: ['just-download'],
type: 'bool',
help: 'Download the GZ Tools installer for later usage.'
}
];
ExperimentalCLI.prototype.do_update_gz_tools.help = (
'Temporary grabbag for updating the SDC global zone tools.\n' +
'The eventual goal is to integrate all of this into "sdcadm update".\n' +
'\n' +
'Usage:\n' +
' {{name}} update-gz-tools IMAGE-UUID\n' +
' {{name}} update-gz-tools PATH-TO-INSTALLER\n' +
' {{name}} update-gz-tools --latest\n' +
'\n' +
'{{options}}'
);
ExperimentalCLI.prototype.do_add_new_agent_svcs =
function do_add_new_agents_svcs(subcmd, opts, args, cb) {
var self = this;
var progress = self.progress;
var execStart = Date.now();
if (opts.help) {
this.do_help('help', {}, [subcmd], cb);
return;
} else if (args.length > 1) {
return cb(new errors.UsageError('too many args: ' + args));
}
// We need at least a MIN_VALID_SAPI_VERSION image so
// type=agent suport is there.
var MIN_VALID_SAPI_VERSION = '20140703';
var app, svc, inst, vm, img;
var agentNames = ['vm-agent', 'net-agent', 'cn-agent'];
var agentServices = {};
agentNames.forEach(function (n) {
var logLevelKey = n.toUpperCase().replace('-', '_') + '_LOG_LEVEL';
agentServices[n] = {
type: 'agent',
params: {
tags: {
smartdc_role: n,
smartdc_type: 'core'
}
},
metadata: {
SERVICE_NAME: n
},
manifests: {
}
};
agentServices[n].metadata[logLevelKey] = 'info';
});
var newAgentServices = [];
// Used by history:
var history;
var changes = [];
vasync.pipeline({funcs: [
function getSdcApp(_, next) {
progress('Getting SDC application details from SAPI');
self.sdcadm.sapi.listApplications({ name: 'sdc' },
function (appErr, apps) {
if (appErr) {
return next(new errors.SDCClientError(appErr, 'sapi'));
} else if (!apps.length) {
return next(new errors.SDCClientError(new Error(
'No applications named "sdc"'), 'sapi'));
}
app = apps[0];
return next();
});
},
function getSapiService(_, next) {
progress('Getting SDC\'s SAPI service details from SAPI');
self.sdcadm.sapi.listServices({
name: 'sapi',
application_uuid: app.uuid
}, function (svcErr, svcs) {
if (svcErr) {
return next(svcErr);
}
if (!svcs.length) {
return next(new errors.SDCClientError(new Error(
'No services named "manatee"'), 'sapi'));
}
svc = svcs[0];
return next();
});
},
function getSapiInstance(_, next) {
progress('Getting SDC\'s sapi instances from SAPI');
self.sdcadm.sapi.listInstances({
service_uuid: svc.uuid
}, function (instErr, insts) {
if (instErr) {
return next(instErr);
}
if (!insts.length) {
return next(new errors.SDCClientError(new Error(
'Unable to find first sapi instance'), 'sapi'));
}
inst = insts[0];
return next();
});
},
function getSapiVm(_, next) {
progress('Getting sapi VM details from VMAPI');
self.sdcadm.vmapi.getVm({uuid: inst.uuid}, function (vmErr, obj) {
if (vmErr) {
return next(vmErr);
}
vm = obj;
return next();
});
},
function getSapiImage(_, next) {
progress('Getting sapi Image details from IMGAPI');
self.sdcadm.imgapi.getImage(vm.image_uuid, function (imgErr, obj) {
if (imgErr) {
return next(imgErr);
}
img = obj;
return next();
});
},
function checkMinSapiVersion(_, next) {
progress('Checking for minimum SAPI version');
var splitVersion = img.version.split('-');
var validSapi = false;
if (splitVersion[0] === 'master') {
validSapi = splitVersion[1].substr(0, 8) >=
MIN_VALID_SAPI_VERSION;
} else if (splitVersion[0] === 'release') {
validSapi = splitVersion[1] >= MIN_VALID_SAPI_VERSION;
}
if (!validSapi) {
return next(new errors.SDCClientError(new Error('Datacenter ' +
'does not have the minimum SAPI version needed for adding' +
' service agents. ' +
'Please, try again after upgrading SAPI')));
}
return next();
},
function checkExistingAgents(_, next) {
vasync.forEachParallel({
func: function checkAgentExist(agent, callback) {
progress('Checking if service \'%s\' exists', agent);
self.sdcadm.sapi.listServices({
name: agent,
type: 'agent',
application_uuid: app.uuid
}, function (svcErr, svcs) {
if (svcErr) {
return callback(svcErr);
}
if (!svcs.length) {
newAgentServices.push(agent);
}
return callback();
});
},
inputs: Object.keys(agentServices)
}, function (err) {
if (err) {
return next(err);
}
return next();
});
},
function saveChangesToHistory(_, next) {
newAgentServices.forEach(function (s) {
changes.push({
service: {
name: s,
type: 'agent'
},
type: 'create-service'
});
});
self.sdcadm.history.saveHistory({
changes: changes
}, function (err, hst) {
if (err) {
return next(err);
}
history = hst;
return next();
});
},
function addAgentsServices(_, next) {
vasync.forEachParallel({
inputs: newAgentServices,
func: function addAgentSvc(agent, callback) {
progress('Adding service for agent \'%s\'', agent);
self.log.trace({
service: agent,
params: agentServices[agent]
}, 'Adding new agent service');
self.sdcadm.sapi.createService(agent, app.uuid,
agentServices[agent], function (err) {
if (err) {
return callback(err);
}
return callback();
});
}
}, function (err) {
if (err) {
return next(err);
}
return next();
});
}
]}, function (err) {
progress('Add new agent services finished (elapsed %ds).',
Math.floor((Date.now() - execStart) / 1000));
if (err) {
history.error = err;
}
self.sdcadm.history.updateHistory(history, function (err2) {
if (err) {
return cb(err);
} else if (err2) {
return cb(err2);
} else {
return cb();
}
});
});
};
ExperimentalCLI.prototype.do_add_new_agent_svcs.options = [ {
names: ['help', 'h'],
type: 'bool',
help: 'Show this help.'
}];
ExperimentalCLI.prototype.do_add_new_agent_svcs.help = (
'Temporary grabbag for installing the SDC global zone new agents.\n' +
'The eventual goal is to integrate all of this into "sdcadm update".\n' +
'\n' +
'Usage:\n' +
' {{name}} add-new-agent-svcs\n' +
'\n' +
'{{options}}'
);
/*
* Update platform in datancenter with a given or latest agents installer.
*/
ExperimentalCLI.prototype.do_install_platform =
function do_install_platform(subcmd, opts, args, cb) {
var self = this;
if (opts.help) {
this.do_help('help', {}, [subcmd], cb);
return;
}
if (opts.latest) {
self.sdcadm._installPlatform({
image: 'latest',
progress: self.progress
}, cb);
} else if (args[0]) {
self.sdcadm._installPlatform({
image: args[0],
progress: self.progress
}, cb);
} else {
cb(new errors.UsageError(
'must specify platform image UUID or --latest'));
}
};
ExperimentalCLI.prototype.do_install_platform.help = (
'Download and install platform image for later assignment.\n' +
'\n' +
'Usage:\n' +
' {{name}} install-platform IMAGE-UUID\n' +
' {{name}} install-platform PATH-TO-IMAGE\n' +
' {{name}} install-platform --latest\n' +
'\n' +
'{{options}}'
);
ExperimentalCLI.prototype.do_install_platform.options = [
{
names: ['help', 'h'],
type: 'bool',
help: 'Show this help.'
},
{
names: ['latest'],
type: 'bool',
help: 'Update using the last published platform image.'
}
];
/*
* Assign a platform image to a particular headnode or computenode.
*/
ExperimentalCLI.prototype.do_assign_platform =
function do_assign_platform(subcmd, opts, args, cb) {
var self = this;
if (opts.help) {
this.do_help('help', {}, [subcmd], cb);
return;
}
var platform = args[0];
var server = args[1];
var assignOpts;
if (opts.all && server) {
return cb(new errors.UsageError(
'using --all and explicitly specifying ' +
'a server are mutually exclusive'));
} else if (opts.all) {
assignOpts = {
all: true,
platform: platform,
progress: self.progress
};
} else if (platform && server) {
assignOpts = {
server: server,
platform: platform,
progress: self.progress
};
} else {
return cb(new errors.UsageError(
'must specify platform and server (or --all)'));
}
self.sdcadm._assignPlatform(assignOpts, cb);
};
ExperimentalCLI.prototype.do_assign_platform.help = (
'Assign platform image to SDC servers.\n' +
'\n' +
'Usage:\n' +
' {{name}} assign-platform PLATFORM SERVER\n' +
' {{name}} assign-platform PLATFORM --all\n' +
'\n' +
'{{options}}'
);
ExperimentalCLI.prototype.do_assign_platform.options = [
{
names: ['help', 'h'],
type: 'bool',
help: 'Show this help.'
},
{
names: ['all'],
type: 'bool',
help: 'Assign given platform image to all servers instead of just one.'
}
];
/**
* Update this SDC docker service setup:
* - update docker0 to latest image, adding the 'docker' service to the 'sdc'
* app in SAPI if necessary. Limitations: Presumes only a single instance
* (docker0). Presumes docker0 is on the HN.
* - nfs service and an instance on every CN (including the HN for now
* because we typically test with HN provisioning).
*
* TODO: import other setup ideas from
* https://gist.github.com/joshwilsdon/643e317ac0e2469d8e43
*/
ExperimentalCLI.prototype.do_update_docker =
function do_update_docker(subcmd, opts, args, cb) {
var self = this;
if (opts.help) {
this.do_help('help', {}, [subcmd], cb);
return;
} else if (args.length > 0) {
return cb(new errors.UsageError('too many args: ' + args));
}
var dockerSvcData = {
name: 'docker',
params: {
package_name: 'sdc_768',
image_uuid: 'TO_FILL_IN',
maintain_resolvers: true,
networks: [
{name: 'admin'},
{name: 'external', primary: true}
],
firewall_enabled: false,
tags: {
smartdc_role: 'docker',
smartdc_type: 'core'
},
customer_metadata: {}
// TO_FILL_IN: Fill out package values using $package_name package.
},
metadata: {
SERVICE_NAME: 'docker',
SERVICE_DOMAIN: 'TO_FILL_IN',
'user-script': 'TO_FILL_IN'
}
};
var nfsSvcData = {
name: 'nfs',
params: {
package_name: 'sdc_4096',
image_uuid: 'TO_FILL_IN',
maintain_resolvers: true,
networks: [
{name: 'admin'},
{name: 'external', primary: true}
],
filesystems: [
{
source: '/manta',
target: '/manta',
type: 'lofs',
options: [
'rw',
'nodevices'
]
}
],
firewall_enabled: false,
tags: {
smartdc_role: 'nfs',
smartdc_type: 'core'
},
customer_metadata: {}
// TO_FILL_IN: Fill out package values using $package_name package.
},
metadata: {
SERVICE_NAME: 'nfs',
SERVICE_DOMAIN: 'TO_FILL_IN',
'user-script': 'TO_FILL_IN'
}
};
var context = {
imgsToDownload: []
};
vasync.pipeline({arg: context, funcs: [
/* @field ctx.dockerPkg */
function getDockerPkg(ctx, next) {
var filter = {name: dockerSvcData.params.package_name};
self.sdcadm.papi.list(filter, {}, function (err, pkgs) {
if (err) {
return next(err);
} else if (pkgs.length !== 1) {
return next(new errors.InternalError({
message: format('%d "%s" packages found', pkgs.length,
dockerSvcData.params.package_name)}));
}
ctx.dockerPkg = pkgs[0];
next();
});
},
/* @field ctx.nfsPkg */
function getNfsPkg(ctx, next) {
var filter = {name: nfsSvcData.params.package_name};
self.sdcadm.papi.list(filter, {}, function (err, pkgs) {
if (err) {
return next(err);
} else if (pkgs.length !== 1) {
return next(new errors.InternalError({
message: format('%d "%s" packages found', pkgs.length,
nfsSvcData.params.package_name)}));
}
ctx.nfsPkg = pkgs[0];
next();
});
},
function ensureSapiMode(_, next) {
// Bail if SAPI not in 'full' mode.
self.sdcadm.sapi.getMode(function (err, mode) {
if (err) {
next(new errors.SDCClientError(err, 'sapi'));
} else if (mode !== 'full') {
next(new errors.UpdateError(format(
'SAPI is not in "full" mode: mode=%s', mode)));
} else {
next();
}
});
},
function getSdcApp(ctx, next) {
self.sdcadm.sapi.listApplications({name: 'sdc'},
function (appErr, apps) {
if (appErr) {
return next(new errors.SDCClientError(appErr, 'sapi'));
} else if (!apps.length) {
return next(new errors.SDCClientError(new Error(
'No applications named "sdc"'), 'sapi'));
}
ctx.app = apps[0];
next();
});
},
function ensureNoRabbitTrue(ctx, next) {
if (ctx.app.metadata.no_rabbit === true) {
return next();
}
self.progress('Setting "no_rabbit=true" SDC config');
self.progress('Warning: This changes other behaviour in the '
+ 'whole DC to use some new agents');
var update = {
metadata: {
no_rabbit: true
}
};
self.sdcadm.sapi.updateApplication(ctx.app.uuid, update,
errors.sdcClientErrWrap(next, 'sapi'));
},
function getDockerSvc(ctx, next) {
self.sdcadm.sapi.listServices({
name: 'docker',
application_uuid: ctx.app.uuid
}, function (svcErr, svcs) {
if (svcErr) {
return next(svcErr);
} else if (svcs.length) {
ctx.dockerSvc = svcs[0];
}
next();
});
},
function getNfsSvc(ctx, next) {
self.sdcadm.sapi.listServices({
name: 'nfs',
application_uuid: ctx.app.uuid
}, function (svcErr, svcs) {
if (svcErr) {
return next(svcErr);
} else if (svcs.length) {
ctx.nfsSvc = svcs[0];
}
next();
});
},
function getDockerInst(ctx, next) {
if (!ctx.dockerSvc) {
return next();
}
var filter = {
service_uuid: ctx.dockerSvc.uuid
};
self.sdcadm.sapi.listInstances(filter, function (err, insts) {
if (err) {
return next(new errors.SDCClientError(err, 'sapi'));
} else if (insts && insts.length) {
// Note this doesn't handle multiple insts.
ctx.dockerInst = insts[0];
}
next();
});
},
function getNfsInsts(ctx, next) {
if (!ctx.nfsSvc) {
ctx.nfsInsts = [];
return next();
}
var filter = {
service_uuid: ctx.nfsSvc.uuid
};
self.sdcadm.sapi.listInstances(filter, function (err, insts) {
if (err) {
return next(new errors.SDCClientError(err, 'sapi'));
}
ctx.nfsInsts = insts;
next();
});
},
function getLatestDockerImage(ctx, next) {
var filter = {name: 'docker'};
self.sdcadm.updates.listImages(filter, function (err, images) {
if (err) {
next(err);
} else if (images && images.length) {
//XXX presuming sorted
ctx.dockerImg = images[images.length - 1];
} else {
next(new errors.UpdateError('no "docker" image found'));
}
if (!opts.force && ctx.dockerSvc && ctx.dockerImg.uuid
=== ctx.dockerSvc.params.image_uuid) {
ctx.dockerImgNoop = true;
self.progress('Latest Docker image %s (%s %s) matches ' +
'the service (no image update)', ctx.dockerImg.uuid,
ctx.dockerImg.name, ctx.dockerImg.version);
} else {
ctx.dockerImgNoop = false;
}
next();
});
},
function getLatestNfsImage(ctx, next) {
var filter = {name: 'nfs'};
self.sdcadm.updates.listImages(filter, function (err, images) {
if (err) {
next(err);
} else if (images && images.length) {
//XXX presuming sorted
ctx.nfsImg = images[images.length - 1];
} else {
next(new errors.UpdateError('no "nfs" image found'));
}
if (!opts.force && ctx.nfsSvc &&
ctx.nfsImg.uuid === ctx.nfsSvc.params.image_uuid) {
ctx.nfsImgNoop = true;
self.progress('Latest NFS image %s (%s %s) matches ' +
'the service (no image update)', ctx.nfsImg.uuid,
ctx.nfsImg.name, ctx.nfsImg.version);
} else {
ctx.nfsImgNoop = false;
}
next();
});
},
function haveDockerImageAlready(ctx, next) {
self.sdcadm.imgapi.getImage(ctx.dockerImg.uuid,
function (err, img_) {
if (err && err.body && err.body.code === 'ResourceNotFound') {
ctx.imgsToDownload.push(ctx.dockerImg);
} else if (err) {
return next(err);
}
next();
});
},
function haveNfsImageAlready(ctx, next) {
self.sdcadm.imgapi.getImage(ctx.nfsImg.uuid, function (err, img_) {
if (err && err.body && err.body.code === 'ResourceNotFound') {
ctx.imgsToDownload.push(ctx.nfsImg);
} else if (err) {
return next(err);
}
next();
});
},
function importImages(ctx, next) {
if (ctx.imgsToDownload.length === 0) {
return next();
}
var proc = new DownloadImages({images: ctx.imgsToDownload});
proc.execute({
sdcadm: self.sdcadm,
log: self.log,
progress: self.progress
}, next);
},
/* @field ctx.userString */
shared.getUserScript,
function createDockerSvc(ctx, next) {
if (ctx.dockerSvc) {
return next();
}
var domain = ctx.app.metadata.datacenter_name + '.' +
ctx.app.metadata.dns_domain;
var svcDomain = dockerSvcData.name + '.' + domain;
self.progress('Creating "docker" service');
dockerSvcData.params.image_uuid = ctx.dockerImg.uuid;
dockerSvcData.metadata['user-script'] = ctx.userScript;
dockerSvcData.metadata['SERVICE_DOMAIN'] = svcDomain;
dockerSvcData.params.cpu_shares = ctx.dockerPkg.max_physical_memory;
dockerSvcData.params.cpu_cap = ctx.dockerPkg.cpu_cap;
dockerSvcData.params.zfs_io_priority
= ctx.dockerPkg.zfs_io_priority;
dockerSvcData.params.max_lwps = ctx.dockerPkg.max_lwps;
dockerSvcData.params.max_physical_memory =
dockerSvcData.params.max_locked_memory =
ctx.dockerPkg.max_physical_memory;
dockerSvcData.params.max_swap = ctx.dockerPkg.max_swap;
dockerSvcData.params.quota =
(ctx.dockerPkg.quota / 1024).toFixed(0);
dockerSvcData.params.package_version = ctx.dockerPkg.version;
dockerSvcData.params.billing_id = ctx.dockerPkg.uuid;
self.sdcadm.sapi.createService('docker', ctx.app.uuid,
dockerSvcData, function (err, svc) {
if (err) {
return next(new errors.SDCClientError(err, 'sapi'));
}
ctx.dockerSvc = svc;
self.log.info({svc: svc}, 'created docker svc');
next();
});
},
function createNfsSvc(ctx, next) {
if (ctx.nfsSvc) {
return next();
}
var domain = ctx.app.metadata.datacenter_name + '.' +
ctx.app.metadata.dns_domain;
var svcDomain = nfsSvcData.name + '.' + domain;
self.progress('Creating "nfs" service');
nfsSvcData.params.image_uuid = ctx.nfsImg.uuid;
nfsSvcData.metadata['user-script'] = ctx.userScript;
nfsSvcData.metadata['SERVICE_DOMAIN'] = svcDomain;
nfsSvcData.params.cpu_shares = ctx.nfsPkg.max_physical_memory;
nfsSvcData.params.cpu_cap = ctx.nfsPkg.cpu_cap;
nfsSvcData.params.zfs_io_priority = ctx.nfsPkg.zfs_io_priority;
nfsSvcData.params.max_lwps = ctx.nfsPkg.max_lwps;
nfsSvcData.params.max_physical_memory =
nfsSvcData.params.max_locked_memory =
ctx.nfsPkg.max_physical_memory;
nfsSvcData.params.max_swap = ctx.nfsPkg.max_swap;
nfsSvcData.params.quota = (ctx.nfsPkg.quota / 1024).toFixed(0);
nfsSvcData.params.package_version = ctx.nfsPkg.version;
nfsSvcData.params.billing_id = ctx.nfsPkg.uuid;
self.sdcadm.sapi.createService('nfs', ctx.app.uuid,
nfsSvcData, function (err, svc) {
if (err) {
return next(new errors.SDCClientError(err, 'sapi'));
}
ctx.nfsSvc = svc;
self.log.info({svc: svc}, 'created nfs svc');
next();
});
},
function createDockerInst(ctx, next) {
if (ctx.dockerInst) {
return next();
}
self.progress('Creating "docker" instance');
var instOpts = {
params: {
alias: 'docker0'
}
};
self.sdcadm.sapi.createInstance(ctx.dockerSvc.uuid, instOpts,
function (err, inst) {
if (err) {
return next(new errors.SDCClientError(err, 'sapi'));
}
self.progress('Created VM %s (%s)', inst.uuid,
inst.params.alias);
next();
});
},
function getServersNeedingNfs(ctx, next) {
var filter = {
setup: true,
reserved: false
};
self.sdcadm.cnapi.listServers(filter, function (err, servers) {
if (err) {
return next(new errors.SDCClientError(err, 'cnapi'));
}
// Only include running servers.
// We *are* incuding the headnode for now because common dev
// practice includes using the headnode for docker containers.
var nfsServers = servers.filter(
function (s) { return s.status === 'running'; });
var nfsInstFromServer = {};
ctx.nfsInsts.forEach(function (inst) {
nfsInstFromServer[inst.params.server_uuid] = inst;
});
ctx.serversWithNoNfsInst = nfsServers.filter(function (s) {
return nfsInstFromServer[s.uuid] === undefined;
});
self.progress('Found %d setup, not reserved, '
+ 'and running server(s) without an "nfs" instance',
ctx.serversWithNoNfsInst.length);
next();
});
},
function createGzMantaDirOnNfsServers(ctx, next) {
if (ctx.serversWithNoNfsInst.length === 0) {
return next();
}
self.progress('Creating "/manta" dir in GZ for "nfs" instances '
+ 'on %d server(s)', ctx.serversWithNoNfsInst.length);
/**
* Dev Note: I'd like to use the urclient here (as in
* sdcadm.js#checkHealth), but until the
* `process._getActiveHandles()` hack is obviated, I'm not touching
* it.
*
* Dev Note: I'm doing this one at a time to avoid MAX_LINE
* command, and because doing in blocks of 10 servers is a coding
* pain. TODO: improve this.
*/
vasync.forEachParallel({
inputs: ctx.serversWithNoNfsInst,
func: function createGzMantaDir(server, nextServer) {
var argv = [
'/opt/smartdc/bin/sdc-oneachnode', '-j',
'-n', server.uuid, 'mkdir -p /manta'
];
common.execFilePlus({argv: argv, log: self.log},
function (err, stdout, stderr) {
if (err) {
return nextServer(err);
}
try {
var res = JSON.parse(stdout)[0];
} catch (ex) {
return nextServer(ex);
}
if (res.error || res.result.exit_status !== 0) {
nextServer(new errors.UpdateError(
'error creating GZ /manta dir on server %s: %s',
server.uuid, stdout));
} else {
nextServer();
}
});
}
}, next);
},
function createNfsInsts(ctx, next) {
if (ctx.serversWithNoNfsInst.length === 0) {
return next();
}
self.progress('Creating "nfs" instances on %d server(s)',
ctx.serversWithNoNfsInst.length);
ctx.newNfsInsts = [];
vasync.forEachPipeline({
inputs: ctx.serversWithNoNfsInst,
func: function createNfsInst(server, nextServer) {
var instOpts = {
params: {
alias: 'nfs-' + server.hostname,
server_uuid: server.uuid
}
};
self.sdcadm.sapi.createInstance(ctx.nfsSvc.uuid, instOpts,
function (err, inst) {
if (err) {
return next(new errors.SDCClientError(err, 'sapi'));
}
self.progress('Created VM %s (%s)', inst.uuid,
inst.params.alias);
ctx.newNfsInsts.push(inst);
nextServer();
});
}
}, next);
},
function updateDockerSvcImageUuid(ctx, next) {
if (ctx.dockerImgNoop || !ctx.dockerInst) {
return next();
}
self.progress('Update "image_uuid=%s" in "docker" SAPI service',
ctx.dockerImg.uuid);
var update = {
params: {
image_uuid: ctx.dockerImg.uuid
}
};
self.sdcadm.sapi.updateService(ctx.dockerSvc.uuid, update,
errors.sdcClientErrWrap(next, 'sapi'));
},
function updateNfsSvcImageUuid(ctx, next) {
if (ctx.nfsImgNoop || ctx.nfsInsts.length === 0) {
return next();
}
self.progress('Update "image_uuid=%s" in "nfs" SAPI service',
ctx.nfsImg.uuid);
var update = {
params: {
image_uuid: ctx.nfsImg.uuid
}
};
self.sdcadm.sapi.updateService(ctx.nfsSvc.uuid, update,
errors.sdcClientErrWrap(next, 'sapi'));
},
function reprovisionDockerInst(ctx, next) {
if (ctx.dockerImgNoop || !ctx.dockerInst) {
return next();
}
self.progress('Reprovision "docker" instance %s',
ctx.dockerInst.uuid);
self.sdcadm.sapi.reprovisionInstance(ctx.dockerInst.uuid,
ctx.dockerImg.uuid, function (err) {
if (err) {
return next(new errors.SDCClientError(err, 'sapi'));
}
next();
});
},
function reprovisionNfsInsts(ctx, next) {
if (ctx.nfsImgNoop) {
return next();
}
vasync.forEachPipeline({
inputs: ctx.nfsInsts,
func: function reproNfsInst(inst, nextInst) {
// First get its current image from VMAPI to not reprov
// if not necessary.
self.sdcadm.vmapi.getVm({uuid: inst.uuid},
function (vmErr, vm) {
if (vmErr) {
return nextInst(vmErr);
} else if (vm.image_uuid === ctx.nfsImg.uuid) {
return nextInst();
}
self.progress('Reprovision %s (%s) inst to image %s',
inst.uuid, inst.params.alias, ctx.nfsImg.uuid);
self.sdcadm.sapi.reprovisionInstance(ctx.nfsInst.uuid,
ctx.nfsImg.uuid, function (err) {
if (err) {
return nextInst(
new errors.SDCClientError(err, 'sapi'));
}
nextInst();
});
});
}
}, next);
},
function done(_, next) {
self.progress('Updated SDC Docker');
next();
}
]}, cb);
};
ExperimentalCLI.prototype.do_update_docker.options = [
{
names: ['help', 'h'],
type: 'bool',
help: 'Show this help.'
},
{
names: ['force', 'f'],
type: 'bool',
help: 'Allow update to proceed even if already at latest image.'
}
];
ExperimentalCLI.prototype.do_update_docker.help = (
'Add/update the docker service.\n' +
'\n' +
'Usage:\n' +
' {{name}} update-docker\n' +
'\n' +
'{{options}}'
);
/**
* Update portolan0, adding the 'portolan' service to the 'sdc' app in SAPI
* if necessary.
*
* Limitations:
* - presumes only a single instance (portolan0)
* - presumes portolan0 is on the HN
*/
ExperimentalCLI.prototype.do_portolan =
function portolan(subcmd, opts, args, cb) {
var self = this;
if (opts.help) {
this.do_help('help', {}, [subcmd], cb);
return;
} else if (args.length > 0) {
return cb(new errors.UsageError('too many args: ' + args));
}
var svcData = {
name: 'portolan',
params: {
package_name: 'sdc_768',
image_uuid: 'TO_FILL_IN',
maintain_resolvers: true,
networks: ['admin'],
firewall_enabled: true,
tags: {
smartdc_role: 'portolan',
smartdc_type: 'core'
},
customer_metadata: {}
// TO_FILL_IN: Fill out package values using sdc_768 package.
},
metadata: {
SERVICE_NAME: 'portolan',
SERVICE_DOMAIN: 'TO_FILL_IN',
'user-script': 'TO_FILL_IN'
}
};
var img, haveImg, app, svc, inst, svcExists, instExists, imgNoop;
vasync.pipeline({arg: {}, funcs: [
/* @field ctx.package */
function getPackage(ctx, next) {
var filter = {name: 'sdc_768'};
self.sdcadm.papi.list(filter, {}, function (err, pkgs) {
if (err) {
return next(err);
} else if (pkgs.length !== 1) {
return next(new errors.InternalError({
message: pkgs.length + ' "sdc_768" packages found'}));
}
ctx.package = pkgs[0];
next();
});
},
function getSdcApp(_, next) {
self.sdcadm.sapi.listApplications({name: 'sdc'},
function (appErr, apps) {
if (appErr) {
return next(new errors.SDCClientError(appErr, 'sapi'));
} else if (!apps.length) {
return next(new errors.SDCClientError(new Error(
'No applications named "sdc"'), 'sapi'));
}
app = apps[0];
next();
});
},
function getPortolanSvc(_, next) {
self.sdcadm.sapi.listServices({
name: 'portolan',
application_uuid: app.uuid
}, function (svcErr, svcs) {
if (svcErr) {
return next(svcErr);
} else if (svcs.length) {
svc = svcs[0];
svcExists = true;
} else {
svcExists = false;
}
next();
});
},
function getPortolanInst(_, next) {
if (!svcExists) {
instExists = false;
return next();
}
var filter = {
service_uuid: svc.uuid,
name: 'portolan'
};
self.sdcadm.sapi.listInstances(filter, function (err, insts) {
if (err) {
return next(new errors.SDCClientError(err, 'sapi'));
} else if (insts && insts.length) {
// Note this doesn't handle multiple insts.
inst = insts[0];
instExists = true;
} else {
instExists = false;
}
next();
});
},
function getLatestImage(_, next) {
var filter = {name: 'portolan'};
self.sdcadm.updates.listImages(filter, function (err, images) {
if (err) {
next(err);
} else if (images && images.length) {
img = images[images.length - 1]; //XXX presuming sorted
} else {
next(new errors.UpdateError('no "portolan" image found'));
}
if (!opts.force && svcExists &&
img.uuid === svc.params.image_uuid) {
imgNoop = true;
self.progress('Portolan image %s (%s %s) matches the ' +
'service: nothing to do', img.uuid, img.name,
img.version);
} else {
imgNoop = false;
}
next();
});
},
function haveImageAlready(_, next) {
self.sdcadm.imgapi.getImage(img.uuid, function (err, img_) {
if (err && err.body && err.body.code === 'ResourceNotFound') {
haveImg = false;
} else if (err) {
next(err);
} else {
haveImg = true;
}
next();
});
},
function importImage(_, next) {
if (imgNoop || haveImg) {
return next();
}
var proc = new DownloadImages({images: [img]});
proc.execute({
sdcadm: self.sdcadm,
log: self.log,
progress: self.progress
}, next);
},
/* @field ctx.userScript */
shared.getUserScript,
function createPortolanSvc(ctx, next) {
if (imgNoop || svcExists) {
return next();
}
var domain = app.metadata.datacenter_name + '.' +
app.metadata.dns_domain;
var svcDomain = svcData.name + '.' + domain;
self.progress('Creating "portolan" service');
svcData.params.image_uuid = img.uuid;
svcData.metadata['user-script'] = ctx.userScript;
svcData.metadata['SERVICE_DOMAIN'] = svcDomain;
svcData.params.cpu_shares = ctx.package.max_physical_memory;
svcData.params.cpu_cap = ctx.package.cpu_cap;
svcData.params.zfs_io_priority = ctx.package.zfs_io_priority;
svcData.params.max_lwps = ctx.package.max_lwps;
svcData.params.max_physical_memory =
ctx.package.max_physical_memory;
svcData.params.max_locked_memory = ctx.package.max_physical_memory;
svcData.params.max_swap = ctx.package.max_swap;
svcData.params.quota = (ctx.package.quota / 1024).toFixed(0);
svcData.params.package_version = ctx.package.version;
svcData.params.billing_id = ctx.package.uuid;
self.sdcadm.sapi.createService('portolan', app.uuid, svcData,
function (err, svc_) {
if (err) {
return next(new errors.SDCClientError(err, 'sapi'));
}
svc = svc_;
self.log.info({svc: svc}, 'created portolan svc');
next();
});
},
function createPortolanInst(_, next) {
if (imgNoop || instExists) {
return next();
}
self.progress('Creating "portolan" instance');
var instOpts = {
params: {
alias: 'portolan0'
}
};
self.sdcadm.sapi.createInstance(svc.uuid, instOpts,
function (err, inst_) {
if (err) {
return next(new errors.SDCClientError(err, 'sapi'));
}
inst = inst_;
next();
});
},
function reprovisionPortolanInst(_, next) {
if (imgNoop || !instExists) {
return next();
}
self.progress('Reprovision "portolan" instance %s (%s)',
inst.uuid, inst.alias);
self.sdcadm.sapi.reprovisionInstance(inst.uuid, img.uuid,
function (err) {
if (err) {
return next(new errors.SDCClientError(err, 'sapi'));
}
next();
});
},
function done(_, next) {
if (imgNoop) {
return next();
}
self.progress('Updated portolan');
next();
}
]}, cb);
};
ExperimentalCLI.prototype.do_portolan.options = [
{
names: ['help', 'h'],
type: 'bool',
help: 'Show this help.'
},
{
names: ['force', 'f'],
type: 'bool',
help: 'Allow updates to proceed even if already at latest image.'
}
];
ExperimentalCLI.prototype.do_portolan.help = (
'Add/update the portolan service.\n' +
'\n' +
'Usage:\n' +
' {{name}} portolan\n' +
'\n' +
'{{options}}'
);
//---- exports
module.exports = {
ExperimentalCLI: ExperimentalCLI
};
| lib/experimental.js | /*
* 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/.
*/
/*
* Copyright (c) 2014, Joyent, Inc.
*/
/*
* Collecting 'sdcadm experimental ...' CLI commands.
*
* These are temporary, unsupported commands for running SDC updates before
* the grand plan of 'sdcadm update' fully handling updates is complete.
*/
var p = console.log;
var util = require('util'),
format = util.format;
var fs = require('fs');
var cp = require('child_process');
var execFile = cp.execFile;
var spawn = cp.spawn;
var vasync = require('vasync');
var read = require('read');
var assert = require('assert-plus');
var cmdln = require('cmdln'),
Cmdln = cmdln.Cmdln;
var common = require('./common');
var errors = require('./errors');
var DownloadImages = require('./procedures/download-images').DownloadImages;
var shared = require('./procedures/shared');
//---- globals
//---- Experimental CLI class
function ExperimentalCLI(top) {
this.top = top;
Cmdln.call(this, {
name: 'sdcadm experimental',
desc: 'Experimental, unsupported, temporary sdcadm commands.\n' +
'\n' +
'These are unsupported and temporary commands to assist with\n' +
'migration away from incr-upgrade scripts. The eventual\n' +
'general upgrade process will not include any commands under\n' +
'"sdcadm experimental".',
helpOpts: {
minHelpCol: 24 /* line up with option help */
}
});
}
util.inherits(ExperimentalCLI, Cmdln);
ExperimentalCLI.prototype.init = function init(opts, args, callback) {
this.sdcadm = this.top.sdcadm;
this.progress = this.top.progress;
this.log = this.top.log;
Cmdln.prototype.init.apply(this, arguments);
};
/*
* Update agents in datancenter with a given or latest agents installer.
*/
ExperimentalCLI.prototype.do_update_agents =
function do_update_agents(subcmd, opts, args, cb) {
var self = this;
if (!opts.latest && !args[0]) {
return cb(new errors.UsageError(
'must specify installer image UUID or --latest'));
}
return self.sdcadm.updateAgents({
image: (opts.latest) ? 'latest' : args[0],
progress: self.progress,
justDownload: opts.just_download
}, cb);
};
ExperimentalCLI.prototype.do_update_agents.help = (
'Update SDC agents\n' +
'\n' +
'Usage:\n' +
' {{name}} update-agents IMAGE-UUID\n' +
' {{name}} update-agents PATH-TO-INSTALLER\n' +
' {{name}} update-agents --latest\n' +
'\n' +
'{{options}}'
);
ExperimentalCLI.prototype.do_update_agents.options = [
{
names: ['latest'],
type: 'bool',
help: 'Update using the last published agents installer.'
},
{
names: ['just-download'],
type: 'bool',
help: 'Download the agents installer for later usage.'
}
];
ExperimentalCLI.prototype.do_dc_maint =
function do_dc_maint(subcmd, opts, args, cb) {
var self = this;
if (opts.help) {
this.do_help('help', {}, [subcmd], cb);
return;
} else if (args.length > 0) {
return cb(new errors.UsageError('too many args: ' + args));
}
if (opts.start && opts.stop) {
cb(new errors.UsageError('cannot use --start and --stop'));
} else if (opts.start) {
this.sdcadm.dcMaintStart({progress: self.progress}, cb);
} else if (opts.stop) {
this.sdcadm.dcMaintStop({progress: self.progress}, cb);
} else {
this.sdcadm.dcMaintStatus(function (err, status) {
if (err) {
return cb(err);
}
if (opts.json) {
self.progress(JSON.stringify(status, null, 4));
} else if (status.maint) {
if (status.startTime) {
self.progress('DC maintenance: on (since %s)',
status.startTime);
} else {
self.progress('DC maintenance: on');
}
} else {
self.progress('DC maintenance: off');
}
cb();
});
}
cb();
};
ExperimentalCLI.prototype.do_dc_maint.options = [
{
names: ['help', 'h'],
type: 'bool',
help: 'Show this help.'
},
{
names: ['json', 'j'],
type: 'bool',
help: 'Show status as JSON.'
},
{
names: ['start'],
type: 'bool',
help: 'Start maintenance mode.'
},
{
names: ['stop'],
type: 'bool',
help: 'Stop maintenance mode (i.e. restore DC to full operation).'
}
];
ExperimentalCLI.prototype.do_dc_maint.help = (
'Show and modify the DC maintenance mode.\n' +
'\n' +
'"Maintenance mode" for an SDC means that Cloud API is in read-only\n' +
'mode. Modifying requests will return "503 Service Unavailable".\n' +
'Workflow API will be drained on entering maint mode.\n' +
'\n' +
'Limitation: This does not current wait for config changes to be made\n' +
'and cloudapi instances restarted. That means there is a window after\n' +
'starting that new jobs could come in.\n' +
'\n' +
'Usage:\n' +
' {{name}} dc-maint [-j] # show DC maint status\n' +
' {{name}} dc-maint [--start] # start DC maint\n' +
' {{name}} dc-maint [--stop] # stop DC maint\n' +
'\n' +
'{{options}}'
);
/**
* This is the temporary quick replacement for incr-upgrade's
* "upgrade-other.sh".
*/
ExperimentalCLI.prototype.do_update_other =
function do_update_other(subcmd, opts, args, cb) {
var self = this;
var progress = self.progress;
if (opts.help) {
this.do_help('help', {}, [subcmd], cb);
return;
} else if (args.length > 0) {
return cb(new errors.UsageError('too many args: ' + args));
}
var app, caInst, caSvc, domain, regionName, sapiUrl, services;
// Used by history:
var history;
var changes = [];
// Helper functions
function updateService(uuid, svcOpts, next) {
self.sdcadm.sapi.updateService(uuid, svcOpts, function (err, svc) {
if (err) {
return next(new errors.SDCClientError(err, 'sapi'));
}
next();
});
}
function updateApplication(svcOpts, next) {
self.sdcadm.sapi.updateApplication(app.uuid, svcOpts,
function (err, svc) {
if (err) {
return next(new errors.SDCClientError(err, 'sapi'));
}
next();
});
}
function readField(field, default_, cbRead) {
if (cbRead === undefined) {
cbRead = default_;
default_ = undefined;
}
assert.object(field, 'field');
assert.func(cbRead);
var readOpts = {
prompt: field.name + ':',
silent: field.hidden,
default: default_
};
read(readOpts, function (rErr, val) {
if (rErr) {
return cbRead(rErr);
}
val = val.trim();
if (!field.confirm) {
return cbRead(null, val);
}
readOpts.prompt = field.name + ' confirm:';
read(readOpts, function (rErr2, val2) {
if (rErr2) {
return cbRead(rErr2);
}
val2 = val2.trim();
if (val !== val2) {
cbRead(new Error(format(
'%s values do not match', field.name)));
} else {
cbRead(null, val);
}
});
});
}
// TODO move to some place where it can be reused
function mountUsbKey(_, cbMount) {
execFile('/usbkey/scripts/mount-usb.sh', cbMount);
}
// TODO move to some place where it can be reused
function unmountUsbKey(_, cbMount) {
execFile('/usr/sbin/umount', [ '/mnt/usbkey' ], cbMount);
}
// Upgrade pipeline
vasync.pipeline({funcs: [
function getSdcApp(_, next) {
self.sdcadm.sapi.listApplications({ name: 'sdc' },
function (appErr, apps) {
if (appErr) {
return next(new errors.SDCClientError(appErr, 'sapi'));
} else if (!apps.length) {
return next(new errors.SDCClientError(new Error(
'No applications named "sdc"'), 'sapi'));
}
app = apps[0];
domain = app.metadata.datacenter_name + '.' +
app.metadata.dns_domain;
sapiUrl = app.metadata['sapi-url'];
return next();
});
},
function getServices(_, next) {
self.sdcadm.getServices({}, function (err, svcs) {
if (err) {
return next(err);
}
services = svcs;
// Locate CA for later
svcs.forEach(function (svc) {
if (svc.name === 'ca') {
caSvc = svc;
}
});
return next();
});
},
function saveChangesToHistory(_, next) {
services.forEach(function (svc) {
if (svc.type === 'vm') {
changes.push({
service: svc,
type: 'update-service-cfg'
});
}
});
self.sdcadm.history.saveHistory({
changes: changes
}, function (err, hst) {
if (err) {
return next(err);
}
history = hst;
return next();
});
},
function updateMaintainResolvers(_, next) {
progress('Updating maintain_resolvers for all vm services');
function updateSvc(svc, nextSvc) {
if (svc.type === 'vm' && svc.params &&
svc.params.maintain_resolvers !== true) {
updateService(svc.uuid,
{ params: { maintain_resolvers: true } },
nextSvc);
return;
}
return nextSvc();
}
vasync.forEachParallel({
inputs: services,
func: updateSvc
}, next);
},
function updateServiceDomains(_, next) {
var SERVICES = ['papi', 'mahi'];
progress('Updating DNS domain service metadata for %s',
SERVICES.join(', '));
function updateSvc(svc, nextSvc) {
if (SERVICES.indexOf(svc.name) !== -1) {
var svcDomain = svc.name + '.' + domain;
updateService(svc.uuid,
{ metadata: {
SERVICE_DOMAIN: svcDomain,
'sapi-url': sapiUrl
} },
nextSvc);
return;
}
return nextSvc();
}
vasync.forEachParallel({
inputs: services,
func: updateSvc
}, next);
},
function updateAppDomains(_, next) {
var SERVICES = ['papi', 'mahi'];
progress('Updating DNS domain SDC application metadata for %s',
SERVICES.join(', '));
function updateApp(svc, nextSvc) {
if (SERVICES.indexOf(svc.name) !== -1) {
var svcDomain = svc.name + '.' + domain;
var metadata = {};
metadata[svc.name.toUpperCase() + '_SERVICE'] = svcDomain;
metadata[svc.name + '_domain'] = svcDomain;
updateApplication({ metadata: metadata }, nextSvc);
return;
}
return nextSvc();
}
vasync.forEachParallel({
inputs: services,
func: updateApp
}, next);
},
function updateCaParams(_, next) {
function getCaInstance(__, next_) {
var filters = {
state: 'active',
owner_uuid: self.sdcadm.config.ufds_admin_uuid,
alias: 'ca0'
};
self.sdcadm.vmapi.listVms(filters, function (vmsErr, vms) {
if (vmsErr) {
return next_(vmsErr);
}
caInst = vms[0];
return next_();
});
}
function updateCaService(__, next_) {
if (caSvc.params.max_physical_memory >= 4096) {
return next_();
}
progress('Updating CA service\'s max_physical_memory value');
var params = {
max_physical_memory: 4096,
max_locked_memory: 4096,
max_swap: 8192,
zfs_io_priority: 20,
cpu_cap: 400,
package_name: 'sdc_4096'
};
updateService(caSvc.uuid, { params: params }, next_);
}
function updateCaInstance(__, next_) {
if (caInst.max_physical_memory >= 4096) {
return next_();
}
progress('Updating CA\'s ca0 instance ' +
'max_physical_memory value');
var argv = [
'/usr/sbin/vmadm',
'update',
caInst.uuid,
'max_physical_memory=4096',
'max_locked_memory=4096',
'max_swap=8192',
'zfs_io_priority=20',
'cpu_cap=400'
];
common.execFilePlus({argv: argv, log: self.log}, next_);
}
vasync.pipeline({
funcs: [getCaInstance, updateCaService, updateCaInstance]
}, next);
},
function updateRegionName(_, next) {
fs.readFile('/usbkey/config', {
encoding: 'utf8'
}, function (err, data) {
if (err) {
return next(err);
/* JSSTYLED */
} else if (data.search(/region_name=/) !== -1) {
progress('No need to update region_name for ' +
'this data center');
return next();
}
function readRegionName(__, next_) {
progress('Updating region_name for this data center');
var field = {
name: 'region_name',
hidden: false,
confirm: true
};
readField(field, function (err1, value) {
if (err1) {
return next_(err1);
}
regionName = value;
return next_();
});
}
function appendRegionName(__, next_) {
var region = 'region_name=' + regionName + '\n';
fs.appendFile('/mnt/usbkey/config', region,
function (err1) {
if (err1) {
return next_(err1);
}
var argv = [
'/usr/bin/cp',
'/mnt/usbkey/config',
'/usbkey/config'
];
common.execFilePlus({argv: argv, log: self.log}, next_);
});
}
function updateSapiRegionName(__, next_) {
var metadata = { region_name: regionName };
updateApplication({ metadata: metadata }, next_);
}
vasync.pipeline({funcs: [
readRegionName,
mountUsbKey,
appendRegionName,
unmountUsbKey,
updateSapiRegionName
]}, next);
});
},
function addSapiDomainToNodeConfig(_, next) {
var nodeConfig = '/usbkey/extra/joysetup/node.config';
var sapiDomain = 'sapi_domain=\'sapi.' + domain + '\'\n';
fs.readFile(nodeConfig, { encoding: 'utf8' }, function (err, data) {
if (err) {
return next(err);
/* JSSTYLED */
} else if (data.search(/sapi_domain=/) !== -1) {
progress('sapi_domain already present on node.config');
return next();
}
progress('Appending sapi_domain to node.config');
fs.appendFile(nodeConfig, sapiDomain, next);
});
}
]}, function (err) {
if (err) {
history.error = err;
}
self.sdcadm.history.updateHistory(history, function (err2) {
if (err) {
return cb(err);
}
progress('Done.');
if (err2) {
return cb(err2);
} else {
return cb();
}
});
});
};
ExperimentalCLI.prototype.do_update_other.options = [
{
names: ['help', 'h'],
type: 'bool',
help: 'Show this help.'
}
];
ExperimentalCLI.prototype.do_update_other.help = (
'Temporary grabbag for small SDC update steps.\n' +
'The eventual goal is to integrate all of this into "sdcadm update".\n' +
'\n' +
'Usage:\n' +
' {{name}} update-other\n' +
'\n' +
'{{options}}'
);
/**
* This is the temporary quick replacement for incr-upgrade's
* "upgrade-tools.sh".
*/
ExperimentalCLI.prototype.do_update_gz_tools =
function do_update_gz_tools(subcmd, opts, args, cb) {
var self = this;
var progress = self.progress;
var execStart = Date.now();
function finish(err) {
if (err) {
return cb(err);
}
progress('Updated gz-tools successfully (elapsed %ds).',
Math.floor((Date.now() - execStart) / 1000));
return cb();
}
if (!opts.latest && !args[0]) {
return finish(new errors.UsageError(
'must specify installer image UUID or --latest'));
}
self.sdcadm.updateGzTools({
image: opts.latest ? 'latest' : args[0],
progress: progress,
justDownload: opts.just_download
}, finish);
};
ExperimentalCLI.prototype.do_update_gz_tools.options = [
{
names: ['help', 'h'],
type: 'bool',
help: 'Show this help.'
},
{
names: ['latest'],
type: 'bool',
help: 'Update using the last published gz-tools installer.'
},
{
names: ['just-download'],
type: 'bool',
help: 'Download the GZ Tools installer for later usage.'
}
];
ExperimentalCLI.prototype.do_update_gz_tools.help = (
'Temporary grabbag for updating the SDC global zone tools.\n' +
'The eventual goal is to integrate all of this into "sdcadm update".\n' +
'\n' +
'Usage:\n' +
' {{name}} update-gz-tools IMAGE-UUID\n' +
' {{name}} update-gz-tools PATH-TO-INSTALLER\n' +
' {{name}} update-gz-tools --latest\n' +
'\n' +
'{{options}}'
);
ExperimentalCLI.prototype.do_add_new_agent_svcs =
function do_add_new_agents_svcs(subcmd, opts, args, cb) {
var self = this;
var progress = self.progress;
var execStart = Date.now();
if (opts.help) {
this.do_help('help', {}, [subcmd], cb);
return;
} else if (args.length > 1) {
return cb(new errors.UsageError('too many args: ' + args));
}
// We need at least a MIN_VALID_SAPI_VERSION image so
// type=agent suport is there.
var MIN_VALID_SAPI_VERSION = '20140703';
var app, svc, inst, vm, img;
var agentNames = ['vm-agent', 'net-agent', 'cn-agent'];
var agentServices = {};
agentNames.forEach(function (n) {
var logLevelKey = n.toUpperCase().replace('-', '_') + '_LOG_LEVEL';
agentServices[n] = {
type: 'agent',
params: {
tags: {
smartdc_role: n,
smartdc_type: 'core'
}
},
metadata: {
SERVICE_NAME: n
},
manifests: {
}
};
agentServices[n].metadata[logLevelKey] = 'info';
});
var newAgentServices = [];
// Used by history:
var history;
var changes = [];
vasync.pipeline({funcs: [
function getSdcApp(_, next) {
progress('Getting SDC application details from SAPI');
self.sdcadm.sapi.listApplications({ name: 'sdc' },
function (appErr, apps) {
if (appErr) {
return next(new errors.SDCClientError(appErr, 'sapi'));
} else if (!apps.length) {
return next(new errors.SDCClientError(new Error(
'No applications named "sdc"'), 'sapi'));
}
app = apps[0];
return next();
});
},
function getSapiService(_, next) {
progress('Getting SDC\'s SAPI service details from SAPI');
self.sdcadm.sapi.listServices({
name: 'sapi',
application_uuid: app.uuid
}, function (svcErr, svcs) {
if (svcErr) {
return next(svcErr);
}
if (!svcs.length) {
return next(new errors.SDCClientError(new Error(
'No services named "manatee"'), 'sapi'));
}
svc = svcs[0];
return next();
});
},
function getSapiInstance(_, next) {
progress('Getting SDC\'s sapi instances from SAPI');
self.sdcadm.sapi.listInstances({
service_uuid: svc.uuid
}, function (instErr, insts) {
if (instErr) {
return next(instErr);
}
if (!insts.length) {
return next(new errors.SDCClientError(new Error(
'Unable to find first sapi instance'), 'sapi'));
}
inst = insts[0];
return next();
});
},
function getSapiVm(_, next) {
progress('Getting sapi VM details from VMAPI');
self.sdcadm.vmapi.getVm({uuid: inst.uuid}, function (vmErr, obj) {
if (vmErr) {
return next(vmErr);
}
vm = obj;
return next();
});
},
function getSapiImage(_, next) {
progress('Getting sapi Image details from IMGAPI');
self.sdcadm.imgapi.getImage(vm.image_uuid, function (imgErr, obj) {
if (imgErr) {
return next(imgErr);
}
img = obj;
return next();
});
},
function checkMinSapiVersion(_, next) {
progress('Checking for minimum SAPI version');
var splitVersion = img.version.split('-');
var validSapi = false;
if (splitVersion[0] === 'master') {
validSapi = splitVersion[1].substr(0, 8) >=
MIN_VALID_SAPI_VERSION;
} else if (splitVersion[0] === 'release') {
validSapi = splitVersion[1] >= MIN_VALID_SAPI_VERSION;
}
if (!validSapi) {
return next(new errors.SDCClientError(new Error('Datacenter ' +
'does not have the minimum SAPI version needed for adding' +
' service agents. ' +
'Please, try again after upgrading SAPI')));
}
return next();
},
function checkExistingAgents(_, next) {
vasync.forEachParallel({
func: function checkAgentExist(agent, callback) {
progress('Checking if service \'%s\' exists', agent);
self.sdcadm.sapi.listServices({
name: agent,
type: 'agent',
application_uuid: app.uuid
}, function (svcErr, svcs) {
if (svcErr) {
return callback(svcErr);
}
if (!svcs.length) {
newAgentServices.push(agent);
}
return callback();
});
},
inputs: Object.keys(agentServices)
}, function (err) {
if (err) {
return next(err);
}
return next();
});
},
function saveChangesToHistory(_, next) {
newAgentServices.forEach(function (s) {
changes.push({
service: {
name: s,
type: 'agent'
},
type: 'create-service'
});
});
self.sdcadm.history.saveHistory({
changes: changes
}, function (err, hst) {
if (err) {
return next(err);
}
history = hst;
return next();
});
},
function addAgentsServices(_, next) {
vasync.forEachParallel({
inputs: newAgentServices,
func: function addAgentSvc(agent, callback) {
progress('Adding service for agent \'%s\'', agent);
self.log.trace({
service: agent,
params: agentServices[agent]
}, 'Adding new agent service');
self.sdcadm.sapi.createService(agent, app.uuid,
agentServices[agent], function (err) {
if (err) {
return callback(err);
}
return callback();
});
}
}, function (err) {
if (err) {
return next(err);
}
return next();
});
}
]}, function (err) {
progress('Add new agent services finished (elapsed %ds).',
Math.floor((Date.now() - execStart) / 1000));
if (err) {
history.error = err;
}
self.sdcadm.history.updateHistory(history, function (err2) {
if (err) {
return cb(err);
} else if (err2) {
return cb(err2);
} else {
return cb();
}
});
});
};
ExperimentalCLI.prototype.do_add_new_agent_svcs.options = [ {
names: ['help', 'h'],
type: 'bool',
help: 'Show this help.'
}];
ExperimentalCLI.prototype.do_add_new_agent_svcs.help = (
'Temporary grabbag for installing the SDC global zone new agents.\n' +
'The eventual goal is to integrate all of this into "sdcadm update".\n' +
'\n' +
'Usage:\n' +
' {{name}} add-new-agent-svcs\n' +
'\n' +
'{{options}}'
);
/*
* Update platform in datancenter with a given or latest agents installer.
*/
ExperimentalCLI.prototype.do_install_platform =
function do_install_platform(subcmd, opts, args, cb) {
var self = this;
if (opts.help) {
this.do_help('help', {}, [subcmd], cb);
return;
}
if (opts.latest) {
self.sdcadm._installPlatform({
image: 'latest',
progress: self.progress
}, cb);
} else if (args[0]) {
self.sdcadm._installPlatform({
image: args[0],
progress: self.progress
}, cb);
} else {
cb(new errors.UsageError(
'must specify platform image UUID or --latest'));
}
};
ExperimentalCLI.prototype.do_install_platform.help = (
'Download and install platform image for later assignment.\n' +
'\n' +
'Usage:\n' +
' {{name}} install-platform IMAGE-UUID\n' +
' {{name}} install-platform PATH-TO-IMAGE\n' +
' {{name}} install-platform --latest\n' +
'\n' +
'{{options}}'
);
ExperimentalCLI.prototype.do_install_platform.options = [
{
names: ['help', 'h'],
type: 'bool',
help: 'Show this help.'
},
{
names: ['latest'],
type: 'bool',
help: 'Update using the last published platform image.'
}
];
/*
* Assign a platform image to a particular headnode or computenode.
*/
ExperimentalCLI.prototype.do_assign_platform =
function do_assign_platform(subcmd, opts, args, cb) {
var self = this;
if (opts.help) {
this.do_help('help', {}, [subcmd], cb);
return;
}
var platform = args[0];
var server = args[1];
var assignOpts;
if (opts.all && server) {
return cb(new errors.UsageError(
'using --all and explicitly specifying ' +
'a server are mutually exclusive'));
} else if (opts.all) {
assignOpts = {
all: true,
platform: platform,
progress: self.progress
};
} else if (platform && server) {
assignOpts = {
server: server,
platform: platform,
progress: self.progress
};
} else {
return cb(new errors.UsageError(
'must specify platform and server (or --all)'));
}
self.sdcadm._assignPlatform(assignOpts, cb);
};
ExperimentalCLI.prototype.do_assign_platform.help = (
'Assign platform image to SDC servers.\n' +
'\n' +
'Usage:\n' +
' {{name}} assign-platform PLATFORM SERVER\n' +
' {{name}} assign-platform PLATFORM --all\n' +
'\n' +
'{{options}}'
);
ExperimentalCLI.prototype.do_assign_platform.options = [
{
names: ['help', 'h'],
type: 'bool',
help: 'Show this help.'
},
{
names: ['all'],
type: 'bool',
help: 'Assign given platform image to all servers instead of just one.'
}
];
/**
* Update docker0, adding the 'docker' service to the 'sdc' app in SAPI
* if necessary.
*
* Limitations:
* - presumes only a single instance (docker0)
* - presumes docker0 is on the HN
*
* TODO: import other setup ideas from
* https://gist.github.com/joshwilsdon/643e317ac0e2469d8e43
*/
ExperimentalCLI.prototype.do_update_docker =
function do_update_docker(subcmd, opts, args, cb) {
var self = this;
if (opts.help) {
this.do_help('help', {}, [subcmd], cb);
return;
} else if (args.length > 0) {
return cb(new errors.UsageError('too many args: ' + args));
}
var dockerSvcData = {
name: 'docker',
params: {
package_name: 'sdc_768',
image_uuid: 'TO_FILL_IN',
maintain_resolvers: true,
networks: [
{name: 'admin'},
{name: 'external', primary: true}
],
firewall_enabled: false,
tags: {
smartdc_role: 'docker',
smartdc_type: 'core'
},
customer_metadata: {}
// TO_FILL_IN: Fill out package values using sdc_768 package.
},
metadata: {
SERVICE_NAME: 'docker',
SERVICE_DOMAIN: 'TO_FILL_IN',
'user-script': 'TO_FILL_IN'
}
};
vasync.pipeline({arg: {}, funcs: [
/* @field ctx.package */
function getPackage(ctx, next) {
var filter = {name: 'sdc_768'};
self.sdcadm.papi.list(filter, {}, function (err, pkgs) {
if (err) {
return next(err);
} else if (pkgs.length !== 1) {
return next(new errors.InternalError({
message: pkgs.length + ' "sdc_768" packages found'}));
}
ctx.package = pkgs[0];
next();
});
},
function ensureSapiMode(_, next) {
// Bail if SAPI not in 'full' mode.
self.sdcadm.sapi.getMode(function (err, mode) {
if (err) {
next(new errors.SDCClientError(err, 'sapi'));
} else if (mode !== 'full') {
next(new errors.UpdateError(format(
'SAPI is not in "full" mode: mode=%s', mode)));
} else {
next();
}
});
},
function getSdcApp(ctx, next) {
self.sdcadm.sapi.listApplications({name: 'sdc'},
function (appErr, apps) {
if (appErr) {
return next(new errors.SDCClientError(appErr, 'sapi'));
} else if (!apps.length) {
return next(new errors.SDCClientError(new Error(
'No applications named "sdc"'), 'sapi'));
}
ctx.app = apps[0];
next();
});
},
function ensureNoRabbitTrue(ctx, next) {
if (ctx.app.metadata.no_rabbit === true) {
return next();
}
self.progress('Setting "no_rabbit=true" SDC config');
self.progress('Warning: This changes other behaviour in the '
+ 'whole DC to use some new agents');
var update = {
metadata: {
no_rabbit: true
}
};
self.sdcadm.sapi.updateApplication(ctx.app.uuid, update,
errors.sdcClientErrWrap(next, 'sapi'));
},
function getDockerSvc(ctx, next) {
self.sdcadm.sapi.listServices({
name: 'docker',
application_uuid: ctx.app.uuid
}, function (svcErr, svcs) {
if (svcErr) {
return next(svcErr);
} else if (svcs.length) {
ctx.svc = svcs[0];
}
next();
});
},
function getDockerInst(ctx, next) {
if (!ctx.svc) {
return next();
}
var filter = {
service_uuid: ctx.svc.uuid
};
self.sdcadm.sapi.listInstances(filter, function (err, insts) {
if (err) {
return next(new errors.SDCClientError(err, 'sapi'));
} else if (insts && insts.length) {
// Note this doesn't handle multiple insts.
ctx.inst = insts[0];
}
next();
});
},
function getLatestImage(ctx, next) {
var filter = {name: 'docker'};
self.sdcadm.updates.listImages(filter, function (err, images) {
if (err) {
next(err);
} else if (images && images.length) {
ctx.img = images[images.length - 1]; //XXX presuming sorted
} else {
next(new errors.UpdateError('no "docker" image found'));
}
if (!opts.force && ctx.svc &&
ctx.img.uuid === ctx.svc.params.image_uuid) {
ctx.imgNoop = true;
self.progress('Latest Docker image %s (%s %s) matches ' +
'the service (no image update)', ctx.img.uuid,
ctx.img.name, ctx.img.version);
} else {
ctx.imgNoop = false;
}
next();
});
},
function haveImageAlready(ctx, next) {
self.sdcadm.imgapi.getImage(ctx.img.uuid, function (err, img_) {
if (err && err.body && err.body.code === 'ResourceNotFound') {
ctx.haveImg = false;
} else if (err) {
next(err);
} else {
ctx.haveImg = true;
}
next();
});
},
function importImage(ctx, next) {
if (ctx.imgNoop || ctx.haveImg) {
return next();
}
var proc = new DownloadImages({images: [ctx.img]});
proc.execute({
sdcadm: self.sdcadm,
log: self.log,
progress: self.progress
}, next);
},
/* @field ctx.userString */
shared.getUserScript,
function createDockerSvc(ctx, next) {
if (ctx.imgNoop || ctx.svc) {
return next();
}
var domain = ctx.app.metadata.datacenter_name + '.' +
ctx.app.metadata.dns_domain;
var svcDomain = dockerSvcData.name + '.' + domain;
self.progress('Creating "docker" service');
dockerSvcData.params.image_uuid = ctx.img.uuid;
dockerSvcData.metadata['user-script'] = ctx.userScript;
dockerSvcData.metadata['SERVICE_DOMAIN'] = svcDomain;
dockerSvcData.params.cpu_shares = ctx.package.max_physical_memory;
dockerSvcData.params.cpu_cap = ctx.package.cpu_cap;
dockerSvcData.params.zfs_io_priority = ctx.package.zfs_io_priority;
dockerSvcData.params.max_lwps = ctx.package.max_lwps;
dockerSvcData.params.max_physical_memory =
ctx.package.max_physical_memory;
dockerSvcData.params.max_locked_memory =
ctx.package.max_physical_memory;
dockerSvcData.params.max_swap = ctx.package.max_swap;
dockerSvcData.params.quota = (ctx.package.quota / 1024).toFixed(0);
dockerSvcData.params.package_version = ctx.package.version;
dockerSvcData.params.billing_id = ctx.package.uuid;
self.sdcadm.sapi.createService('docker', ctx.app.uuid,
dockerSvcData, function (err, svc_) {
if (err) {
return next(new errors.SDCClientError(err, 'sapi'));
}
svc = svc_;
self.log.info({svc: svc}, 'created docker svc');
next();
});
},
function createDockerInst(ctx, next) {
if (ctx.inst) {
return next();
}
self.progress('Creating "docker" instance');
var instOpts = {
params: {
alias: 'docker0'
}
};
self.sdcadm.sapi.createInstance(ctx.svc.uuid, instOpts,
function (err, inst_) {
if (err) {
return next(new errors.SDCClientError(err, 'sapi'));
}
ctx.inst = inst_;
next();
});
},
function updateSvcImageUuid(ctx, next) {
if (ctx.imgNoop || !ctx.inst) {
return next();
}
self.progress('Update "image_uuid=%s" in "docker" SAPI service',
ctx.img.uuid);
var update = {
params: {
image_uuid: ctx.img.uuid
}
};
self.sdcadm.sapi.updateService(ctx.svc.uuid, update,
errors.sdcClientErrWrap(next, 'sapi'));
},
function reprovisionDockerInst(ctx, next) {
if (ctx.imgNoop || !ctx.inst) {
return next();
}
self.progress('Reprovision "docker" instance %s', ctx.inst.uuid);
self.sdcadm.sapi.reprovisionInstance(ctx.inst.uuid, ctx.img.uuid,
function (err) {
if (err) {
return next(new errors.SDCClientError(err, 'sapi'));
}
next();
});
},
function done(_, next) {
self.progress('Updated SDC Docker');
next();
}
]}, cb);
};
ExperimentalCLI.prototype.do_update_docker.options = [
{
names: ['help', 'h'],
type: 'bool',
help: 'Show this help.'
},
{
names: ['force', 'f'],
type: 'bool',
help: 'Allow update to proceed even if already at latest image.'
}
];
ExperimentalCLI.prototype.do_update_docker.help = (
'Add/update the docker service.\n' +
'\n' +
'Usage:\n' +
' {{name}} update-docker\n' +
'\n' +
'{{options}}'
);
/**
* Update portolan0, adding the 'portolan' service to the 'sdc' app in SAPI
* if necessary.
*
* Limitations:
* - presumes only a single instance (portolan0)
* - presumes portolan0 is on the HN
*/
ExperimentalCLI.prototype.do_portolan =
function portolan(subcmd, opts, args, cb) {
var self = this;
if (opts.help) {
this.do_help('help', {}, [subcmd], cb);
return;
} else if (args.length > 0) {
return cb(new errors.UsageError('too many args: ' + args));
}
var svcData = {
name: 'portolan',
params: {
package_name: 'sdc_768',
image_uuid: 'TO_FILL_IN',
maintain_resolvers: true,
networks: ['admin'],
firewall_enabled: true,
tags: {
smartdc_role: 'portolan',
smartdc_type: 'core'
},
customer_metadata: {}
// TO_FILL_IN: Fill out package values using sdc_768 package.
},
metadata: {
SERVICE_NAME: 'portolan',
SERVICE_DOMAIN: 'TO_FILL_IN',
'user-script': 'TO_FILL_IN'
}
};
var img, haveImg, app, svc, inst, svcExists, instExists, imgNoop;
vasync.pipeline({arg: {}, funcs: [
/* @field ctx.package */
function getPackage(ctx, next) {
var filter = {name: 'sdc_768'};
self.sdcadm.papi.list(filter, {}, function (err, pkgs) {
if (err) {
return next(err);
} else if (pkgs.length !== 1) {
return next(new errors.InternalError({
message: pkgs.length + ' "sdc_768" packages found'}));
}
ctx.package = pkgs[0];
next();
});
},
function getSdcApp(_, next) {
self.sdcadm.sapi.listApplications({name: 'sdc'},
function (appErr, apps) {
if (appErr) {
return next(new errors.SDCClientError(appErr, 'sapi'));
} else if (!apps.length) {
return next(new errors.SDCClientError(new Error(
'No applications named "sdc"'), 'sapi'));
}
app = apps[0];
next();
});
},
function getPortolanSvc(_, next) {
self.sdcadm.sapi.listServices({
name: 'portolan',
application_uuid: app.uuid
}, function (svcErr, svcs) {
if (svcErr) {
return next(svcErr);
} else if (svcs.length) {
svc = svcs[0];
svcExists = true;
} else {
svcExists = false;
}
next();
});
},
function getPortolanInst(_, next) {
if (!svcExists) {
instExists = false;
return next();
}
var filter = {
service_uuid: svc.uuid,
name: 'portolan'
};
self.sdcadm.sapi.listInstances(filter, function (err, insts) {
if (err) {
return next(new errors.SDCClientError(err, 'sapi'));
} else if (insts && insts.length) {
// Note this doesn't handle multiple insts.
inst = insts[0];
instExists = true;
} else {
instExists = false;
}
next();
});
},
function getLatestImage(_, next) {
var filter = {name: 'portolan'};
self.sdcadm.updates.listImages(filter, function (err, images) {
if (err) {
next(err);
} else if (images && images.length) {
img = images[images.length - 1]; //XXX presuming sorted
} else {
next(new errors.UpdateError('no "portolan" image found'));
}
if (!opts.force && svcExists &&
img.uuid === svc.params.image_uuid) {
imgNoop = true;
self.progress('Portolan image %s (%s %s) matches the ' +
'service: nothing to do', img.uuid, img.name,
img.version);
} else {
imgNoop = false;
}
next();
});
},
function haveImageAlready(_, next) {
self.sdcadm.imgapi.getImage(img.uuid, function (err, img_) {
if (err && err.body && err.body.code === 'ResourceNotFound') {
haveImg = false;
} else if (err) {
next(err);
} else {
haveImg = true;
}
next();
});
},
function importImage(_, next) {
if (imgNoop || haveImg) {
return next();
}
var proc = new DownloadImages({images: [img]});
proc.execute({
sdcadm: self.sdcadm,
log: self.log,
progress: self.progress
}, next);
},
/* @field ctx.userScript */
shared.getUserScript,
function createPortolanSvc(ctx, next) {
if (imgNoop || svcExists) {
return next();
}
var domain = app.metadata.datacenter_name + '.' +
app.metadata.dns_domain;
var svcDomain = svcData.name + '.' + domain;
self.progress('Creating "portolan" service');
svcData.params.image_uuid = img.uuid;
svcData.metadata['user-script'] = ctx.userScript;
svcData.metadata['SERVICE_DOMAIN'] = svcDomain;
svcData.params.cpu_shares = ctx.package.max_physical_memory;
svcData.params.cpu_cap = ctx.package.cpu_cap;
svcData.params.zfs_io_priority = ctx.package.zfs_io_priority;
svcData.params.max_lwps = ctx.package.max_lwps;
svcData.params.max_physical_memory =
ctx.package.max_physical_memory;
svcData.params.max_locked_memory = ctx.package.max_physical_memory;
svcData.params.max_swap = ctx.package.max_swap;
svcData.params.quota = (ctx.package.quota / 1024).toFixed(0);
svcData.params.package_version = ctx.package.version;
svcData.params.billing_id = ctx.package.uuid;
self.sdcadm.sapi.createService('portolan', app.uuid, svcData,
function (err, svc_) {
if (err) {
return next(new errors.SDCClientError(err, 'sapi'));
}
svc = svc_;
self.log.info({svc: svc}, 'created portolan svc');
next();
});
},
function createPortolanInst(_, next) {
if (imgNoop || instExists) {
return next();
}
self.progress('Creating "portolan" instance');
var instOpts = {
params: {
alias: 'portolan0'
}
};
self.sdcadm.sapi.createInstance(svc.uuid, instOpts,
function (err, inst_) {
if (err) {
return next(new errors.SDCClientError(err, 'sapi'));
}
inst = inst_;
next();
});
},
function reprovisionPortolanInst(_, next) {
if (imgNoop || !instExists) {
return next();
}
self.progress('Reprovision "portolan" instance %s (%s)',
inst.uuid, inst.alias);
self.sdcadm.sapi.reprovisionInstance(inst.uuid, img.uuid,
function (err) {
if (err) {
return next(new errors.SDCClientError(err, 'sapi'));
}
next();
});
},
function done(_, next) {
if (imgNoop) {
return next();
}
self.progress('Updated portolan');
next();
}
]}, cb);
};
ExperimentalCLI.prototype.do_portolan.options = [
{
names: ['help', 'h'],
type: 'bool',
help: 'Show this help.'
},
{
names: ['force', 'f'],
type: 'bool',
help: 'Allow updates to proceed even if already at latest image.'
}
];
ExperimentalCLI.prototype.do_portolan.help = (
'Add/update the portolan service.\n' +
'\n' +
'Usage:\n' +
' {{name}} portolan\n' +
'\n' +
'{{options}}'
);
//---- exports
module.exports = {
ExperimentalCLI: ExperimentalCLI
};
| HEAD-2202: get 'sdcadm experimental update-docker' to handle the nfs svc and instances
| lib/experimental.js | HEAD-2202: get 'sdcadm experimental update-docker' to handle the nfs svc and instances | <ide><path>ib/experimental.js
<ide>
<ide>
<ide> /**
<del> * Update docker0, adding the 'docker' service to the 'sdc' app in SAPI
<del> * if necessary.
<del> *
<del> * Limitations:
<del> * - presumes only a single instance (docker0)
<del> * - presumes docker0 is on the HN
<add> * Update this SDC docker service setup:
<add> * - update docker0 to latest image, adding the 'docker' service to the 'sdc'
<add> * app in SAPI if necessary. Limitations: Presumes only a single instance
<add> * (docker0). Presumes docker0 is on the HN.
<add> * - nfs service and an instance on every CN (including the HN for now
<add> * because we typically test with HN provisioning).
<ide> *
<ide> * TODO: import other setup ideas from
<ide> * https://gist.github.com/joshwilsdon/643e317ac0e2469d8e43
<ide> smartdc_type: 'core'
<ide> },
<ide> customer_metadata: {}
<del> // TO_FILL_IN: Fill out package values using sdc_768 package.
<add> // TO_FILL_IN: Fill out package values using $package_name package.
<ide> },
<ide> metadata: {
<ide> SERVICE_NAME: 'docker',
<ide> }
<ide> };
<ide>
<del> vasync.pipeline({arg: {}, funcs: [
<del> /* @field ctx.package */
<del> function getPackage(ctx, next) {
<del> var filter = {name: 'sdc_768'};
<add> var nfsSvcData = {
<add> name: 'nfs',
<add> params: {
<add> package_name: 'sdc_4096',
<add> image_uuid: 'TO_FILL_IN',
<add> maintain_resolvers: true,
<add> networks: [
<add> {name: 'admin'},
<add> {name: 'external', primary: true}
<add> ],
<add> filesystems: [
<add> {
<add> source: '/manta',
<add> target: '/manta',
<add> type: 'lofs',
<add> options: [
<add> 'rw',
<add> 'nodevices'
<add> ]
<add> }
<add> ],
<add> firewall_enabled: false,
<add> tags: {
<add> smartdc_role: 'nfs',
<add> smartdc_type: 'core'
<add> },
<add> customer_metadata: {}
<add> // TO_FILL_IN: Fill out package values using $package_name package.
<add> },
<add> metadata: {
<add> SERVICE_NAME: 'nfs',
<add> SERVICE_DOMAIN: 'TO_FILL_IN',
<add> 'user-script': 'TO_FILL_IN'
<add> }
<add> };
<add>
<add> var context = {
<add> imgsToDownload: []
<add> };
<add> vasync.pipeline({arg: context, funcs: [
<add> /* @field ctx.dockerPkg */
<add> function getDockerPkg(ctx, next) {
<add> var filter = {name: dockerSvcData.params.package_name};
<ide> self.sdcadm.papi.list(filter, {}, function (err, pkgs) {
<ide> if (err) {
<ide> return next(err);
<ide> } else if (pkgs.length !== 1) {
<ide> return next(new errors.InternalError({
<del> message: pkgs.length + ' "sdc_768" packages found'}));
<del> }
<del> ctx.package = pkgs[0];
<add> message: format('%d "%s" packages found', pkgs.length,
<add> dockerSvcData.params.package_name)}));
<add> }
<add> ctx.dockerPkg = pkgs[0];
<add> next();
<add> });
<add> },
<add>
<add> /* @field ctx.nfsPkg */
<add> function getNfsPkg(ctx, next) {
<add> var filter = {name: nfsSvcData.params.package_name};
<add> self.sdcadm.papi.list(filter, {}, function (err, pkgs) {
<add> if (err) {
<add> return next(err);
<add> } else if (pkgs.length !== 1) {
<add> return next(new errors.InternalError({
<add> message: format('%d "%s" packages found', pkgs.length,
<add> nfsSvcData.params.package_name)}));
<add> }
<add> ctx.nfsPkg = pkgs[0];
<ide> next();
<ide> });
<ide> },
<ide> if (svcErr) {
<ide> return next(svcErr);
<ide> } else if (svcs.length) {
<del> ctx.svc = svcs[0];
<add> ctx.dockerSvc = svcs[0];
<add> }
<add> next();
<add> });
<add> },
<add>
<add> function getNfsSvc(ctx, next) {
<add> self.sdcadm.sapi.listServices({
<add> name: 'nfs',
<add> application_uuid: ctx.app.uuid
<add> }, function (svcErr, svcs) {
<add> if (svcErr) {
<add> return next(svcErr);
<add> } else if (svcs.length) {
<add> ctx.nfsSvc = svcs[0];
<ide> }
<ide> next();
<ide> });
<ide> },
<ide>
<ide> function getDockerInst(ctx, next) {
<del> if (!ctx.svc) {
<add> if (!ctx.dockerSvc) {
<ide> return next();
<ide> }
<ide> var filter = {
<del> service_uuid: ctx.svc.uuid
<add> service_uuid: ctx.dockerSvc.uuid
<ide> };
<ide> self.sdcadm.sapi.listInstances(filter, function (err, insts) {
<ide> if (err) {
<ide> return next(new errors.SDCClientError(err, 'sapi'));
<ide> } else if (insts && insts.length) {
<ide> // Note this doesn't handle multiple insts.
<del> ctx.inst = insts[0];
<del> }
<del> next();
<del> });
<del> },
<del>
<del> function getLatestImage(ctx, next) {
<add> ctx.dockerInst = insts[0];
<add> }
<add> next();
<add> });
<add> },
<add>
<add> function getNfsInsts(ctx, next) {
<add> if (!ctx.nfsSvc) {
<add> ctx.nfsInsts = [];
<add> return next();
<add> }
<add> var filter = {
<add> service_uuid: ctx.nfsSvc.uuid
<add> };
<add> self.sdcadm.sapi.listInstances(filter, function (err, insts) {
<add> if (err) {
<add> return next(new errors.SDCClientError(err, 'sapi'));
<add> }
<add> ctx.nfsInsts = insts;
<add> next();
<add> });
<add> },
<add>
<add> function getLatestDockerImage(ctx, next) {
<ide> var filter = {name: 'docker'};
<ide> self.sdcadm.updates.listImages(filter, function (err, images) {
<ide> if (err) {
<ide> next(err);
<ide> } else if (images && images.length) {
<del> ctx.img = images[images.length - 1]; //XXX presuming sorted
<add> //XXX presuming sorted
<add> ctx.dockerImg = images[images.length - 1];
<ide> } else {
<ide> next(new errors.UpdateError('no "docker" image found'));
<ide> }
<ide>
<del> if (!opts.force && ctx.svc &&
<del> ctx.img.uuid === ctx.svc.params.image_uuid) {
<del> ctx.imgNoop = true;
<add> if (!opts.force && ctx.dockerSvc && ctx.dockerImg.uuid
<add> === ctx.dockerSvc.params.image_uuid) {
<add> ctx.dockerImgNoop = true;
<ide> self.progress('Latest Docker image %s (%s %s) matches ' +
<del> 'the service (no image update)', ctx.img.uuid,
<del> ctx.img.name, ctx.img.version);
<add> 'the service (no image update)', ctx.dockerImg.uuid,
<add> ctx.dockerImg.name, ctx.dockerImg.version);
<ide> } else {
<del> ctx.imgNoop = false;
<del> }
<del> next();
<del> });
<del> },
<del>
<del> function haveImageAlready(ctx, next) {
<del> self.sdcadm.imgapi.getImage(ctx.img.uuid, function (err, img_) {
<add> ctx.dockerImgNoop = false;
<add> }
<add> next();
<add> });
<add> },
<add>
<add> function getLatestNfsImage(ctx, next) {
<add> var filter = {name: 'nfs'};
<add> self.sdcadm.updates.listImages(filter, function (err, images) {
<add> if (err) {
<add> next(err);
<add> } else if (images && images.length) {
<add> //XXX presuming sorted
<add> ctx.nfsImg = images[images.length - 1];
<add> } else {
<add> next(new errors.UpdateError('no "nfs" image found'));
<add> }
<add>
<add> if (!opts.force && ctx.nfsSvc &&
<add> ctx.nfsImg.uuid === ctx.nfsSvc.params.image_uuid) {
<add> ctx.nfsImgNoop = true;
<add> self.progress('Latest NFS image %s (%s %s) matches ' +
<add> 'the service (no image update)', ctx.nfsImg.uuid,
<add> ctx.nfsImg.name, ctx.nfsImg.version);
<add> } else {
<add> ctx.nfsImgNoop = false;
<add> }
<add> next();
<add> });
<add> },
<add>
<add> function haveDockerImageAlready(ctx, next) {
<add> self.sdcadm.imgapi.getImage(ctx.dockerImg.uuid,
<add> function (err, img_) {
<ide> if (err && err.body && err.body.code === 'ResourceNotFound') {
<del> ctx.haveImg = false;
<add> ctx.imgsToDownload.push(ctx.dockerImg);
<ide> } else if (err) {
<del> next(err);
<del> } else {
<del> ctx.haveImg = true;
<del> }
<del> next();
<del> });
<del> },
<del>
<del> function importImage(ctx, next) {
<del> if (ctx.imgNoop || ctx.haveImg) {
<del> return next();
<del> }
<del> var proc = new DownloadImages({images: [ctx.img]});
<add> return next(err);
<add> }
<add> next();
<add> });
<add> },
<add>
<add> function haveNfsImageAlready(ctx, next) {
<add> self.sdcadm.imgapi.getImage(ctx.nfsImg.uuid, function (err, img_) {
<add> if (err && err.body && err.body.code === 'ResourceNotFound') {
<add> ctx.imgsToDownload.push(ctx.nfsImg);
<add> } else if (err) {
<add> return next(err);
<add> }
<add> next();
<add> });
<add> },
<add>
<add> function importImages(ctx, next) {
<add> if (ctx.imgsToDownload.length === 0) {
<add> return next();
<add> }
<add> var proc = new DownloadImages({images: ctx.imgsToDownload});
<ide> proc.execute({
<ide> sdcadm: self.sdcadm,
<ide> log: self.log,
<ide> shared.getUserScript,
<ide>
<ide> function createDockerSvc(ctx, next) {
<del> if (ctx.imgNoop || ctx.svc) {
<add> if (ctx.dockerSvc) {
<ide> return next();
<ide> }
<ide>
<ide> var svcDomain = dockerSvcData.name + '.' + domain;
<ide>
<ide> self.progress('Creating "docker" service');
<del> dockerSvcData.params.image_uuid = ctx.img.uuid;
<add> dockerSvcData.params.image_uuid = ctx.dockerImg.uuid;
<ide> dockerSvcData.metadata['user-script'] = ctx.userScript;
<ide> dockerSvcData.metadata['SERVICE_DOMAIN'] = svcDomain;
<del> dockerSvcData.params.cpu_shares = ctx.package.max_physical_memory;
<del> dockerSvcData.params.cpu_cap = ctx.package.cpu_cap;
<del> dockerSvcData.params.zfs_io_priority = ctx.package.zfs_io_priority;
<del> dockerSvcData.params.max_lwps = ctx.package.max_lwps;
<add> dockerSvcData.params.cpu_shares = ctx.dockerPkg.max_physical_memory;
<add> dockerSvcData.params.cpu_cap = ctx.dockerPkg.cpu_cap;
<add> dockerSvcData.params.zfs_io_priority
<add> = ctx.dockerPkg.zfs_io_priority;
<add> dockerSvcData.params.max_lwps = ctx.dockerPkg.max_lwps;
<ide> dockerSvcData.params.max_physical_memory =
<del> ctx.package.max_physical_memory;
<del> dockerSvcData.params.max_locked_memory =
<del> ctx.package.max_physical_memory;
<del> dockerSvcData.params.max_swap = ctx.package.max_swap;
<del> dockerSvcData.params.quota = (ctx.package.quota / 1024).toFixed(0);
<del> dockerSvcData.params.package_version = ctx.package.version;
<del> dockerSvcData.params.billing_id = ctx.package.uuid;
<add> dockerSvcData.params.max_locked_memory =
<add> ctx.dockerPkg.max_physical_memory;
<add> dockerSvcData.params.max_swap = ctx.dockerPkg.max_swap;
<add> dockerSvcData.params.quota =
<add> (ctx.dockerPkg.quota / 1024).toFixed(0);
<add> dockerSvcData.params.package_version = ctx.dockerPkg.version;
<add> dockerSvcData.params.billing_id = ctx.dockerPkg.uuid;
<ide>
<ide> self.sdcadm.sapi.createService('docker', ctx.app.uuid,
<del> dockerSvcData, function (err, svc_) {
<add> dockerSvcData, function (err, svc) {
<ide> if (err) {
<ide> return next(new errors.SDCClientError(err, 'sapi'));
<ide> }
<del> svc = svc_;
<add> ctx.dockerSvc = svc;
<ide> self.log.info({svc: svc}, 'created docker svc');
<ide> next();
<ide> });
<ide> },
<ide>
<add> function createNfsSvc(ctx, next) {
<add> if (ctx.nfsSvc) {
<add> return next();
<add> }
<add>
<add> var domain = ctx.app.metadata.datacenter_name + '.' +
<add> ctx.app.metadata.dns_domain;
<add> var svcDomain = nfsSvcData.name + '.' + domain;
<add>
<add> self.progress('Creating "nfs" service');
<add> nfsSvcData.params.image_uuid = ctx.nfsImg.uuid;
<add> nfsSvcData.metadata['user-script'] = ctx.userScript;
<add> nfsSvcData.metadata['SERVICE_DOMAIN'] = svcDomain;
<add> nfsSvcData.params.cpu_shares = ctx.nfsPkg.max_physical_memory;
<add> nfsSvcData.params.cpu_cap = ctx.nfsPkg.cpu_cap;
<add> nfsSvcData.params.zfs_io_priority = ctx.nfsPkg.zfs_io_priority;
<add> nfsSvcData.params.max_lwps = ctx.nfsPkg.max_lwps;
<add> nfsSvcData.params.max_physical_memory =
<add> nfsSvcData.params.max_locked_memory =
<add> ctx.nfsPkg.max_physical_memory;
<add> nfsSvcData.params.max_swap = ctx.nfsPkg.max_swap;
<add> nfsSvcData.params.quota = (ctx.nfsPkg.quota / 1024).toFixed(0);
<add> nfsSvcData.params.package_version = ctx.nfsPkg.version;
<add> nfsSvcData.params.billing_id = ctx.nfsPkg.uuid;
<add>
<add> self.sdcadm.sapi.createService('nfs', ctx.app.uuid,
<add> nfsSvcData, function (err, svc) {
<add> if (err) {
<add> return next(new errors.SDCClientError(err, 'sapi'));
<add> }
<add> ctx.nfsSvc = svc;
<add> self.log.info({svc: svc}, 'created nfs svc');
<add> next();
<add> });
<add> },
<add>
<ide> function createDockerInst(ctx, next) {
<del> if (ctx.inst) {
<add> if (ctx.dockerInst) {
<ide> return next();
<ide> }
<ide> self.progress('Creating "docker" instance');
<ide> alias: 'docker0'
<ide> }
<ide> };
<del> self.sdcadm.sapi.createInstance(ctx.svc.uuid, instOpts,
<del> function (err, inst_) {
<add> self.sdcadm.sapi.createInstance(ctx.dockerSvc.uuid, instOpts,
<add> function (err, inst) {
<ide> if (err) {
<ide> return next(new errors.SDCClientError(err, 'sapi'));
<ide> }
<del> ctx.inst = inst_;
<del> next();
<del> });
<del> },
<del>
<del> function updateSvcImageUuid(ctx, next) {
<del> if (ctx.imgNoop || !ctx.inst) {
<add> self.progress('Created VM %s (%s)', inst.uuid,
<add> inst.params.alias);
<add> next();
<add> });
<add> },
<add>
<add> function getServersNeedingNfs(ctx, next) {
<add> var filter = {
<add> setup: true,
<add> reserved: false
<add> };
<add> self.sdcadm.cnapi.listServers(filter, function (err, servers) {
<add> if (err) {
<add> return next(new errors.SDCClientError(err, 'cnapi'));
<add> }
<add> // Only include running servers.
<add> // We *are* incuding the headnode for now because common dev
<add> // practice includes using the headnode for docker containers.
<add> var nfsServers = servers.filter(
<add> function (s) { return s.status === 'running'; });
<add> var nfsInstFromServer = {};
<add> ctx.nfsInsts.forEach(function (inst) {
<add> nfsInstFromServer[inst.params.server_uuid] = inst;
<add> });
<add> ctx.serversWithNoNfsInst = nfsServers.filter(function (s) {
<add> return nfsInstFromServer[s.uuid] === undefined;
<add> });
<add> self.progress('Found %d setup, not reserved, '
<add> + 'and running server(s) without an "nfs" instance',
<add> ctx.serversWithNoNfsInst.length);
<add> next();
<add> });
<add> },
<add>
<add> function createGzMantaDirOnNfsServers(ctx, next) {
<add> if (ctx.serversWithNoNfsInst.length === 0) {
<add> return next();
<add> }
<add>
<add> self.progress('Creating "/manta" dir in GZ for "nfs" instances '
<add> + 'on %d server(s)', ctx.serversWithNoNfsInst.length);
<add> /**
<add> * Dev Note: I'd like to use the urclient here (as in
<add> * sdcadm.js#checkHealth), but until the
<add> * `process._getActiveHandles()` hack is obviated, I'm not touching
<add> * it.
<add> *
<add> * Dev Note: I'm doing this one at a time to avoid MAX_LINE
<add> * command, and because doing in blocks of 10 servers is a coding
<add> * pain. TODO: improve this.
<add> */
<add> vasync.forEachParallel({
<add> inputs: ctx.serversWithNoNfsInst,
<add> func: function createGzMantaDir(server, nextServer) {
<add> var argv = [
<add> '/opt/smartdc/bin/sdc-oneachnode', '-j',
<add> '-n', server.uuid, 'mkdir -p /manta'
<add> ];
<add> common.execFilePlus({argv: argv, log: self.log},
<add> function (err, stdout, stderr) {
<add> if (err) {
<add> return nextServer(err);
<add> }
<add> try {
<add> var res = JSON.parse(stdout)[0];
<add> } catch (ex) {
<add> return nextServer(ex);
<add> }
<add> if (res.error || res.result.exit_status !== 0) {
<add> nextServer(new errors.UpdateError(
<add> 'error creating GZ /manta dir on server %s: %s',
<add> server.uuid, stdout));
<add> } else {
<add> nextServer();
<add> }
<add> });
<add> }
<add> }, next);
<add> },
<add>
<add> function createNfsInsts(ctx, next) {
<add> if (ctx.serversWithNoNfsInst.length === 0) {
<add> return next();
<add> }
<add>
<add> self.progress('Creating "nfs" instances on %d server(s)',
<add> ctx.serversWithNoNfsInst.length);
<add> ctx.newNfsInsts = [];
<add> vasync.forEachPipeline({
<add> inputs: ctx.serversWithNoNfsInst,
<add> func: function createNfsInst(server, nextServer) {
<add> var instOpts = {
<add> params: {
<add> alias: 'nfs-' + server.hostname,
<add> server_uuid: server.uuid
<add> }
<add> };
<add> self.sdcadm.sapi.createInstance(ctx.nfsSvc.uuid, instOpts,
<add> function (err, inst) {
<add> if (err) {
<add> return next(new errors.SDCClientError(err, 'sapi'));
<add> }
<add> self.progress('Created VM %s (%s)', inst.uuid,
<add> inst.params.alias);
<add> ctx.newNfsInsts.push(inst);
<add> nextServer();
<add> });
<add> }
<add> }, next);
<add> },
<add>
<add> function updateDockerSvcImageUuid(ctx, next) {
<add> if (ctx.dockerImgNoop || !ctx.dockerInst) {
<ide> return next();
<ide> }
<ide> self.progress('Update "image_uuid=%s" in "docker" SAPI service',
<del> ctx.img.uuid);
<add> ctx.dockerImg.uuid);
<ide> var update = {
<ide> params: {
<del> image_uuid: ctx.img.uuid
<add> image_uuid: ctx.dockerImg.uuid
<ide> }
<ide> };
<del> self.sdcadm.sapi.updateService(ctx.svc.uuid, update,
<add> self.sdcadm.sapi.updateService(ctx.dockerSvc.uuid, update,
<ide> errors.sdcClientErrWrap(next, 'sapi'));
<ide> },
<ide>
<add> function updateNfsSvcImageUuid(ctx, next) {
<add> if (ctx.nfsImgNoop || ctx.nfsInsts.length === 0) {
<add> return next();
<add> }
<add> self.progress('Update "image_uuid=%s" in "nfs" SAPI service',
<add> ctx.nfsImg.uuid);
<add> var update = {
<add> params: {
<add> image_uuid: ctx.nfsImg.uuid
<add> }
<add> };
<add> self.sdcadm.sapi.updateService(ctx.nfsSvc.uuid, update,
<add> errors.sdcClientErrWrap(next, 'sapi'));
<add> },
<add>
<ide> function reprovisionDockerInst(ctx, next) {
<del> if (ctx.imgNoop || !ctx.inst) {
<del> return next();
<del> }
<del> self.progress('Reprovision "docker" instance %s', ctx.inst.uuid);
<del> self.sdcadm.sapi.reprovisionInstance(ctx.inst.uuid, ctx.img.uuid,
<del> function (err) {
<add> if (ctx.dockerImgNoop || !ctx.dockerInst) {
<add> return next();
<add> }
<add> self.progress('Reprovision "docker" instance %s',
<add> ctx.dockerInst.uuid);
<add> self.sdcadm.sapi.reprovisionInstance(ctx.dockerInst.uuid,
<add> ctx.dockerImg.uuid, function (err) {
<ide> if (err) {
<ide> return next(new errors.SDCClientError(err, 'sapi'));
<ide> }
<ide> next();
<ide> });
<add> },
<add>
<add> function reprovisionNfsInsts(ctx, next) {
<add> if (ctx.nfsImgNoop) {
<add> return next();
<add> }
<add>
<add> vasync.forEachPipeline({
<add> inputs: ctx.nfsInsts,
<add> func: function reproNfsInst(inst, nextInst) {
<add> // First get its current image from VMAPI to not reprov
<add> // if not necessary.
<add> self.sdcadm.vmapi.getVm({uuid: inst.uuid},
<add> function (vmErr, vm) {
<add> if (vmErr) {
<add> return nextInst(vmErr);
<add> } else if (vm.image_uuid === ctx.nfsImg.uuid) {
<add> return nextInst();
<add> }
<add> self.progress('Reprovision %s (%s) inst to image %s',
<add> inst.uuid, inst.params.alias, ctx.nfsImg.uuid);
<add> self.sdcadm.sapi.reprovisionInstance(ctx.nfsInst.uuid,
<add> ctx.nfsImg.uuid, function (err) {
<add> if (err) {
<add> return nextInst(
<add> new errors.SDCClientError(err, 'sapi'));
<add> }
<add> nextInst();
<add> });
<add> });
<add> }
<add> }, next);
<ide> },
<ide>
<ide> function done(_, next) { |
|
Java | apache-2.0 | 443655c746106a58f708ab3ecfd862c110a810a6 | 0 | edubarr/Ticker | /*
*
* * Copyright (C) 2014 Eduardo Barrenechea
* *
* * 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 ca.barrenechea.ticker.ui;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.ActionMode;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import javax.inject.Inject;
import butterknife.ButterKnife;
import butterknife.InjectView;
import ca.barrenechea.ticker.R;
import ca.barrenechea.ticker.data.Event;
import ca.barrenechea.ticker.data.EventLoader;
import ca.barrenechea.ticker.event.OnEventDelete;
import ca.barrenechea.ticker.event.OnEventEdit;
import ca.barrenechea.ticker.utils.ViewUtils;
import ca.barrenechea.ticker.widget.HistoryAdapter;
import io.realm.RealmQuery;
import io.realm.RealmResults;
import rx.Observer;
import rx.Subscription;
public class EventFragment extends BaseFragment implements Observer<RealmResults<Event>> {
private static final String TAG = "EventFragment";
private static final long DURATION = 175;
private static final String KEY_ID = "Event.Id";
private static final int FLAGS = DateUtils.FORMAT_ABBREV_ALL | DateUtils.FORMAT_SHOW_TIME
| DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR;
private static enum Status {CANCELLED, SUCCESS, FAILURE}
@InjectView(R.id.text_name)
TextView mTextName;
@InjectView(R.id.text_note)
TextView mTextNote;
@InjectView(R.id.text_time)
TextView mTextTime;
@InjectView(R.id.edit_name)
EditText mEditName;
@InjectView(R.id.edit_note)
EditText mEditNote;
@InjectView(R.id.list)
ListView mListView;
@InjectView(R.id.empty)
View mEmptyView;
@Inject
EventLoader mEventLoader;
private String mId;
private boolean mIsDirty = false;
private HistoryAdapter mAdapter;
private Event mEvent;
private Subscription mSubscription;
private ActionMode mActionMode;
private ActionMode.Callback mCallback = new ActionMode.Callback() {
private Status mEditState;
@Override
public boolean onCreateActionMode(ActionMode actionMode, Menu menu) {
if (mActionMode == null) {
mActionMode = actionMode;
mEditState = Status.CANCELLED;
return true;
}
return false;
}
@Override
public boolean onPrepareActionMode(ActionMode actionMode, Menu menu) {
MenuInflater inflater = actionMode.getMenuInflater();
inflater.inflate(R.menu.actionmode_event, menu);
return true;
}
@Override
public boolean onActionItemClicked(ActionMode actionMode, MenuItem menuItem) {
if (menuItem.getItemId() == R.id.action_save) {
if (saveEdit()) {
mEditState = Status.SUCCESS;
} else {
mEditState = Status.FAILURE;
}
actionMode.finish();
transitionViews(false);
return true;
}
return false;
}
@Override
public void onDestroyActionMode(ActionMode actionMode) {
mActionMode = null;
int message = 0;
switch (mEditState) {
case FAILURE:
message = R.string.event_not_saved;
resetForm();
break;
case CANCELLED:
message = R.string.changes_discarded;
resetForm();
break;
case SUCCESS:
message = R.string.event_saved;
break;
}
Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show();
transitionViews(false);
ViewUtils.hideSoftInput(mEditName);
}
};
public static EventFragment newInstance(String id) {
Bundle args = new Bundle();
args.putString(KEY_ID, id);
EventFragment f = new EventFragment();
f.setArguments(args);
return f;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle args = getArguments();
if (args == null) {
throw new IllegalArgumentException("Event id cannot be null!");
}
mId = args.getString(KEY_ID);
this.setHasOptionsMenu(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_event, container, false);
ButterKnife.inject(this, view);
mTextName.setOnClickListener(v -> startEdit(mEditName));
mTextNote.setOnClickListener(v -> startEdit(mEditNote));
mAdapter = new HistoryAdapter(getActivity(), null);
mListView.setAdapter(mAdapter);
mListView.setEmptyView(mEmptyView);
return view;
}
@Override
public void onDestroyView() {
super.onDestroyView();
ButterKnife.reset(this);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.fragment_event, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_delete:
mBus.post(new OnEventDelete(mEvent.getId()));
return true;
case R.id.action_reset:
//TODO: re-enable event reset
// mEvent.reset();
mIsDirty = true;
bindEventData();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onResume() {
super.onResume();
resetSubscription();
registerEvent();
}
private void resetSubscription() {
if (mSubscription != null) {
mSubscription.unsubscribe();
mSubscription = null;
}
}
private void startEdit(View view) {
if (mEvent != null) {
transitionViews(true);
view.requestFocus();
}
}
private void transitionViews(final boolean editing) {
final ObjectAnimator hideName = ObjectAnimator.ofFloat(mTextName, "alpha", editing ? 0 : 1);
final ObjectAnimator hideNote = ObjectAnimator.ofFloat(mTextNote, "alpha", editing ? 0 : 1);
final ObjectAnimator editName = ObjectAnimator.ofFloat(mEditName, "alpha", editing ? 1 : 0);
final ObjectAnimator editNote = ObjectAnimator.ofFloat(mEditNote, "alpha", editing ? 1 : 0);
final AnimatorSet set = new AnimatorSet();
set.playTogether(hideName, hideNote, editName, editNote);
set.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
if (editing) {
mTextName.setVisibility(View.INVISIBLE);
mTextNote.setVisibility(View.INVISIBLE);
getActivity().startActionMode(mCallback);
} else {
mEditName.setVisibility(View.INVISIBLE);
mEditNote.setVisibility(View.INVISIBLE);
}
}
});
if (editing) {
mEditName.setVisibility(View.VISIBLE);
mEditNote.setVisibility(View.VISIBLE);
} else {
mTextName.setVisibility(View.VISIBLE);
mTextNote.setVisibility(View.VISIBLE);
mTextNote.requestFocus();
}
set.setDuration(DURATION);
set.start();
}
private void registerEvent() {
RealmQuery<Event> query = mEventLoader.getQuery().equalTo("id", mId);
mSubscription = mEventLoader.load(query).subscribe(this);
}
@Override
public void onPause() {
super.onPause();
resetSubscription();
if (mIsDirty) {
mBus.post(new OnEventEdit(mEvent.getId()));
mIsDirty = false;
}
}
private boolean saveEdit() {
// we still don't have an id to listen to changes on save
final CharSequence name = mEditName.getText();
final CharSequence note = mEditNote.getText();
if (TextUtils.isEmpty(name)) {
// ABORT! can't save event without a name!
return false;
}
mEvent.setName(name.toString());
mEvent.setNote(note.toString());
mBus.post(new OnEventEdit(mEvent.getId()));
return true;
}
private void resetForm() {
mEditName.setText("");
mEditName.append(mEvent.getName());
final String note = mEvent.getNote();
if (!TextUtils.isEmpty(note)) {
mEditNote.setText("");
mEditNote.append(note);
}
}
@Override
public void onCompleted() {
// do nothing
}
@Override
public void onError(Throwable e) {
Log.e(TAG, "Error loading data!", e);
}
@Override
public void onNext(RealmResults<Event> result) {
if (result != null) {
mEvent = result.first();
bindEventData();
mAdapter.setEvent(mEvent);
}
}
private void bindEventData() {
final String name = mEvent.getName();
mTextName.setText(name);
mEditName.setText("");
mEditName.append(name);
final String note = mEvent.getNote();
if (!TextUtils.isEmpty(note)) {
mTextNote.setText(note);
mEditNote.setText("");
mEditNote.append(note);
}
mTextTime.setText(DateUtils.formatDateTime(getActivity(), mEvent.getStarted(), FLAGS));
mAdapter.notifyDataSetChanged();
}
}
| mobile/src/main/java/ca/barrenechea/ticker/ui/EventFragment.java | /*
*
* * Copyright (C) 2014 Eduardo Barrenechea
* *
* * 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 ca.barrenechea.ticker.ui;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.ActionMode;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import javax.inject.Inject;
import butterknife.ButterKnife;
import butterknife.InjectView;
import ca.barrenechea.ticker.R;
import ca.barrenechea.ticker.data.Event;
import ca.barrenechea.ticker.data.EventLoader;
import ca.barrenechea.ticker.event.OnEventDelete;
import ca.barrenechea.ticker.event.OnEventEdit;
import ca.barrenechea.ticker.widget.HistoryAdapter;
import io.realm.RealmQuery;
import io.realm.RealmResults;
import rx.Observer;
import rx.Subscription;
public class EventFragment extends BaseFragment implements Observer<RealmResults<Event>> {
private static final String TAG = "EventFragment";
private static final long DURATION = 175;
private static final String KEY_ID = "Event.Id";
private static final int FLAGS = DateUtils.FORMAT_ABBREV_ALL | DateUtils.FORMAT_SHOW_TIME
| DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR;
private static enum Status {CANCELLED, SUCCESS, FAILURE}
@InjectView(R.id.text_name)
TextView mTextName;
@InjectView(R.id.text_note)
TextView mTextNote;
@InjectView(R.id.text_time)
TextView mTextTime;
@InjectView(R.id.edit_name)
EditText mEditName;
@InjectView(R.id.edit_note)
EditText mEditNote;
@InjectView(R.id.list)
ListView mListView;
@InjectView(R.id.empty)
View mEmptyView;
@Inject
EventLoader mEventLoader;
private String mId;
private boolean mIsDirty = false;
private HistoryAdapter mAdapter;
private Event mEvent;
private Subscription mSubscription;
private ActionMode mActionMode;
private ActionMode.Callback mCallback = new ActionMode.Callback() {
private Status mEditState;
@Override
public boolean onCreateActionMode(ActionMode actionMode, Menu menu) {
if (mActionMode == null) {
mActionMode = actionMode;
mEditState = Status.CANCELLED;
return true;
}
return false;
}
@Override
public boolean onPrepareActionMode(ActionMode actionMode, Menu menu) {
MenuInflater inflater = actionMode.getMenuInflater();
inflater.inflate(R.menu.actionmode_event, menu);
return true;
}
@Override
public boolean onActionItemClicked(ActionMode actionMode, MenuItem menuItem) {
if (menuItem.getItemId() == R.id.action_save) {
if (saveEdit()) {
mEditState = Status.SUCCESS;
} else {
mEditState = Status.FAILURE;
}
actionMode.finish();
transitionViews(false);
return true;
}
return false;
}
@Override
public void onDestroyActionMode(ActionMode actionMode) {
mActionMode = null;
String message = null;
switch (mEditState) {
case FAILURE:
message = "Invalid changes discarded.";
resetForm();
break;
case CANCELLED:
message = "Edit cancelled.";
resetForm();
break;
case SUCCESS:
message = "Changes saved.";
break;
}
Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show();
transitionViews(false);
}
};
public static EventFragment newInstance(String id) {
Bundle args = new Bundle();
args.putString(KEY_ID, id);
EventFragment f = new EventFragment();
f.setArguments(args);
return f;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle args = getArguments();
if (args == null) {
throw new IllegalArgumentException("Event id cannot be null!");
}
mId = args.getString(KEY_ID);
this.setHasOptionsMenu(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_event, container, false);
ButterKnife.inject(this, view);
mTextName.setOnClickListener(v -> startEdit(mEditName));
mTextNote.setOnClickListener(v -> startEdit(mEditNote));
mAdapter = new HistoryAdapter(getActivity(), null);
mListView.setAdapter(mAdapter);
mListView.setEmptyView(mEmptyView);
return view;
}
@Override
public void onDestroyView() {
super.onDestroyView();
ButterKnife.reset(this);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.fragment_event, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_delete:
mBus.post(new OnEventDelete(mEvent.getId()));
return true;
case R.id.action_reset:
//TODO: re-enable event reset
// mEvent.reset();
mIsDirty = true;
bindEventData();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onResume() {
super.onResume();
resetSubscription();
registerEvent();
}
private void resetSubscription() {
if (mSubscription != null) {
mSubscription.unsubscribe();
mSubscription = null;
}
}
private void startEdit(View view) {
if (mEvent != null) {
transitionViews(true);
view.requestFocus();
}
}
private void transitionViews(final boolean editing) {
final ObjectAnimator hideName = ObjectAnimator.ofFloat(mTextName, "alpha", editing ? 0 : 1);
final ObjectAnimator hideNote = ObjectAnimator.ofFloat(mTextNote, "alpha", editing ? 0 : 1);
final ObjectAnimator editName = ObjectAnimator.ofFloat(mEditName, "alpha", editing ? 1 : 0);
final ObjectAnimator editNote = ObjectAnimator.ofFloat(mEditNote, "alpha", editing ? 1 : 0);
final AnimatorSet set = new AnimatorSet();
set.playTogether(hideName, hideNote, editName, editNote);
set.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
if (editing) {
mTextName.setVisibility(View.INVISIBLE);
mTextNote.setVisibility(View.INVISIBLE);
getActivity().startActionMode(mCallback);
} else {
mEditName.setVisibility(View.INVISIBLE);
mEditNote.setVisibility(View.INVISIBLE);
}
}
});
if (editing) {
mEditName.setVisibility(View.VISIBLE);
mEditNote.setVisibility(View.VISIBLE);
} else {
mTextName.setVisibility(View.VISIBLE);
mTextNote.setVisibility(View.VISIBLE);
mTextNote.requestFocus();
}
set.setDuration(DURATION);
set.start();
}
private void registerEvent() {
RealmQuery<Event> query = mEventLoader.getQuery().equalTo("id", mId);
mSubscription = mEventLoader.load(query).subscribe(this);
}
@Override
public void onPause() {
super.onPause();
resetSubscription();
if (mIsDirty) {
mBus.post(new OnEventEdit(mEvent.getId()));
mIsDirty = false;
}
}
private boolean saveEdit() {
// we still don't have an id to listen to changes on save
final CharSequence name = mEditName.getText();
final CharSequence note = mEditNote.getText();
if (TextUtils.isEmpty(name)) {
// ABORT! can't save event without a name!
return false;
}
mEvent.setName(name.toString());
mEvent.setNote(note.toString());
mBus.post(new OnEventEdit(mEvent.getId()));
return true;
}
private void resetForm() {
mEditName.setText("");
mEditName.append(mEvent.getName());
final String note = mEvent.getNote();
if (!TextUtils.isEmpty(note)) {
mEditNote.setText("");
mEditNote.append(note);
}
}
@Override
public void onCompleted() {
// do nothing
}
@Override
public void onError(Throwable e) {
Log.e(TAG, "Error loading data!", e);
}
@Override
public void onNext(RealmResults<Event> result) {
if (result != null) {
mEvent = result.first();
bindEventData();
mAdapter.setEvent(mEvent);
}
}
private void bindEventData() {
final String name = mEvent.getName();
mTextName.setText(name);
mEditName.setText("");
mEditName.append(name);
final String note = mEvent.getNote();
if (!TextUtils.isEmpty(note)) {
mTextNote.setText(note);
mEditNote.setText("");
mEditNote.append(note);
}
mTextTime.setText(DateUtils.formatDateTime(getActivity(), mEvent.getStarted(), FLAGS));
mAdapter.notifyDataSetChanged();
}
}
| Use new string messages for editing events.
| mobile/src/main/java/ca/barrenechea/ticker/ui/EventFragment.java | Use new string messages for editing events. | <ide><path>obile/src/main/java/ca/barrenechea/ticker/ui/EventFragment.java
<ide> import ca.barrenechea.ticker.data.EventLoader;
<ide> import ca.barrenechea.ticker.event.OnEventDelete;
<ide> import ca.barrenechea.ticker.event.OnEventEdit;
<add>import ca.barrenechea.ticker.utils.ViewUtils;
<ide> import ca.barrenechea.ticker.widget.HistoryAdapter;
<ide> import io.realm.RealmQuery;
<ide> import io.realm.RealmResults;
<ide> public void onDestroyActionMode(ActionMode actionMode) {
<ide> mActionMode = null;
<ide>
<del> String message = null;
<add> int message = 0;
<ide> switch (mEditState) {
<ide> case FAILURE:
<del> message = "Invalid changes discarded.";
<add> message = R.string.event_not_saved;
<ide> resetForm();
<ide> break;
<ide> case CANCELLED:
<del> message = "Edit cancelled.";
<add> message = R.string.changes_discarded;
<ide> resetForm();
<ide> break;
<ide> case SUCCESS:
<del> message = "Changes saved.";
<add> message = R.string.event_saved;
<ide> break;
<ide> }
<ide>
<ide> Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show();
<ide> transitionViews(false);
<add>
<add> ViewUtils.hideSoftInput(mEditName);
<ide> }
<ide> };
<ide> |
|
Java | mit | ab0bb7bd70d213cb2be903ecfb75e6472855de7d | 0 | madumlao/oxTrust,GluuFederation/oxTrust,GluuFederation/oxTrust,GluuFederation/oxTrust,madumlao/oxTrust,GluuFederation/oxTrust,madumlao/oxTrust,GluuFederation/oxTrust,madumlao/oxTrust,madumlao/oxTrust | /*
* oxTrust is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text.
*
* Copyright (c) 2014, Gluu
*/
package org.gluu.oxauth.client.util;
import java.io.File;
import org.apache.commons.lang.StringUtils;
import org.gluu.oxauth.client.OpenIdClient;
import org.gluu.oxauth.client.conf.AppConfiguration;
import org.gluu.oxauth.client.conf.LdapAppConfiguration;
import org.xdi.oxauth.client.OpenIdConfigurationResponse;
import org.xdi.oxauth.model.util.Util;
import org.xdi.util.StringHelper;
import org.xdi.util.properties.FileConfiguration;
/**
* oAuth properties and constants
*
* @author Yuriy Movchan
* @version 0.1, 03/20/2013
*/
public final class Configuration {
/**
* Represents the constant for where the OAuth data will be located in memory
*/
public static final String SESSION_OAUTH_DATA = "_oauth_data_";
/**
* OAuth constants
*/
public static final String OAUTH_CLIENT_ID = "client_id";
public static final String OAUTH_CLIENT_PASSWORD = "client_password";
public static final String OAUTH_CLIENT_CREDENTIALS = "client_credentials";
public static final String OAUTH_REDIRECT_URI = "redirect_uri";
public static final String OAUTH_RESPONSE_TYPE = "response_type";
public static final String OAUTH_SCOPE = "scope";
public static final String OAUTH_STATE = "state";
public static final String OAUTH_CODE = "code";
public static final String OAUTH_ID_TOKEN = "id_token";
public static final String OAUTH_ERROR = "error";
public static final String OAUTH_NONCE = "nonce";
public static final String OAUTH_ERROR_DESCRIPTION = "error_description";
public static final String OAUTH_ACCESS_TOKEN = "access_token";
public static final String OAUTH_AUTH_MODE = "acr_values";
public static final String OAUTH_ID_TOKEN_HINT = "id_token_hint";
public static final String OAUTH_POST_LOGOUT_REDIRECT_URI = "post_logout_redirect_uri";
/**
* OAuth properties
*/
public static final String OAUTH_PROPERTY_AUTHORIZE_URL = "oxauth.authorize.url";
public static final String OAUTH_PROPERTY_TOKEN_URL = "oxauth.token.url";
public static final String OAUTH_PROPERTY_TOKEN_VALIDATION_URL = "oxauth.token.validation.url";
public static final String OAUTH_PROPERTY_USERINFO_URL = "oxauth.userinfo.url";
public static final String OAUTH_PROPERTY_LOGOUT_URL = "oxauth.logout.url";
public static final String OAUTH_PROPERTY_CLIENT_ID = "oxauth.client.id";
public static final String OAUTH_PROPERTY_CLIENT_PASSWORD = "oxauth.client.password";
public static final String OAUTH_PROPERTY_CLIENT_SCOPE = "oxauth.client.scope";
private static class ConfigurationSingleton {
static Configuration INSTANCE = new Configuration();
}
private AppConfiguration appConfiguration;
private OpenIdConfigurationResponse openIdConfiguration;
private Configuration() {
SamlConfiguration samlConfiguration = SamlConfiguration.instance();
this.appConfiguration = samlConfiguration.getAppConfiguration();
OpenIdClient<AppConfiguration, LdapAppConfiguration> openIdClient = new OpenIdClient<AppConfiguration, LdapAppConfiguration>(samlConfiguration);
openIdClient.init();
this.openIdConfiguration = openIdClient.getOpenIdConfiguration();
}
public static Configuration instance() {
return ConfigurationSingleton.INSTANCE;
}
public String getPropertyValue(String propertyName) {
if (StringHelper.equalsIgnoreCase(Configuration.OAUTH_PROPERTY_AUTHORIZE_URL, propertyName)) {
return openIdConfiguration.getAuthorizationEndpoint();
} else if (StringHelper.equalsIgnoreCase(Configuration.OAUTH_PROPERTY_TOKEN_URL, propertyName)) {
return openIdConfiguration.getTokenEndpoint();
} else if (StringHelper.equalsIgnoreCase(Configuration.OAUTH_PROPERTY_TOKEN_VALIDATION_URL, propertyName)) {
return openIdConfiguration.getValidateTokenEndpoint();
} else if (StringHelper.equalsIgnoreCase(Configuration.OAUTH_PROPERTY_USERINFO_URL, propertyName)) {
return openIdConfiguration.getUserInfoEndpoint();
} else if (StringHelper.equalsIgnoreCase(Configuration.OAUTH_PROPERTY_LOGOUT_URL, propertyName)) {
return openIdConfiguration.getEndSessionEndpoint();
} else if (StringHelper.equalsIgnoreCase(Configuration.OAUTH_PROPERTY_CLIENT_ID, propertyName)) {
return appConfiguration.getOpenIdClientId();
} else if (StringHelper.equalsIgnoreCase(Configuration.OAUTH_PROPERTY_CLIENT_PASSWORD, propertyName)) {
return appConfiguration.getOpenIdClientPassword();
} else if (StringHelper.equalsIgnoreCase(Configuration.OAUTH_PROPERTY_CLIENT_SCOPE, propertyName)) {
return Util.listAsString(appConfiguration.getOpenIdScopes());
}
return null;
}
public String getCryptoPropertyValue() {
return SamlConfiguration.instance().getCryptoConfigurationSalt();
}
}
| saml-openid-auth-client/src/main/java/org/gluu/oxauth/client/util/Configuration.java | /*
* oxTrust is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text.
*
* Copyright (c) 2014, Gluu
*/
package org.gluu.oxauth.client.util;
import java.io.File;
import org.apache.commons.lang.StringUtils;
import org.gluu.oxauth.client.OpenIdClient;
import org.gluu.oxauth.client.conf.AppConfiguration;
import org.gluu.oxauth.client.conf.LdapAppConfiguration;
import org.xdi.oxauth.client.OpenIdConfigurationResponse;
import org.xdi.oxauth.model.util.Util;
import org.xdi.util.StringHelper;
import org.xdi.util.properties.FileConfiguration;
/**
* oAuth properties and constants
*
* @author Yuriy Movchan
* @version 0.1, 03/20/2013
*/
public final class Configuration {
/**
* Represents the constant for where the OAuth data will be located in memory
*/
public static final String SESSION_OAUTH_DATA = "_oauth_data_";
/**
* OAuth constants
*/
public static final String OAUTH_CLIENT_ID = "client_id";
public static final String OAUTH_CLIENT_PASSWORD = "client_password";
public static final String OAUTH_CLIENT_CREDENTIALS = "client_credentials";
public static final String OAUTH_REDIRECT_URI = "redirect_uri";
public static final String OAUTH_RESPONSE_TYPE = "response_type";
public static final String OAUTH_SCOPE = "scope";
public static final String OAUTH_STATE = "state";
public static final String OAUTH_CODE = "code";
public static final String OAUTH_ID_TOKEN = "id_token";
public static final String OAUTH_ERROR = "error";
public static final String OAUTH_NONCE = "nonce";
public static final String OAUTH_ERROR_DESCRIPTION = "error_description";
public static final String OAUTH_ACCESS_TOKEN = "access_token";
public static final String OAUTH_AUTH_MODE = "acr_values";
public static final String OAUTH_ID_TOKEN_HINT = "id_token_hint";
public static final String OAUTH_POST_LOGOUT_REDIRECT_URI = "post_logout_redirect_uri";
/**
* OAuth properties
*/
public static final String OAUTH_PROPERTY_AUTHORIZE_URL = "oxauth.authorize.url";
public static final String OAUTH_PROPERTY_TOKEN_URL = "oxauth.token.url";
public static final String OAUTH_PROPERTY_TOKEN_VALIDATION_URL = "oxauth.token.validation.url";
public static final String OAUTH_PROPERTY_USERINFO_URL = "oxauth.userinfo.url";
public static final String OAUTH_PROPERTY_LOGOUT_URL = "oxauth.logout.url";
public static final String OAUTH_PROPERTY_CLIENT_ID = "oxauth.client.id";
public static final String OAUTH_PROPERTY_CLIENT_PASSWORD = "oxauth.client.password";
public static final String OAUTH_PROPERTY_CLIENT_SCOPE = "oxauth.client.scope";
private static class ConfigurationSingleton {
static Configuration INSTANCE = new Configuration();
}
private Configuration() {
}
public static Configuration instance() {
return ConfigurationSingleton.INSTANCE;
}
public String getPropertyValue(String propertyName) {
SamlConfiguration samlConfiguration = SamlConfiguration.instance();
AppConfiguration appConfiguration = samlConfiguration.getAppConfiguration();
OpenIdClient<AppConfiguration, LdapAppConfiguration> openIdClient = new OpenIdClient<AppConfiguration, LdapAppConfiguration>(samlConfiguration);
OpenIdConfigurationResponse openIdConfiguration = openIdClient.getOpenIdConfiguration();
if (StringHelper.equalsIgnoreCase(Configuration.OAUTH_PROPERTY_AUTHORIZE_URL, propertyName)) {
return openIdConfiguration.getAuthorizationEndpoint();
} else if (StringHelper.equalsIgnoreCase(Configuration.OAUTH_PROPERTY_TOKEN_URL, propertyName)) {
return openIdConfiguration.getTokenEndpoint();
} else if (StringHelper.equalsIgnoreCase(Configuration.OAUTH_PROPERTY_TOKEN_VALIDATION_URL, propertyName)) {
return openIdConfiguration.getValidateTokenEndpoint();
} else if (StringHelper.equalsIgnoreCase(Configuration.OAUTH_PROPERTY_USERINFO_URL, propertyName)) {
return openIdConfiguration.getUserInfoEndpoint();
} else if (StringHelper.equalsIgnoreCase(Configuration.OAUTH_PROPERTY_LOGOUT_URL, propertyName)) {
return openIdConfiguration.getEndSessionEndpoint();
} else if (StringHelper.equalsIgnoreCase(Configuration.OAUTH_PROPERTY_CLIENT_ID, propertyName)) {
return appConfiguration.getOpenIdClientId();
} else if (StringHelper.equalsIgnoreCase(Configuration.OAUTH_PROPERTY_CLIENT_PASSWORD, propertyName)) {
return appConfiguration.getOpenIdClientPassword();
} else if (StringHelper.equalsIgnoreCase(Configuration.OAUTH_PROPERTY_CLIENT_SCOPE, propertyName)) {
return Util.listAsString(appConfiguration.getOpenIdScopes());
}
return null;
}
public String getCryptoPropertyValue() {
return SamlConfiguration.instance().getCryptoConfigurationSalt();
}
}
| Fix OpenId client initialization | saml-openid-auth-client/src/main/java/org/gluu/oxauth/client/util/Configuration.java | Fix OpenId client initialization | <ide><path>aml-openid-auth-client/src/main/java/org/gluu/oxauth/client/util/Configuration.java
<ide> static Configuration INSTANCE = new Configuration();
<ide> }
<ide>
<add> private AppConfiguration appConfiguration;
<add>
<add> private OpenIdConfigurationResponse openIdConfiguration;
<add>
<ide> private Configuration() {
<add> SamlConfiguration samlConfiguration = SamlConfiguration.instance();
<add> this.appConfiguration = samlConfiguration.getAppConfiguration();
<add>
<add> OpenIdClient<AppConfiguration, LdapAppConfiguration> openIdClient = new OpenIdClient<AppConfiguration, LdapAppConfiguration>(samlConfiguration);
<add> openIdClient.init();
<add>
<add> this.openIdConfiguration = openIdClient.getOpenIdConfiguration();
<ide> }
<ide>
<ide> public static Configuration instance() {
<ide> }
<ide>
<ide> public String getPropertyValue(String propertyName) {
<del> SamlConfiguration samlConfiguration = SamlConfiguration.instance();
<del> AppConfiguration appConfiguration = samlConfiguration.getAppConfiguration();
<del> OpenIdClient<AppConfiguration, LdapAppConfiguration> openIdClient = new OpenIdClient<AppConfiguration, LdapAppConfiguration>(samlConfiguration);
<del> OpenIdConfigurationResponse openIdConfiguration = openIdClient.getOpenIdConfiguration();
<ide>
<ide> if (StringHelper.equalsIgnoreCase(Configuration.OAUTH_PROPERTY_AUTHORIZE_URL, propertyName)) {
<ide> return openIdConfiguration.getAuthorizationEndpoint(); |
|
Java | mit | 4ba924e02b4f0bbb785eac57ae0312239a908e99 | 0 | gekoil/java.fuel.station | import java.io.IOException;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
public class GasStation extends Thread{
private static final Logger log = Logger.getLogger(GasStation.class.getName());
private final String FILE_HANDLER = GasStation.class.getName() + ".xml";
private CarWash carWash;
private ArrayList<Pump> fuelPumps;
private ArrayDeque<Car> incomingCars;
private Integer fuelReserve;
private int maxFuelCapacity;
private Double profits = 0.0;
private boolean pay = false;
private boolean isWorking;
public GasStation(CarWash carWash, ArrayList<Pump> fuelPumps, int fuelReserve, int fuelCapacity) {
initLog();
this.carWash = carWash;
carWash.setStation(this);
this.fuelPumps = fuelPumps;
this.fuelReserve = fuelReserve;
this.maxFuelCapacity = fuelCapacity;
incomingCars = new ArrayDeque<Car>();
isWorking = true;
}
@Override
public void run() {
log.log(Level.INFO, "The Station is open.");
carWash.start();
while(isWorking || !incomingCars.isEmpty()) {
if(!incomingCars.isEmpty())
organizer(incomingCars.pollFirst());
}
log.log(Level.INFO, "Start a closing procedure.");
try {
carWash.join();
for(Pump p : fuelPumps) {
p.join();
}
} catch (InterruptedException e) {
log.log(Level.WARNING, e.getMessage());
}
}
private void initLog() {
FileHandler handler;
try {
handler = new FileHandler(FILE_HANDLER);
handler.setFormatter(new CustomFormatter());
log.addHandler(handler);
log.setUseParentHandlers(false);
} catch (SecurityException | IOException e) {
e.getMessage();
}
}
private void organizer(Car next) {
if(next.isNeedFuel() && !next.isNeedWash())
fuelPumps.get(next.getPumpNumber()).addCar(next);
else if(next.isNeedWash() && !next.isNeedFuel())
carWash.addCar(next);
else if(next.isNeedFuel() && next.isNeedWash())
if(carWash.getWaitingTime() < fuelPumps.get(next.getPumpNumber()).getWatingTime())
carWash.addCar(next);
else
fuelPumps.get(next.getPumpNumber()).addCar(next);
}
public void payForServise(double money) {
synchronized (profits) {
if(pay)
try {
wait();
} catch (InterruptedException e) {
e.getMessage();
}
pay = true;
profits += money;
notifyAll();
}
}
public CarWash getCarWash() {
return carWash;
}
public ArrayList<Pump> getFuelPumps() { // I don't think its a good design to let someone out side the class
return fuelPumps; // to touch the fuelPumps.
}
public void addFuelPump(Pump fuelPump) {
fuelPumps.add(fuelPump);
}
public void addCar(Car car) throws Exception {
if(isWorking)
incomingCars.addLast(car);
else
throw new Exception("Cant add more cars today.");
}
public boolean isWorking() {
return isWorking;
}
public void setWorking(boolean isWorking) {
this.isWorking = isWorking;
carWash.setEndOfDay();
for(Pump p : fuelPumps)
p.shutDown();
}
public boolean requestFuel(int fuelRequest) throws InterruptedException {
synchronized(fuelReserve) {
while(fuelReserve < maxFuelCapacity * 0.2) {
wait();
}
if (fuelReserve > fuelRequest) { // Do we really need to get into this?
fuelReserve -= fuelRequest;
return true;
} else {
return false;
}
}
}
public void addFuel(int fuelRefill) {
synchronized (fuelReserve) {
fuelReserve += fuelRefill;
}
fuelReserve.notifyAll();
}
}
| GIN/src/GasStation.java | import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
public class GasStation extends Thread{
private static final Logger log = Logger.getLogger(GasStation.class.getName());
private CarWash carWash;
private ArrayList<Pump> fuelPumps;
private ArrayDeque<Car> incomingCars;
private Integer fuelReserve;
private int maxFuelCapacity;
private Double profits = 0.0;
private boolean pay = false;
private boolean isWorking;
public GasStation(CarWash carWash, ArrayList<Pump> fuelPumps, int fuelReserve, int fuelCapacity) {
this.carWash = carWash;
carWash.setStation(this);
this.fuelPumps = fuelPumps;
this.fuelReserve = fuelReserve;
this.maxFuelCapacity = fuelCapacity;
incomingCars = new ArrayDeque<Car>();
isWorking = true;
}
@Override
public void run() {
log.log(Level.INFO, "The Station is open");
carWash.start();
while(isWorking || !incomingCars.isEmpty()) {
if(!incomingCars.isEmpty())
organizer(incomingCars.pollFirst());
}
try {
carWash.join();
for(Pump p : fuelPumps) {
p.join();
}
} catch (InterruptedException e) {
e.getMessage();
}
}
private void organizer(Car next) {
if(next.isNeedFuel() && !next.isNeedWash())
fuelPumps.get(next.getPumpNumber()).addCar(next);
else if(next.isNeedWash() && !next.isNeedFuel())
carWash.addCar(next);
else if(next.isNeedFuel() && next.isNeedWash())
if(carWash.getWaitingTime() < fuelPumps.get(next.getPumpNumber()).getWatingTime())
carWash.addCar(next);
else
fuelPumps.get(next.getPumpNumber()).addCar(next);
}
public void payForServise(double money) {
synchronized (profits) {
if(pay)
try {
wait();
} catch (InterruptedException e) {
e.getMessage();
}
pay = true;
profits += money;
notifyAll();
}
}
public CarWash getCarWash() {
return carWash;
}
public ArrayList<Pump> getFuelPumps() { // I don't think its a good design to let someone out side the class
return fuelPumps; // to touch the fuelPumps.
}
public void addFuelPump(Pump fuelPump) {
fuelPumps.add(fuelPump);
}
public void addCar(Car car) throws Exception {
if(isWorking)
incomingCars.addLast(car);
else
throw new Exception("Cant add more cars today.");
}
public boolean isWorking() {
return isWorking;
}
public void setWorking(boolean isWorking) {
this.isWorking = isWorking;
carWash.setEndOfDay();
for(Pump p : fuelPumps)
p.shutDown();
}
public boolean requestFuel(int fuelRequest) throws InterruptedException {
synchronized(fuelReserve) {
while(fuelReserve < maxFuelCapacity * 0.2) {
wait();
}
if (fuelReserve > fuelRequest) { // Do we really need to get into this?
fuelReserve -= fuelRequest;
return true;
} else {
return false;
}
}
}
public void addFuel(int fuelRefill) {
synchronized (fuelReserve) {
fuelReserve += fuelRefill;
}
fuelReserve.notifyAll();
}
}
| I added Handler. | GIN/src/GasStation.java | I added Handler. | <ide><path>IN/src/GasStation.java
<add>import java.io.IOException;
<ide> import java.util.ArrayDeque;
<ide> import java.util.ArrayList;
<add>import java.util.logging.FileHandler;
<ide> import java.util.logging.Level;
<ide> import java.util.logging.Logger;
<ide>
<ide> public class GasStation extends Thread{
<ide> private static final Logger log = Logger.getLogger(GasStation.class.getName());
<add> private final String FILE_HANDLER = GasStation.class.getName() + ".xml";
<ide>
<ide> private CarWash carWash;
<ide> private ArrayList<Pump> fuelPumps;
<ide> private boolean isWorking;
<ide>
<ide> public GasStation(CarWash carWash, ArrayList<Pump> fuelPumps, int fuelReserve, int fuelCapacity) {
<add> initLog();
<ide> this.carWash = carWash;
<ide> carWash.setStation(this);
<ide> this.fuelPumps = fuelPumps;
<ide>
<ide> @Override
<ide> public void run() {
<del> log.log(Level.INFO, "The Station is open");
<add> log.log(Level.INFO, "The Station is open.");
<ide> carWash.start();
<ide> while(isWorking || !incomingCars.isEmpty()) {
<ide> if(!incomingCars.isEmpty())
<ide> organizer(incomingCars.pollFirst());
<ide> }
<add> log.log(Level.INFO, "Start a closing procedure.");
<ide> try {
<ide> carWash.join();
<ide> for(Pump p : fuelPumps) {
<ide> p.join();
<ide> }
<ide> } catch (InterruptedException e) {
<add> log.log(Level.WARNING, e.getMessage());
<add> }
<add> }
<add>
<add> private void initLog() {
<add> FileHandler handler;
<add> try {
<add> handler = new FileHandler(FILE_HANDLER);
<add> handler.setFormatter(new CustomFormatter());
<add> log.addHandler(handler);
<add> log.setUseParentHandlers(false);
<add> } catch (SecurityException | IOException e) {
<ide> e.getMessage();
<ide> }
<ide> } |
|
Java | apache-2.0 | 5dc5ca4517a0c4c07daebe5b694c8cf563b64dbc | 0 | passion1014/metaworks_framework,gengzhengtao/BroadleafCommerce,TouK/BroadleafCommerce,zhaorui1/BroadleafCommerce,arshadalisoomro/BroadleafCommerce,cengizhanozcan/BroadleafCommerce,caosg/BroadleafCommerce,TouK/BroadleafCommerce,zhaorui1/BroadleafCommerce,cengizhanozcan/BroadleafCommerce,udayinfy/BroadleafCommerce,trombka/blc-tmp,lgscofield/BroadleafCommerce,bijukunjummen/BroadleafCommerce,liqianggao/BroadleafCommerce,passion1014/metaworks_framework,bijukunjummen/BroadleafCommerce,rawbenny/BroadleafCommerce,sanlingdd/broadleaf,sitexa/BroadleafCommerce,cengizhanozcan/BroadleafCommerce,trombka/blc-tmp,cloudbearings/BroadleafCommerce,daniellavoie/BroadleafCommerce,macielbombonato/BroadleafCommerce,SerPenTeHoK/BroadleafCommerce,caosg/BroadleafCommerce,trombka/blc-tmp,rawbenny/BroadleafCommerce,udayinfy/BroadleafCommerce,arshadalisoomro/BroadleafCommerce,shopizer/BroadleafCommerce,cogitoboy/BroadleafCommerce,shopizer/BroadleafCommerce,TouK/BroadleafCommerce,bijukunjummen/BroadleafCommerce,liqianggao/BroadleafCommerce,sanlingdd/broadleaf,lgscofield/BroadleafCommerce,shopizer/BroadleafCommerce,SerPenTeHoK/BroadleafCommerce,cogitoboy/BroadleafCommerce,gengzhengtao/BroadleafCommerce,ljshj/BroadleafCommerce,cloudbearings/BroadleafCommerce,daniellavoie/BroadleafCommerce,ljshj/BroadleafCommerce,passion1014/metaworks_framework,wenmangbo/BroadleafCommerce,zhaorui1/BroadleafCommerce,cogitoboy/BroadleafCommerce,jiman94/BroadleafCommerce-BroadleafCommerce2014,ljshj/BroadleafCommerce,lgscofield/BroadleafCommerce,alextiannus/BroadleafCommerce,macielbombonato/BroadleafCommerce,SerPenTeHoK/BroadleafCommerce,cloudbearings/BroadleafCommerce,daniellavoie/BroadleafCommerce,arshadalisoomro/BroadleafCommerce,alextiannus/BroadleafCommerce,rawbenny/BroadleafCommerce,liqianggao/BroadleafCommerce,wenmangbo/BroadleafCommerce,jiman94/BroadleafCommerce-BroadleafCommerce2014,gengzhengtao/BroadleafCommerce,udayinfy/BroadleafCommerce,sitexa/BroadleafCommerce,sitexa/BroadleafCommerce,wenmangbo/BroadleafCommerce,caosg/BroadleafCommerce,alextiannus/BroadleafCommerce,macielbombonato/BroadleafCommerce | /*
* Copyright 2008-2013 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.broadleafcommerce.common.extension;
import org.apache.commons.beanutils.BeanComparator;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* The ExtensionManager pattern is intended for out of box components to be extended by Broadleaf modules.
*
* Each component that needs an extension should define an interface which is a descendant of ExtensionHandler.
* The concrete ExtensionManager class will utilize that interface as a parameter (e.g. T below).
*
* The default extension manager pattern loops through all handlers and examines their {@link ExtensionResultStatusType}
* to determine whether or not to continue with other handlers.
*
* @author bpolster
*
* @param <T>
*/
public abstract class ExtensionManager<T extends ExtensionHandler> implements InvocationHandler {
protected boolean handlersSorted = false;
protected static String LOCK_OBJECT = new String("EM_LOCK");
protected T extensionHandler;
protected List<T> handlers = new ArrayList<T>();
/**
* Should take in a className that matches the ExtensionHandler interface being managed.
* @param className
*/
@SuppressWarnings("unchecked")
public ExtensionManager(Class<T> _clazz) {
extensionHandler = (T) Proxy.newProxyInstance(_clazz.getClassLoader(),
new Class[] { _clazz },
this);
}
public T getProxy() {
return extensionHandler;
}
/**
* If you are attempting to register a handler with this manager and are invoking this outside of an {@link ExtensionManager}
* subclass, consider using {@link #registerHandler(ExtensionHandler)} instead.
*
* While the sorting of the handlers prior to their return is thread safe, adding directly to this list is not.
*
* @return a list of handlers sorted by their priority
* @see {@link #registerHandler(ExtensionHandler)}
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public List<T> getHandlers() {
synchronized (LOCK_OBJECT) {
if (!handlersSorted) {
if (!handlersSorted) {
Comparator fieldCompare = new BeanComparator("priority");
Collections.sort(handlers, fieldCompare);
handlersSorted = true;
}
}
return handlers;
}
}
/**
* Intended to be invoked from the extension handlers themselves. This will add the given handler to this manager's list of
* handlers. This also checks to ensure that the handler has not been already registered with this {@link ExtensionManager}
* by checking the class names of the already-added handlers.
*
* This method is thread safe.
*
* @param handler the handler to register with this extension manager
* @return true if the handler was successfully registered, false if this handler was already contained in the list of
* handlers for this manager
*/
public boolean registerHandler(T handler) {
synchronized (LOCK_OBJECT) {
boolean add = true;
for (T item : this.handlers) {
if (item.getClass().equals(handler.getClass())) {
add = false;
}
}
if (add) {
this.handlers.add(handler);
handlersSorted = false;
}
return add;
}
}
public void setHandlers(List<T> handlers) {
this.handlers = handlers;
}
/**
* Utility method that is useful for determining whether or not an ExtensionManager implementation
* should continue after processing a ExtensionHandler call.
*
* By default, returns true for CONTINUE
*
* @return
*/
public boolean shouldContinue(ExtensionResultStatusType result, ExtensionHandler handler,
Method method, Object[] args) {
if (result != null) {
if (ExtensionResultStatusType.HANDLED_STOP.equals(result)) {
return false;
}
if (ExtensionResultStatusType.HANDLED.equals(result) && ! continueOnHandled()) {
return false;
}
}
return true;
}
/**
* Returns whether or not this extension manager continues on {@link ExtensionResultStatusType}.HANDLED.
*
* @return
*/
public boolean continueOnHandled() {
return false;
}
/**
* {@link ExtensionManager}s don't really need a priority but they pick up this property due to the
* fact that we want them to implement the same interface <T> as the handlers they are managing.
*
* @return
*/
public int getPriority() {
throw new UnsupportedOperationException();
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
boolean notHandled = true;
for (ExtensionHandler handler : getHandlers()) {
ExtensionResultStatusType result = (ExtensionResultStatusType) method.invoke(handler, args);
if (!ExtensionResultStatusType.NOT_HANDLED.equals(result)) {
notHandled = false;
}
if (!shouldContinue(result, handler, method, args)) {
break;
}
}
if (notHandled) {
return ExtensionResultStatusType.NOT_HANDLED;
}
return null;
}
}
| common/src/main/java/org/broadleafcommerce/common/extension/ExtensionManager.java | /*
* Copyright 2008-2013 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.broadleafcommerce.common.extension;
import org.apache.commons.beanutils.BeanComparator;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* The ExtensionManager pattern is intended for out of box components to be extended by Broadleaf modules.
*
* Each component that needs an extension should define an interface which is a descendant of ExtensionHandler.
* The concrete ExtensionManager class will utilize that interface as a parameter (e.g. T below).
*
* The default extension manager pattern loops through all handlers and examines their {@link ExtensionResultStatusType}
* to determine whether or not to continue with other handlers.
*
* @author bpolster
*
* @param <T>
*/
public abstract class ExtensionManager<T extends ExtensionHandler> implements InvocationHandler {
protected boolean handlersSorted = false;
protected static String LOCK_OBJECT = new String("EM_LOCK");
protected T extensionHandler;
protected List<T> handlers = new ArrayList<T>();
/**
* Should take in a className that matches the ExtensionHandler interface being managed.
* @param className
*/
@SuppressWarnings("unchecked")
public ExtensionManager(Class<T> _clazz) {
extensionHandler = (T) Proxy.newProxyInstance(_clazz.getClassLoader(),
new Class[] { _clazz },
this);
}
public T getProxy() {
return extensionHandler;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public List<T> getHandlers() {
if (!handlersSorted) {
synchronized (LOCK_OBJECT) {
if (!handlersSorted) {
Comparator fieldCompare = new BeanComparator("priority");
Collections.sort(handlers, fieldCompare);
handlersSorted = true;
}
}
}
return handlers;
}
public void setHandlers(List<T> handlers) {
this.handlers = handlers;
}
/**
* Utility method that is useful for determining whether or not an ExtensionManager implementation
* should continue after processing a ExtensionHandler call.
*
* By default, returns true for CONTINUE
*
* @return
*/
public boolean shouldContinue(ExtensionResultStatusType result, ExtensionHandler handler,
Method method, Object[] args) {
if (result != null) {
if (ExtensionResultStatusType.HANDLED_STOP.equals(result)) {
return false;
}
if (ExtensionResultStatusType.HANDLED.equals(result) && ! continueOnHandled()) {
return false;
}
}
return true;
}
/**
* Returns whether or not this extension manager continues on {@link ExtensionResultStatusType}.HANDLED.
*
* @return
*/
public boolean continueOnHandled() {
return false;
}
/**
* {@link ExtensionManager}s don't really need a priority but they pick up this property due to the
* fact that we want them to implement the same interface <T> as the handlers they are managing.
*
* @return
*/
public int getPriority() {
throw new UnsupportedOperationException();
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
boolean notHandled = true;
for (ExtensionHandler handler : getHandlers()) {
ExtensionResultStatusType result = (ExtensionResultStatusType) method.invoke(handler, args);
if (!ExtensionResultStatusType.NOT_HANDLED.equals(result)) {
notHandled = false;
}
if (!shouldContinue(result, handler, method, args)) {
break;
}
}
if (notHandled) {
return ExtensionResultStatusType.NOT_HANDLED;
}
return null;
}
}
| #384 - Make the extension handler registration with an extension manager more explicit
| common/src/main/java/org/broadleafcommerce/common/extension/ExtensionManager.java | #384 - Make the extension handler registration with an extension manager more explicit | <ide><path>ommon/src/main/java/org/broadleafcommerce/common/extension/ExtensionManager.java
<ide> return extensionHandler;
<ide> }
<ide>
<add> /**
<add> * If you are attempting to register a handler with this manager and are invoking this outside of an {@link ExtensionManager}
<add> * subclass, consider using {@link #registerHandler(ExtensionHandler)} instead.
<add> *
<add> * While the sorting of the handlers prior to their return is thread safe, adding directly to this list is not.
<add> *
<add> * @return a list of handlers sorted by their priority
<add> * @see {@link #registerHandler(ExtensionHandler)}
<add> */
<ide> @SuppressWarnings({ "unchecked", "rawtypes" })
<ide> public List<T> getHandlers() {
<del> if (!handlersSorted) {
<del> synchronized (LOCK_OBJECT) {
<add> synchronized (LOCK_OBJECT) {
<add> if (!handlersSorted) {
<ide> if (!handlersSorted) {
<ide> Comparator fieldCompare = new BeanComparator("priority");
<ide> Collections.sort(handlers, fieldCompare);
<ide> handlersSorted = true;
<ide> }
<ide> }
<add> return handlers;
<ide> }
<del> return handlers;
<add> }
<add>
<add> /**
<add> * Intended to be invoked from the extension handlers themselves. This will add the given handler to this manager's list of
<add> * handlers. This also checks to ensure that the handler has not been already registered with this {@link ExtensionManager}
<add> * by checking the class names of the already-added handlers.
<add> *
<add> * This method is thread safe.
<add> *
<add> * @param handler the handler to register with this extension manager
<add> * @return true if the handler was successfully registered, false if this handler was already contained in the list of
<add> * handlers for this manager
<add> */
<add> public boolean registerHandler(T handler) {
<add> synchronized (LOCK_OBJECT) {
<add> boolean add = true;
<add> for (T item : this.handlers) {
<add> if (item.getClass().equals(handler.getClass())) {
<add> add = false;
<add> }
<add> }
<add> if (add) {
<add> this.handlers.add(handler);
<add> handlersSorted = false;
<add> }
<add>
<add> return add;
<add> }
<ide> }
<ide>
<ide> public void setHandlers(List<T> handlers) { |
|
Java | apache-2.0 | ba15e7b29ea5b1874b4a0c79648f210c725633d5 | 0 | andy2palantir/atlasdb,andy2palantir/atlasdb,palantir/atlasdb,palantir/atlasdb,EvilMcJerkface/atlasdb,EvilMcJerkface/atlasdb,palantir/atlasdb,EvilMcJerkface/atlasdb | /**
* Copyright 2015 Palantir Technologies
*
* Licensed under the BSD-3 License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://opensource.org/licenses/BSD-3-Clause
*
* 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.palantir.atlasdb.keyvalue.cassandra;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import org.apache.cassandra.thrift.Cassandra;
import org.apache.cassandra.thrift.Cassandra.Client;
import org.apache.cassandra.thrift.CfDef;
import org.apache.cassandra.thrift.InvalidRequestException;
import org.apache.cassandra.thrift.KsDef;
import org.apache.cassandra.thrift.NotFoundException;
import org.apache.cassandra.thrift.SchemaDisagreementException;
import org.apache.cassandra.thrift.TimedOutException;
import org.apache.cassandra.thrift.TokenRange;
import org.apache.cassandra.thrift.UnavailableException;
import org.apache.thrift.TException;
import org.apache.thrift.transport.TTransportException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Function;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableRangeMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import com.google.common.collect.Range;
import com.google.common.collect.RangeMap;
import com.google.common.collect.Sets;
import com.google.common.collect.Sets.SetView;
import com.google.common.io.BaseEncoding;
import com.google.common.primitives.UnsignedBytes;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.palantir.atlasdb.cassandra.CassandraKeyValueServiceConfig;
import com.palantir.atlasdb.keyvalue.api.InsufficientConsistencyException;
import com.palantir.atlasdb.keyvalue.api.TableReference;
import com.palantir.atlasdb.keyvalue.cassandra.CassandraClientFactory.ClientCreationFailedException;
import com.palantir.common.base.FunctionCheckedException;
import com.palantir.common.concurrent.PTExecutors;
/**
* Feature breakdown:
* - Pooling
* - Token Aware Mapping / Query Routing / Data partitioning
* - Retriable Queries
* - Pool member error tracking / blacklisting*
* - Pool refreshing
* - Pool node autodiscovery
* - Pool member health checking*
*
* *entirely new features
*
* By our old system, this would be a RefreshingRetriableTokenAwareHealthCheckingManyHostCassandraClientPoolingContainerManager;
* ... this is one of the reasons why there is a new system.
**/
public class CassandraClientPool {
private static final Logger log = LoggerFactory.getLogger(CassandraClientPool.class);
private static final int MAX_TRIES = 3;
volatile RangeMap<LightweightOPPToken, List<InetSocketAddress>> tokenMap = ImmutableRangeMap.of();
Map<InetSocketAddress, Long> blacklistedHosts = Maps.newConcurrentMap();
Map<InetSocketAddress, CassandraClientPoolingContainer> currentPools = Maps.newConcurrentMap();
final CassandraKeyValueServiceConfig config;
final ScheduledThreadPoolExecutor refreshDaemon;
public static class LightweightOPPToken implements Comparable<LightweightOPPToken> {
final byte[] bytes;
public LightweightOPPToken(byte[] bytes) {
this.bytes = bytes;
}
@Override
public int compareTo(LightweightOPPToken other) {
return UnsignedBytes.lexicographicalComparator().compare(this.bytes, other.bytes);
}
}
public CassandraClientPool(CassandraKeyValueServiceConfig config) {
this.config = config;
refreshDaemon = PTExecutors.newScheduledThreadPool(1, new ThreadFactoryBuilder().setDaemon(true).setNameFormat("CassandraClientPoolRefresh-%d").build());
refreshDaemon.scheduleWithFixedDelay(new Runnable() {
@Override
public void run() {
try {
refreshPool();
} catch (Throwable t) {
log.error("Failed to refresh Cassandra KVS pool. Extended periods of being unable to refresh will cause perf degradation.", t);
}
}
}, config.poolRefreshIntervalSeconds(), config.poolRefreshIntervalSeconds(), TimeUnit.SECONDS);
config.servers().forEach((server) -> currentPools.put(server, new CassandraClientPoolingContainer(server, config)));
refreshPool(); // ensure we've initialized before returning
}
public void shutdown() {
refreshDaemon.shutdown();
currentPools.forEach((address, cassandraClientPoolingContainer) -> cassandraClientPoolingContainer.shutdownPooling());
}
private synchronized void refreshPool() {
checkAndUpdateBlacklist();
Set<InetSocketAddress> serversToAdd = Sets.newHashSet(config.servers());
Set<InetSocketAddress> serversToRemove = ImmutableSet.of();
if (config.autoRefreshNodes()) {
refreshTokenRanges(); // re-use token mapping as list of hosts in the cluster
for (List<InetSocketAddress> rangeOwners : tokenMap.asMapOfRanges().values()) {
for (InetSocketAddress address : rangeOwners) {
serversToAdd.add(address);
}
}
}
serversToAdd = Sets.difference(Sets.difference(serversToAdd, currentPools.keySet()), blacklistedHosts.keySet());
if (!config.autoRefreshNodes()) { // (we would just add them back in)
serversToRemove = Sets.difference(currentPools.keySet(), config.servers());
}
for (InetSocketAddress newServer : serversToAdd) {
currentPools.put(newServer, new CassandraClientPoolingContainer(newServer, config));
}
if (!(serversToAdd.isEmpty() && serversToRemove.isEmpty())) { // if we made any changes
sanityCheckRingConsistency();
if (!config.autoRefreshNodes()) { // grab new token mapping, if we didn't already do this before
refreshTokenRanges();
}
}
log.debug("Cassandra pool refresh added hosts {}, removed hosts {}.", serversToAdd, serversToRemove);
debugLogStateOfPool();
}
private void debugLogStateOfPool() {
if (log.isDebugEnabled()) {
StringBuilder currentState = new StringBuilder();
currentState.append(
String.format("POOL STATUS: Current blacklist = %s,%n current hosts in pool = %s%n",
blacklistedHosts.keySet().toString(), currentPools.keySet().toString()));
for (Entry<InetSocketAddress, CassandraClientPoolingContainer> entry : currentPools.entrySet()) {
int activeCheckouts = entry.getValue().getPoolUtilization();
int totalAllowed = entry.getValue().getPoolSize();
currentState.append(
String.format("\tPOOL STATUS: Pooled host %s has %s out of %s connections checked out.%n",
entry.getKey(),
activeCheckouts > 0? Integer.toString(activeCheckouts) : "(unknown)",
totalAllowed > 0? Integer.toString(totalAllowed) : "(not bounded)"));
}
log.debug(currentState.toString());
}
}
private void checkAndUpdateBlacklist() {
// Check blacklist and re-integrate or continue to wait as necessary
for (Map.Entry<InetSocketAddress, Long> blacklistedEntry : blacklistedHosts.entrySet()) {
long backoffTimeMillis = TimeUnit.SECONDS.toMillis(config.unresponsiveHostBackoffTimeSeconds());
if (blacklistedEntry.getValue() + backoffTimeMillis < System.currentTimeMillis()) {
InetSocketAddress host = blacklistedEntry.getKey();
if (isHostHealthy(host)) {
blacklistedHosts.remove(host);
log.error("Added host {} back into the pool after a waiting period and successful health check.", host);
}
}
}
}
private void addToBlacklist(InetSocketAddress badHost) {
blacklistedHosts.put(badHost, System.currentTimeMillis());
}
private boolean isHostHealthy(InetSocketAddress host) {
try {
CassandraClientPoolingContainer testingContainer = new CassandraClientPoolingContainer(host, config);
testingContainer.runWithPooledResource(describeRing);
testingContainer.runWithPooledResource(validatePartitioner);
} catch (Exception e) {
log.error("We tried to add {} back into the pool, but got an exception that caused to us distrust this host further.", host, e);
return false;
}
return true;
}
private CassandraClientPoolingContainer getRandomGoodHost() {
Map<InetSocketAddress, CassandraClientPoolingContainer> pools = currentPools;
Set<InetSocketAddress> livingHosts = Sets.difference(pools.keySet(), blacklistedHosts.keySet());
if (livingHosts.isEmpty()) {
log.error("There are no known live hosts in the connection pool. We're choosing one at random in a last-ditch attempt at forward progress.");
livingHosts = pools.keySet();
}
return pools.get(ImmutableList.copyOf(livingHosts).get(ThreadLocalRandom.current().nextInt(livingHosts.size())));
}
public InetSocketAddress getRandomHostForKey(byte[] key) {
List<InetSocketAddress> hostsForKey = tokenMap.get(new LightweightOPPToken(key));
SetView<InetSocketAddress> liveOwnerHosts;
if (hostsForKey == null) {
log.warn("Cluster not fully initialized, not routing query to correct host as not token map found.");
return getRandomGoodHost().getHost();
} else {
liveOwnerHosts = Sets.difference(ImmutableSet.copyOf(hostsForKey), blacklistedHosts.keySet());
}
if (liveOwnerHosts.isEmpty()) {
log.warn("Perf / cluster stability issue. Token aware query routing has failed because there are no known " +
"live hosts that claim ownership of the given range. Falling back to choosing a random live node. " +
"For debugging, our current ring view is: {} and our current host blacklist is {}", tokenMap, blacklistedHosts);
return getRandomGoodHost().getHost();
} else {
return currentPools.get(ImmutableList.copyOf(liveOwnerHosts).get(ThreadLocalRandom.current().nextInt(liveOwnerHosts.size()))).getHost();
}
}
public void runOneTimeStartupChecks() {
try {
CassandraVerifier.ensureKeyspaceExistsAndIsUpToDate(this, config);
} catch (Exception e) {
log.error("Startup checks failed, was not able to create the keyspace or ensure it already existed.");
throw new RuntimeException(e);
}
Map<InetSocketAddress, Exception> completelyUnresponsiveHosts = Maps.newHashMap(), aliveButInvalidPartitionerHosts = Maps.newHashMap();
boolean thisHostResponded, atLeastOneHostResponded = false, atLeastOneHostSaidWeHaveAMetadataTable = false;
for (InetSocketAddress liveHost : Sets.difference(currentPools.keySet(), blacklistedHosts.keySet())) {
thisHostResponded = false;
try {
runOnHost(liveHost, CassandraVerifier.healthCheck);
thisHostResponded = true;
atLeastOneHostResponded = true;
} catch (Exception e) {
completelyUnresponsiveHosts.put(liveHost, e);
addToBlacklist(liveHost);
}
if (thisHostResponded) {
try {
runOnHost(liveHost, validatePartitioner);
} catch (Exception e) {
aliveButInvalidPartitionerHosts.put(liveHost, e);
}
try {
runOnHost(liveHost, createInternalMetadataTable);
atLeastOneHostSaidWeHaveAMetadataTable = true;
} catch (Exception e) {
// don't fail here, want to give the user all the errors at once at the end
}
}
}
StringBuilder errorBuilderForEntireCluster = new StringBuilder();
if (completelyUnresponsiveHosts.size() > 0) {
errorBuilderForEntireCluster.append("Performing routine startup checks, determined that the following hosts are unreachable for the following reasons: \n");
completelyUnresponsiveHosts.forEach((host, exception) ->
errorBuilderForEntireCluster.append(String.format("\tHost: %s was marked unreachable via exception: %s%n", host.toString(), exception.toString())));
}
if (aliveButInvalidPartitionerHosts.size() > 0) {
errorBuilderForEntireCluster.append("Performing routine startup checks, determined that the following hosts were alive but are configured with an invalid partitioner: \n");
aliveButInvalidPartitionerHosts.forEach((host, exception) ->
errorBuilderForEntireCluster.append(String.format("\tHost: %s was marked as invalid partitioner via exception: %s%n", host.toString(), exception.toString())));
}
if (atLeastOneHostResponded && atLeastOneHostSaidWeHaveAMetadataTable && aliveButInvalidPartitionerHosts.size() == 0) {
return;
} else {
throw new RuntimeException(errorBuilderForEntireCluster.toString());
}
}
//todo dedupe this into a name-demangling class that everyone can access
protected static String internalTableName(TableReference tableRef) {
String tableName = tableRef.getQualifiedName();
if (tableName.startsWith("_")) {
return tableName;
}
return tableName.replaceFirst("\\.", "__");
}
// for tables internal / implementation specific to this KVS; these also don't get metadata in metadata table, nor do they show up in getTablenames
private void createTableInternal(Client client, final TableReference tableRef) throws InvalidRequestException, SchemaDisagreementException, TException, NotFoundException {
KsDef ks = client.describe_keyspace(config.keyspace());
for (CfDef cf : ks.getCf_defs()) {
if (cf.getName().equalsIgnoreCase(internalTableName(tableRef))) {
return;
}
}
CfDef cf = CassandraConstants.getStandardCfDef(config.keyspace(), internalTableName(tableRef));
client.system_add_column_family(cf);
CassandraKeyValueServices.waitForSchemaVersions(client, tableRef.getQualifiedName(), config.schemaMutationTimeoutMillis());
return;
}
private void refreshTokenRanges() {
try {
List<TokenRange> tokenRanges = getRandomGoodHost().runWithPooledResource(describeRing);
ImmutableRangeMap.Builder<LightweightOPPToken, List<InetSocketAddress>> newTokenRing = ImmutableRangeMap.builder();
for (TokenRange tokenRange : tokenRanges) {
List<InetSocketAddress> hosts = Lists.transform(tokenRange.getEndpoints(), new Function<String, InetSocketAddress>() {
@Override
public InetSocketAddress apply(String endpoint) {
return new InetSocketAddress(endpoint, CassandraConstants.DEFAULT_THRIFT_PORT);
}
});
LightweightOPPToken startToken = new LightweightOPPToken(BaseEncoding.base16().decode(tokenRange.getStart_token().toUpperCase()));
LightweightOPPToken endToken = new LightweightOPPToken(BaseEncoding.base16().decode(tokenRange.getEnd_token().toUpperCase()));
if (startToken.compareTo(endToken) <= 0) {
newTokenRing.put(Range.openClosed(startToken, endToken), hosts);
} else {
// Handle wrap-around
newTokenRing.put(Range.greaterThan(startToken), hosts);
newTokenRing.put(Range.atMost(endToken), hosts);
}
}
tokenMap = newTokenRing.build();
} catch (Exception e) {
log.error("Couldn't grab new token ranges for token aware cassandra mapping!", e);
}
}
private FunctionCheckedException<Cassandra.Client, List<TokenRange>, Exception> describeRing = new FunctionCheckedException<Cassandra.Client, List<TokenRange>, Exception>() {
@Override
public List<TokenRange> apply (Cassandra.Client client) throws Exception {
return client.describe_ring(config.keyspace());
}};
public <V, K extends Exception> V runWithRetry(FunctionCheckedException<Cassandra.Client, V, K> f) throws K {
return runWithRetryOnHost(getRandomGoodHost().getHost(), f);
}
public <V, K extends Exception> V runWithRetryOnHost(InetSocketAddress specifiedHost, FunctionCheckedException<Cassandra.Client, V, K> f) throws K {
int numTries = 0;
while (true) {
CassandraClientPoolingContainer hostPool = currentPools.get(specifiedHost);
if (blacklistedHosts.containsKey(specifiedHost) || hostPool == null) {
log.warn("Randomly redirected a query intended for host {} because it was not currently a live member of the pool.", specifiedHost);
hostPool = getRandomGoodHost();
}
try {
return hostPool.runWithPooledResource(f);
} catch (Exception e) {
numTries++;
this.<K>handleException(numTries, hostPool.getHost(), e);
}
}
}
public <V, K extends Exception> V run(FunctionCheckedException<Cassandra.Client, V, K> f) throws K {
return runOnHost(getRandomGoodHost().getHost(), f);
}
public <V, K extends Exception> V runOnHost(InetSocketAddress specifiedHost, FunctionCheckedException<Cassandra.Client, V, K> f) throws K {
CassandraClientPoolingContainer hostPool = currentPools.get(specifiedHost);
return hostPool.runWithPooledResource(f);
}
@SuppressWarnings("unchecked")
private <K extends Exception> void handleException(int numTries, InetSocketAddress host, Exception e) throws K {
if (isRetriableException(e)) {
if (numTries >= MAX_TRIES) {
if (e instanceof TTransportException
&& e.getCause() != null
&& (e.getCause().getClass() == SocketException.class)) {
String msg = "Error writing to Cassandra socket. Likely cause: Exceeded maximum thrift frame size; unlikely cause: network issues.";
log.error("Tried to connect to cassandra " + numTries + " times. " + msg, e);
e = new TTransportException(((TTransportException) e).getType(), msg, e);
} else {
log.error("Tried to connect to cassandra " + numTries + " times.", e);
}
throw (K) e;
} else {
log.warn("Error occurred talking to cassandra. Attempt {} of {}.", numTries, MAX_TRIES, e);
if (isConnectionException(e)) {
addToBlacklist(host);
}
}
} else {
throw (K) e;
}
}
// This method exists to verify a particularly nasty bug where cassandra doesn't have a
// consistent ring across all of it's nodes. One node will think it owns more than the others
// think it does and they will not send writes to it, but it will respond to requests
// acting like it does.
private void sanityCheckRingConsistency() {
Multimap<Set<TokenRange>, InetSocketAddress> tokenRangesToHost = HashMultimap.create();
for (InetSocketAddress host : currentPools.keySet()) {
Cassandra.Client client = null;
try {
client = CassandraClientFactory.getClientInternal(host, config.ssl(), config.socketTimeoutMillis(), config.socketQueryTimeoutMillis());
try {
client.describe_keyspace(config.keyspace());
} catch (NotFoundException e) {
return; // don't care to check for ring consistency when we're not even fully initialized
}
tokenRangesToHost.put(ImmutableSet.copyOf(client.describe_ring(config.keyspace())), host);
} catch (Exception e) {
log.warn("failed to get ring info from host: {}", host, e);
} finally {
if (client != null) {
client.getOutputProtocol().getTransport().close();
}
}
if (tokenRangesToHost.isEmpty()) {
log.warn("Failed to get ring info for entire Cassandra cluster ({}); ring could not be checked for consistency.", config.keyspace());
return;
}
if (tokenRangesToHost.keySet().size() == 1) { // all nodes agree on a consistent view of the cluster. Good.
return;
}
RuntimeException e = new IllegalStateException("Hosts have differing ring descriptions. This can lead to inconsistent reads and lost data. ");
log.error("QA-86204 " + e.getMessage() + tokenRangesToHost, e);
// provide some easier to grok logging for the two most common cases
if (tokenRangesToHost.size() > 2) {
for (Map.Entry<Set<TokenRange>, Collection<InetSocketAddress>> entry : tokenRangesToHost.asMap().entrySet()) {
if (entry.getValue().size() == 1) {
log.error("Host: " + entry.getValue().iterator().next() +
" disagrees with the other nodes about the ring state.");
}
}
}
if (tokenRangesToHost.keySet().size() == 2) {
ImmutableList<Set<TokenRange>> sets = ImmutableList.copyOf(tokenRangesToHost.keySet());
Set<TokenRange> set1 = sets.get(0);
Set<TokenRange> set2 = sets.get(1);
log.error("Hosts are split. group1: " + tokenRangesToHost.get(set1) +
" group2: " + tokenRangesToHost.get(set2));
}
CassandraVerifier.logErrorOrThrow(e.getMessage(), config.safetyDisabled());
}
}
@VisibleForTesting
static boolean isConnectionException(Throwable t) {
return t != null
&& (t instanceof SocketTimeoutException
|| t instanceof ClientCreationFailedException
|| t instanceof UnavailableException
|| t instanceof NoSuchElementException
|| isConnectionException(t.getCause()));
}
@VisibleForTesting
static boolean isRetriableException(Throwable t) {
return t != null
&& (t instanceof TTransportException
|| t instanceof TimedOutException
|| t instanceof InsufficientConsistencyException
|| isConnectionException(t)
|| isRetriableException(t.getCause()));
}
final FunctionCheckedException<Cassandra.Client, Void, Exception> validatePartitioner = new FunctionCheckedException<Cassandra.Client, Void, Exception>() {
@Override
public Void apply(Cassandra.Client client) throws Exception {
CassandraVerifier.validatePartitioner(client, config);
return null;
}
};
final FunctionCheckedException<Cassandra.Client, Void, Exception> createInternalMetadataTable = new FunctionCheckedException<Cassandra.Client, Void, Exception>() {
@Override
public Void apply(Cassandra.Client client) throws Exception {
createTableInternal(client, CassandraConstants.METADATA_TABLE);
return null;
}
};
}
| atlasdb-cassandra/src/main/java/com/palantir/atlasdb/keyvalue/cassandra/CassandraClientPool.java | /**
* Copyright 2015 Palantir Technologies
*
* Licensed under the BSD-3 License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://opensource.org/licenses/BSD-3-Clause
*
* 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.palantir.atlasdb.keyvalue.cassandra;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import org.apache.cassandra.thrift.Cassandra;
import org.apache.cassandra.thrift.Cassandra.Client;
import org.apache.cassandra.thrift.CfDef;
import org.apache.cassandra.thrift.InvalidRequestException;
import org.apache.cassandra.thrift.KsDef;
import org.apache.cassandra.thrift.NotFoundException;
import org.apache.cassandra.thrift.SchemaDisagreementException;
import org.apache.cassandra.thrift.TimedOutException;
import org.apache.cassandra.thrift.TokenRange;
import org.apache.cassandra.thrift.UnavailableException;
import org.apache.thrift.TException;
import org.apache.thrift.transport.TTransportException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Function;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableRangeMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import com.google.common.collect.Range;
import com.google.common.collect.RangeMap;
import com.google.common.collect.Sets;
import com.google.common.collect.Sets.SetView;
import com.google.common.io.BaseEncoding;
import com.google.common.primitives.UnsignedBytes;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.palantir.atlasdb.cassandra.CassandraKeyValueServiceConfig;
import com.palantir.atlasdb.keyvalue.api.InsufficientConsistencyException;
import com.palantir.atlasdb.keyvalue.api.TableReference;
import com.palantir.atlasdb.keyvalue.cassandra.CassandraClientFactory.ClientCreationFailedException;
import com.palantir.common.base.FunctionCheckedException;
import com.palantir.common.concurrent.PTExecutors;
/**
* Feature breakdown:
* - Pooling
* - Token Aware Mapping / Query Routing / Data partitioning
* - Retriable Queries
* - Pool member error tracking / blacklisting*
* - Pool refreshing
* - Pool node autodiscovery
* - Pool member health checking*
*
* *entirely new features
*
* By our old system, this would be a RefreshingRetriableTokenAwareHealthCheckingManyHostCassandraClientPoolingContainerManager;
* ... this is one of the reasons why there is a new system.
**/
public class CassandraClientPool {
private static final Logger log = LoggerFactory.getLogger(CassandraClientPool.class);
private static final int MAX_TRIES = 3;
volatile RangeMap<LightweightOPPToken, List<InetSocketAddress>> tokenMap = ImmutableRangeMap.of();
Map<InetSocketAddress, Long> blacklistedHosts = Maps.newConcurrentMap();
Map<InetSocketAddress, CassandraClientPoolingContainer> currentPools = Maps.newConcurrentMap();
final CassandraKeyValueServiceConfig config;
final ScheduledThreadPoolExecutor refreshDaemon;
public static class LightweightOPPToken implements Comparable<LightweightOPPToken> {
final byte[] bytes;
public LightweightOPPToken(byte[] bytes) {
this.bytes = bytes;
}
@Override
public int compareTo(LightweightOPPToken other) {
return UnsignedBytes.lexicographicalComparator().compare(this.bytes, other.bytes);
}
}
public CassandraClientPool(CassandraKeyValueServiceConfig config) {
this.config = config;
refreshDaemon = PTExecutors.newScheduledThreadPool(1, new ThreadFactoryBuilder().setDaemon(true).setNameFormat("CassandraClientPoolRefresh-%d").build());
refreshDaemon.scheduleWithFixedDelay(new Runnable() {
@Override
public void run() {
try {
refreshPool();
} catch (Throwable t) {
log.error("Failed to refresh Cassandra KVS pool. Extended periods of being unable to refresh will cause perf degradation.", t);
}
}
}, config.poolRefreshIntervalSeconds(), config.poolRefreshIntervalSeconds(), TimeUnit.SECONDS);
config.servers().forEach((server) -> currentPools.put(server, new CassandraClientPoolingContainer(server, config)));
refreshPool(); // ensure we've initialized before returning
}
public void shutdown() {
refreshDaemon.shutdown();
currentPools.forEach((address, cassandraClientPoolingContainer) -> cassandraClientPoolingContainer.shutdownPooling());
}
private synchronized void refreshPool() {
checkAndUpdateBlacklist();
Set<InetSocketAddress> serversToAdd = Sets.newHashSet(config.servers());
Set<InetSocketAddress> serversToRemove = ImmutableSet.of();
if (config.autoRefreshNodes()) {
refreshTokenRanges(); // re-use token mapping as list of hosts in the cluster
for (List<InetSocketAddress> rangeOwners : tokenMap.asMapOfRanges().values()) {
for (InetSocketAddress address : rangeOwners) {
serversToAdd.add(address);
}
}
}
serversToAdd = Sets.difference(Sets.difference(serversToAdd, currentPools.keySet()), blacklistedHosts.keySet());
if (!config.autoRefreshNodes()) { // (we would just add them back in)
serversToRemove = Sets.difference(currentPools.keySet(), config.servers());
}
for (InetSocketAddress newServer : serversToAdd) {
currentPools.put(newServer, new CassandraClientPoolingContainer(newServer, config));
}
if (!(serversToAdd.isEmpty() && serversToRemove.isEmpty())) { // if we made any changes
sanityCheckRingConsistency();
if (!config.autoRefreshNodes()) { // grab new token mapping, if we didn't already do this before
refreshTokenRanges();
}
}
log.debug("Cassandra pool refresh added hosts {}, removed hosts {}.", serversToAdd, serversToRemove);
debugLogStateOfPool();
}
private void debugLogStateOfPool() {
if (log.isDebugEnabled()) {
StringBuilder currentState = new StringBuilder();
currentState.append(
String.format("POOL STATUS: Current blacklist = %s,%n current hosts in pool = %s%n",
blacklistedHosts.keySet().toString(), currentPools.keySet().toString()));
for (Entry<InetSocketAddress, CassandraClientPoolingContainer> entry : currentPools.entrySet()) {
int activeCheckouts = entry.getValue().getPoolUtilization();
int totalAllowed = entry.getValue().getPoolSize();
currentState.append(
String.format("\tPOOL STATUS: Pooled host %s has %s out of %s connections checked out.%n",
entry.getKey(),
activeCheckouts > 0? Integer.toString(activeCheckouts) : "(unknown)",
totalAllowed > 0? Integer.toString(totalAllowed) : "(not bounded)"));
}
log.debug(currentState.toString());
}
}
private void checkAndUpdateBlacklist() {
// Check blacklist and re-integrate or continue to wait as necessary
for (Map.Entry<InetSocketAddress, Long> blacklistedEntry : blacklistedHosts.entrySet()) {
long backoffTimeMillis = TimeUnit.SECONDS.toMillis(config.unresponsiveHostBackoffTimeSeconds());
if (blacklistedEntry.getValue() + backoffTimeMillis < System.currentTimeMillis()) {
InetSocketAddress host = blacklistedEntry.getKey();
if (isHostHealthy(host)) {
blacklistedHosts.remove(host);
log.error("Added host {} back into the pool after a waiting period and successful health check.", host);
}
}
}
}
private void addToBlacklist(InetSocketAddress badHost) {
blacklistedHosts.put(badHost, System.currentTimeMillis());
}
private boolean isHostHealthy(InetSocketAddress host) {
try {
CassandraClientPoolingContainer testingContainer = new CassandraClientPoolingContainer(host, config);
testingContainer.runWithPooledResource(describeRing);
testingContainer.runWithPooledResource(CassandraVerifier.healthCheck);
} catch (Exception e) {
log.error("We tried to add {} back into the pool, but got an exception that caused to us distrust this host further.", host, e);
return false;
}
return true;
}
private CassandraClientPoolingContainer getRandomGoodHost() {
Map<InetSocketAddress, CassandraClientPoolingContainer> pools = currentPools;
Set<InetSocketAddress> livingHosts = Sets.difference(pools.keySet(), blacklistedHosts.keySet());
if (livingHosts.isEmpty()) {
log.error("There are no known live hosts in the connection pool. We're choosing one at random in a last-ditch attempt at forward progress.");
livingHosts = pools.keySet();
}
return pools.get(ImmutableList.copyOf(livingHosts).get(ThreadLocalRandom.current().nextInt(livingHosts.size())));
}
public InetSocketAddress getRandomHostForKey(byte[] key) {
List<InetSocketAddress> hostsForKey = tokenMap.get(new LightweightOPPToken(key));
SetView<InetSocketAddress> liveOwnerHosts;
if (hostsForKey == null) {
log.warn("Cluster not fully initialized, not routing query to correct host as not token map found.");
return getRandomGoodHost().getHost();
} else {
liveOwnerHosts = Sets.difference(ImmutableSet.copyOf(hostsForKey), blacklistedHosts.keySet());
}
if (liveOwnerHosts.isEmpty()) {
log.warn("Perf / cluster stability issue. Token aware query routing has failed because there are no known " +
"live hosts that claim ownership of the given range. Falling back to choosing a random live node. " +
"For debugging, our current ring view is: {} and our current host blacklist is {}", tokenMap, blacklistedHosts);
return getRandomGoodHost().getHost();
} else {
return currentPools.get(ImmutableList.copyOf(liveOwnerHosts).get(ThreadLocalRandom.current().nextInt(liveOwnerHosts.size()))).getHost();
}
}
public void runOneTimeStartupChecks() {
final FunctionCheckedException<Cassandra.Client, Void, Exception> validatePartitioner = new FunctionCheckedException<Cassandra.Client, Void, Exception>() {
@Override
public Void apply(Cassandra.Client client) throws Exception {
CassandraVerifier.validatePartitioner(client, config);
return null;
}
};
final FunctionCheckedException<Cassandra.Client, Void, Exception> createInternalMetadataTable = new FunctionCheckedException<Cassandra.Client, Void, Exception>() {
@Override
public Void apply(Cassandra.Client client) throws Exception {
createTableInternal(client, CassandraConstants.METADATA_TABLE);
return null;
}
};
try {
CassandraVerifier.ensureKeyspaceExistsAndIsUpToDate(this, config);
} catch (Exception e) {
log.error("Startup checks failed, was not able to create the keyspace or ensure it already existed.");
throw new RuntimeException(e);
}
Map<InetSocketAddress, Exception> completelyUnresponsiveHosts = Maps.newHashMap(), aliveButInvalidPartitionerHosts = Maps.newHashMap();
boolean thisHostResponded, atLeastOneHostResponded = false, atLeastOneHostSaidWeHaveAMetadataTable = false;
for (InetSocketAddress liveHost : Sets.difference(currentPools.keySet(), blacklistedHosts.keySet())) {
thisHostResponded = false;
try {
runOnHost(liveHost, CassandraVerifier.healthCheck);
thisHostResponded = true;
atLeastOneHostResponded = true;
} catch (Exception e) {
completelyUnresponsiveHosts.put(liveHost, e);
addToBlacklist(liveHost);
}
if (thisHostResponded) {
try {
runOnHost(liveHost, validatePartitioner);
} catch (Exception e) {
aliveButInvalidPartitionerHosts.put(liveHost, e);
}
try {
runOnHost(liveHost, createInternalMetadataTable);
atLeastOneHostSaidWeHaveAMetadataTable = true;
} catch (Exception e) {
// don't fail here, want to give the user all the errors at once at the end
}
}
}
StringBuilder errorBuilderForEntireCluster = new StringBuilder();
if (completelyUnresponsiveHosts.size() > 0) {
errorBuilderForEntireCluster.append("Performing routine startup checks, determined that the following hosts are unreachable for the following reasons: \n");
completelyUnresponsiveHosts.forEach((host, exception) ->
errorBuilderForEntireCluster.append(String.format("\tHost: %s was marked unreachable via exception: %s%n", host.toString(), exception.toString())));
}
if (aliveButInvalidPartitionerHosts.size() > 0) {
errorBuilderForEntireCluster.append("Performing routine startup checks, determined that the following hosts were alive but are configured with an invalid partitioner: \n");
aliveButInvalidPartitionerHosts.forEach((host, exception) ->
errorBuilderForEntireCluster.append(String.format("\tHost: %s was marked as invalid partitioner via exception: %s%n", host.toString(), exception.toString())));
}
if (atLeastOneHostResponded && atLeastOneHostSaidWeHaveAMetadataTable && aliveButInvalidPartitionerHosts.size() == 0) {
return;
} else {
throw new RuntimeException(errorBuilderForEntireCluster.toString());
}
}
//todo dedupe this into a name-demangling class that everyone can access
protected static String internalTableName(TableReference tableRef) {
String tableName = tableRef.getQualifiedName();
if (tableName.startsWith("_")) {
return tableName;
}
return tableName.replaceFirst("\\.", "__");
}
// for tables internal / implementation specific to this KVS; these also don't get metadata in metadata table, nor do they show up in getTablenames
private void createTableInternal(Client client, final TableReference tableRef) throws InvalidRequestException, SchemaDisagreementException, TException, NotFoundException {
KsDef ks = client.describe_keyspace(config.keyspace());
for (CfDef cf : ks.getCf_defs()) {
if (cf.getName().equalsIgnoreCase(internalTableName(tableRef))) {
return;
}
}
CfDef cf = CassandraConstants.getStandardCfDef(config.keyspace(), internalTableName(tableRef));
client.system_add_column_family(cf);
CassandraKeyValueServices.waitForSchemaVersions(client, tableRef.getQualifiedName(), config.schemaMutationTimeoutMillis());
return;
}
private void refreshTokenRanges() {
try {
List<TokenRange> tokenRanges = getRandomGoodHost().runWithPooledResource(describeRing);
ImmutableRangeMap.Builder<LightweightOPPToken, List<InetSocketAddress>> newTokenRing = ImmutableRangeMap.builder();
for (TokenRange tokenRange : tokenRanges) {
List<InetSocketAddress> hosts = Lists.transform(tokenRange.getEndpoints(), new Function<String, InetSocketAddress>() {
@Override
public InetSocketAddress apply(String endpoint) {
return new InetSocketAddress(endpoint, CassandraConstants.DEFAULT_THRIFT_PORT);
}
});
LightweightOPPToken startToken = new LightweightOPPToken(BaseEncoding.base16().decode(tokenRange.getStart_token().toUpperCase()));
LightweightOPPToken endToken = new LightweightOPPToken(BaseEncoding.base16().decode(tokenRange.getEnd_token().toUpperCase()));
if (startToken.compareTo(endToken) <= 0) {
newTokenRing.put(Range.openClosed(startToken, endToken), hosts);
} else {
// Handle wrap-around
newTokenRing.put(Range.greaterThan(startToken), hosts);
newTokenRing.put(Range.atMost(endToken), hosts);
}
}
tokenMap = newTokenRing.build();
} catch (Exception e) {
log.error("Couldn't grab new token ranges for token aware cassandra mapping!", e);
}
}
private FunctionCheckedException<Cassandra.Client, List<TokenRange>, Exception> describeRing = new FunctionCheckedException<Cassandra.Client, List<TokenRange>, Exception>() {
@Override
public List<TokenRange> apply (Cassandra.Client client) throws Exception {
return client.describe_ring(config.keyspace());
}};
public <V, K extends Exception> V runWithRetry(FunctionCheckedException<Cassandra.Client, V, K> f) throws K {
return runWithRetryOnHost(getRandomGoodHost().getHost(), f);
}
public <V, K extends Exception> V runWithRetryOnHost(InetSocketAddress specifiedHost, FunctionCheckedException<Cassandra.Client, V, K> f) throws K {
int numTries = 0;
while (true) {
CassandraClientPoolingContainer hostPool = currentPools.get(specifiedHost);
if (blacklistedHosts.containsKey(specifiedHost) || hostPool == null) {
log.warn("Randomly redirected a query intended for host {} because it was not currently a live member of the pool.", specifiedHost);
hostPool = getRandomGoodHost();
}
try {
return hostPool.runWithPooledResource(f);
} catch (Exception e) {
numTries++;
this.<K>handleException(numTries, hostPool.getHost(), e);
}
}
}
public <V, K extends Exception> V run(FunctionCheckedException<Cassandra.Client, V, K> f) throws K {
return runOnHost(getRandomGoodHost().getHost(), f);
}
public <V, K extends Exception> V runOnHost(InetSocketAddress specifiedHost, FunctionCheckedException<Cassandra.Client, V, K> f) throws K {
CassandraClientPoolingContainer hostPool = currentPools.get(specifiedHost);
return hostPool.runWithPooledResource(f);
}
@SuppressWarnings("unchecked")
private <K extends Exception> void handleException(int numTries, InetSocketAddress host, Exception e) throws K {
if (isRetriableException(e)) {
if (numTries >= MAX_TRIES) {
if (e instanceof TTransportException
&& e.getCause() != null
&& (e.getCause().getClass() == SocketException.class)) {
String msg = "Error writing to Cassandra socket. Likely cause: Exceeded maximum thrift frame size; unlikely cause: network issues.";
log.error("Tried to connect to cassandra " + numTries + " times. " + msg, e);
e = new TTransportException(((TTransportException) e).getType(), msg, e);
} else {
log.error("Tried to connect to cassandra " + numTries + " times.", e);
}
throw (K) e;
} else {
log.warn("Error occurred talking to cassandra. Attempt {} of {}.", numTries, MAX_TRIES, e);
if (isConnectionException(e)) {
addToBlacklist(host);
}
}
} else {
throw (K) e;
}
}
// This method exists to verify a particularly nasty bug where cassandra doesn't have a
// consistent ring across all of it's nodes. One node will think it owns more than the others
// think it does and they will not send writes to it, but it will respond to requests
// acting like it does.
private void sanityCheckRingConsistency() {
Multimap<Set<TokenRange>, InetSocketAddress> tokenRangesToHost = HashMultimap.create();
for (InetSocketAddress host : currentPools.keySet()) {
Cassandra.Client client = null;
try {
client = CassandraClientFactory.getClientInternal(host, config.ssl(), config.socketTimeoutMillis(), config.socketQueryTimeoutMillis());
try {
client.describe_keyspace(config.keyspace());
} catch (NotFoundException e) {
return; // don't care to check for ring consistency when we're not even fully initialized
}
tokenRangesToHost.put(ImmutableSet.copyOf(client.describe_ring(config.keyspace())), host);
} catch (Exception e) {
log.warn("failed to get ring info from host: {}", host, e);
} finally {
if (client != null) {
client.getOutputProtocol().getTransport().close();
}
}
if (tokenRangesToHost.isEmpty()) {
log.warn("Failed to get ring info for entire Cassandra cluster ({}); ring could not be checked for consistency.", config.keyspace());
return;
}
if (tokenRangesToHost.keySet().size() == 1) { // all nodes agree on a consistent view of the cluster. Good.
return;
}
RuntimeException e = new IllegalStateException("Hosts have differing ring descriptions. This can lead to inconsistent reads and lost data. ");
log.error("QA-86204 " + e.getMessage() + tokenRangesToHost, e);
// provide some easier to grok logging for the two most common cases
if (tokenRangesToHost.size() > 2) {
for (Map.Entry<Set<TokenRange>, Collection<InetSocketAddress>> entry : tokenRangesToHost.asMap().entrySet()) {
if (entry.getValue().size() == 1) {
log.error("Host: " + entry.getValue().iterator().next() +
" disagrees with the other nodes about the ring state.");
}
}
}
if (tokenRangesToHost.keySet().size() == 2) {
ImmutableList<Set<TokenRange>> sets = ImmutableList.copyOf(tokenRangesToHost.keySet());
Set<TokenRange> set1 = sets.get(0);
Set<TokenRange> set2 = sets.get(1);
log.error("Hosts are split. group1: " + tokenRangesToHost.get(set1) +
" group2: " + tokenRangesToHost.get(set2));
}
CassandraVerifier.logErrorOrThrow(e.getMessage(), config.safetyDisabled());
}
}
@VisibleForTesting
static boolean isConnectionException(Throwable t) {
return t != null
&& (t instanceof SocketTimeoutException
|| t instanceof ClientCreationFailedException
|| t instanceof UnavailableException
|| t instanceof NoSuchElementException
|| isConnectionException(t.getCause()));
}
@VisibleForTesting
static boolean isRetriableException(Throwable t) {
return t != null
&& (t instanceof TTransportException
|| t instanceof TimedOutException
|| t instanceof InsufficientConsistencyException
|| isConnectionException(t)
|| isRetriableException(t.getCause()));
}
}
| cassandra pool verify partitioner on node entrance
| atlasdb-cassandra/src/main/java/com/palantir/atlasdb/keyvalue/cassandra/CassandraClientPool.java | cassandra pool verify partitioner on node entrance | <ide><path>tlasdb-cassandra/src/main/java/com/palantir/atlasdb/keyvalue/cassandra/CassandraClientPool.java
<ide> final CassandraKeyValueServiceConfig config;
<ide> final ScheduledThreadPoolExecutor refreshDaemon;
<ide>
<del>
<ide> public static class LightweightOPPToken implements Comparable<LightweightOPPToken> {
<ide> final byte[] bytes;
<ide>
<ide> refreshPool(); // ensure we've initialized before returning
<ide> }
<ide>
<del>
<ide> public void shutdown() {
<ide> refreshDaemon.shutdown();
<ide> currentPools.forEach((address, cassandraClientPoolingContainer) -> cassandraClientPoolingContainer.shutdownPooling());
<ide> try {
<ide> CassandraClientPoolingContainer testingContainer = new CassandraClientPoolingContainer(host, config);
<ide> testingContainer.runWithPooledResource(describeRing);
<del> testingContainer.runWithPooledResource(CassandraVerifier.healthCheck);
<add> testingContainer.runWithPooledResource(validatePartitioner);
<ide> } catch (Exception e) {
<ide> log.error("We tried to add {} back into the pool, but got an exception that caused to us distrust this host further.", host, e);
<ide> return false;
<ide> }
<ide>
<ide> public void runOneTimeStartupChecks() {
<del> final FunctionCheckedException<Cassandra.Client, Void, Exception> validatePartitioner = new FunctionCheckedException<Cassandra.Client, Void, Exception>() {
<del> @Override
<del> public Void apply(Cassandra.Client client) throws Exception {
<del> CassandraVerifier.validatePartitioner(client, config);
<del> return null;
<del> }
<del> };
<del>
<del> final FunctionCheckedException<Cassandra.Client, Void, Exception> createInternalMetadataTable = new FunctionCheckedException<Cassandra.Client, Void, Exception>() {
<del> @Override
<del> public Void apply(Cassandra.Client client) throws Exception {
<del> createTableInternal(client, CassandraConstants.METADATA_TABLE);
<del> return null;
<del> }
<del> };
<del>
<ide> try {
<ide> CassandraVerifier.ensureKeyspaceExistsAndIsUpToDate(this, config);
<ide> } catch (Exception e) {
<ide> || isRetriableException(t.getCause()));
<ide> }
<ide>
<add> final FunctionCheckedException<Cassandra.Client, Void, Exception> validatePartitioner = new FunctionCheckedException<Cassandra.Client, Void, Exception>() {
<add> @Override
<add> public Void apply(Cassandra.Client client) throws Exception {
<add> CassandraVerifier.validatePartitioner(client, config);
<add> return null;
<add> }
<add> };
<add>
<add> final FunctionCheckedException<Cassandra.Client, Void, Exception> createInternalMetadataTable = new FunctionCheckedException<Cassandra.Client, Void, Exception>() {
<add> @Override
<add> public Void apply(Cassandra.Client client) throws Exception {
<add> createTableInternal(client, CassandraConstants.METADATA_TABLE);
<add> return null;
<add> }
<add> };
<add>
<ide> } |
|
Java | bsd-2-clause | 857b67d16bc53a683996ff31e3cf6f7aded41f02 | 0 | scijava/scijava-ui-swing | /*
* #%L
* SciJava UI components for Java Swing.
* %%
* Copyright (C) 2010 - 2015 Board of Regents of the University of
* Wisconsin-Madison.
* %%
* 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 org.scijava.ui.swing.widget;
import java.awt.Adjustable;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.DecimalFormat;
import java.text.ParsePosition;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.JSlider;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import javax.swing.SpinnerNumberModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin;
import org.scijava.thread.ThreadService;
import org.scijava.util.NumberUtils;
import org.scijava.widget.InputWidget;
import org.scijava.widget.NumberWidget;
import org.scijava.widget.WidgetModel;
/**
* Swing implementation of number chooser widget.
*
* @author Curtis Rueden
*/
@Plugin(type = InputWidget.class)
public class SwingNumberWidget extends SwingInputWidget<Number> implements
NumberWidget<JPanel>, AdjustmentListener, ChangeListener
{
@Parameter
private ThreadService threadService;
private JScrollBar scrollBar;
private JSlider slider;
private JSpinner spinner;
// -- InputWidget methods --
@Override
public Number getValue() {
return (Number) spinner.getValue();
}
// -- WrapperPlugin methods --
@Override
public void set(final WidgetModel model) {
super.set(model);
final Number min = model.getMin();
final Number max = model.getMax();
final Number softMin = model.getSoftMin();
final Number softMax = model.getSoftMax();
final Number stepSize = model.getStepSize();
// add optional widgets, if specified
if (model.isStyle(NumberWidget.SCROLL_BAR_STYLE)) {
int smx = softMax.intValue();
if (smx < Integer.MAX_VALUE) smx++;
scrollBar =
new JScrollBar(Adjustable.HORIZONTAL, softMin.intValue(), 1, softMin
.intValue(), smx);
scrollBar.setUnitIncrement(stepSize.intValue());
setToolTip(scrollBar);
getComponent().add(scrollBar);
scrollBar.addAdjustmentListener(this);
}
else if (model.isStyle(NumberWidget.SLIDER_STYLE)) {
slider =
new JSlider(softMin.intValue(), softMax.intValue(), softMin.intValue());
slider.setMajorTickSpacing((softMax.intValue() - softMin.intValue()) / 4);
slider.setMinorTickSpacing(stepSize.intValue());
slider.setPaintLabels(true);
slider.setPaintTicks(true);
setToolTip(slider);
getComponent().add(slider);
slider.addChangeListener(this);
}
// add spinner widget
final Class<?> type = model.getItem().getType();
if (model.getValue() == null) {
final Number defaultValue = NumberUtils.getDefaultValue(min, max, type);
model.setValue(defaultValue);
}
final Number value = (Number) model.getValue();
final SpinnerNumberModel spinnerModel =
new SpinnerNumberModelFactory().createModel(value, min, max, stepSize);
spinner = new JSpinner(spinnerModel);
fixSpinner(type);
setToolTip(spinner);
getComponent().add(spinner);
limitWidth(200);
spinner.addChangeListener(this);
refreshWidget();
syncSliders();
}
// -- Typed methods --
@Override
public boolean supports(final WidgetModel model) {
return super.supports(model) && model.isNumber();
}
// -- AdjustmentListener methods --
@Override
public void adjustmentValueChanged(final AdjustmentEvent e) {
// sync spinner with scroll bar value
final int value = scrollBar.getValue();
spinner.setValue(value);
}
// -- ChangeListener methods --
@Override
public void stateChanged(final ChangeEvent e) {
final Object source = e.getSource();
if (source == slider) {
// sync spinner with slider value
final int value = slider.getValue();
spinner.setValue(value);
}
else if (source == spinner) {
// sync slider and/or scroll bar with spinner value
syncSliders();
}
updateModel();
}
// -- Helper methods --
/**
* Limit component width to a certain maximum. This is a HACK to work around
* an issue with Double-based spinners that attempt to size themselves very
* large (presumably to match Double.MAX_VALUE).
*/
private void limitWidth(final int maxWidth) {
final Dimension minSize = spinner.getMinimumSize();
if (minSize.width > maxWidth) {
minSize.width = maxWidth;
spinner.setMinimumSize(minSize);
}
final Dimension prefSize = spinner.getPreferredSize();
if (prefSize.width > maxWidth) {
prefSize.width = maxWidth;
spinner.setPreferredSize(prefSize);
}
}
/** Improves behavior of the {@link JSpinner} widget. */
private void fixSpinner(final Class<?> type) {
fixSpinnerType(type);
fixSpinnerFocus();
}
/**
* Fixes spinners that display {@link BigDecimal} or {@link BigInteger}
* values. This is a HACK to work around the fact that
* {@link DecimalFormat#parse(String, ParsePosition)} uses {@link Double}
* and/or {@link Long} by default, hence losing precision.
*/
private void fixSpinnerType(final Class<?> type) {
if (!BigDecimal.class.isAssignableFrom(type) &&
!BigInteger.class.isAssignableFrom(type))
{
return;
}
final JComponent editor = spinner.getEditor();
final JSpinner.NumberEditor numberEditor = (JSpinner.NumberEditor) editor;
final DecimalFormat decimalFormat = numberEditor.getFormat();
decimalFormat.setParseBigDecimal(true);
}
/**
* Tries to ensure that the text of a {@link JSpinner} becomes selected when
* it first receives the focus.
* <p>
* Adapted from <a href="http://stackoverflow.com/q/20971050">this SO
* post</a>.
*/
private void fixSpinnerFocus() {
for (final Component c : spinner.getEditor().getComponents()) {
if (!(c instanceof JTextField)) continue;
final JTextField textField = (JTextField) c;
textField.addFocusListener(new FocusListener() {
@Override
public void focusGained(final FocusEvent e) {
queueSelection();
}
@Override
public void focusLost(final FocusEvent e) {
queueSelection();
}
private void queueSelection() {
threadService.queue(new Runnable() {
@Override
public void run() {
textField.selectAll();
}
});
}
});
}
}
/** Sets slider values to match the spinner. */
private void syncSliders() {
if (slider != null) {
// clamp value within slider bounds
int value = getValue().intValue();
if (value < slider.getMinimum()) value = slider.getMinimum();
else if (value > slider.getMaximum()) value = slider.getMaximum();
slider.removeChangeListener(this);
slider.setValue(value);
slider.addChangeListener(this);
}
if (scrollBar != null) {
// clamp value within scroll bar bounds
int value = getValue().intValue();
if (value < scrollBar.getMinimum()) value = scrollBar.getMinimum();
else if (value > scrollBar.getMaximum()) value = scrollBar.getMaximum();
scrollBar.removeAdjustmentListener(this);
scrollBar.setValue(getValue().intValue());
scrollBar.addAdjustmentListener(this);
}
}
// -- AbstractUIInputWidget methods ---
@Override
public void doRefresh() {
final Object value = get().getValue();
if (spinner.getValue().equals(value)) return; // no change
spinner.setValue(value);
}
}
| src/main/java/org/scijava/ui/swing/widget/SwingNumberWidget.java | /*
* #%L
* SciJava UI components for Java Swing.
* %%
* Copyright (C) 2010 - 2015 Board of Regents of the University of
* Wisconsin-Madison.
* %%
* 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 org.scijava.ui.swing.widget;
import java.awt.Adjustable;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.DecimalFormat;
import java.text.ParsePosition;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.JSlider;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import javax.swing.SpinnerNumberModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin;
import org.scijava.thread.ThreadService;
import org.scijava.util.NumberUtils;
import org.scijava.widget.InputWidget;
import org.scijava.widget.NumberWidget;
import org.scijava.widget.WidgetModel;
/**
* Swing implementation of number chooser widget.
*
* @author Curtis Rueden
*/
@Plugin(type = InputWidget.class)
public class SwingNumberWidget extends SwingInputWidget<Number> implements
NumberWidget<JPanel>, AdjustmentListener, ChangeListener
{
@Parameter
private ThreadService threadService;
private JScrollBar scrollBar;
private JSlider slider;
private JSpinner spinner;
// -- InputWidget methods --
@Override
public Number getValue() {
return (Number) spinner.getValue();
}
// -- WrapperPlugin methods --
@Override
public void set(final WidgetModel model) {
super.set(model);
final Number min = model.getMin();
final Number max = model.getMax();
final Number softMin = model.getSoftMin();
final Number softMax = model.getSoftMax();
final Number stepSize = model.getStepSize();
// add optional widgets, if specified
if (model.isStyle(NumberWidget.SCROLL_BAR_STYLE)) {
int smx = softMax.intValue();
if (smx < Integer.MAX_VALUE) smx++;
scrollBar =
new JScrollBar(Adjustable.HORIZONTAL, softMin.intValue(), 1, softMin
.intValue(), smx);
scrollBar.setUnitIncrement(stepSize.intValue());
setToolTip(scrollBar);
getComponent().add(scrollBar);
scrollBar.addAdjustmentListener(this);
}
else if (model.isStyle(NumberWidget.SLIDER_STYLE)) {
slider =
new JSlider(softMin.intValue(), softMax.intValue(), softMin.intValue());
slider.setMajorTickSpacing((softMax.intValue() - softMin.intValue()) / 4);
slider.setMinorTickSpacing(stepSize.intValue());
slider.setPaintLabels(true);
slider.setPaintTicks(true);
setToolTip(slider);
getComponent().add(slider);
slider.addChangeListener(this);
}
// add spinner widget
final Class<?> type = model.getItem().getType();
if (model.getValue() == null) {
final Number defaultValue = NumberUtils.getDefaultValue(min, max, type);
model.setValue(defaultValue);
}
final Number value = (Number) model.getValue();
final SpinnerNumberModel spinnerModel =
new SpinnerNumberModelFactory().createModel(value, min, max, stepSize);
spinner = new JSpinner(spinnerModel);
fixSpinner(type);
setToolTip(spinner);
getComponent().add(spinner);
limitWidth(200);
spinner.addChangeListener(this);
refreshWidget();
syncSliders();
}
// -- Typed methods --
@Override
public boolean supports(final WidgetModel model) {
return super.supports(model) && model.isNumber();
}
// -- AdjustmentListener methods --
@Override
public void adjustmentValueChanged(final AdjustmentEvent e) {
// sync spinner with scroll bar value
final int value = scrollBar.getValue();
spinner.setValue(value);
}
// -- ChangeListener methods --
@Override
public void stateChanged(final ChangeEvent e) {
final Object source = e.getSource();
if (source == slider) {
// sync spinner with slider value
final int value = slider.getValue();
spinner.setValue(value);
}
else if (source == spinner) {
// sync slider and/or scroll bar with spinner value
syncSliders();
}
updateModel();
}
// -- Helper methods --
/**
* Limit component width to a certain maximum. This is a HACK to work around
* an issue with Double-based spinners that attempt to size themselves very
* large (presumably to match Double.MAX_VALUE).
*/
private void limitWidth(final int maxWidth) {
final Dimension minSize = spinner.getMinimumSize();
if (minSize.width > maxWidth) {
minSize.width = maxWidth;
spinner.setMinimumSize(minSize);
}
final Dimension prefSize = spinner.getPreferredSize();
if (prefSize.width > maxWidth) {
prefSize.width = maxWidth;
spinner.setPreferredSize(prefSize);
}
}
/** Improves behavior of the {@link JSpinner} widget. */
private void fixSpinner(final Class<?> type) {
fixSpinnerType(type);
fixSpinnerFocus();
}
/**
* Fixes spinners that display {@link BigDecimal} or {@link BigInteger}
* values. This is a HACK to work around the fact that
* {@link DecimalFormat#parse(String, ParsePosition)} uses {@link Double}
* and/or {@link Long} by default, hence losing precision.
*/
private void fixSpinnerType(final Class<?> type) {
if (!BigDecimal.class.isAssignableFrom(type) &&
!BigInteger.class.isAssignableFrom(type))
{
return;
}
final JComponent editor = spinner.getEditor();
final JSpinner.NumberEditor numberEditor = (JSpinner.NumberEditor) editor;
final DecimalFormat decimalFormat = numberEditor.getFormat();
decimalFormat.setParseBigDecimal(true);
}
/**
* Tries to ensure that the text of a {@link JSpinner} becomes selected when
* it first receives the focus.
* <p>
* Adapted from <a href="http://stackoverflow.com/q/20971050">this SO
* post</a>.
*/
private void fixSpinnerFocus() {
for (final Component c : spinner.getEditor().getComponents()) {
if (!(c instanceof JTextField)) continue;
final JTextField textField = (JTextField) c;
textField.addFocusListener(new FocusListener() {
@Override
public void focusGained(final FocusEvent e) {
queueSelection();
}
@Override
public void focusLost(final FocusEvent e) {
queueSelection();
}
private void queueSelection() {
threadService.queue(new Runnable() {
@Override
public void run() {
textField.selectAll();
}
});
}
});
}
}
/** Sets slider values to match the spinner. */
private void syncSliders() {
if (slider != null) {
// clamp value within slider bounds
int value = getValue().intValue();
if (value < slider.getMinimum()) value = slider.getMinimum();
else if (value > slider.getMaximum()) value = slider.getMaximum();
slider.removeChangeListener(this);
slider.setValue(value);
slider.addChangeListener(this);
}
if (scrollBar != null) {
// clamp value within scroll bar bounds
int value = getValue().intValue();
if (value < scrollBar.getMinimum()) value = scrollBar.getMinimum();
else if (value > scrollBar.getMaximum()) value = scrollBar.getMaximum();
scrollBar.removeAdjustmentListener(this);
scrollBar.setValue(getValue().intValue());
scrollBar.addAdjustmentListener(this);
}
}
// -- AbstractUIInputWidget methods ---
@Override
public void doRefresh() {
final Object value = get().getValue();
if (spinner.getValue().equals(value)) return; // no change
spinner.setValue(value);
}
}
| SwingNumberWidget: tweak whitespace
| src/main/java/org/scijava/ui/swing/widget/SwingNumberWidget.java | SwingNumberWidget: tweak whitespace | <ide><path>rc/main/java/org/scijava/ui/swing/widget/SwingNumberWidget.java
<ide> getComponent().add(spinner);
<ide> limitWidth(200);
<ide> spinner.addChangeListener(this);
<add>
<ide> refreshWidget();
<ide> syncSliders();
<ide> } |
|
Java | apache-2.0 | 280ceeb2f3178605fc22cfddcdf897a08dfa7572 | 0 | sdgdsffdsfff/zeus,sdgdsffdsfff/zeus,ctripcorp/zeus,ctripcorp/zeus,ctripcorp/zeus,ctripcorp/zeus,sdgdsffdsfff/zeus,sdgdsffdsfff/zeus,sdgdsffdsfff/zeus | package com.ctrip.zeus.client;
import com.ctrip.zeus.nginx.entity.NginxResponse;
import com.ctrip.zeus.nginx.entity.UpstreamStatus;
import com.ctrip.zeus.nginx.transform.DefaultJsonParser;
import com.netflix.config.DynamicIntProperty;
import com.netflix.config.DynamicPropertyFactory;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.IOException;
/**
* Created by fanqq on 2015/4/28.
*/
public class LocalClient {
private static final String LOCALHOST = "http://127.0.0.1";
//TODO unify port get
private static final DynamicIntProperty nginxDyupsPort = DynamicPropertyFactory.getInstance().getIntProperty("dyups.port", 8081);
private static final DynamicIntProperty nginxStatusPort = DynamicPropertyFactory.getInstance().getIntProperty("slb.nginx.status-port", 10001);
private static final DynamicIntProperty nginxDyupsTimeout = DynamicPropertyFactory.getInstance().getIntProperty("nginx.dyups.read.timeout", 500);
private static final LocalClient localClient = new LocalClient();
public static LocalClient getInstance() {
return localClient;
}
private final NginxDyupsClient dyupsClient;
private final NginxStatusClient statusClient;
private UpstreamStatus upstreamStatus = null;
public LocalClient() {
dyupsClient = new NginxDyupsClient();
statusClient = new NginxStatusClient();
}
protected LocalClient(String host) {
dyupsClient = new NginxDyupsClient(host + ":" + nginxDyupsPort.get(), nginxDyupsTimeout.get());
statusClient = new NginxStatusClient(host + ":" + nginxStatusPort.get());
}
public synchronized NginxResponse dyups(String upsName, String upsCommands) throws IOException {
Response responseStr = dyupsClient.getTarget().path("/upstream/" + upsName).request().post(Entity.entity(upsCommands,
MediaType.APPLICATION_JSON
));
if (responseStr.getStatus() == 200) {
return new NginxResponse().setSucceed(true).setOutMsg(responseStr.getEntity().toString());
} else {
return new NginxResponse().setSucceed(false).setErrMsg(responseStr.getEntity().toString());
}
}
public UpstreamStatus getUpstreamStatus() throws IOException {
String result = statusClient.getTarget().path("/status.json").request().get(String.class);
upstreamStatus = DefaultJsonParser.parse(UpstreamStatus.class, result);
return upstreamStatus;
}
public String getStubStatus() {
return statusClient.getTarget().path("/stub_status").request().get(String.class);
}
public String getReqStatuses() {
return statusClient.getTarget().path("/req_status").request().get(String.class);
}
private class NginxDyupsClient extends AbstractRestClient {
public NginxDyupsClient() {
this(LOCALHOST + ":" + nginxDyupsPort.get(), nginxDyupsTimeout.get());
}
protected NginxDyupsClient(String url, int timeout) {
super(url, timeout);
}
}
private class NginxStatusClient extends AbstractRestClient {
public NginxStatusClient() {
this(LOCALHOST + ":" + nginxStatusPort.get());
}
protected NginxStatusClient(String url) {
super(url);
}
}
}
| src/main/java/com/ctrip/zeus/client/LocalClient.java | package com.ctrip.zeus.client;
import com.ctrip.zeus.nginx.entity.NginxResponse;
import com.ctrip.zeus.nginx.entity.UpstreamStatus;
import com.ctrip.zeus.nginx.transform.DefaultJsonParser;
import com.netflix.config.DynamicIntProperty;
import com.netflix.config.DynamicPropertyFactory;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.IOException;
/**
* Created by fanqq on 2015/4/28.
*/
public class LocalClient {
private static final String LOCALHOST = "http://127.0.0.1";
private static final LocalClient localClient = new LocalClient();
public static LocalClient getInstance() {
return localClient;
}
//TODO unify port get
private static final DynamicIntProperty nginxDyupsPort = DynamicPropertyFactory.getInstance().getIntProperty("dyups.port", 8081);
private static final DynamicIntProperty nginxStatusPort = DynamicPropertyFactory.getInstance().getIntProperty("slb.nginx.status-port", 10001);
private static final DynamicIntProperty nginxDyupsTimeout = DynamicPropertyFactory.getInstance().getIntProperty("nginx.dyups.read.timeout", 500);
private final NginxDyupsClient dyupsClient;
private final NginxStatusClient statusClient;
private UpstreamStatus upstreamStatus = null;
public LocalClient() {
dyupsClient = new NginxDyupsClient();
statusClient = new NginxStatusClient();
}
protected LocalClient(String host) {
dyupsClient = new NginxDyupsClient(host + ":" + nginxDyupsPort.get(), nginxDyupsTimeout.get());
statusClient = new NginxStatusClient(host + ":" + nginxStatusPort.get());
}
public synchronized NginxResponse dyups(String upsName, String upsCommands) throws IOException {
Response responseStr = dyupsClient.getTarget().path("/upstream/" + upsName).request().post(Entity.entity(upsCommands,
MediaType.APPLICATION_JSON
));
if (responseStr.getStatus() == 200) {
return new NginxResponse().setSucceed(true).setOutMsg(responseStr.getEntity().toString());
} else {
return new NginxResponse().setSucceed(false).setErrMsg(responseStr.getEntity().toString());
}
}
public UpstreamStatus getUpstreamStatus() throws IOException {
String result = statusClient.getTarget().path("/status.json").request().get(String.class);
upstreamStatus = DefaultJsonParser.parse(UpstreamStatus.class, result);
return upstreamStatus;
}
public String getStubStatus() {
return statusClient.getTarget().path("/stub_status").request().get(String.class);
}
public String getReqStatuses() {
return statusClient.getTarget().path("/req_status").request().get(String.class);
}
private class NginxDyupsClient extends AbstractRestClient {
public NginxDyupsClient() {
this(LOCALHOST + ":" + nginxDyupsPort.get(), nginxDyupsTimeout.get());
}
protected NginxDyupsClient(String url, int timeout) {
super(url, timeout);
}
}
private class NginxStatusClient extends AbstractRestClient {
public NginxStatusClient() {
this(LOCALHOST + ":" + nginxStatusPort.get());
}
protected NginxStatusClient(String url) {
super(url);
}
}
}
| fix local client init prob
| src/main/java/com/ctrip/zeus/client/LocalClient.java | fix local client init prob | <ide><path>rc/main/java/com/ctrip/zeus/client/LocalClient.java
<ide> */
<ide> public class LocalClient {
<ide> private static final String LOCALHOST = "http://127.0.0.1";
<del> private static final LocalClient localClient = new LocalClient();
<del>
<del> public static LocalClient getInstance() {
<del> return localClient;
<del> }
<ide>
<ide> //TODO unify port get
<ide> private static final DynamicIntProperty nginxDyupsPort = DynamicPropertyFactory.getInstance().getIntProperty("dyups.port", 8081);
<ide> private static final DynamicIntProperty nginxStatusPort = DynamicPropertyFactory.getInstance().getIntProperty("slb.nginx.status-port", 10001);
<ide>
<ide> private static final DynamicIntProperty nginxDyupsTimeout = DynamicPropertyFactory.getInstance().getIntProperty("nginx.dyups.read.timeout", 500);
<add>
<add> private static final LocalClient localClient = new LocalClient();
<add>
<add> public static LocalClient getInstance() {
<add> return localClient;
<add> }
<ide>
<ide> private final NginxDyupsClient dyupsClient;
<ide> private final NginxStatusClient statusClient; |
|
Java | apache-2.0 | 35a646fae2d0d59702cd955a7e15c95cd58f5401 | 0 | xquery/marklogic-sesame,xquery/marklogic-sesame,marklogic/marklogic-sesame,marklogic/marklogic-sesame,xquery/marklogic-sesame,marklogic/marklogic-sesame | /*
* Copyright 2015-2016 MarkLogic Corporation
*
* 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.
*/
/**
* A library that enables access to a MarkLogic-backed triple-store via the
* Sesame API.
*/
package com.marklogic.semantics.sesame.client;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.marklogic.client.DatabaseClient;
import com.marklogic.client.DatabaseClientFactory;
import com.marklogic.client.FailedRequestException;
import com.marklogic.client.Transaction;
import com.marklogic.client.impl.SPARQLBindingsImpl;
import com.marklogic.client.io.FileHandle;
import com.marklogic.client.io.InputStreamHandle;
import com.marklogic.client.query.QueryDefinition;
import com.marklogic.client.semantics.*;
import com.marklogic.semantics.sesame.MarkLogicSesameException;
import org.openrdf.model.Literal;
import org.openrdf.model.Resource;
import org.openrdf.model.URI;
import org.openrdf.model.Value;
import org.openrdf.query.Binding;
import org.openrdf.repository.sparql.query.SPARQLQueryBindingSet;
import org.openrdf.rio.RDFFormat;
import org.openrdf.rio.RDFParseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
/**
* internal class for interacting with java api client
*
* @author James Fuller
*/
class MarkLogicClientImpl {
protected final Logger logger = LoggerFactory.getLogger(MarkLogicClientImpl.class);
private static final String DEFAULT_GRAPH_URI = "http://marklogic.com/semantics#default-graph";
private SPARQLRuleset[] ruleset;
private QueryDefinition constrainingQueryDef;
private GraphPermissions graphPerms;
private SPARQLQueryManager sparqlManager;
private GraphManager graphManager;
private DatabaseClient databaseClient;
/**
* constructor
*
* @param host
* @param port
* @param user
* @param password
* @param auth
*/
public MarkLogicClientImpl(String host, int port, String user, String password, String auth) {
setDatabaseClient(DatabaseClientFactory.newClient(host, port, user, password, DatabaseClientFactory.Authentication.valueOf(auth)));
}
/**
* set databaseclient
*
* @param databaseClient
*/
public MarkLogicClientImpl(DatabaseClient databaseClient) {
setDatabaseClient(databaseClient);
}
/**
* set databaseclient and instantate related managers
*
* @param databaseClient
*/
private void setDatabaseClient(DatabaseClient databaseClient) {
this.databaseClient = databaseClient;
this.sparqlManager = getDatabaseClient().newSPARQLQueryManager();
this.graphManager = getDatabaseClient().newGraphManager();
}
/**
* gets database client
*
* @return DatabaseClient
*/
public DatabaseClient getDatabaseClient() {
return this.databaseClient;
}
/**
* executes SPARQLQuery
*
* @param queryString
* @param bindings
* @param start
* @param pageLength
* @param tx
* @param includeInferred
* @param baseURI
* @return
* @throws JsonProcessingException
*/
public InputStream performSPARQLQuery(String queryString, SPARQLQueryBindingSet bindings, long start, long pageLength, Transaction tx, boolean includeInferred, String baseURI) throws JsonProcessingException {
return performSPARQLQuery(queryString, bindings, new InputStreamHandle(), start, pageLength, tx, includeInferred, baseURI);
}
/**
* executes SPARQLQuery
*
* @param queryString
* @param bindings
* @param handle
* @param start
* @param pageLength
* @param tx
* @param includeInferred
* @param baseURI
* @return
* @throws JsonProcessingException
*/
public InputStream performSPARQLQuery(String queryString, SPARQLQueryBindingSet bindings, InputStreamHandle handle, long start, long pageLength, Transaction tx, boolean includeInferred, String baseURI) throws JsonProcessingException {
SPARQLQueryDefinition qdef = sparqlManager.newQueryDefinition(queryString);
if(notNull(baseURI) && baseURI != ""){ qdef.setBaseUri(baseURI);}
if (notNull(ruleset)){qdef.setRulesets(ruleset);}
if (notNull(getConstrainingQueryDefinition())) {qdef.setConstrainingQueryDefinition(getConstrainingQueryDefinition());}
qdef.setIncludeDefaultRulesets(includeInferred);
if(notNull(graphPerms)){ qdef.setUpdatePermissions(graphPerms);}
if(pageLength > 0){
sparqlManager.setPageLength(pageLength);
}else{
//sparqlManager.clearPageLength();
}
sparqlManager.executeSelect(qdef, handle, start, tx);
InputStream in = new BufferedInputStream(handle.get());
return in;
}
/**
* executes GraphQuery
* @param queryString
* @param bindings
* @param tx
* @param includeInferred
* @param baseURI
* @return
* @throws JsonProcessingException
*/
public InputStream performGraphQuery(String queryString, SPARQLQueryBindingSet bindings, Transaction tx, boolean includeInferred, String baseURI) throws JsonProcessingException {
return performGraphQuery(queryString, bindings, new InputStreamHandle(), tx, includeInferred, baseURI);
}
/**
* executes GraphQuery
*
* @param queryString
* @param bindings
* @param handle
* @param tx
* @param includeInferred
* @param baseURI
* @return
* @throws JsonProcessingException
*/
public InputStream performGraphQuery(String queryString, SPARQLQueryBindingSet bindings, InputStreamHandle handle, Transaction tx, boolean includeInferred, String baseURI) throws JsonProcessingException {
SPARQLQueryDefinition qdef = sparqlManager.newQueryDefinition(queryString);
if(notNull(baseURI) && baseURI != ""){ qdef.setBaseUri(baseURI);}
if (notNull(ruleset)) {qdef.setRulesets(ruleset);}
if (notNull(getConstrainingQueryDefinition())){qdef.setConstrainingQueryDefinition(getConstrainingQueryDefinition());}
if(notNull(graphPerms)){ qdef.setUpdatePermissions(graphPerms);}
qdef.setIncludeDefaultRulesets(includeInferred);
sparqlManager.executeDescribe(qdef, handle, tx);
InputStream in = new BufferedInputStream(handle.get());
return in;
}
/**
* executes BooleanQuery
*
* @param queryString
* @param bindings
* @param tx
* @param includeInferred
* @param baseURI
* @return
*/
public boolean performBooleanQuery(String queryString, SPARQLQueryBindingSet bindings, Transaction tx, boolean includeInferred, String baseURI) {
SPARQLQueryDefinition qdef = sparqlManager.newQueryDefinition(queryString);
if(notNull(baseURI) && baseURI != ""){ qdef.setBaseUri(baseURI);}
qdef.setIncludeDefaultRulesets(includeInferred);
if (notNull(ruleset)) {qdef.setRulesets(ruleset);}
if (notNull(getConstrainingQueryDefinition())){qdef.setConstrainingQueryDefinition(getConstrainingQueryDefinition());}
if(notNull(graphPerms)){ qdef.setUpdatePermissions(graphPerms);}
return sparqlManager.executeAsk(qdef,tx);
}
/**
* executes UpdateQuery
*
* @param queryString
* @param bindings
* @param tx
* @param includeInferred
* @param baseURI
*/
public void performUpdateQuery(String queryString, SPARQLQueryBindingSet bindings, Transaction tx, boolean includeInferred, String baseURI) {
SPARQLQueryDefinition qdef = sparqlManager.newQueryDefinition(queryString);
if(notNull(baseURI) && baseURI != ""){ qdef.setBaseUri(baseURI);}
if (notNull(ruleset) ) {qdef.setRulesets(ruleset);}
if(notNull(graphPerms)){ qdef.setUpdatePermissions(graphPerms);}
qdef.setIncludeDefaultRulesets(includeInferred);
sparqlManager.clearPageLength();
sparqlManager.executeUpdate(qdef, tx);
}
/**
* executes merge of triples from File
*
* @param file
* @param baseURI
* @param dataFormat
* @param tx
* @param contexts
* @throws RDFParseException
*/
// performAdd
// as we use mergeGraphs, baseURI is always file.toURI
public void performAdd(File file, String baseURI, RDFFormat dataFormat, Transaction tx, Resource... contexts) throws RDFParseException {
try {
graphManager.setDefaultMimetype(dataFormat.getDefaultMIMEType());
if (dataFormat.equals(RDFFormat.NQUADS) || dataFormat.equals(RDFFormat.TRIG)) {
graphManager.mergeGraphs(new FileHandle(file),tx);
} else {
if (notNull(contexts) && contexts.length>0) {
for (int i = 0; i < contexts.length; i++) {
if(notNull(contexts[i])){
graphManager.mergeAs(contexts[i].toString(), new FileHandle(file), getGraphPerms(),tx);
}else{
graphManager.mergeAs(DEFAULT_GRAPH_URI, new FileHandle(file),getGraphPerms(), tx);
}
}
} else {
graphManager.mergeAs(DEFAULT_GRAPH_URI, new FileHandle(file), getGraphPerms(),tx);
}
}
} catch (FailedRequestException e) {
throw new RDFParseException("Request to MarkLogic server failed, check file and format.");
}
}
/**
* executes merge of triples from InputStream
*
* @param in
* @param baseURI
* @param dataFormat
* @param tx
* @param contexts
* @throws RDFParseException
*/
public void performAdd(InputStream in, String baseURI, RDFFormat dataFormat, Transaction tx, Resource... contexts) throws RDFParseException {
try {
graphManager.setDefaultMimetype(dataFormat.getDefaultMIMEType());
if (dataFormat.equals(RDFFormat.NQUADS) || dataFormat.equals(RDFFormat.TRIG)) {
graphManager.mergeGraphs(new InputStreamHandle(in),tx);
} else {
if (notNull(contexts) && contexts.length > 0) {
for (int i = 0; i < contexts.length; i++) {
if (notNull(contexts[i])) {
graphManager.mergeAs(contexts[i].toString(), new InputStreamHandle(in), getGraphPerms(), tx);
} else {
graphManager.mergeAs(DEFAULT_GRAPH_URI, new InputStreamHandle(in),getGraphPerms(), tx);
}
}
} else {
graphManager.mergeAs(DEFAULT_GRAPH_URI, new InputStreamHandle(in),getGraphPerms(), tx);
}
}
} catch (FailedRequestException e) {
throw new RDFParseException("Request to MarkLogic server failed, check input is valid.");
}
}
/**
* executes INSERT of single triple
*
* @param baseURI
* @param subject
* @param predicate
* @param object
* @param tx
* @param contexts
* @throws MarkLogicSesameException
*/
public void performAdd(String baseURI, Resource subject, URI predicate, Value object, Transaction tx, Resource... contexts) throws MarkLogicSesameException {
StringBuilder sb = new StringBuilder();
if(notNull(contexts) && contexts.length>0) {
if (notNull(baseURI)) sb.append("BASE <" + baseURI + ">\n");
sb.append("INSERT DATA { ");
for (int i = 0; i < contexts.length; i++) {
if (notNull(contexts[i])) {
sb.append("GRAPH <" + contexts[i].stringValue() + "> { ?s ?p ?o .} ");
} else {
sb.append("GRAPH <" + DEFAULT_GRAPH_URI + "> { ?s ?p ?o .} ");
}
}
sb.append("}");
} else {
sb.append("INSERT DATA { GRAPH <" + DEFAULT_GRAPH_URI + "> {?s ?p ?o .}}");
}
SPARQLQueryDefinition qdef = sparqlManager.newQueryDefinition(sb.toString());
if (notNull(ruleset) ) {qdef.setRulesets(ruleset);}
if(notNull(graphPerms)){ qdef.setUpdatePermissions(graphPerms);}
if(notNull(baseURI) && baseURI != ""){ qdef.setBaseUri(baseURI);}
if(notNull(subject)) qdef.withBinding("s", subject.stringValue());
if(notNull(predicate)) qdef.withBinding("p", predicate.stringValue());
if(notNull(object)) bindObject(qdef, "o", object);
sparqlManager.executeUpdate(qdef, tx);
}
/**
* executes DELETE of single triple
*
* @param baseURI
* @param subject
* @param predicate
* @param object
* @param tx
* @param contexts
* @throws MarkLogicSesameException
*/
public void performRemove(String baseURI, Resource subject, URI predicate, Value object, Transaction tx, Resource... contexts) throws MarkLogicSesameException {
StringBuilder sb = new StringBuilder();
if(notNull(contexts) && contexts.length>0) {
if (notNull(baseURI))sb.append("BASE <" + baseURI + ">\n");
sb.append("DELETE WHERE { ");
for (int i = 0; i < contexts.length; i++) {
if (notNull(contexts[i])) {
sb.append("GRAPH <" + contexts[i].stringValue() + "> { ?s ?p ?o .} ");
} else {
sb.append("GRAPH <" + DEFAULT_GRAPH_URI + "> { ?s ?p ?o .} ");
}
}
sb.append("}");
}else{
sb.append("DELETE WHERE { GRAPH ?ctx { ?s ?p ?o .}}");
}
SPARQLQueryDefinition qdef = sparqlManager.newQueryDefinition(sb.toString());
if(notNull(baseURI) && baseURI != ""){ qdef.setBaseUri(baseURI);}
if(notNull(subject)) qdef.withBinding("s", subject.stringValue());
if(notNull(predicate)) qdef.withBinding("p", predicate.stringValue());
if(notNull(object)) bindObject(qdef, "o", object);
sparqlManager.executeUpdate(qdef, tx);
}
/**
* clears triples from named graph
*
* @param tx
* @param contexts
*/
public void performClear(Transaction tx, Resource... contexts) {
if(notNull(contexts)) {
for (int i = 0; i < contexts.length; i++) {
if (notNull(contexts[i])) {
graphManager.delete(contexts[i].stringValue(), tx);
} else {
graphManager.delete(DEFAULT_GRAPH_URI, tx);
}
}
}else{
graphManager.delete(DEFAULT_GRAPH_URI, tx);
}
}
/**
* clears all triples
*
* @param tx
*/
public void performClearAll(Transaction tx) {
graphManager.deleteGraphs(tx);
}
/**
* getter rulesets
*
* @return
*/
public SPARQLRuleset[] getRulesets() {
return this.ruleset;
}
/**
* setter for rulesets, filters out nulls
*
* @param rulesets
*/
public void setRulesets(SPARQLRuleset ... rulesets) {
if(notNull(rulesets)) {
List<SPARQLRuleset> list = new ArrayList<>();
for(Object r : rulesets) {
if(r != null && rulesets.length > 0) {
list.add((SPARQLRuleset)r);
}
}
this.ruleset = list.toArray(new SPARQLRuleset[list.size()]);
}else{
this.ruleset = null;
}
}
/**
* setter for graph permissions
*
* @param graphPerms
*/
public void setGraphPerms(GraphPermissions graphPerms) {
this.graphPerms = graphPerms;
}
/**
* getter for graph permissions
*
* @return
*/
public GraphPermissions getGraphPerms() {
return this.graphPerms;
}
/**
* setter for ConstrainingQueryDefinition
*
* @param constrainingQueryDefinition
*/
public void setConstrainingQueryDefinition(QueryDefinition constrainingQueryDefinition) {
this.constrainingQueryDef = constrainingQueryDefinition;
}
/**
* getter for ConstrainingQueryDefinition
*
* @return
*/
public QueryDefinition getConstrainingQueryDefinition() {
return this.constrainingQueryDef;
}
///////////////////////////////////////////////////////////////////////////////////////////////
/**
* converts Sesame BindingSet to java api client SPARQLBindings
*
* @param bindings
* @return
*/
protected SPARQLBindings getSPARQLBindings(SPARQLQueryBindingSet bindings) {
SPARQLBindings sps = new SPARQLBindingsImpl();
for (Binding binding : bindings) {
sps.bind(binding.getName(), binding.getValue().stringValue());
}
return sps;
}
///////////////////////////////////////////////////////////////////////////////////////////////
/**
* bind object
*
* @param qdef
* @param variableName
* @param object
* @return
* @throws MarkLogicSesameException
*/
private static SPARQLQueryDefinition bindObject(SPARQLQueryDefinition qdef, String variableName, Value object) throws MarkLogicSesameException{
SPARQLBindings bindings = qdef.getBindings();
if(object != null){
if (object instanceof URI) {
bindings.bind(variableName, object.stringValue());
} else if (object instanceof Literal) {
Literal lit = (Literal) object;
if (lit.getLanguage() != null) {
String languageTag = lit.getLanguage();
bindings.bind(variableName, lit.getLabel(), Locale.forLanguageTag(languageTag));
}else if (((Literal) object).getDatatype() != null) {
try {
String xsdType = lit.getDatatype().toString();
String fragment = new java.net.URI(xsdType).getFragment();
bindings.bind(variableName,lit.getLabel(),RDFTypes.valueOf(fragment.toUpperCase()));
} catch (URISyntaxException e) {
throw new MarkLogicSesameException("Problem with object datatype.");
}
}else {
// assume we have a string value
bindings.bind(variableName, lit.getLabel(), RDFTypes.STRING);
}
}
qdef.setBindings(bindings);
}
return qdef;
}
/**
* tedious utility for checking if object is null or not
*
* @param item
* @return
*/
private static Boolean notNull(Object item) {
if (item!=null)
return true;
else
return false;
}
} | marklogic-sesame/src/main/java/com/marklogic/semantics/sesame/client/MarkLogicClientImpl.java | /*
* Copyright 2015-2016 MarkLogic Corporation
*
* 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.
*/
/**
* A library that enables access to a MarkLogic-backed triple-store via the
* Sesame API.
*/
package com.marklogic.semantics.sesame.client;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.marklogic.client.DatabaseClient;
import com.marklogic.client.DatabaseClientFactory;
import com.marklogic.client.FailedRequestException;
import com.marklogic.client.Transaction;
import com.marklogic.client.impl.SPARQLBindingsImpl;
import com.marklogic.client.io.FileHandle;
import com.marklogic.client.io.InputStreamHandle;
import com.marklogic.client.query.QueryDefinition;
import com.marklogic.client.semantics.*;
import com.marklogic.semantics.sesame.MarkLogicSesameException;
import org.openrdf.model.Literal;
import org.openrdf.model.Resource;
import org.openrdf.model.URI;
import org.openrdf.model.Value;
import org.openrdf.query.Binding;
import org.openrdf.repository.sparql.query.SPARQLQueryBindingSet;
import org.openrdf.rio.RDFFormat;
import org.openrdf.rio.RDFParseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
/**
* internal class for interacting with java api client
*
* @author James Fuller
*/
class MarkLogicClientImpl {
protected final Logger logger = LoggerFactory.getLogger(MarkLogicClientImpl.class);
private static final String DEFAULT_GRAPH_URI = "http://marklogic.com/semantics#default-graph";
private SPARQLRuleset[] ruleset;
private QueryDefinition constrainingQueryDef;
private GraphPermissions graphPerms;
private SPARQLQueryManager sparqlManager;
private GraphManager graphManager;
private DatabaseClient databaseClient;
/**
* constructor
*
* @param host
* @param port
* @param user
* @param password
* @param auth
*/
public MarkLogicClientImpl(String host, int port, String user, String password, String auth) {
setDatabaseClient(DatabaseClientFactory.newClient(host, port, user, password, DatabaseClientFactory.Authentication.valueOf(auth)));
}
/**
* set databaseclient
*
* @param databaseClient
*/
public MarkLogicClientImpl(DatabaseClient databaseClient) {
setDatabaseClient(databaseClient);
}
/**
* set databaseclient and instantate related managers
*
* @param databaseClient
*/
private void setDatabaseClient(DatabaseClient databaseClient) {
this.databaseClient = databaseClient;
this.sparqlManager = getDatabaseClient().newSPARQLQueryManager();
this.graphManager = getDatabaseClient().newGraphManager();
}
/**
* gets database client
*
* @return DatabaseClient
*/
public DatabaseClient getDatabaseClient() {
return this.databaseClient;
}
/**
* executes SPARQLQuery
*
* @param queryString
* @param bindings
* @param start
* @param pageLength
* @param tx
* @param includeInferred
* @param baseURI
* @return
* @throws JsonProcessingException
*/
public InputStream performSPARQLQuery(String queryString, SPARQLQueryBindingSet bindings, long start, long pageLength, Transaction tx, boolean includeInferred, String baseURI) throws JsonProcessingException {
return performSPARQLQuery(queryString, bindings, new InputStreamHandle(), start, pageLength, tx, includeInferred, baseURI);
}
/**
* executes SPARQLQuery
*
* @param queryString
* @param bindings
* @param handle
* @param start
* @param pageLength
* @param tx
* @param includeInferred
* @param baseURI
* @return
* @throws JsonProcessingException
*/
public InputStream performSPARQLQuery(String queryString, SPARQLQueryBindingSet bindings, InputStreamHandle handle, long start, long pageLength, Transaction tx, boolean includeInferred, String baseURI) throws JsonProcessingException {
SPARQLQueryDefinition qdef = sparqlManager.newQueryDefinition(queryString);
if(notNull(baseURI) && baseURI != ""){ qdef.setBaseUri(baseURI);}
if (notNull(ruleset)){qdef.setRulesets(ruleset);}
if (notNull(getConstrainingQueryDefinition())) {qdef.setConstrainingQueryDefinition(getConstrainingQueryDefinition());}
qdef.setIncludeDefaultRulesets(includeInferred);
if(notNull(graphPerms)){ qdef.setUpdatePermissions(graphPerms);}
if(pageLength > 0){
sparqlManager.setPageLength(pageLength);
}else{
//sparqlManager.clearPageLength();
}
sparqlManager.executeSelect(qdef, handle, start, tx);
InputStream in = new BufferedInputStream(handle.get());
return in;
}
/**
* executes GraphQuery
* @param queryString
* @param bindings
* @param tx
* @param includeInferred
* @param baseURI
* @return
* @throws JsonProcessingException
*/
public InputStream performGraphQuery(String queryString, SPARQLQueryBindingSet bindings, Transaction tx, boolean includeInferred, String baseURI) throws JsonProcessingException {
return performGraphQuery(queryString, bindings, new InputStreamHandle(), tx, includeInferred, baseURI);
}
/**
* executes GraphQuery
*
* @param queryString
* @param bindings
* @param handle
* @param tx
* @param includeInferred
* @param baseURI
* @return
* @throws JsonProcessingException
*/
public InputStream performGraphQuery(String queryString, SPARQLQueryBindingSet bindings, InputStreamHandle handle, Transaction tx, boolean includeInferred, String baseURI) throws JsonProcessingException {
SPARQLQueryDefinition qdef = sparqlManager.newQueryDefinition(queryString);
if(notNull(baseURI) && baseURI != ""){ qdef.setBaseUri(baseURI);}
if (notNull(ruleset)) {qdef.setRulesets(ruleset);}
if (notNull(getConstrainingQueryDefinition())){qdef.setConstrainingQueryDefinition(getConstrainingQueryDefinition());}
if(notNull(graphPerms)){ qdef.setUpdatePermissions(graphPerms);}
qdef.setIncludeDefaultRulesets(includeInferred);
sparqlManager.executeDescribe(qdef, handle, tx);
InputStream in = new BufferedInputStream(handle.get());
return in;
}
/**
* executes BooleanQuery
*
* @param queryString
* @param bindings
* @param tx
* @param includeInferred
* @param baseURI
* @return
*/
public boolean performBooleanQuery(String queryString, SPARQLQueryBindingSet bindings, Transaction tx, boolean includeInferred, String baseURI) {
SPARQLQueryDefinition qdef = sparqlManager.newQueryDefinition(queryString);
if(notNull(baseURI) && baseURI != ""){ qdef.setBaseUri(baseURI);}
qdef.setIncludeDefaultRulesets(includeInferred);
if (notNull(ruleset)) {qdef.setRulesets(ruleset);}
if (notNull(getConstrainingQueryDefinition())){qdef.setConstrainingQueryDefinition(getConstrainingQueryDefinition());}
if(notNull(graphPerms)){ qdef.setUpdatePermissions(graphPerms);}
return sparqlManager.executeAsk(qdef,tx);
}
/**
* executes UpdateQuery
*
* @param queryString
* @param bindings
* @param tx
* @param includeInferred
* @param baseURI
*/
public void performUpdateQuery(String queryString, SPARQLQueryBindingSet bindings, Transaction tx, boolean includeInferred, String baseURI) {
SPARQLQueryDefinition qdef = sparqlManager.newQueryDefinition(queryString);
if(notNull(baseURI) && baseURI != ""){ qdef.setBaseUri(baseURI);}
if (notNull(ruleset) ) {qdef.setRulesets(ruleset);}
// constraining query unused when adding triple
//if (notNull(getConstrainingQueryDefinition())){qdef.setConstrainingQueryDefinition(getConstrainingQueryDefinition());}
if(notNull(graphPerms)){ qdef.setUpdatePermissions(graphPerms);}
qdef.setIncludeDefaultRulesets(includeInferred);
sparqlManager.clearPageLength();
sparqlManager.executeUpdate(qdef, tx);
}
/**
* executes merge of triples from File
*
* @param file
* @param baseURI
* @param dataFormat
* @param tx
* @param contexts
* @throws RDFParseException
*/
// performAdd
// as we use mergeGraphs, baseURI is always file.toURI
public void performAdd(File file, String baseURI, RDFFormat dataFormat, Transaction tx, Resource... contexts) throws RDFParseException {
try {
graphManager.setDefaultMimetype(dataFormat.getDefaultMIMEType());
if (dataFormat.equals(RDFFormat.NQUADS) || dataFormat.equals(RDFFormat.TRIG)) {
graphManager.mergeGraphs(new FileHandle(file),tx);
} else {
if (notNull(contexts) && contexts.length>0) {
for (int i = 0; i < contexts.length; i++) {
if(notNull(contexts[i])){
graphManager.mergeAs(contexts[i].toString(), new FileHandle(file), getGraphPerms(),tx);
}else{
graphManager.mergeAs(DEFAULT_GRAPH_URI, new FileHandle(file),getGraphPerms(), tx);
}
}
} else {
graphManager.mergeAs(DEFAULT_GRAPH_URI, new FileHandle(file), getGraphPerms(),tx);
}
}
} catch (FailedRequestException e) {
throw new RDFParseException("Request to MarkLogic server failed, check file and format.");
}
}
/**
* executes merge of triples from InputStream
*
* @param in
* @param baseURI
* @param dataFormat
* @param tx
* @param contexts
* @throws RDFParseException
*/
public void performAdd(InputStream in, String baseURI, RDFFormat dataFormat, Transaction tx, Resource... contexts) throws RDFParseException {
try {
graphManager.setDefaultMimetype(dataFormat.getDefaultMIMEType());
if (dataFormat.equals(RDFFormat.NQUADS) || dataFormat.equals(RDFFormat.TRIG)) {
graphManager.mergeGraphs(new InputStreamHandle(in),tx);
} else {
if (notNull(contexts) && contexts.length > 0) {
for (int i = 0; i < contexts.length; i++) {
if (notNull(contexts[i])) {
graphManager.mergeAs(contexts[i].toString(), new InputStreamHandle(in), getGraphPerms(), tx);
} else {
graphManager.mergeAs(DEFAULT_GRAPH_URI, new InputStreamHandle(in),getGraphPerms(), tx);
}
}
} else {
graphManager.mergeAs(DEFAULT_GRAPH_URI, new InputStreamHandle(in),getGraphPerms(), tx);
}
}
} catch (FailedRequestException e) {
throw new RDFParseException("Request to MarkLogic server failed, check input is valid.");
}
}
/**
* executes INSERT of single triple
*
* @param baseURI
* @param subject
* @param predicate
* @param object
* @param tx
* @param contexts
* @throws MarkLogicSesameException
*/
public void performAdd(String baseURI, Resource subject, URI predicate, Value object, Transaction tx, Resource... contexts) throws MarkLogicSesameException {
StringBuilder sb = new StringBuilder();
if(notNull(contexts) && contexts.length>0) {
if (notNull(baseURI)) sb.append("BASE <" + baseURI + ">\n");
sb.append("INSERT DATA { ");
for (int i = 0; i < contexts.length; i++) {
if (notNull(contexts[i])) {
sb.append("GRAPH <" + contexts[i].stringValue() + "> { ?s ?p ?o .} ");
} else {
sb.append("GRAPH <" + DEFAULT_GRAPH_URI + "> { ?s ?p ?o .} ");
}
}
sb.append("}");
} else {
sb.append("INSERT DATA { GRAPH <" + DEFAULT_GRAPH_URI + "> {?s ?p ?o .}}");
}
SPARQLQueryDefinition qdef = sparqlManager.newQueryDefinition(sb.toString());
if (notNull(ruleset) ) {qdef.setRulesets(ruleset);}
// constraining query unused when adding triple
//if (notNull(getConstrainingQueryDefinition())){qdef.setConstrainingQueryDefinition(getConstrainingQueryDefinition());}
if(notNull(graphPerms)){ qdef.setUpdatePermissions(graphPerms);}
if(notNull(baseURI) && baseURI != ""){ qdef.setBaseUri(baseURI);}
if(notNull(subject)) qdef.withBinding("s", subject.stringValue());
if(notNull(predicate)) qdef.withBinding("p", predicate.stringValue());
if(notNull(object)) bindObject(qdef, "o", object);
sparqlManager.executeUpdate(qdef, tx);
}
/**
* executes DELETE of single triple
*
* @param baseURI
* @param subject
* @param predicate
* @param object
* @param tx
* @param contexts
* @throws MarkLogicSesameException
*/
public void performRemove(String baseURI, Resource subject, URI predicate, Value object, Transaction tx, Resource... contexts) throws MarkLogicSesameException {
StringBuilder sb = new StringBuilder();
if(notNull(contexts) && contexts.length>0) {
if (notNull(baseURI))sb.append("BASE <" + baseURI + ">\n");
sb.append("DELETE WHERE { ");
for (int i = 0; i < contexts.length; i++) {
if (notNull(contexts[i])) {
sb.append("GRAPH <" + contexts[i].stringValue() + "> { ?s ?p ?o .} ");
} else {
sb.append("GRAPH <" + DEFAULT_GRAPH_URI + "> { ?s ?p ?o .} ");
}
}
sb.append("}");
}else{
sb.append("DELETE WHERE { GRAPH ?ctx { ?s ?p ?o .}}");
}
SPARQLQueryDefinition qdef = sparqlManager.newQueryDefinition(sb.toString());
if(notNull(baseURI) && baseURI != ""){ qdef.setBaseUri(baseURI);}
if(notNull(subject)) qdef.withBinding("s", subject.stringValue());
if(notNull(predicate)) qdef.withBinding("p", predicate.stringValue());
if(notNull(object)) bindObject(qdef, "o", object);
sparqlManager.executeUpdate(qdef, tx);
}
/**
* clears triples from named graph
*
* @param tx
* @param contexts
*/
public void performClear(Transaction tx, Resource... contexts) {
if(notNull(contexts)) {
for (int i = 0; i < contexts.length; i++) {
if (notNull(contexts[i])) {
graphManager.delete(contexts[i].stringValue(), tx);
} else {
graphManager.delete(DEFAULT_GRAPH_URI, tx);
}
}
}else{
graphManager.delete(DEFAULT_GRAPH_URI, tx);
}
}
/**
* clears all triples
*
* @param tx
*/
public void performClearAll(Transaction tx) {
graphManager.deleteGraphs();
}
/**
* getter rulesets
*
* @return
*/
public SPARQLRuleset[] getRulesets() {
return this.ruleset;
}
/**
* setter for rulesets, filters out nulls
*
* @param rulesets
*/
public void setRulesets(SPARQLRuleset ... rulesets) {
if(notNull(rulesets)) {
List<SPARQLRuleset> list = new ArrayList<>();
for(Object r : rulesets) {
if(r != null && rulesets.length > 0) {
list.add((SPARQLRuleset)r);
}
}
this.ruleset = list.toArray(new SPARQLRuleset[list.size()]);
}else{
this.ruleset = null;
}
}
/**
* setter for graph permissions
*
* @param graphPerms
*/
public void setGraphPerms(GraphPermissions graphPerms) {
this.graphPerms = graphPerms;
}
/**
* getter for graph permissions
*
* @return
*/
public GraphPermissions getGraphPerms() {
return this.graphPerms;
}
/**
* setter for ConstrainingQueryDefinition
*
* @param constrainingQueryDefinition
*/
public void setConstrainingQueryDefinition(QueryDefinition constrainingQueryDefinition) {
this.constrainingQueryDef = constrainingQueryDefinition;
}
/**
* getter for ConstrainingQueryDefinition
*
* @return
*/
public QueryDefinition getConstrainingQueryDefinition() {
return this.constrainingQueryDef;
}
///////////////////////////////////////////////////////////////////////////////////////////////
/**
* converts Sesame BindingSet to java api client SPARQLBindings
*
* @param bindings
* @return
*/
protected SPARQLBindings getSPARQLBindings(SPARQLQueryBindingSet bindings) {
SPARQLBindings sps = new SPARQLBindingsImpl();
for (Binding binding : bindings) {
sps.bind(binding.getName(), binding.getValue().stringValue());
}
return sps;
}
///////////////////////////////////////////////////////////////////////////////////////////////
/**
* bind object
*
* @param qdef
* @param variableName
* @param object
* @return
* @throws MarkLogicSesameException
*/
private static SPARQLQueryDefinition bindObject(SPARQLQueryDefinition qdef, String variableName, Value object) throws MarkLogicSesameException{
SPARQLBindings bindings = qdef.getBindings();
if(object != null){
if (object instanceof URI) {
bindings.bind(variableName, object.stringValue());
} else if (object instanceof Literal) {
Literal lit = (Literal) object;
if (lit.getLanguage() != null) {
String languageTag = lit.getLanguage();
bindings.bind(variableName, lit.getLabel(), Locale.forLanguageTag(languageTag));
}else if (((Literal) object).getDatatype() != null) {
try {
String xsdType = lit.getDatatype().toString();
String fragment = new java.net.URI(xsdType).getFragment();
bindings.bind(variableName,lit.getLabel(),RDFTypes.valueOf(fragment.toUpperCase()));
} catch (URISyntaxException e) {
throw new MarkLogicSesameException("Problem with object datatype.");
}
}else {
// assume we have a string value
bindings.bind(variableName, lit.getLabel(), RDFTypes.STRING);
}
}
qdef.setBindings(bindings);
}
return qdef;
}
/**
* tedious utility for checking if object is null or not
*
* @param item
* @return
*/
private static Boolean notNull(Object item) {
if (item!=null)
return true;
else
return false;
}
} | java api client now supports tx on delete all
| marklogic-sesame/src/main/java/com/marklogic/semantics/sesame/client/MarkLogicClientImpl.java | java api client now supports tx on delete all | <ide><path>arklogic-sesame/src/main/java/com/marklogic/semantics/sesame/client/MarkLogicClientImpl.java
<ide> SPARQLQueryDefinition qdef = sparqlManager.newQueryDefinition(queryString);
<ide> if(notNull(baseURI) && baseURI != ""){ qdef.setBaseUri(baseURI);}
<ide> if (notNull(ruleset) ) {qdef.setRulesets(ruleset);}
<del> // constraining query unused when adding triple
<del> //if (notNull(getConstrainingQueryDefinition())){qdef.setConstrainingQueryDefinition(getConstrainingQueryDefinition());}
<ide> if(notNull(graphPerms)){ qdef.setUpdatePermissions(graphPerms);}
<ide> qdef.setIncludeDefaultRulesets(includeInferred);
<ide> sparqlManager.clearPageLength();
<ide> }
<ide> SPARQLQueryDefinition qdef = sparqlManager.newQueryDefinition(sb.toString());
<ide> if (notNull(ruleset) ) {qdef.setRulesets(ruleset);}
<del> // constraining query unused when adding triple
<del> //if (notNull(getConstrainingQueryDefinition())){qdef.setConstrainingQueryDefinition(getConstrainingQueryDefinition());}
<ide> if(notNull(graphPerms)){ qdef.setUpdatePermissions(graphPerms);}
<ide> if(notNull(baseURI) && baseURI != ""){ qdef.setBaseUri(baseURI);}
<ide>
<ide> * @param tx
<ide> */
<ide> public void performClearAll(Transaction tx) {
<del> graphManager.deleteGraphs();
<add> graphManager.deleteGraphs(tx);
<ide> }
<ide>
<ide> /** |
|
Java | apache-2.0 | ef9da52c5ad22a53557ca2313c2b37ae9b7e2eef | 0 | HaStr/kieker,HaStr/kieker,kieker-monitoring/kieker,HaStr/kieker,HaStr/kieker,kieker-monitoring/kieker,leadwire-apm/leadwire-javaagent,leadwire-apm/leadwire-javaagent,kieker-monitoring/kieker,kieker-monitoring/kieker,kieker-monitoring/kieker,HaStr/kieker | /***************************************************************************
* Copyright 2014 Kieker Project (http://kieker-monitoring.net)
*
* 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 kieker.tools.tslib;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
* @author Andre van Hoorn, Tobias Rudolph, Andreas Eberlein
*
* @since 1.10
* @param <T>
* The type of the time series.
*/
public class TimeSeries<T> implements ITimeSeries<T> {
private volatile long startTime;
private final TimeUnit timeSeriesTimeUnit;
private long nextTime;
private final long deltaTime;
private final TimeUnit deltaTimeUnit;
private final int frequency;
private final int capacity;
private final TimeSeriesPointsBuffer<ITimeSeriesPoint<T>> points;
private final long timeSeriesStepSize;
/**
* @param startTime
* start time of Timeseries
* @param timeSeriesTimeUnit
* time unit of the startTime
* @param deltaTime
* time of timeseries
* @param deltaTimeUnit
* Time unit
* @param capacity
* length of timeseries
*/
public TimeSeries(final long startTime, final TimeUnit timeSeriesTimeUnit, final long deltaTime, final TimeUnit deltaTimeUnit, final int frequency,
final int capacity) {
this.startTime = startTime;
this.timeSeriesTimeUnit = timeSeriesTimeUnit;
this.deltaTime = deltaTime;
this.deltaTimeUnit = deltaTimeUnit;
this.frequency = frequency;
this.capacity = capacity;
this.timeSeriesStepSize = timeSeriesTimeUnit.convert(this.deltaTime, this.deltaTimeUnit);
if (ITimeSeries.INFINITE_CAPACITY == capacity) {
this.points = new TimeSeriesPointsBuffer<ITimeSeriesPoint<T>>();
} else {
this.points = new TimeSeriesPointsBuffer<ITimeSeriesPoint<T>>(this.capacity);
}
this.nextTime = this.startTime;
}
/**
* @param startTime
* start time of Timeseries
* @param timeSeriesTimeUnit
* time unit of the startTime
* @param deltaTime
* time of timeseries
* @param deltaTimeUnit
* Time unit
* @param capacity
* length of timeseries
*/
public TimeSeries(final long startTime, final TimeUnit timeSeriesTimeUnit, final long deltaTime, final TimeUnit deltaTimeUnit, final int capacity) {
// frequency = 24 best practice
this(startTime, timeSeriesTimeUnit, deltaTime, deltaTimeUnit, 24, capacity);
}
/**
* @param startTime
* start time of Timeseries
* @param timeSeriesTimeUnit
* time unit of the startTime
* @param deltaTime
* time of timeseries
* @param deltaTimeUnit
* Time unit
*/
public TimeSeries(final long startTime, final TimeUnit timeSeriesTimeUnit, final long deltaTime, final TimeUnit deltaTimeUnit) {
this(startTime, timeSeriesTimeUnit, deltaTime, deltaTimeUnit, ITimeSeries.INFINITE_CAPACITY);
}
/**
* Constructor using the timeunit as unit for internal usage and deltatime time unit.
* Furthermore using infinite capacity and a frequency of 24 by default.
*/
public TimeSeries(final long startTime, final TimeUnit timeUnit, final long deltaTime) {
this(startTime, timeUnit, deltaTime, timeUnit);
}
/**
* Constructor using the timeunit as unit for internal usage and deltatime time unit
*/
public TimeSeries(final long startTime, final TimeUnit timeUnit, final long deltaTime, final int frequency,
final int capacity) {
this(startTime, timeUnit, deltaTime, timeUnit, frequency, capacity);
}
public TimeSeries(final long startTime, final TimeUnit timeUnit, final long deltaTime, final int frequency) {
this(startTime, timeUnit, deltaTime, timeUnit, frequency, ITimeSeries.INFINITE_CAPACITY);
}
@Override
public long getStartTime() {
return this.startTime;
}
@Override
public TimeUnit getTimeSeriesTimeUnit() {
return this.timeSeriesTimeUnit;
}
@Override
public long getDeltaTime() {
return this.deltaTime;
}
@Override
public TimeUnit getDeltaTimeUnit() {
return this.deltaTimeUnit;
}
/**
* Returns the step size between each item in the timeseries. The {@link TimeUnit} of the stepSize is equal to the {@link #timeSeriesTimeUnit}.
*
* @return step size
*/
public long getStepSize() {
return this.timeSeriesStepSize;
}
/**
* @param value
* value which should append to timeseries
*
* @return tspoint
*/
@Override
public ITimeSeriesPoint<T> append(final T value) {
final ITimeSeriesPoint<T> point;
synchronized (value) {
point = new TimeSeriesPoint<T>(this.nextTime, value);
this.points.add(point);
this.startTime = this.points.peek().getTime(); // we have a bounded buffer so the first element might be gone
this.nextTime = this.nextTime + this.timeSeriesStepSize;
}
return point;
}
@Override
public List<ITimeSeriesPoint<T>> getPoints() {
return new ArrayList<ITimeSeriesPoint<T>>(this.points);
}
@Override
public List<T> getValues() {
final List<ITimeSeriesPoint<T>> pointsCopy = this.getPoints();
final List<T> retVals = new ArrayList<T>(pointsCopy.size());
for (final ITimeSeriesPoint<T> curPoint : pointsCopy) {
retVals.add(curPoint.getValue());
}
return retVals;
}
@Override
public int getCapacity() {
return this.capacity;
}
@Override
public int size() {
return this.points.getSize();
}
@Override
public long getEndTime() {
if (this.getPoints().isEmpty()) {
throw new IllegalStateException("The TimeSeries is empty, so no end time can be returned.");
} else {
return this.getStartTime() + (this.timeSeriesStepSize * (this.getPoints().size() - 1));
}
}
@Override
public List<ITimeSeriesPoint<T>> appendAll(final T[] values) {
final List<ITimeSeriesPoint<T>> retVals = new ArrayList<ITimeSeriesPoint<T>>(values.length);
for (final T value : values) {
retVals.add(this.append(value));
}
return retVals;
}
@Override
public String toString() {
final StringBuffer buf = new StringBuffer();
buf.append("Time Series with delta: " + this.deltaTime + " " + this.deltaTimeUnit + " starting at: " + this.getStartTime() + " " + this.timeSeriesTimeUnit);
for (final ITimeSeriesPoint<T> curPoint : this.getPoints()) {
buf.append(curPoint);
}
return buf.toString();
}
@Override
public int getFrequency() {
return this.frequency;
}
}
| src/tools/kieker/tools/tslib/TimeSeries.java | /***************************************************************************
* Copyright 2014 Kieker Project (http://kieker-monitoring.net)
*
* 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 kieker.tools.tslib;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
* @author Andre van Hoorn, Tobias Rudolph, Andreas Eberlein
*
* @since 1.10
* @param <T>
* The type of the time series.
*/
public class TimeSeries<T> implements ITimeSeries<T> {
private final long startTime;
private final TimeUnit timeSeriesTimeUnit;
private long nextTime;
private final long deltaTime;
private final TimeUnit deltaTimeUnit;
private final int frequency;
private final int capacity;
private final TimeSeriesPointsBuffer<ITimeSeriesPoint<T>> points;
private long timeSeriesStepSize;
/**
* @param startTime
* start time of Timeseries
* @param timeSeriesTimeUnit
* time unit of the startTime
* @param deltaTime
* time of timeseries
* @param deltaTimeUnit
* Time unit
* @param capacity
* length of timeseries
*/
public TimeSeries(final long startTime, final TimeUnit timeSeriesTimeUnit, final long deltaTime, final TimeUnit deltaTimeUnit, final int frequency,
final int capacity) {
this.startTime = startTime;
this.timeSeriesTimeUnit = timeSeriesTimeUnit;
this.deltaTime = deltaTime;
this.deltaTimeUnit = deltaTimeUnit;
this.frequency = frequency;
this.capacity = capacity;
this.timeSeriesStepSize = timeSeriesTimeUnit.convert(this.deltaTime, this.deltaTimeUnit);
if (ITimeSeries.INFINITE_CAPACITY == capacity) {
this.points = new TimeSeriesPointsBuffer<ITimeSeriesPoint<T>>();
} else {
this.points = new TimeSeriesPointsBuffer<ITimeSeriesPoint<T>>(this.capacity);
}
this.nextTime = this.startTime;
}
/**
* @param startTime
* start time of Timeseries
* @param timeSeriesTimeUnit
* time unit of the startTime
* @param deltaTime
* time of timeseries
* @param deltaTimeUnit
* Time unit
* @param capacity
* length of timeseries
*/
public TimeSeries(final long startTime, final TimeUnit timeSeriesTimeUnit, final long deltaTime, final TimeUnit deltaTimeUnit, final int capacity) {
// frequency = 24 best practice
this(startTime, timeSeriesTimeUnit, deltaTime, deltaTimeUnit, 24, capacity);
}
/**
* @param startTime
* start time of Timeseries
* @param timeSeriesTimeUnit
* time unit of the startTime
* @param deltaTime
* time of timeseries
* @param deltaTimeUnit
* Time unit
*/
public TimeSeries(final long startTime, final TimeUnit timeSeriesTimeUnit, final long deltaTime, final TimeUnit deltaTimeUnit) {
this(startTime, timeSeriesTimeUnit, deltaTime, deltaTimeUnit, ITimeSeries.INFINITE_CAPACITY);
}
/**
* Constructor using the timeunit as unit for internal usage and deltatime time unit.
* Furthermore using infinite capacity and a frequency of 24 by default.
*/
public TimeSeries(final long startTime, final TimeUnit timeUnit, final long deltaTime) {
this(startTime, timeUnit, deltaTime, timeUnit);
}
/**
* Constructor using the timeunit as unit for internal usage and deltatime time unit
*/
public TimeSeries(final long startTime, final TimeUnit timeUnit, final long deltaTime, final int frequency,
final int capacity) {
this(startTime, timeUnit, deltaTime, timeUnit, frequency, capacity);
}
public TimeSeries(final long startTime, final TimeUnit timeUnit, final long deltaTime, final int frequency) {
this(startTime, timeUnit, deltaTime, timeUnit, frequency, ITimeSeries.INFINITE_CAPACITY);
}
@Override
public long getStartTime() {
return this.startTime;
}
@Override
public TimeUnit getTimeSeriesTimeUnit() {
return this.timeSeriesTimeUnit;
}
@Override
public long getDeltaTime() {
return this.deltaTime;
}
@Override
public TimeUnit getDeltaTimeUnit() {
return this.deltaTimeUnit;
}
/**
* Returns the step size between each item in the timeseries. The {@link TimeUnit} of the stepSize is equal to the {@link #timeSeriesTimeUnit}.
*
* @return step size
*/
public long getStepSize() {
return this.timeSeriesStepSize;
}
/**
* @param value
* value which should append to timeseries
*
* @return tspoint
*/
@Override
public ITimeSeriesPoint<T> append(final T value) {
final ITimeSeriesPoint<T> point;
synchronized (value) {
// this.setNextTime();
point = new TimeSeriesPoint<T>(this.nextTime, value);
this.points.add(point);
this.nextTime = this.points.peek().getTime();
}
return point;
}
private void setNextTime() {
this.nextTime = this.nextTime + this.timeSeriesStepSize;
}
@Override
public List<ITimeSeriesPoint<T>> getPoints() {
return new ArrayList<ITimeSeriesPoint<T>>(this.points);
}
@Override
public List<T> getValues() {
final List<ITimeSeriesPoint<T>> pointsCopy = this.getPoints();
final List<T> retVals = new ArrayList<T>(pointsCopy.size());
for (final ITimeSeriesPoint<T> curPoint : pointsCopy) {
retVals.add(curPoint.getValue());
}
return retVals;
}
@Override
public int getCapacity() {
return this.capacity;
}
@Override
public int size() {
return this.points.getSize();
}
@Override
public long getEndTime() {
if (this.getPoints().isEmpty()) {
throw new IllegalStateException("The TimeSeries is empty, so no end time can be returned.");
} else {
return this.getStartTime() + (this.timeSeriesStepSize * (this.getPoints().size() - 1));
}
}
@Override
public List<ITimeSeriesPoint<T>> appendAll(final T[] values) {
final List<ITimeSeriesPoint<T>> retVals = new ArrayList<ITimeSeriesPoint<T>>(values.length);
for (final T value : values) {
retVals.add(this.append(value));
}
return retVals;
}
@Override
public String toString() {
final StringBuffer buf = new StringBuffer();
buf.append("Time Series with delta: " + this.deltaTime + " " + this.deltaTimeUnit + " starting at: " + this.getStartTime() + " " + this.timeSeriesTimeUnit);
for (final ITimeSeriesPoint<T> curPoint : this.getPoints()) {
buf.append(curPoint);
}
return buf.toString();
}
@Override
public int getFrequency() {
return this.frequency;
}
}
| #1436: fix for adjusting start time in bounded buffer
| src/tools/kieker/tools/tslib/TimeSeries.java | #1436: fix for adjusting start time in bounded buffer | <ide><path>rc/tools/kieker/tools/tslib/TimeSeries.java
<ide>
<ide> /**
<ide> * @author Andre van Hoorn, Tobias Rudolph, Andreas Eberlein
<del> *
<add> *
<ide> * @since 1.10
<ide> * @param <T>
<ide> * The type of the time series.
<ide> */
<ide> public class TimeSeries<T> implements ITimeSeries<T> {
<del> private final long startTime;
<add> private volatile long startTime;
<ide> private final TimeUnit timeSeriesTimeUnit;
<ide> private long nextTime;
<ide> private final long deltaTime;
<ide> private final int frequency;
<ide> private final int capacity;
<ide> private final TimeSeriesPointsBuffer<ITimeSeriesPoint<T>> points;
<del> private long timeSeriesStepSize;
<add> private final long timeSeriesStepSize;
<ide>
<ide> /**
<ide> * @param startTime
<ide>
<ide> /**
<ide> * Returns the step size between each item in the timeseries. The {@link TimeUnit} of the stepSize is equal to the {@link #timeSeriesTimeUnit}.
<del> *
<add> *
<ide> * @return step size
<ide> */
<ide> public long getStepSize() {
<ide> /**
<ide> * @param value
<ide> * value which should append to timeseries
<del> *
<add> *
<ide> * @return tspoint
<ide> */
<ide> @Override
<ide> final ITimeSeriesPoint<T> point;
<ide>
<ide> synchronized (value) {
<del> // this.setNextTime();
<ide> point = new TimeSeriesPoint<T>(this.nextTime, value);
<ide> this.points.add(point);
<del> this.nextTime = this.points.peek().getTime();
<add> this.startTime = this.points.peek().getTime(); // we have a bounded buffer so the first element might be gone
<add> this.nextTime = this.nextTime + this.timeSeriesStepSize;
<ide> }
<ide> return point;
<del> }
<del>
<del> private void setNextTime() {
<del> this.nextTime = this.nextTime + this.timeSeriesStepSize;
<ide> }
<ide>
<ide> @Override |
|
Java | mit | 17a93bedc1dd8b59a07b743e1ea8843e5078372e | 0 | INVASIS/Viola-Jones,INVASIS/Viola-Jones | package process;
import jeigen.DenseMatrix;
import utils.Serializer;
import java.util.ArrayList;
import java.util.Date;
import static java.lang.Math.log;
import static process.features.FeatureExtractor.*;
import static utils.Utils.countFiles;
import static utils.Utils.listFiles;
public class Classifier {
/**
* A Classifier maps an observation to a label valued in a finite set.
* f(HaarFeaturesOfTheImage) = -1 or 1
* CAUTION: the training only works on same-sized images!
* This Classifier uses what is know as Strong & Weak classifiers
* A Weak classifier is just a simple basic classifier, it could be Binary, Naive Bayes or anything else.
* The only need for a weak classifier is to return results with a success rate > 0.5, which is actually better than random.
* The combination of all these Weak classifier create of very good classifier, which is called the Strong classifier.
* <p>
* This is what we call Adaboosting.
*/
/* --- CONSTANTS FOR TRAINING --- */
private static final float TWEAK_UNIT = 1e-2f; // initial tweak unit
private static final double MIN_TWEAK = 1e-5; // tweak unit cannot go lower than this
private static final double GOAL = 1e-7;
/* --- CLASS VARIABLES --- */
private int countTrainPos;
private int countTrainNeg;
private int trainN;
private long featureCount;
private int countTestPos;
private int countTestNeg;
private int testN;
private String train_dir;
private ArrayList<String> train_faces;
private ArrayList<String> train_nonfaces;
private String test_dir;
private final int width;
private final int height;
private boolean computed = false;
private ArrayList<Integer> layerMemory;
private ArrayList<StumpRule>[] cascade;
private ArrayList<Float> tweaks;
private DenseMatrix weightsTrain;
private DenseMatrix weightsTest;
private DenseMatrix labelsTrain;
private DenseMatrix labelsTest;
private double totalWeightPos; // total weight received by positive examples currently
private double totalWeightNeg; // total weight received by negative examples currently
private double minWeight; // minimum weight among all weights currently
private double maxWeight; // maximum weight among all weights currently
public Classifier(int width, int height) {
this.width = width;
this.height = height;
this.featureCount = countAllFeatures(width, height);
System.out.println("Feature count for " + width + "x" + height + ": " + featureCount);
}
private void predictLabel(int round, int N, float decisionTweak, DenseMatrix prediction, boolean onlyMostRecent) {
// prediction = Matrix<int, 1,n > -> To be filled here
int committeeSize = cascade[round].size();
DenseMatrix memberVerdict = new DenseMatrix(committeeSize, N);
DenseMatrix memberWeight = new DenseMatrix(1, committeeSize);
onlyMostRecent = committeeSize == 1 || onlyMostRecent;
int start = onlyMostRecent ? committeeSize - 1 : 0;
for (int member = start; member < committeeSize; member++) {
if (cascade[round].get(member).error == 0 && member != 0) {
System.err.println("Boosting Error Occurred!");
System.exit(1);
}
// 0.5 does not count here
// if member's weightedError is zero, member weight is nan, but it won't be used anyway
double err = cascade[round].get(member).error;
assert Double.isFinite(err); // <=> !NaN && !Infinity
if (err != 0)
memberWeight.set(member, log((1 / err) - 1)); // log((1 / commitee[member].error) - 1)
else
memberWeight.set(member, Double.MAX_VALUE);
long featureIndex = cascade[round].get(member).featureIndex;
for (int i = 0; i < N; i++) {
int exampleIndex = getExampleIndex(featureIndex, i, N);
memberVerdict.set(member, exampleIndex,
((getExampleFeature(featureIndex, i, N) > cascade[round].get(member).threshold ? 1 : -1) * cascade[round].get(member).toggle) + decisionTweak);
}
}
if (!onlyMostRecent) {
DenseMatrix finalVerdict = memberWeight.mmul(memberVerdict); // FIXME : matrix mul error Sould use mmul ??
for (int i = 0; i < N; i++)
prediction.set(0, i, finalVerdict.get(0, i) > 0 ? 1 : -1);
}
else {
for (int i = 0; i < N; i++)
prediction.set(0, i, memberVerdict.get(start, i) > 0 ? 1 : -1);
}
}
/**
* Algorithm 5 from the original paper
*
* Explication: We want to find the feature that gives the lowest error when separating positive and negative examples with that feature's threshold!
*
* Return the most discriminative feature and its rule
* We compute each StumpRule, and find the one with:
* - the lower weighted error first
* - the wider margin
*
* Pair<Integer i, Boolean b> indicates whether feature i is a face (b=true) or not (b=false)
*/
private StumpRule bestStump() {
long startTime = System.currentTimeMillis();
// Compare each StumpRule and find the best by following this algorithm:
// if (current.weightedError < best.weightedError) -> best = current
// else if (current.weightedError == best.weightedError && current.margin > best.margin) -> best = current
System.out.println(" - Calling bestStump with totalWeightsPos : " + totalWeightPos + " totalWeightNeg : " + totalWeightNeg + " minWeight : " + minWeight);
int nb_threads = Runtime.getRuntime().availableProcessors();
DecisionStump managerFor0 = new DecisionStump(labelsTrain, weightsTrain, 0, trainN, totalWeightPos, totalWeightNeg, minWeight);
managerFor0.run();
StumpRule best = managerFor0.getBest();
for (long i = 1; i < featureCount; i++) { // TODO: Replace by threadPoolExecutor
ArrayList<DecisionStump> listThreads = new ArrayList<>(nb_threads);
long j;
for (j = 0; j < nb_threads && j + i < featureCount; j++) {
DecisionStump decisionStump = new DecisionStump(labelsTrain, weightsTrain, i + j, trainN, totalWeightPos, totalWeightNeg, minWeight);
listThreads.add(decisionStump);
decisionStump.start();
}
i += (j - 1);
for (int k = 0; k < j; k++) {
try {
listThreads.get(k).join();
} catch (InterruptedException e) {
System.err.println(" - Error in thread while computing bestStump - i = " + i + " k = " + k + " j = " + j);
e.printStackTrace();
}
}
for (int k = 0; k < j; k++) {
if (listThreads.get(k).getBest().compare(best))
best = listThreads.get(k).getBest();
}
}
if (best.error >= 0.5) {
System.out.println(" - Failed best stump, error : " + best.error + " >= 0.5 !");
System.exit(1);
}
System.out.println(" - Found best stump in " + ((new Date()).getTime() - startTime)/1000 + "s" +
" : (featureIdx: " + best.featureIndex +
", threshold: " + best.threshold +
", margin:" + best.margin +
", error:" + best.error +
", toggle:" + best.toggle + ")");
return best;
}
/**
* Algorithm 6 from the original paper
*
* Strong classifier based on multiple weak classifiers.
* Here, weak classifier are called "Stumps", see: https://en.wikipedia.org/wiki/Decision_stump
*
* Explication: The training aims to find the feature with the threshold that will allows to separate positive & negative examples in the best way possible!
*/
private void adaboost(int round) {
// STATE: OK & CHECKED 16/31/08
StumpRule bestDS = bestStump(); // A new weak classifier
cascade[round].add(bestDS); // Add this weak classifier to our current strong classifier to get better results
DenseMatrix prediction = new DenseMatrix(1, trainN);
predictLabel(round, trainN, 0, prediction, true);
DenseMatrix agree = labelsTrain.mul(prediction);
DenseMatrix weightUpdate = DenseMatrix.ones(1, trainN); // new ArrayList<>(trainN);
boolean werror = false;
for (int i = 0; i < trainN; i++) {
if (agree.get(0, i) < 0) {
if (bestDS.error != 0)
weightUpdate.set(0, i, (1 / bestDS.error) - 1); // (1 / bestDS.error) - 1
else
weightUpdate.set(0, i, Double.MAX_VALUE - 1);
werror = true;
}
}
//
if (werror) {
weightsTrain = weightsTrain.mul(weightUpdate);
/*for (int i = 0; i < trainN; i++)
weightsTrain.set(i, weightsTrain.get(i) * weightUpdate.get(i));
*/
double sum = 0;
for (int i = 0; i < trainN; i++)
sum += weightsTrain.get(0, i);
double sumPos = 0;
minWeight = 1;
maxWeight = 0;
for (int i = 0; i < trainN; i++) {
double newVal = weightsTrain.get(0, i) / sum;
weightsTrain.set(0, i, newVal);
if (i < countTrainPos)
sumPos += newVal;
if (minWeight > newVal)
minWeight = newVal;
if (maxWeight < newVal)
maxWeight = newVal;
}
totalWeightPos = sumPos;
totalWeightNeg = 1 - sumPos;
assert totalWeightPos + totalWeightNeg == 1;
assert totalWeightPos <= 1;
assert totalWeightNeg <= 1;
}
}
// p141 in paper?
private float[] calcEmpiricalError(int round, int N, int countPos, DenseMatrix labels) {
// STATE: OK & CHECKED 16/26/08
float res[] = new float[2];
int nFalsePositive = 0;
int nFalseNegative = 0;
DenseMatrix verdicts = DenseMatrix.ones(1, N);
DenseMatrix layerPrediction = DenseMatrix.zeros(1, N);
for (int layer = 0; layer < round + 1; layer++) {
predictLabel(round, N, tweaks.get(round), layerPrediction, false);
verdicts = verdicts.min(layerPrediction);
}
DenseMatrix agree = labels.mul(verdicts);
for (int exampleIndex = 0; exampleIndex < N; exampleIndex++) {
if (agree.get(0, exampleIndex) < 0) {
if (exampleIndex < countPos) {
nFalseNegative += 1;
} else {
nFalsePositive += 1;
}
}
}
res[0] = nFalsePositive / (float) (N - countPos);
res[1] = 1 - nFalseNegative / (float) countPos;
return res;
}
/**
* Algorithm 10 from the original paper
*/
private int attentionalCascade(int round, float overallTargetDetectionRate, float overallTargetFalsePositiveRate) {
// STATE: OK & CHECKED 16/31/08
int committeeSizeGuide = Math.min(20 + round * 10, 200);
System.out.println(" - CommitteeSizeGuide = " + committeeSizeGuide);
cascade[round] = new ArrayList<>();
int nbWeakClassifier = 0;
boolean layerMissionAccomplished = false;
while (!layerMissionAccomplished) {
// Run algorithm N°6 (adaboost) to produce a classifier (== ArrayList<StumpRule>)
adaboost(round);
boolean overSized = cascade[round].size() > committeeSizeGuide;
boolean finalTweak = overSized;
int tweakCounter = 0;
int[] oscillationObserver = new int[2];
float tweak = 0;
if (finalTweak)
tweak = -1;
float tweakUnit = TWEAK_UNIT;
float falsePositive, detectionRate;
while (Math.abs(tweak) < 1.1) {
tweaks.set(round, tweak);
float tmp[] = calcEmpiricalError(round, trainN, countTrainPos, labelsTrain);
falsePositive = tmp[0];
detectionRate = tmp[1];
/*
FIXME : train without using the test values... maybe less detection rate doing that ?
tmp = calcEmpiricalError(round, testN, countTestPos, labelsTest);
ctrlFalsePositive = tmp[0];
ctrlDetectionRate = tmp[1];
float worstFalsePositive = Math.max(falsePositive, ctrlFalsePositive);
float worstDetectionRate = Math.min(detectionRate, ctrlDetectionRate);
*/
float worstFalsePositive = falsePositive;
float worstDetectionRate = detectionRate;
if (finalTweak) {
if (worstDetectionRate >= 0.99) {
System.out.println(" - Final tweak settles to " + tweak);
break;
} else {
tweak += TWEAK_UNIT;
continue;
}
}
//System.out.println(" - worstDetectionRate: " + worstDetectionRate + ">= overallTargetDetectionRate: " + overallTargetDetectionRate + " && worstFalsePositive: " + worstFalsePositive + "<= overallTargetFalsePositiveRate: " + overallTargetFalsePositiveRate);
if (worstDetectionRate >= overallTargetDetectionRate && worstFalsePositive <= overallTargetFalsePositiveRate) {
layerMissionAccomplished = true;
break;
} else if (worstDetectionRate >= overallTargetDetectionRate && worstFalsePositive > overallTargetFalsePositiveRate) {
tweak -= tweakUnit;
tweakCounter++;
oscillationObserver[tweakCounter % 2] = -1;
} else if (worstDetectionRate < overallTargetDetectionRate && worstFalsePositive <= overallTargetFalsePositiveRate) {
tweak += tweakUnit;
tweakCounter++;
oscillationObserver[tweakCounter % 2] = 1;
} else {
finalTweak = true;
System.out.println(" - No way out at this point. tweak goes from " + tweak);
continue;
}
// It is possible that tweak vacillates
if (!finalTweak && tweakCounter > 1 && (oscillationObserver[0] + oscillationObserver[1]) == 0) {
// One solution is to reduce tweakUnit
tweakUnit /= 2;
tweak += oscillationObserver[tweakCounter % 2] == 1 ? -1 * tweakUnit : tweakUnit;
System.out.println(" - Backtracked at " + tweakCounter + "! Modify tweakUnit to " + tweakUnit);
if (tweakUnit < MIN_TWEAK) {
finalTweak = true;
System.out.println(" - TweakUnit too small. Tweak goes from " + tweak);
}
}
}
if (overSized)
break;
nbWeakClassifier++;
}
return nbWeakClassifier;
}
private ArrayList<String> orderedExamples() {
ArrayList<String> examples = new ArrayList<>(trainN);
examples.addAll(train_faces);
examples.addAll(train_nonfaces);
return examples;
}
public void train(String dir, float initialPositiveWeight, float overallTargetDetectionRate, float overallTargetFalsePositiveRate, float targetFalsePositiveRate) {
if (computed) {
System.out.println("Training already done!");
return;
}
train_dir = dir;
countTrainPos = countFiles(train_dir + "/faces", Conf.IMAGES_EXTENSION);
countTrainNeg = countFiles(train_dir + "/non-faces", Conf.IMAGES_EXTENSION);
trainN = countTrainPos + countTrainNeg;
System.out.println("Total number of training images: " + trainN + " (pos: " + countTrainPos + ", neg: " + countTrainNeg + ")");
train_faces = listFiles(train_dir + "/faces", Conf.IMAGES_EXTENSION);
train_nonfaces = listFiles(train_dir + "/non-faces", Conf.IMAGES_EXTENSION);
layerMemory = new ArrayList<>();
// Compute all features for train & test set
computeFeaturesTimed(train_dir);
// Now organize all those features, so that it is easier to make requests on it
organizeFeatures(featureCount, orderedExamples(), Conf.ORGANIZED_FEATURES, Conf.ORGANIZED_SAMPLE, false);
System.out.println("Training classifier:");
// Estimated number of rounds needed
int boostingRounds = (int) (Math.ceil(Math.log(overallTargetFalsePositiveRate) / Math.log(targetFalsePositiveRate)) + 20);
System.out.println(" - Estimated needed boosting rounds: " + boostingRounds);
// Initialization
tweaks = new ArrayList<>(boostingRounds);
for (int i = 0; i < boostingRounds; i++)
tweaks.add(0f);
cascade = new ArrayList[boostingRounds];
// Init labels
labelsTrain = new DenseMatrix(1, trainN);
for (int i = 0; i < trainN; i++)
labelsTrain.set(0, i, i < countTrainPos ? 1 : -1); // face == 1 VS non-face == -1
double accumulatedFalsePositive = 1;
// Training: run Cascade until we arrive to a certain wanted rate of success
for (int round = 0; round < boostingRounds && accumulatedFalsePositive > GOAL; round++) {
System.out.println(" - Round N." + round + ":");
// Update weights (needed because adaboost changes weights when running)
totalWeightPos = initialPositiveWeight;
totalWeightNeg = 1 - initialPositiveWeight;
double averageWeightPos = totalWeightPos / countTrainPos;
double averageWeightNeg = totalWeightNeg / countTrainNeg;
minWeight = averageWeightPos < averageWeightNeg ? averageWeightPos : averageWeightNeg;
maxWeight = averageWeightPos > averageWeightNeg ? averageWeightPos : averageWeightNeg;
weightsTrain = DenseMatrix.zeros(1, trainN);
for (int i = 0; i < trainN; i++)
weightsTrain.set(0, i, i < countTrainPos ? averageWeightPos : averageWeightNeg);
System.out.println(" - Initialized weights:");
System.out.println(" - TotW+: " + totalWeightPos + " | TotW-: " + totalWeightNeg);
System.out.println(" - AverW+: " + averageWeightPos + " | AverW-: " + averageWeightNeg);
System.out.println(" - MinW: " + minWeight + " | MaxW: " + maxWeight);
int nbWC = attentionalCascade(round, overallTargetDetectionRate, overallTargetFalsePositiveRate);
System.out.println(" - Attentional Cascade computed!");
System.out.println(" - Number of weak classifier: " + nbWC);
// -- Display results for this round --
//layerMemory.add(trainSet.committee.size());
layerMemory.add(cascade[round].size());
System.out.println(" - The committee size is " + cascade[round].size());
float detectionRate, falsePositive;
float[] tmp = calcEmpiricalError(round, trainN, countTrainPos, labelsTrain);
falsePositive = tmp[0];
detectionRate = tmp[1];
System.out.println(" - The current tweak " + tweaks.get(round) + " has falsePositive " + falsePositive + " and detectionRate " + detectionRate + " on the training examples.");
/*
tmp = calcEmpiricalError(round, testN, countTestPos, labelsTest);
falsePositive = tmp[0];
detectionRate = tmp[1];
System.out.println("The current tweak " + tweaks.get(round) + " has falsePositive " + falsePositive + " and detectionRate " + detectionRate + " on the validation examples.");
*/
accumulatedFalsePositive *= falsePositive;
System.out.println(" - Accumulated False Positive Rate is around " + accumulatedFalsePositive);
// TODO : blackList ??
//record the boosted rule into a target file
Serializer.writeRule(cascade[round], round == 0, Conf.TRAIN_FEATURES);
}
// Serialize training
Serializer.writeLayerMemory(this.layerMemory, this.tweaks, Conf.TRAIN_FEATURES);
computed = true;
}
public float test(String dir) {
if (!computed) {
System.err.println("Train the classifier before testing it!");
System.exit(1);
}
test_dir = dir;
countTestPos = countFiles(test_dir + "/faces", Conf.IMAGES_EXTENSION);
countTestNeg = countFiles(test_dir + "/non-faces", Conf.IMAGES_EXTENSION);
testN = countTestPos + countTestNeg;
computeFeaturesTimed(test_dir);
// TODO: after the training has been done, we can test on a new set of images.
return 0;
}
}
| src/process/Classifier.java | package process;
import jeigen.DenseMatrix;
import utils.Serializer;
import java.util.ArrayList;
import java.util.Date;
import static java.lang.Math.log;
import static process.features.FeatureExtractor.*;
import static utils.Utils.countFiles;
import static utils.Utils.listFiles;
public class Classifier {
/**
* A Classifier maps an observation to a label valued in a finite set.
* f(HaarFeaturesOfTheImage) = -1 or 1
* CAUTION: the training only works on same-sized images!
* This Classifier uses what is know as Strong & Weak classifiers
* A Weak classifier is just a simple basic classifier, it could be Binary, Naive Bayes or anything else.
* The only need for a weak classifier is to return results with a success rate > 0.5, which is actually better than random.
* The combination of all these Weak classifier create of very good classifier, which is called the Strong classifier.
* <p>
* This is what we call Adaboosting.
*/
/* --- CONSTANTS FOR TRAINING --- */
private static final float TWEAK_UNIT = 1e-2f; // initial tweak unit
private static final double MIN_TWEAK = 1e-5; // tweak unit cannot go lower than this
private static final double GOAL = 1e-7;
/* --- CLASS VARIABLES --- */
private int countTrainPos;
private int countTrainNeg;
private int trainN;
private long featureCount;
private int countTestPos;
private int countTestNeg;
private int testN;
private String train_dir;
private ArrayList<String> train_faces;
private ArrayList<String> train_nonfaces;
private String test_dir;
private final int width;
private final int height;
private boolean computed = false;
private ArrayList<Integer> layerMemory;
private ArrayList<StumpRule>[] cascade;
private ArrayList<Float> tweaks;
private DenseMatrix weightsTrain;
private DenseMatrix weightsTest;
private DenseMatrix labelsTrain;
private DenseMatrix labelsTest;
private double totalWeightPos; // total weight received by positive examples currently
private double totalWeightNeg; // total weight received by negative examples currently
private double minWeight; // minimum weight among all weights currently
private double maxWeight; // maximum weight among all weights currently
public Classifier(int width, int height) {
this.width = width;
this.height = height;
this.featureCount = countAllFeatures(width, height);
System.out.println("Feature count for " + width + "x" + height + ": " + featureCount);
}
private void predictLabel(int round, int N, float decisionTweak, DenseMatrix prediction, boolean onlyMostRecent) {
// prediction = Matrix<int, 1,n > -> To be filled here
int committeeSize = cascade[round].size();
DenseMatrix memberVerdict = new DenseMatrix(committeeSize, N);
DenseMatrix memberWeight = new DenseMatrix(1, committeeSize);
onlyMostRecent = committeeSize == 1 || onlyMostRecent;
int start = onlyMostRecent ? committeeSize - 1 : 0;
for (int member = start; member < committeeSize; member++) {
if (cascade[round].get(member).error == 0 && member != 0) {
System.err.println("Boosting Error Occurred!");
System.exit(1);
}
// 0.5 does not count here
// if member's weightedError is zero, member weight is nan, but it won't be used anyway
double err = cascade[round].get(member).error;
assert Double.isFinite(err); // <=> !NaN && !Infinity
if (err != 0)
memberWeight.set(member, log((1 / err) - 1)); // log((1 / commitee[member].error) - 1)
else
memberWeight.set(member, Double.MAX_VALUE);
long featureIndex = cascade[round].get(member).featureIndex;
for (int i = 0; i < N; i++) {
int exampleIndex = getExampleIndex(featureIndex, i, N);
memberVerdict.set(member, exampleIndex, ((getExampleFeature(featureIndex, i, N) > cascade[round].get(member).threshold ? 1 : -1) * cascade[round].get(member).toggle) + decisionTweak);
}
}
if (!onlyMostRecent) {
DenseMatrix finalVerdict = memberWeight.mul(memberVerdict); // FIXME : matrix mul error
for (int i = 0; i < N; i++)
prediction.set(0, i, finalVerdict.get(1, i) > 0 ? 1 : -1);
}
else {
for (int i = 0; i < N; i++)
prediction.set(0, i, memberVerdict.get(start, i) > 0 ? 1 : -1);
}
}
/**
* Algorithm 5 from the original paper
*
* Explication: We want to find the feature that gives the lowest error when separating positive and negative examples with that feature's threshold!
*
* Return the most discriminative feature and its rule
* We compute each StumpRule, and find the one with:
* - the lower weighted error first
* - the wider margin
*
* Pair<Integer i, Boolean b> indicates whether feature i is a face (b=true) or not (b=false)
*/
private StumpRule bestStump() {
long startTime = System.currentTimeMillis();
// Compare each StumpRule and find the best by following this algorithm:
// if (current.weightedError < best.weightedError) -> best = current
// else if (current.weightedError == best.weightedError && current.margin > best.margin) -> best = current
System.out.println(" - Calling bestStump with totalWeightsPos : " + totalWeightPos + " totalWeightNeg : " + totalWeightNeg + " minWeight : " + minWeight);
int nb_threads = Runtime.getRuntime().availableProcessors();
DecisionStump managerFor0 = new DecisionStump(labelsTrain, weightsTrain, 0, trainN, totalWeightPos, totalWeightNeg, minWeight);
managerFor0.run();
StumpRule best = managerFor0.getBest();
for (long i = 1; i < featureCount; i++) { // TODO: Replace by threadPoolExecutor
ArrayList<DecisionStump> listThreads = new ArrayList<>(nb_threads);
long j;
for (j = 0; j < nb_threads && j + i < featureCount; j++) {
DecisionStump decisionStump = new DecisionStump(labelsTrain, weightsTrain, i + j, trainN, totalWeightPos, totalWeightNeg, minWeight);
listThreads.add(decisionStump);
decisionStump.start();
}
i += (j - 1);
for (int k = 0; k < j; k++) {
try {
listThreads.get(k).join();
} catch (InterruptedException e) {
System.err.println(" - Error in thread while computing bestStump - i = " + i + " k = " + k + " j = " + j);
e.printStackTrace();
}
}
for (int k = 0; k < j; k++) {
if (listThreads.get(k).getBest().compare(best))
best = listThreads.get(k).getBest();
}
}
if (best.error >= 0.5) {
System.out.println(" - Failed best stump, error : " + best.error + " >= 0.5 !");
System.exit(1);
}
System.out.println(" - Found best stump in " + ((new Date()).getTime() - startTime)/1000 + "s" +
" : (featureIdx: " + best.featureIndex +
", threshold: " + best.threshold +
", margin:" + best.margin +
", error:" + best.error +
", toggle:" + best.toggle + ")");
return best;
}
/**
* Algorithm 6 from the original paper
*
* Strong classifier based on multiple weak classifiers.
* Here, weak classifier are called "Stumps", see: https://en.wikipedia.org/wiki/Decision_stump
*
* Explication: The training aims to find the feature with the threshold that will allows to separate positive & negative examples in the best way possible!
*/
private void adaboost(int round) {
// STATE: OK & CHECKED 16/31/08
StumpRule bestDS = bestStump(); // A new weak classifier
cascade[round].add(bestDS); // Add this weak classifier to our current strong classifier to get better results
DenseMatrix prediction = new DenseMatrix(1, trainN);
predictLabel(round, trainN, 0, prediction, true);
DenseMatrix agree = labelsTrain.mul(prediction);
DenseMatrix weightUpdate = DenseMatrix.ones(1, trainN); // new ArrayList<>(trainN);
boolean werror = false;
for (int i = 0; i < trainN; i++) {
if (agree.get(0, i) < 0) {
if (bestDS.error != 0)
weightUpdate.set(0, i, (1 / bestDS.error) - 1); // (1 / bestDS.error) - 1
else
weightUpdate.set(0, i, Double.MAX_VALUE - 1);
werror = true;
}
}
//
if (werror) {
weightsTrain = weightsTrain.mul(weightUpdate);
/*for (int i = 0; i < trainN; i++)
weightsTrain.set(i, weightsTrain.get(i) * weightUpdate.get(i));
*/
double sum = 0;
for (int i = 0; i < trainN; i++)
sum += weightsTrain.get(0, i);
double sumPos = 0;
for (int i = 0; i < trainN; i++) {
double newVal = weightsTrain.get(0, i) / sum;
weightsTrain.set(0, i, newVal);
sumPos += newVal;
}
totalWeightPos = sumPos;
totalWeightNeg = 1 - sumPos;
assert totalWeightPos + totalWeightNeg == 1;
assert totalWeightPos <= 1;
assert totalWeightNeg <= 1;
minWeight = weightsTrain.get(0, 0);
maxWeight = weightsTrain.get(0, 0);
for (int i = 1; i < trainN; i++) {
double currentVal = weightsTrain.get(0, i);
if (minWeight > currentVal)
minWeight = currentVal;
if (maxWeight < currentVal)
maxWeight = currentVal;
}
}
}
// p141 in paper?
private float[] calcEmpiricalError(int round, int N, int countPos, DenseMatrix labels) {
// STATE: OK & CHECKED 16/26/08
float res[] = new float[2];
int nFalsePositive = 0;
int nFalseNegative = 0;
DenseMatrix verdicts = DenseMatrix.ones(1, N);
DenseMatrix layerPrediction = DenseMatrix.zeros(1, N);
for (int layer = 0; layer < round + 1; layer++) {
predictLabel(round, N, tweaks.get(round), layerPrediction, false);
verdicts = verdicts.min(layerPrediction);
}
DenseMatrix agree = labels.mul(verdicts);
for (int exampleIndex = 0; exampleIndex < N; exampleIndex++) {
if (agree.get(0, exampleIndex) < 0) {
if (exampleIndex < countPos) {
nFalseNegative += 1;
} else {
nFalsePositive += 1;
}
}
}
res[0] = nFalsePositive / (float) (N - countPos);
res[1] = 1 - nFalseNegative / (float) countPos;
return res;
}
/**
* Algorithm 10 from the original paper
*/
private int attentionalCascade(int round, float overallTargetDetectionRate, float overallTargetFalsePositiveRate) {
// STATE: OK & CHECKED 16/31/08
int committeeSizeGuide = Math.min(20 + round * 10, 200);
System.out.println(" - CommitteeSizeGuide = " + committeeSizeGuide);
cascade[round] = new ArrayList<>();
int nbWeakClassifier = 0;
boolean layerMissionAccomplished = false;
while (!layerMissionAccomplished) {
// Run algorithm N°6 (adaboost) to produce a classifier (== ArrayList<StumpRule>)
adaboost(round);
boolean overSized = cascade[round].size() > committeeSizeGuide;
boolean finalTweak = overSized;
int tweakCounter = 0;
int[] oscillationObserver = new int[2];
float tweak = 0;
if (finalTweak)
tweak = -1;
float tweakUnit = TWEAK_UNIT;
float falsePositive, detectionRate;
while (Math.abs(tweak) < 1.1) {
tweaks.set(round, tweak);
float tmp[] = calcEmpiricalError(round, trainN, countTrainPos, labelsTrain);
falsePositive = tmp[0];
detectionRate = tmp[1];
/*
FIXME : train without using the test values... maybe less detection rate doing that ?
tmp = calcEmpiricalError(round, testN, countTestPos, labelsTest);
ctrlFalsePositive = tmp[0];
ctrlDetectionRate = tmp[1];
float worstFalsePositive = Math.max(falsePositive, ctrlFalsePositive);
float worstDetectionRate = Math.min(detectionRate, ctrlDetectionRate);
*/
float worstFalsePositive = falsePositive;
float worstDetectionRate = detectionRate;
if (finalTweak) {
if (worstDetectionRate >= 0.99) {
System.out.println(" - Final tweak settles to " + tweak);
break;
} else {
tweak += TWEAK_UNIT;
continue;
}
}
System.out.println(" - worstDetectionRate: " + worstDetectionRate + ">= overallTargetDetectionRate: " + overallTargetDetectionRate + " && worstFalsePositive: " + worstFalsePositive + "<= overallTargetFalsePositiveRate: " + overallTargetFalsePositiveRate);
if (worstDetectionRate >= overallTargetDetectionRate && worstFalsePositive <= overallTargetFalsePositiveRate) {
layerMissionAccomplished = true;
break;
} else if (worstDetectionRate >= overallTargetDetectionRate && worstFalsePositive > overallTargetFalsePositiveRate) {
tweak -= tweakUnit;
tweakCounter++;
oscillationObserver[tweakCounter % 2] = -1;
} else if (worstDetectionRate < overallTargetDetectionRate && worstFalsePositive <= overallTargetFalsePositiveRate) {
tweak += tweakUnit;
tweakCounter++;
oscillationObserver[tweakCounter % 2] = 1;
} else {
finalTweak = true;
System.out.println(" - No way out at this point. tweak goes from " + tweak);
continue;
}
// It is possible that tweak vacillates
if (!finalTweak && tweakCounter > 1 && (oscillationObserver[0] + oscillationObserver[1]) == 0) {
// One solution is to reduce tweakUnit
tweakUnit /= 2;
tweak += oscillationObserver[tweakCounter % 2] == 1 ? -1 * tweakUnit : tweakUnit;
System.out.println(" - Backtracked at " + tweakCounter + "! Modify tweakUnit to " + tweakUnit);
if (tweakUnit < MIN_TWEAK) {
finalTweak = true;
System.out.println(" - TweakUnit too small. Tweak goes from " + tweak);
}
}
}
if (overSized)
break;
nbWeakClassifier++;
}
return nbWeakClassifier;
}
private ArrayList<String> orderedExamples() {
ArrayList<String> examples = new ArrayList<>(trainN);
examples.addAll(train_faces);
examples.addAll(train_nonfaces);
return examples;
}
public void train(String dir, float initialPositiveWeight, float overallTargetDetectionRate, float overallTargetFalsePositiveRate, float targetFalsePositiveRate) {
if (computed) {
System.out.println("Training already done!");
return;
}
train_dir = dir;
countTrainPos = countFiles(train_dir + "/faces", Conf.IMAGES_EXTENSION);
countTrainNeg = countFiles(train_dir + "/non-faces", Conf.IMAGES_EXTENSION);
trainN = countTrainPos + countTrainNeg;
System.out.println("Total number of training images: " + trainN + " (pos: " + countTrainPos + ", neg: " + countTrainNeg + ")");
train_faces = listFiles(train_dir + "/faces", Conf.IMAGES_EXTENSION);
train_nonfaces = listFiles(train_dir + "/non-faces", Conf.IMAGES_EXTENSION);
layerMemory = new ArrayList<>();
// Compute all features for train & test set
computeFeaturesTimed(train_dir);
// Now organize all those features, so that it is easier to make requests on it
organizeFeatures(featureCount, orderedExamples(), Conf.ORGANIZED_FEATURES, Conf.ORGANIZED_SAMPLE, false);
System.out.println("Training classifier:");
// Estimated number of rounds needed
int boostingRounds = (int) (Math.ceil(Math.log(overallTargetFalsePositiveRate) / Math.log(targetFalsePositiveRate)) + 20);
System.out.println(" - Estimated needed boosting rounds: " + boostingRounds);
// Initialization
tweaks = new ArrayList<>(boostingRounds);
for (int i = 0; i < boostingRounds; i++)
tweaks.add(0f);
cascade = new ArrayList[boostingRounds];
// Init labels
labelsTrain = new DenseMatrix(1, trainN);
for (int i = 0; i < trainN; i++)
labelsTrain.set(0, i, i < countTrainPos ? 1 : -1); // face == 1 VS non-face == -1
double accumulatedFalsePositive = 1;
// Training: run Cascade until we arrive to a certain wanted rate of success
for (int round = 0; round < boostingRounds && accumulatedFalsePositive > GOAL; round++) {
System.out.println(" - Round N." + round + ":");
// Update weights (needed because adaboost changes weights when running)
totalWeightPos = initialPositiveWeight;
totalWeightNeg = 1 - initialPositiveWeight;
double averageWeightPos = totalWeightPos / countTrainPos;
double averageWeightNeg = totalWeightNeg / countTrainNeg;
minWeight = averageWeightPos < averageWeightNeg ? averageWeightPos : averageWeightNeg;
maxWeight = averageWeightPos > averageWeightNeg ? averageWeightPos : averageWeightNeg;
weightsTrain = DenseMatrix.zeros(1, trainN);
for (int i = 0; i < trainN; i++)
weightsTrain.set(0, i, i < countTrainPos ? averageWeightPos : averageWeightNeg);
System.out.println(" - Initialized weights:");
System.out.println(" - TotW+: " + totalWeightPos + " | TotW-: " + totalWeightNeg);
System.out.println(" - AverW+: " + averageWeightPos + " | AverW-: " + averageWeightNeg);
System.out.println(" - MinW: " + minWeight + " | MaxW: " + maxWeight);
int nbWC = attentionalCascade(round, overallTargetDetectionRate, overallTargetFalsePositiveRate);
System.out.println(" - Attentional Cascade computed!");
System.out.println(" - Number of weak classifier: " + nbWC);
// -- Display results for this round --
//layerMemory.add(trainSet.committee.size());
layerMemory.add(cascade[round].size());
System.out.println(" - The committee size is " + cascade[round].size());
float detectionRate, falsePositive;
float[] tmp = calcEmpiricalError(round, trainN, countTrainPos, labelsTrain);
falsePositive = tmp[0];
detectionRate = tmp[1];
System.out.println(" - The current tweak " + tweaks.get(round) + " has falsePositive " + falsePositive + " and detectionRate " + detectionRate + " on the training examples.");
/*
tmp = calcEmpiricalError(round, testN, countTestPos, labelsTest);
falsePositive = tmp[0];
detectionRate = tmp[1];
System.out.println("The current tweak " + tweaks.get(round) + " has falsePositive " + falsePositive + " and detectionRate " + detectionRate + " on the validation examples.");
*/
accumulatedFalsePositive *= falsePositive;
System.out.println(" - Accumulated False Positive Rate is around " + accumulatedFalsePositive);
// TODO : blackList ??
//record the boosted rule into a target file
Serializer.writeRule(cascade[round], round == 0, Conf.TRAIN_FEATURES);
}
// Serialize training
Serializer.writeLayerMemory(this.layerMemory, this.tweaks, Conf.TRAIN_FEATURES);
computed = true;
}
public float test(String dir) {
if (!computed) {
System.err.println("Train the classifier before testing it!");
System.exit(1);
}
test_dir = dir;
countTestPos = countFiles(test_dir + "/faces", Conf.IMAGES_EXTENSION);
countTestNeg = countFiles(test_dir + "/non-faces", Conf.IMAGES_EXTENSION);
testN = countTestPos + countTestNeg;
computeFeaturesTimed(test_dir);
// TODO: after the training has been done, we can test on a new set of images.
return 0;
}
}
| Fix use of matrix + little improvement in a for loop
| src/process/Classifier.java | Fix use of matrix + little improvement in a for loop | <ide><path>rc/process/Classifier.java
<ide> long featureIndex = cascade[round].get(member).featureIndex;
<ide> for (int i = 0; i < N; i++) {
<ide> int exampleIndex = getExampleIndex(featureIndex, i, N);
<del> memberVerdict.set(member, exampleIndex, ((getExampleFeature(featureIndex, i, N) > cascade[round].get(member).threshold ? 1 : -1) * cascade[round].get(member).toggle) + decisionTweak);
<add> memberVerdict.set(member, exampleIndex,
<add> ((getExampleFeature(featureIndex, i, N) > cascade[round].get(member).threshold ? 1 : -1) * cascade[round].get(member).toggle) + decisionTweak);
<ide> }
<ide> }
<ide> if (!onlyMostRecent) {
<del> DenseMatrix finalVerdict = memberWeight.mul(memberVerdict); // FIXME : matrix mul error
<add> DenseMatrix finalVerdict = memberWeight.mmul(memberVerdict); // FIXME : matrix mul error Sould use mmul ??
<ide> for (int i = 0; i < N; i++)
<del> prediction.set(0, i, finalVerdict.get(1, i) > 0 ? 1 : -1);
<add> prediction.set(0, i, finalVerdict.get(0, i) > 0 ? 1 : -1);
<ide> }
<ide> else {
<ide> for (int i = 0; i < N; i++)
<ide> double sum = 0;
<ide> for (int i = 0; i < trainN; i++)
<ide> sum += weightsTrain.get(0, i);
<add>
<ide> double sumPos = 0;
<add>
<add> minWeight = 1;
<add> maxWeight = 0;
<add>
<ide> for (int i = 0; i < trainN; i++) {
<ide> double newVal = weightsTrain.get(0, i) / sum;
<ide> weightsTrain.set(0, i, newVal);
<del> sumPos += newVal;
<add> if (i < countTrainPos)
<add> sumPos += newVal;
<add> if (minWeight > newVal)
<add> minWeight = newVal;
<add> if (maxWeight < newVal)
<add> maxWeight = newVal;
<ide> }
<ide> totalWeightPos = sumPos;
<ide> totalWeightNeg = 1 - sumPos;
<ide> assert totalWeightPos + totalWeightNeg == 1;
<ide> assert totalWeightPos <= 1;
<ide> assert totalWeightNeg <= 1;
<del>
<del> minWeight = weightsTrain.get(0, 0);
<del> maxWeight = weightsTrain.get(0, 0);
<del>
<del> for (int i = 1; i < trainN; i++) {
<del> double currentVal = weightsTrain.get(0, i);
<del> if (minWeight > currentVal)
<del> minWeight = currentVal;
<del> if (maxWeight < currentVal)
<del> maxWeight = currentVal;
<del> }
<del>
<ide> }
<ide> }
<ide>
<ide> }
<ide> }
<ide>
<del> System.out.println(" - worstDetectionRate: " + worstDetectionRate + ">= overallTargetDetectionRate: " + overallTargetDetectionRate + " && worstFalsePositive: " + worstFalsePositive + "<= overallTargetFalsePositiveRate: " + overallTargetFalsePositiveRate);
<add> //System.out.println(" - worstDetectionRate: " + worstDetectionRate + ">= overallTargetDetectionRate: " + overallTargetDetectionRate + " && worstFalsePositive: " + worstFalsePositive + "<= overallTargetFalsePositiveRate: " + overallTargetFalsePositiveRate);
<ide> if (worstDetectionRate >= overallTargetDetectionRate && worstFalsePositive <= overallTargetFalsePositiveRate) {
<ide> layerMissionAccomplished = true;
<ide> break; |
|
Java | mit | c5d78d732b59616d48a5cbb65c8398db293baa1c | 0 | BackSpace47/main,BackSpace47/main | //#######################
//## ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___
//## /\ \ /\ \ /\ \ /\ \ /\ \ /\ \ |\__\ /\ \ /\ \ /\ \ /\ \ /\ \ /\ \ /\ \ /\ \ /\ \ /\__\
//## /::\ \ /::\ \ /::\ \ /::\ \ /::\ \ /::\ \ |:| | /::\ \ /::\ \ /::\ \ /::\ \ /::\ \ /::\ \ \:\ \ /::\ \ /::\ \ /::| |
//## /:/\:\ \ /:/\:\ \ /:/\:\ \ /:/\:\ \ /:/\:\ \ /:/\:\ \ |:| | /:/\:\ \ /:/\:\ \ /:/\:\ \ /:/\:\ \ /:/\:\ \ /:/\ \ \ \:\ \ /:/\:\ \ /:/\:\ \ /:|:| |
//## /::\~\:\ \ /::\~\:\ \ /::\~\:\ \ /::\~\:\ \ /:/ \:\__\ /:/ \:\ \ |:|__|__ /:/ \:\ \ /:/ \:\ \ /:/ \:\__\ /::\~\:\ \ /::\~\:\ \ _\:\~\ \ \ /::\ \ /::\~\:\ \ /::\~\:\ \ /:/|:|__|__
//## /:/\:\ \:\__\ /:/\:\ \:\__\ /:/\:\ \:\__\ /:/\:\ \:\__\ /:/__/ \:|__| /:/__/ \:\__\ ____/::::\__\ /:/__/ \:\__\ /:/__/ \:\__\ /:/__/ \:|__| /:/\:\ \:\__\ /:/\:\ \:\__\ /\ \:\ \ \__\ /:/\:\__\ /:/\:\ \:\__\ /:/\:\ \:\__\ /:/ |::::\__\
//## \/__\:\/:/ / \/__\:\/:/ / \/_|::\/:/ / \/__\:\/:/ / \:\ \ /:| | \:\ \ /:/ / \::::/~~/~ \:\ \ \/__/ \:\ \ /:/ / \:\ \ /:/ / \:\~\:\ \/__/ \/_|::\/:/ / \:\ \:\ \/__/ /:/ \/__/ \:\~\:\ \/__/ \/__\:\/:/ / \/__/~~/:/ /
//## \::/ / \::/ / |:|::/ / \::/ / \:\ /:/ / \:\ /:/ / ~~|:|~~| \:\ \ \:\ /:/ / \:\ /:/ / \:\ \:\__\ |:|::/ / \:\ \:\__\ /:/ / \:\ \:\__\ \::/ / /:/ /
//## \/__/ /:/ / |:|\/__/ /:/ / \:\/:/ / \:\/:/ / |:| | \:\ \ \:\/:/ / \:\/:/ / \:\ \/__/ |:|\/__/ \:\/:/ / \/__/ \:\ \/__/ /:/ / /:/ /
//## /:/ / |:| | /:/ / \__/__/ \::/ / |:| | \:\__\ \::/ / \::/__/ \:\__\ |:| | \::/ / \:\__\ /:/ / /:/ /
//## \/__/ \|__| \/__/ \/__/ \|__| \/__/ \/__/ ~~ \/__/ \|__| \/__/ \/__/ \/__/ \/__/
//##
//##
//##
//##
//## Mod Made Possible by Magnus,Backspace & Rebel
//##
//##
//##
//##
//##
//##
//#######################
package net.RPower.RPowermod.core;
import net.RPower.RPowermod.block.BlockTCAM;
import net.RPower.RPowermod.block.BlockoreAnthtracite;
import net.RPower.RPowermod.block.BlocksandTreated;
import net.RPower.RPowermod.block.ObsidianWhite;
import net.RPower.RPowermod.block.blockREBL;
import net.RPower.RPowermod.block.blockREBLo;
import net.RPower.RPowermod.block.blockREBS;
import net.RPower.RPowermod.block.blockRPBlock;
import net.RPower.RPowermod.block.blockRPBlockBSpace;
import net.RPower.RPowermod.block.blockRPOre;
import net.RPower.RPowermod.gui.GuiHandler;
import net.RPower.RPowermod.item.*;
import net.RPower.RPowermod.item.ItemHeadBspace;
import net.RPower.RPowermod.net.ItemFoodcreativeCookie;
import net.RPower.RPowermod.proxy.CommonProxy;
import net.RPower.RPowermod.tileentity.TileEntityalloySmelter;
import net.RPower.RPowermod.world.RPWorldGen;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.Item.ToolMaterial;
import net.minecraft.item.ItemStack;
import net.minecraftforge.common.util.EnumHelper;
import net.minecraftforge.oredict.OreDictionary;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.Mod.EventHandler;
import cpw.mods.fml.common.Mod.Instance;
import cpw.mods.fml.common.SidedProxy;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.network.NetworkRegistry;
import cpw.mods.fml.common.registry.GameRegistry;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
@Mod(modid = RPCore.modid, name = "Mine Facility", version = "1.0.9")
public class RPCore {
public static final String modid = "rpower";
public static ToolMaterial jadeToolMaterial;
@Instance(modid)
public static RPCore instance;
//Blocks
/*
To add a block first do these lines (public static Block <name of block>;) then inside preInit do (<name of block> = new Block<name of block>(Material.rock).setCreativeTab(CreativeTabs.tabBlock).setBlockName("<name of block whit capital leters and space if two or more words>").setBlockTextureName(modid + ":" + "<texture name of block>"); then under init do (Recipies.registerBlock(<name of block>, "<name of block whit capital leters and space if two or more words>");))
*/
//NOTE BACKSPACE CREATE STEELDUST, BRONZEDUST
//ADD ZINK ORE & BRASSDUST
//Ores
public static Block oreJade;
public static Block oreCopper;
public static Block oreFerrous;
public static Block oreLead;
public static Block oreSilver;
public static Block oreTin;
public static Block oreTungsten;
public static Block oreExp;
public static Block oreAnthtracite;
public static Block obsidianWhite;
public static Block oreZinc;
//Blocks of items
public static Block copperBlock;
public static Block ferrousBlock;
public static Block leadBlock;
public static Block jadeBlock;
public static Block netherstarBlock;
public static Block organizeddiamondBlock;
public static Block organizedemeraldBlock;
public static Block silverBlock;
public static Block tinBlock;
public static Block tungstenBlock;
public static Block tungstencarbideBlock;
//other
public static Block TCAM;
public static Block oreCrusher;
public static Block sandTreated;
//machines
public static Block alloySmelterIdle;
public static Block alloySmelterActive;
public static final int guiIDalloySmelter = 0;
//Trees & Plants
public static Block elderSap;
public static Block elderLeaf;
public static Block elderLog;
public static Block elderPlanks;
public static Block blueStabilizer;
public static Block polymer;
public static Block polymerWoven;
//Caustic Items
public static Item causticMeal;
public static Item causticCorpuscles;
public static Item bloodFirey;
public static Item acidSulfuric;
public static Item dustPN;
public static Item dustCharcoal;
public static Item toolSkinning;
//Food
public static Item megaCookie;
public static Item ghostCookie;
public static Item testCookie;
public static Item poisonCookie;
public static Item miniCookie;
public static Item oneupCookie;
public static Item springCookie;
public static Item propellerCookie;
public static Item rockCookie;
public static Item superCookie;
public static Item baconRaw;
public static Item baconCooked;
public static Item knife;
public static Item dustSugar;
//Items
/*
To add a item first do these lines (public static Item <name of item>;) then inside preInit do (<name of item> = new Item<name of item>().setCreativeTab(CreativeTabs.tabMaterials).setUnlocalizedName("<name of item whit capital leters and space if two or more words>").setTextureName(modid + ":" + "<texture name of item>"); then under init do (Recipies.registerItem(<name of item>, "<name of item whit capital leters and space if two or more words>");))
*/
public static Item gemJade;
public static Item gemJadepure;
public static Item ingotTungsten;
public static Item ingotTungstencarbide;
public static Item ingotCopper;
public static Item gemDiamond;
public static Item gemEmerald;
public static Item ingotFerrous;
public static Item ingotLead;
public static Item ingotNetherstar;
public static Item ingotSilver;
public static Item ingotTin;
public static Item ingotSteel;
public static Item ingotBronze;
public static Item ingotBrass;
public static Item ingotZink;
public static Item magnusCookie;
//Chunks
public static Item chunkTungsten;
public static Item chunkCopper;
public static Item chunkFerrous;
public static Item chunkLead;
public static Item chunkSilver;
public static Item chunkTin;
//Dust
public static Item dustNetherstar;
public static Item dustCopper;
public static Item dustDiamond;
public static Item dustEmerald;
public static Item dustFerrous;
public static Item dustGold;
public static Item dustIron;
public static Item dustLead;
public static Item dustSilver;
public static Item dustTin;
public static Item dustTungsten;
public static Item dustBronze;
public static Item dustSteel;
//random
public static Item amuletofprotestas;
//Electronic Parts
//Capacitor
public static Item foil;
public static Item foilAluminumoxide;
public static Item paperElectrolized;
//parts^^
public static Item capacitorBasic;
public static Item capacitorCopper;
public static Item capacitorDiamond;
public static Item capacitorGold;
public static Item capacitorTungstencarbide;
//Diode
public static Item anvilPostassembly;
public static Item Epoxy;
public static Item lenseReflective;
//parts^^
public static Item diode;
//Resistor
public static Item clayTreated;
public static Item clayTreatedbaked;
public static Item coiledNichrome;
//^^parts
public static Item resistorCase;
public static Item resistorBasic;
public static Item resistorCopper;
public static Item resistorDiamond;
public static Item resistorGold;
public static Item resistorIron;
public static Item resistorTungstencarbide;
//Transistors
public static Item kitTransistor;
//Parts^^
public static Item transistorBasic;
public static Item transistorCopper;
public static Item transistorDiamond;
public static Item transistorGold;
public static Item transistorIron;
public static Item transistorTungstencarbide;
//Protosprays
public static Item protopaintCopper;
public static Item protopaintDiamond;
public static Item protopaintGold;
public static Item protopaintTungstencarbide;
//Runes
public static Item runeAir;
public static Item runeEarth;
public static Item runeFire;
public static Item runePlate;
public static Item runeSpirit;
public static Item runeWater;
public static Item dustMagick;
public static Item dustMagickcompound;
//Stuff
public static Item glue;
public static Item tcbar;
public static Item TCAI;
public static Item jadeSword;
public static Item jadeHoe;
public static Item jadeAxe;
public static Item jadePickaxe;
public static Item jadeShovel;
public static Item anthracite;
public static Item jadeHeadSw;
public static Item jadeHeadSh;
public static Item jadeHeadAx;
public static Item jadeHeadHo;
public static Item jadeHeadPi;
public static Item tungstenCarbideHead;
public static Item tungstenCarbideHammer;
public static Item stoneHammer;
public static Item stoneHamHead;
public static Item sandPaper;
public static Item mortar_and_pestle;
public static Item quartzStick;
public static Item quartzBowl;
public static Item dustFlour;
public static Item cookieSugar;
public static Item Pencil;
public static Item blankScroll;
public static Item scrollCircle;
public static Item oilTreatment;
//Gears/Cog
public static Item mouldCog;
//unfired
public static Item cogUnfiredcopper;
public static Item cogUnfireddiamond;
public static Item cogUnfiredgold;
public static Item cogUnfirediron;
public static Item cogUnfiredtungstencarbide;
//fiered
public static Item cogCopper;
public static Item cogDiamond;
public static Item cogGold;
public static Item cogIron;
public static Item cogTungstencarbide;
//Drops
public static Item dropBig;
public static Item dropBounce;
public static Item dropDeath;
public static Item dropFly;
public static Item dropLife;
public static Item dropMagick;
public static Item dropPoison;
public static Item dropRock;
public static Item dropSmall;
public static Item dropSuper;
//Plants
public static Item yellowLeaf;
//Tool Heads
public static Item headDiamond;
public static Item headJade;
public static Item headNetherstar;
public static Item headSandstone;
public static Item headWooden;
public static Item headCopper;
public static Item headSilver;
//Tools
public static Item hammerDiamond;
public static Item hammerJade;
public static Item hammerNetherstar;
public static Item hammerSandstone;
public static Item hammerWooden;
public static Item hammerCopper;
public static Item hammerSilver;
//Rtools
public static Item axeJadeR;
public static Item hoeJadeR;
public static Item pickaxeJadeR;
public static Item shovelJadeR;
public static Item swordJadeR;
//Handle Modifiers
public static Item handleTCA;
public static Item handleTCASword;
//Other Stuff
public static final Block.SoundType soundTypePiston = new Block.SoundType("stone", 1.0F, 1.0F);
private static final Object ItemStack = null;
@SidedProxy(clientSide="net.RPower.RPowermod.proxy.ClientProxy", serverSide="net.RPower.RPowermod.proxy.CommonProxy")
public static CommonProxy proxy;
public static CreativeTabs RPCoreBTab = new CreativeTabs(modid) {
@SideOnly(Side.CLIENT)
public Item getTabIconItem() {
return Item.getItemFromBlock(jadeBlock);
}
};
public static CreativeTabs RPCoreITab = new CreativeTabs(modid) {
@SideOnly(Side.CLIENT)
public Item getTabIconItem() {
return TCAI;
}
};
@EventHandler
public void preInit(FMLPreInitializationEvent e){
//ToolMaterial
//To Create A Tool Material Do This ToolMaterialName = EnumHelper.addToolMaterial(name, harvestLevel, maxUses, efficiency, damage, enchantability)
/*
* 0 = Wood/Gold
* 1 = Stone
* 2 = Iron
* 3 = Diamond
* 4 = Jade
*/
jadeToolMaterial = EnumHelper.addToolMaterial("JADE", 4, 35, 16F, 7F, 50);
//Blocks----------
//Ores
oreExp = new blockRPOreExp(Material.rock).setCreativeTab(RPCoreBTab).setBlockName("Exp Ore").setBlockTextureName(modid + ":" + "exp_ore").setHardness(5F).setResistance(1F);
oreTin = new blockRPOreTin(Material.rock).setCreativeTab(RPCoreBTab).setBlockName("Tin Ore").setBlockTextureName(modid + ":" + "tin_ore").setHardness(1F).setResistance(0F);
oreSilver = new blockRPOreSilver(Material.rock).setCreativeTab(RPCoreBTab).setBlockName("Silver Ore").setBlockTextureName(modid + ":" + "silver_ore").setHardness(1F).setResistance(1F);
oreJade = new blockRPOre(Material.rock).setCreativeTab(RPCoreBTab).setBlockName("Jade Ore").setBlockTextureName(modid + ":" + "Jade Ore").setHardness(50F).setResistance(5F);
oreCopper = new blockRPBlockBSpace(Material.rock).setCreativeTab(RPCoreBTab).setBlockName("Copper Ore").setBlockTextureName(modid + ":" + "copper_ore").setHardness(1F).setResistance(1F);
oreFerrous = new blockRPOreFerrous(Material.rock).setCreativeTab(RPCoreBTab).setBlockName("Ferrous Ore").setBlockTextureName(modid + ":" + "ferrous_ore").setHardness(1F).setResistance(1F);
oreLead = new blockRPOreLead (Material.rock).setCreativeTab(RPCoreBTab).setBlockName("Lead Ore").setBlockTextureName(modid + ":" + "lead_ore").setHardness(1F).setResistance(1F);
oreTungsten = new blockRPOreTungsten(Material.rock).setCreativeTab(RPCoreBTab).setBlockName("Tungsten Ore").setBlockTextureName(modid + ":" + "tungstenore").setHardness(50F).setResistance(5F);
oreAnthtracite = new BlockoreAnthtracite(Material.rock).setCreativeTab(RPCoreBTab).setBlockName("Anthracite Ore").setBlockTextureName(modid + ":" + "anthracite_ore").setHardness(50F).setResistance(2000F);
obsidianWhite = new ObsidianWhite(Material.rock).setCreativeTab(RPCoreBTab).setBlockName("White Obsidian").setBlockTextureName(modid + ":" + "obsidianWhite").setHardness(50F).setResistance(10F);
oreZinc = new blockRPOreZinc (Material.rock).setCreativeTab(RPCoreBTab).setBlockName("Zinc Ore").setBlockTextureName(modid + ":" + "zinc").setHardness(1F).setResistance(1F);
//Blocks Of items
jadeBlock = new blockRPBlock(Material.rock).setCreativeTab(RPCoreBTab).setBlockName("Jade Block").setBlockTextureName(modid + ":" + "jade_block").setHardness(50F).setResistance(5F);
copperBlock = new blockRPBlock (Material.rock).setCreativeTab(RPCoreBTab).setBlockName("Copper Block").setBlockTextureName(modid + ":" + "copper_block").setHardness(5F).setResistance(1F);
ferrousBlock = new blockRPBlock(Material.rock).setCreativeTab(RPCoreBTab).setBlockName("Ferrous Block").setBlockTextureName(modid + ":" + "ferrous_block").setHardness(5F).setResistance(1F);
leadBlock = new blockRPBlock(Material.rock).setCreativeTab(RPCoreBTab).setBlockName("Lead Block").setBlockTextureName(modid + ":" + "lead_block").setHardness(5F).setResistance(1F);
netherstarBlock = new blockRPBlock(Material.rock).setCreativeTab(RPCoreBTab).setBlockName("Netherstar Block").setBlockTextureName(modid + ":" + "netherstar_block").setHardness(5F).setResistance(1F);
organizeddiamondBlock = new blockRPBlock(Material.rock).setCreativeTab(RPCoreBTab).setBlockName("Organizeddiamond Block").setBlockTextureName(modid + ":" + "organizeddiamond_block").setHardness(5F).setResistance(1F);
organizedemeraldBlock = new blockRPBlock(Material.rock).setCreativeTab(RPCoreBTab).setBlockName("Organizedemerald Block").setBlockTextureName(modid + ":" + "organizedemerald_block").setHardness(5F).setResistance(1F);
silverBlock = new blockRPBlock(Material.rock).setCreativeTab(RPCoreBTab).setBlockName("Silver Block").setBlockTextureName(modid + ":" + "silver_block").setHardness(5F).setResistance(1F);
tinBlock = new blockRPBlock(Material.rock).setCreativeTab(RPCoreBTab).setBlockName("Tin Block").setBlockTextureName(modid + ":" + "tin_block").setHardness(5F).setResistance(1F);
tungstenBlock = new blockRPBlock(Material.rock).setCreativeTab(RPCoreBTab).setBlockName("Tungsten Block").setBlockTextureName(modid + ":" + "tungsten_block").setHardness(5F).setResistance(1F);
tungstencarbideBlock = new blockRPBlock(Material.rock).setCreativeTab(RPCoreBTab).setBlockName("Tungstencarbide Block").setBlockTextureName(modid + ":" + "tungstencarbide_block").setHardness(5F).setResistance(1F);
//
sandTreated = new BlocksandTreated(Material.rock).setCreativeTab(RPCoreITab).setBlockName("Treated Sand").setBlockTextureName(modid + ":" + "sandTreated").setHardness(50F).setResistance(5F);
//Alloys
TCAM = new BlockTCAM(Material.rock).setCreativeTab(RPCoreBTab).setBlockName("TCAM").setBlockTextureName(modid + ":" + "TCAM").setHardness(50F).setResistance(5F);
//Machines
oreCrusher = new BlockoreCrusher(false).setCreativeTab(RPCoreBTab).setBlockName("Ore Crusher").setHardness(50F).setResistance(5F);
alloySmelterIdle = new alloySmelter(false).setCreativeTab(RPCoreBTab).setBlockName("alloySmelterIdle");
alloySmelterActive = new alloySmelter(true).setBlockName("alloySmelterActive").setLightLevel(0.625F);
//Woods & Planks & Trees
elderLog = new blockREBLo().setBlockName("Red Elderberry Log").setHardness(1.5F).setResistance(1F).setStepSound(Block.soundTypeWood).setCreativeTab(RPCoreBTab).setBlockTextureName("log");
elderLeaf = new blockREBL(Material.leaves).setBlockName("Red Elderberry Leaves").setHardness(0.5F).setStepSound(Block.soundTypeGrass).setCreativeTab(RPCoreBTab).setBlockTextureName(modid + ":" + "leaves_redelderberry");
elderSap = new blockREBS().setBlockName("Red Elderberry Sapling").setHardness(0.0F).setCreativeTab(RPCoreBTab).setStepSound(Block.soundTypeGrass).setBlockTextureName(modid + ":" + "elderSap").setBlockTextureName("sapling");
elderPlanks = new blockRPBlock(Material.wood).setCreativeTab(RPCoreBTab).setBlockName("Elder Planks").setBlockTextureName(modid + ":" + "planks_redelderberry").setHardness(1.5F).setStepSound(Block.soundTypeWood).setResistance(0.5F);
polymer = new blockRPBlock(Material.glass).setCreativeTab(RPCoreBTab).setStepSound(Block.soundTypeGrass).setBlockName("Polymer").setBlockTextureName(modid + ":" + "polymer").setHardness(0.5F).setResistance(1F);
polymerWoven = new blockRPBlock(Material.glass).setCreativeTab(RPCoreBTab).setStepSound(Block.soundTypeGrass).setBlockName("Woven Polyester").setBlockTextureName(modid + ":" + "woven_polyester").setHardness(0.5F).setResistance(0.5F);
//WIP //blueStabilizer =new Plants(Material.plants).setBlockName("Blue Stabilizer").setHardness(0.0F).setCreativeTab(RPCoreBTab).setBlockTextureName(modid + ":" + "flowerBlue").setBlockTextureName("flowerB");
//Blocks End----------
//Caustic Items
causticMeal = new itemmealCaustic().setUnlocalizedName("Caustic Mix").setTextureName(modid + ":" + "mealCaustic").setCreativeTab(RPCoreITab);
causticCorpuscles = new itemcorpCaustic().setUnlocalizedName("Caustic Corpuscles").setTextureName(modid + ":" + "corpusclesCaustic").setCreativeTab(RPCoreITab);
bloodFirey = new itembloodFirey().setUnlocalizedName("Firey Blood").setTextureName(modid + ":" + "bloodFirey").setCreativeTab(RPCoreITab);
acidSulfuric = new itemacidS().setUnlocalizedName("Sulfuric Acid").setTextureName(modid + ":" + "SulfuricAcid").setCreativeTab(RPCoreITab);
dustPN = new itemDustPN().setUnlocalizedName("Potassium Nitrate").setTextureName(modid + ":" + "PotassiumNitrate").setCreativeTab(RPCoreITab);
dustCharcoal = new itemdustCharcoal().setUnlocalizedName("Charcoal Dust").setTextureName(modid + ":" + "dustCharcoal").setCreativeTab(RPCoreITab);
toolSkinning = new itemSkinningtool().setUnlocalizedName("Skinning Tool").setTextureName(modid + ":" + "toolSkinning").setCreativeTab(RPCoreITab);
//
//Tools->Hammers
hammerDiamond = new hammerDiamond().setUnlocalizedName("Diamond Hammer").setTextureName(modid + ":" + "hammerDiamond").setCreativeTab(RPCoreITab);
hammerJade = new hammerJade().setUnlocalizedName("Jade Hammer Head").setTextureName(modid + ":" + "hammerJade").setCreativeTab(RPCoreITab);
hammerNetherstar = new hammerNetherstar().setUnlocalizedName("Netherstar Hammer").setTextureName(modid + ":" + "hammerNetherstar").setCreativeTab(RPCoreITab);
hammerSandstone = new hammerSandstone().setUnlocalizedName("Sandstone Hammer").setTextureName(modid + ":" + "hammerSandstone").setCreativeTab(RPCoreITab);
hammerWooden = new hammerWooden().setUnlocalizedName("Wooden Hammer").setTextureName(modid + ":" + "hammerWooden").setCreativeTab(RPCoreITab);
hammerCopper = new hammerCopper().setUnlocalizedName("Copper Hammer").setTextureName(modid + ":" + "hammerCopper").setCreativeTab(RPCoreITab);
hammerSilver = new hammerSilver().setUnlocalizedName("Silver Hammer").setTextureName(modid + ":" + "hammerSilver").setCreativeTab(RPCoreITab);
stoneHammer = new hammerStone().setUnlocalizedName("Stone Hammer").setTextureName(modid + ":" + "Stone_Hammer");
tungstenCarbideHammer = new ItemHeadBspace().setUnlocalizedName("TungstenCarbideHammer").setTextureName(modid + ":" + "TugstenCarbide_Hammer").setNoRepair();
//Tools->Mining
jadeSword = new ItemJadeSword(RPCore.jadeToolMaterial).setNoRepair().setCreativeTab(RPCoreITab).setUnlocalizedName("Jade Sword").setTextureName(modid + ":" + "jade_Sword");
jadeHoe = new ItemJadeHoe(RPCore.jadeToolMaterial).setNoRepair().setCreativeTab(RPCoreITab).setUnlocalizedName("Jade Hoe").setTextureName(modid + ":" + "jade_hoe");
jadeAxe = new ItemJadeAxe(RPCore.jadeToolMaterial).setNoRepair().setCreativeTab(RPCoreITab).setUnlocalizedName("Jade Axe").setTextureName(modid + ":" + "jade_axe");
jadePickaxe = new ItemJadePickaxe(RPCore.jadeToolMaterial).setNoRepair().setCreativeTab(RPCoreITab).setUnlocalizedName("Jade Pickaxe").setTextureName(modid + ":" + "jade_pickaxe");
jadeShovel = new ItemJadeSpade(RPCore.jadeToolMaterial).setNoRepair().setCreativeTab(RPCoreITab).setUnlocalizedName("Jade Shovel").setTextureName(modid + ":" + "jade_shovel");
//Tool Heads
headDiamond = new ItemHead().setUnlocalizedName("Diamond Hammer Head").setTextureName(modid + ":" + "headDiamond").setCreativeTab(RPCoreITab);
headJade = new ItemHead().setUnlocalizedName("Jade Hammer Head").setTextureName(modid + ":" + "headJade").setCreativeTab(RPCoreITab);
headNetherstar = new ItemHead().setUnlocalizedName("Netherstar Hammer Head").setTextureName(modid + ":" + "headNetherstar").setCreativeTab(RPCoreITab);
headSandstone = new ItemHead().setUnlocalizedName("Sandstone Hammer Head").setTextureName(modid + ":" + "headSandstone").setCreativeTab(RPCoreITab);
headWooden = new ItemHead().setUnlocalizedName("Wooden Hammer Head").setTextureName(modid + ":" + "headWooden").setCreativeTab(RPCoreITab);
headCopper = new ItemHead().setUnlocalizedName("Copper Hammer Head").setTextureName(modid + ":" + "headCopper").setCreativeTab(RPCoreITab);
headSilver = new ItemHead().setUnlocalizedName("Silver Hammer Head").setTextureName(modid + ":" + "headSilver").setCreativeTab(RPCoreITab);
tungstenCarbideHead = new ItemHead().setUnlocalizedName("TungstenCarbideHead").setTextureName(modid + ":" + "TugstenCarbide_Hammer_Head");
stoneHamHead = new ItemHead().setUnlocalizedName("Stone Hammer Head").setTextureName(modid + ":" + "HammerHead");
jadeHeadSw = new ItemHead().setUnlocalizedName("JadeSwordHead").setTextureName(modid + ":" + "JadeSwordHead");
jadeHeadSh = new ItemHead().setUnlocalizedName("JadeShovHead").setTextureName(modid + ":" + "JadeShovHead");
jadeHeadAx = new ItemHead().setUnlocalizedName("JadeAxeHead").setTextureName(modid + ":" + "JadeAxeHead");
jadeHeadHo = new ItemHead().setUnlocalizedName("JadeHoeHead").setTextureName(modid + ":" + "JadeHoeHead");
jadeHeadPi = new ItemHead().setUnlocalizedName("JadePickHead").setTextureName(modid + ":" + "JadePickHead");
//Tool Handle Modifiers
//Dusts
dustNetherstar = new ItemNetherstarDust().setCreativeTab(RPCoreITab).setUnlocalizedName("Netherstar Dust").setTextureName(modid + ":" + "Netherstar_Dust");
dustCopper = new ItemCopperDust().setCreativeTab(RPCoreITab).setUnlocalizedName("Copper Dust").setTextureName(modid + ":" + "Copper_Dust");
dustDiamond = new ItemDiamondDust().setCreativeTab(RPCoreITab).setUnlocalizedName("Diamond Dust").setTextureName(modid + ":" + "Diamond_Dust");
dustEmerald = new ItemEmeraldDust().setCreativeTab(RPCoreITab).setUnlocalizedName("Emerald Dust").setTextureName(modid + ":" + "Emerald_Dust");
dustFerrous = new ItemFerrousDust().setCreativeTab(RPCoreITab).setUnlocalizedName("Ferrous Dust").setTextureName(modid + ":" + "Ferrous_Dust");
dustGold = new ItemGoldDust().setCreativeTab(RPCoreITab).setUnlocalizedName("Gold Dust").setTextureName(modid + ":" + "Gold_Dust");
dustIron = new ItemIronDust().setCreativeTab(RPCoreITab).setUnlocalizedName("Iron Dust").setTextureName(modid + ":" + "Iron_Dust");
dustLead = new ItemLeadDust().setCreativeTab(RPCoreITab).setUnlocalizedName("Lead Dust").setTextureName(modid + ":" + "Lead_Dust");
dustSilver = new ItemSilverDust().setCreativeTab(RPCoreITab).setUnlocalizedName("Silver Dust").setTextureName(modid + ":" + "Silver_Dust");
dustTungsten = new ItemTugstenDust().setCreativeTab(RPCoreITab).setUnlocalizedName("Tungsten Dust").setTextureName(modid + ":" + "Tugsten_Dust");
dustTin = new ItemTinDust().setCreativeTab(RPCoreITab).setUnlocalizedName("Tin Dust").setTextureName(modid + ":" + "Tin_Dust");
dustBronze =new ItemBronzeDust().setCreativeTab(RPCoreITab).setUnlocalizedName("Bronze Dust").setTextureName(modid + ":" + "bronze_dust");
dustSteel = new ItemSteelDust().setCreativeTab(RPCoreITab).setUnlocalizedName("Steel Dust").setTextureName(modid + ":" + "steel_dust");
//Ingots
ingotCopper = new ItemCopperIngot().setCreativeTab(RPCoreITab).setUnlocalizedName("Copper Ingot").setTextureName(modid + ":" + "copper_ingot");
ingotFerrous = new ItemFerrousIngot().setCreativeTab(RPCoreITab).setUnlocalizedName("Ferrous Ingot").setTextureName(modid + ":" + "ferrous_ingot");
ingotLead = new ItemLeadIngot().setCreativeTab(RPCoreITab).setUnlocalizedName("Lead Ingot").setTextureName(modid + ":" + "lead_ingot");
ingotNetherstar = new ItemNetherstarIngot().setCreativeTab(RPCoreITab).setUnlocalizedName("Nether Star Ingot").setTextureName(modid + ":" + "netherstar_ingot");
ingotSilver = new ItemSilverIngot().setCreativeTab(RPCoreITab).setUnlocalizedName("Silver Ingot").setTextureName(modid + ":" + "silver_ingot");
ingotTin = new ItemTinIngot().setCreativeTab(RPCoreITab).setUnlocalizedName("Tin Ingot").setTextureName(modid + ":" + "tin_ingot");
ingotTungsten = new ItemTungstenIngot().setCreativeTab(RPCoreITab).setUnlocalizedName("Tungsten Ingot").setTextureName(modid + ":" + "tungsten_ingot");
ingotTungstencarbide = new ItemTungstencarbideIngot().setCreativeTab(RPCoreITab).setUnlocalizedName("Tungstencarbide Ingot").setTextureName(modid + ":" + "tungsten_carbide_ingot");
ingotSteel = new ItemingotSteel().setCreativeTab(RPCoreITab).setUnlocalizedName("Steel Ingot").setTextureName(modid + ":" + "steel_ingot");
ingotBronze = new ItemingotBronze().setCreativeTab(RPCoreITab).setUnlocalizedName("Bronze Ingot").setTextureName(modid + ":" + "bronze_ingot");
TCAI = new ItemTCAI().setCreativeTab(RPCoreITab).setUnlocalizedName("TCAI").setTextureName(modid + ":" + "TCAI");
//Gems
gemDiamond = new ItemDiamondIngot().setCreativeTab(RPCoreITab).setUnlocalizedName("Diamond Ingot").setTextureName(modid + ":" + "diamond_ingot");
gemEmerald = new ItemEmeraldIngot().setCreativeTab(RPCoreITab).setUnlocalizedName("Emerald Ingot").setTextureName(modid + ":" + "emerald_ingot");
gemJade = new ItemJade().setCreativeTab(RPCoreITab).setUnlocalizedName("Raw Jade").setTextureName(modid + ":" + "jade_refined");
gemJadepure = new ItemJade().setCreativeTab(RPCoreITab).setUnlocalizedName("Jade").setTextureName(modid + ":" + "Jade");
//Fuel
anthracite = new ItemAnthracite().setCreativeTab(RPCoreITab).setUnlocalizedName("Anthracite").setTextureName(modid + ":" + "Anthracite");
//Misc
sandPaper = new ItemsandPaper().setCreativeTab(RPCoreITab).setUnlocalizedName("Sand Paper").setTextureName(modid + ":" + "SandPaper");
mortar_and_pestle = new Itemmortar_and_pestle().setCreativeTab(RPCoreITab).setUnlocalizedName("Mortar and Pestle").setTextureName(modid + ":" + "mp");
quartzStick = new ItemquartcStick().setCreativeTab(RPCoreITab).setUnlocalizedName("Quartz Stick").setTextureName(modid + ":" + "quartzStick");
quartzBowl = new ItemquartcBowl().setCreativeTab(RPCoreITab).setUnlocalizedName("Quartz Bowl").setTextureName(modid + ":" + "quartzBowl");
dustFlour = new ItemdustFlour().setCreativeTab(RPCoreITab).setUnlocalizedName("Bag of Flour").setTextureName(modid + ":" + "Flour");
Pencil = new itemPencil().setCreativeTab(RPCoreITab).setUnlocalizedName("Pencil").setTextureName(modid + ":" + "Pencil");
blankScroll = new ItemblankScroll().setCreativeTab(RPCoreITab).setUnlocalizedName("Blank Scroll").setTextureName(modid + ":" + "scrollBlank");
scrollCircle = new ItemscrollCircle().setCreativeTab(RPCoreITab).setUnlocalizedName("Circle Scroll").setTextureName(modid + ":" + "scrollCircle");
oilTreatment = new ItemoilTreatment().setCreativeTab(RPCoreITab).setUnlocalizedName("Treatment Oil").setTextureName(modid + ":" + "oilTreatment");
mouldCog = new ItemmouldCog().setCreativeTab(RPCoreITab).setUnlocalizedName("Cog Mould").setTextureName(modid + ":" + "mouldCog");
//gears
cogUnfiredcopper = new ItemcogUnfiredcopper().setCreativeTab(RPCoreITab).setUnlocalizedName("UnfiredcopperCog").setTextureName(modid + ":" + "cogUnfiredcopper");
cogUnfireddiamond = new ItemcogUnfireddiamond().setCreativeTab(RPCoreITab).setUnlocalizedName("UnfireddiamondCog").setTextureName(modid + ":" + "cogUnfireddiamond");
cogUnfiredgold = new ItemcogUnfiredgold().setCreativeTab(RPCoreITab).setUnlocalizedName("UnfiredgoldCog").setTextureName(modid + ":" + "cogUnfiredgold");
cogUnfirediron = new ItemcogUnfirediron().setCreativeTab(RPCoreITab).setUnlocalizedName("UnfiredironCog").setTextureName(modid + ":" + "cogUnfirediron");
cogUnfiredtungstencarbide = new ItemcogUnfiredtungstencarbide().setCreativeTab(RPCoreITab).setUnlocalizedName("UnfiredtungstencarbideCog").setTextureName(modid + ":" + "cogUnfiredtungstencarbide");
//fiered
cogCopper = new ItemcogCopper().setCreativeTab(RPCoreITab).setUnlocalizedName("CopperCog").setTextureName(modid + ":" + "cogCopper");
cogDiamond = new ItemcogDiamond().setCreativeTab(RPCoreITab).setUnlocalizedName("DiamondCog").setTextureName(modid + ":" + "cogDiamond");
cogGold = new ItemcogGold().setCreativeTab(RPCoreITab).setUnlocalizedName("GoldCog").setTextureName(modid + ":" + "cogGold");
cogIron = new ItemcogIron().setCreativeTab(RPCoreITab).setUnlocalizedName("IronCog").setTextureName(modid + ":" + "cogIron");
cogTungstencarbide = new ItemcogTungstencarbide().setCreativeTab(RPCoreITab).setUnlocalizedName("TungstencarbideCog").setTextureName(modid + ":" + "cogTungstencarbide");
//public static Item ingotSteel;
//public static Item ingotBronze;
//^^ Priority
//public static Item ingotBrass;
//public static Item ingotZink;; <----OreGen REMEMBER
//^^meh
//Chunks
chunkCopper = new chunkCopper().setCreativeTab(RPCoreITab).setUnlocalizedName("Copper Chunk").setTextureName(modid + ":" + "Copper_Chunk");
chunkTungsten = new chunkCopper().setCreativeTab(RPCoreITab).setUnlocalizedName("Tungsten Chunk").setTextureName(modid + ":" + "Tungsten_Chunk");
chunkSilver = new chunkCopper().setCreativeTab(RPCoreITab).setUnlocalizedName("Silver Chunk").setTextureName(modid + ":" + "Silver_Chunk");
chunkLead = new chunkCopper().setCreativeTab(RPCoreITab).setUnlocalizedName("Lead Chunk").setTextureName(modid + ":" + "Lead_Chunk");
chunkTin = new chunkCopper().setCreativeTab(RPCoreITab).setUnlocalizedName("Tin Chunk").setTextureName(modid + ":" + "Tin_Chunk");
chunkFerrous = new chunkCopper().setCreativeTab(RPCoreITab).setUnlocalizedName("Ferrous Chunk").setTextureName(modid + ":" + "Ferrous_Chunk");
//Magic
dustMagick = new dustMagick().setCreativeTab(RPCoreITab).setUnlocalizedName("Magick Dust").setTextureName(modid + ":" + "magick_dust");
dustMagickcompound = new dustMagickcompound().setCreativeTab(RPCoreITab).setUnlocalizedName("Magick Compound").setTextureName(modid + ":" + "magick_compound");
dropBig = new dropBig().setCreativeTab(RPCoreITab).setUnlocalizedName("Big Drop").setTextureName(modid + ":" + "big_drop");
dropBounce = new dropBounce().setCreativeTab(RPCoreITab).setUnlocalizedName("Bounce Drop").setTextureName(modid + ":" + "bounce_drop");
dropDeath = new dropDeath().setCreativeTab(RPCoreITab).setUnlocalizedName("Death Drop").setTextureName(modid + ":" + "death_drop");
dropFly = new dropFly().setCreativeTab(RPCoreITab).setUnlocalizedName("Fly Drop").setTextureName(modid + ":" + "fly_drop");
dropLife = new dropLife().setCreativeTab(RPCoreITab).setUnlocalizedName("Life Drop").setTextureName(modid + ":" + "life_drop");
dropMagick = new dropMagick().setCreativeTab(RPCoreITab).setUnlocalizedName("Magick Drop").setTextureName(modid + ":" + "magick_drop");
dropPoison = new dropPoisen().setCreativeTab(RPCoreITab).setUnlocalizedName("Poison Drop").setTextureName(modid + ":" + "poison_drop");
dropRock = new dropRock().setCreativeTab(RPCoreITab).setUnlocalizedName("Rock Drop").setTextureName(modid + ":" + "rock_drop");
dropSmall = new dropSmall().setCreativeTab(RPCoreITab).setUnlocalizedName("Small Drop").setTextureName(modid + ":" + "small_drop");
dropSuper = new dropSuper().setCreativeTab(RPCoreITab).setUnlocalizedName("Super Drop").setTextureName(modid + ":" + "super_drop");
//Runes
runeFire= new runeFire().setCreativeTab(RPCoreITab).setUnlocalizedName("Fire Rune").setTextureName(modid + ":" + "Fire Rune");
runeEarth= new runeEarth().setCreativeTab(RPCoreITab).setUnlocalizedName("Earth Rune").setTextureName(modid + ":" + "Earth Rune");
runeAir= new runeAir().setCreativeTab(RPCoreITab).setUnlocalizedName("Air Rune").setTextureName(modid + ":" + "Air Rune");
runePlate= new runePlate().setCreativeTab(RPCoreITab).setUnlocalizedName("Runeic Plate").setTextureName(modid + ":" + "runicPlate");
runeSpirit= new runeSpirit().setCreativeTab(RPCoreITab).setUnlocalizedName("Spirit Rune").setTextureName(modid + ":" + "Spirit Rune");
runeWater= new runeWater().setCreativeTab(RPCoreITab).setUnlocalizedName("Water Rune").setTextureName(modid + ":" + "Water Rune");
//Food
megaCookie = new ItemFoodmegaCookie(16, 1, true).setCreativeTab(RPCoreITab).setUnlocalizedName("Mega Cookie").setTextureName(modid + ":" + "Megacookie");
ghostCookie = new ItemFoodghostCookie(8, 1, true).setCreativeTab(RPCoreITab).setUnlocalizedName("Ghost Cookie").setTextureName(modid + ":" + "Ghostcookie");
poisonCookie = new ItemFoodpoisonCookie(-10, 1, true).setCreativeTab(RPCoreITab).setUnlocalizedName("Poison Cookie").setTextureName(modid + ":" + "Poisoncookie");
miniCookie = new ItemFoodminiCookie(8, 1, true).setCreativeTab(RPCoreITab).setUnlocalizedName("Mini Cookie").setTextureName(modid + ":" + "minicookie");
oneupCookie = new ItemFoodoneupCookie(20, 1, true).setCreativeTab(RPCoreITab).setUnlocalizedName("1Up Cookie").setTextureName(modid + ":" + "1Upcookie");
springCookie = new ItemFoodspringCookie(8, 1, true).setCreativeTab(RPCoreITab).setUnlocalizedName("Spring Cookie").setTextureName(modid + ":" + "Springcookie");
propellerCookie = new ItemFoodpropellerCookie(8, 1, true).setCreativeTab(RPCoreITab).setUnlocalizedName("Propeller Cookie[WIP]").setTextureName(modid + ":" + "Propellercookie");
rockCookie =new ItemFoodrockCookie(8, 1, true).setCreativeTab(RPCoreITab).setUnlocalizedName("Rock Cookie").setTextureName(modid + ":" + "Rockcookie");
superCookie =new ItemFoodsuperCookie(8, 1, true).setCreativeTab(RPCoreITab).setUnlocalizedName("Super Cookie").setTextureName(modid + ":" + "Supercookie");
cookieSugar = new ItemFoodcookieSugar(8, 1, true).setCreativeTab(RPCoreITab).setUnlocalizedName("Sugar Cookie").setTextureName(modid + ":" + "cookieSugar");
baconRaw = new ItemFoodbaconRaw(1, 1, true).setCreativeTab(RPCoreITab).setUnlocalizedName("Raw Bacon").setTextureName(modid + ":" + "Bacon_Raw");
baconCooked = new ItemFoodbaconCooked(3, 1, true).setCreativeTab(RPCoreITab).setUnlocalizedName("Cooked Bacon").setTextureName(modid + ":" + "Bacon_Cooked");
knife = new Itemknife().setCreativeTab(RPCoreITab).setUnlocalizedName("Knife").setTextureName(modid + ":" + "Knife");
dustSugar = new ItemdustSugar().setCreativeTab(RPCoreITab).setUnlocalizedName("Pouch Of Sugar").setTextureName(modid + ":" + "Bag_Of_Sugar");
magnusCookie = new ItemFoodcreativeCookie(1, 1, true).setCreativeTab(RPCoreITab).setUnlocalizedName("Magnus Cookie").setTextureName("cookie");
//test
testCookie = new ItemFoodtestCookie(-10, 1, false).setCreativeTab(RPCoreITab).setUnlocalizedName("Item Of Testing").setTextureName(modid + ":" + "ItemOfTesting");
//Plants
yellowLeaf = new ItemyellowLeaf().setCreativeTab(RPCoreITab).setUnlocalizedName("Yellow Leaf").setTextureName(modid + ":" + "MagickYellowLeaf");
//OreDictionary
OreDictionary.registerOre("ingotBronze",new ItemStack(ingotBronze));
OreDictionary.registerOre("ingotSteel",new ItemStack(ingotSteel));
OreDictionary.registerOre("dustBronze", new ItemStack(dustBronze));
OreDictionary.registerOre("dustSteel",new ItemStack(dustSteel));
OreDictionary.registerOre("dustSugar", Items.sugar);
OreDictionary.registerOre("dustSugar", dustSugar);
OreDictionary.registerOre("ingotCopper", ingotCopper);
OreDictionary.registerOre("ingotFerrous", new ItemStack(ingotFerrous));
OreDictionary.registerOre("ingotLead", new ItemStack(ingotLead));
OreDictionary.registerOre("ingotSilver", new ItemStack(ingotSilver));
OreDictionary.registerOre("ingotTin", new ItemStack(ingotTin));
OreDictionary.registerOre("gemDiamond", new ItemStack(gemDiamond));
OreDictionary.registerOre("gemEmerald", new ItemStack(gemEmerald));
OreDictionary.registerOre("ingotTungsten", new ItemStack(ingotTungsten));
OreDictionary.registerOre("ingotNetherstar", new ItemStack(ingotNetherstar));
OreDictionary.registerOre("ingotTugstencarbide", new ItemStack(ingotTungstencarbide));
OreDictionary.registerOre("dustCopper", new ItemStack (dustCopper));
OreDictionary.registerOre("dustFerrous", new ItemStack(dustFerrous));
OreDictionary.registerOre("dustLead", new ItemStack(dustLead));
OreDictionary.registerOre("dustSilver", new ItemStack(dustSilver));
OreDictionary.registerOre("dustTin", new ItemStack(dustTin));
OreDictionary.registerOre("dustDiamond", new ItemStack(dustDiamond));
OreDictionary.registerOre("dustEmerald", new ItemStack(dustEmerald));
OreDictionary.registerOre("dustTungsten", new ItemStack(dustTungsten));
OreDictionary.registerOre("dustNetherstar", new ItemStack(dustNetherstar));
OreDictionary.registerOre("dustGold", new ItemStack(dustGold));
OreDictionary.registerOre("oreCopper", new ItemStack(chunkCopper));
OreDictionary.registerOre("oreTin", new ItemStack(chunkTin));
OreDictionary.registerOre("oreFerrous", new ItemStack(chunkFerrous));
OreDictionary.registerOre("oreLead", new ItemStack(chunkLead));
OreDictionary.registerOre("oreSilver", new ItemStack(chunkSilver));
OreDictionary.registerOre("oreTungsten", new ItemStack(chunkTungsten));
}
@EventHandler
public void init(FMLInitializationEvent e){
ItemStack slabM0 = new ItemStack (Blocks.stone_slab);
slabM0.setItemDamage(5);
GameRegistry.registerTileEntity(TileEntityalloySmelter.class, "alloySmelter");
//machines
GameRegistry.registerBlock(alloySmelterIdle, "AlloySmelterIdle");
GameRegistry.registerBlock(alloySmelterActive, "AlloySmelterActive");
//Blocks
Recipies.registerItem(magnusCookie, "Magnus Cookie");
Recipies.registerBlock(obsidianWhite,"White Obsidian");
Recipies.registerBlock(oreCrusher, "Ore Crusher");
Recipies.registerBlock(sandTreated, "Treated Sand");
//Recipies.registerBlock(blueStabilizer, "Blue Stabilizer");
Recipies.registerBlock(polymer, "Polymer");
Recipies.registerBlock(polymerWoven, "Polyester");
Recipies.registerBlock(oreExp, "Exp Ore");
Recipies.registerBlock(oreTin, "Tin Ore");
Recipies.registerBlock(oreSilver,"Silver Ore");
Recipies.registerBlock(oreLead, "Lead Ore");
Recipies.registerBlock(oreFerrous, "Ferrous Ore");
Recipies.registerBlock(oreCopper, "Copper Ore");
Recipies.registerBlock(oreJade, "Jade Ore");
Recipies.registerBlock(jadeBlock, "Jade Block");
Recipies.registerBlock(oreTungsten, "Tungsten Ore");
Recipies.registerBlock(TCAM, "TCAM");
Recipies.registerBlock(oreAnthtracite, "Anthracite Ore");
Recipies.registerBlock(copperBlock, "Copper Block");
Recipies.registerBlock(ferrousBlock, "Ferrous Block");
Recipies.registerBlock(leadBlock, "Lead Block");
Recipies.registerBlock(netherstarBlock, "Netherstar Block");
Recipies.registerBlock(organizeddiamondBlock, "Organizeddiamond Block");
Recipies.registerBlock(organizedemeraldBlock, "Organizedemerald Block");
Recipies.registerBlock(silverBlock, "Silver Block");
Recipies.registerBlock(tinBlock, "Tin Block");
Recipies.registerBlock(tungstenBlock, "Tungsten Block");
Recipies.registerBlock(tungstencarbideBlock, "Tungstencarbide Block");
//Trees
Recipies.registerBlock(elderLog, "Red Elderberry Log");
Recipies.registerBlock(elderLeaf, "Red Elderberry Leaf");
Recipies.registerBlock(elderSap, "Red Elderberry Sapling");
Recipies.registerBlock(elderPlanks, "Red Elderberry Planks");
//items
//Ingots
Recipies.registerItem(ingotSteel,"Steel Ingot");
Recipies.registerItem(ingotBronze,"Bronze Ingot");
Recipies.registerItem(ingotTin,"Tin Ingot");
Recipies.registerItem(ingotSilver, "Silver Ingot");
Recipies.registerItem(ingotLead, "Lead Ingot");
Recipies.registerItem(ingotFerrous, "Ferrous Ingot");
Recipies.registerItem(ingotCopper, "Copper Ingot");
Recipies.registerItem(ingotNetherstar, "Nether Star Ingot");
Recipies.registerItem(ingotTungsten, "Tungsten Ingot");
Recipies.registerItem(TCAI, "TCAI");
//Gems
Recipies.registerItem(gemDiamond, "Diamond Ingot");
Recipies.registerItem(gemEmerald, "Emerald Ingot");
Recipies.registerItem(gemJade, "Raw Jade");
Recipies.registerItem(gemJadepure, "Jade");
//Dusts
Recipies.registerItem(dustNetherstar, "Netherstar Dust");
Recipies.registerItem(dustCopper, "Copper Dust");
Recipies.registerItem(dustDiamond, "Diamond Dust");
Recipies.registerItem(dustEmerald, "Emerald Dust");
Recipies.registerItem(dustFerrous, "Ferrous Dust");
Recipies.registerItem(dustGold, "Gold Dust");
Recipies.registerItem(dustIron, "Iron Dust");
Recipies.registerItem(dustLead, "Lead Dust");
Recipies.registerItem(dustSilver, "Silver Dust");
Recipies.registerItem(dustTin, "Tin Dust");
Recipies.registerItem(dustTungsten, "Tungsten Dust");
Recipies.registerItem(dustBronze,"Bronze Dust");
Recipies.registerItem(dustSteel,"Steel Dust");
//Magick
Recipies.registerItem(dropBig, "Big Drop");
Recipies.registerItem(dropBounce,"Bounce Drop");
Recipies.registerItem(dropDeath, "Death Drop");
Recipies.registerItem(dropFly,"Fly Drop");
Recipies.registerItem(dropLife,"Life Drop");
Recipies.registerItem(dropMagick,"Magick Drop");
Recipies.registerItem(dropPoison,"Poisen Drop");
Recipies.registerItem(dropRock,"Rock Drop");
Recipies.registerItem(dropSmall,"Small Drop");
Recipies.registerItem(dropSuper, "Super Drop");
Recipies.registerItem(dustMagick, "Magick Dust");
Recipies.registerItem(dustMagickcompound, "Magick Compound");
Recipies.registerItem(runeFire, "Fire Rune");
Recipies.registerItem(runeWater, "Water Rune");
Recipies.registerItem(runeAir, "Air Rune");
Recipies.registerItem(runeSpirit, "Spirit Rune");
Recipies.registerItem(runeEarth, "Earth Rune");
Recipies.registerItem(runePlate, "Runic Plate");
//Misc
Recipies.registerItem(sandPaper,"Sand Paper");
Recipies.registerItem(anthracite, "Anthracite");
Recipies.registerItem(quartzStick, "Quartc Stick");
Recipies.registerItem(quartzBowl, "Quartc Bowl");
Recipies.registerItem(mortar_and_pestle, "Mortar and Pestle");
Recipies.registerItem(Pencil, "Pencil");
Recipies.registerItem(blankScroll, "Blank Scroll");
Recipies.registerItem(scrollCircle, "Circle Scroll");
Recipies.registerItem(oilTreatment, "Treatment Oil");
Recipies.registerItem(mouldCog, "Cog Mould");
//gears
Recipies.registerItem(cogUnfiredcopper, "UnfiredcopperCog");
Recipies.registerItem(cogUnfireddiamond, "UnfireddiamondCog");
Recipies.registerItem(cogUnfiredgold, "CogUnfiredgold");
Recipies.registerItem(cogUnfirediron, "CogUnfirediron");
Recipies.registerItem(cogUnfiredtungstencarbide, "CogUnfiredtungstencarbide");
//fiered
Recipies.registerItem(cogCopper, "CogCopper");
Recipies.registerItem(cogDiamond, "CogDiamond");
Recipies.registerItem(cogGold, "CogGold");
Recipies.registerItem(cogIron, "CogIron");
Recipies.registerItem(cogTungstencarbide, "CogTungstencarbide");
//Chunks
Recipies.registerItem(chunkCopper, "Copper Chunk");
Recipies.registerItem(chunkTin, "Tin Chunk");
Recipies.registerItem(chunkFerrous, "Ferrous Chunk");
Recipies.registerItem(chunkSilver, "Silver Chunk");
Recipies.registerItem(chunkTungsten, "Tungsten Chunk");
Recipies.registerItem(chunkLead, "Lead Chunk");
//Tools
Recipies.registerItem(hammerDiamond,"Diamond Hammer");
Recipies.registerItem(hammerJade,"Jade Hammer");
Recipies.registerItem(hammerNetherstar,"Netherstar Hammer");
Recipies.registerItem(hammerSandstone,"Sandstone Hammer");
Recipies.registerItem(hammerWooden ,"Wooden Hammer");
Recipies.registerItem(hammerCopper,"Copper Hammer");
Recipies.registerItem(hammerSilver,"Silver Hammer");
Recipies.registerItem(tungstenCarbideHammer, "Tungsten Carbide Hammer");
Recipies.registerItem(stoneHammer, "Stone Hammer");
//Tools->Mining
Recipies.registerItem(jadeSword, "Jade Sword");
Recipies.registerItem(jadePickaxe, "Jade Pickaxe");
Recipies.registerItem(jadeAxe, "Jade Axe");
Recipies.registerItem(jadeHoe, "Jade Hoe");
Recipies.registerItem(jadeShovel, "Jade Shovel");
//Tool Heads
Recipies.registerItem(headDiamond,"Diamond Hammer Head");
Recipies.registerItem(headJade,"Jade Hammer Head");
Recipies.registerItem(headNetherstar,"Netherstar Hammer Head");
Recipies.registerItem(headSandstone,"Sandstone Hammer Head");
Recipies.registerItem(headWooden ,"Wooden Hammer Head");
Recipies.registerItem(headCopper,"Copper Hammer Head");
Recipies.registerItem(headSilver,"Silver Hammer Head");
Recipies.registerItem(tungstenCarbideHead, "Tungsten Carbide Hammer Head");
Recipies.registerItem(stoneHamHead, "Stone Hammer Head");
//Tools->Mining
Recipies.registerItem(jadeHeadAx, "JadeAxeHead");
Recipies.registerItem(jadeHeadSw, "JadeSwordHead");
Recipies.registerItem(jadeHeadSh, "JadeShovHead");
Recipies.registerItem(jadeHeadHo, "JadeHoeHead");
Recipies.registerItem(jadeHeadPi, "JadePickHead");
//Handle Modifiers
//Caustic Items
Recipies.registerItem(causticMeal, "Caustic Mix");
Recipies.registerItem(causticCorpuscles, "Caustic Corpuscles ");
Recipies.registerItem(bloodFirey, "Firey Blood");
Recipies.registerItem(acidSulfuric, "Sulferic Acid");
Recipies.registerItem(dustPN,"Potassium Nitrate");
Recipies.registerItem(dustCharcoal, "Charcoal Dust");
Recipies.registerItem(toolSkinning, "Skinning Tool");
//Food
Recipies.registerItem(megaCookie, "Mega Cookie");
Recipies.registerItem(ghostCookie, "Ghost Cookie");
Recipies.registerItem(poisonCookie, "Poison Cookie");
Recipies.registerItem(miniCookie, "Mini Cookie");
Recipies.registerItem(oneupCookie, "1Up Cookie");
Recipies.registerItem(springCookie, "Spring Cookie");
Recipies.registerItem(propellerCookie, "Propeller Cookie[WIP]");
Recipies.registerItem(rockCookie, "Rock Cookie");
Recipies.registerItem(superCookie, "Super Cookie");
Recipies.registerItem(cookieSugar, "Sugar Cookie");
Recipies.registerItem(baconRaw, "Raw Bacon");
Recipies.registerItem(baconCooked,"Cooked Bacon");
Recipies.registerItem(knife,"Knife");
Recipies.registerItem(dustSugar,"Pouch Of Sugar");
Recipies.registerItem(dustFlour, "Bag Of Flour");
//Plants
Recipies.registerItem(yellowLeaf, "Yellow Leaf");
//test
Recipies.registerItem(testCookie, "Item Of Testing");
//Smelting
Recipies.registerSmeltingItemWUM(chunkCopper, ingotCopper,5F);
Recipies.registerSmeltingItemWUM(chunkTin, ingotTin,5F);
Recipies.registerSmeltingItemWUM(chunkFerrous, ingotFerrous,5F);
Recipies.registerSmeltingItemWUM(chunkSilver, ingotSilver,5F);
Recipies.registerSmeltingItemWUM(chunkTungsten, ingotTungsten,5F);
Recipies.registerSmeltingItemWUM(chunkLead, ingotLead,5F);
//gears
Recipies.registerSmeltingItemWUM(cogUnfiredcopper, cogCopper,5F);
Recipies.registerSmeltingItemWUM(cogUnfireddiamond, cogDiamond,5F);
Recipies.registerSmeltingItemWUM(cogUnfiredgold, cogGold,5F);
Recipies.registerSmeltingItemWUM(cogUnfirediron, cogIron,5F);
Recipies.registerSmeltingItemWUM(cogUnfiredtungstencarbide, cogTungstencarbide,5F);
//other
Recipies.registerSmeltingItemWUM(dustFlour,Items.bread,5F);
Recipies.registerSmeltingItemWUM(dustMagick,runePlate,5F);
Recipies.registerSmeltingItemWUM(gemJade, gemJadepure, 5F);
Recipies.registerSmeltingItemWUM(Items.nether_star,ingotNetherstar, 5F);
Recipies.registerSmeltingItemWUM(Items.diamond,gemDiamond, 5F);
Recipies.registerSmeltingItemWUM(Items.emerald,gemEmerald, 5F);
Recipies.registerSmeltingItemWUM(Items.diamond_horse_armor,gemDiamond, 5F);
Recipies.registerSmeltingItemWUM(Items.iron_horse_armor,Items.iron_ingot, 5F);
Recipies.registerSmeltingItemWUM(Items.golden_horse_armor,Items.gold_ingot, 5F);
Recipies.registerSmeltingItemWUM(Items.rotten_flesh,Items.leather, 5F);
Recipies.registerSmeltingItemWUM(Items.poisonous_potato,Items.poisonous_potato, 5F);
//Smelting Ores
Recipies.registerSmeltingBlockToItemWUM(oreTungsten, ingotTungsten, 5F);
Recipies.registerSmeltingBlockToItemWUM(oreCopper,ingotCopper,5f);
Recipies.registerSmeltingBlockToItemWUM(oreFerrous,ingotFerrous,5f);
Recipies.registerSmeltingBlockWUM(obsidianWhite,Blocks.obsidian,5f);
Recipies.registerSmeltingBlockToItemWUM(oreLead,ingotLead,5f);
Recipies.registerSmeltingBlockToItemWUM(oreSilver,ingotSilver,5f);
Recipies.registerSmeltingBlockToItemWUM(oreTin,ingotTin,5f);
//Smelting Dusts
Recipies.registerSmeltingItemWUM(dustTin,ingotTin,5f);
Recipies.registerSmeltingItemWUM(dustTungsten, ingotTungsten, 5F);
Recipies.registerSmeltingItemWUM(dustCopper,ingotCopper,5f);
Recipies.registerSmeltingItemWUM(dustFerrous,ingotFerrous,5f);
Recipies.registerSmeltingItemWUM(dustLead,ingotLead,5f);
Recipies.registerSmeltingItemWUM(dustSilver,ingotSilver,5f);
Recipies.registerSmeltingItemWUM(dustTin,ingotTin,5f);
Recipies.registerSmeltingItemWUM(dustDiamond,gemDiamond,5f);
Recipies.registerSmeltingItemWUM(dustEmerald,gemEmerald,5f);
Recipies.registerSmeltingItemWUM(dustIron,Items.iron_ingot,5f);
Recipies.registerSmeltingItemWUM(dustGold,Items.gold_ingot,5f);
Recipies.registerSmeltingItemWUM(dustNetherstar,ingotNetherstar,5f);
Recipies.registerSmeltingItemWUM(baconRaw,baconCooked,5f);
//Smelting Alloys # Will need to be changed when we get the alloy smelter going
Recipies.registerSmeltingBlockToItemWUM(TCAM, TCAI, 5F);
//Crafting
// #
// #
// 0
GameRegistry.addShapedRecipe(new ItemStack (knife), " ", " x ", " 0 ", 'x',new ItemStack(Items.iron_ingot), '0',new ItemStack(Items.stick));
GameRegistry.addShapedRecipe(new ItemStack (Blocks.stonebrick), "x", "x", 'x', slabM0);
GameRegistry.addShapedRecipe(new ItemStack (dustSteel,4),"###","#0#","###", '#', new ItemStack (RPCore.dustCharcoal),'0',new ItemStack(Items.iron_ingot));
GameRegistry.addShapedRecipe(new ItemStack (tungstenCarbideHead), "###", "# #", '#', new ItemStack (TCAI));
GameRegistry.addShapedRecipe(new ItemStack (tungstenCarbideHammer), "#", "x", '#', new ItemStack (tungstenCarbideHead), 'x', new ItemStack(Items.stick));
GameRegistry.addShapedRecipe(new ItemStack (jadeSword), "x", "z", 'x', new ItemStack (jadeHeadSw), 'z', new ItemStack (Items.stick));
GameRegistry.addShapedRecipe(new ItemStack (jadeShovel), "x", "z", 'x', new ItemStack (jadeHeadSh), 'z', new ItemStack (Items.stick));
GameRegistry.addShapedRecipe(new ItemStack (jadePickaxe), "x", "z", 'x', new ItemStack (jadeHeadPi), 'z', new ItemStack (Items.stick));
GameRegistry.addShapedRecipe(new ItemStack (jadeAxe), "x", "z", 'x', new ItemStack (jadeHeadAx), 'z', new ItemStack (Items.stick));
GameRegistry.addShapedRecipe(new ItemStack (jadeHoe), "x", "z", 'x', new ItemStack (jadeHeadHo), 'z', new ItemStack (Items.stick));
GameRegistry.addShapedRecipe(new ItemStack (copperBlock), "xxx", "xxx", "xxx", 'x', new ItemStack (ingotCopper));
GameRegistry.addShapedRecipe(new ItemStack (leadBlock), "xxx", "xxx", "xxx", 'x', new ItemStack (ingotLead));
GameRegistry.addShapedRecipe(new ItemStack (ferrousBlock), "xxx", "xxx", "xxx", 'x', new ItemStack (ingotFerrous));
GameRegistry.addShapedRecipe(new ItemStack (netherstarBlock), "xxx", "xxx", "xxx", 'x', new ItemStack (ingotNetherstar));
GameRegistry.addShapedRecipe(new ItemStack (organizeddiamondBlock), "xxx", "xxx", "xxx", 'x', new ItemStack (gemDiamond));
GameRegistry.addShapedRecipe(new ItemStack (organizedemeraldBlock), "xxx", "xxx", "xxx", 'x', new ItemStack (gemEmerald));
GameRegistry.addShapedRecipe(new ItemStack (silverBlock), "xxx", "xxx", "xxx", 'x', new ItemStack (ingotSilver));
GameRegistry.addShapedRecipe(new ItemStack (tinBlock), "xxx", "xxx", "xxx", 'x', new ItemStack (ingotTin));
GameRegistry.addShapedRecipe(new ItemStack (tungstenBlock), "xxx", "xxx", "xxx", 'x', new ItemStack (ingotTungsten));
GameRegistry.addShapedRecipe(new ItemStack (tungstencarbideBlock), "xxx", "xxx", "xxx", 'x', new ItemStack (TCAI));
GameRegistry.addShapedRecipe(new ItemStack (jadeBlock), "xx", "xx", 'x', new ItemStack (gemJadepure));
GameRegistry.addShapedRecipe(new ItemStack (yellowLeaf), "xxx", "xxx", "xxx", 'x', new ItemStack (elderLeaf));
GameRegistry.addShapedRecipe(new ItemStack (quartzStick, 4), " x", " x ", "xx ", 'x', new ItemStack (Items.quartz));
GameRegistry.addShapedRecipe(new ItemStack (quartzBowl, 4), "x x", " x ", 'x', new ItemStack (Items.quartz));
GameRegistry.addShapedRecipe(new ItemStack (mortar_and_pestle), "x", "#", 'x', new ItemStack (quartzStick), '#', new ItemStack(quartzBowl));
GameRegistry.addShapedRecipe(new ItemStack (dustMagick, 8), "xxx", "x#x", "xxx", 'x', new ItemStack(yellowLeaf), '#', new ItemStack (mortar_and_pestle));
GameRegistry.addShapedRecipe(new ItemStack (dustSugar, 1), "xxx", "xxx", "xxx", 'x', new ItemStack(Items.sugar));
GameRegistry.addShapelessRecipe(new ItemStack (TCAM), new ItemStack (Blocks.coal_block), new ItemStack (ingotTungsten));
GameRegistry.addShapelessRecipe(new ItemStack (dustBronze,2), new ItemStack (dustCopper,3), new ItemStack (dustTin,1));
GameRegistry.addShapedRecipe(new ItemStack (Blocks.torch, 16), "x", "z", 'x', new ItemStack (anthracite), 'z', new ItemStack (Items.stick));
GameRegistry.addShapedRecipe(new ItemStack (Pencil, 32), "xzx", "xzx", "xsx", 'x', new ItemStack(Blocks.planks), 'z', new ItemStack(Items.coal), 's', new ItemStack(ingotLead));
GameRegistry.addShapelessRecipe(new ItemStack (blankScroll), new ItemStack(Items.paper), new ItemStack(oilTreatment));
GameRegistry.addShapedRecipe(new ItemStack(scrollCircle), "xxx","xzx","xxx", 'x', new ItemStack(Pencil), 'z', new ItemStack(blankScroll));
GameRegistry.addShapedRecipe(new ItemStack (sandTreated, 4), " z ", "zxz", " z ", 'z', new ItemStack(oilTreatment), 'x', new ItemStack(Blocks.sand));
GameRegistry.addShapedRecipe(new ItemStack(mouldCog), " x ", "xzx", " x ", 'x', new ItemStack(sandTreated), 'z', new ItemStack(scrollCircle));
//gears
GameRegistry.addShapedRecipe(new ItemStack(cogUnfiredcopper), " x ", "xzx", " x ", 'x', new ItemStack(dustCopper), 'z', new ItemStack(mouldCog, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapedRecipe(new ItemStack(cogUnfireddiamond), " x ", "xzx", " x ", 'x', new ItemStack(dustDiamond), 'z', new ItemStack(mouldCog, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapedRecipe(new ItemStack(cogUnfiredgold), " x ", "xzx", " x ", 'x', new ItemStack(dustGold), 'z', new ItemStack(mouldCog, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapedRecipe(new ItemStack(cogUnfirediron), " x ", "xzx", " x ", 'x', new ItemStack(dustIron), 'z', new ItemStack(mouldCog, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapedRecipe(new ItemStack(cogUnfiredtungstencarbide), " x ", "xzx", " x ", 'x', new ItemStack(ingotCopper), 'z', new ItemStack(mouldCog, 1, OreDictionary.WILDCARD_VALUE));
//Plants
GameRegistry.addShapedRecipe(new ItemStack (polymer,1),"###","###","###", '#', new ItemStack (Blocks.leaves));
GameRegistry.addShapedRecipe(new ItemStack (polymerWoven,1),"###","###","###", '#', new ItemStack (polymer));
GameRegistry.addShapedRecipe(new ItemStack (Blocks.wool,16),"###","###","###", '#', new ItemStack (polymerWoven));
//Hammer Recipes
//Stone
GameRegistry.addShapedRecipe(new ItemStack (jadeHeadSw,1, OreDictionary.WILDCARD_VALUE), " x", " #", 'x', new ItemStack (jadeBlock), '#', new ItemStack (stoneHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapedRecipe(new ItemStack (jadeHeadSh,1, OreDictionary.WILDCARD_VALUE), "#x", 'x', new ItemStack (jadeBlock), '#', new ItemStack (stoneHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (jadeHeadHo,1, OreDictionary.WILDCARD_VALUE), new ItemStack (jadeBlock), new ItemStack (stoneHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapedRecipe(new ItemStack (jadeHeadAx,1, OreDictionary.WILDCARD_VALUE), " #", " x", 'x', new ItemStack (jadeBlock), '#', new ItemStack (stoneHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapedRecipe(new ItemStack (jadeHeadPi,1, OreDictionary.WILDCARD_VALUE), " x","# ", 'x', new ItemStack (jadeBlock), '#', new ItemStack (stoneHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustCopper,2), new ItemStack (oreCopper), new ItemStack (stoneHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustLead,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreLead), new ItemStack (stoneHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustFerrous,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreFerrous), new ItemStack (stoneHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustCopper,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkCopper), new ItemStack (stoneHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustSilver,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreSilver), new ItemStack (stoneHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustTin,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreTin), new ItemStack (stoneHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustTungsten,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreTungsten), new ItemStack (stoneHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustCopper,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreCopper), new ItemStack (stoneHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack(dustIron,2,OreDictionary.WILDCARD_VALUE), new ItemStack (Blocks.iron_ore), new ItemStack(stoneHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustFlour,4, OreDictionary.WILDCARD_VALUE),new ItemStack(stoneHammer, 1, OreDictionary.WILDCARD_VALUE),new ItemStack(Items.wheat));
GameRegistry.addShapelessRecipe(new ItemStack (dustCharcoal,4, OreDictionary.WILDCARD_VALUE),new ItemStack(stoneHammer, 1, OreDictionary.WILDCARD_VALUE),new ItemStack(Items.coal,1,1));
GameRegistry.addShapelessRecipe(new ItemStack (dustLead,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkLead), new ItemStack (stoneHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustFerrous,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkFerrous), new ItemStack (stoneHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustSilver,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkSilver), new ItemStack (stoneHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustTin,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkTin), new ItemStack (stoneHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustTungsten,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkTungsten), new ItemStack (stoneHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustCopper,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkCopper), new ItemStack (stoneHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (Blocks.sand,2, OreDictionary.WILDCARD_VALUE), new ItemStack (Blocks.cobblestone), new ItemStack (stoneHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustGold,2, OreDictionary.WILDCARD_VALUE), new ItemStack (Blocks.gold_ore), new ItemStack (stoneHammer, 1, OreDictionary.WILDCARD_VALUE));
//Tugsten Carbide
GameRegistry.addShapelessRecipe(new ItemStack (dustEmerald,2, OreDictionary.WILDCARD_VALUE), new ItemStack (Blocks.emerald_ore), new ItemStack (tungstenCarbideHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack(dustDiamond, 3, OreDictionary.WILDCARD_VALUE), new ItemStack (Blocks.diamond_ore), new ItemStack(tungstenCarbideHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapedRecipe(new ItemStack (jadeHeadSw,1, OreDictionary.WILDCARD_VALUE), " x", " #", 'x', new ItemStack (jadeBlock), '#', new ItemStack (tungstenCarbideHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapedRecipe(new ItemStack (jadeHeadSh,1, OreDictionary.WILDCARD_VALUE), "#x", 'x', new ItemStack (jadeBlock), '#', new ItemStack (tungstenCarbideHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (jadeHeadHo,1, OreDictionary.WILDCARD_VALUE), new ItemStack (jadeBlock), new ItemStack (tungstenCarbideHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapedRecipe(new ItemStack (jadeHeadAx,1, OreDictionary.WILDCARD_VALUE), " #", " x", 'x', new ItemStack (jadeBlock), '#', new ItemStack (tungstenCarbideHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapedRecipe(new ItemStack (jadeHeadPi,1, OreDictionary.WILDCARD_VALUE), " x","# ", 'x', new ItemStack (jadeBlock), '#', new ItemStack (tungstenCarbideHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustCopper,2), new ItemStack (oreCopper), new ItemStack (tungstenCarbideHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustLead,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreLead), new ItemStack (tungstenCarbideHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustFerrous,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreFerrous), new ItemStack (tungstenCarbideHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustCopper,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkCopper), new ItemStack (tungstenCarbideHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustSilver,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreSilver), new ItemStack (tungstenCarbideHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustTin,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreTin), new ItemStack (tungstenCarbideHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustTungsten,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreTungsten), new ItemStack (tungstenCarbideHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustCopper,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreCopper), new ItemStack (tungstenCarbideHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack(dustIron,2,OreDictionary.WILDCARD_VALUE), new ItemStack (Blocks.iron_ore), new ItemStack(tungstenCarbideHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustFlour,4, OreDictionary.WILDCARD_VALUE),new ItemStack(tungstenCarbideHammer, 1, OreDictionary.WILDCARD_VALUE),new ItemStack(Items.wheat));
GameRegistry.addShapelessRecipe(new ItemStack (dustCharcoal,4, OreDictionary.WILDCARD_VALUE),new ItemStack(tungstenCarbideHammer, 1, OreDictionary.WILDCARD_VALUE),new ItemStack(Items.coal,1,1));
GameRegistry.addShapelessRecipe(new ItemStack (dustLead,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkLead), new ItemStack (tungstenCarbideHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustFerrous,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkFerrous), new ItemStack (tungstenCarbideHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustSilver,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkSilver), new ItemStack (tungstenCarbideHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustTin,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkTin), new ItemStack (tungstenCarbideHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustTungsten,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkTungsten), new ItemStack (tungstenCarbideHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustCopper,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkCopper), new ItemStack (tungstenCarbideHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (Blocks.sand,2, OreDictionary.WILDCARD_VALUE), new ItemStack (Blocks.cobblestone), new ItemStack (tungstenCarbideHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustGold,2, OreDictionary.WILDCARD_VALUE), new ItemStack (Blocks.gold_ore), new ItemStack (tungstenCarbideHammer, 1, OreDictionary.WILDCARD_VALUE));
//Diamond
GameRegistry.addShapelessRecipe(new ItemStack (dustEmerald,2, OreDictionary.WILDCARD_VALUE), new ItemStack (Blocks.emerald_ore), new ItemStack (hammerDiamond, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack(dustDiamond, 3, OreDictionary.WILDCARD_VALUE), new ItemStack (Blocks.diamond_ore), new ItemStack(hammerDiamond, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapedRecipe(new ItemStack (jadeHeadSw,1, OreDictionary.WILDCARD_VALUE), " x", " #", 'x', new ItemStack (jadeBlock), '#', new ItemStack (hammerDiamond, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapedRecipe(new ItemStack (jadeHeadSh,1, OreDictionary.WILDCARD_VALUE), "#x", 'x', new ItemStack (jadeBlock), '#', new ItemStack (hammerDiamond, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (jadeHeadHo,1, OreDictionary.WILDCARD_VALUE), new ItemStack (jadeBlock), new ItemStack (hammerDiamond, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapedRecipe(new ItemStack (jadeHeadAx,1, OreDictionary.WILDCARD_VALUE), " #", " x", 'x', new ItemStack (jadeBlock), '#', new ItemStack (hammerDiamond, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapedRecipe(new ItemStack (jadeHeadPi,1, OreDictionary.WILDCARD_VALUE), " x","# ", 'x', new ItemStack (jadeBlock), '#', new ItemStack (hammerDiamond, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustCopper,2), new ItemStack (oreCopper), new ItemStack (hammerDiamond, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustLead,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreLead), new ItemStack (hammerDiamond, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustFerrous,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreFerrous), new ItemStack (hammerDiamond, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustCopper,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkCopper), new ItemStack (hammerDiamond, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustSilver,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreSilver), new ItemStack (hammerDiamond, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustTin,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreTin), new ItemStack (hammerDiamond, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustTungsten,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreTungsten), new ItemStack (hammerDiamond, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustCopper,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreCopper), new ItemStack (hammerDiamond, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack(dustIron,2,OreDictionary.WILDCARD_VALUE), new ItemStack (Blocks.iron_ore), new ItemStack(hammerDiamond, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustFlour,4, OreDictionary.WILDCARD_VALUE),new ItemStack(hammerDiamond, 1, OreDictionary.WILDCARD_VALUE),new ItemStack(Items.wheat));
GameRegistry.addShapelessRecipe(new ItemStack (dustCharcoal,4, OreDictionary.WILDCARD_VALUE),new ItemStack(hammerDiamond, 1, OreDictionary.WILDCARD_VALUE),new ItemStack(Items.coal,1,1));
GameRegistry.addShapelessRecipe(new ItemStack (dustLead,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkLead), new ItemStack (hammerDiamond, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustFerrous,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkFerrous), new ItemStack (hammerDiamond, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustSilver,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkSilver), new ItemStack (hammerDiamond, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustTin,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkTin), new ItemStack (hammerDiamond, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustTungsten,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkTungsten), new ItemStack (hammerDiamond, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustCopper,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkCopper), new ItemStack (hammerDiamond, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (Blocks.sand,2, OreDictionary.WILDCARD_VALUE), new ItemStack (Blocks.cobblestone), new ItemStack (hammerDiamond, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustGold,2, OreDictionary.WILDCARD_VALUE), new ItemStack (Blocks.gold_ore), new ItemStack (hammerDiamond, 1, OreDictionary.WILDCARD_VALUE));
//Jade
GameRegistry.addShapelessRecipe(new ItemStack (dustEmerald,2, OreDictionary.WILDCARD_VALUE), new ItemStack (Blocks.emerald_ore), new ItemStack (hammerJade, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack(dustDiamond, 3, OreDictionary.WILDCARD_VALUE), new ItemStack (Blocks.diamond_ore), new ItemStack(hammerJade, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapedRecipe(new ItemStack (jadeHeadSw,1, OreDictionary.WILDCARD_VALUE), " x", " #", 'x', new ItemStack (jadeBlock), '#', new ItemStack (hammerJade, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapedRecipe(new ItemStack (jadeHeadSh,1, OreDictionary.WILDCARD_VALUE), "#x", 'x', new ItemStack (jadeBlock), '#', new ItemStack (hammerJade, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (jadeHeadHo,1, OreDictionary.WILDCARD_VALUE), new ItemStack (jadeBlock), new ItemStack (hammerJade, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapedRecipe(new ItemStack (jadeHeadAx,1, OreDictionary.WILDCARD_VALUE), " #", " x", 'x', new ItemStack (jadeBlock), '#', new ItemStack (hammerJade, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapedRecipe(new ItemStack (jadeHeadPi,1, OreDictionary.WILDCARD_VALUE), " x","# ", 'x', new ItemStack (jadeBlock), '#', new ItemStack (hammerJade, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustCopper,2), new ItemStack (oreCopper), new ItemStack (hammerJade, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustLead,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreLead), new ItemStack (hammerJade, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustFerrous,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreFerrous), new ItemStack (hammerJade, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustCopper,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkCopper), new ItemStack (hammerJade, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustSilver,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreSilver), new ItemStack (hammerJade, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustTin,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreTin), new ItemStack (hammerJade, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustTungsten,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreTungsten), new ItemStack (hammerJade, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustCopper,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreCopper), new ItemStack (hammerJade, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack(dustIron,2,OreDictionary.WILDCARD_VALUE), new ItemStack (Blocks.iron_ore), new ItemStack(hammerJade, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustFlour,4, OreDictionary.WILDCARD_VALUE),new ItemStack(hammerJade, 1, OreDictionary.WILDCARD_VALUE),new ItemStack(Items.wheat));
GameRegistry.addShapelessRecipe(new ItemStack (dustCharcoal,4, OreDictionary.WILDCARD_VALUE),new ItemStack(hammerJade, 1, OreDictionary.WILDCARD_VALUE),new ItemStack(Items.coal,1,1));
GameRegistry.addShapelessRecipe(new ItemStack (dustLead,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkLead), new ItemStack (hammerJade, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustFerrous,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkFerrous), new ItemStack (hammerJade, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustSilver,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkSilver), new ItemStack (hammerJade, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustTin,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkTin), new ItemStack (hammerJade, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustTungsten,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkTungsten), new ItemStack (hammerJade, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustCopper,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkCopper), new ItemStack (hammerJade, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (Blocks.sand,2, OreDictionary.WILDCARD_VALUE), new ItemStack (Blocks.cobblestone), new ItemStack (hammerJade, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustGold,2, OreDictionary.WILDCARD_VALUE), new ItemStack (Blocks.gold_ore), new ItemStack (hammerJade, 1, OreDictionary.WILDCARD_VALUE));
//Netherstar
GameRegistry.addShapelessRecipe(new ItemStack (dustEmerald,2, OreDictionary.WILDCARD_VALUE), new ItemStack (Blocks.emerald_ore), new ItemStack (hammerNetherstar, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack(dustDiamond, 3, OreDictionary.WILDCARD_VALUE), new ItemStack (Blocks.diamond_ore), new ItemStack(hammerNetherstar, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapedRecipe(new ItemStack (jadeHeadSw,1, OreDictionary.WILDCARD_VALUE), " x", " #", 'x', new ItemStack (jadeBlock), '#', new ItemStack (hammerNetherstar, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapedRecipe(new ItemStack (jadeHeadSh,1, OreDictionary.WILDCARD_VALUE), "#x", 'x', new ItemStack (jadeBlock), '#', new ItemStack (hammerNetherstar, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (jadeHeadHo,1, OreDictionary.WILDCARD_VALUE), new ItemStack (jadeBlock), new ItemStack (hammerNetherstar, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapedRecipe(new ItemStack (jadeHeadAx,1, OreDictionary.WILDCARD_VALUE), " #", " x", 'x', new ItemStack (jadeBlock), '#', new ItemStack (hammerNetherstar, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapedRecipe(new ItemStack (jadeHeadPi,1, OreDictionary.WILDCARD_VALUE), " x","# ", 'x', new ItemStack (jadeBlock), '#', new ItemStack (hammerNetherstar, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustCopper,2), new ItemStack (oreCopper), new ItemStack (hammerNetherstar, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustLead,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreLead), new ItemStack (hammerNetherstar, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustFerrous,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreFerrous), new ItemStack (hammerNetherstar, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustCopper,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkCopper), new ItemStack (hammerNetherstar, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustSilver,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreSilver), new ItemStack (hammerNetherstar, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustTin,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreTin), new ItemStack (hammerNetherstar, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustTungsten,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreTungsten), new ItemStack (hammerNetherstar, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustCopper,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreCopper), new ItemStack (hammerNetherstar, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack(dustIron,2,OreDictionary.WILDCARD_VALUE), new ItemStack (Blocks.iron_ore), new ItemStack(hammerNetherstar, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustFlour,4, OreDictionary.WILDCARD_VALUE),new ItemStack(hammerNetherstar, 1, OreDictionary.WILDCARD_VALUE),new ItemStack(Items.wheat));
GameRegistry.addShapelessRecipe(new ItemStack (dustCharcoal,4, OreDictionary.WILDCARD_VALUE),new ItemStack(hammerNetherstar, 1, OreDictionary.WILDCARD_VALUE),new ItemStack(Items.coal,1,1));
GameRegistry.addShapelessRecipe(new ItemStack (dustLead,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkLead), new ItemStack (hammerNetherstar, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustFerrous,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkFerrous), new ItemStack (hammerNetherstar, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustSilver,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkSilver), new ItemStack (hammerNetherstar, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustTin,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkTin), new ItemStack (hammerNetherstar, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustTungsten,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkTungsten), new ItemStack (hammerNetherstar, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustCopper,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkCopper), new ItemStack (hammerNetherstar, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (Blocks.sand,2, OreDictionary.WILDCARD_VALUE), new ItemStack (Blocks.cobblestone), new ItemStack (hammerNetherstar, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustGold,2, OreDictionary.WILDCARD_VALUE), new ItemStack (Blocks.gold_ore), new ItemStack (hammerNetherstar, 1, OreDictionary.WILDCARD_VALUE));
//sandstone
GameRegistry.addShapedRecipe(new ItemStack (jadeHeadSw,1, OreDictionary.WILDCARD_VALUE), " x", " #", 'x', new ItemStack (jadeBlock), '#', new ItemStack (hammerSandstone, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapedRecipe(new ItemStack (jadeHeadSh,1, OreDictionary.WILDCARD_VALUE), "#x", 'x', new ItemStack (jadeBlock), '#', new ItemStack (hammerSandstone, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (jadeHeadHo,1, OreDictionary.WILDCARD_VALUE), new ItemStack (jadeBlock), new ItemStack (hammerSandstone, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapedRecipe(new ItemStack (jadeHeadAx,1, OreDictionary.WILDCARD_VALUE), " #", " x", 'x', new ItemStack (jadeBlock), '#', new ItemStack (hammerSandstone, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapedRecipe(new ItemStack (jadeHeadPi,1, OreDictionary.WILDCARD_VALUE), " x","# ", 'x', new ItemStack (jadeBlock), '#', new ItemStack (hammerSandstone, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustCopper,2), new ItemStack (oreCopper), new ItemStack (hammerSandstone, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustLead,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreLead), new ItemStack (hammerSandstone, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustFerrous,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreFerrous), new ItemStack (hammerSandstone, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustCopper,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkCopper), new ItemStack (hammerSandstone, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustSilver,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreSilver), new ItemStack (hammerSandstone, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustTin,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreTin), new ItemStack (hammerSandstone, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustTungsten,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreTungsten), new ItemStack (hammerSandstone, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustCopper,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreCopper), new ItemStack (hammerSandstone, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack(dustIron,2,OreDictionary.WILDCARD_VALUE), new ItemStack (Blocks.iron_ore), new ItemStack(hammerSandstone, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustFlour,4, OreDictionary.WILDCARD_VALUE),new ItemStack(hammerSandstone, 1, OreDictionary.WILDCARD_VALUE),new ItemStack(Items.wheat));
GameRegistry.addShapelessRecipe(new ItemStack (dustCharcoal,4, OreDictionary.WILDCARD_VALUE),new ItemStack(hammerSandstone, 1, OreDictionary.WILDCARD_VALUE),new ItemStack(Items.coal,1,1));
GameRegistry.addShapelessRecipe(new ItemStack (dustLead,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkLead), new ItemStack (hammerSandstone, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustFerrous,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkFerrous), new ItemStack (hammerSandstone, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustSilver,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkSilver), new ItemStack (hammerSandstone, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustTin,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkTin), new ItemStack (hammerSandstone, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustTungsten,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkTungsten), new ItemStack (hammerSandstone, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustCopper,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkCopper), new ItemStack (hammerSandstone, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (Blocks.sand,2, OreDictionary.WILDCARD_VALUE), new ItemStack (Blocks.cobblestone), new ItemStack (hammerSandstone, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustGold,2, OreDictionary.WILDCARD_VALUE), new ItemStack (Blocks.gold_ore), new ItemStack (hammerSandstone, 1, OreDictionary.WILDCARD_VALUE));
//wooden
GameRegistry.addShapedRecipe(new ItemStack (jadeHeadSw,1, OreDictionary.WILDCARD_VALUE), " x", " #", 'x', new ItemStack (jadeBlock), '#', new ItemStack (hammerWooden, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapedRecipe(new ItemStack (jadeHeadSh,1, OreDictionary.WILDCARD_VALUE), "#x", 'x', new ItemStack (jadeBlock), '#', new ItemStack (hammerWooden, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (jadeHeadHo,1, OreDictionary.WILDCARD_VALUE), new ItemStack (jadeBlock), new ItemStack (hammerWooden, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapedRecipe(new ItemStack (jadeHeadAx,1, OreDictionary.WILDCARD_VALUE), " #", " x", 'x', new ItemStack (jadeBlock), '#', new ItemStack (hammerWooden, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapedRecipe(new ItemStack (jadeHeadPi,1, OreDictionary.WILDCARD_VALUE), " x","# ", 'x', new ItemStack (jadeBlock), '#', new ItemStack (hammerWooden, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustCopper,2), new ItemStack (oreCopper), new ItemStack (hammerWooden, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustLead,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreLead), new ItemStack (hammerWooden, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustFerrous,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreFerrous), new ItemStack (hammerWooden, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustCopper,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkCopper), new ItemStack (hammerWooden, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustSilver,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreSilver), new ItemStack (hammerWooden, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustTin,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreTin), new ItemStack (hammerWooden, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustTungsten,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreTungsten), new ItemStack (hammerWooden, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustCopper,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreCopper), new ItemStack (hammerWooden, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack(dustIron,2,OreDictionary.WILDCARD_VALUE), new ItemStack (Blocks.iron_ore), new ItemStack(hammerWooden, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustFlour,4, OreDictionary.WILDCARD_VALUE),new ItemStack(hammerWooden, 1, OreDictionary.WILDCARD_VALUE),new ItemStack(Items.wheat));
GameRegistry.addShapelessRecipe(new ItemStack (dustCharcoal,4, OreDictionary.WILDCARD_VALUE),new ItemStack(hammerWooden, 1, OreDictionary.WILDCARD_VALUE),new ItemStack(Items.coal,1,1));
GameRegistry.addShapelessRecipe(new ItemStack (dustLead,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkLead), new ItemStack (hammerWooden, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustFerrous,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkFerrous), new ItemStack (hammerWooden, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustSilver,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkSilver), new ItemStack (hammerWooden, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustTin,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkTin), new ItemStack (hammerWooden, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustTungsten,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkTungsten), new ItemStack (hammerWooden, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustCopper,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkCopper), new ItemStack (hammerWooden, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (Blocks.sand,2, OreDictionary.WILDCARD_VALUE), new ItemStack (Blocks.cobblestone), new ItemStack (hammerWooden, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustGold,2, OreDictionary.WILDCARD_VALUE), new ItemStack (Blocks.gold_ore), new ItemStack (hammerWooden, 1, OreDictionary.WILDCARD_VALUE));
//Copper
GameRegistry.addShapedRecipe(new ItemStack (jadeHeadSw,1, OreDictionary.WILDCARD_VALUE), " x", " #", 'x', new ItemStack (jadeBlock), '#', new ItemStack (hammerCopper, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapedRecipe(new ItemStack (jadeHeadSh,1, OreDictionary.WILDCARD_VALUE), "#x", 'x', new ItemStack (jadeBlock), '#', new ItemStack (hammerCopper, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (jadeHeadHo,1, OreDictionary.WILDCARD_VALUE), new ItemStack (jadeBlock), new ItemStack (hammerCopper, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapedRecipe(new ItemStack (jadeHeadAx,1, OreDictionary.WILDCARD_VALUE), " #", " x", 'x', new ItemStack (jadeBlock), '#', new ItemStack (hammerCopper, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapedRecipe(new ItemStack (jadeHeadPi,1, OreDictionary.WILDCARD_VALUE), " x","# ", 'x', new ItemStack (jadeBlock), '#', new ItemStack (hammerCopper, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustCopper,2), new ItemStack (oreCopper), new ItemStack (hammerCopper, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustLead,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreLead), new ItemStack (hammerCopper, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustFerrous,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreFerrous), new ItemStack (hammerCopper, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustSilver,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreSilver), new ItemStack (hammerCopper, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustTin,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreTin), new ItemStack (hammerCopper, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustTungsten,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreTungsten), new ItemStack (hammerCopper, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustCopper,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreCopper), new ItemStack (hammerCopper, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack(dustIron,2,OreDictionary.WILDCARD_VALUE), new ItemStack (Blocks.iron_ore), new ItemStack(hammerCopper, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustFlour,4, OreDictionary.WILDCARD_VALUE),new ItemStack(hammerCopper, 1, OreDictionary.WILDCARD_VALUE),new ItemStack(Items.wheat));
GameRegistry.addShapelessRecipe(new ItemStack (dustCharcoal,4, OreDictionary.WILDCARD_VALUE),new ItemStack(hammerCopper, 1, OreDictionary.WILDCARD_VALUE),new ItemStack(Items.coal,1,1));
GameRegistry.addShapelessRecipe(new ItemStack (dustCopper,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkCopper), new ItemStack (hammerCopper, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustLead,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkLead), new ItemStack (hammerCopper, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustFerrous,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkFerrous), new ItemStack (hammerCopper, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustSilver,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkSilver), new ItemStack (hammerCopper, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustTin,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkTin), new ItemStack (hammerCopper, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustTungsten,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkTungsten), new ItemStack (hammerCopper, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustCopper,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkCopper), new ItemStack (hammerCopper, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (Blocks.sand,2, OreDictionary.WILDCARD_VALUE), new ItemStack (Blocks.cobblestone), new ItemStack (hammerCopper, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustGold,2, OreDictionary.WILDCARD_VALUE), new ItemStack (Blocks.gold_ore), new ItemStack (hammerCopper, 1, OreDictionary.WILDCARD_VALUE));
//silver
GameRegistry.addShapedRecipe(new ItemStack (jadeHeadSw,1, OreDictionary.WILDCARD_VALUE), " x", " #", 'x', new ItemStack (jadeBlock), '#', new ItemStack (hammerSilver, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapedRecipe(new ItemStack (jadeHeadSh,1, OreDictionary.WILDCARD_VALUE), "#x", 'x', new ItemStack (jadeBlock), '#', new ItemStack (hammerSilver, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (jadeHeadHo,1, OreDictionary.WILDCARD_VALUE), new ItemStack (jadeBlock), new ItemStack (hammerSilver, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapedRecipe(new ItemStack (jadeHeadAx,1, OreDictionary.WILDCARD_VALUE), " #", " x", 'x', new ItemStack (jadeBlock), '#', new ItemStack (hammerSilver, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapedRecipe(new ItemStack (jadeHeadPi,1, OreDictionary.WILDCARD_VALUE), " x","# ", 'x', new ItemStack (jadeBlock), '#', new ItemStack (hammerSilver, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustCopper,2), new ItemStack (oreCopper), new ItemStack (hammerSilver, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustLead,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreLead), new ItemStack (hammerSilver, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustFerrous,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreFerrous), new ItemStack (hammerSilver, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustCopper,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkCopper), new ItemStack (hammerSilver, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustSilver,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreSilver), new ItemStack (hammerSilver, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustTin,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreTin), new ItemStack (hammerSilver, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustTungsten,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreTungsten), new ItemStack (hammerSilver, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustCopper,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreCopper), new ItemStack (hammerSilver, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack(dustIron,2,OreDictionary.WILDCARD_VALUE), new ItemStack (Blocks.iron_ore), new ItemStack(hammerSilver, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustFlour,4, OreDictionary.WILDCARD_VALUE),new ItemStack(hammerSilver, 1, OreDictionary.WILDCARD_VALUE),new ItemStack(Items.wheat));
GameRegistry.addShapelessRecipe(new ItemStack (dustCharcoal,4, OreDictionary.WILDCARD_VALUE),new ItemStack(hammerSilver, 1, OreDictionary.WILDCARD_VALUE),new ItemStack(Items.coal,1,1));
GameRegistry.addShapelessRecipe(new ItemStack (dustLead,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkLead), new ItemStack (hammerSilver, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustFerrous,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkFerrous), new ItemStack (hammerSilver, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustSilver,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkSilver), new ItemStack (hammerSilver, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustTin,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkTin), new ItemStack (hammerSilver, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustTungsten,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkTungsten), new ItemStack (hammerSilver, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustCopper,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkCopper), new ItemStack (hammerSilver, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (Blocks.sand,2, OreDictionary.WILDCARD_VALUE), new ItemStack (Blocks.cobblestone), new ItemStack (hammerSilver, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustGold,2, OreDictionary.WILDCARD_VALUE), new ItemStack (Blocks.gold_ore), new ItemStack (hammerSilver, 1, OreDictionary.WILDCARD_VALUE));
//#addironhammer
//public static Item headDiamond;
//public static Item headJade;
//public static Item headNetherstar;
//public static Item headSandstone;
//public static Item headWooden;
//public static Item headCopper;
//public static Item headSilver;
//public static Item hammerDiamond;
//public static Item hammerJade;
// public static Item hammerNetherstar;
// public static Item hammerSandstone;
// public static Item hammerWooden;
// public static Item hammerCopper;
// public static Item hammerSilver;
//Hammer Crafting
GameRegistry.addShapelessRecipe(new ItemStack (stoneHammer), new ItemStack (stoneHamHead), new ItemStack (Items.stick));
GameRegistry.addShapedRecipe(new ItemStack (stoneHamHead), " ", "# #","###", '#', new ItemStack (Blocks.cobblestone));
GameRegistry.addShapelessRecipe(new ItemStack (hammerDiamond), new ItemStack (headDiamond), new ItemStack (Items.stick));
GameRegistry.addShapedRecipe(new ItemStack (headDiamond), " ", "# #","###", '#', new ItemStack (Items.diamond));
GameRegistry.addShapelessRecipe(new ItemStack (hammerJade), new ItemStack (headJade), new ItemStack (Items.stick));
GameRegistry.addShapedRecipe(new ItemStack (headJade), " ", "# #","###", '#', new ItemStack (RPCore.gemJadepure));
GameRegistry.addShapelessRecipe(new ItemStack (hammerNetherstar), new ItemStack (headNetherstar), new ItemStack (Items.stick));
GameRegistry.addShapedRecipe(new ItemStack (headNetherstar), " ", "# #","###", '#', new ItemStack (RPCore.ingotNetherstar));
GameRegistry.addShapelessRecipe(new ItemStack (hammerSandstone), new ItemStack (headSandstone), new ItemStack (Items.stick));
GameRegistry.addShapedRecipe(new ItemStack (headSandstone), " ", "# #","###", '#', new ItemStack (Blocks.sandstone));
GameRegistry.addShapelessRecipe(new ItemStack (hammerWooden), new ItemStack (headWooden), new ItemStack (Items.stick));
GameRegistry.addShapedRecipe(new ItemStack (headWooden), " ", "# #","###", '#', new ItemStack (Blocks.planks));
GameRegistry.addShapelessRecipe(new ItemStack (hammerCopper), new ItemStack (headCopper), new ItemStack (Items.stick));
GameRegistry.addShapedRecipe(new ItemStack (headCopper), " ", "# #","###", '#', new ItemStack (RPCore.ingotCopper));
GameRegistry.addShapelessRecipe(new ItemStack (hammerSilver), new ItemStack (headSilver), new ItemStack (Items.stick));
GameRegistry.addShapedRecipe(new ItemStack (headSilver), " ", "# #","###", '#', new ItemStack (RPCore.ingotSilver));
//Hammer End------- #AllofThehammerrecipes o.o
//Caustic Crafting
GameRegistry.addShapelessRecipe(new ItemStack(RPCore.causticCorpuscles,2),new ItemStack(Items.rotten_flesh), new ItemStack(toolSkinning,1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapedRecipe(new ItemStack (toolSkinning,1), "# #", "# #"," # ", '#', new ItemStack (Items.iron_ingot));
//GameRegistry.addShapelessRecipe(new ItemStack (bloodFirey,1)," # ","# #","###","#", new ItemStack (Blocks.glass_pane)); <-Dont Use Will Crash Game
GameRegistry.addShapelessRecipe(new ItemStack (bloodFirey,1),new ItemStack(RPCore.causticMeal), new ItemStack(Items.glass_bottle));
GameRegistry.addShapelessRecipe(new ItemStack (acidSulfuric ,1),new ItemStack(RPCore.causticCorpuscles), new ItemStack(Items.glass_bottle));
GameRegistry.addShapelessRecipe(new ItemStack (causticMeal,2),new ItemStack(RPCore.causticCorpuscles), new ItemStack(Items.dye,1,15));
GameRegistry.addShapelessRecipe(new ItemStack (dustPN,1),new ItemStack(RPCore.bloodFirey), new ItemStack(acidSulfuric));
GameRegistry.addShapedRecipe(new ItemStack (Items.gunpowder,4),"###","#0#","###", '#', new ItemStack (RPCore.dustCharcoal),'0',new ItemStack(RPCore.dustPN));
//###
//#0#
//###
GameRegistry.addShapelessRecipe(new ItemStack (dustMagickcompound,2), new ItemStack(dustMagick), new ItemStack(Items.glowstone_dust), new ItemStack(Items.redstone));
GameRegistry.addShapelessRecipe(new ItemStack(baconRaw,3, OreDictionary.WILDCARD_VALUE), new ItemStack (Items.porkchop), new ItemStack(knife, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (elderPlanks,5), new ItemStack (elderLog));
GameRegistry.addShapelessRecipe(new ItemStack(dropMagick,4), new ItemStack (Items.water_bucket), new ItemStack (dustMagickcompound), new ItemStack(dustDiamond),new ItemStack (runePlate));
GameRegistry.addShapelessRecipe(new ItemStack(dropBig,1), new ItemStack (dropMagick), new ItemStack(Items.dye,1,3));
GameRegistry.addShapelessRecipe(new ItemStack(dropBounce,1),new ItemStack (dropMagick), new ItemStack(Items.dye,1,7));
GameRegistry.addShapelessRecipe(new ItemStack(dropDeath,1),new ItemStack (dropMagick),new ItemStack(Items.dye));
GameRegistry.addShapelessRecipe(new ItemStack(dropFly,1),new ItemStack (dropMagick),new ItemStack(Items.dye,1,11));
GameRegistry.addShapelessRecipe(new ItemStack(dropLife,1),new ItemStack (dropMagick),new ItemStack(Items.dye,1,2));
GameRegistry.addShapelessRecipe(new ItemStack(dropPoison,1),new ItemStack (dropMagick),new ItemStack(Items.dye,1,5));
GameRegistry.addShapelessRecipe(new ItemStack(dropRock,1),new ItemStack (dropMagick),new ItemStack(Items.dye,1,8));
GameRegistry.addShapelessRecipe(new ItemStack(dropSmall,1),new ItemStack (dropMagick),new ItemStack(Items.dye,1,5));
GameRegistry.addShapelessRecipe(new ItemStack(dropSuper,1),new ItemStack (dropMagick),new ItemStack(Items.dye,1,9));
GameRegistry.addShapelessRecipe(new ItemStack(megaCookie,4),new ItemStack(dropBig),new ItemStack(cookieSugar));
GameRegistry.addShapelessRecipe(new ItemStack(ghostCookie,4),new ItemStack(dropDeath),new ItemStack(dropLife),new ItemStack(cookieSugar));
GameRegistry.addShapelessRecipe(new ItemStack(poisonCookie,4),new ItemStack(dropDeath),new ItemStack(cookieSugar));
GameRegistry.addShapelessRecipe(new ItemStack(miniCookie,4),new ItemStack(dropSmall),new ItemStack(cookieSugar));
GameRegistry.addShapelessRecipe(new ItemStack(oneupCookie,4),new ItemStack(dropLife),new ItemStack(cookieSugar));
GameRegistry.addShapelessRecipe(new ItemStack(springCookie,4),new ItemStack(dropBounce),new ItemStack(cookieSugar));
GameRegistry.addShapelessRecipe(new ItemStack(propellerCookie,4),new ItemStack(dropFly),new ItemStack(cookieSugar));
GameRegistry.addShapelessRecipe(new ItemStack(rockCookie,4),new ItemStack(dropRock),new ItemStack(cookieSugar));
GameRegistry.addShapelessRecipe(new ItemStack(superCookie,4),new ItemStack(dropSuper),new ItemStack(cookieSugar));
GameRegistry.addShapedRecipe(new ItemStack (cookieSugar,4)," ","#0#"," ", '#', new ItemStack (RPCore.dustFlour),'0',new ItemStack(Items.sugar));
GameRegistry.addShapelessRecipe(new ItemStack(Blocks.planks), new ItemStack(elderPlanks));
GameRegistry.addShapelessRecipe(new ItemStack(gemJadepure, 4), new ItemStack(jadeBlock));
GameRegistry.addShapelessRecipe(new ItemStack(ingotCopper, 9), new ItemStack(copperBlock));
GameRegistry.addShapelessRecipe(new ItemStack(ingotLead, 9), new ItemStack(leadBlock));
GameRegistry.addShapelessRecipe(new ItemStack(ingotFerrous, 9), new ItemStack(ferrousBlock));
GameRegistry.addShapelessRecipe(new ItemStack(ingotNetherstar, 9), new ItemStack(netherstarBlock));
GameRegistry.addShapelessRecipe(new ItemStack(gemDiamond, 9), new ItemStack(organizeddiamondBlock));
GameRegistry.addShapelessRecipe(new ItemStack(gemEmerald, 9), new ItemStack(organizedemeraldBlock));
GameRegistry.addShapelessRecipe(new ItemStack(ingotSilver, 9), new ItemStack(silverBlock));
GameRegistry.addShapelessRecipe(new ItemStack(ingotTin, 9), new ItemStack(tinBlock));
GameRegistry.addShapelessRecipe(new ItemStack(ingotTungsten, 9), new ItemStack(tungstenBlock));
GameRegistry.addShapelessRecipe(new ItemStack(TCAI, 9), new ItemStack(tungstencarbideBlock));
GameRegistry.registerWorldGenerator(new RPWorldGen(), 1);
GameRegistry.registerFuelHandler(new RPFuelHandler());
NetworkRegistry.INSTANCE.registerGuiHandler(this, new GuiHandler());
proxy.registerProxies();
}
private Object ItemStack() {
// TODO Auto-generated method stub
return null;
}
public static ItemStack anthracite() {
// TODO Auto-generated method stub
return null;
}
}
//test Sync
| java/net/RPower/RPowermod/core/RPCore.java | //#######################
//## ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___
//## /\ \ /\ \ /\ \ /\ \ /\ \ /\ \ |\__\ /\ \ /\ \ /\ \ /\ \ /\ \ /\ \ /\ \ /\ \ /\ \ /\__\
//## /::\ \ /::\ \ /::\ \ /::\ \ /::\ \ /::\ \ |:| | /::\ \ /::\ \ /::\ \ /::\ \ /::\ \ /::\ \ \:\ \ /::\ \ /::\ \ /::| |
//## /:/\:\ \ /:/\:\ \ /:/\:\ \ /:/\:\ \ /:/\:\ \ /:/\:\ \ |:| | /:/\:\ \ /:/\:\ \ /:/\:\ \ /:/\:\ \ /:/\:\ \ /:/\ \ \ \:\ \ /:/\:\ \ /:/\:\ \ /:|:| |
//## /::\~\:\ \ /::\~\:\ \ /::\~\:\ \ /::\~\:\ \ /:/ \:\__\ /:/ \:\ \ |:|__|__ /:/ \:\ \ /:/ \:\ \ /:/ \:\__\ /::\~\:\ \ /::\~\:\ \ _\:\~\ \ \ /::\ \ /::\~\:\ \ /::\~\:\ \ /:/|:|__|__
//## /:/\:\ \:\__\ /:/\:\ \:\__\ /:/\:\ \:\__\ /:/\:\ \:\__\ /:/__/ \:|__| /:/__/ \:\__\ ____/::::\__\ /:/__/ \:\__\ /:/__/ \:\__\ /:/__/ \:|__| /:/\:\ \:\__\ /:/\:\ \:\__\ /\ \:\ \ \__\ /:/\:\__\ /:/\:\ \:\__\ /:/\:\ \:\__\ /:/ |::::\__\
//## \/__\:\/:/ / \/__\:\/:/ / \/_|::\/:/ / \/__\:\/:/ / \:\ \ /:| | \:\ \ /:/ / \::::/~~/~ \:\ \ \/__/ \:\ \ /:/ / \:\ \ /:/ / \:\~\:\ \/__/ \/_|::\/:/ / \:\ \:\ \/__/ /:/ \/__/ \:\~\:\ \/__/ \/__\:\/:/ / \/__/~~/:/ /
//## \::/ / \::/ / |:|::/ / \::/ / \:\ /:/ / \:\ /:/ / ~~|:|~~| \:\ \ \:\ /:/ / \:\ /:/ / \:\ \:\__\ |:|::/ / \:\ \:\__\ /:/ / \:\ \:\__\ \::/ / /:/ /
//## \/__/ /:/ / |:|\/__/ /:/ / \:\/:/ / \:\/:/ / |:| | \:\ \ \:\/:/ / \:\/:/ / \:\ \/__/ |:|\/__/ \:\/:/ / \/__/ \:\ \/__/ /:/ / /:/ /
//## /:/ / |:| | /:/ / \__/__/ \::/ / |:| | \:\__\ \::/ / \::/__/ \:\__\ |:| | \::/ / \:\__\ /:/ / /:/ /
//## \/__/ \|__| \/__/ \/__/ \|__| \/__/ \/__/ ~~ \/__/ \|__| \/__/ \/__/ \/__/ \/__/
//##
//##
//##
//##
//## Mod Made Possible by Magnus,Backspace & Rebel
//##
//##
//##
//##
//##
//##
//#######################
package net.RPower.RPowermod.core;
import net.RPower.RPowermod.block.BlockTCAM;
import net.RPower.RPowermod.block.BlockoreAnthtracite;
import net.RPower.RPowermod.block.BlocksandTreated;
import net.RPower.RPowermod.block.ObsidianWhite;
import net.RPower.RPowermod.block.blockREBL;
import net.RPower.RPowermod.block.blockREBLo;
import net.RPower.RPowermod.block.blockREBS;
import net.RPower.RPowermod.block.blockRPBlock;
import net.RPower.RPowermod.block.blockRPBlockBSpace;
import net.RPower.RPowermod.block.blockRPOre;
<<<<<<< HEAD
import net.RPower.RPowermod.item.ItemAnthracite;
import net.RPower.RPowermod.item.ItemBronzeDust;
import net.RPower.RPowermod.item.ItemCopperDust;
import net.RPower.RPowermod.item.ItemCopperIngot;
import net.RPower.RPowermod.item.ItemDiamondDust;
import net.RPower.RPowermod.item.ItemDiamondIngot;
import net.RPower.RPowermod.item.ItemEmeraldDust;
import net.RPower.RPowermod.item.ItemEmeraldIngot;
import net.RPower.RPowermod.item.ItemFerrousDust;
import net.RPower.RPowermod.item.ItemFerrousIngot;
import net.RPower.RPowermod.item.ItemFoodbaconCooked;
import net.RPower.RPowermod.item.ItemFoodbaconRaw;
import net.RPower.RPowermod.item.ItemFoodcookieSugar;
import net.RPower.RPowermod.item.ItemFoodghostCookie;
import net.RPower.RPowermod.item.ItemFoodmegaCookie;
import net.RPower.RPowermod.item.ItemFoodminiCookie;
import net.RPower.RPowermod.item.ItemFoodoneupCookie;
import net.RPower.RPowermod.item.ItemFoodpoisonCookie;
import net.RPower.RPowermod.item.ItemFoodpropellerCookie;
import net.RPower.RPowermod.item.ItemFoodrockCookie;
import net.RPower.RPowermod.item.ItemFoodspringCookie;
import net.RPower.RPowermod.item.ItemFoodsuperCookie;
import net.RPower.RPowermod.item.ItemFoodtestCookie;
import net.RPower.RPowermod.item.ItemGoldDust;
import net.RPower.RPowermod.item.ItemHeadBspace;
import net.RPower.RPowermod.item.ItemIronDust;
import net.RPower.RPowermod.item.ItemJade;
import net.RPower.RPowermod.item.ItemJadeAxe;
import net.RPower.RPowermod.item.ItemJadeHoe;
import net.RPower.RPowermod.item.ItemJadePickaxe;
import net.RPower.RPowermod.item.ItemJadeSpade;
import net.RPower.RPowermod.item.ItemJadeSword;
import net.RPower.RPowermod.item.ItemLeadDust;
import net.RPower.RPowermod.item.ItemLeadIngot;
import net.RPower.RPowermod.item.ItemNetherstarDust;
import net.RPower.RPowermod.item.ItemNetherstarIngot;
import net.RPower.RPowermod.item.ItemSilverDust;
import net.RPower.RPowermod.item.ItemSilverIngot;
import net.RPower.RPowermod.item.ItemSteelDust;
import net.RPower.RPowermod.item.ItemTCAI;
import net.RPower.RPowermod.item.ItemTinDust;
import net.RPower.RPowermod.item.ItemTinIngot;
import net.RPower.RPowermod.item.ItemTugstenDust;
import net.RPower.RPowermod.item.ItemTungstenIngot;
import net.RPower.RPowermod.item.ItemTungstencarbideIngot;
import net.RPower.RPowermod.item.ItemblankScroll;
import net.RPower.RPowermod.item.ItemdustFlour;
import net.RPower.RPowermod.item.ItemdustSugar;
import net.RPower.RPowermod.item.ItemingotBronze;
import net.RPower.RPowermod.item.ItemingotSteel;
import net.RPower.RPowermod.item.Itemknife;
import net.RPower.RPowermod.item.Itemmortar_and_pestle;
import net.RPower.RPowermod.item.ItemquartcBowl;
import net.RPower.RPowermod.item.ItemquartcStick;
import net.RPower.RPowermod.item.ItemsandPaper;
import net.RPower.RPowermod.item.ItemscrollCircle;
import net.RPower.RPowermod.item.ItemyellowLeaf;
import net.RPower.RPowermod.item.chunkCopper;
import net.RPower.RPowermod.item.dropBig;
import net.RPower.RPowermod.item.dropBounce;
import net.RPower.RPowermod.item.dropDeath;
import net.RPower.RPowermod.item.dropFly;
import net.RPower.RPowermod.item.dropLife;
import net.RPower.RPowermod.item.dropMagick;
import net.RPower.RPowermod.item.dropPoisen;
import net.RPower.RPowermod.item.dropRock;
import net.RPower.RPowermod.item.dropSmall;
import net.RPower.RPowermod.item.dropSuper;
import net.RPower.RPowermod.item.dustMagick;
import net.RPower.RPowermod.item.dustMagickcompound;
import net.RPower.RPowermod.item.hammerCopper;
import net.RPower.RPowermod.item.hammerDiamond;
import net.RPower.RPowermod.item.hammerJade;
import net.RPower.RPowermod.item.hammerNetherstar;
import net.RPower.RPowermod.item.hammerSandstone;
import net.RPower.RPowermod.item.hammerSilver;
import net.RPower.RPowermod.item.hammerStone;
import net.RPower.RPowermod.item.hammerWooden;
import net.RPower.RPowermod.item.itemDustPN;
import net.RPower.RPowermod.item.itemPencil;
import net.RPower.RPowermod.item.itemSkinningtool;
import net.RPower.RPowermod.item.itemacidS;
import net.RPower.RPowermod.item.itembloodFirey;
import net.RPower.RPowermod.item.itemcorpCaustic;
import net.RPower.RPowermod.item.itemdustCharcoal;
import net.RPower.RPowermod.item.itemmealCaustic;
import net.RPower.RPowermod.item.runeAir;
import net.RPower.RPowermod.item.runeEarth;
import net.RPower.RPowermod.item.runeFire;
import net.RPower.RPowermod.item.runePlate;
import net.RPower.RPowermod.item.runeSpirit;
import net.RPower.RPowermod.item.runeWater;
=======
import net.RPower.RPowermod.gui.GuiHandler;
import net.RPower.RPowermod.item.*;
>>>>>>> ec95970406957eae8e3cdd0ac616691e205e3dc4
import net.RPower.RPowermod.net.ItemFoodcreativeCookie;
import net.RPower.RPowermod.proxy.CommonProxy;
import net.RPower.RPowermod.tileentity.TileEntityalloySmelter;
import net.RPower.RPowermod.world.RPWorldGen;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.Item.ToolMaterial;
import net.minecraft.item.ItemStack;
import net.minecraftforge.common.util.EnumHelper;
import net.minecraftforge.oredict.OreDictionary;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.Mod.EventHandler;
import cpw.mods.fml.common.Mod.Instance;
import cpw.mods.fml.common.SidedProxy;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.network.NetworkRegistry;
import cpw.mods.fml.common.registry.GameRegistry;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
@Mod(modid = RPCore.modid, name = "Mine Facility", version = "1.0.9")
public class RPCore {
public static final String modid = "rpower";
public static ToolMaterial jadeToolMaterial;
@Instance(modid)
public static RPCore instance;
//Blocks
/*
To add a block first do these lines (public static Block <name of block>;) then inside preInit do (<name of block> = new Block<name of block>(Material.rock).setCreativeTab(CreativeTabs.tabBlock).setBlockName("<name of block whit capital leters and space if two or more words>").setBlockTextureName(modid + ":" + "<texture name of block>"); then under init do (Recipies.registerBlock(<name of block>, "<name of block whit capital leters and space if two or more words>");))
*/
//NOTE BACKSPACE CREATE STEELDUST, BRONZEDUST
//ADD ZINK ORE & BRASSDUST
//Ores
public static Block oreJade;
public static Block oreCopper;
public static Block oreFerrous;
public static Block oreLead;
public static Block oreSilver;
public static Block oreTin;
public static Block oreTungsten;
public static Block oreExp;
public static Block oreAnthtracite;
public static Block obsidianWhite;
public static Block oreZinc;
//Blocks of items
public static Block copperBlock;
public static Block ferrousBlock;
public static Block leadBlock;
public static Block jadeBlock;
public static Block netherstarBlock;
public static Block organizeddiamondBlock;
public static Block organizedemeraldBlock;
public static Block silverBlock;
public static Block tinBlock;
public static Block tungstenBlock;
public static Block tungstencarbideBlock;
//other
public static Block TCAM;
public static Block oreCrusher;
public static Block sandTreated;
//machines
public static Block alloySmelterIdle;
public static Block alloySmelterActive;
public static final int guiIDalloySmelter = 0;
//Trees & Plants
public static Block elderSap;
public static Block elderLeaf;
public static Block elderLog;
public static Block elderPlanks;
public static Block blueStabilizer;
public static Block polymer;
public static Block polymerWoven;
//Caustic Items
public static Item causticMeal;
public static Item causticCorpuscles;
public static Item bloodFirey;
public static Item acidSulfuric;
public static Item dustPN;
public static Item dustCharcoal;
public static Item toolSkinning;
//Food
public static Item megaCookie;
public static Item ghostCookie;
public static Item testCookie;
public static Item poisonCookie;
public static Item miniCookie;
public static Item oneupCookie;
public static Item springCookie;
public static Item propellerCookie;
public static Item rockCookie;
public static Item superCookie;
public static Item baconRaw;
public static Item baconCooked;
public static Item knife;
public static Item dustSugar;
//Items
/*
To add a item first do these lines (public static Item <name of item>;) then inside preInit do (<name of item> = new Item<name of item>().setCreativeTab(CreativeTabs.tabMaterials).setUnlocalizedName("<name of item whit capital leters and space if two or more words>").setTextureName(modid + ":" + "<texture name of item>"); then under init do (Recipies.registerItem(<name of item>, "<name of item whit capital leters and space if two or more words>");))
*/
public static Item gemJade;
public static Item gemJadepure;
public static Item ingotTungsten;
public static Item ingotTungstencarbide;
public static Item ingotCopper;
public static Item gemDiamond;
public static Item gemEmerald;
public static Item ingotFerrous;
public static Item ingotLead;
public static Item ingotNetherstar;
public static Item ingotSilver;
public static Item ingotTin;
public static Item ingotSteel;
public static Item ingotBronze;
public static Item ingotBrass;
public static Item ingotZink;
public static Item magnusCookie;
//Chunks
public static Item chunkTungsten;
public static Item chunkCopper;
public static Item chunkFerrous;
public static Item chunkLead;
public static Item chunkSilver;
public static Item chunkTin;
//Dust
public static Item dustNetherstar;
public static Item dustCopper;
public static Item dustDiamond;
public static Item dustEmerald;
public static Item dustFerrous;
public static Item dustGold;
public static Item dustIron;
public static Item dustLead;
public static Item dustSilver;
public static Item dustTin;
public static Item dustTungsten;
public static Item dustBronze;
public static Item dustSteel;
//random
public static Item amuletofprotestas;
//Electronic Parts
//Capacitor
public static Item foil;
public static Item foilAluminumoxide;
public static Item paperElectrolized;
//parts^^
public static Item capacitorBasic;
public static Item capacitorCopper;
public static Item capacitorDiamond;
public static Item capacitorGold;
public static Item capacitorTungstencarbide;
//Diode
public static Item anvilPostassembly;
public static Item Epoxy;
public static Item lenseReflective;
//parts^^
public static Item diode;
//Resistor
public static Item clayTreated;
public static Item clayTreatedbaked;
public static Item coiledNichrome;
//^^parts
public static Item resistorCase;
public static Item resistorBasic;
public static Item resistorCopper;
public static Item resistorDiamond;
public static Item resistorGold;
public static Item resistorIron;
public static Item resistorTungstencarbide;
//Transistors
public static Item kitTransistor;
//Parts^^
public static Item transistorBasic;
public static Item transistorCopper;
public static Item transistorDiamond;
public static Item transistorGold;
public static Item transistorIron;
public static Item transistorTungstencarbide;
//Protosprays
public static Item protopaintCopper;
public static Item protopaintDiamond;
public static Item protopaintGold;
public static Item protopaintTungstencarbide;
//Runes
public static Item runeAir;
public static Item runeEarth;
public static Item runeFire;
public static Item runePlate;
public static Item runeSpirit;
public static Item runeWater;
public static Item dustMagick;
public static Item dustMagickcompound;
//Stuff
public static Item glue;
public static Item tcbar;
public static Item TCAI;
public static Item jadeSword;
public static Item jadeHoe;
public static Item jadeAxe;
public static Item jadePickaxe;
public static Item jadeShovel;
public static Item anthracite;
public static Item jadeHeadSw;
public static Item jadeHeadSh;
public static Item jadeHeadAx;
public static Item jadeHeadHo;
public static Item jadeHeadPi;
public static Item tungstenCarbideHead;
public static Item tungstenCarbideHammer;
public static Item stoneHammer;
public static Item stoneHamHead;
public static Item sandPaper;
public static Item mortar_and_pestle;
public static Item quartzStick;
public static Item quartzBowl;
public static Item dustFlour;
public static Item cookieSugar;
public static Item Pencil;
public static Item blankScroll;
public static Item scrollCircle;
public static Item oilTreatment;
//Gears/Cog
public static Item mouldCog;
//unfired
public static Item cogUnfiredcopper;
public static Item cogUnfireddiamond;
public static Item cogUnfiredgold;
public static Item cogUnfirediron;
public static Item cogUnfiredtungstencarbide;
//fiered
public static Item cogCopper;
public static Item cogDiamond;
public static Item cogGold;
public static Item cogIron;
public static Item cogTungstencarbide;
//Drops
public static Item dropBig;
public static Item dropBounce;
public static Item dropDeath;
public static Item dropFly;
public static Item dropLife;
public static Item dropMagick;
public static Item dropPoison;
public static Item dropRock;
public static Item dropSmall;
public static Item dropSuper;
//Plants
public static Item yellowLeaf;
//Tool Heads
public static Item headDiamond;
public static Item headJade;
public static Item headNetherstar;
public static Item headSandstone;
public static Item headWooden;
public static Item headCopper;
public static Item headSilver;
//Tools
public static Item hammerDiamond;
public static Item hammerJade;
public static Item hammerNetherstar;
public static Item hammerSandstone;
public static Item hammerWooden;
public static Item hammerCopper;
public static Item hammerSilver;
//Rtools
public static Item axeJadeR;
public static Item hoeJadeR;
public static Item pickaxeJadeR;
public static Item shovelJadeR;
public static Item swordJadeR;
//Handle Modifiers
public static Item handleTCA;
public static Item handleTCASword;
//Other Stuff
public static final Block.SoundType soundTypePiston = new Block.SoundType("stone", 1.0F, 1.0F);
private static final Object ItemStack = null;
@SidedProxy(clientSide="net.RPower.RPowermod.proxy.ClientProxy", serverSide="net.RPower.RPowermod.proxy.CommonProxy")
public static CommonProxy proxy;
public static CreativeTabs RPCoreBTab = new CreativeTabs(modid) {
@SideOnly(Side.CLIENT)
public Item getTabIconItem() {
return Item.getItemFromBlock(jadeBlock);
}
};
public static CreativeTabs RPCoreITab = new CreativeTabs(modid) {
@SideOnly(Side.CLIENT)
public Item getTabIconItem() {
return TCAI;
}
};
@EventHandler
public void preInit(FMLPreInitializationEvent e){
//ToolMaterial
//To Create A Tool Material Do This ToolMaterialName = EnumHelper.addToolMaterial(name, harvestLevel, maxUses, efficiency, damage, enchantability)
/*
* 0 = Wood/Gold
* 1 = Stone
* 2 = Iron
* 3 = Diamond
* 4 = Jade
*/
jadeToolMaterial = EnumHelper.addToolMaterial("JADE", 4, 35, 16F, 7F, 50);
//Blocks----------
//Ores
oreExp = new blockRPOreExp(Material.rock).setCreativeTab(RPCoreBTab).setBlockName("Exp Ore").setBlockTextureName(modid + ":" + "exp_ore").setHardness(5F).setResistance(1F);
oreTin = new blockRPOreTin(Material.rock).setCreativeTab(RPCoreBTab).setBlockName("Tin Ore").setBlockTextureName(modid + ":" + "tin_ore").setHardness(1F).setResistance(0F);
oreSilver = new blockRPOreSilver(Material.rock).setCreativeTab(RPCoreBTab).setBlockName("Silver Ore").setBlockTextureName(modid + ":" + "silver_ore").setHardness(1F).setResistance(1F);
oreJade = new blockRPOre(Material.rock).setCreativeTab(RPCoreBTab).setBlockName("Jade Ore").setBlockTextureName(modid + ":" + "Jade Ore").setHardness(50F).setResistance(5F);
oreCopper = new blockRPBlockBSpace(Material.rock).setCreativeTab(RPCoreBTab).setBlockName("Copper Ore").setBlockTextureName(modid + ":" + "copper_ore").setHardness(1F).setResistance(1F);
oreFerrous = new blockRPOreFerrous(Material.rock).setCreativeTab(RPCoreBTab).setBlockName("Ferrous Ore").setBlockTextureName(modid + ":" + "ferrous_ore").setHardness(1F).setResistance(1F);
oreLead = new blockRPOreLead (Material.rock).setCreativeTab(RPCoreBTab).setBlockName("Lead Ore").setBlockTextureName(modid + ":" + "lead_ore").setHardness(1F).setResistance(1F);
oreTungsten = new blockRPOreTungsten(Material.rock).setCreativeTab(RPCoreBTab).setBlockName("Tungsten Ore").setBlockTextureName(modid + ":" + "tungstenore").setHardness(50F).setResistance(5F);
oreAnthtracite = new BlockoreAnthtracite(Material.rock).setCreativeTab(RPCoreBTab).setBlockName("Anthracite Ore").setBlockTextureName(modid + ":" + "anthracite_ore").setHardness(50F).setResistance(2000F);
obsidianWhite = new ObsidianWhite(Material.rock).setCreativeTab(RPCoreBTab).setBlockName("White Obsidian").setBlockTextureName(modid + ":" + "obsidianWhite").setHardness(50F).setResistance(10F);
oreZinc = new blockRPOreZinc (Material.rock).setCreativeTab(RPCoreBTab).setBlockName("Zinc Ore").setBlockTextureName(modid + ":" + "zinc").setHardness(1F).setResistance(1F);
//Blocks Of items
jadeBlock = new blockRPBlock(Material.rock).setCreativeTab(RPCoreBTab).setBlockName("Jade Block").setBlockTextureName(modid + ":" + "jade_block").setHardness(50F).setResistance(5F);
copperBlock = new blockRPBlock (Material.rock).setCreativeTab(RPCoreBTab).setBlockName("Copper Block").setBlockTextureName(modid + ":" + "copper_block").setHardness(5F).setResistance(1F);
ferrousBlock = new blockRPBlock(Material.rock).setCreativeTab(RPCoreBTab).setBlockName("Ferrous Block").setBlockTextureName(modid + ":" + "ferrous_block").setHardness(5F).setResistance(1F);
leadBlock = new blockRPBlock(Material.rock).setCreativeTab(RPCoreBTab).setBlockName("Lead Block").setBlockTextureName(modid + ":" + "lead_block").setHardness(5F).setResistance(1F);
netherstarBlock = new blockRPBlock(Material.rock).setCreativeTab(RPCoreBTab).setBlockName("Netherstar Block").setBlockTextureName(modid + ":" + "netherstar_block").setHardness(5F).setResistance(1F);
organizeddiamondBlock = new blockRPBlock(Material.rock).setCreativeTab(RPCoreBTab).setBlockName("Organizeddiamond Block").setBlockTextureName(modid + ":" + "organizeddiamond_block").setHardness(5F).setResistance(1F);
organizedemeraldBlock = new blockRPBlock(Material.rock).setCreativeTab(RPCoreBTab).setBlockName("Organizedemerald Block").setBlockTextureName(modid + ":" + "organizedemerald_block").setHardness(5F).setResistance(1F);
silverBlock = new blockRPBlock(Material.rock).setCreativeTab(RPCoreBTab).setBlockName("Silver Block").setBlockTextureName(modid + ":" + "silver_block").setHardness(5F).setResistance(1F);
tinBlock = new blockRPBlock(Material.rock).setCreativeTab(RPCoreBTab).setBlockName("Tin Block").setBlockTextureName(modid + ":" + "tin_block").setHardness(5F).setResistance(1F);
tungstenBlock = new blockRPBlock(Material.rock).setCreativeTab(RPCoreBTab).setBlockName("Tungsten Block").setBlockTextureName(modid + ":" + "tungsten_block").setHardness(5F).setResistance(1F);
tungstencarbideBlock = new blockRPBlock(Material.rock).setCreativeTab(RPCoreBTab).setBlockName("Tungstencarbide Block").setBlockTextureName(modid + ":" + "tungstencarbide_block").setHardness(5F).setResistance(1F);
//
sandTreated = new BlocksandTreated(Material.rock).setCreativeTab(RPCoreITab).setBlockName("Treated Sand").setBlockTextureName(modid + ":" + "sandTreated").setHardness(50F).setResistance(5F);
//Alloys
TCAM = new BlockTCAM(Material.rock).setCreativeTab(RPCoreBTab).setBlockName("TCAM").setBlockTextureName(modid + ":" + "TCAM").setHardness(50F).setResistance(5F);
//Machines
oreCrusher = new BlockoreCrusher(false).setCreativeTab(RPCoreBTab).setBlockName("Ore Crusher").setHardness(50F).setResistance(5F);
alloySmelterIdle = new alloySmelter(false).setCreativeTab(RPCoreBTab).setBlockName("alloySmelterIdle");
alloySmelterActive = new alloySmelter(true).setBlockName("alloySmelterActive").setLightLevel(0.625F);
//Woods & Planks & Trees
elderLog = new blockREBLo().setBlockName("Red Elderberry Log").setHardness(1.5F).setResistance(1F).setStepSound(Block.soundTypeWood).setCreativeTab(RPCoreBTab).setBlockTextureName("log");
elderLeaf = new blockREBL(Material.leaves).setBlockName("Red Elderberry Leaves").setHardness(0.5F).setStepSound(Block.soundTypeGrass).setCreativeTab(RPCoreBTab).setBlockTextureName(modid + ":" + "leaves_redelderberry");
elderSap = new blockREBS().setBlockName("Red Elderberry Sapling").setHardness(0.0F).setCreativeTab(RPCoreBTab).setStepSound(Block.soundTypeGrass).setBlockTextureName(modid + ":" + "elderSap").setBlockTextureName("sapling");
elderPlanks = new blockRPBlock(Material.wood).setCreativeTab(RPCoreBTab).setBlockName("Elder Planks").setBlockTextureName(modid + ":" + "planks_redelderberry").setHardness(1.5F).setStepSound(Block.soundTypeWood).setResistance(0.5F);
polymer = new blockRPBlock(Material.glass).setCreativeTab(RPCoreBTab).setStepSound(Block.soundTypeGrass).setBlockName("Polymer").setBlockTextureName(modid + ":" + "polymer").setHardness(0.5F).setResistance(1F);
polymerWoven = new blockRPBlock(Material.glass).setCreativeTab(RPCoreBTab).setStepSound(Block.soundTypeGrass).setBlockName("Woven Polyester").setBlockTextureName(modid + ":" + "woven_polyester").setHardness(0.5F).setResistance(0.5F);
//WIP //blueStabilizer =new Plants(Material.plants).setBlockName("Blue Stabilizer").setHardness(0.0F).setCreativeTab(RPCoreBTab).setBlockTextureName(modid + ":" + "flowerBlue").setBlockTextureName("flowerB");
//Blocks End----------
//Caustic Items
causticMeal = new itemmealCaustic().setUnlocalizedName("Caustic Mix").setTextureName(modid + ":" + "mealCaustic").setCreativeTab(RPCoreITab);
causticCorpuscles = new itemcorpCaustic().setUnlocalizedName("Caustic Corpuscles").setTextureName(modid + ":" + "corpusclesCaustic").setCreativeTab(RPCoreITab);
bloodFirey = new itembloodFirey().setUnlocalizedName("Firey Blood").setTextureName(modid + ":" + "bloodFirey").setCreativeTab(RPCoreITab);
acidSulfuric = new itemacidS().setUnlocalizedName("Sulfuric Acid").setTextureName(modid + ":" + "SulfuricAcid").setCreativeTab(RPCoreITab);
dustPN = new itemDustPN().setUnlocalizedName("Potassium Nitrate").setTextureName(modid + ":" + "PotassiumNitrate").setCreativeTab(RPCoreITab);
dustCharcoal = new itemdustCharcoal().setUnlocalizedName("Charcoal Dust").setTextureName(modid + ":" + "dustCharcoal").setCreativeTab(RPCoreITab);
toolSkinning = new itemSkinningtool().setUnlocalizedName("Skinning Tool").setTextureName(modid + ":" + "toolSkinning").setCreativeTab(RPCoreITab);
//
//Tools->Hammers
hammerDiamond = new hammerDiamond().setUnlocalizedName("Diamond Hammer").setTextureName(modid + ":" + "hammerDiamond").setCreativeTab(RPCoreITab);
hammerJade = new hammerJade().setUnlocalizedName("Jade Hammer Head").setTextureName(modid + ":" + "hammerJade").setCreativeTab(RPCoreITab);
hammerNetherstar = new hammerNetherstar().setUnlocalizedName("Netherstar Hammer").setTextureName(modid + ":" + "hammerNetherstar").setCreativeTab(RPCoreITab);
hammerSandstone = new hammerSandstone().setUnlocalizedName("Sandstone Hammer").setTextureName(modid + ":" + "hammerSandstone").setCreativeTab(RPCoreITab);
hammerWooden = new hammerWooden().setUnlocalizedName("Wooden Hammer").setTextureName(modid + ":" + "hammerWooden").setCreativeTab(RPCoreITab);
hammerCopper = new hammerCopper().setUnlocalizedName("Copper Hammer").setTextureName(modid + ":" + "hammerCopper").setCreativeTab(RPCoreITab);
hammerSilver = new hammerSilver().setUnlocalizedName("Silver Hammer").setTextureName(modid + ":" + "hammerSilver").setCreativeTab(RPCoreITab);
stoneHammer = new hammerStone().setUnlocalizedName("Stone Hammer").setTextureName(modid + ":" + "Stone_Hammer");
tungstenCarbideHammer = new ItemHeadBspace().setUnlocalizedName("TungstenCarbideHammer").setTextureName(modid + ":" + "TugstenCarbide_Hammer").setNoRepair();
//Tools->Mining
jadeSword = new ItemJadeSword(RPCore.jadeToolMaterial).setNoRepair().setCreativeTab(RPCoreITab).setUnlocalizedName("Jade Sword").setTextureName(modid + ":" + "jade_Sword");
jadeHoe = new ItemJadeHoe(RPCore.jadeToolMaterial).setNoRepair().setCreativeTab(RPCoreITab).setUnlocalizedName("Jade Hoe").setTextureName(modid + ":" + "jade_hoe");
jadeAxe = new ItemJadeAxe(RPCore.jadeToolMaterial).setNoRepair().setCreativeTab(RPCoreITab).setUnlocalizedName("Jade Axe").setTextureName(modid + ":" + "jade_axe");
jadePickaxe = new ItemJadePickaxe(RPCore.jadeToolMaterial).setNoRepair().setCreativeTab(RPCoreITab).setUnlocalizedName("Jade Pickaxe").setTextureName(modid + ":" + "jade_pickaxe");
jadeShovel = new ItemJadeSpade(RPCore.jadeToolMaterial).setNoRepair().setCreativeTab(RPCoreITab).setUnlocalizedName("Jade Shovel").setTextureName(modid + ":" + "jade_shovel");
//Tool Heads
headDiamond = new ItemHead().setUnlocalizedName("Diamond Hammer Head").setTextureName(modid + ":" + "headDiamond").setCreativeTab(RPCoreITab);
headJade = new ItemHead().setUnlocalizedName("Jade Hammer Head").setTextureName(modid + ":" + "headJade").setCreativeTab(RPCoreITab);
headNetherstar = new ItemHead().setUnlocalizedName("Netherstar Hammer Head").setTextureName(modid + ":" + "headNetherstar").setCreativeTab(RPCoreITab);
headSandstone = new ItemHead().setUnlocalizedName("Sandstone Hammer Head").setTextureName(modid + ":" + "headSandstone").setCreativeTab(RPCoreITab);
headWooden = new ItemHead().setUnlocalizedName("Wooden Hammer Head").setTextureName(modid + ":" + "headWooden").setCreativeTab(RPCoreITab);
headCopper = new ItemHead().setUnlocalizedName("Copper Hammer Head").setTextureName(modid + ":" + "headCopper").setCreativeTab(RPCoreITab);
headSilver = new ItemHead().setUnlocalizedName("Silver Hammer Head").setTextureName(modid + ":" + "headSilver").setCreativeTab(RPCoreITab);
tungstenCarbideHead = new ItemHead().setUnlocalizedName("TungstenCarbideHead").setTextureName(modid + ":" + "TugstenCarbide_Hammer_Head");
stoneHamHead = new ItemHead().setUnlocalizedName("Stone Hammer Head").setTextureName(modid + ":" + "HammerHead");
jadeHeadSw = new ItemHead().setUnlocalizedName("JadeSwordHead").setTextureName(modid + ":" + "JadeSwordHead");
jadeHeadSh = new ItemHead().setUnlocalizedName("JadeShovHead").setTextureName(modid + ":" + "JadeShovHead");
jadeHeadAx = new ItemHead().setUnlocalizedName("JadeAxeHead").setTextureName(modid + ":" + "JadeAxeHead");
jadeHeadHo = new ItemHead().setUnlocalizedName("JadeHoeHead").setTextureName(modid + ":" + "JadeHoeHead");
jadeHeadPi = new ItemHead().setUnlocalizedName("JadePickHead").setTextureName(modid + ":" + "JadePickHead");
//Tool Handle Modifiers
//Dusts
dustNetherstar = new ItemNetherstarDust().setCreativeTab(RPCoreITab).setUnlocalizedName("Netherstar Dust").setTextureName(modid + ":" + "Netherstar_Dust");
dustCopper = new ItemCopperDust().setCreativeTab(RPCoreITab).setUnlocalizedName("Copper Dust").setTextureName(modid + ":" + "Copper_Dust");
dustDiamond = new ItemDiamondDust().setCreativeTab(RPCoreITab).setUnlocalizedName("Diamond Dust").setTextureName(modid + ":" + "Diamond_Dust");
dustEmerald = new ItemEmeraldDust().setCreativeTab(RPCoreITab).setUnlocalizedName("Emerald Dust").setTextureName(modid + ":" + "Emerald_Dust");
dustFerrous = new ItemFerrousDust().setCreativeTab(RPCoreITab).setUnlocalizedName("Ferrous Dust").setTextureName(modid + ":" + "Ferrous_Dust");
dustGold = new ItemGoldDust().setCreativeTab(RPCoreITab).setUnlocalizedName("Gold Dust").setTextureName(modid + ":" + "Gold_Dust");
dustIron = new ItemIronDust().setCreativeTab(RPCoreITab).setUnlocalizedName("Iron Dust").setTextureName(modid + ":" + "Iron_Dust");
dustLead = new ItemLeadDust().setCreativeTab(RPCoreITab).setUnlocalizedName("Lead Dust").setTextureName(modid + ":" + "Lead_Dust");
dustSilver = new ItemSilverDust().setCreativeTab(RPCoreITab).setUnlocalizedName("Silver Dust").setTextureName(modid + ":" + "Silver_Dust");
dustTungsten = new ItemTugstenDust().setCreativeTab(RPCoreITab).setUnlocalizedName("Tungsten Dust").setTextureName(modid + ":" + "Tugsten_Dust");
dustTin = new ItemTinDust().setCreativeTab(RPCoreITab).setUnlocalizedName("Tin Dust").setTextureName(modid + ":" + "Tin_Dust");
dustBronze =new ItemBronzeDust().setCreativeTab(RPCoreITab).setUnlocalizedName("Bronze Dust").setTextureName(modid + ":" + "bronze_dust");
dustSteel = new ItemSteelDust().setCreativeTab(RPCoreITab).setUnlocalizedName("Steel Dust").setTextureName(modid + ":" + "steel_dust");
//Ingots
ingotCopper = new ItemCopperIngot().setCreativeTab(RPCoreITab).setUnlocalizedName("Copper Ingot").setTextureName(modid + ":" + "copper_ingot");
ingotFerrous = new ItemFerrousIngot().setCreativeTab(RPCoreITab).setUnlocalizedName("Ferrous Ingot").setTextureName(modid + ":" + "ferrous_ingot");
ingotLead = new ItemLeadIngot().setCreativeTab(RPCoreITab).setUnlocalizedName("Lead Ingot").setTextureName(modid + ":" + "lead_ingot");
ingotNetherstar = new ItemNetherstarIngot().setCreativeTab(RPCoreITab).setUnlocalizedName("Nether Star Ingot").setTextureName(modid + ":" + "netherstar_ingot");
ingotSilver = new ItemSilverIngot().setCreativeTab(RPCoreITab).setUnlocalizedName("Silver Ingot").setTextureName(modid + ":" + "silver_ingot");
ingotTin = new ItemTinIngot().setCreativeTab(RPCoreITab).setUnlocalizedName("Tin Ingot").setTextureName(modid + ":" + "tin_ingot");
ingotTungsten = new ItemTungstenIngot().setCreativeTab(RPCoreITab).setUnlocalizedName("Tungsten Ingot").setTextureName(modid + ":" + "tungsten_ingot");
ingotTungstencarbide = new ItemTungstencarbideIngot().setCreativeTab(RPCoreITab).setUnlocalizedName("Tungstencarbide Ingot").setTextureName(modid + ":" + "tungsten_carbide_ingot");
ingotSteel = new ItemingotSteel().setCreativeTab(RPCoreITab).setUnlocalizedName("Steel Ingot").setTextureName(modid + ":" + "steel_ingot");
ingotBronze = new ItemingotBronze().setCreativeTab(RPCoreITab).setUnlocalizedName("Bronze Ingot").setTextureName(modid + ":" + "bronze_ingot");
TCAI = new ItemTCAI().setCreativeTab(RPCoreITab).setUnlocalizedName("TCAI").setTextureName(modid + ":" + "TCAI");
//Gems
gemDiamond = new ItemDiamondIngot().setCreativeTab(RPCoreITab).setUnlocalizedName("Diamond Ingot").setTextureName(modid + ":" + "diamond_ingot");
gemEmerald = new ItemEmeraldIngot().setCreativeTab(RPCoreITab).setUnlocalizedName("Emerald Ingot").setTextureName(modid + ":" + "emerald_ingot");
gemJade = new ItemJade().setCreativeTab(RPCoreITab).setUnlocalizedName("Raw Jade").setTextureName(modid + ":" + "jade_refined");
gemJadepure = new ItemJade().setCreativeTab(RPCoreITab).setUnlocalizedName("Jade").setTextureName(modid + ":" + "Jade");
//Fuel
anthracite = new ItemAnthracite().setCreativeTab(RPCoreITab).setUnlocalizedName("Anthracite").setTextureName(modid + ":" + "Anthracite");
//Misc
sandPaper = new ItemsandPaper().setCreativeTab(RPCoreITab).setUnlocalizedName("Sand Paper").setTextureName(modid + ":" + "SandPaper");
mortar_and_pestle = new Itemmortar_and_pestle().setCreativeTab(RPCoreITab).setUnlocalizedName("Mortar and Pestle").setTextureName(modid + ":" + "mp");
quartzStick = new ItemquartcStick().setCreativeTab(RPCoreITab).setUnlocalizedName("Quartz Stick").setTextureName(modid + ":" + "quartzStick");
quartzBowl = new ItemquartcBowl().setCreativeTab(RPCoreITab).setUnlocalizedName("Quartz Bowl").setTextureName(modid + ":" + "quartzBowl");
dustFlour = new ItemdustFlour().setCreativeTab(RPCoreITab).setUnlocalizedName("Bag of Flour").setTextureName(modid + ":" + "Flour");
Pencil = new itemPencil().setCreativeTab(RPCoreITab).setUnlocalizedName("Pencil").setTextureName(modid + ":" + "Pencil");
blankScroll = new ItemblankScroll().setCreativeTab(RPCoreITab).setUnlocalizedName("Blank Scroll").setTextureName(modid + ":" + "scrollBlank");
scrollCircle = new ItemscrollCircle().setCreativeTab(RPCoreITab).setUnlocalizedName("Circle Scroll").setTextureName(modid + ":" + "scrollCircle");
oilTreatment = new ItemoilTreatment().setCreativeTab(RPCoreITab).setUnlocalizedName("Treatment Oil").setTextureName(modid + ":" + "oilTreatment");
mouldCog = new ItemmouldCog().setCreativeTab(RPCoreITab).setUnlocalizedName("Cog Mould").setTextureName(modid + ":" + "mouldCog");
//gears
cogUnfiredcopper = new ItemcogUnfiredcopper().setCreativeTab(RPCoreITab).setUnlocalizedName("UnfiredcopperCog").setTextureName(modid + ":" + "cogUnfiredcopper");
cogUnfireddiamond = new ItemcogUnfireddiamond().setCreativeTab(RPCoreITab).setUnlocalizedName("UnfireddiamondCog").setTextureName(modid + ":" + "cogUnfireddiamond");
cogUnfiredgold = new ItemcogUnfiredgold().setCreativeTab(RPCoreITab).setUnlocalizedName("UnfiredgoldCog").setTextureName(modid + ":" + "cogUnfiredgold");
cogUnfirediron = new ItemcogUnfirediron().setCreativeTab(RPCoreITab).setUnlocalizedName("UnfiredironCog").setTextureName(modid + ":" + "cogUnfirediron");
cogUnfiredtungstencarbide = new ItemcogUnfiredtungstencarbide().setCreativeTab(RPCoreITab).setUnlocalizedName("UnfiredtungstencarbideCog").setTextureName(modid + ":" + "cogUnfiredtungstencarbide");
//fiered
cogCopper = new ItemcogCopper().setCreativeTab(RPCoreITab).setUnlocalizedName("CopperCog").setTextureName(modid + ":" + "cogCopper");
cogDiamond = new ItemcogDiamond().setCreativeTab(RPCoreITab).setUnlocalizedName("DiamondCog").setTextureName(modid + ":" + "cogDiamond");
cogGold = new ItemcogGold().setCreativeTab(RPCoreITab).setUnlocalizedName("GoldCog").setTextureName(modid + ":" + "cogGold");
cogIron = new ItemcogIron().setCreativeTab(RPCoreITab).setUnlocalizedName("IronCog").setTextureName(modid + ":" + "cogIron");
cogTungstencarbide = new ItemcogTungstencarbide().setCreativeTab(RPCoreITab).setUnlocalizedName("TungstencarbideCog").setTextureName(modid + ":" + "cogTungstencarbide");
//public static Item ingotSteel;
//public static Item ingotBronze;
//^^ Priority
//public static Item ingotBrass;
//public static Item ingotZink;; <----OreGen REMEMBER
//^^meh
//Chunks
chunkCopper = new chunkCopper().setCreativeTab(RPCoreITab).setUnlocalizedName("Copper Chunk").setTextureName(modid + ":" + "Copper_Chunk");
chunkTungsten = new chunkCopper().setCreativeTab(RPCoreITab).setUnlocalizedName("Tungsten Chunk").setTextureName(modid + ":" + "Tungsten_Chunk");
chunkSilver = new chunkCopper().setCreativeTab(RPCoreITab).setUnlocalizedName("Silver Chunk").setTextureName(modid + ":" + "Silver_Chunk");
chunkLead = new chunkCopper().setCreativeTab(RPCoreITab).setUnlocalizedName("Lead Chunk").setTextureName(modid + ":" + "Lead_Chunk");
chunkTin = new chunkCopper().setCreativeTab(RPCoreITab).setUnlocalizedName("Tin Chunk").setTextureName(modid + ":" + "Tin_Chunk");
chunkFerrous = new chunkCopper().setCreativeTab(RPCoreITab).setUnlocalizedName("Ferrous Chunk").setTextureName(modid + ":" + "Ferrous_Chunk");
//Magic
dustMagick = new dustMagick().setCreativeTab(RPCoreITab).setUnlocalizedName("Magick Dust").setTextureName(modid + ":" + "magick_dust");
dustMagickcompound = new dustMagickcompound().setCreativeTab(RPCoreITab).setUnlocalizedName("Magick Compound").setTextureName(modid + ":" + "magick_compound");
dropBig = new dropBig().setCreativeTab(RPCoreITab).setUnlocalizedName("Big Drop").setTextureName(modid + ":" + "big_drop");
dropBounce = new dropBounce().setCreativeTab(RPCoreITab).setUnlocalizedName("Bounce Drop").setTextureName(modid + ":" + "bounce_drop");
dropDeath = new dropDeath().setCreativeTab(RPCoreITab).setUnlocalizedName("Death Drop").setTextureName(modid + ":" + "death_drop");
dropFly = new dropFly().setCreativeTab(RPCoreITab).setUnlocalizedName("Fly Drop").setTextureName(modid + ":" + "fly_drop");
dropLife = new dropLife().setCreativeTab(RPCoreITab).setUnlocalizedName("Life Drop").setTextureName(modid + ":" + "life_drop");
dropMagick = new dropMagick().setCreativeTab(RPCoreITab).setUnlocalizedName("Magick Drop").setTextureName(modid + ":" + "magick_drop");
dropPoison = new dropPoisen().setCreativeTab(RPCoreITab).setUnlocalizedName("Poison Drop").setTextureName(modid + ":" + "poison_drop");
dropRock = new dropRock().setCreativeTab(RPCoreITab).setUnlocalizedName("Rock Drop").setTextureName(modid + ":" + "rock_drop");
dropSmall = new dropSmall().setCreativeTab(RPCoreITab).setUnlocalizedName("Small Drop").setTextureName(modid + ":" + "small_drop");
dropSuper = new dropSuper().setCreativeTab(RPCoreITab).setUnlocalizedName("Super Drop").setTextureName(modid + ":" + "super_drop");
//Runes
runeFire= new runeFire().setCreativeTab(RPCoreITab).setUnlocalizedName("Fire Rune").setTextureName(modid + ":" + "Fire Rune");
runeEarth= new runeEarth().setCreativeTab(RPCoreITab).setUnlocalizedName("Earth Rune").setTextureName(modid + ":" + "Earth Rune");
runeAir= new runeAir().setCreativeTab(RPCoreITab).setUnlocalizedName("Air Rune").setTextureName(modid + ":" + "Air Rune");
runePlate= new runePlate().setCreativeTab(RPCoreITab).setUnlocalizedName("Runeic Plate").setTextureName(modid + ":" + "runicPlate");
runeSpirit= new runeSpirit().setCreativeTab(RPCoreITab).setUnlocalizedName("Spirit Rune").setTextureName(modid + ":" + "Spirit Rune");
runeWater= new runeWater().setCreativeTab(RPCoreITab).setUnlocalizedName("Water Rune").setTextureName(modid + ":" + "Water Rune");
//Food
megaCookie = new ItemFoodmegaCookie(16, 1, true).setCreativeTab(RPCoreITab).setUnlocalizedName("Mega Cookie").setTextureName(modid + ":" + "Megacookie");
ghostCookie = new ItemFoodghostCookie(8, 1, true).setCreativeTab(RPCoreITab).setUnlocalizedName("Ghost Cookie").setTextureName(modid + ":" + "Ghostcookie");
poisonCookie = new ItemFoodpoisonCookie(-10, 1, true).setCreativeTab(RPCoreITab).setUnlocalizedName("Poison Cookie").setTextureName(modid + ":" + "Poisoncookie");
miniCookie = new ItemFoodminiCookie(8, 1, true).setCreativeTab(RPCoreITab).setUnlocalizedName("Mini Cookie").setTextureName(modid + ":" + "minicookie");
oneupCookie = new ItemFoodoneupCookie(20, 1, true).setCreativeTab(RPCoreITab).setUnlocalizedName("1Up Cookie").setTextureName(modid + ":" + "1Upcookie");
springCookie = new ItemFoodspringCookie(8, 1, true).setCreativeTab(RPCoreITab).setUnlocalizedName("Spring Cookie").setTextureName(modid + ":" + "Springcookie");
propellerCookie = new ItemFoodpropellerCookie(8, 1, true).setCreativeTab(RPCoreITab).setUnlocalizedName("Propeller Cookie[WIP]").setTextureName(modid + ":" + "Propellercookie");
rockCookie =new ItemFoodrockCookie(8, 1, true).setCreativeTab(RPCoreITab).setUnlocalizedName("Rock Cookie").setTextureName(modid + ":" + "Rockcookie");
superCookie =new ItemFoodsuperCookie(8, 1, true).setCreativeTab(RPCoreITab).setUnlocalizedName("Super Cookie").setTextureName(modid + ":" + "Supercookie");
cookieSugar = new ItemFoodcookieSugar(8, 1, true).setCreativeTab(RPCoreITab).setUnlocalizedName("Sugar Cookie").setTextureName(modid + ":" + "cookieSugar");
baconRaw = new ItemFoodbaconRaw(1, 1, true).setCreativeTab(RPCoreITab).setUnlocalizedName("Raw Bacon").setTextureName(modid + ":" + "Bacon_Raw");
baconCooked = new ItemFoodbaconCooked(3, 1, true).setCreativeTab(RPCoreITab).setUnlocalizedName("Cooked Bacon").setTextureName(modid + ":" + "Bacon_Cooked");
knife = new Itemknife().setCreativeTab(RPCoreITab).setUnlocalizedName("Knife").setTextureName(modid + ":" + "Knife");
dustSugar = new ItemdustSugar().setCreativeTab(RPCoreITab).setUnlocalizedName("Pouch Of Sugar").setTextureName(modid + ":" + "Bag_Of_Sugar");
magnusCookie = new ItemFoodcreativeCookie(1, 1, true).setCreativeTab(RPCoreITab).setUnlocalizedName("Magnus Cookie").setTextureName("cookie");
//test
testCookie = new ItemFoodtestCookie(-10, 1, false).setCreativeTab(RPCoreITab).setUnlocalizedName("Item Of Testing").setTextureName(modid + ":" + "ItemOfTesting");
//Plants
yellowLeaf = new ItemyellowLeaf().setCreativeTab(RPCoreITab).setUnlocalizedName("Yellow Leaf").setTextureName(modid + ":" + "MagickYellowLeaf");
//OreDictionary
OreDictionary.registerOre("ingotBronze",new ItemStack(ingotBronze));
OreDictionary.registerOre("ingotSteel",new ItemStack(ingotSteel));
OreDictionary.registerOre("dustBronze", new ItemStack(dustBronze));
OreDictionary.registerOre("dustSteel",new ItemStack(dustSteel));
OreDictionary.registerOre("dustSugar", Items.sugar);
OreDictionary.registerOre("dustSugar", dustSugar);
OreDictionary.registerOre("ingotCopper", ingotCopper);
OreDictionary.registerOre("ingotFerrous", new ItemStack(ingotFerrous));
OreDictionary.registerOre("ingotLead", new ItemStack(ingotLead));
OreDictionary.registerOre("ingotSilver", new ItemStack(ingotSilver));
OreDictionary.registerOre("ingotTin", new ItemStack(ingotTin));
OreDictionary.registerOre("gemDiamond", new ItemStack(gemDiamond));
OreDictionary.registerOre("gemEmerald", new ItemStack(gemEmerald));
OreDictionary.registerOre("ingotTungsten", new ItemStack(ingotTungsten));
OreDictionary.registerOre("ingotNetherstar", new ItemStack(ingotNetherstar));
OreDictionary.registerOre("ingotTugstencarbide", new ItemStack(ingotTungstencarbide));
OreDictionary.registerOre("dustCopper", new ItemStack (dustCopper));
OreDictionary.registerOre("dustFerrous", new ItemStack(dustFerrous));
OreDictionary.registerOre("dustLead", new ItemStack(dustLead));
OreDictionary.registerOre("dustSilver", new ItemStack(dustSilver));
OreDictionary.registerOre("dustTin", new ItemStack(dustTin));
OreDictionary.registerOre("dustDiamond", new ItemStack(dustDiamond));
OreDictionary.registerOre("dustEmerald", new ItemStack(dustEmerald));
OreDictionary.registerOre("dustTungsten", new ItemStack(dustTungsten));
OreDictionary.registerOre("dustNetherstar", new ItemStack(dustNetherstar));
OreDictionary.registerOre("dustGold", new ItemStack(dustGold));
OreDictionary.registerOre("oreCopper", new ItemStack(chunkCopper));
OreDictionary.registerOre("oreTin", new ItemStack(chunkTin));
OreDictionary.registerOre("oreFerrous", new ItemStack(chunkFerrous));
OreDictionary.registerOre("oreLead", new ItemStack(chunkLead));
OreDictionary.registerOre("oreSilver", new ItemStack(chunkSilver));
OreDictionary.registerOre("oreTungsten", new ItemStack(chunkTungsten));
}
@EventHandler
public void init(FMLInitializationEvent e){
ItemStack slabM0 = new ItemStack (Blocks.stone_slab);
slabM0.setItemDamage(5);
GameRegistry.registerTileEntity(TileEntityalloySmelter.class, "alloySmelter");
//machines
GameRegistry.registerBlock(alloySmelterIdle, "AlloySmelterIdle");
GameRegistry.registerBlock(alloySmelterActive, "AlloySmelterActive");
//Blocks
Recipies.registerItem(magnusCookie, "Magnus Cookie");
Recipies.registerBlock(obsidianWhite,"White Obsidian");
Recipies.registerBlock(oreCrusher, "Ore Crusher");
Recipies.registerBlock(sandTreated, "Treated Sand");
//Recipies.registerBlock(blueStabilizer, "Blue Stabilizer");
Recipies.registerBlock(polymer, "Polymer");
Recipies.registerBlock(polymerWoven, "Polyester");
Recipies.registerBlock(oreExp, "Exp Ore");
Recipies.registerBlock(oreTin, "Tin Ore");
Recipies.registerBlock(oreSilver,"Silver Ore");
Recipies.registerBlock(oreLead, "Lead Ore");
Recipies.registerBlock(oreFerrous, "Ferrous Ore");
Recipies.registerBlock(oreCopper, "Copper Ore");
Recipies.registerBlock(oreJade, "Jade Ore");
Recipies.registerBlock(jadeBlock, "Jade Block");
Recipies.registerBlock(oreTungsten, "Tungsten Ore");
Recipies.registerBlock(TCAM, "TCAM");
Recipies.registerBlock(oreAnthtracite, "Anthracite Ore");
Recipies.registerBlock(copperBlock, "Copper Block");
Recipies.registerBlock(ferrousBlock, "Ferrous Block");
Recipies.registerBlock(leadBlock, "Lead Block");
Recipies.registerBlock(netherstarBlock, "Netherstar Block");
Recipies.registerBlock(organizeddiamondBlock, "Organizeddiamond Block");
Recipies.registerBlock(organizedemeraldBlock, "Organizedemerald Block");
Recipies.registerBlock(silverBlock, "Silver Block");
Recipies.registerBlock(tinBlock, "Tin Block");
Recipies.registerBlock(tungstenBlock, "Tungsten Block");
Recipies.registerBlock(tungstencarbideBlock, "Tungstencarbide Block");
//Trees
Recipies.registerBlock(elderLog, "Red Elderberry Log");
Recipies.registerBlock(elderLeaf, "Red Elderberry Leaf");
Recipies.registerBlock(elderSap, "Red Elderberry Sapling");
Recipies.registerBlock(elderPlanks, "Red Elderberry Planks");
//items
//Ingots
Recipies.registerItem(ingotSteel,"Steel Ingot");
Recipies.registerItem(ingotBronze,"Bronze Ingot");
Recipies.registerItem(ingotTin,"Tin Ingot");
Recipies.registerItem(ingotSilver, "Silver Ingot");
Recipies.registerItem(ingotLead, "Lead Ingot");
Recipies.registerItem(ingotFerrous, "Ferrous Ingot");
Recipies.registerItem(ingotCopper, "Copper Ingot");
Recipies.registerItem(ingotNetherstar, "Nether Star Ingot");
Recipies.registerItem(ingotTungsten, "Tungsten Ingot");
Recipies.registerItem(TCAI, "TCAI");
//Gems
Recipies.registerItem(gemDiamond, "Diamond Ingot");
Recipies.registerItem(gemEmerald, "Emerald Ingot");
Recipies.registerItem(gemJade, "Raw Jade");
Recipies.registerItem(gemJadepure, "Jade");
//Dusts
Recipies.registerItem(dustNetherstar, "Netherstar Dust");
Recipies.registerItem(dustCopper, "Copper Dust");
Recipies.registerItem(dustDiamond, "Diamond Dust");
Recipies.registerItem(dustEmerald, "Emerald Dust");
Recipies.registerItem(dustFerrous, "Ferrous Dust");
Recipies.registerItem(dustGold, "Gold Dust");
Recipies.registerItem(dustIron, "Iron Dust");
Recipies.registerItem(dustLead, "Lead Dust");
Recipies.registerItem(dustSilver, "Silver Dust");
Recipies.registerItem(dustTin, "Tin Dust");
Recipies.registerItem(dustTungsten, "Tungsten Dust");
Recipies.registerItem(dustBronze,"Bronze Dust");
Recipies.registerItem(dustSteel,"Steel Dust");
//Magick
Recipies.registerItem(dropBig, "Big Drop");
Recipies.registerItem(dropBounce,"Bounce Drop");
Recipies.registerItem(dropDeath, "Death Drop");
Recipies.registerItem(dropFly,"Fly Drop");
Recipies.registerItem(dropLife,"Life Drop");
Recipies.registerItem(dropMagick,"Magick Drop");
Recipies.registerItem(dropPoison,"Poisen Drop");
Recipies.registerItem(dropRock,"Rock Drop");
Recipies.registerItem(dropSmall,"Small Drop");
Recipies.registerItem(dropSuper, "Super Drop");
Recipies.registerItem(dustMagick, "Magick Dust");
Recipies.registerItem(dustMagickcompound, "Magick Compound");
Recipies.registerItem(runeFire, "Fire Rune");
Recipies.registerItem(runeWater, "Water Rune");
Recipies.registerItem(runeAir, "Air Rune");
Recipies.registerItem(runeSpirit, "Spirit Rune");
Recipies.registerItem(runeEarth, "Earth Rune");
Recipies.registerItem(runePlate, "Runic Plate");
//Misc
Recipies.registerItem(sandPaper,"Sand Paper");
Recipies.registerItem(anthracite, "Anthracite");
Recipies.registerItem(quartzStick, "Quartc Stick");
Recipies.registerItem(quartzBowl, "Quartc Bowl");
Recipies.registerItem(mortar_and_pestle, "Mortar and Pestle");
Recipies.registerItem(Pencil, "Pencil");
Recipies.registerItem(blankScroll, "Blank Scroll");
Recipies.registerItem(scrollCircle, "Circle Scroll");
Recipies.registerItem(oilTreatment, "Treatment Oil");
Recipies.registerItem(mouldCog, "Cog Mould");
//gears
Recipies.registerItem(cogUnfiredcopper, "UnfiredcopperCog");
Recipies.registerItem(cogUnfireddiamond, "UnfireddiamondCog");
Recipies.registerItem(cogUnfiredgold, "CogUnfiredgold");
Recipies.registerItem(cogUnfirediron, "CogUnfirediron");
Recipies.registerItem(cogUnfiredtungstencarbide, "CogUnfiredtungstencarbide");
//fiered
Recipies.registerItem(cogCopper, "CogCopper");
Recipies.registerItem(cogDiamond, "CogDiamond");
Recipies.registerItem(cogGold, "CogGold");
Recipies.registerItem(cogIron, "CogIron");
Recipies.registerItem(cogTungstencarbide, "CogTungstencarbide");
//Chunks
Recipies.registerItem(chunkCopper, "Copper Chunk");
Recipies.registerItem(chunkTin, "Tin Chunk");
Recipies.registerItem(chunkFerrous, "Ferrous Chunk");
Recipies.registerItem(chunkSilver, "Silver Chunk");
Recipies.registerItem(chunkTungsten, "Tungsten Chunk");
Recipies.registerItem(chunkLead, "Lead Chunk");
//Tools
Recipies.registerItem(hammerDiamond,"Diamond Hammer");
Recipies.registerItem(hammerJade,"Jade Hammer");
Recipies.registerItem(hammerNetherstar,"Netherstar Hammer");
Recipies.registerItem(hammerSandstone,"Sandstone Hammer");
Recipies.registerItem(hammerWooden ,"Wooden Hammer");
Recipies.registerItem(hammerCopper,"Copper Hammer");
Recipies.registerItem(hammerSilver,"Silver Hammer");
Recipies.registerItem(tungstenCarbideHammer, "Tungsten Carbide Hammer");
Recipies.registerItem(stoneHammer, "Stone Hammer");
//Tools->Mining
Recipies.registerItem(jadeSword, "Jade Sword");
Recipies.registerItem(jadePickaxe, "Jade Pickaxe");
Recipies.registerItem(jadeAxe, "Jade Axe");
Recipies.registerItem(jadeHoe, "Jade Hoe");
Recipies.registerItem(jadeShovel, "Jade Shovel");
//Tool Heads
Recipies.registerItem(headDiamond,"Diamond Hammer Head");
Recipies.registerItem(headJade,"Jade Hammer Head");
Recipies.registerItem(headNetherstar,"Netherstar Hammer Head");
Recipies.registerItem(headSandstone,"Sandstone Hammer Head");
Recipies.registerItem(headWooden ,"Wooden Hammer Head");
Recipies.registerItem(headCopper,"Copper Hammer Head");
Recipies.registerItem(headSilver,"Silver Hammer Head");
Recipies.registerItem(tungstenCarbideHead, "Tungsten Carbide Hammer Head");
Recipies.registerItem(stoneHamHead, "Stone Hammer Head");
//Tools->Mining
Recipies.registerItem(jadeHeadAx, "JadeAxeHead");
Recipies.registerItem(jadeHeadSw, "JadeSwordHead");
Recipies.registerItem(jadeHeadSh, "JadeShovHead");
Recipies.registerItem(jadeHeadHo, "JadeHoeHead");
Recipies.registerItem(jadeHeadPi, "JadePickHead");
//Handle Modifiers
//Caustic Items
Recipies.registerItem(causticMeal, "Caustic Mix");
Recipies.registerItem(causticCorpuscles, "Caustic Corpuscles ");
Recipies.registerItem(bloodFirey, "Firey Blood");
Recipies.registerItem(acidSulfuric, "Sulferic Acid");
Recipies.registerItem(dustPN,"Potassium Nitrate");
Recipies.registerItem(dustCharcoal, "Charcoal Dust");
Recipies.registerItem(toolSkinning, "Skinning Tool");
//Food
Recipies.registerItem(megaCookie, "Mega Cookie");
Recipies.registerItem(ghostCookie, "Ghost Cookie");
Recipies.registerItem(poisonCookie, "Poison Cookie");
Recipies.registerItem(miniCookie, "Mini Cookie");
Recipies.registerItem(oneupCookie, "1Up Cookie");
Recipies.registerItem(springCookie, "Spring Cookie");
Recipies.registerItem(propellerCookie, "Propeller Cookie[WIP]");
Recipies.registerItem(rockCookie, "Rock Cookie");
Recipies.registerItem(superCookie, "Super Cookie");
Recipies.registerItem(cookieSugar, "Sugar Cookie");
Recipies.registerItem(baconRaw, "Raw Bacon");
Recipies.registerItem(baconCooked,"Cooked Bacon");
Recipies.registerItem(knife,"Knife");
Recipies.registerItem(dustSugar,"Pouch Of Sugar");
Recipies.registerItem(dustFlour, "Bag Of Flour");
//Plants
Recipies.registerItem(yellowLeaf, "Yellow Leaf");
//test
Recipies.registerItem(testCookie, "Item Of Testing");
//Smelting
Recipies.registerSmeltingItemWUM(chunkCopper, ingotCopper,5F);
Recipies.registerSmeltingItemWUM(chunkTin, ingotTin,5F);
Recipies.registerSmeltingItemWUM(chunkFerrous, ingotFerrous,5F);
Recipies.registerSmeltingItemWUM(chunkSilver, ingotSilver,5F);
Recipies.registerSmeltingItemWUM(chunkTungsten, ingotTungsten,5F);
Recipies.registerSmeltingItemWUM(chunkLead, ingotLead,5F);
//gears
Recipies.registerSmeltingItemWUM(cogUnfiredcopper, cogCopper,5F);
Recipies.registerSmeltingItemWUM(cogUnfireddiamond, cogDiamond,5F);
Recipies.registerSmeltingItemWUM(cogUnfiredgold, cogGold,5F);
Recipies.registerSmeltingItemWUM(cogUnfirediron, cogIron,5F);
Recipies.registerSmeltingItemWUM(cogUnfiredtungstencarbide, cogTungstencarbide,5F);
//other
Recipies.registerSmeltingItemWUM(dustFlour,Items.bread,5F);
Recipies.registerSmeltingItemWUM(dustMagick,runePlate,5F);
Recipies.registerSmeltingItemWUM(gemJade, gemJadepure, 5F);
Recipies.registerSmeltingItemWUM(Items.nether_star,ingotNetherstar, 5F);
Recipies.registerSmeltingItemWUM(Items.diamond,gemDiamond, 5F);
Recipies.registerSmeltingItemWUM(Items.emerald,gemEmerald, 5F);
Recipies.registerSmeltingItemWUM(Items.diamond_horse_armor,gemDiamond, 5F);
Recipies.registerSmeltingItemWUM(Items.iron_horse_armor,Items.iron_ingot, 5F);
Recipies.registerSmeltingItemWUM(Items.golden_horse_armor,Items.gold_ingot, 5F);
Recipies.registerSmeltingItemWUM(Items.rotten_flesh,Items.leather, 5F);
Recipies.registerSmeltingItemWUM(Items.poisonous_potato,Items.poisonous_potato, 5F);
//Smelting Ores
Recipies.registerSmeltingBlockToItemWUM(oreTungsten, ingotTungsten, 5F);
Recipies.registerSmeltingBlockToItemWUM(oreCopper,ingotCopper,5f);
Recipies.registerSmeltingBlockToItemWUM(oreFerrous,ingotFerrous,5f);
Recipies.registerSmeltingBlockWUM(obsidianWhite,Blocks.obsidian,5f);
Recipies.registerSmeltingBlockToItemWUM(oreLead,ingotLead,5f);
Recipies.registerSmeltingBlockToItemWUM(oreSilver,ingotSilver,5f);
Recipies.registerSmeltingBlockToItemWUM(oreTin,ingotTin,5f);
//Smelting Dusts
Recipies.registerSmeltingItemWUM(dustTin,ingotTin,5f);
Recipies.registerSmeltingItemWUM(dustTungsten, ingotTungsten, 5F);
Recipies.registerSmeltingItemWUM(dustCopper,ingotCopper,5f);
Recipies.registerSmeltingItemWUM(dustFerrous,ingotFerrous,5f);
Recipies.registerSmeltingItemWUM(dustLead,ingotLead,5f);
Recipies.registerSmeltingItemWUM(dustSilver,ingotSilver,5f);
Recipies.registerSmeltingItemWUM(dustTin,ingotTin,5f);
Recipies.registerSmeltingItemWUM(dustDiamond,gemDiamond,5f);
Recipies.registerSmeltingItemWUM(dustEmerald,gemEmerald,5f);
Recipies.registerSmeltingItemWUM(dustIron,Items.iron_ingot,5f);
Recipies.registerSmeltingItemWUM(dustGold,Items.gold_ingot,5f);
Recipies.registerSmeltingItemWUM(dustNetherstar,ingotNetherstar,5f);
Recipies.registerSmeltingItemWUM(baconRaw,baconCooked,5f);
//Smelting Alloys # Will need to be changed when we get the alloy smelter going
Recipies.registerSmeltingBlockToItemWUM(TCAM, TCAI, 5F);
//Crafting
// #
// #
// 0
GameRegistry.addShapedRecipe(new ItemStack (knife), " ", " x ", " 0 ", 'x',new ItemStack(Items.iron_ingot), '0',new ItemStack(Items.stick));
GameRegistry.addShapedRecipe(new ItemStack (Blocks.stonebrick), "x", "x", 'x', slabM0);
GameRegistry.addShapedRecipe(new ItemStack (dustSteel,4),"###","#0#","###", '#', new ItemStack (RPCore.dustCharcoal),'0',new ItemStack(Items.iron_ingot));
GameRegistry.addShapedRecipe(new ItemStack (tungstenCarbideHead), "###", "# #", '#', new ItemStack (TCAI));
GameRegistry.addShapedRecipe(new ItemStack (tungstenCarbideHammer), "#", "x", '#', new ItemStack (tungstenCarbideHead), 'x', new ItemStack(Items.stick));
GameRegistry.addShapedRecipe(new ItemStack (jadeSword), "x", "z", 'x', new ItemStack (jadeHeadSw), 'z', new ItemStack (Items.stick));
GameRegistry.addShapedRecipe(new ItemStack (jadeShovel), "x", "z", 'x', new ItemStack (jadeHeadSh), 'z', new ItemStack (Items.stick));
GameRegistry.addShapedRecipe(new ItemStack (jadePickaxe), "x", "z", 'x', new ItemStack (jadeHeadPi), 'z', new ItemStack (Items.stick));
GameRegistry.addShapedRecipe(new ItemStack (jadeAxe), "x", "z", 'x', new ItemStack (jadeHeadAx), 'z', new ItemStack (Items.stick));
GameRegistry.addShapedRecipe(new ItemStack (jadeHoe), "x", "z", 'x', new ItemStack (jadeHeadHo), 'z', new ItemStack (Items.stick));
GameRegistry.addShapedRecipe(new ItemStack (copperBlock), "xxx", "xxx", "xxx", 'x', new ItemStack (ingotCopper));
GameRegistry.addShapedRecipe(new ItemStack (leadBlock), "xxx", "xxx", "xxx", 'x', new ItemStack (ingotLead));
GameRegistry.addShapedRecipe(new ItemStack (ferrousBlock), "xxx", "xxx", "xxx", 'x', new ItemStack (ingotFerrous));
GameRegistry.addShapedRecipe(new ItemStack (netherstarBlock), "xxx", "xxx", "xxx", 'x', new ItemStack (ingotNetherstar));
GameRegistry.addShapedRecipe(new ItemStack (organizeddiamondBlock), "xxx", "xxx", "xxx", 'x', new ItemStack (gemDiamond));
GameRegistry.addShapedRecipe(new ItemStack (organizedemeraldBlock), "xxx", "xxx", "xxx", 'x', new ItemStack (gemEmerald));
GameRegistry.addShapedRecipe(new ItemStack (silverBlock), "xxx", "xxx", "xxx", 'x', new ItemStack (ingotSilver));
GameRegistry.addShapedRecipe(new ItemStack (tinBlock), "xxx", "xxx", "xxx", 'x', new ItemStack (ingotTin));
GameRegistry.addShapedRecipe(new ItemStack (tungstenBlock), "xxx", "xxx", "xxx", 'x', new ItemStack (ingotTungsten));
GameRegistry.addShapedRecipe(new ItemStack (tungstencarbideBlock), "xxx", "xxx", "xxx", 'x', new ItemStack (TCAI));
GameRegistry.addShapedRecipe(new ItemStack (jadeBlock), "xx", "xx", 'x', new ItemStack (gemJadepure));
GameRegistry.addShapedRecipe(new ItemStack (yellowLeaf), "xxx", "xxx", "xxx", 'x', new ItemStack (elderLeaf));
GameRegistry.addShapedRecipe(new ItemStack (quartzStick, 4), " x", " x ", "xx ", 'x', new ItemStack (Items.quartz));
GameRegistry.addShapedRecipe(new ItemStack (quartzBowl, 4), "x x", " x ", 'x', new ItemStack (Items.quartz));
GameRegistry.addShapedRecipe(new ItemStack (mortar_and_pestle), "x", "#", 'x', new ItemStack (quartzStick), '#', new ItemStack(quartzBowl));
GameRegistry.addShapedRecipe(new ItemStack (dustMagick, 8), "xxx", "x#x", "xxx", 'x', new ItemStack(yellowLeaf), '#', new ItemStack (mortar_and_pestle));
GameRegistry.addShapedRecipe(new ItemStack (dustSugar, 1), "xxx", "xxx", "xxx", 'x', new ItemStack(Items.sugar));
GameRegistry.addShapelessRecipe(new ItemStack (TCAM), new ItemStack (Blocks.coal_block), new ItemStack (ingotTungsten));
GameRegistry.addShapelessRecipe(new ItemStack (dustBronze,2), new ItemStack (dustCopper,3), new ItemStack (dustTin,1));
GameRegistry.addShapedRecipe(new ItemStack (Blocks.torch, 16), "x", "z", 'x', new ItemStack (anthracite), 'z', new ItemStack (Items.stick));
GameRegistry.addShapedRecipe(new ItemStack (Pencil, 32), "xzx", "xzx", "xsx", 'x', new ItemStack(Blocks.planks), 'z', new ItemStack(Items.coal), 's', new ItemStack(ingotLead));
GameRegistry.addShapelessRecipe(new ItemStack (blankScroll), new ItemStack(Items.paper), new ItemStack(oilTreatment));
GameRegistry.addShapedRecipe(new ItemStack(scrollCircle), "xxx","xzx","xxx", 'x', new ItemStack(Pencil), 'z', new ItemStack(blankScroll));
GameRegistry.addShapedRecipe(new ItemStack (sandTreated, 4), " z ", "zxz", " z ", 'z', new ItemStack(oilTreatment), 'x', new ItemStack(Blocks.sand));
GameRegistry.addShapedRecipe(new ItemStack(mouldCog), " x ", "xzx", " x ", 'x', new ItemStack(sandTreated), 'z', new ItemStack(scrollCircle));
//gears
GameRegistry.addShapedRecipe(new ItemStack(cogUnfiredcopper), " x ", "xzx", " x ", 'x', new ItemStack(dustCopper), 'z', new ItemStack(mouldCog, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapedRecipe(new ItemStack(cogUnfireddiamond), " x ", "xzx", " x ", 'x', new ItemStack(dustDiamond), 'z', new ItemStack(mouldCog, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapedRecipe(new ItemStack(cogUnfiredgold), " x ", "xzx", " x ", 'x', new ItemStack(dustGold), 'z', new ItemStack(mouldCog, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapedRecipe(new ItemStack(cogUnfirediron), " x ", "xzx", " x ", 'x', new ItemStack(dustIron), 'z', new ItemStack(mouldCog, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapedRecipe(new ItemStack(cogUnfiredtungstencarbide), " x ", "xzx", " x ", 'x', new ItemStack(ingotCopper), 'z', new ItemStack(mouldCog, 1, OreDictionary.WILDCARD_VALUE));
//Plants
GameRegistry.addShapedRecipe(new ItemStack (polymer,1),"###","###","###", '#', new ItemStack (Blocks.leaves));
GameRegistry.addShapedRecipe(new ItemStack (polymerWoven,1),"###","###","###", '#', new ItemStack (polymer));
GameRegistry.addShapedRecipe(new ItemStack (Blocks.wool,16),"###","###","###", '#', new ItemStack (polymerWoven));
//Hammer Recipes
//Stone
GameRegistry.addShapedRecipe(new ItemStack (jadeHeadSw,1, OreDictionary.WILDCARD_VALUE), " x", " #", 'x', new ItemStack (jadeBlock), '#', new ItemStack (stoneHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapedRecipe(new ItemStack (jadeHeadSh,1, OreDictionary.WILDCARD_VALUE), "#x", 'x', new ItemStack (jadeBlock), '#', new ItemStack (stoneHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (jadeHeadHo,1, OreDictionary.WILDCARD_VALUE), new ItemStack (jadeBlock), new ItemStack (stoneHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapedRecipe(new ItemStack (jadeHeadAx,1, OreDictionary.WILDCARD_VALUE), " #", " x", 'x', new ItemStack (jadeBlock), '#', new ItemStack (stoneHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapedRecipe(new ItemStack (jadeHeadPi,1, OreDictionary.WILDCARD_VALUE), " x","# ", 'x', new ItemStack (jadeBlock), '#', new ItemStack (stoneHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustCopper,2), new ItemStack (oreCopper), new ItemStack (stoneHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustLead,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreLead), new ItemStack (stoneHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustFerrous,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreFerrous), new ItemStack (stoneHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustCopper,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkCopper), new ItemStack (stoneHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustSilver,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreSilver), new ItemStack (stoneHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustTin,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreTin), new ItemStack (stoneHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustTungsten,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreTungsten), new ItemStack (stoneHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustCopper,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreCopper), new ItemStack (stoneHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack(dustIron,2,OreDictionary.WILDCARD_VALUE), new ItemStack (Blocks.iron_ore), new ItemStack(stoneHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustFlour,4, OreDictionary.WILDCARD_VALUE),new ItemStack(stoneHammer, 1, OreDictionary.WILDCARD_VALUE),new ItemStack(Items.wheat));
GameRegistry.addShapelessRecipe(new ItemStack (dustCharcoal,4, OreDictionary.WILDCARD_VALUE),new ItemStack(stoneHammer, 1, OreDictionary.WILDCARD_VALUE),new ItemStack(Items.coal,1,1));
GameRegistry.addShapelessRecipe(new ItemStack (dustLead,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkLead), new ItemStack (stoneHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustFerrous,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkFerrous), new ItemStack (stoneHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustSilver,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkSilver), new ItemStack (stoneHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustTin,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkTin), new ItemStack (stoneHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustTungsten,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkTungsten), new ItemStack (stoneHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustCopper,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkCopper), new ItemStack (stoneHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (Blocks.sand,2, OreDictionary.WILDCARD_VALUE), new ItemStack (Blocks.cobblestone), new ItemStack (stoneHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustGold,2, OreDictionary.WILDCARD_VALUE), new ItemStack (Blocks.gold_ore), new ItemStack (stoneHammer, 1, OreDictionary.WILDCARD_VALUE));
//Tugsten Carbide
GameRegistry.addShapelessRecipe(new ItemStack (dustEmerald,2, OreDictionary.WILDCARD_VALUE), new ItemStack (Blocks.emerald_ore), new ItemStack (tungstenCarbideHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack(dustDiamond, 3, OreDictionary.WILDCARD_VALUE), new ItemStack (Blocks.diamond_ore), new ItemStack(tungstenCarbideHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapedRecipe(new ItemStack (jadeHeadSw,1, OreDictionary.WILDCARD_VALUE), " x", " #", 'x', new ItemStack (jadeBlock), '#', new ItemStack (tungstenCarbideHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapedRecipe(new ItemStack (jadeHeadSh,1, OreDictionary.WILDCARD_VALUE), "#x", 'x', new ItemStack (jadeBlock), '#', new ItemStack (tungstenCarbideHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (jadeHeadHo,1, OreDictionary.WILDCARD_VALUE), new ItemStack (jadeBlock), new ItemStack (tungstenCarbideHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapedRecipe(new ItemStack (jadeHeadAx,1, OreDictionary.WILDCARD_VALUE), " #", " x", 'x', new ItemStack (jadeBlock), '#', new ItemStack (tungstenCarbideHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapedRecipe(new ItemStack (jadeHeadPi,1, OreDictionary.WILDCARD_VALUE), " x","# ", 'x', new ItemStack (jadeBlock), '#', new ItemStack (tungstenCarbideHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustCopper,2), new ItemStack (oreCopper), new ItemStack (tungstenCarbideHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustLead,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreLead), new ItemStack (tungstenCarbideHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustFerrous,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreFerrous), new ItemStack (tungstenCarbideHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustCopper,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkCopper), new ItemStack (tungstenCarbideHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustSilver,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreSilver), new ItemStack (tungstenCarbideHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustTin,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreTin), new ItemStack (tungstenCarbideHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustTungsten,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreTungsten), new ItemStack (tungstenCarbideHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustCopper,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreCopper), new ItemStack (tungstenCarbideHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack(dustIron,2,OreDictionary.WILDCARD_VALUE), new ItemStack (Blocks.iron_ore), new ItemStack(tungstenCarbideHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustFlour,4, OreDictionary.WILDCARD_VALUE),new ItemStack(tungstenCarbideHammer, 1, OreDictionary.WILDCARD_VALUE),new ItemStack(Items.wheat));
GameRegistry.addShapelessRecipe(new ItemStack (dustCharcoal,4, OreDictionary.WILDCARD_VALUE),new ItemStack(tungstenCarbideHammer, 1, OreDictionary.WILDCARD_VALUE),new ItemStack(Items.coal,1,1));
GameRegistry.addShapelessRecipe(new ItemStack (dustLead,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkLead), new ItemStack (tungstenCarbideHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustFerrous,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkFerrous), new ItemStack (tungstenCarbideHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustSilver,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkSilver), new ItemStack (tungstenCarbideHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustTin,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkTin), new ItemStack (tungstenCarbideHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustTungsten,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkTungsten), new ItemStack (tungstenCarbideHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustCopper,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkCopper), new ItemStack (tungstenCarbideHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (Blocks.sand,2, OreDictionary.WILDCARD_VALUE), new ItemStack (Blocks.cobblestone), new ItemStack (tungstenCarbideHammer, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustGold,2, OreDictionary.WILDCARD_VALUE), new ItemStack (Blocks.gold_ore), new ItemStack (tungstenCarbideHammer, 1, OreDictionary.WILDCARD_VALUE));
//Diamond
GameRegistry.addShapelessRecipe(new ItemStack (dustEmerald,2, OreDictionary.WILDCARD_VALUE), new ItemStack (Blocks.emerald_ore), new ItemStack (hammerDiamond, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack(dustDiamond, 3, OreDictionary.WILDCARD_VALUE), new ItemStack (Blocks.diamond_ore), new ItemStack(hammerDiamond, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapedRecipe(new ItemStack (jadeHeadSw,1, OreDictionary.WILDCARD_VALUE), " x", " #", 'x', new ItemStack (jadeBlock), '#', new ItemStack (hammerDiamond, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapedRecipe(new ItemStack (jadeHeadSh,1, OreDictionary.WILDCARD_VALUE), "#x", 'x', new ItemStack (jadeBlock), '#', new ItemStack (hammerDiamond, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (jadeHeadHo,1, OreDictionary.WILDCARD_VALUE), new ItemStack (jadeBlock), new ItemStack (hammerDiamond, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapedRecipe(new ItemStack (jadeHeadAx,1, OreDictionary.WILDCARD_VALUE), " #", " x", 'x', new ItemStack (jadeBlock), '#', new ItemStack (hammerDiamond, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapedRecipe(new ItemStack (jadeHeadPi,1, OreDictionary.WILDCARD_VALUE), " x","# ", 'x', new ItemStack (jadeBlock), '#', new ItemStack (hammerDiamond, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustCopper,2), new ItemStack (oreCopper), new ItemStack (hammerDiamond, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustLead,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreLead), new ItemStack (hammerDiamond, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustFerrous,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreFerrous), new ItemStack (hammerDiamond, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustCopper,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkCopper), new ItemStack (hammerDiamond, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustSilver,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreSilver), new ItemStack (hammerDiamond, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustTin,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreTin), new ItemStack (hammerDiamond, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustTungsten,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreTungsten), new ItemStack (hammerDiamond, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustCopper,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreCopper), new ItemStack (hammerDiamond, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack(dustIron,2,OreDictionary.WILDCARD_VALUE), new ItemStack (Blocks.iron_ore), new ItemStack(hammerDiamond, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustFlour,4, OreDictionary.WILDCARD_VALUE),new ItemStack(hammerDiamond, 1, OreDictionary.WILDCARD_VALUE),new ItemStack(Items.wheat));
GameRegistry.addShapelessRecipe(new ItemStack (dustCharcoal,4, OreDictionary.WILDCARD_VALUE),new ItemStack(hammerDiamond, 1, OreDictionary.WILDCARD_VALUE),new ItemStack(Items.coal,1,1));
GameRegistry.addShapelessRecipe(new ItemStack (dustLead,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkLead), new ItemStack (hammerDiamond, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustFerrous,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkFerrous), new ItemStack (hammerDiamond, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustSilver,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkSilver), new ItemStack (hammerDiamond, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustTin,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkTin), new ItemStack (hammerDiamond, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustTungsten,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkTungsten), new ItemStack (hammerDiamond, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustCopper,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkCopper), new ItemStack (hammerDiamond, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (Blocks.sand,2, OreDictionary.WILDCARD_VALUE), new ItemStack (Blocks.cobblestone), new ItemStack (hammerDiamond, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustGold,2, OreDictionary.WILDCARD_VALUE), new ItemStack (Blocks.gold_ore), new ItemStack (hammerDiamond, 1, OreDictionary.WILDCARD_VALUE));
//Jade
GameRegistry.addShapelessRecipe(new ItemStack (dustEmerald,2, OreDictionary.WILDCARD_VALUE), new ItemStack (Blocks.emerald_ore), new ItemStack (hammerJade, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack(dustDiamond, 3, OreDictionary.WILDCARD_VALUE), new ItemStack (Blocks.diamond_ore), new ItemStack(hammerJade, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapedRecipe(new ItemStack (jadeHeadSw,1, OreDictionary.WILDCARD_VALUE), " x", " #", 'x', new ItemStack (jadeBlock), '#', new ItemStack (hammerJade, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapedRecipe(new ItemStack (jadeHeadSh,1, OreDictionary.WILDCARD_VALUE), "#x", 'x', new ItemStack (jadeBlock), '#', new ItemStack (hammerJade, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (jadeHeadHo,1, OreDictionary.WILDCARD_VALUE), new ItemStack (jadeBlock), new ItemStack (hammerJade, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapedRecipe(new ItemStack (jadeHeadAx,1, OreDictionary.WILDCARD_VALUE), " #", " x", 'x', new ItemStack (jadeBlock), '#', new ItemStack (hammerJade, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapedRecipe(new ItemStack (jadeHeadPi,1, OreDictionary.WILDCARD_VALUE), " x","# ", 'x', new ItemStack (jadeBlock), '#', new ItemStack (hammerJade, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustCopper,2), new ItemStack (oreCopper), new ItemStack (hammerJade, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustLead,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreLead), new ItemStack (hammerJade, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustFerrous,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreFerrous), new ItemStack (hammerJade, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustCopper,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkCopper), new ItemStack (hammerJade, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustSilver,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreSilver), new ItemStack (hammerJade, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustTin,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreTin), new ItemStack (hammerJade, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustTungsten,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreTungsten), new ItemStack (hammerJade, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustCopper,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreCopper), new ItemStack (hammerJade, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack(dustIron,2,OreDictionary.WILDCARD_VALUE), new ItemStack (Blocks.iron_ore), new ItemStack(hammerJade, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustFlour,4, OreDictionary.WILDCARD_VALUE),new ItemStack(hammerJade, 1, OreDictionary.WILDCARD_VALUE),new ItemStack(Items.wheat));
GameRegistry.addShapelessRecipe(new ItemStack (dustCharcoal,4, OreDictionary.WILDCARD_VALUE),new ItemStack(hammerJade, 1, OreDictionary.WILDCARD_VALUE),new ItemStack(Items.coal,1,1));
GameRegistry.addShapelessRecipe(new ItemStack (dustLead,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkLead), new ItemStack (hammerJade, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustFerrous,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkFerrous), new ItemStack (hammerJade, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustSilver,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkSilver), new ItemStack (hammerJade, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustTin,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkTin), new ItemStack (hammerJade, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustTungsten,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkTungsten), new ItemStack (hammerJade, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustCopper,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkCopper), new ItemStack (hammerJade, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (Blocks.sand,2, OreDictionary.WILDCARD_VALUE), new ItemStack (Blocks.cobblestone), new ItemStack (hammerJade, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustGold,2, OreDictionary.WILDCARD_VALUE), new ItemStack (Blocks.gold_ore), new ItemStack (hammerJade, 1, OreDictionary.WILDCARD_VALUE));
//Netherstar
GameRegistry.addShapelessRecipe(new ItemStack (dustEmerald,2, OreDictionary.WILDCARD_VALUE), new ItemStack (Blocks.emerald_ore), new ItemStack (hammerNetherstar, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack(dustDiamond, 3, OreDictionary.WILDCARD_VALUE), new ItemStack (Blocks.diamond_ore), new ItemStack(hammerNetherstar, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapedRecipe(new ItemStack (jadeHeadSw,1, OreDictionary.WILDCARD_VALUE), " x", " #", 'x', new ItemStack (jadeBlock), '#', new ItemStack (hammerNetherstar, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapedRecipe(new ItemStack (jadeHeadSh,1, OreDictionary.WILDCARD_VALUE), "#x", 'x', new ItemStack (jadeBlock), '#', new ItemStack (hammerNetherstar, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (jadeHeadHo,1, OreDictionary.WILDCARD_VALUE), new ItemStack (jadeBlock), new ItemStack (hammerNetherstar, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapedRecipe(new ItemStack (jadeHeadAx,1, OreDictionary.WILDCARD_VALUE), " #", " x", 'x', new ItemStack (jadeBlock), '#', new ItemStack (hammerNetherstar, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapedRecipe(new ItemStack (jadeHeadPi,1, OreDictionary.WILDCARD_VALUE), " x","# ", 'x', new ItemStack (jadeBlock), '#', new ItemStack (hammerNetherstar, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustCopper,2), new ItemStack (oreCopper), new ItemStack (hammerNetherstar, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustLead,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreLead), new ItemStack (hammerNetherstar, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustFerrous,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreFerrous), new ItemStack (hammerNetherstar, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustCopper,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkCopper), new ItemStack (hammerNetherstar, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustSilver,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreSilver), new ItemStack (hammerNetherstar, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustTin,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreTin), new ItemStack (hammerNetherstar, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustTungsten,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreTungsten), new ItemStack (hammerNetherstar, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustCopper,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreCopper), new ItemStack (hammerNetherstar, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack(dustIron,2,OreDictionary.WILDCARD_VALUE), new ItemStack (Blocks.iron_ore), new ItemStack(hammerNetherstar, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustFlour,4, OreDictionary.WILDCARD_VALUE),new ItemStack(hammerNetherstar, 1, OreDictionary.WILDCARD_VALUE),new ItemStack(Items.wheat));
GameRegistry.addShapelessRecipe(new ItemStack (dustCharcoal,4, OreDictionary.WILDCARD_VALUE),new ItemStack(hammerNetherstar, 1, OreDictionary.WILDCARD_VALUE),new ItemStack(Items.coal,1,1));
GameRegistry.addShapelessRecipe(new ItemStack (dustLead,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkLead), new ItemStack (hammerNetherstar, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustFerrous,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkFerrous), new ItemStack (hammerNetherstar, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustSilver,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkSilver), new ItemStack (hammerNetherstar, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustTin,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkTin), new ItemStack (hammerNetherstar, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustTungsten,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkTungsten), new ItemStack (hammerNetherstar, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustCopper,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkCopper), new ItemStack (hammerNetherstar, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (Blocks.sand,2, OreDictionary.WILDCARD_VALUE), new ItemStack (Blocks.cobblestone), new ItemStack (hammerNetherstar, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustGold,2, OreDictionary.WILDCARD_VALUE), new ItemStack (Blocks.gold_ore), new ItemStack (hammerNetherstar, 1, OreDictionary.WILDCARD_VALUE));
//sandstone
GameRegistry.addShapedRecipe(new ItemStack (jadeHeadSw,1, OreDictionary.WILDCARD_VALUE), " x", " #", 'x', new ItemStack (jadeBlock), '#', new ItemStack (hammerSandstone, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapedRecipe(new ItemStack (jadeHeadSh,1, OreDictionary.WILDCARD_VALUE), "#x", 'x', new ItemStack (jadeBlock), '#', new ItemStack (hammerSandstone, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (jadeHeadHo,1, OreDictionary.WILDCARD_VALUE), new ItemStack (jadeBlock), new ItemStack (hammerSandstone, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapedRecipe(new ItemStack (jadeHeadAx,1, OreDictionary.WILDCARD_VALUE), " #", " x", 'x', new ItemStack (jadeBlock), '#', new ItemStack (hammerSandstone, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapedRecipe(new ItemStack (jadeHeadPi,1, OreDictionary.WILDCARD_VALUE), " x","# ", 'x', new ItemStack (jadeBlock), '#', new ItemStack (hammerSandstone, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustCopper,2), new ItemStack (oreCopper), new ItemStack (hammerSandstone, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustLead,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreLead), new ItemStack (hammerSandstone, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustFerrous,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreFerrous), new ItemStack (hammerSandstone, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustCopper,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkCopper), new ItemStack (hammerSandstone, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustSilver,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreSilver), new ItemStack (hammerSandstone, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustTin,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreTin), new ItemStack (hammerSandstone, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustTungsten,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreTungsten), new ItemStack (hammerSandstone, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustCopper,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreCopper), new ItemStack (hammerSandstone, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack(dustIron,2,OreDictionary.WILDCARD_VALUE), new ItemStack (Blocks.iron_ore), new ItemStack(hammerSandstone, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustFlour,4, OreDictionary.WILDCARD_VALUE),new ItemStack(hammerSandstone, 1, OreDictionary.WILDCARD_VALUE),new ItemStack(Items.wheat));
GameRegistry.addShapelessRecipe(new ItemStack (dustCharcoal,4, OreDictionary.WILDCARD_VALUE),new ItemStack(hammerSandstone, 1, OreDictionary.WILDCARD_VALUE),new ItemStack(Items.coal,1,1));
GameRegistry.addShapelessRecipe(new ItemStack (dustLead,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkLead), new ItemStack (hammerSandstone, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustFerrous,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkFerrous), new ItemStack (hammerSandstone, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustSilver,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkSilver), new ItemStack (hammerSandstone, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustTin,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkTin), new ItemStack (hammerSandstone, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustTungsten,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkTungsten), new ItemStack (hammerSandstone, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustCopper,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkCopper), new ItemStack (hammerSandstone, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (Blocks.sand,2, OreDictionary.WILDCARD_VALUE), new ItemStack (Blocks.cobblestone), new ItemStack (hammerSandstone, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustGold,2, OreDictionary.WILDCARD_VALUE), new ItemStack (Blocks.gold_ore), new ItemStack (hammerSandstone, 1, OreDictionary.WILDCARD_VALUE));
//wooden
GameRegistry.addShapedRecipe(new ItemStack (jadeHeadSw,1, OreDictionary.WILDCARD_VALUE), " x", " #", 'x', new ItemStack (jadeBlock), '#', new ItemStack (hammerWooden, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapedRecipe(new ItemStack (jadeHeadSh,1, OreDictionary.WILDCARD_VALUE), "#x", 'x', new ItemStack (jadeBlock), '#', new ItemStack (hammerWooden, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (jadeHeadHo,1, OreDictionary.WILDCARD_VALUE), new ItemStack (jadeBlock), new ItemStack (hammerWooden, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapedRecipe(new ItemStack (jadeHeadAx,1, OreDictionary.WILDCARD_VALUE), " #", " x", 'x', new ItemStack (jadeBlock), '#', new ItemStack (hammerWooden, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapedRecipe(new ItemStack (jadeHeadPi,1, OreDictionary.WILDCARD_VALUE), " x","# ", 'x', new ItemStack (jadeBlock), '#', new ItemStack (hammerWooden, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustCopper,2), new ItemStack (oreCopper), new ItemStack (hammerWooden, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustLead,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreLead), new ItemStack (hammerWooden, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustFerrous,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreFerrous), new ItemStack (hammerWooden, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustCopper,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkCopper), new ItemStack (hammerWooden, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustSilver,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreSilver), new ItemStack (hammerWooden, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustTin,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreTin), new ItemStack (hammerWooden, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustTungsten,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreTungsten), new ItemStack (hammerWooden, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustCopper,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreCopper), new ItemStack (hammerWooden, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack(dustIron,2,OreDictionary.WILDCARD_VALUE), new ItemStack (Blocks.iron_ore), new ItemStack(hammerWooden, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustFlour,4, OreDictionary.WILDCARD_VALUE),new ItemStack(hammerWooden, 1, OreDictionary.WILDCARD_VALUE),new ItemStack(Items.wheat));
GameRegistry.addShapelessRecipe(new ItemStack (dustCharcoal,4, OreDictionary.WILDCARD_VALUE),new ItemStack(hammerWooden, 1, OreDictionary.WILDCARD_VALUE),new ItemStack(Items.coal,1,1));
GameRegistry.addShapelessRecipe(new ItemStack (dustLead,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkLead), new ItemStack (hammerWooden, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustFerrous,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkFerrous), new ItemStack (hammerWooden, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustSilver,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkSilver), new ItemStack (hammerWooden, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustTin,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkTin), new ItemStack (hammerWooden, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustTungsten,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkTungsten), new ItemStack (hammerWooden, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustCopper,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkCopper), new ItemStack (hammerWooden, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (Blocks.sand,2, OreDictionary.WILDCARD_VALUE), new ItemStack (Blocks.cobblestone), new ItemStack (hammerWooden, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustGold,2, OreDictionary.WILDCARD_VALUE), new ItemStack (Blocks.gold_ore), new ItemStack (hammerWooden, 1, OreDictionary.WILDCARD_VALUE));
//Copper
GameRegistry.addShapedRecipe(new ItemStack (jadeHeadSw,1, OreDictionary.WILDCARD_VALUE), " x", " #", 'x', new ItemStack (jadeBlock), '#', new ItemStack (hammerCopper, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapedRecipe(new ItemStack (jadeHeadSh,1, OreDictionary.WILDCARD_VALUE), "#x", 'x', new ItemStack (jadeBlock), '#', new ItemStack (hammerCopper, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (jadeHeadHo,1, OreDictionary.WILDCARD_VALUE), new ItemStack (jadeBlock), new ItemStack (hammerCopper, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapedRecipe(new ItemStack (jadeHeadAx,1, OreDictionary.WILDCARD_VALUE), " #", " x", 'x', new ItemStack (jadeBlock), '#', new ItemStack (hammerCopper, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapedRecipe(new ItemStack (jadeHeadPi,1, OreDictionary.WILDCARD_VALUE), " x","# ", 'x', new ItemStack (jadeBlock), '#', new ItemStack (hammerCopper, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustCopper,2), new ItemStack (oreCopper), new ItemStack (hammerCopper, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustLead,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreLead), new ItemStack (hammerCopper, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustFerrous,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreFerrous), new ItemStack (hammerCopper, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustSilver,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreSilver), new ItemStack (hammerCopper, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustTin,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreTin), new ItemStack (hammerCopper, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustTungsten,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreTungsten), new ItemStack (hammerCopper, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustCopper,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreCopper), new ItemStack (hammerCopper, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack(dustIron,2,OreDictionary.WILDCARD_VALUE), new ItemStack (Blocks.iron_ore), new ItemStack(hammerCopper, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustFlour,4, OreDictionary.WILDCARD_VALUE),new ItemStack(hammerCopper, 1, OreDictionary.WILDCARD_VALUE),new ItemStack(Items.wheat));
GameRegistry.addShapelessRecipe(new ItemStack (dustCharcoal,4, OreDictionary.WILDCARD_VALUE),new ItemStack(hammerCopper, 1, OreDictionary.WILDCARD_VALUE),new ItemStack(Items.coal,1,1));
GameRegistry.addShapelessRecipe(new ItemStack (dustCopper,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkCopper), new ItemStack (hammerCopper, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustLead,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkLead), new ItemStack (hammerCopper, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustFerrous,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkFerrous), new ItemStack (hammerCopper, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustSilver,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkSilver), new ItemStack (hammerCopper, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustTin,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkTin), new ItemStack (hammerCopper, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustTungsten,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkTungsten), new ItemStack (hammerCopper, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustCopper,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkCopper), new ItemStack (hammerCopper, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (Blocks.sand,2, OreDictionary.WILDCARD_VALUE), new ItemStack (Blocks.cobblestone), new ItemStack (hammerCopper, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustGold,2, OreDictionary.WILDCARD_VALUE), new ItemStack (Blocks.gold_ore), new ItemStack (hammerCopper, 1, OreDictionary.WILDCARD_VALUE));
//silver
GameRegistry.addShapedRecipe(new ItemStack (jadeHeadSw,1, OreDictionary.WILDCARD_VALUE), " x", " #", 'x', new ItemStack (jadeBlock), '#', new ItemStack (hammerSilver, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapedRecipe(new ItemStack (jadeHeadSh,1, OreDictionary.WILDCARD_VALUE), "#x", 'x', new ItemStack (jadeBlock), '#', new ItemStack (hammerSilver, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (jadeHeadHo,1, OreDictionary.WILDCARD_VALUE), new ItemStack (jadeBlock), new ItemStack (hammerSilver, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapedRecipe(new ItemStack (jadeHeadAx,1, OreDictionary.WILDCARD_VALUE), " #", " x", 'x', new ItemStack (jadeBlock), '#', new ItemStack (hammerSilver, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapedRecipe(new ItemStack (jadeHeadPi,1, OreDictionary.WILDCARD_VALUE), " x","# ", 'x', new ItemStack (jadeBlock), '#', new ItemStack (hammerSilver, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustCopper,2), new ItemStack (oreCopper), new ItemStack (hammerSilver, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustLead,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreLead), new ItemStack (hammerSilver, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustFerrous,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreFerrous), new ItemStack (hammerSilver, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustCopper,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkCopper), new ItemStack (hammerSilver, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustSilver,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreSilver), new ItemStack (hammerSilver, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustTin,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreTin), new ItemStack (hammerSilver, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustTungsten,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreTungsten), new ItemStack (hammerSilver, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustCopper,2, OreDictionary.WILDCARD_VALUE), new ItemStack (oreCopper), new ItemStack (hammerSilver, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack(dustIron,2,OreDictionary.WILDCARD_VALUE), new ItemStack (Blocks.iron_ore), new ItemStack(hammerSilver, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustFlour,4, OreDictionary.WILDCARD_VALUE),new ItemStack(hammerSilver, 1, OreDictionary.WILDCARD_VALUE),new ItemStack(Items.wheat));
GameRegistry.addShapelessRecipe(new ItemStack (dustCharcoal,4, OreDictionary.WILDCARD_VALUE),new ItemStack(hammerSilver, 1, OreDictionary.WILDCARD_VALUE),new ItemStack(Items.coal,1,1));
GameRegistry.addShapelessRecipe(new ItemStack (dustLead,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkLead), new ItemStack (hammerSilver, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustFerrous,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkFerrous), new ItemStack (hammerSilver, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustSilver,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkSilver), new ItemStack (hammerSilver, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustTin,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkTin), new ItemStack (hammerSilver, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustTungsten,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkTungsten), new ItemStack (hammerSilver, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustCopper,2, OreDictionary.WILDCARD_VALUE), new ItemStack (chunkCopper), new ItemStack (hammerSilver, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (Blocks.sand,2, OreDictionary.WILDCARD_VALUE), new ItemStack (Blocks.cobblestone), new ItemStack (hammerSilver, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (dustGold,2, OreDictionary.WILDCARD_VALUE), new ItemStack (Blocks.gold_ore), new ItemStack (hammerSilver, 1, OreDictionary.WILDCARD_VALUE));
//#addironhammer
//public static Item headDiamond;
//public static Item headJade;
//public static Item headNetherstar;
//public static Item headSandstone;
//public static Item headWooden;
//public static Item headCopper;
//public static Item headSilver;
//public static Item hammerDiamond;
//public static Item hammerJade;
// public static Item hammerNetherstar;
// public static Item hammerSandstone;
// public static Item hammerWooden;
// public static Item hammerCopper;
// public static Item hammerSilver;
//Hammer Crafting
GameRegistry.addShapelessRecipe(new ItemStack (stoneHammer), new ItemStack (stoneHamHead), new ItemStack (Items.stick));
GameRegistry.addShapedRecipe(new ItemStack (stoneHamHead), " ", "# #","###", '#', new ItemStack (Blocks.cobblestone));
GameRegistry.addShapelessRecipe(new ItemStack (hammerDiamond), new ItemStack (headDiamond), new ItemStack (Items.stick));
GameRegistry.addShapedRecipe(new ItemStack (headDiamond), " ", "# #","###", '#', new ItemStack (Items.diamond));
GameRegistry.addShapelessRecipe(new ItemStack (hammerJade), new ItemStack (headJade), new ItemStack (Items.stick));
GameRegistry.addShapedRecipe(new ItemStack (headJade), " ", "# #","###", '#', new ItemStack (RPCore.gemJadepure));
GameRegistry.addShapelessRecipe(new ItemStack (hammerNetherstar), new ItemStack (headNetherstar), new ItemStack (Items.stick));
GameRegistry.addShapedRecipe(new ItemStack (headNetherstar), " ", "# #","###", '#', new ItemStack (RPCore.ingotNetherstar));
GameRegistry.addShapelessRecipe(new ItemStack (hammerSandstone), new ItemStack (headSandstone), new ItemStack (Items.stick));
GameRegistry.addShapedRecipe(new ItemStack (headSandstone), " ", "# #","###", '#', new ItemStack (Blocks.sandstone));
GameRegistry.addShapelessRecipe(new ItemStack (hammerWooden), new ItemStack (headWooden), new ItemStack (Items.stick));
GameRegistry.addShapedRecipe(new ItemStack (headWooden), " ", "# #","###", '#', new ItemStack (Blocks.planks));
GameRegistry.addShapelessRecipe(new ItemStack (hammerCopper), new ItemStack (headCopper), new ItemStack (Items.stick));
GameRegistry.addShapedRecipe(new ItemStack (headCopper), " ", "# #","###", '#', new ItemStack (RPCore.ingotCopper));
GameRegistry.addShapelessRecipe(new ItemStack (hammerSilver), new ItemStack (headSilver), new ItemStack (Items.stick));
GameRegistry.addShapedRecipe(new ItemStack (headSilver), " ", "# #","###", '#', new ItemStack (RPCore.ingotSilver));
//Hammer End------- #AllofThehammerrecipes o.o
//Caustic Crafting
GameRegistry.addShapelessRecipe(new ItemStack(RPCore.causticCorpuscles,2),new ItemStack(Items.rotten_flesh), new ItemStack(toolSkinning,1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapedRecipe(new ItemStack (toolSkinning,1), "# #", "# #"," # ", '#', new ItemStack (Items.iron_ingot));
//GameRegistry.addShapelessRecipe(new ItemStack (bloodFirey,1)," # ","# #","###","#", new ItemStack (Blocks.glass_pane)); <-Dont Use Will Crash Game
GameRegistry.addShapelessRecipe(new ItemStack (bloodFirey,1),new ItemStack(RPCore.causticMeal), new ItemStack(Items.glass_bottle));
GameRegistry.addShapelessRecipe(new ItemStack (acidSulfuric ,1),new ItemStack(RPCore.causticCorpuscles), new ItemStack(Items.glass_bottle));
GameRegistry.addShapelessRecipe(new ItemStack (causticMeal,2),new ItemStack(RPCore.causticCorpuscles), new ItemStack(Items.dye,1,15));
GameRegistry.addShapelessRecipe(new ItemStack (dustPN,1),new ItemStack(RPCore.bloodFirey), new ItemStack(acidSulfuric));
GameRegistry.addShapedRecipe(new ItemStack (Items.gunpowder,4),"###","#0#","###", '#', new ItemStack (RPCore.dustCharcoal),'0',new ItemStack(RPCore.dustPN));
//###
//#0#
//###
GameRegistry.addShapelessRecipe(new ItemStack (dustMagickcompound,2), new ItemStack(dustMagick), new ItemStack(Items.glowstone_dust), new ItemStack(Items.redstone));
GameRegistry.addShapelessRecipe(new ItemStack(baconRaw,3, OreDictionary.WILDCARD_VALUE), new ItemStack (Items.porkchop), new ItemStack(knife, 1, OreDictionary.WILDCARD_VALUE));
GameRegistry.addShapelessRecipe(new ItemStack (elderPlanks,5), new ItemStack (elderLog));
GameRegistry.addShapelessRecipe(new ItemStack(dropMagick,4), new ItemStack (Items.water_bucket), new ItemStack (dustMagickcompound), new ItemStack(dustDiamond),new ItemStack (runePlate));
GameRegistry.addShapelessRecipe(new ItemStack(dropBig,1), new ItemStack (dropMagick), new ItemStack(Items.dye,1,3));
GameRegistry.addShapelessRecipe(new ItemStack(dropBounce,1),new ItemStack (dropMagick), new ItemStack(Items.dye,1,7));
GameRegistry.addShapelessRecipe(new ItemStack(dropDeath,1),new ItemStack (dropMagick),new ItemStack(Items.dye));
GameRegistry.addShapelessRecipe(new ItemStack(dropFly,1),new ItemStack (dropMagick),new ItemStack(Items.dye,1,11));
GameRegistry.addShapelessRecipe(new ItemStack(dropLife,1),new ItemStack (dropMagick),new ItemStack(Items.dye,1,2));
GameRegistry.addShapelessRecipe(new ItemStack(dropPoison,1),new ItemStack (dropMagick),new ItemStack(Items.dye,1,5));
GameRegistry.addShapelessRecipe(new ItemStack(dropRock,1),new ItemStack (dropMagick),new ItemStack(Items.dye,1,8));
GameRegistry.addShapelessRecipe(new ItemStack(dropSmall,1),new ItemStack (dropMagick),new ItemStack(Items.dye,1,5));
GameRegistry.addShapelessRecipe(new ItemStack(dropSuper,1),new ItemStack (dropMagick),new ItemStack(Items.dye,1,9));
GameRegistry.addShapelessRecipe(new ItemStack(megaCookie,4),new ItemStack(dropBig),new ItemStack(cookieSugar));
GameRegistry.addShapelessRecipe(new ItemStack(ghostCookie,4),new ItemStack(dropDeath),new ItemStack(dropLife),new ItemStack(cookieSugar));
GameRegistry.addShapelessRecipe(new ItemStack(poisonCookie,4),new ItemStack(dropDeath),new ItemStack(cookieSugar));
GameRegistry.addShapelessRecipe(new ItemStack(miniCookie,4),new ItemStack(dropSmall),new ItemStack(cookieSugar));
GameRegistry.addShapelessRecipe(new ItemStack(oneupCookie,4),new ItemStack(dropLife),new ItemStack(cookieSugar));
GameRegistry.addShapelessRecipe(new ItemStack(springCookie,4),new ItemStack(dropBounce),new ItemStack(cookieSugar));
GameRegistry.addShapelessRecipe(new ItemStack(propellerCookie,4),new ItemStack(dropFly),new ItemStack(cookieSugar));
GameRegistry.addShapelessRecipe(new ItemStack(rockCookie,4),new ItemStack(dropRock),new ItemStack(cookieSugar));
GameRegistry.addShapelessRecipe(new ItemStack(superCookie,4),new ItemStack(dropSuper),new ItemStack(cookieSugar));
GameRegistry.addShapedRecipe(new ItemStack (cookieSugar,4)," ","#0#"," ", '#', new ItemStack (RPCore.dustFlour),'0',new ItemStack(Items.sugar));
GameRegistry.addShapelessRecipe(new ItemStack(Blocks.planks), new ItemStack(elderPlanks));
GameRegistry.addShapelessRecipe(new ItemStack(gemJadepure, 4), new ItemStack(jadeBlock));
GameRegistry.addShapelessRecipe(new ItemStack(ingotCopper, 9), new ItemStack(copperBlock));
GameRegistry.addShapelessRecipe(new ItemStack(ingotLead, 9), new ItemStack(leadBlock));
GameRegistry.addShapelessRecipe(new ItemStack(ingotFerrous, 9), new ItemStack(ferrousBlock));
GameRegistry.addShapelessRecipe(new ItemStack(ingotNetherstar, 9), new ItemStack(netherstarBlock));
GameRegistry.addShapelessRecipe(new ItemStack(gemDiamond, 9), new ItemStack(organizeddiamondBlock));
GameRegistry.addShapelessRecipe(new ItemStack(gemEmerald, 9), new ItemStack(organizedemeraldBlock));
GameRegistry.addShapelessRecipe(new ItemStack(ingotSilver, 9), new ItemStack(silverBlock));
GameRegistry.addShapelessRecipe(new ItemStack(ingotTin, 9), new ItemStack(tinBlock));
GameRegistry.addShapelessRecipe(new ItemStack(ingotTungsten, 9), new ItemStack(tungstenBlock));
GameRegistry.addShapelessRecipe(new ItemStack(TCAI, 9), new ItemStack(tungstencarbideBlock));
GameRegistry.registerWorldGenerator(new RPWorldGen(), 1);
GameRegistry.registerFuelHandler(new RPFuelHandler());
NetworkRegistry.INSTANCE.registerGuiHandler(this, new GuiHandler());
proxy.registerProxies();
}
private Object ItemStack() {
// TODO Auto-generated method stub
return null;
}
public static ItemStack anthracite() {
// TODO Auto-generated method stub
return null;
}
}
//test Sync
| Full Commit MineFacility, Update Gratz Bro You Have Done a YoloSwaggins
| java/net/RPower/RPowermod/core/RPCore.java | Full Commit MineFacility, Update Gratz Bro You Have Done a YoloSwaggins | <ide><path>ava/net/RPower/RPowermod/core/RPCore.java
<ide> import net.RPower.RPowermod.block.blockRPBlock;
<ide> import net.RPower.RPowermod.block.blockRPBlockBSpace;
<ide> import net.RPower.RPowermod.block.blockRPOre;
<del><<<<<<< HEAD
<del>import net.RPower.RPowermod.item.ItemAnthracite;
<del>import net.RPower.RPowermod.item.ItemBronzeDust;
<del>import net.RPower.RPowermod.item.ItemCopperDust;
<del>import net.RPower.RPowermod.item.ItemCopperIngot;
<del>import net.RPower.RPowermod.item.ItemDiamondDust;
<del>import net.RPower.RPowermod.item.ItemDiamondIngot;
<del>import net.RPower.RPowermod.item.ItemEmeraldDust;
<del>import net.RPower.RPowermod.item.ItemEmeraldIngot;
<del>import net.RPower.RPowermod.item.ItemFerrousDust;
<del>import net.RPower.RPowermod.item.ItemFerrousIngot;
<del>import net.RPower.RPowermod.item.ItemFoodbaconCooked;
<del>import net.RPower.RPowermod.item.ItemFoodbaconRaw;
<del>import net.RPower.RPowermod.item.ItemFoodcookieSugar;
<del>import net.RPower.RPowermod.item.ItemFoodghostCookie;
<del>import net.RPower.RPowermod.item.ItemFoodmegaCookie;
<del>import net.RPower.RPowermod.item.ItemFoodminiCookie;
<del>import net.RPower.RPowermod.item.ItemFoodoneupCookie;
<del>import net.RPower.RPowermod.item.ItemFoodpoisonCookie;
<del>import net.RPower.RPowermod.item.ItemFoodpropellerCookie;
<del>import net.RPower.RPowermod.item.ItemFoodrockCookie;
<del>import net.RPower.RPowermod.item.ItemFoodspringCookie;
<del>import net.RPower.RPowermod.item.ItemFoodsuperCookie;
<del>import net.RPower.RPowermod.item.ItemFoodtestCookie;
<del>import net.RPower.RPowermod.item.ItemGoldDust;
<del>import net.RPower.RPowermod.item.ItemHeadBspace;
<del>import net.RPower.RPowermod.item.ItemIronDust;
<del>import net.RPower.RPowermod.item.ItemJade;
<del>import net.RPower.RPowermod.item.ItemJadeAxe;
<del>import net.RPower.RPowermod.item.ItemJadeHoe;
<del>import net.RPower.RPowermod.item.ItemJadePickaxe;
<del>import net.RPower.RPowermod.item.ItemJadeSpade;
<del>import net.RPower.RPowermod.item.ItemJadeSword;
<del>import net.RPower.RPowermod.item.ItemLeadDust;
<del>import net.RPower.RPowermod.item.ItemLeadIngot;
<del>import net.RPower.RPowermod.item.ItemNetherstarDust;
<del>import net.RPower.RPowermod.item.ItemNetherstarIngot;
<del>import net.RPower.RPowermod.item.ItemSilverDust;
<del>import net.RPower.RPowermod.item.ItemSilverIngot;
<del>import net.RPower.RPowermod.item.ItemSteelDust;
<del>import net.RPower.RPowermod.item.ItemTCAI;
<del>import net.RPower.RPowermod.item.ItemTinDust;
<del>import net.RPower.RPowermod.item.ItemTinIngot;
<del>import net.RPower.RPowermod.item.ItemTugstenDust;
<del>import net.RPower.RPowermod.item.ItemTungstenIngot;
<del>import net.RPower.RPowermod.item.ItemTungstencarbideIngot;
<del>import net.RPower.RPowermod.item.ItemblankScroll;
<del>import net.RPower.RPowermod.item.ItemdustFlour;
<del>import net.RPower.RPowermod.item.ItemdustSugar;
<del>import net.RPower.RPowermod.item.ItemingotBronze;
<del>import net.RPower.RPowermod.item.ItemingotSteel;
<del>import net.RPower.RPowermod.item.Itemknife;
<del>import net.RPower.RPowermod.item.Itemmortar_and_pestle;
<del>import net.RPower.RPowermod.item.ItemquartcBowl;
<del>import net.RPower.RPowermod.item.ItemquartcStick;
<del>import net.RPower.RPowermod.item.ItemsandPaper;
<del>import net.RPower.RPowermod.item.ItemscrollCircle;
<del>import net.RPower.RPowermod.item.ItemyellowLeaf;
<del>import net.RPower.RPowermod.item.chunkCopper;
<del>import net.RPower.RPowermod.item.dropBig;
<del>import net.RPower.RPowermod.item.dropBounce;
<del>import net.RPower.RPowermod.item.dropDeath;
<del>import net.RPower.RPowermod.item.dropFly;
<del>import net.RPower.RPowermod.item.dropLife;
<del>import net.RPower.RPowermod.item.dropMagick;
<del>import net.RPower.RPowermod.item.dropPoisen;
<del>import net.RPower.RPowermod.item.dropRock;
<del>import net.RPower.RPowermod.item.dropSmall;
<del>import net.RPower.RPowermod.item.dropSuper;
<del>import net.RPower.RPowermod.item.dustMagick;
<del>import net.RPower.RPowermod.item.dustMagickcompound;
<del>import net.RPower.RPowermod.item.hammerCopper;
<del>import net.RPower.RPowermod.item.hammerDiamond;
<del>import net.RPower.RPowermod.item.hammerJade;
<del>import net.RPower.RPowermod.item.hammerNetherstar;
<del>import net.RPower.RPowermod.item.hammerSandstone;
<del>import net.RPower.RPowermod.item.hammerSilver;
<del>import net.RPower.RPowermod.item.hammerStone;
<del>import net.RPower.RPowermod.item.hammerWooden;
<del>import net.RPower.RPowermod.item.itemDustPN;
<del>import net.RPower.RPowermod.item.itemPencil;
<del>import net.RPower.RPowermod.item.itemSkinningtool;
<del>import net.RPower.RPowermod.item.itemacidS;
<del>import net.RPower.RPowermod.item.itembloodFirey;
<del>import net.RPower.RPowermod.item.itemcorpCaustic;
<del>import net.RPower.RPowermod.item.itemdustCharcoal;
<del>import net.RPower.RPowermod.item.itemmealCaustic;
<del>import net.RPower.RPowermod.item.runeAir;
<del>import net.RPower.RPowermod.item.runeEarth;
<del>import net.RPower.RPowermod.item.runeFire;
<del>import net.RPower.RPowermod.item.runePlate;
<del>import net.RPower.RPowermod.item.runeSpirit;
<del>import net.RPower.RPowermod.item.runeWater;
<del>=======
<ide> import net.RPower.RPowermod.gui.GuiHandler;
<ide> import net.RPower.RPowermod.item.*;
<del>>>>>>>> ec95970406957eae8e3cdd0ac616691e205e3dc4
<add>import net.RPower.RPowermod.item.ItemHeadBspace;
<ide> import net.RPower.RPowermod.net.ItemFoodcreativeCookie;
<ide> import net.RPower.RPowermod.proxy.CommonProxy;
<ide> import net.RPower.RPowermod.tileentity.TileEntityalloySmelter;
<ide> public static Item protopaintGold;
<ide> public static Item protopaintTungstencarbide;
<ide>
<del>
<del>
<del>
<del>
<del>
<del>
<del>
<del>
<del>
<del>
<del>
<del>
<del>
<del>
<del>
<del>
<del>
<del>
<del>
<del>
<del>
<add>
<ide> //Runes
<ide> public static Item runeAir;
<ide> public static Item runeEarth; |
|
Java | agpl-3.0 | 91d1cea51f6459e2cf48f2bbbf3ceaca70d2e215 | 0 | Freeyourgadget/Gadgetbridge,Freeyourgadget/Gadgetbridge,roidelapluie/Gadgetbridge,roidelapluie/Gadgetbridge,rosenpin/Gadgetbridge,rosenpin/Gadgetbridge,roidelapluie/Gadgetbridge,Freeyourgadget/Gadgetbridge,Freeyourgadget/Gadgetbridge,ivanovlev/Gadgetbridge,rosenpin/Gadgetbridge,ivanovlev/Gadgetbridge,ivanovlev/Gadgetbridge | package nodomain.freeyourgadget.gadgetbridge.service.devices.miband;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.content.Intent;
import android.net.Uri;
import android.support.v4.content.LocalBroadcastManager;
import android.widget.Toast;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.UUID;
import nodomain.freeyourgadget.gadgetbridge.GBApplication;
import nodomain.freeyourgadget.gadgetbridge.R;
import nodomain.freeyourgadget.gadgetbridge.deviceevents.GBDeviceEventBatteryInfo;
import nodomain.freeyourgadget.gadgetbridge.deviceevents.GBDeviceEventVersionInfo;
import nodomain.freeyourgadget.gadgetbridge.devices.miband.MiBandConst;
import nodomain.freeyourgadget.gadgetbridge.devices.miband.MiBandCoordinator;
import nodomain.freeyourgadget.gadgetbridge.devices.miband.MiBandDateConverter;
import nodomain.freeyourgadget.gadgetbridge.devices.miband.MiBandFWHelper;
import nodomain.freeyourgadget.gadgetbridge.devices.miband.MiBandService;
import nodomain.freeyourgadget.gadgetbridge.devices.miband.VibrationProfile;
import nodomain.freeyourgadget.gadgetbridge.impl.GBDevice;
import nodomain.freeyourgadget.gadgetbridge.impl.GBDevice.State;
import nodomain.freeyourgadget.gadgetbridge.model.Alarm;
import nodomain.freeyourgadget.gadgetbridge.model.CalendarEventSpec;
import nodomain.freeyourgadget.gadgetbridge.model.CalendarEvents;
import nodomain.freeyourgadget.gadgetbridge.model.CallSpec;
import nodomain.freeyourgadget.gadgetbridge.model.CannedMessagesSpec;
import nodomain.freeyourgadget.gadgetbridge.model.DeviceService;
import nodomain.freeyourgadget.gadgetbridge.model.GenericItem;
import nodomain.freeyourgadget.gadgetbridge.model.MusicSpec;
import nodomain.freeyourgadget.gadgetbridge.model.MusicStateSpec;
import nodomain.freeyourgadget.gadgetbridge.model.NotificationSpec;
import nodomain.freeyourgadget.gadgetbridge.service.btle.AbstractBTLEDeviceSupport;
import nodomain.freeyourgadget.gadgetbridge.service.btle.BtLEAction;
import nodomain.freeyourgadget.gadgetbridge.service.btle.GattCharacteristic;
import nodomain.freeyourgadget.gadgetbridge.service.btle.GattService;
import nodomain.freeyourgadget.gadgetbridge.service.btle.TransactionBuilder;
import nodomain.freeyourgadget.gadgetbridge.service.btle.actions.AbortTransactionAction;
import nodomain.freeyourgadget.gadgetbridge.service.btle.actions.ConditionalWriteAction;
import nodomain.freeyourgadget.gadgetbridge.service.btle.actions.SetDeviceStateAction;
import nodomain.freeyourgadget.gadgetbridge.service.btle.actions.WriteAction;
import nodomain.freeyourgadget.gadgetbridge.service.devices.miband.operations.FetchActivityOperation;
import nodomain.freeyourgadget.gadgetbridge.service.devices.miband.operations.UpdateFirmwareOperation;
import nodomain.freeyourgadget.gadgetbridge.util.DateTimeUtils;
import nodomain.freeyourgadget.gadgetbridge.util.GB;
import nodomain.freeyourgadget.gadgetbridge.util.Prefs;
import static nodomain.freeyourgadget.gadgetbridge.devices.miband.MiBandConst.DEFAULT_VALUE_FLASH_COLOUR;
import static nodomain.freeyourgadget.gadgetbridge.devices.miband.MiBandConst.DEFAULT_VALUE_FLASH_COUNT;
import static nodomain.freeyourgadget.gadgetbridge.devices.miband.MiBandConst.DEFAULT_VALUE_FLASH_DURATION;
import static nodomain.freeyourgadget.gadgetbridge.devices.miband.MiBandConst.DEFAULT_VALUE_FLASH_ORIGINAL_COLOUR;
import static nodomain.freeyourgadget.gadgetbridge.devices.miband.MiBandConst.DEFAULT_VALUE_VIBRATION_COUNT;
import static nodomain.freeyourgadget.gadgetbridge.devices.miband.MiBandConst.DEFAULT_VALUE_VIBRATION_DURATION;
import static nodomain.freeyourgadget.gadgetbridge.devices.miband.MiBandConst.DEFAULT_VALUE_VIBRATION_PAUSE;
import static nodomain.freeyourgadget.gadgetbridge.devices.miband.MiBandConst.DEFAULT_VALUE_VIBRATION_PROFILE;
import static nodomain.freeyourgadget.gadgetbridge.devices.miband.MiBandConst.FLASH_COLOUR;
import static nodomain.freeyourgadget.gadgetbridge.devices.miband.MiBandConst.FLASH_COUNT;
import static nodomain.freeyourgadget.gadgetbridge.devices.miband.MiBandConst.FLASH_DURATION;
import static nodomain.freeyourgadget.gadgetbridge.devices.miband.MiBandConst.FLASH_ORIGINAL_COLOUR;
import static nodomain.freeyourgadget.gadgetbridge.devices.miband.MiBandConst.ORIGIN_GENERIC;
import static nodomain.freeyourgadget.gadgetbridge.devices.miband.MiBandConst.ORIGIN_K9MAIL;
import static nodomain.freeyourgadget.gadgetbridge.devices.miband.MiBandConst.ORIGIN_PEBBLEMSG;
import static nodomain.freeyourgadget.gadgetbridge.devices.miband.MiBandConst.ORIGIN_SMS;
import static nodomain.freeyourgadget.gadgetbridge.devices.miband.MiBandConst.VIBRATION_COUNT;
import static nodomain.freeyourgadget.gadgetbridge.devices.miband.MiBandConst.VIBRATION_DURATION;
import static nodomain.freeyourgadget.gadgetbridge.devices.miband.MiBandConst.VIBRATION_PAUSE;
import static nodomain.freeyourgadget.gadgetbridge.devices.miband.MiBandConst.VIBRATION_PROFILE;
import static nodomain.freeyourgadget.gadgetbridge.devices.miband.MiBandConst.getNotificationPrefIntValue;
import static nodomain.freeyourgadget.gadgetbridge.devices.miband.MiBandConst.getNotificationPrefStringValue;
public class MiBandSupport extends AbstractBTLEDeviceSupport {
private static final Logger LOG = LoggerFactory.getLogger(MiBandSupport.class);
/**
* This is just for temporary testing of Mi1A double firmware update.
* DO NOT SET TO TRUE UNLESS YOU KNOW WHAT YOU'RE DOING!
*/
public static final boolean MI_1A_HR_FW_UPDATE_TEST_MODE_ENABLED = false;
private volatile boolean telephoneRinging;
private volatile boolean isLocatingDevice;
private DeviceInfo mDeviceInfo;
private final GBDeviceEventVersionInfo versionCmd = new GBDeviceEventVersionInfo();
private final GBDeviceEventBatteryInfo batteryCmd = new GBDeviceEventBatteryInfo();
public MiBandSupport() {
addSupportedService(GattService.UUID_SERVICE_GENERIC_ACCESS);
addSupportedService(GattService.UUID_SERVICE_GENERIC_ATTRIBUTE);
addSupportedService(MiBandService.UUID_SERVICE_MIBAND_SERVICE);
addSupportedService(MiBandService.UUID_SERVICE_HEART_RATE);
addSupportedService(GattService.UUID_SERVICE_IMMEDIATE_ALERT);
}
@Override
protected TransactionBuilder initializeDevice(TransactionBuilder builder) {
builder.add(new SetDeviceStateAction(getDevice(), State.INITIALIZING, getContext()));
enableNotifications(builder, true)
.setLowLatency(builder)
.readDate(builder) // without reading the data, we get sporadic connection problems, especially directly after turning on BT
.pair(builder)
.requestDeviceInfo(builder)
.sendUserInfo(builder)
.checkAuthenticationNeeded(builder, getDevice())
.setWearLocation(builder)
.setHeartrateSleepSupport(builder)
.setFitnessGoal(builder)
.enableFurtherNotifications(builder, true)
.setCurrentTime(builder)
.requestBatteryInfo(builder)
.setHighLatency(builder)
.setInitialized(builder);
return builder;
}
private MiBandSupport readDate(TransactionBuilder builder) {
builder.read(getCharacteristic(MiBandService.UUID_CHARACTERISTIC_DATE_TIME));
return this;
}
public MiBandSupport setLowLatency(TransactionBuilder builder) {
builder.write(getCharacteristic(MiBandService.UUID_CHARACTERISTIC_LE_PARAMS), getLowLatency());
return this;
}
public MiBandSupport setHighLatency(TransactionBuilder builder) {
builder.write(getCharacteristic(MiBandService.UUID_CHARACTERISTIC_LE_PARAMS), getHighLatency());
return this;
}
private MiBandSupport checkAuthenticationNeeded(TransactionBuilder builder, GBDevice device) {
builder.add(new CheckAuthenticationNeededAction(device));
return this;
}
/**
* Last action of initialization sequence. Sets the device to initialized.
* It is only invoked if all other actions were successfully run, so the device
* must be initialized, then.
*
* @param builder
*/
private void setInitialized(TransactionBuilder builder) {
builder.add(new SetDeviceStateAction(getDevice(), State.INITIALIZED, getContext()));
}
// TODO: tear down the notifications on quit
private MiBandSupport enableNotifications(TransactionBuilder builder, boolean enable) {
builder.notify(getCharacteristic(MiBandService.UUID_CHARACTERISTIC_NOTIFICATION), enable);
return this;
}
private MiBandSupport enableFurtherNotifications(TransactionBuilder builder, boolean enable) {
builder.notify(getCharacteristic(MiBandService.UUID_CHARACTERISTIC_REALTIME_STEPS), enable)
.notify(getCharacteristic(MiBandService.UUID_CHARACTERISTIC_ACTIVITY_DATA), enable)
.notify(getCharacteristic(MiBandService.UUID_CHARACTERISTIC_BATTERY), enable)
.notify(getCharacteristic(MiBandService.UUID_CHARACTERISTIC_SENSOR_DATA), enable);
// cannot use supportsHeartrate() here because we don't have that information yet
BluetoothGattCharacteristic heartrateCharacteristic = getCharacteristic(MiBandService.UUID_CHARACTERISTIC_HEART_RATE_MEASUREMENT);
if (heartrateCharacteristic != null) {
builder.notify(heartrateCharacteristic, enable);
}
return this;
}
@Override
public boolean useAutoConnect() {
return true;
}
@Override
public void pair() {
for (int i = 0; i < 5; i++) {
if (connect()) {
return;
}
}
}
public DeviceInfo getDeviceInfo() {
return mDeviceInfo;
}
private MiBandSupport sendDefaultNotification(TransactionBuilder builder, short repeat, BtLEAction extraAction) {
LOG.info("Sending notification to MiBand: (" + repeat + " times)");
NotificationStrategy strategy = getNotificationStrategy();
for (short i = 0; i < repeat; i++) {
strategy.sendDefaultNotification(builder, extraAction);
}
return this;
}
/**
* Adds a custom notification to the given transaction builder
*
* @param vibrationProfile specifies how and how often the Band shall vibrate.
* @param flashTimes
* @param flashColour
* @param originalColour
* @param flashDuration
* @param extraAction an extra action to be executed after every vibration and flash sequence. Allows to abort the repetition, for example.
* @param builder
*/
private MiBandSupport sendCustomNotification(VibrationProfile vibrationProfile, int flashTimes, int flashColour, int originalColour, long flashDuration, BtLEAction extraAction, TransactionBuilder builder) {
getNotificationStrategy().sendCustomNotification(vibrationProfile, flashTimes, flashColour, originalColour, flashDuration, extraAction, builder);
LOG.info("Sending notification to MiBand");
return this;
}
private NotificationStrategy getNotificationStrategy() {
if (mDeviceInfo == null) {
// not initialized yet?
return new NoNotificationStrategy();
}
if (mDeviceInfo.getFirmwareVersion() < MiBandFWHelper.FW_16779790) {
return new V1NotificationStrategy(this);
} else {
//use the new alert characteristic
return new V2NotificationStrategy(this);
}
}
static final byte[] reboot = new byte[]{MiBandService.COMMAND_REBOOT};
static final byte[] startHeartMeasurementManual = new byte[]{0x15, MiBandService.COMMAND_SET_HR_MANUAL, 1};
static final byte[] stopHeartMeasurementManual = new byte[]{0x15, MiBandService.COMMAND_SET_HR_MANUAL, 0};
static final byte[] startHeartMeasurementContinuous = new byte[]{0x15, MiBandService.COMMAND_SET__HR_CONTINUOUS, 1};
static final byte[] stopHeartMeasurementContinuous = new byte[]{0x15, MiBandService.COMMAND_SET__HR_CONTINUOUS, 0};
static final byte[] startHeartMeasurementSleep = new byte[]{0x15, MiBandService.COMMAND_SET_HR_SLEEP, 1};
static final byte[] stopHeartMeasurementSleep = new byte[]{0x15, MiBandService.COMMAND_SET_HR_SLEEP, 0};
static final byte[] startRealTimeStepsNotifications = new byte[]{MiBandService.COMMAND_SET_REALTIME_STEPS_NOTIFICATION, 1};
static final byte[] stopRealTimeStepsNotifications = new byte[]{MiBandService.COMMAND_SET_REALTIME_STEPS_NOTIFICATION, 0};
/**
* Part of device initialization process. Do not call manually.
*
* @param builder
* @return
*/
private MiBandSupport sendUserInfo(TransactionBuilder builder) {
LOG.debug("Writing User Info!");
// Use a custom action instead of just builder.write() because mDeviceInfo
// is set by handleDeviceInfo *after* this action is created.
builder.add(new BtLEAction(getCharacteristic(MiBandService.UUID_CHARACTERISTIC_USER_INFO)) {
@Override
public boolean expectsResult() {
return true;
}
@Override
public boolean run(BluetoothGatt gatt) {
// at this point, mDeviceInfo should be set
return new WriteAction(getCharacteristic(),
MiBandCoordinator.getAnyUserInfo(getDevice().getAddress()).getData(mDeviceInfo)
).run(gatt);
}
});
return this;
}
private MiBandSupport requestBatteryInfo(TransactionBuilder builder) {
LOG.debug("Requesting Battery Info!");
BluetoothGattCharacteristic characteristic = getCharacteristic(MiBandService.UUID_CHARACTERISTIC_BATTERY);
builder.read(characteristic);
return this;
}
private MiBandSupport requestDeviceInfo(TransactionBuilder builder) {
LOG.debug("Requesting Device Info!");
BluetoothGattCharacteristic deviceInfo = getCharacteristic(MiBandService.UUID_CHARACTERISTIC_DEVICE_INFO);
builder.read(deviceInfo);
BluetoothGattCharacteristic deviceName = getCharacteristic(GattCharacteristic.UUID_CHARACTERISTIC_GAP_DEVICE_NAME);
builder.read(deviceName);
return this;
}
/* private MiBandSupport requestHRInfo(TransactionBuilder builder) {
LOG.debug("Requesting HR Info!");
BluetoothGattCharacteristic HRInfo = getCharacteristic(MiBandService.UUID_CHAR_HEART_RATE_MEASUREMENT);
builder.read(HRInfo);
BluetoothGattCharacteristic HR_Point = getCharacteristic(GattCharacteristic.UUID_CHARACTERISTIC_HEART_RATE_CONTROL_POINT);
builder.read(HR_Point);
return this;
}
*//**
* Part of HR test. Do not call manually.
*
* @param transaction
* @return
*//*
private MiBandSupport heartrate(TransactionBuilder transaction) {
LOG.info("Attempting to read HR ...");
BluetoothGattCharacteristic characteristic = getCharacteristic(MiBandService.UUID_CHAR_HEART_RATE_MEASUREMENT);
if (characteristic != null) {
transaction.write(characteristic, new byte[]{MiBandService.COMMAND_SET__HR_CONTINUOUS});
} else {
LOG.info("Unable to read HR from MI device -- characteristic not available");
}
return this;
}*/
/**
* Part of device initialization process. Do not call manually.
*
* @param transaction
* @return
*/
private MiBandSupport pair(TransactionBuilder transaction) {
LOG.info("Attempting to pair MI device...");
BluetoothGattCharacteristic characteristic = getCharacteristic(MiBandService.UUID_CHARACTERISTIC_PAIR);
if (characteristic != null) {
transaction.write(characteristic, new byte[]{2});
} else {
LOG.info("Unable to pair MI device -- characteristic not available");
}
return this;
}
/**
* Part of device initialization process. Do not call manually.
*
* @param transaction
* @return
*/
private MiBandSupport setFitnessGoal(TransactionBuilder transaction) {
LOG.info("Attempting to set Fitness Goal...");
BluetoothGattCharacteristic characteristic = getCharacteristic(MiBandService.UUID_CHARACTERISTIC_CONTROL_POINT);
if (characteristic != null) {
int fitnessGoal = MiBandCoordinator.getFitnessGoal(getDevice().getAddress());
transaction.write(characteristic, new byte[]{
MiBandService.COMMAND_SET_FITNESS_GOAL,
0,
(byte) (fitnessGoal & 0xff),
(byte) ((fitnessGoal >>> 8) & 0xff)
});
} else {
LOG.info("Unable to set Fitness Goal");
}
return this;
}
/**
* Part of device initialization process. Do not call manually.
*
* @param transaction
* @return
*/
private MiBandSupport setWearLocation(TransactionBuilder transaction) {
LOG.info("Attempting to set wear location...");
BluetoothGattCharacteristic characteristic = getCharacteristic(MiBandService.UUID_CHARACTERISTIC_CONTROL_POINT);
if (characteristic != null) {
transaction.add(new ConditionalWriteAction(characteristic) {
@Override
protected byte[] checkCondition() {
if (getDeviceInfo() != null && getDeviceInfo().isAmazFit()) {
return null;
}
int location = MiBandCoordinator.getWearLocation(getDevice().getAddress());
return new byte[]{
MiBandService.COMMAND_SET_WEAR_LOCATION,
(byte) location
};
}
});
} else {
LOG.info("Unable to set Wear Location");
}
return this;
}
@Override
public void onEnableHeartRateSleepSupport(boolean enable) {
try {
TransactionBuilder builder = performInitialized("enable heart rate sleep support: " + enable);
setHeartrateSleepSupport(builder);
builder.queue(getQueue());
} catch (IOException e) {
GB.toast(getContext(), "Error toggling heart rate sleep support: " + e.getLocalizedMessage(), Toast.LENGTH_LONG, GB.ERROR);
}
}
@Override
public void onAddCalendarEvent(CalendarEventSpec calendarEventSpec) {
// not supported
}
@Override
public void onDeleteCalendarEvent(byte type, long id) {
// not supported
}
/**
* Part of device initialization process. Do not call manually.
*
* @param builder
*/
private MiBandSupport setHeartrateSleepSupport(TransactionBuilder builder) {
BluetoothGattCharacteristic characteristic = getCharacteristic(MiBandService.UUID_CHARACTERISTIC_HEART_RATE_CONTROL_POINT);
if (characteristic != null) {
builder.add(new ConditionalWriteAction(characteristic) {
@Override
protected byte[] checkCondition() {
if (!supportsHeartRate()) {
return null;
}
if (MiBandCoordinator.getHeartrateSleepSupport(getDevice().getAddress())) {
LOG.info("Enabling heartrate sleep support...");
return startHeartMeasurementSleep;
} else {
LOG.info("Disabling heartrate sleep support...");
return stopHeartMeasurementSleep;
}
}
});
}
return this;
}
private void performDefaultNotification(String task, short repeat, BtLEAction extraAction) {
try {
TransactionBuilder builder = performInitialized(task);
sendDefaultNotification(builder, repeat, extraAction);
builder.queue(getQueue());
} catch (IOException ex) {
LOG.error("Unable to send notification to MI device", ex);
}
}
private void performPreferredNotification(String task, String notificationOrigin, BtLEAction extraAction) {
try {
TransactionBuilder builder = performInitialized(task);
Prefs prefs = GBApplication.getPrefs();
int vibrateDuration = getPreferredVibrateDuration(notificationOrigin, prefs);
int vibratePause = getPreferredVibratePause(notificationOrigin, prefs);
short vibrateTimes = getPreferredVibrateCount(notificationOrigin, prefs);
VibrationProfile profile = getPreferredVibrateProfile(notificationOrigin, prefs, vibrateTimes);
int flashTimes = getPreferredFlashCount(notificationOrigin, prefs);
int flashColour = getPreferredFlashColour(notificationOrigin, prefs);
int originalColour = getPreferredOriginalColour(notificationOrigin, prefs);
int flashDuration = getPreferredFlashDuration(notificationOrigin, prefs);
sendCustomNotification(profile, flashTimes, flashColour, originalColour, flashDuration, extraAction, builder);
// sendCustomNotification(vibrateDuration, vibrateTimes, vibratePause, flashTimes, flashColour, originalColour, flashDuration, builder);
builder.queue(getQueue());
} catch (IOException ex) {
LOG.error("Unable to send notification to MI device", ex);
}
}
private int getPreferredFlashDuration(String notificationOrigin, Prefs prefs) {
return getNotificationPrefIntValue(FLASH_DURATION, notificationOrigin, prefs, DEFAULT_VALUE_FLASH_DURATION);
}
private int getPreferredOriginalColour(String notificationOrigin, Prefs prefs) {
return getNotificationPrefIntValue(FLASH_ORIGINAL_COLOUR, notificationOrigin, prefs, DEFAULT_VALUE_FLASH_ORIGINAL_COLOUR);
}
private int getPreferredFlashColour(String notificationOrigin, Prefs prefs) {
return getNotificationPrefIntValue(FLASH_COLOUR, notificationOrigin, prefs, DEFAULT_VALUE_FLASH_COLOUR);
}
private int getPreferredFlashCount(String notificationOrigin, Prefs prefs) {
return getNotificationPrefIntValue(FLASH_COUNT, notificationOrigin, prefs, DEFAULT_VALUE_FLASH_COUNT);
}
private int getPreferredVibratePause(String notificationOrigin, Prefs prefs) {
return getNotificationPrefIntValue(VIBRATION_PAUSE, notificationOrigin, prefs, DEFAULT_VALUE_VIBRATION_PAUSE);
}
private short getPreferredVibrateCount(String notificationOrigin, Prefs prefs) {
return (short) Math.min(Short.MAX_VALUE, getNotificationPrefIntValue(VIBRATION_COUNT, notificationOrigin, prefs, DEFAULT_VALUE_VIBRATION_COUNT));
}
private int getPreferredVibrateDuration(String notificationOrigin, Prefs prefs) {
return getNotificationPrefIntValue(VIBRATION_DURATION, notificationOrigin, prefs, DEFAULT_VALUE_VIBRATION_DURATION);
}
private VibrationProfile getPreferredVibrateProfile(String notificationOrigin, Prefs prefs, short repeat) {
String profileId = getNotificationPrefStringValue(VIBRATION_PROFILE, notificationOrigin, prefs, DEFAULT_VALUE_VIBRATION_PROFILE);
return VibrationProfile.getProfile(profileId, repeat);
}
@Override
public void onSetAlarms(ArrayList<? extends Alarm> alarms) {
try {
BluetoothGattCharacteristic characteristic = getCharacteristic(MiBandService.UUID_CHARACTERISTIC_CONTROL_POINT);
TransactionBuilder builder = performInitialized("Set alarm");
boolean anyAlarmEnabled = false;
for (Alarm alarm : alarms) {
anyAlarmEnabled |= alarm.isEnabled();
queueAlarm(alarm, builder, characteristic);
}
builder.queue(getQueue());
if (anyAlarmEnabled) {
GB.toast(getContext(), getContext().getString(R.string.user_feedback_miband_set_alarms_ok), Toast.LENGTH_SHORT, GB.INFO);
} else {
GB.toast(getContext(), getContext().getString(R.string.user_feedback_all_alarms_disabled), Toast.LENGTH_SHORT, GB.INFO);
}
} catch (IOException ex) {
GB.toast(getContext(), getContext().getString(R.string.user_feedback_miband_set_alarms_failed), Toast.LENGTH_LONG, GB.ERROR, ex);
}
}
@Override
public void onNotification(NotificationSpec notificationSpec) {
// FIXME: these ORIGIN contants do not really make sense anymore
switch (notificationSpec.type) {
case SMS:
performPreferredNotification("sms received", ORIGIN_SMS, null);
break;
case EMAIL:
performPreferredNotification("email received", ORIGIN_K9MAIL, null);
break;
case CHAT:
performPreferredNotification("chat message received", ORIGIN_PEBBLEMSG, null);
break;
default:
performPreferredNotification("generic notification received", ORIGIN_GENERIC, null);
}
}
@Override
public void onSetTime() {
try {
TransactionBuilder builder = performInitialized("Set date and time");
setCurrentTime(builder);
builder.queue(getQueue());
} catch (IOException ex) {
LOG.error("Unable to set time on MI device", ex);
}
//TODO: once we have a common strategy for sending events (e.g. EventHandler), remove this call from here. Meanwhile it does no harm.
sendCalendarEvents();
}
/**
* Sets the current time to the Mi device using the given builder.
*
* @param builder
*/
private MiBandSupport setCurrentTime(TransactionBuilder builder) {
Calendar now = GregorianCalendar.getInstance();
Date date = now.getTime();
LOG.info("Sending current time to Mi Band: " + DateTimeUtils.formatDate(date) + " (" + date.toGMTString() + ")");
byte[] nowBytes = MiBandDateConverter.calendarToRawBytes(now);
byte[] time = new byte[]{
nowBytes[0],
nowBytes[1],
nowBytes[2],
nowBytes[3],
nowBytes[4],
nowBytes[5],
(byte) 0x0f,
(byte) 0x0f,
(byte) 0x0f,
(byte) 0x0f,
(byte) 0x0f,
(byte) 0x0f
};
BluetoothGattCharacteristic characteristic = getCharacteristic(MiBandService.UUID_CHARACTERISTIC_DATE_TIME);
if (characteristic != null) {
builder.write(characteristic, time);
} else {
LOG.info("Unable to set time -- characteristic not available");
}
return this;
}
@Override
public void onSetCallState(CallSpec callSpec) {
if (callSpec.command == CallSpec.CALL_INCOMING) {
telephoneRinging = true;
AbortTransactionAction abortAction = new AbortTransactionAction() {
@Override
protected boolean shouldAbort() {
return !isTelephoneRinging();
}
};
performPreferredNotification("incoming call", MiBandConst.ORIGIN_INCOMING_CALL, abortAction);
} else if ((callSpec.command == CallSpec.CALL_START) || (callSpec.command == CallSpec.CALL_END)) {
telephoneRinging = false;
}
}
@Override
public void onSetCannedMessages(CannedMessagesSpec cannedMessagesSpec) {
}
private boolean isTelephoneRinging() {
// don't synchronize, this is not really important
return telephoneRinging;
}
@Override
public void onSetMusicState(MusicStateSpec stateSpec) {
// not supported
}
@Override
public void onSetMusicInfo(MusicSpec musicSpec) {
// not supported
}
@Override
public void onReboot() {
try {
TransactionBuilder builder = performInitialized("Reboot");
builder.write(getCharacteristic(MiBandService.UUID_CHARACTERISTIC_CONTROL_POINT), reboot);
builder.queue(getQueue());
} catch (IOException ex) {
LOG.error("Unable to reboot MI", ex);
}
}
@Override
public void onHeartRateTest() {
if (supportsHeartRate()) {
try {
TransactionBuilder builder = performInitialized("HeartRateTest");
builder.write(getCharacteristic(MiBandService.UUID_CHARACTERISTIC_HEART_RATE_CONTROL_POINT), stopHeartMeasurementContinuous);
builder.write(getCharacteristic(MiBandService.UUID_CHARACTERISTIC_HEART_RATE_CONTROL_POINT), stopHeartMeasurementManual);
builder.write(getCharacteristic(MiBandService.UUID_CHARACTERISTIC_HEART_RATE_CONTROL_POINT), startHeartMeasurementManual);
builder.queue(getQueue());
} catch (IOException ex) {
LOG.error("Unable to read HearRate in MI1S", ex);
}
} else {
GB.toast(getContext(), "Heart rate is not supported on this device", Toast.LENGTH_LONG, GB.ERROR);
}
}
@Override
public void onEnableRealtimeHeartRateMeasurement(boolean enable) {
if (supportsHeartRate()) {
try {
TransactionBuilder builder = performInitialized("EnableRealtimeHeartRateMeasurement");
if (enable) {
builder.write(getCharacteristic(MiBandService.UUID_CHARACTERISTIC_HEART_RATE_CONTROL_POINT), stopHeartMeasurementManual);
builder.write(getCharacteristic(MiBandService.UUID_CHARACTERISTIC_HEART_RATE_CONTROL_POINT), startHeartMeasurementContinuous);
} else {
builder.write(getCharacteristic(MiBandService.UUID_CHARACTERISTIC_HEART_RATE_CONTROL_POINT), stopHeartMeasurementContinuous);
}
builder.queue(getQueue());
} catch (IOException ex) {
LOG.error("Unable to enable realtime heart rate measurement in MI1S", ex);
}
}
}
public boolean supportsHeartRate() {
return getDeviceInfo() != null && getDeviceInfo().supportsHeartrate();
}
@Override
public void onFindDevice(boolean start) {
isLocatingDevice = start;
if (start) {
AbortTransactionAction abortAction = new AbortTransactionAction() {
@Override
protected boolean shouldAbort() {
return !isLocatingDevice;
}
};
performDefaultNotification("locating device", (short) 255, abortAction);
}
}
@Override
public void onFetchActivityData() {
try {
new FetchActivityOperation(this).perform();
} catch (IOException ex) {
LOG.error("Unable to fetch MI activity data", ex);
}
}
@Override
public void onEnableRealtimeSteps(boolean enable) {
try {
BluetoothGattCharacteristic controlPoint = getCharacteristic(MiBandService.UUID_CHARACTERISTIC_CONTROL_POINT);
if (enable) {
TransactionBuilder builder = performInitialized("Read realtime steps");
builder.read(getCharacteristic(MiBandService.UUID_CHARACTERISTIC_REALTIME_STEPS)).queue(getQueue());
}
performInitialized(enable ? "Enabling realtime steps notifications" : "Disabling realtime steps notifications")
.write(getCharacteristic(MiBandService.UUID_CHARACTERISTIC_LE_PARAMS), enable ? getLowLatency() : getHighLatency())
.write(controlPoint, enable ? startRealTimeStepsNotifications : stopRealTimeStepsNotifications).queue(getQueue());
} catch (IOException e) {
LOG.error("Unable to change realtime steps notification to: " + enable, e);
}
}
private byte[] getHighLatency() {
int minConnectionInterval = 460;
int maxConnectionInterval = 500;
int latency = 0;
int timeout = 500;
int advertisementInterval = 0;
return getLatency(minConnectionInterval, maxConnectionInterval, latency, timeout, advertisementInterval);
}
private byte[] getLatency(int minConnectionInterval, int maxConnectionInterval, int latency, int timeout, int advertisementInterval) {
byte result[] = new byte[12];
result[0] = (byte) (minConnectionInterval & 0xff);
result[1] = (byte) (0xff & minConnectionInterval >> 8);
result[2] = (byte) (maxConnectionInterval & 0xff);
result[3] = (byte) (0xff & maxConnectionInterval >> 8);
result[4] = (byte) (latency & 0xff);
result[5] = (byte) (0xff & latency >> 8);
result[6] = (byte) (timeout & 0xff);
result[7] = (byte) (0xff & timeout >> 8);
result[8] = 0;
result[9] = 0;
result[10] = (byte) (advertisementInterval & 0xff);
result[11] = (byte) (0xff & advertisementInterval >> 8);
return result;
}
private byte[] getLowLatency() {
int minConnectionInterval = 39;
int maxConnectionInterval = 49;
int latency = 0;
int timeout = 500;
int advertisementInterval = 0;
return getLatency(minConnectionInterval, maxConnectionInterval, latency, timeout, advertisementInterval);
}
@Override
public void onInstallApp(Uri uri) {
try {
new UpdateFirmwareOperation(uri, this).perform();
} catch (IOException ex) {
GB.toast(getContext(), "Firmware cannot be installed: " + ex.getMessage(), Toast.LENGTH_LONG, GB.ERROR, ex);
}
}
@Override
public void onAppInfoReq() {
// not supported
}
@Override
public void onAppStart(UUID uuid, boolean start) {
// not supported
}
@Override
public void onAppDelete(UUID uuid) {
// not supported
}
@Override
public void onAppConfiguration(UUID uuid, String config) {
// not supported
}
@Override
public void onAppReorder(UUID[] uuids) {
// not supported
}
@Override
public void onScreenshotReq() {
// not supported
}
@Override
public void onCharacteristicChanged(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic) {
super.onCharacteristicChanged(gatt, characteristic);
UUID characteristicUUID = characteristic.getUuid();
if (MiBandService.UUID_CHARACTERISTIC_BATTERY.equals(characteristicUUID)) {
handleBatteryInfo(characteristic.getValue(), BluetoothGatt.GATT_SUCCESS);
} else if (MiBandService.UUID_CHARACTERISTIC_NOTIFICATION.equals(characteristicUUID)) {
handleNotificationNotif(characteristic.getValue());
} else if (MiBandService.UUID_CHARACTERISTIC_REALTIME_STEPS.equals(characteristicUUID)) {
handleRealtimeSteps(characteristic.getValue());
} else if (MiBandService.UUID_CHARACTERISTIC_REALTIME_STEPS.equals(characteristicUUID)) {
handleRealtimeSteps(characteristic.getValue());
} else if (MiBandService.UUID_CHARACTERISTIC_HEART_RATE_MEASUREMENT.equals(characteristicUUID)) {
handleHeartrate(characteristic.getValue());
} else {
LOG.info("Unhandled characteristic changed: " + characteristicUUID);
logMessageContent(characteristic.getValue());
}
}
@Override
public void onCharacteristicRead(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic, int status) {
super.onCharacteristicRead(gatt, characteristic, status);
UUID characteristicUUID = characteristic.getUuid();
if (MiBandService.UUID_CHARACTERISTIC_DEVICE_INFO.equals(characteristicUUID)) {
handleDeviceInfo(characteristic.getValue(), status);
} else if (GattCharacteristic.UUID_CHARACTERISTIC_GAP_DEVICE_NAME.equals(characteristicUUID)) {
handleDeviceName(characteristic.getValue(), status);
} else if (MiBandService.UUID_CHARACTERISTIC_BATTERY.equals(characteristicUUID)) {
handleBatteryInfo(characteristic.getValue(), status);
} else if (MiBandService.UUID_CHARACTERISTIC_HEART_RATE_MEASUREMENT.equals(characteristicUUID)) {
logHeartrate(characteristic.getValue(), status);
} else if (MiBandService.UUID_CHARACTERISTIC_DATE_TIME.equals(characteristicUUID)) {
logDate(characteristic.getValue(), status);
} else {
LOG.info("Unhandled characteristic read: " + characteristicUUID);
logMessageContent(characteristic.getValue());
}
}
@Override
public void onCharacteristicWrite(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic, int status) {
UUID characteristicUUID = characteristic.getUuid();
if (MiBandService.UUID_CHARACTERISTIC_PAIR.equals(characteristicUUID)) {
handlePairResult(characteristic.getValue(), status);
} else if (MiBandService.UUID_CHARACTERISTIC_USER_INFO.equals(characteristicUUID)) {
handleUserInfoResult(characteristic.getValue(), status);
} else if (MiBandService.UUID_CHARACTERISTIC_CONTROL_POINT.equals(characteristicUUID)) {
handleControlPointResult(characteristic.getValue(), status);
}
}
/**
* Utility method that may be used to log incoming messages when we don't know how to deal with them yet.
*
* @param value
*/
public void logMessageContent(byte[] value) {
LOG.info("RECEIVED DATA WITH LENGTH: " + ((value != null) ? value.length : "(null)"));
if (value != null) {
for (byte b : value) {
LOG.warn("DATA: " + String.format("0x%2x", b));
}
}
}
public void logDate(byte[] value, int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
GregorianCalendar calendar = MiBandDateConverter.rawBytesToCalendar(value);
LOG.info("Got Mi Band Date: " + DateTimeUtils.formatDateTime(calendar.getTime()));
} else {
logMessageContent(value);
}
}
public void logHeartrate(byte[] value, int status) {
if (status == BluetoothGatt.GATT_SUCCESS && value != null) {
LOG.info("Got heartrate:");
if (value.length == 2 && value[0] == 6) {
int hrValue = (value[1] & 0xff);
GB.toast(getContext(), "Heart Rate measured: " + hrValue, Toast.LENGTH_LONG, GB.INFO);
}
return;
}
logMessageContent(value);
}
private void handleHeartrate(byte[] value) {
if (value.length == 2 && value[0] == 6) {
int hrValue = (value[1] & 0xff);
if (LOG.isDebugEnabled()) {
LOG.debug("heart rate: " + hrValue);
}
Intent intent = new Intent(DeviceService.ACTION_HEARTRATE_MEASUREMENT)
.putExtra(DeviceService.EXTRA_HEART_RATE_VALUE, hrValue)
.putExtra(DeviceService.EXTRA_TIMESTAMP, System.currentTimeMillis());
LocalBroadcastManager.getInstance(getContext()).sendBroadcast(intent);
}
}
private void handleRealtimeSteps(byte[] value) {
int steps = 0xff & value[0] | (0xff & value[1]) << 8;
if (LOG.isDebugEnabled()) {
LOG.debug("realtime steps: " + steps);
}
Intent intent = new Intent(DeviceService.ACTION_REALTIME_STEPS)
.putExtra(DeviceService.EXTRA_REALTIME_STEPS, steps)
.putExtra(DeviceService.EXTRA_TIMESTAMP, System.currentTimeMillis());
LocalBroadcastManager.getInstance(getContext()).sendBroadcast(intent);
}
/**
* React to unsolicited messages sent by the Mi Band to the MiBandService.UUID_CHARACTERISTIC_NOTIFICATION
* characteristic,
* These messages appear to be always 1 byte long, with values that are listed in MiBandService.
* It is not excluded that there are further values which are still unknown.
* <p/>
* Upon receiving known values that request further action by GB, the appropriate method is called.
*
* @param value
*/
private void handleNotificationNotif(byte[] value) {
if (value.length != 1) {
LOG.error("Notifications should be 1 byte long.");
LOG.info("RECEIVED DATA WITH LENGTH: " + value.length);
for (byte b : value) {
LOG.warn("DATA: " + String.format("0x%2x", b));
}
return;
}
switch (value[0]) {
case MiBandService.NOTIFY_AUTHENTICATION_FAILED:
// we get first FAILED, then NOTIFY_STATUS_MOTOR_AUTH (0x13)
// which means, we need to authenticate by tapping
getDevice().setState(State.AUTHENTICATION_REQUIRED);
getDevice().sendDeviceUpdateIntent(getContext());
GB.toast(getContext(), "Band needs pairing", Toast.LENGTH_LONG, GB.ERROR);
break;
case MiBandService.NOTIFY_AUTHENTICATION_SUCCESS: // fall through -- not sure which one we get
case MiBandService.NOTIFY_RESET_AUTHENTICATION_SUCCESS: // for Mi 1A
case MiBandService.NOTIFY_STATUS_MOTOR_AUTH_SUCCESS:
LOG.info("Band successfully authenticated");
// maybe we can perform the rest of the initialization from here
doInitialize();
break;
case MiBandService.NOTIFY_STATUS_MOTOR_AUTH:
LOG.info("Band needs authentication (MOTOR_AUTH)");
getDevice().setState(State.AUTHENTICATING);
getDevice().sendDeviceUpdateIntent(getContext());
break;
default:
for (byte b : value) {
LOG.warn("DATA: " + String.format("0x%2x", b));
}
}
}
private void doInitialize() {
try {
TransactionBuilder builder = performInitialized("just initializing after authentication");
builder.queue(getQueue());
} catch (IOException ex) {
LOG.error("Unable to initialize device after authentication", ex);
}
}
private void handleDeviceInfo(byte[] value, int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
mDeviceInfo = new DeviceInfo(value);
mDeviceInfo.setTest1AHRMode(MI_1A_HR_FW_UPDATE_TEST_MODE_ENABLED);
if (getDeviceInfo().supportsHeartrate()) {
getDevice().addDeviceInfo(new GenericItem(
getContext().getString(R.string.DEVINFO_HR_VER),
MiBandFWHelper.formatFirmwareVersion(mDeviceInfo.getHeartrateFirmwareVersion())));
}
LOG.warn("Device info: " + mDeviceInfo);
versionCmd.hwVersion = mDeviceInfo.getHwVersion();
versionCmd.fwVersion = MiBandFWHelper.formatFirmwareVersion(mDeviceInfo.getFirmwareVersion());
handleGBDeviceEvent(versionCmd);
}
}
private void handleDeviceName(byte[] value, int status) {
// if (status == BluetoothGatt.GATT_SUCCESS) {
// versionCmd.hwVersion = new String(value);
// handleGBDeviceEvent(versionCmd);
// }
}
/**
* Convert an alarm from the GB internal structure to a Mi Band message and put on the specified
* builder queue as a write message for the passed characteristic
*
* @param alarm
* @param builder
* @param characteristic
*/
private void queueAlarm(Alarm alarm, TransactionBuilder builder, BluetoothGattCharacteristic characteristic) {
byte[] alarmCalBytes = MiBandDateConverter.calendarToRawBytes(alarm.getAlarmCal());
byte[] alarmMessage = new byte[]{
MiBandService.COMMAND_SET_TIMER,
(byte) alarm.getIndex(),
(byte) (alarm.isEnabled() ? 1 : 0),
alarmCalBytes[0],
alarmCalBytes[1],
alarmCalBytes[2],
alarmCalBytes[3],
alarmCalBytes[4],
alarmCalBytes[5],
(byte) (alarm.isSmartWakeup() ? 30 : 0),
(byte) alarm.getRepetitionMask()
};
builder.write(characteristic, alarmMessage);
}
private void handleControlPointResult(byte[] value, int status) {
if (status != BluetoothGatt.GATT_SUCCESS) {
LOG.warn("Could not write to the control point.");
}
LOG.info("handleControlPoint write status:" + status + "; length: " + (value != null ? value.length : "(null)"));
if (value != null) {
for (byte b : value) {
LOG.info("handleControlPoint WROTE DATA:" + String.format("0x%8x", b));
}
} else {
LOG.warn("handleControlPoint WROTE null");
}
}
private void handleBatteryInfo(byte[] value, int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
BatteryInfo info = new BatteryInfo(value);
batteryCmd.level = ((short) info.getLevelInPercent());
batteryCmd.state = info.getState();
batteryCmd.lastChargeTime = info.getLastChargeTime();
batteryCmd.numCharges = info.getNumCharges();
handleGBDeviceEvent(batteryCmd);
}
}
private void handleUserInfoResult(byte[] value, int status) {
// successfully transferred user info means we're initialized
// commented out, because we have SetDeviceStateAction which sets initialized
// state on every successful initialization.
// if (status == BluetoothGatt.GATT_SUCCESS) {
// setConnectionState(State.INITIALIZED);
// }
}
private void setConnectionState(State newState) {
getDevice().setState(newState);
getDevice().sendDeviceUpdateIntent(getContext());
}
private void handlePairResult(byte[] pairResult, int status) {
if (status != BluetoothGatt.GATT_SUCCESS) {
LOG.info("Pairing MI device failed: " + status);
return;
}
String value = null;
if (pairResult != null) {
if (pairResult.length == 1) {
try {
if (pairResult[0] == 2) {
LOG.info("Successfully paired MI device");
return;
}
} catch (Exception ex) {
LOG.warn("Error identifying pairing result", ex);
return;
}
}
value = Arrays.toString(pairResult);
}
LOG.info("MI Band pairing result: " + value);
}
/**
* Fetch the events from the android device calendars and set the alarms on the miband.
*/
private void sendCalendarEvents() {
try {
TransactionBuilder builder = performInitialized("Send upcoming events");
BluetoothGattCharacteristic characteristic = getCharacteristic(MiBandService.UUID_CHARACTERISTIC_CONTROL_POINT);
Prefs prefs = GBApplication.getPrefs();
int availableSlots = prefs.getInt(MiBandConst.PREF_MIBAND_RESERVE_ALARM_FOR_CALENDAR, 0);
if (availableSlots > 0) {
CalendarEvents upcomingEvents = new CalendarEvents();
List<CalendarEvents.CalendarEvent> mEvents = upcomingEvents.getCalendarEventList(getContext());
int iteration = 0;
for (CalendarEvents.CalendarEvent mEvt : mEvents) {
if (iteration >= availableSlots || iteration > 2) {
break;
}
int slotToUse = 2 - iteration;
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(mEvt.getBegin());
byte[] calBytes = MiBandDateConverter.calendarToRawBytes(calendar);
byte[] alarmMessage = new byte[]{
MiBandService.COMMAND_SET_TIMER,
(byte) slotToUse,
(byte) 1,
calBytes[0],
calBytes[1],
calBytes[2],
calBytes[3],
calBytes[4],
calBytes[5],
(byte) 0,
(byte) 0
};
builder.write(characteristic, alarmMessage);
iteration++;
}
builder.queue(getQueue());
}
} catch (IOException ex) {
LOG.error("Unable to send Events to MI device", ex);
}
}
}
| app/src/main/java/nodomain/freeyourgadget/gadgetbridge/service/devices/miband/MiBandSupport.java | package nodomain.freeyourgadget.gadgetbridge.service.devices.miband;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.content.Intent;
import android.net.Uri;
import android.support.v4.content.LocalBroadcastManager;
import android.widget.Toast;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.UUID;
import nodomain.freeyourgadget.gadgetbridge.GBApplication;
import nodomain.freeyourgadget.gadgetbridge.R;
import nodomain.freeyourgadget.gadgetbridge.deviceevents.GBDeviceEventBatteryInfo;
import nodomain.freeyourgadget.gadgetbridge.deviceevents.GBDeviceEventVersionInfo;
import nodomain.freeyourgadget.gadgetbridge.devices.miband.MiBandConst;
import nodomain.freeyourgadget.gadgetbridge.devices.miband.MiBandCoordinator;
import nodomain.freeyourgadget.gadgetbridge.devices.miband.MiBandDateConverter;
import nodomain.freeyourgadget.gadgetbridge.devices.miband.MiBandFWHelper;
import nodomain.freeyourgadget.gadgetbridge.devices.miband.MiBandService;
import nodomain.freeyourgadget.gadgetbridge.devices.miband.VibrationProfile;
import nodomain.freeyourgadget.gadgetbridge.impl.GBDevice;
import nodomain.freeyourgadget.gadgetbridge.impl.GBDevice.State;
import nodomain.freeyourgadget.gadgetbridge.model.Alarm;
import nodomain.freeyourgadget.gadgetbridge.model.CalendarEventSpec;
import nodomain.freeyourgadget.gadgetbridge.model.CalendarEvents;
import nodomain.freeyourgadget.gadgetbridge.model.CallSpec;
import nodomain.freeyourgadget.gadgetbridge.model.CannedMessagesSpec;
import nodomain.freeyourgadget.gadgetbridge.model.DeviceService;
import nodomain.freeyourgadget.gadgetbridge.model.GenericItem;
import nodomain.freeyourgadget.gadgetbridge.model.MusicSpec;
import nodomain.freeyourgadget.gadgetbridge.model.MusicStateSpec;
import nodomain.freeyourgadget.gadgetbridge.model.NotificationSpec;
import nodomain.freeyourgadget.gadgetbridge.service.btle.AbstractBTLEDeviceSupport;
import nodomain.freeyourgadget.gadgetbridge.service.btle.BtLEAction;
import nodomain.freeyourgadget.gadgetbridge.service.btle.GattCharacteristic;
import nodomain.freeyourgadget.gadgetbridge.service.btle.GattService;
import nodomain.freeyourgadget.gadgetbridge.service.btle.TransactionBuilder;
import nodomain.freeyourgadget.gadgetbridge.service.btle.actions.AbortTransactionAction;
import nodomain.freeyourgadget.gadgetbridge.service.btle.actions.ConditionalWriteAction;
import nodomain.freeyourgadget.gadgetbridge.service.btle.actions.SetDeviceStateAction;
import nodomain.freeyourgadget.gadgetbridge.service.btle.actions.WriteAction;
import nodomain.freeyourgadget.gadgetbridge.service.devices.miband.operations.FetchActivityOperation;
import nodomain.freeyourgadget.gadgetbridge.service.devices.miband.operations.UpdateFirmwareOperation;
import nodomain.freeyourgadget.gadgetbridge.util.DateTimeUtils;
import nodomain.freeyourgadget.gadgetbridge.util.GB;
import nodomain.freeyourgadget.gadgetbridge.util.Prefs;
import static nodomain.freeyourgadget.gadgetbridge.devices.miband.MiBandConst.DEFAULT_VALUE_FLASH_COLOUR;
import static nodomain.freeyourgadget.gadgetbridge.devices.miband.MiBandConst.DEFAULT_VALUE_FLASH_COUNT;
import static nodomain.freeyourgadget.gadgetbridge.devices.miband.MiBandConst.DEFAULT_VALUE_FLASH_DURATION;
import static nodomain.freeyourgadget.gadgetbridge.devices.miband.MiBandConst.DEFAULT_VALUE_FLASH_ORIGINAL_COLOUR;
import static nodomain.freeyourgadget.gadgetbridge.devices.miband.MiBandConst.DEFAULT_VALUE_VIBRATION_COUNT;
import static nodomain.freeyourgadget.gadgetbridge.devices.miband.MiBandConst.DEFAULT_VALUE_VIBRATION_DURATION;
import static nodomain.freeyourgadget.gadgetbridge.devices.miband.MiBandConst.DEFAULT_VALUE_VIBRATION_PAUSE;
import static nodomain.freeyourgadget.gadgetbridge.devices.miband.MiBandConst.DEFAULT_VALUE_VIBRATION_PROFILE;
import static nodomain.freeyourgadget.gadgetbridge.devices.miband.MiBandConst.FLASH_COLOUR;
import static nodomain.freeyourgadget.gadgetbridge.devices.miband.MiBandConst.FLASH_COUNT;
import static nodomain.freeyourgadget.gadgetbridge.devices.miband.MiBandConst.FLASH_DURATION;
import static nodomain.freeyourgadget.gadgetbridge.devices.miband.MiBandConst.FLASH_ORIGINAL_COLOUR;
import static nodomain.freeyourgadget.gadgetbridge.devices.miband.MiBandConst.ORIGIN_GENERIC;
import static nodomain.freeyourgadget.gadgetbridge.devices.miband.MiBandConst.ORIGIN_K9MAIL;
import static nodomain.freeyourgadget.gadgetbridge.devices.miband.MiBandConst.ORIGIN_PEBBLEMSG;
import static nodomain.freeyourgadget.gadgetbridge.devices.miband.MiBandConst.ORIGIN_SMS;
import static nodomain.freeyourgadget.gadgetbridge.devices.miband.MiBandConst.VIBRATION_COUNT;
import static nodomain.freeyourgadget.gadgetbridge.devices.miband.MiBandConst.VIBRATION_DURATION;
import static nodomain.freeyourgadget.gadgetbridge.devices.miband.MiBandConst.VIBRATION_PAUSE;
import static nodomain.freeyourgadget.gadgetbridge.devices.miband.MiBandConst.VIBRATION_PROFILE;
import static nodomain.freeyourgadget.gadgetbridge.devices.miband.MiBandConst.getNotificationPrefIntValue;
import static nodomain.freeyourgadget.gadgetbridge.devices.miband.MiBandConst.getNotificationPrefStringValue;
public class MiBandSupport extends AbstractBTLEDeviceSupport {
private static final Logger LOG = LoggerFactory.getLogger(MiBandSupport.class);
/**
* This is just for temporary testing of Mi1A double firmware update.
* DO NOT SET TO TRUE UNLESS YOU KNOW WHAT YOU'RE DOING!
*/
public static final boolean MI_1A_HR_FW_UPDATE_TEST_MODE_ENABLED = false;
private volatile boolean telephoneRinging;
private volatile boolean isLocatingDevice;
private DeviceInfo mDeviceInfo;
private final GBDeviceEventVersionInfo versionCmd = new GBDeviceEventVersionInfo();
private final GBDeviceEventBatteryInfo batteryCmd = new GBDeviceEventBatteryInfo();
public MiBandSupport() {
addSupportedService(GattService.UUID_SERVICE_GENERIC_ACCESS);
addSupportedService(GattService.UUID_SERVICE_GENERIC_ATTRIBUTE);
addSupportedService(MiBandService.UUID_SERVICE_MIBAND_SERVICE);
addSupportedService(MiBandService.UUID_SERVICE_HEART_RATE);
addSupportedService(GattService.UUID_SERVICE_IMMEDIATE_ALERT);
}
@Override
protected TransactionBuilder initializeDevice(TransactionBuilder builder) {
builder.add(new SetDeviceStateAction(getDevice(), State.INITIALIZING, getContext()));
enableNotifications(builder, true)
.setLowLatency(builder)
.readDate(builder) // without reading the data, we get sporadic connection problems, especially directly after turning on BT
.pair(builder)
.requestDeviceInfo(builder)
.sendUserInfo(builder)
.checkAuthenticationNeeded(builder, getDevice())
.setWearLocation(builder)
.setHeartrateSleepSupport(builder)
.setFitnessGoal(builder)
.enableFurtherNotifications(builder, true)
.setCurrentTime(builder)
.requestBatteryInfo(builder)
.setHighLatency(builder)
.setInitialized(builder);
return builder;
}
private MiBandSupport readDate(TransactionBuilder builder) {
builder.read(getCharacteristic(MiBandService.UUID_CHARACTERISTIC_DATE_TIME));
return this;
}
public MiBandSupport setLowLatency(TransactionBuilder builder) {
builder.write(getCharacteristic(MiBandService.UUID_CHARACTERISTIC_LE_PARAMS), getLowLatency());
return this;
}
public MiBandSupport setHighLatency(TransactionBuilder builder) {
builder.write(getCharacteristic(MiBandService.UUID_CHARACTERISTIC_LE_PARAMS), getHighLatency());
return this;
}
private MiBandSupport checkAuthenticationNeeded(TransactionBuilder builder, GBDevice device) {
builder.add(new CheckAuthenticationNeededAction(device));
return this;
}
/**
* Last action of initialization sequence. Sets the device to initialized.
* It is only invoked if all other actions were successfully run, so the device
* must be initialized, then.
*
* @param builder
*/
private void setInitialized(TransactionBuilder builder) {
builder.add(new SetDeviceStateAction(getDevice(), State.INITIALIZED, getContext()));
}
// TODO: tear down the notifications on quit
private MiBandSupport enableNotifications(TransactionBuilder builder, boolean enable) {
builder.notify(getCharacteristic(MiBandService.UUID_CHARACTERISTIC_NOTIFICATION), enable);
return this;
}
private MiBandSupport enableFurtherNotifications(TransactionBuilder builder, boolean enable) {
builder.notify(getCharacteristic(MiBandService.UUID_CHARACTERISTIC_REALTIME_STEPS), enable)
.notify(getCharacteristic(MiBandService.UUID_CHARACTERISTIC_ACTIVITY_DATA), enable)
.notify(getCharacteristic(MiBandService.UUID_CHARACTERISTIC_BATTERY), enable)
.notify(getCharacteristic(MiBandService.UUID_CHARACTERISTIC_SENSOR_DATA), enable);
// cannot use supportsHeartrate() here because we don't have that information yet
BluetoothGattCharacteristic heartrateCharacteristic = getCharacteristic(MiBandService.UUID_CHARACTERISTIC_HEART_RATE_MEASUREMENT);
if (heartrateCharacteristic != null) {
builder.notify(heartrateCharacteristic, enable);
}
return this;
}
@Override
public boolean useAutoConnect() {
return true;
}
@Override
public void pair() {
for (int i = 0; i < 5; i++) {
if (connect()) {
return;
}
}
}
public DeviceInfo getDeviceInfo() {
return mDeviceInfo;
}
private MiBandSupport sendDefaultNotification(TransactionBuilder builder, short repeat, BtLEAction extraAction) {
LOG.info("Sending notification to MiBand: (" + repeat + " times)");
NotificationStrategy strategy = getNotificationStrategy();
for (short i = 0; i < repeat; i++) {
strategy.sendDefaultNotification(builder, extraAction);
}
return this;
}
/**
* Adds a custom notification to the given transaction builder
*
* @param vibrationProfile specifies how and how often the Band shall vibrate.
* @param flashTimes
* @param flashColour
* @param originalColour
* @param flashDuration
* @param extraAction an extra action to be executed after every vibration and flash sequence. Allows to abort the repetition, for example.
* @param builder
*/
private MiBandSupport sendCustomNotification(VibrationProfile vibrationProfile, int flashTimes, int flashColour, int originalColour, long flashDuration, BtLEAction extraAction, TransactionBuilder builder) {
getNotificationStrategy().sendCustomNotification(vibrationProfile, flashTimes, flashColour, originalColour, flashDuration, extraAction, builder);
LOG.info("Sending notification to MiBand");
return this;
}
private NotificationStrategy getNotificationStrategy() {
if (mDeviceInfo == null) {
// not initialized yet?
return new NoNotificationStrategy();
}
if (mDeviceInfo.getFirmwareVersion() < MiBandFWHelper.FW_16779790) {
return new V1NotificationStrategy(this);
} else {
//use the new alert characteristic
return new V2NotificationStrategy(this);
}
}
static final byte[] reboot = new byte[]{MiBandService.COMMAND_REBOOT};
static final byte[] startHeartMeasurementManual = new byte[]{0x15, MiBandService.COMMAND_SET_HR_MANUAL, 1};
static final byte[] stopHeartMeasurementManual = new byte[]{0x15, MiBandService.COMMAND_SET_HR_MANUAL, 0};
static final byte[] startHeartMeasurementContinuous = new byte[]{0x15, MiBandService.COMMAND_SET__HR_CONTINUOUS, 1};
static final byte[] stopHeartMeasurementContinuous = new byte[]{0x15, MiBandService.COMMAND_SET__HR_CONTINUOUS, 0};
static final byte[] startHeartMeasurementSleep = new byte[]{0x15, MiBandService.COMMAND_SET_HR_SLEEP, 1};
static final byte[] stopHeartMeasurementSleep = new byte[]{0x15, MiBandService.COMMAND_SET_HR_SLEEP, 0};
static final byte[] startRealTimeStepsNotifications = new byte[]{MiBandService.COMMAND_SET_REALTIME_STEPS_NOTIFICATION, 1};
static final byte[] stopRealTimeStepsNotifications = new byte[]{MiBandService.COMMAND_SET_REALTIME_STEPS_NOTIFICATION, 0};
/**
* Part of device initialization process. Do not call manually.
*
* @param builder
* @return
*/
private MiBandSupport sendUserInfo(TransactionBuilder builder) {
LOG.debug("Writing User Info!");
// Use a custom action instead of just builder.write() because mDeviceInfo
// is set by handleDeviceInfo *after* this action is created.
builder.add(new BtLEAction(getCharacteristic(MiBandService.UUID_CHARACTERISTIC_USER_INFO)) {
@Override
public boolean expectsResult() {
return true;
}
@Override
public boolean run(BluetoothGatt gatt) {
// at this point, mDeviceInfo should be set
return new WriteAction(getCharacteristic(),
MiBandCoordinator.getAnyUserInfo(getDevice().getAddress()).getData(mDeviceInfo)
).run(gatt);
}
});
return this;
}
private MiBandSupport requestBatteryInfo(TransactionBuilder builder) {
LOG.debug("Requesting Battery Info!");
BluetoothGattCharacteristic characteristic = getCharacteristic(MiBandService.UUID_CHARACTERISTIC_BATTERY);
builder.read(characteristic);
return this;
}
private MiBandSupport requestDeviceInfo(TransactionBuilder builder) {
LOG.debug("Requesting Device Info!");
BluetoothGattCharacteristic deviceInfo = getCharacteristic(MiBandService.UUID_CHARACTERISTIC_DEVICE_INFO);
builder.read(deviceInfo);
BluetoothGattCharacteristic deviceName = getCharacteristic(GattCharacteristic.UUID_CHARACTERISTIC_GAP_DEVICE_NAME);
builder.read(deviceName);
return this;
}
/* private MiBandSupport requestHRInfo(TransactionBuilder builder) {
LOG.debug("Requesting HR Info!");
BluetoothGattCharacteristic HRInfo = getCharacteristic(MiBandService.UUID_CHAR_HEART_RATE_MEASUREMENT);
builder.read(HRInfo);
BluetoothGattCharacteristic HR_Point = getCharacteristic(GattCharacteristic.UUID_CHARACTERISTIC_HEART_RATE_CONTROL_POINT);
builder.read(HR_Point);
return this;
}
*//**
* Part of HR test. Do not call manually.
*
* @param transaction
* @return
*//*
private MiBandSupport heartrate(TransactionBuilder transaction) {
LOG.info("Attempting to read HR ...");
BluetoothGattCharacteristic characteristic = getCharacteristic(MiBandService.UUID_CHAR_HEART_RATE_MEASUREMENT);
if (characteristic != null) {
transaction.write(characteristic, new byte[]{MiBandService.COMMAND_SET__HR_CONTINUOUS});
} else {
LOG.info("Unable to read HR from MI device -- characteristic not available");
}
return this;
}*/
/**
* Part of device initialization process. Do not call manually.
*
* @param transaction
* @return
*/
private MiBandSupport pair(TransactionBuilder transaction) {
LOG.info("Attempting to pair MI device...");
BluetoothGattCharacteristic characteristic = getCharacteristic(MiBandService.UUID_CHARACTERISTIC_PAIR);
if (characteristic != null) {
transaction.write(characteristic, new byte[]{2});
} else {
LOG.info("Unable to pair MI device -- characteristic not available");
}
return this;
}
/**
* Part of device initialization process. Do not call manually.
*
* @param transaction
* @return
*/
private MiBandSupport setFitnessGoal(TransactionBuilder transaction) {
LOG.info("Attempting to set Fitness Goal...");
BluetoothGattCharacteristic characteristic = getCharacteristic(MiBandService.UUID_CHARACTERISTIC_CONTROL_POINT);
if (characteristic != null) {
int fitnessGoal = MiBandCoordinator.getFitnessGoal(getDevice().getAddress());
transaction.write(characteristic, new byte[]{
MiBandService.COMMAND_SET_FITNESS_GOAL,
0,
(byte) (fitnessGoal & 0xff),
(byte) ((fitnessGoal >>> 8) & 0xff)
});
} else {
LOG.info("Unable to set Fitness Goal");
}
return this;
}
/**
* Part of device initialization process. Do not call manually.
*
* @param transaction
* @return
*/
private MiBandSupport setWearLocation(TransactionBuilder transaction) {
LOG.info("Attempting to set wear location...");
BluetoothGattCharacteristic characteristic = getCharacteristic(MiBandService.UUID_CHARACTERISTIC_CONTROL_POINT);
if (characteristic != null) {
transaction.add(new ConditionalWriteAction(characteristic) {
@Override
protected byte[] checkCondition() {
if (getDeviceInfo() != null && getDeviceInfo().isAmazFit()) {
return null;
}
int location = MiBandCoordinator.getWearLocation(getDevice().getAddress());
return new byte[]{
MiBandService.COMMAND_SET_WEAR_LOCATION,
(byte) location
};
}
});
} else {
LOG.info("Unable to set Wear Location");
}
return this;
}
@Override
public void onEnableHeartRateSleepSupport(boolean enable) {
try {
TransactionBuilder builder = performInitialized("enable heart rate sleep support: " + enable);
setHeartrateSleepSupport(builder);
builder.queue(getQueue());
} catch (IOException e) {
GB.toast(getContext(), "Error toggling heart rate sleep support: " + e.getLocalizedMessage(), Toast.LENGTH_LONG, GB.ERROR);
}
}
@Override
public void onAddCalendarEvent(CalendarEventSpec calendarEventSpec) {
// not supported
}
@Override
public void onDeleteCalendarEvent(byte type, long id) {
// not supported
}
/**
* Part of device initialization process. Do not call manually.
*
* @param builder
*/
private MiBandSupport setHeartrateSleepSupport(TransactionBuilder builder) {
BluetoothGattCharacteristic characteristic = getCharacteristic(MiBandService.UUID_CHARACTERISTIC_HEART_RATE_CONTROL_POINT);
if (characteristic != null) {
builder.add(new ConditionalWriteAction(characteristic) {
@Override
protected byte[] checkCondition() {
if (!supportsHeartRate()) {
return null;
}
if (MiBandCoordinator.getHeartrateSleepSupport(getDevice().getAddress())) {
LOG.info("Enabling heartrate sleep support...");
return startHeartMeasurementSleep;
} else {
LOG.info("Disabling heartrate sleep support...");
return stopHeartMeasurementSleep;
}
}
});
}
return this;
}
private void performDefaultNotification(String task, short repeat, BtLEAction extraAction) {
try {
TransactionBuilder builder = performInitialized(task);
sendDefaultNotification(builder, repeat, extraAction);
builder.queue(getQueue());
} catch (IOException ex) {
LOG.error("Unable to send notification to MI device", ex);
}
}
private void performPreferredNotification(String task, String notificationOrigin, BtLEAction extraAction) {
try {
TransactionBuilder builder = performInitialized(task);
Prefs prefs = GBApplication.getPrefs();
int vibrateDuration = getPreferredVibrateDuration(notificationOrigin, prefs);
int vibratePause = getPreferredVibratePause(notificationOrigin, prefs);
short vibrateTimes = getPreferredVibrateCount(notificationOrigin, prefs);
VibrationProfile profile = getPreferredVibrateProfile(notificationOrigin, prefs, vibrateTimes);
int flashTimes = getPreferredFlashCount(notificationOrigin, prefs);
int flashColour = getPreferredFlashColour(notificationOrigin, prefs);
int originalColour = getPreferredOriginalColour(notificationOrigin, prefs);
int flashDuration = getPreferredFlashDuration(notificationOrigin, prefs);
sendCustomNotification(profile, flashTimes, flashColour, originalColour, flashDuration, extraAction, builder);
// sendCustomNotification(vibrateDuration, vibrateTimes, vibratePause, flashTimes, flashColour, originalColour, flashDuration, builder);
builder.queue(getQueue());
} catch (IOException ex) {
LOG.error("Unable to send notification to MI device", ex);
}
}
private int getPreferredFlashDuration(String notificationOrigin, Prefs prefs) {
return getNotificationPrefIntValue(FLASH_DURATION, notificationOrigin, prefs, DEFAULT_VALUE_FLASH_DURATION);
}
private int getPreferredOriginalColour(String notificationOrigin, Prefs prefs) {
return getNotificationPrefIntValue(FLASH_ORIGINAL_COLOUR, notificationOrigin, prefs, DEFAULT_VALUE_FLASH_ORIGINAL_COLOUR);
}
private int getPreferredFlashColour(String notificationOrigin, Prefs prefs) {
return getNotificationPrefIntValue(FLASH_COLOUR, notificationOrigin, prefs, DEFAULT_VALUE_FLASH_COLOUR);
}
private int getPreferredFlashCount(String notificationOrigin, Prefs prefs) {
return getNotificationPrefIntValue(FLASH_COUNT, notificationOrigin, prefs, DEFAULT_VALUE_FLASH_COUNT);
}
private int getPreferredVibratePause(String notificationOrigin, Prefs prefs) {
return getNotificationPrefIntValue(VIBRATION_PAUSE, notificationOrigin, prefs, DEFAULT_VALUE_VIBRATION_PAUSE);
}
private short getPreferredVibrateCount(String notificationOrigin, Prefs prefs) {
return (short) Math.min(Short.MAX_VALUE, getNotificationPrefIntValue(VIBRATION_COUNT, notificationOrigin, prefs, DEFAULT_VALUE_VIBRATION_COUNT));
}
private int getPreferredVibrateDuration(String notificationOrigin, Prefs prefs) {
return getNotificationPrefIntValue(VIBRATION_DURATION, notificationOrigin, prefs, DEFAULT_VALUE_VIBRATION_DURATION);
}
private VibrationProfile getPreferredVibrateProfile(String notificationOrigin, Prefs prefs, short repeat) {
String profileId = getNotificationPrefStringValue(VIBRATION_PROFILE, notificationOrigin, prefs, DEFAULT_VALUE_VIBRATION_PROFILE);
return VibrationProfile.getProfile(profileId, repeat);
}
@Override
public void onSetAlarms(ArrayList<? extends Alarm> alarms) {
try {
BluetoothGattCharacteristic characteristic = getCharacteristic(MiBandService.UUID_CHARACTERISTIC_CONTROL_POINT);
TransactionBuilder builder = performInitialized("Set alarm");
boolean anyAlarmEnabled = false;
for (Alarm alarm : alarms) {
anyAlarmEnabled |= alarm.isEnabled();
queueAlarm(alarm, builder, characteristic);
}
builder.queue(getQueue());
if (anyAlarmEnabled) {
GB.toast(getContext(), getContext().getString(R.string.user_feedback_miband_set_alarms_ok), Toast.LENGTH_SHORT, GB.INFO);
} else {
GB.toast(getContext(), getContext().getString(R.string.user_feedback_all_alarms_disabled), Toast.LENGTH_SHORT, GB.INFO);
}
} catch (IOException ex) {
GB.toast(getContext(), getContext().getString(R.string.user_feedback_miband_set_alarms_failed), Toast.LENGTH_LONG, GB.ERROR, ex);
}
}
@Override
public void onNotification(NotificationSpec notificationSpec) {
// FIXME: these ORIGIN contants do not really make sense anymore
switch (notificationSpec.type) {
case SMS:
performPreferredNotification("sms received", ORIGIN_SMS, null);
break;
case EMAIL:
performPreferredNotification("email received", ORIGIN_K9MAIL, null);
break;
case CHAT:
performPreferredNotification("chat message received", ORIGIN_PEBBLEMSG, null);
break;
default:
performPreferredNotification("generic notification received", ORIGIN_GENERIC, null);
}
}
@Override
public void onSetTime() {
try {
TransactionBuilder builder = performInitialized("Set date and time");
setCurrentTime(builder);
builder.queue(getQueue());
} catch (IOException ex) {
LOG.error("Unable to set time on MI device", ex);
}
//TODO: once we have a common strategy for sending events (e.g. EventHandler), remove this call from here. Meanwhile it does no harm.
sendCalendarEvents();
}
/**
* Sets the current time to the Mi device using the given builder.
*
* @param builder
*/
private MiBandSupport setCurrentTime(TransactionBuilder builder) {
Calendar now = GregorianCalendar.getInstance();
Date date = now.getTime();
LOG.info("Sending current time to Mi Band: " + DateTimeUtils.formatDate(date) + " (" + date.toGMTString() + ")");
byte[] nowBytes = MiBandDateConverter.calendarToRawBytes(now);
byte[] time = new byte[]{
nowBytes[0],
nowBytes[1],
nowBytes[2],
nowBytes[3],
nowBytes[4],
nowBytes[5],
(byte) 0x0f,
(byte) 0x0f,
(byte) 0x0f,
(byte) 0x0f,
(byte) 0x0f,
(byte) 0x0f
};
BluetoothGattCharacteristic characteristic = getCharacteristic(MiBandService.UUID_CHARACTERISTIC_DATE_TIME);
if (characteristic != null) {
builder.write(characteristic, time);
} else {
LOG.info("Unable to set time -- characteristic not available");
}
return this;
}
@Override
public void onSetCallState(CallSpec callSpec) {
if (callSpec.command == CallSpec.CALL_INCOMING) {
telephoneRinging = true;
AbortTransactionAction abortAction = new AbortTransactionAction() {
@Override
protected boolean shouldAbort() {
return !isTelephoneRinging();
}
};
performPreferredNotification("incoming call", MiBandConst.ORIGIN_INCOMING_CALL, abortAction);
} else if ((callSpec.command == CallSpec.CALL_START) || (callSpec.command == CallSpec.CALL_END)) {
telephoneRinging = false;
}
}
@Override
public void onSetCannedMessages(CannedMessagesSpec cannedMessagesSpec) {
}
private boolean isTelephoneRinging() {
// don't synchronize, this is not really important
return telephoneRinging;
}
@Override
public void onSetMusicState(MusicStateSpec stateSpec) {
// not supported
}
@Override
public void onSetMusicInfo(MusicSpec musicSpec) {
// not supported
}
@Override
public void onReboot() {
try {
TransactionBuilder builder = performInitialized("Reboot");
builder.write(getCharacteristic(MiBandService.UUID_CHARACTERISTIC_CONTROL_POINT), reboot);
builder.queue(getQueue());
} catch (IOException ex) {
LOG.error("Unable to reboot MI", ex);
}
}
@Override
public void onHeartRateTest() {
if (supportsHeartRate()) {
try {
TransactionBuilder builder = performInitialized("HeartRateTest");
builder.write(getCharacteristic(MiBandService.UUID_CHARACTERISTIC_HEART_RATE_CONTROL_POINT), stopHeartMeasurementContinuous);
builder.write(getCharacteristic(MiBandService.UUID_CHARACTERISTIC_HEART_RATE_CONTROL_POINT), stopHeartMeasurementManual);
builder.write(getCharacteristic(MiBandService.UUID_CHARACTERISTIC_HEART_RATE_CONTROL_POINT), startHeartMeasurementManual);
builder.queue(getQueue());
} catch (IOException ex) {
LOG.error("Unable to read HearRate in MI1S", ex);
}
} else {
GB.toast(getContext(), "Heart rate is not supported on this device", Toast.LENGTH_LONG, GB.ERROR);
}
}
@Override
public void onEnableRealtimeHeartRateMeasurement(boolean enable) {
if (supportsHeartRate()) {
try {
TransactionBuilder builder = performInitialized("EnableRealtimeHeartRateMeasurement");
if (enable) {
builder.write(getCharacteristic(MiBandService.UUID_CHARACTERISTIC_HEART_RATE_CONTROL_POINT), stopHeartMeasurementManual);
builder.write(getCharacteristic(MiBandService.UUID_CHARACTERISTIC_HEART_RATE_CONTROL_POINT), startHeartMeasurementContinuous);
} else {
builder.write(getCharacteristic(MiBandService.UUID_CHARACTERISTIC_HEART_RATE_CONTROL_POINT), stopHeartMeasurementContinuous);
}
builder.queue(getQueue());
} catch (IOException ex) {
LOG.error("Unable to enable realtime heart rate measurement in MI1S", ex);
}
}
}
public boolean supportsHeartRate() {
return getDeviceInfo() != null && getDeviceInfo().supportsHeartrate();
}
@Override
public void onFindDevice(boolean start) {
isLocatingDevice = start;
if (start) {
AbortTransactionAction abortAction = new AbortTransactionAction() {
@Override
protected boolean shouldAbort() {
return !isLocatingDevice;
}
};
performDefaultNotification("locating device", (short) 255, abortAction);
}
}
@Override
public void onFetchActivityData() {
try {
new FetchActivityOperation(this).perform();
} catch (IOException ex) {
LOG.error("Unable to fetch MI activity data", ex);
}
}
@Override
public void onEnableRealtimeSteps(boolean enable) {
try {
BluetoothGattCharacteristic controlPoint = getCharacteristic(MiBandService.UUID_CHARACTERISTIC_CONTROL_POINT);
if (enable) {
TransactionBuilder builder = performInitialized("Read realtime steps");
builder.read(getCharacteristic(MiBandService.UUID_CHARACTERISTIC_REALTIME_STEPS)).queue(getQueue());
}
performInitialized(enable ? "Enabling realtime steps notifications" : "Disabling realtime steps notifications")
.write(getCharacteristic(MiBandService.UUID_CHARACTERISTIC_LE_PARAMS), enable ? getLowLatency() : getHighLatency())
.write(controlPoint, enable ? startRealTimeStepsNotifications : stopRealTimeStepsNotifications).queue(getQueue());
} catch (IOException e) {
LOG.error("Unable to change realtime steps notification to: " + enable, e);
}
}
private byte[] getHighLatency() {
int minConnectionInterval = 460;
int maxConnectionInterval = 500;
int latency = 0;
int timeout = 500;
int advertisementInterval = 0;
return getLatency(minConnectionInterval, maxConnectionInterval, latency, timeout, advertisementInterval);
}
private byte[] getLatency(int minConnectionInterval, int maxConnectionInterval, int latency, int timeout, int advertisementInterval) {
byte result[] = new byte[12];
result[0] = (byte) (minConnectionInterval & 0xff);
result[1] = (byte) (0xff & minConnectionInterval >> 8);
result[2] = (byte) (maxConnectionInterval & 0xff);
result[3] = (byte) (0xff & maxConnectionInterval >> 8);
result[4] = (byte) (latency & 0xff);
result[5] = (byte) (0xff & latency >> 8);
result[6] = (byte) (timeout & 0xff);
result[7] = (byte) (0xff & timeout >> 8);
result[8] = 0;
result[9] = 0;
result[10] = (byte) (advertisementInterval & 0xff);
result[11] = (byte) (0xff & advertisementInterval >> 8);
return result;
}
private byte[] getLowLatency() {
int minConnectionInterval = 39;
int maxConnectionInterval = 49;
int latency = 0;
int timeout = 500;
int advertisementInterval = 0;
return getLatency(minConnectionInterval, maxConnectionInterval, latency, timeout, advertisementInterval);
}
@Override
public void onInstallApp(Uri uri) {
try {
new UpdateFirmwareOperation(uri, this).perform();
} catch (IOException ex) {
GB.toast(getContext(), "Firmware cannot be installed: " + ex.getMessage(), Toast.LENGTH_LONG, GB.ERROR, ex);
}
}
@Override
public void onAppInfoReq() {
// not supported
}
@Override
public void onAppStart(UUID uuid, boolean start) {
// not supported
}
@Override
public void onAppDelete(UUID uuid) {
// not supported
}
@Override
public void onAppConfiguration(UUID uuid, String config) {
// not supported
}
@Override
public void onAppReorder(UUID[] uuids) {
// not supported
}
@Override
public void onScreenshotReq() {
// not supported
}
@Override
public void onCharacteristicChanged(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic) {
super.onCharacteristicChanged(gatt, characteristic);
UUID characteristicUUID = characteristic.getUuid();
if (MiBandService.UUID_CHARACTERISTIC_BATTERY.equals(characteristicUUID)) {
handleBatteryInfo(characteristic.getValue(), BluetoothGatt.GATT_SUCCESS);
} else if (MiBandService.UUID_CHARACTERISTIC_NOTIFICATION.equals(characteristicUUID)) {
handleNotificationNotif(characteristic.getValue());
} else if (MiBandService.UUID_CHARACTERISTIC_REALTIME_STEPS.equals(characteristicUUID)) {
handleRealtimeSteps(characteristic.getValue());
} else if (MiBandService.UUID_CHARACTERISTIC_REALTIME_STEPS.equals(characteristicUUID)) {
handleRealtimeSteps(characteristic.getValue());
} else if (MiBandService.UUID_CHARACTERISTIC_HEART_RATE_MEASUREMENT.equals(characteristicUUID)) {
handleHeartrate(characteristic.getValue());
} else {
LOG.info("Unhandled characteristic changed: " + characteristicUUID);
logMessageContent(characteristic.getValue());
}
}
@Override
public void onCharacteristicRead(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic, int status) {
super.onCharacteristicRead(gatt, characteristic, status);
UUID characteristicUUID = characteristic.getUuid();
if (MiBandService.UUID_CHARACTERISTIC_DEVICE_INFO.equals(characteristicUUID)) {
handleDeviceInfo(characteristic.getValue(), status);
} else if (GattCharacteristic.UUID_CHARACTERISTIC_GAP_DEVICE_NAME.equals(characteristicUUID)) {
handleDeviceName(characteristic.getValue(), status);
} else if (MiBandService.UUID_CHARACTERISTIC_BATTERY.equals(characteristicUUID)) {
handleBatteryInfo(characteristic.getValue(), status);
} else if (MiBandService.UUID_CHARACTERISTIC_HEART_RATE_MEASUREMENT.equals(characteristicUUID)) {
logHeartrate(characteristic.getValue());
} else if (MiBandService.UUID_CHARACTERISTIC_DATE_TIME.equals(characteristicUUID)) {
logDate(characteristic.getValue());
} else {
LOG.info("Unhandled characteristic read: " + characteristicUUID);
logMessageContent(characteristic.getValue());
}
}
@Override
public void onCharacteristicWrite(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic, int status) {
UUID characteristicUUID = characteristic.getUuid();
if (MiBandService.UUID_CHARACTERISTIC_PAIR.equals(characteristicUUID)) {
handlePairResult(characteristic.getValue(), status);
} else if (MiBandService.UUID_CHARACTERISTIC_USER_INFO.equals(characteristicUUID)) {
handleUserInfoResult(characteristic.getValue(), status);
} else if (MiBandService.UUID_CHARACTERISTIC_CONTROL_POINT.equals(characteristicUUID)) {
handleControlPointResult(characteristic.getValue(), status);
}
}
/**
* Utility method that may be used to log incoming messages when we don't know how to deal with them yet.
*
* @param value
*/
public void logMessageContent(byte[] value) {
LOG.info("RECEIVED DATA WITH LENGTH: " + value.length);
for (byte b : value) {
LOG.warn("DATA: " + String.format("0x%2x", b));
}
}
public void logDate(byte[] value) {
GregorianCalendar calendar = MiBandDateConverter.rawBytesToCalendar(value);
LOG.info("Got Mi Band Date: " + DateTimeUtils.formatDateTime(calendar.getTime()));
}
public void logHeartrate(byte[] value) {
LOG.info("Got heartrate:");
if (value.length == 2 && value[0] == 6) {
int hrValue = (value[1] & 0xff);
GB.toast(getContext(), "Heart Rate measured: " + hrValue, Toast.LENGTH_LONG, GB.INFO);
} else {
logMessageContent(value);
}
}
private void handleHeartrate(byte[] value) {
if (value.length == 2 && value[0] == 6) {
int hrValue = (value[1] & 0xff);
if (LOG.isDebugEnabled()) {
LOG.debug("heart rate: " + hrValue);
}
Intent intent = new Intent(DeviceService.ACTION_HEARTRATE_MEASUREMENT)
.putExtra(DeviceService.EXTRA_HEART_RATE_VALUE, hrValue)
.putExtra(DeviceService.EXTRA_TIMESTAMP, System.currentTimeMillis());
LocalBroadcastManager.getInstance(getContext()).sendBroadcast(intent);
}
}
private void handleRealtimeSteps(byte[] value) {
int steps = 0xff & value[0] | (0xff & value[1]) << 8;
if (LOG.isDebugEnabled()) {
LOG.debug("realtime steps: " + steps);
}
Intent intent = new Intent(DeviceService.ACTION_REALTIME_STEPS)
.putExtra(DeviceService.EXTRA_REALTIME_STEPS, steps)
.putExtra(DeviceService.EXTRA_TIMESTAMP, System.currentTimeMillis());
LocalBroadcastManager.getInstance(getContext()).sendBroadcast(intent);
}
/**
* React to unsolicited messages sent by the Mi Band to the MiBandService.UUID_CHARACTERISTIC_NOTIFICATION
* characteristic,
* These messages appear to be always 1 byte long, with values that are listed in MiBandService.
* It is not excluded that there are further values which are still unknown.
* <p/>
* Upon receiving known values that request further action by GB, the appropriate method is called.
*
* @param value
*/
private void handleNotificationNotif(byte[] value) {
if (value.length != 1) {
LOG.error("Notifications should be 1 byte long.");
LOG.info("RECEIVED DATA WITH LENGTH: " + value.length);
for (byte b : value) {
LOG.warn("DATA: " + String.format("0x%2x", b));
}
return;
}
switch (value[0]) {
case MiBandService.NOTIFY_AUTHENTICATION_FAILED:
// we get first FAILED, then NOTIFY_STATUS_MOTOR_AUTH (0x13)
// which means, we need to authenticate by tapping
getDevice().setState(State.AUTHENTICATION_REQUIRED);
getDevice().sendDeviceUpdateIntent(getContext());
GB.toast(getContext(), "Band needs pairing", Toast.LENGTH_LONG, GB.ERROR);
break;
case MiBandService.NOTIFY_AUTHENTICATION_SUCCESS: // fall through -- not sure which one we get
case MiBandService.NOTIFY_RESET_AUTHENTICATION_SUCCESS: // for Mi 1A
case MiBandService.NOTIFY_STATUS_MOTOR_AUTH_SUCCESS:
LOG.info("Band successfully authenticated");
// maybe we can perform the rest of the initialization from here
doInitialize();
break;
case MiBandService.NOTIFY_STATUS_MOTOR_AUTH:
LOG.info("Band needs authentication (MOTOR_AUTH)");
getDevice().setState(State.AUTHENTICATING);
getDevice().sendDeviceUpdateIntent(getContext());
break;
default:
for (byte b : value) {
LOG.warn("DATA: " + String.format("0x%2x", b));
}
}
}
private void doInitialize() {
try {
TransactionBuilder builder = performInitialized("just initializing after authentication");
builder.queue(getQueue());
} catch (IOException ex) {
LOG.error("Unable to initialize device after authentication", ex);
}
}
private void handleDeviceInfo(byte[] value, int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
mDeviceInfo = new DeviceInfo(value);
mDeviceInfo.setTest1AHRMode(MI_1A_HR_FW_UPDATE_TEST_MODE_ENABLED);
if (getDeviceInfo().supportsHeartrate()) {
getDevice().addDeviceInfo(new GenericItem(
getContext().getString(R.string.DEVINFO_HR_VER),
MiBandFWHelper.formatFirmwareVersion(mDeviceInfo.getHeartrateFirmwareVersion())));
}
LOG.warn("Device info: " + mDeviceInfo);
versionCmd.hwVersion = mDeviceInfo.getHwVersion();
versionCmd.fwVersion = MiBandFWHelper.formatFirmwareVersion(mDeviceInfo.getFirmwareVersion());
handleGBDeviceEvent(versionCmd);
}
}
private void handleDeviceName(byte[] value, int status) {
// if (status == BluetoothGatt.GATT_SUCCESS) {
// versionCmd.hwVersion = new String(value);
// handleGBDeviceEvent(versionCmd);
// }
}
/**
* Convert an alarm from the GB internal structure to a Mi Band message and put on the specified
* builder queue as a write message for the passed characteristic
*
* @param alarm
* @param builder
* @param characteristic
*/
private void queueAlarm(Alarm alarm, TransactionBuilder builder, BluetoothGattCharacteristic characteristic) {
byte[] alarmCalBytes = MiBandDateConverter.calendarToRawBytes(alarm.getAlarmCal());
byte[] alarmMessage = new byte[]{
MiBandService.COMMAND_SET_TIMER,
(byte) alarm.getIndex(),
(byte) (alarm.isEnabled() ? 1 : 0),
alarmCalBytes[0],
alarmCalBytes[1],
alarmCalBytes[2],
alarmCalBytes[3],
alarmCalBytes[4],
alarmCalBytes[5],
(byte) (alarm.isSmartWakeup() ? 30 : 0),
(byte) alarm.getRepetitionMask()
};
builder.write(characteristic, alarmMessage);
}
private void handleControlPointResult(byte[] value, int status) {
if (status != BluetoothGatt.GATT_SUCCESS) {
LOG.warn("Could not write to the control point.");
}
LOG.info("handleControlPoint write status:" + status + "; length: " + (value != null ? value.length : "(null)"));
if (value != null) {
for (byte b : value) {
LOG.info("handleControlPoint WROTE DATA:" + String.format("0x%8x", b));
}
} else {
LOG.warn("handleControlPoint WROTE null");
}
}
private void handleBatteryInfo(byte[] value, int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
BatteryInfo info = new BatteryInfo(value);
batteryCmd.level = ((short) info.getLevelInPercent());
batteryCmd.state = info.getState();
batteryCmd.lastChargeTime = info.getLastChargeTime();
batteryCmd.numCharges = info.getNumCharges();
handleGBDeviceEvent(batteryCmd);
}
}
private void handleUserInfoResult(byte[] value, int status) {
// successfully transferred user info means we're initialized
// commented out, because we have SetDeviceStateAction which sets initialized
// state on every successful initialization.
// if (status == BluetoothGatt.GATT_SUCCESS) {
// setConnectionState(State.INITIALIZED);
// }
}
private void setConnectionState(State newState) {
getDevice().setState(newState);
getDevice().sendDeviceUpdateIntent(getContext());
}
private void handlePairResult(byte[] pairResult, int status) {
if (status != BluetoothGatt.GATT_SUCCESS) {
LOG.info("Pairing MI device failed: " + status);
return;
}
String value = null;
if (pairResult != null) {
if (pairResult.length == 1) {
try {
if (pairResult[0] == 2) {
LOG.info("Successfully paired MI device");
return;
}
} catch (Exception ex) {
LOG.warn("Error identifying pairing result", ex);
return;
}
}
value = Arrays.toString(pairResult);
}
LOG.info("MI Band pairing result: " + value);
}
/**
* Fetch the events from the android device calendars and set the alarms on the miband.
*/
private void sendCalendarEvents() {
try {
TransactionBuilder builder = performInitialized("Send upcoming events");
BluetoothGattCharacteristic characteristic = getCharacteristic(MiBandService.UUID_CHARACTERISTIC_CONTROL_POINT);
Prefs prefs = GBApplication.getPrefs();
int availableSlots = prefs.getInt(MiBandConst.PREF_MIBAND_RESERVE_ALARM_FOR_CALENDAR, 0);
if (availableSlots > 0) {
CalendarEvents upcomingEvents = new CalendarEvents();
List<CalendarEvents.CalendarEvent> mEvents = upcomingEvents.getCalendarEventList(getContext());
int iteration = 0;
for (CalendarEvents.CalendarEvent mEvt : mEvents) {
if (iteration >= availableSlots || iteration > 2) {
break;
}
int slotToUse = 2 - iteration;
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(mEvt.getBegin());
byte[] calBytes = MiBandDateConverter.calendarToRawBytes(calendar);
byte[] alarmMessage = new byte[]{
MiBandService.COMMAND_SET_TIMER,
(byte) slotToUse,
(byte) 1,
calBytes[0],
calBytes[1],
calBytes[2],
calBytes[3],
calBytes[4],
calBytes[5],
(byte) 0,
(byte) 0
};
builder.write(characteristic, alarmMessage);
iteration++;
}
builder.queue(getQueue());
}
} catch (IOException ex) {
LOG.error("Unable to send Events to MI device", ex);
}
}
}
| Avoid potential NPEs
| app/src/main/java/nodomain/freeyourgadget/gadgetbridge/service/devices/miband/MiBandSupport.java | Avoid potential NPEs | <ide><path>pp/src/main/java/nodomain/freeyourgadget/gadgetbridge/service/devices/miband/MiBandSupport.java
<ide> } else if (MiBandService.UUID_CHARACTERISTIC_BATTERY.equals(characteristicUUID)) {
<ide> handleBatteryInfo(characteristic.getValue(), status);
<ide> } else if (MiBandService.UUID_CHARACTERISTIC_HEART_RATE_MEASUREMENT.equals(characteristicUUID)) {
<del> logHeartrate(characteristic.getValue());
<add> logHeartrate(characteristic.getValue(), status);
<ide> } else if (MiBandService.UUID_CHARACTERISTIC_DATE_TIME.equals(characteristicUUID)) {
<del> logDate(characteristic.getValue());
<add> logDate(characteristic.getValue(), status);
<ide> } else {
<ide> LOG.info("Unhandled characteristic read: " + characteristicUUID);
<ide> logMessageContent(characteristic.getValue());
<ide> * @param value
<ide> */
<ide> public void logMessageContent(byte[] value) {
<del> LOG.info("RECEIVED DATA WITH LENGTH: " + value.length);
<del> for (byte b : value) {
<del> LOG.warn("DATA: " + String.format("0x%2x", b));
<del> }
<del> }
<del>
<del> public void logDate(byte[] value) {
<del> GregorianCalendar calendar = MiBandDateConverter.rawBytesToCalendar(value);
<del> LOG.info("Got Mi Band Date: " + DateTimeUtils.formatDateTime(calendar.getTime()));
<del> }
<del>
<del> public void logHeartrate(byte[] value) {
<del> LOG.info("Got heartrate:");
<del> if (value.length == 2 && value[0] == 6) {
<del> int hrValue = (value[1] & 0xff);
<del> GB.toast(getContext(), "Heart Rate measured: " + hrValue, Toast.LENGTH_LONG, GB.INFO);
<add> LOG.info("RECEIVED DATA WITH LENGTH: " + ((value != null) ? value.length : "(null)"));
<add> if (value != null) {
<add> for (byte b : value) {
<add> LOG.warn("DATA: " + String.format("0x%2x", b));
<add> }
<add> }
<add> }
<add>
<add> public void logDate(byte[] value, int status) {
<add> if (status == BluetoothGatt.GATT_SUCCESS) {
<add> GregorianCalendar calendar = MiBandDateConverter.rawBytesToCalendar(value);
<add> LOG.info("Got Mi Band Date: " + DateTimeUtils.formatDateTime(calendar.getTime()));
<ide> } else {
<ide> logMessageContent(value);
<ide> }
<add> }
<add>
<add> public void logHeartrate(byte[] value, int status) {
<add> if (status == BluetoothGatt.GATT_SUCCESS && value != null) {
<add> LOG.info("Got heartrate:");
<add> if (value.length == 2 && value[0] == 6) {
<add> int hrValue = (value[1] & 0xff);
<add> GB.toast(getContext(), "Heart Rate measured: " + hrValue, Toast.LENGTH_LONG, GB.INFO);
<add> }
<add> return;
<add> }
<add> logMessageContent(value);
<ide> }
<ide>
<ide> private void handleHeartrate(byte[] value) { |
|
Java | apache-2.0 | fa60c612718491c983026c4f4540c266edc6799b | 0 | CycloneAxe/phphub-android,CycloneAxe/phphub-android | package org.estgroup.phphub.ui.view;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.widget.TextView;
import android.widget.Toast;
import com.levelmoney.velodrome.Velodrome;
import com.levelmoney.velodrome.annotations.OnActivityResult;
import com.orhanobut.logger.Logger;
import org.estgroup.phphub.R;
import org.estgroup.phphub.api.entity.UserEntity;
import org.estgroup.phphub.api.entity.element.Token;
import org.estgroup.phphub.api.entity.element.User;
import org.estgroup.phphub.common.App;
import org.estgroup.phphub.common.Navigator;
import org.estgroup.phphub.common.service.NotificationService;
import org.estgroup.phphub.model.TokenModel;
import org.estgroup.phphub.model.UserModel;
import java.util.Set;
import javax.inject.Inject;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import eu.unicate.retroauth.AuthenticationActivity;
import rx.Observable;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.functions.Action1;
import rx.functions.Func1;
import static org.estgroup.phphub.common.Constant.LOGIN_TOKEN_KEY;
import static org.estgroup.phphub.common.Constant.USERNAME_KEY;
import static org.estgroup.phphub.common.Constant.USER_AVATAR_KEY;
import static org.estgroup.phphub.common.Constant.USER_ID_KEY;
import static org.estgroup.phphub.common.Constant.USER_SIGNATURE;
import static org.estgroup.phphub.common.Constant.USER_REPLY_URL_KEY;
import static org.estgroup.phphub.common.qualifier.AuthType.AUTH_TYPE_GUEST;
import static org.estgroup.phphub.common.qualifier.AuthType.AUTH_TYPE_REFRESH;
public class LoginActivity extends AuthenticationActivity {
private final static int CODE_SCANNER = 100;
@Bind(R.id.toolbar)
Toolbar toolbarView;
@Bind(R.id.toolbar_title)
TextView toolbarTitleView;
@Inject
Navigator navigator;
@Inject
TokenModel tokenModel;
@Inject
UserModel userModel;
@Inject
AccountManager accountManager;
Subscription subscription;
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.login);
ButterKnife.bind(this);
initializeToolbar();
((App) getApplication()).getApiComponent().inject(this);
if (accountManager.getAccountsByType(getString(R.string.auth_account_type)).length > 0) {
Toast.makeText(this, "只能有一个账号", Toast.LENGTH_SHORT).show();
finish();
return;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Velodrome.handleResult(this, requestCode, resultCode, data);
}
protected void initializeToolbar() {
setSupportActionBar(toolbarView);
getSupportActionBar().setDisplayShowTitleEnabled(false);
toolbarTitleView.setText(R.string.please_login);
}
public static Intent getCallingIntent(Context context) {
return new Intent(context, LoginActivity.class);
}
@OnClick(R.id.btn_login_guide)
public void loginGuide() {
Uri uri = Uri.parse("http://7xnqwn.com1.z0.glb.clouddn.com/index.html");
Intent intent = new Intent();
intent.setAction("android.intent.action.VIEW");
intent.setData(uri);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
} else {
startActivity(Intent.createChooser(intent, "请选择浏览器"));
}
}
@OnClick(R.id.btn_scanner)
public void navigateToScanner() {
navigator.navigateToScanner(this, CODE_SCANNER);
}
@OnActivityResult(CODE_SCANNER)
public void onScanner(Intent data) {
final String username = data.getStringExtra(USERNAME_KEY),
loginToken = data.getStringExtra(LOGIN_TOKEN_KEY);
if (TextUtils.isEmpty(username) || TextUtils.isEmpty(loginToken)) {
Toast.makeText(this, "用户名或密码错误", Toast.LENGTH_SHORT).show();
return;
}
final ProgressDialog dialog = new ProgressDialog(this);
dialog.setMessage("登陆中");
dialog.setCancelable(false);
final Account account = createOrGetAccount(username);
subscription = tokenModel.tokenGenerator(username, loginToken)
.doOnSubscribe(new Action0() {
@Override
public void call() {
dialog.show();
}
})
.doOnNext(new Action1<Token>() {
@Override
public void call(Token token) {
}
})
.flatMap(new Func1<Token, Observable<User>>() {
@Override
public Observable<User> call(final Token token) {
return ((UserModel) userModel.once()
.setToken(token.getToken()))
.getMyselfInfo()
.map(new Func1<UserEntity.AUser, User>() {
@Override
public User call(UserEntity.AUser user) {
return user.getData();
}
})
.doOnNext(new Action1<User>() {
@Override
public void call(User user) {
storeToken(account, getString(R.string.auth_token_type), token.getToken());
storeUserData(account, AUTH_TYPE_REFRESH, token.getRefreshToken());
storeUserData(account, USER_ID_KEY, String.valueOf(user.getId()));
storeUserData(account, USERNAME_KEY, user.getName());
storeUserData(account, USER_SIGNATURE, user.getSignature());
storeUserData(account, USER_AVATAR_KEY, user.getAvatar());
storeUserData(account, USER_REPLY_URL_KEY, user.getLinks().getRepliesWebView());
JPushInterface.setAlias(getApplicationContext(), "userid_" + user.getId(), new TagAliasCallback() {
@Override
public void gotResult(int i, String s, Set<String> set) {
}
});
}
});
}
})
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<User>() {
@Override
public void call(User user) {
dialog.dismiss();
startService(new Intent(LoginActivity.this, NotificationService.class));
finalizeAuthentication(account);
}
},
new Action1<Throwable>() {
@Override
public void call(Throwable throwable) {
dialog.dismiss();
Toast.makeText(LoginActivity.this, throwable.getMessage(), Toast.LENGTH_SHORT).show();
Logger.e(throwable.toString());
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
if (subscription != null && !subscription.isUnsubscribed()) {
subscription.unsubscribe();
}
}
} | app/src/main/java/org/estgroup/phphub/ui/view/LoginActivity.java | package org.estgroup.phphub.ui.view;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.widget.TextView;
import android.widget.Toast;
import com.levelmoney.velodrome.Velodrome;
import com.levelmoney.velodrome.annotations.OnActivityResult;
import com.orhanobut.logger.Logger;
import org.estgroup.phphub.R;
import org.estgroup.phphub.api.entity.UserEntity;
import org.estgroup.phphub.api.entity.element.Token;
import org.estgroup.phphub.api.entity.element.User;
import org.estgroup.phphub.common.App;
import org.estgroup.phphub.common.Navigator;
import org.estgroup.phphub.common.service.NotificationService;
import org.estgroup.phphub.model.TokenModel;
import org.estgroup.phphub.model.UserModel;
import java.util.Set;
import javax.inject.Inject;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import eu.unicate.retroauth.AuthenticationActivity;
import rx.Observable;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.functions.Action1;
import rx.functions.Func1;
import static org.estgroup.phphub.common.Constant.LOGIN_TOKEN_KEY;
import static org.estgroup.phphub.common.Constant.USERNAME_KEY;
import static org.estgroup.phphub.common.Constant.USER_AVATAR_KEY;
import static org.estgroup.phphub.common.Constant.USER_ID_KEY;
import static org.estgroup.phphub.common.Constant.USER_SIGNATURE;
import static org.estgroup.phphub.common.Constant.USER_REPLY_URL_KEY;
import static org.estgroup.phphub.common.qualifier.AuthType.AUTH_TYPE_GUEST;
import static org.estgroup.phphub.common.qualifier.AuthType.AUTH_TYPE_REFRESH;
public class LoginActivity extends AuthenticationActivity {
private final static int CODE_SCANNER = 100;
@Bind(R.id.toolbar)
Toolbar toolbarView;
@Bind(R.id.toolbar_title)
TextView toolbarTitleView;
@Inject
Navigator navigator;
@Inject
TokenModel tokenModel;
@Inject
UserModel userModel;
@Inject
AccountManager accountManager;
Subscription subscription;
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.login);
ButterKnife.bind(this);
initializeToolbar();
((App) getApplication()).getApiComponent().inject(this);
if (accountManager.getAccountsByType(getString(R.string.auth_account_type)).length > 0) {
Toast.makeText(this, "只能有一个账号", Toast.LENGTH_SHORT).show();
finish();
return;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Velodrome.handleResult(this, requestCode, resultCode, data);
}
protected void initializeToolbar() {
setSupportActionBar(toolbarView);
getSupportActionBar().setDisplayShowTitleEnabled(false);
toolbarTitleView.setText(R.string.please_login);
}
public static Intent getCallingIntent(Context context) {
return new Intent(context, LoginActivity.class);
}
@OnClick(R.id.btn_login_guide)
public void loginGuide() {
Uri uri = Uri.parse("https://phphub.org/helps/qr-login-guide");
Intent intent = new Intent();
intent.setAction("android.intent.action.VIEW");
intent.setData(uri);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
} else {
startActivity(Intent.createChooser(intent, "请选择浏览器"));
}
}
@OnClick(R.id.btn_scanner)
public void navigateToScanner() {
navigator.navigateToScanner(this, CODE_SCANNER);
}
@OnActivityResult(CODE_SCANNER)
public void onScanner(Intent data) {
final String username = data.getStringExtra(USERNAME_KEY),
loginToken = data.getStringExtra(LOGIN_TOKEN_KEY);
if (TextUtils.isEmpty(username) || TextUtils.isEmpty(loginToken)) {
Toast.makeText(this, "用户名或密码错误", Toast.LENGTH_SHORT).show();
return;
}
final ProgressDialog dialog = new ProgressDialog(this);
dialog.setMessage("登陆中");
dialog.setCancelable(false);
final Account account = createOrGetAccount(username);
subscription = tokenModel.tokenGenerator(username, loginToken)
.doOnSubscribe(new Action0() {
@Override
public void call() {
dialog.show();
}
})
.doOnNext(new Action1<Token>() {
@Override
public void call(Token token) {
}
})
.flatMap(new Func1<Token, Observable<User>>() {
@Override
public Observable<User> call(final Token token) {
return ((UserModel) userModel.once()
.setToken(token.getToken()))
.getMyselfInfo()
.map(new Func1<UserEntity.AUser, User>() {
@Override
public User call(UserEntity.AUser user) {
return user.getData();
}
})
.doOnNext(new Action1<User>() {
@Override
public void call(User user) {
storeToken(account, getString(R.string.auth_token_type), token.getToken());
storeUserData(account, AUTH_TYPE_REFRESH, token.getRefreshToken());
storeUserData(account, USER_ID_KEY, String.valueOf(user.getId()));
storeUserData(account, USERNAME_KEY, user.getName());
storeUserData(account, USER_SIGNATURE, user.getSignature());
storeUserData(account, USER_AVATAR_KEY, user.getAvatar());
storeUserData(account, USER_REPLY_URL_KEY, user.getLinks().getRepliesWebView());
JPushInterface.setAlias(getApplicationContext(), "userid_" + user.getId(), new TagAliasCallback() {
@Override
public void gotResult(int i, String s, Set<String> set) {
}
});
}
});
}
})
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<User>() {
@Override
public void call(User user) {
dialog.dismiss();
startService(new Intent(LoginActivity.this, NotificationService.class));
finalizeAuthentication(account);
}
},
new Action1<Throwable>() {
@Override
public void call(Throwable throwable) {
dialog.dismiss();
Toast.makeText(LoginActivity.this, throwable.getMessage(), Toast.LENGTH_SHORT).show();
Logger.e(throwable.toString());
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
if (subscription != null && !subscription.isUnsubscribed()) {
subscription.unsubscribe();
}
}
} | change btn_login_guide uri
| app/src/main/java/org/estgroup/phphub/ui/view/LoginActivity.java | change btn_login_guide uri | <ide><path>pp/src/main/java/org/estgroup/phphub/ui/view/LoginActivity.java
<ide>
<ide> @OnClick(R.id.btn_login_guide)
<ide> public void loginGuide() {
<del> Uri uri = Uri.parse("https://phphub.org/helps/qr-login-guide");
<add> Uri uri = Uri.parse("http://7xnqwn.com1.z0.glb.clouddn.com/index.html");
<ide> Intent intent = new Intent();
<ide> intent.setAction("android.intent.action.VIEW");
<ide> intent.setData(uri); |
|
Java | apache-2.0 | b3906f1c20414729693b347c254868c93eedf8e3 | 0 | gokhanakgul/vertx-swagger,phiz71/vertx-swagger,gokhanakgul/vertx-swagger,phiz71/vertx-swagger,gokhanakgul/vertx-swagger,phiz71/vertx-swagger | package io.vertx.ext.swagger.codegen;
import org.junit.Test;
import io.swagger.codegen.SwaggerCodegen;
public class SampleVertXGeneratorTest {
@Test
public void generateSampleServer() {
String[] args = new String[11];
args[0] = "generate";
args[1] = "-l";
args[2] = "java-vertx";
args[3] = "-i";
args[4] = "petstore.json";
args[5] = "-o";
args[6] = "../../sample/petstore-vertx-server";
args[7] = "--group-id";
args[8] = "io.swagger";
args[9] = "--artifact-id";
args[10] = "petstore-vertx-server";
SwaggerCodegen.main(args);
}
}
| modules/vertx-swagger-codegen/src/test/java/io/vertx/ext/swagger/codegen/SampleVertXGeneratorTest.java | package io.vertx.ext.swagger.codegen;
import org.junit.Test;
import io.swagger.codegen.SwaggerCodegen;
public class SampleVertXGeneratorTest {
@Test
public void generateSampleServer() {
String[] args = new String[11];
args[0] = "generate";
args[1] = "-l";
args[2] = "java-vertx";
args[3] = "-i";
args[4] = "src/test/resources/petstore.json";
args[5] = "-o";
args[6] = "../../sample/petstore-vertx-server";
args[7] = "--group-id";
args[8] = "io.swagger";
args[9] = "--artifact-id";
args[10] = "petstore-vertx-server";
SwaggerCodegen.main(args);
}
}
| fixing file location
| modules/vertx-swagger-codegen/src/test/java/io/vertx/ext/swagger/codegen/SampleVertXGeneratorTest.java | fixing file location | <ide><path>odules/vertx-swagger-codegen/src/test/java/io/vertx/ext/swagger/codegen/SampleVertXGeneratorTest.java
<ide> args[1] = "-l";
<ide> args[2] = "java-vertx";
<ide> args[3] = "-i";
<del> args[4] = "src/test/resources/petstore.json";
<add> args[4] = "petstore.json";
<ide> args[5] = "-o";
<ide> args[6] = "../../sample/petstore-vertx-server";
<ide> args[7] = "--group-id"; |
|
Java | agpl-3.0 | error: pathspec 'src/fi/tnie/db/query/Query.java' did not match any file(s) known to git
| fd5aa143a1e84df6c097af5c9f3b77ef3eb6a71f | 1 | tjn/relaxe,tjn/relaxe | /*
* Copyright (c) 2009-2013 Topi Nieminen
*/
package fi.tnie.db.query;
import fi.tnie.db.expr.QueryExpression;
import fi.tnie.db.rpc.AbstractRequest;
public class Query
extends AbstractRequest {
/**
*
*/
private static final long serialVersionUID = 1412811343522826948L;
private QueryExpression expression;
/**
* No-argument constructor for GWT Serialization
*/
protected Query() {
}
public Query(QueryExpression expression) {
super();
if (expression == null) {
throw new NullPointerException("expression");
}
this.expression = expression;
}
public QueryExpression getExpression() {
return expression;
}
}
| src/fi/tnie/db/query/Query.java | Move Query to "query" sub-package
| src/fi/tnie/db/query/Query.java | Move Query to "query" sub-package | <ide><path>rc/fi/tnie/db/query/Query.java
<add>/*
<add> * Copyright (c) 2009-2013 Topi Nieminen
<add> */
<add>package fi.tnie.db.query;
<add>
<add>import fi.tnie.db.expr.QueryExpression;
<add>import fi.tnie.db.rpc.AbstractRequest;
<add>
<add>public class Query
<add> extends AbstractRequest {
<add>
<add> /**
<add> *
<add> */
<add> private static final long serialVersionUID = 1412811343522826948L;
<add>
<add> private QueryExpression expression;
<add>
<add> /**
<add> * No-argument constructor for GWT Serialization
<add> */
<add> protected Query() {
<add> }
<add>
<add> public Query(QueryExpression expression) {
<add> super();
<add>
<add> if (expression == null) {
<add> throw new NullPointerException("expression");
<add> }
<add>
<add> this.expression = expression;
<add> }
<add>
<add> public QueryExpression getExpression() {
<add> return expression;
<add> }
<add>} |
|
Java | epl-1.0 | c854cbc90f7655b66155ccc2af49198a03480e49 | 0 | gnodet/wikitext | /*******************************************************************************
* Copyright (c) 2004, 2007 Mylyn project committers and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package org.eclipse.mylyn.internal.tasks.core;
import java.io.File;
import java.io.IOException;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.ISchedulingRule;
import org.eclipse.mylyn.commons.core.StatusHandler;
import org.eclipse.mylyn.internal.tasks.core.externalization.AbstractExternalizationParticipant;
import org.eclipse.mylyn.internal.tasks.core.externalization.ExternalizationManager;
import org.eclipse.mylyn.internal.tasks.core.externalization.IExternalizationContext;
import org.eclipse.mylyn.tasks.core.ITaskRepositoryListener;
import org.eclipse.mylyn.tasks.core.TaskRepository;
/**
* @author Rob Elves
* @since 3.0
*/
public class RepositoryExternalizationParticipant extends AbstractExternalizationParticipant implements
ITaskRepositoryListener {
private final TaskRepositoryManager repositoryManager;
private boolean dirty = false;
private final ExternalizationManager externalizationManager;
public RepositoryExternalizationParticipant(ExternalizationManager exManager, TaskRepositoryManager manager) {
this.repositoryManager = manager;
this.externalizationManager = exManager;
this.repositoryManager.addListener(this);
}
@Override
public void execute(IExternalizationContext context, IProgressMonitor monitor) throws CoreException {
Assert.isNotNull(context);
String filePath = context.getRootPath() + File.separator + TaskRepositoryManager.DEFAULT_REPOSITORIES_FILE;
final File repositoriesFile = new File(filePath);
if (!repositoriesFile.exists()) {
try {
repositoriesFile.createNewFile();
} catch (IOException e) {
throw new CoreException(new Status(IStatus.ERROR, ITasksCoreConstants.ID_PLUGIN,
"Task Repositories file not found, error creating new file.", e));
}
}
switch (context.getKind()) {
case SAVE:
if (!takeSnapshot(repositoriesFile)) {
StatusHandler.fail(new Status(IStatus.WARNING, ITasksCoreConstants.ID_PLUGIN,
"Task List snapshot failed"));
}
repositoryManager.saveRepositories(filePath);
synchronized (RepositoryExternalizationParticipant.this) {
dirty = false;
}
break;
case LOAD:
try {
repositoryManager.readRepositories(filePath);
} catch (Exception e) {
if (restoreSnapshot(repositoriesFile)) {
repositoryManager.readRepositories(filePath);
} else {
throw new CoreException(new Status(IStatus.ERROR, ITasksCoreConstants.ID_PLUGIN,
"Failed to load repositories", e));
}
}
break;
}
}
@Override
public String getDescription() {
return "Task Repositories";
}
@Override
public ISchedulingRule getSchedulingRule() {
return ITasksCoreConstants.TASKLIST_SCHEDULING_RULE;
}
@Override
public boolean isDirty() {
return dirty;
}
public void repositoryUrlChanged(TaskRepository repository, String oldUrl) {
requestSave();
}
public void repositoriesRead() {
// ignore
}
public void repositoryAdded(TaskRepository repository) {
requestSave();
}
public void repositoryRemoved(TaskRepository repository) {
requestSave();
}
public void repositorySettingsChanged(TaskRepository repository) {
requestSave();
}
private void requestSave() {
synchronized (RepositoryExternalizationParticipant.this) {
dirty = true;
}
externalizationManager.requestSave();
}
}
| org.eclipse.mylyn.tasks.core/src/org/eclipse/mylyn/internal/tasks/core/RepositoryExternalizationParticipant.java | /*******************************************************************************
* Copyright (c) 2004, 2007 Mylyn project committers and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package org.eclipse.mylyn.internal.tasks.core;
import java.io.File;
import java.io.IOException;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.ISchedulingRule;
import org.eclipse.mylyn.commons.core.StatusHandler;
import org.eclipse.mylyn.internal.tasks.core.externalization.AbstractExternalizationParticipant;
import org.eclipse.mylyn.internal.tasks.core.externalization.ExternalizationManager;
import org.eclipse.mylyn.internal.tasks.core.externalization.IExternalizationContext;
import org.eclipse.mylyn.tasks.core.ITaskRepositoryListener;
import org.eclipse.mylyn.tasks.core.TaskRepository;
/**
* @author Rob Elves
* @since 3.0
*/
public class RepositoryExternalizationParticipant extends AbstractExternalizationParticipant implements
ITaskRepositoryListener {
private final TaskRepositoryManager repositoryManager;
private boolean dirty = false;
private final ExternalizationManager externalizationManager;
public RepositoryExternalizationParticipant(ExternalizationManager exManager, TaskRepositoryManager manager) {
this.repositoryManager = manager;
this.externalizationManager = exManager;
this.repositoryManager.addListener(this);
}
@Override
public void execute(IExternalizationContext context, IProgressMonitor monitor) throws CoreException {
Assert.isNotNull(context);
String filePath = context.getRootPath() + File.separator + TaskRepositoryManager.DEFAULT_REPOSITORIES_FILE;
final File repositoriesFile = new File(filePath);
if (!repositoriesFile.exists()) {
try {
repositoriesFile.createNewFile();
} catch (IOException e) {
throw new CoreException(new Status(IStatus.ERROR, ITasksCoreConstants.ID_PLUGIN,
"Task Repositories file not found, error creating new file.", e));
}
}
switch (context.getKind()) {
case SAVE:
System.err.println(">>> save repositories");
if (!takeSnapshot(repositoriesFile)) {
StatusHandler.fail(new Status(IStatus.WARNING, ITasksCoreConstants.ID_PLUGIN,
"Task List snapshot failed"));
}
repositoryManager.saveRepositories(filePath);
synchronized (RepositoryExternalizationParticipant.this) {
dirty = false;
}
break;
case LOAD:
try {
repositoryManager.readRepositories(filePath);
} catch (Exception e) {
if (restoreSnapshot(repositoriesFile)) {
repositoryManager.readRepositories(filePath);
} else {
throw new CoreException(new Status(IStatus.ERROR, ITasksCoreConstants.ID_PLUGIN,
"Failed to load repositories", e));
}
}
break;
}
}
@Override
public String getDescription() {
return "Task Repositories";
}
@Override
public ISchedulingRule getSchedulingRule() {
return ITasksCoreConstants.TASKLIST_SCHEDULING_RULE;
}
@Override
public boolean isDirty() {
return dirty;
}
public void repositoryUrlChanged(TaskRepository repository, String oldUrl) {
requestSave();
}
public void repositoriesRead() {
// ignore
}
public void repositoryAdded(TaskRepository repository) {
requestSave();
}
public void repositoryRemoved(TaskRepository repository) {
requestSave();
}
public void repositorySettingsChanged(TaskRepository repository) {
requestSave();
}
private void requestSave() {
synchronized (RepositoryExternalizationParticipant.this) {
dirty = true;
}
externalizationManager.requestSave();
}
}
| NEW - bug 232180: stop unnecessary saves of task list and related information upon startup
https://bugs.eclipse.org/bugs/show_bug.cgi?id=232180
| org.eclipse.mylyn.tasks.core/src/org/eclipse/mylyn/internal/tasks/core/RepositoryExternalizationParticipant.java | NEW - bug 232180: stop unnecessary saves of task list and related information upon startup https://bugs.eclipse.org/bugs/show_bug.cgi?id=232180 | <ide><path>rg.eclipse.mylyn.tasks.core/src/org/eclipse/mylyn/internal/tasks/core/RepositoryExternalizationParticipant.java
<ide>
<ide> switch (context.getKind()) {
<ide> case SAVE:
<del> System.err.println(">>> save repositories");
<ide> if (!takeSnapshot(repositoriesFile)) {
<ide> StatusHandler.fail(new Status(IStatus.WARNING, ITasksCoreConstants.ID_PLUGIN,
<ide> "Task List snapshot failed")); |
|
Java | apache-2.0 | 83fe4fd4510349d809ba93bb2cb1c97854bdabc8 | 0 | ShinySide/KernelAdiutor | /*
* Copyright (C) 2015-2016 Willi Ye <[email protected]>
*
* This file is part of Kernel Adiutor.
*
* Kernel Adiutor 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.
*
* Kernel Adiutor 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 Kernel Adiutor. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.grarak.kerneladiutor.services.boot;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import android.support.v7.app.NotificationCompat;
import com.grarak.kerneladiutor.BuildConfig;
import com.grarak.kerneladiutor.R;
import com.grarak.kerneladiutor.activities.StartActivity;
import com.grarak.kerneladiutor.database.Settings;
import com.grarak.kerneladiutor.database.tools.customcontrols.Controls;
import com.grarak.kerneladiutor.database.tools.profiles.Profiles;
import com.grarak.kerneladiutor.fragments.ApplyOnBootFragment;
import com.grarak.kerneladiutor.services.profile.Tile;
import com.grarak.kerneladiutor.utils.Prefs;
import com.grarak.kerneladiutor.utils.Utils;
import com.grarak.kerneladiutor.utils.kernel.cpu.CPUFreq;
import com.grarak.kerneladiutor.utils.kernel.cpuhotplug.MPDecision;
import com.grarak.kerneladiutor.utils.root.Control;
import com.grarak.kerneladiutor.utils.root.RootFile;
import com.grarak.kerneladiutor.utils.root.RootUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* Created by willi on 03.05.16.
*/
public class Service extends android.app.Service {
private static final String TAG = Service.class.getSimpleName();
private static boolean sCancel;
private HashMap<String, Boolean> mCategoryEnabled = new HashMap<>();
private HashMap<String, String> mCustomControls = new HashMap<>();
private List<String> mProfiles = new ArrayList<>();
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Messenger messenger = null;
if (intent != null) {
Bundle extras = intent.getExtras();
if (extras != null) {
messenger = (Messenger) extras.get("messenger");
}
}
if (messenger == null) {
PackageManager pm = getPackageManager();
if (Utils.hideStartActivity()) {
pm.setComponentEnabledSetting(new ComponentName(this, StartActivity.class),
PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
pm.setComponentEnabledSetting(new ComponentName(BuildConfig.APPLICATION_ID,
BuildConfig.APPLICATION_ID + ".activities.StartActivity"),
PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
} else {
Utils.setStartActivity(Prefs.getBoolean("materialicon", false, this), this);
}
}
boolean enabled = false;
final Settings settings = new Settings(this);
Controls controls = new Controls(this);
List<Profiles.ProfileItem> profiles = new Profiles(this).getAllProfiles();
if (messenger == null) {
Tile.publishProfileTile(profiles, this);
}
for (Settings.SettingsItem item : settings.getAllSettings()) {
if (!mCategoryEnabled.containsKey(item.getCategory())) {
mCategoryEnabled.put(item.getCategory(), Prefs.getBoolean(item.getCategory(), false, this));
}
}
for (String key : mCategoryEnabled.keySet()) {
if (mCategoryEnabled.get(key)) {
enabled = true;
break;
}
}
for (Controls.ControlItem item : controls.getAllControls()) {
if (item.isOnBootEnabled() && item.getArguments() != null) {
mCustomControls.put(item.getApply(), item.getArguments());
}
}
for (Profiles.ProfileItem profileItem : profiles) {
if (profileItem.isOnBootEnabled()) {
for (String commad : profileItem.getCommands()) {
mProfiles.add(commad);
}
}
}
final boolean initdEnabled = Prefs.getBoolean("initd_onboot", false, this);
enabled = enabled || mCustomControls.size() > 0 || mProfiles.size() > 0 || initdEnabled;
if (!enabled) {
if (messenger != null) {
try {
Message message = Message.obtain();
message.arg1 = 1;
messenger.send(message);
} catch (RemoteException ignored) {
}
}
stopSelf();
return;
}
final int seconds = Utils.strToInt(Prefs.getString("applyonbootdelay", "10", this));
final boolean hideNotification = Prefs.getBoolean("applyonboothide", false, this);
final boolean confirmationNotification = Prefs.getBoolean("applyonbootconfirmationnotification",
true, this);
final boolean toast = Prefs.getBoolean("applyonboottoast", false, this);
final boolean script = Prefs.getBoolean("applyonbootscript", false, this);
PendingIntent cancelIntent = PendingIntent.getBroadcast(this, 0, new Intent(this,
CancelReceiver.class), 0);
PackageManager pm = getPackageManager();
Intent launchIntent = pm.getLaunchIntentForPackage(BuildConfig.APPLICATION_ID);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, launchIntent, 0);
final NotificationManager notificationManager = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
final NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
if (!hideNotification) {
builder.setContentTitle(getString(R.string.app_name))
.setContentText(getString(R.string.apply_on_boot_text, seconds))
.setSmallIcon(R.drawable.ic_restore)
.addAction(0, getString(R.string.cancel), cancelIntent)
.setAutoCancel(true)
.setContentIntent(contentIntent)
.setWhen(0);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
builder.setPriority(Notification.PRIORITY_MAX);
}
}
final NotificationCompat.Builder builderComplete = new NotificationCompat.Builder(this);
if (!hideNotification) {
builderComplete.setContentTitle(getString(R.string.app_name))
.setSmallIcon(R.drawable.ic_restore)
.setContentIntent(contentIntent);
}
final Handler handler = new Handler();
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < seconds; i++) {
if (!hideNotification) {
if (sCancel) {
break;
}
builder.setContentText(getString(R.string.apply_on_boot_text, seconds - i));
builder.setProgress(seconds, i, false);
notificationManager.notify(0, builder.build());
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (!hideNotification) {
if (confirmationNotification) {
builderComplete.setContentText(getString(sCancel ? R.string.apply_on_boot_canceled :
R.string.apply_on_boot_complete));
notificationManager.notify(0, builderComplete.build());
} else {
notificationManager.cancel(0);
}
if (sCancel) {
sCancel = false;
stopSelf();
return;
}
}
RootUtils.SU su = new RootUtils.SU(true, TAG);
if (initdEnabled) {
RootUtils.mount(true, "/system", su);
su.runCommand("for i in `ls /system/etc/init.d`;do chmod 755 $i;done");
su.runCommand("[ -d /system/etc/init.d ] && run-parts /system/etc/init.d");
RootUtils.mount(false, "/system", su);
}
List<String> commands = new ArrayList<>();
for (Settings.SettingsItem item : settings.getAllSettings()) {
String category = item.getCategory();
String setting = item.getSetting();
String id = item.getId();
CPUFreq.ApplyCpu applyCpu;
if (mCategoryEnabled.get(category)) {
if (category.equals(ApplyOnBootFragment.CPU)
&& id.contains("%d")
&& setting.startsWith("#")
&& ((applyCpu =
new CPUFreq.ApplyCpu(setting.substring(1))).toString() != null)) {
synchronized (this) {
commands.addAll(getApplyCpu(applyCpu, su));
}
} else {
commands.add(setting);
}
}
}
if (script) {
StringBuilder s = new StringBuilder("#!/system/bin/sh\n\n");
for (String command : commands) {
s.append(command).append("\n");
}
RootFile file = new RootFile("/data/local/tmp/kerneladiutortmp.sh", su);
file.mkdir();
file.write(s.toString(), false);
file.execute();
} else {
for (String command : commands) {
synchronized (this) {
su.runCommand(command);
}
}
}
for (String script : mCustomControls.keySet()) {
RootFile file = new RootFile("/data/local/tmp/kerneladiutortmp.sh", su);
file.mkdir();
file.write(script, false);
file.execute(mCustomControls.get(script));
}
List<String> profileCommands = new ArrayList<>();
for (String command : mProfiles) {
CPUFreq.ApplyCpu applyCpu;
if (command.startsWith("#")
&& ((applyCpu =
new CPUFreq.ApplyCpu(command.substring(1))).toString() != null)) {
synchronized (this) {
profileCommands.addAll(getApplyCpu(applyCpu, su));
}
}
profileCommands.add(command);
}
if (script) {
StringBuilder s = new StringBuilder("#!/system/bin/sh\n\n");
for (String command : profileCommands) {
s.append(command).append("\n");
}
RootFile file = new RootFile("/data/local/tmp/kerneladiutortmp.sh", su);
file.mkdir();
file.write(s.toString(), false);
file.execute();
} else {
for (String command : profileCommands) {
synchronized (this) {
su.runCommand(command);
}
}
}
su.close();
if (toast) {
handler.post(new Runnable() {
@Override
public void run() {
Utils.toast(R.string.apply_on_boot_complete, Service.this);
}
});
}
stopSelf();
}
}).start();
}
public static List<String> getApplyCpu(CPUFreq.ApplyCpu applyCpu, RootUtils.SU su) {
List<String> commands = new ArrayList<>();
boolean mpdecision = Utils.hasProp(MPDecision.HOTPLUG_MPDEC, su)
&& Utils.isPropRunning(MPDecision.HOTPLUG_MPDEC, su);
if (mpdecision) {
commands.add(Control.stopService(MPDecision.HOTPLUG_MPDEC));
}
for (int i = applyCpu.getMin(); i <= applyCpu.getMax(); i++) {
boolean offline = !Utils.existFile(Utils.strFormat(applyCpu.getPath(), i), su);
if (offline) {
commands.add(Control.write("1", Utils.strFormat(CPUFreq.CPU_ONLINE, i)));
}
commands.add(Control.chmod("644", Utils.strFormat(applyCpu.getPath(), i)));
commands.add(Control.write(applyCpu.getValue(), Utils.strFormat(applyCpu.getPath(), i)));
commands.add(Control.chmod("444", Utils.strFormat(applyCpu.getPath(), i)));
if (offline) {
commands.add(Control.write("0", Utils.strFormat(CPUFreq.CPU_ONLINE, i)));
}
}
if (mpdecision) {
commands.add(Control.startService(MPDecision.HOTPLUG_MPDEC));
}
return commands;
}
public static class CancelReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
sCancel = true;
}
}
}
| app/src/main/java/com/grarak/kerneladiutor/services/boot/Service.java | /*
* Copyright (C) 2015-2016 Willi Ye <[email protected]>
*
* This file is part of Kernel Adiutor.
*
* Kernel Adiutor 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.
*
* Kernel Adiutor 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 Kernel Adiutor. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.grarak.kerneladiutor.services.boot;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import android.support.v7.app.NotificationCompat;
import com.grarak.kerneladiutor.BuildConfig;
import com.grarak.kerneladiutor.R;
import com.grarak.kerneladiutor.activities.StartActivity;
import com.grarak.kerneladiutor.database.Settings;
import com.grarak.kerneladiutor.database.tools.customcontrols.Controls;
import com.grarak.kerneladiutor.database.tools.profiles.Profiles;
import com.grarak.kerneladiutor.fragments.ApplyOnBootFragment;
import com.grarak.kerneladiutor.services.profile.Tile;
import com.grarak.kerneladiutor.utils.Prefs;
import com.grarak.kerneladiutor.utils.Utils;
import com.grarak.kerneladiutor.utils.kernel.cpu.CPUFreq;
import com.grarak.kerneladiutor.utils.kernel.cpuhotplug.MPDecision;
import com.grarak.kerneladiutor.utils.root.Control;
import com.grarak.kerneladiutor.utils.root.RootFile;
import com.grarak.kerneladiutor.utils.root.RootUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* Created by willi on 03.05.16.
*/
public class Service extends android.app.Service {
private static final String TAG = Service.class.getSimpleName();
private static boolean sCancel;
private HashMap<String, Boolean> mCategoryEnabled = new HashMap<>();
private HashMap<String, String> mCustomControls = new HashMap<>();
private List<String> mProfiles = new ArrayList<>();
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Messenger messenger = null;
if (intent != null) {
Bundle extras = intent.getExtras();
if (extras != null) {
messenger = (Messenger) extras.get("messenger");
}
}
if (messenger == null) {
PackageManager pm = getPackageManager();
if (Utils.hideStartActivity()) {
pm.setComponentEnabledSetting(new ComponentName(this, StartActivity.class),
PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
pm.setComponentEnabledSetting(new ComponentName(BuildConfig.APPLICATION_ID,
BuildConfig.APPLICATION_ID + ".activities.StartActivity"),
PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
} else {
Utils.setStartActivity(Prefs.getBoolean("materialicon", false, this), this);
}
}
boolean enabled = false;
final Settings settings = new Settings(this);
Controls controls = new Controls(this);
List<Profiles.ProfileItem> profiles = new Profiles(this).getAllProfiles();
if (messenger == null) {
Tile.publishProfileTile(profiles, this);
}
for (Settings.SettingsItem item : settings.getAllSettings()) {
if (!mCategoryEnabled.containsKey(item.getCategory())) {
mCategoryEnabled.put(item.getCategory(), Prefs.getBoolean(item.getCategory(), false, this));
}
}
for (String key : mCategoryEnabled.keySet()) {
if (mCategoryEnabled.get(key)) {
enabled = true;
break;
}
}
for (Controls.ControlItem item : controls.getAllControls()) {
if (item.isOnBootEnabled() && item.getArguments() != null) {
mCustomControls.put(item.getApply(), item.getArguments());
}
}
for (Profiles.ProfileItem profileItem : profiles) {
if (profileItem.isOnBootEnabled()) {
for (String commad : profileItem.getCommands()) {
mProfiles.add(commad);
}
}
}
final boolean initdEnabled = Prefs.getBoolean("initd_onboot", false, this);
enabled = enabled || mCustomControls.size() > 0 || mProfiles.size() > 0 || initdEnabled;
if (!enabled) {
if (messenger != null) {
try {
Message message = Message.obtain();
message.arg1 = 1;
messenger.send(message);
} catch (RemoteException ignored) {
}
}
stopSelf();
return;
}
final int seconds = Utils.strToInt(Prefs.getString("applyonbootdelay", "10", this));
final boolean hideNotification = Prefs.getBoolean("applyonboothide", false, this);
final boolean confirmationNotification = Prefs.getBoolean("applyonbootconfirmationnotification",
true, this);
final boolean toast = Prefs.getBoolean("applyonboottoast", false, this);
final boolean script = Prefs.getBoolean("applyonbootscript", false, this);
PendingIntent cancelIntent = PendingIntent.getBroadcast(this, 0, new Intent(this,
CancelReceiver.class), 0);
PackageManager pm = getPackageManager();
Intent launchIntent = pm.getLaunchIntentForPackage(BuildConfig.APPLICATION_ID);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, launchIntent, 0);
final NotificationManager notificationManager = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
final NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
if (!hideNotification) {
builder.setContentTitle(getString(R.string.app_name))
.setContentText(getString(R.string.apply_on_boot_text, seconds))
.setSmallIcon(R.drawable.ic_restore)
.addAction(0, getString(R.string.cancel), cancelIntent)
.setAutoCancel(true)
.setContentIntent(contentIntent)
.setWhen(0);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
builder.setPriority(Notification.PRIORITY_MAX);
}
}
final NotificationCompat.Builder builderComplete = new NotificationCompat.Builder(this);
if (!hideNotification) {
builderComplete.setContentTitle(getString(R.string.app_name))
.setSmallIcon(R.drawable.ic_restore)
.setContentIntent(contentIntent);
}
final Handler handler = new Handler();
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < seconds; i++) {
if (!hideNotification) {
if (sCancel) {
break;
}
builder.setContentText(getString(R.string.apply_on_boot_text, seconds - i));
builder.setProgress(seconds, i, false);
notificationManager.notify(0, builder.build());
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (!hideNotification && confirmationNotification) {
builderComplete.setContentText(getString(sCancel ? R.string.apply_on_boot_canceled :
R.string.apply_on_boot_complete));
notificationManager.notify(0, builderComplete.build());
if (sCancel) {
sCancel = false;
stopSelf();
return;
}
}
RootUtils.SU su = new RootUtils.SU(true, TAG);
if (initdEnabled) {
RootUtils.mount(true, "/system", su);
su.runCommand("for i in `ls /system/etc/init.d`;do chmod 755 $i;done");
su.runCommand("[ -d /system/etc/init.d ] && run-parts /system/etc/init.d");
RootUtils.mount(false, "/system", su);
}
List<String> commands = new ArrayList<>();
for (Settings.SettingsItem item : settings.getAllSettings()) {
String category = item.getCategory();
String setting = item.getSetting();
String id = item.getId();
CPUFreq.ApplyCpu applyCpu;
if (mCategoryEnabled.get(category)) {
if (category.equals(ApplyOnBootFragment.CPU)
&& id.contains("%d")
&& setting.startsWith("#")
&& ((applyCpu =
new CPUFreq.ApplyCpu(setting.substring(1))).toString() != null)) {
synchronized (this) {
commands.addAll(getApplyCpu(applyCpu, su));
}
} else {
commands.add(setting);
}
}
}
if (script) {
StringBuilder s = new StringBuilder("#!/system/bin/sh\n\n");
for (String command : commands) {
s.append(command).append("\n");
}
RootFile file = new RootFile("/data/local/tmp/kerneladiutortmp.sh", su);
file.mkdir();
file.write(s.toString(), false);
file.execute();
} else {
for (String command : commands) {
synchronized (this) {
su.runCommand(command);
}
}
}
for (String script : mCustomControls.keySet()) {
RootFile file = new RootFile("/data/local/tmp/kerneladiutortmp.sh", su);
file.mkdir();
file.write(script, false);
file.execute(mCustomControls.get(script));
}
List<String> profileCommands = new ArrayList<>();
for (String command : mProfiles) {
CPUFreq.ApplyCpu applyCpu;
if (command.startsWith("#")
&& ((applyCpu =
new CPUFreq.ApplyCpu(command.substring(1))).toString() != null)) {
synchronized (this) {
profileCommands.addAll(getApplyCpu(applyCpu, su));
}
}
profileCommands.add(command);
}
if (script) {
StringBuilder s = new StringBuilder("#!/system/bin/sh\n\n");
for (String command : profileCommands) {
s.append(command).append("\n");
}
RootFile file = new RootFile("/data/local/tmp/kerneladiutortmp.sh", su);
file.mkdir();
file.write(s.toString(), false);
file.execute();
} else {
for (String command : profileCommands) {
synchronized (this) {
su.runCommand(command);
}
}
}
su.close();
if (toast) {
handler.post(new Runnable() {
@Override
public void run() {
Utils.toast(R.string.apply_on_boot_complete, Service.this);
}
});
}
stopSelf();
}
}).start();
}
public static List<String> getApplyCpu(CPUFreq.ApplyCpu applyCpu, RootUtils.SU su) {
List<String> commands = new ArrayList<>();
boolean mpdecision = Utils.hasProp(MPDecision.HOTPLUG_MPDEC, su)
&& Utils.isPropRunning(MPDecision.HOTPLUG_MPDEC, su);
if (mpdecision) {
commands.add(Control.stopService(MPDecision.HOTPLUG_MPDEC));
}
for (int i = applyCpu.getMin(); i <= applyCpu.getMax(); i++) {
boolean offline = !Utils.existFile(Utils.strFormat(applyCpu.getPath(), i), su);
if (offline) {
commands.add(Control.write("1", Utils.strFormat(CPUFreq.CPU_ONLINE, i)));
}
commands.add(Control.chmod("644", Utils.strFormat(applyCpu.getPath(), i)));
commands.add(Control.write(applyCpu.getValue(), Utils.strFormat(applyCpu.getPath(), i)));
commands.add(Control.chmod("444", Utils.strFormat(applyCpu.getPath(), i)));
if (offline) {
commands.add(Control.write("0", Utils.strFormat(CPUFreq.CPU_ONLINE, i)));
}
}
if (mpdecision) {
commands.add(Control.startService(MPDecision.HOTPLUG_MPDEC));
}
return commands;
}
public static class CancelReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
sCancel = true;
}
}
}
| Boot: Service: Make sure notification gets cancelled
| app/src/main/java/com/grarak/kerneladiutor/services/boot/Service.java | Boot: Service: Make sure notification gets cancelled | <ide><path>pp/src/main/java/com/grarak/kerneladiutor/services/boot/Service.java
<ide> e.printStackTrace();
<ide> }
<ide> }
<del> if (!hideNotification && confirmationNotification) {
<del> builderComplete.setContentText(getString(sCancel ? R.string.apply_on_boot_canceled :
<del> R.string.apply_on_boot_complete));
<del> notificationManager.notify(0, builderComplete.build());
<add> if (!hideNotification) {
<add> if (confirmationNotification) {
<add> builderComplete.setContentText(getString(sCancel ? R.string.apply_on_boot_canceled :
<add> R.string.apply_on_boot_complete));
<add> notificationManager.notify(0, builderComplete.build());
<add> } else {
<add> notificationManager.cancel(0);
<add> }
<ide>
<ide> if (sCancel) {
<ide> sCancel = false; |
|
Java | apache-2.0 | 6f2f304890cd5316f80018a1a9f0ddaf0ea45f7e | 0 | js42721/datastructures | package datastructures;
/**
* A fixed-capacity mutable min-heap of {@code double} values where each value
* is associated with an {@code int} index.
*/
public class MinHeap {
final double[] a;
final int[] htoi;
final int[] itoh;
int size;
/**
* Creates a min-heap with a capacity of n.
*
* @param n the capacity
* @throws IllegalArgumentException if n is negative
*/
public MinHeap(int n) {
if (n < 0) {
throw new IllegalArgumentException("n must not be negative");
}
a = new double[n];
htoi = new int[n];
itoh = new int[n];
for (int i = 0; i < n; ++i) {
itoh[i] = -1;
}
}
/** Returns the capacity of this heap. */
public int capacity() {
return a.length;
}
/** Returns the number of values in this heap. */
public int size() {
return size;
}
/**
* Checks if this heap is empty.
*
* @return {@code true} if this heap is empty
*/
public boolean isEmpty() {
return size == 0;
}
/**
* Returns the index associated with the minimum value.
*
* @return the index associated with the minimum value or -1 if the heap
* is empty
*/
public int peek() {
return (size == 0) ? -1 : htoi[0];
}
/**
* Returns the minimum value.
*
* @return the minimum value or NaN if the heap is empty
*/
public double peekVal() {
return (size == 0) ? Double.NaN : a[htoi[0]];
}
/**
* Checks if the value associated with an index is present.
*
* @param i the index
* @return {@code true} if the heap contains a value for i
* @throws IndexOutOfBoundsException if i is outside [0, capacity)
*/
public boolean contains(int i) {
if (i < 0 || i >= itoh.length) {
throw new IndexOutOfBoundsException(String.valueOf(i));
}
return itoh[i] != -1;
}
/**
* Returns the value associated with an index.
*
* @param i the index
* @return the value associated with i or NaN if there is no such value
* @throws IndexOutOfBoundsException if i is outside [0, capacity)
*/
public double get(int i) {
return contains(i) ? a[i] : Double.NaN;
}
/**
* Inserts a value and associates it with an index unless there is already
* a value for the index.
*
* @param i the index
* @param val the value
* @return {@code true} if the heap does not already contain a value for i
* @throws IndexOutOfBoundsException if i is outside [0, capacity)
* @throws IllegalArgumentException if val is NaN
*/
public boolean insert(int i, double val) {
if (Double.isNaN(val)) {
throw new IllegalArgumentException("Value is NaN");
}
if (contains(i)) {
return false;
}
siftUp(size++, i, val);
a[i] = val;
return true;
}
/**
* Removes the minimum value.
*
* @return the index associated with the minimum value or -1 if the heap
* is empty
*/
public int delete() {
if (size == 0) {
return -1;
}
int min = htoi[0];
int i = htoi[--size];
siftDown(0, i, a[i]);
itoh[min] = -1;
return min;
}
/**
* Removes the value associated with an index.
*
* @param i the index
* @return the value associated with i or NaN if there is no such value
* @throws IndexOutOfBoundsException if i is outside [0, capacity)
*/
public double delete(int i) {
if (!contains(i)) {
return Double.NaN;
}
int last = htoi[--size];
double lv = a[last];
double val = a[i];
if (lv <= val) {
siftUp(itoh[i], last, lv);
} else {
siftDown(itoh[i], last, lv);
}
itoh[i] = -1;
return val;
}
/**
* Replaces the value associated with an index.
*
* @param i the index
* @param val the replacement value
* @return the old value or NaN if there is no value associated with i
* @throws IndexOutOfBoundsException if i is outside [0, capacity)
* @throws IllegalArgumentException if val is NaN
*/
public double update(int i, double val) {
if (Double.isNaN(val)) {
throw new IllegalArgumentException("Value is NaN");
}
if (!contains(i)) {
return Double.NaN;
}
double old = a[i];
if (val <= old) {
siftUp(itoh[i], i, val);
} else {
siftDown(itoh[i], i, val);
}
a[i] = val;
return old;
}
/** Empties the heap. */
public void clear() {
for (int i = 0; i < itoh.length; ++i) {
itoh[i] = -1;
}
size = 0;
}
private void siftUp(int h, int i, double val) {
while (h > 0) {
int parent = (h - 1) >> 1;
int p = htoi[parent];
if (val >= a[p]) {
break;
}
itoh[p] = h;
htoi[h] = p;
h = parent;
}
htoi[h] = i;
itoh[i] = h;
}
private void siftDown(int h, int i, double val) {
int limit = ((size - 1) - 1) >> 1;
while (h <= limit) {
int successor = (h << 1) + 1;
int s = htoi[successor];
double sv = a[s];
int right = successor + 1;
if (right < size) {
int r = htoi[right];
double rv = a[r];
if (rv < sv) {
successor = right;
sv = rv;
s = r;
}
}
if (val <= sv) {
break;
}
itoh[s] = h;
htoi[h] = s;
h = successor;
}
htoi[h] = i;
itoh[i] = h;
}
}
| src/datastructures/MinHeap.java | package datastructures;
/**
* A fixed-capacity mutable min-heap of {@code double} values where each value
* is associated with an {@code int} index.
*/
public class MinHeap {
final double[] a;
final int[] htoi;
final int[] itoh;
int size;
/**
* Creates a min-heap with a maximum capacity of n.
*
* @param n the maximum capacity
* @throws IllegalArgumentException if n is negative
*/
public MinHeap(int n) {
if (n < 0) {
throw new IllegalArgumentException("n must not be negative");
}
a = new double[n];
htoi = new int[n];
itoh = new int[n];
for (int i = 0; i < n; ++i) {
itoh[i] = -1;
}
}
/**
* Returns the number of values in the heap.
*
* @return the number of values in the heap
*/
public int size() {
return size;
}
/**
* Returns true if the heap is empty.
*
* @return {@code true} if the heap is empty
*/
public boolean isEmpty() {
return size == 0;
}
/**
* Returns the index associated with the minimum value.
*
* @return the index associated with the minimum value or -1 if the heap
* is empty
*/
public int peek() {
return (size == 0) ? -1 : htoi[0];
}
/**
* Returns the minimum value.
*
* @return the minimum value or NaN if the heap is empty
*/
public double peekVal() {
return (size == 0) ? Double.NaN : a[htoi[0]];
}
/**
* Checks if the value associated with an index is present.
*
* @param i the index
* @return {@code true} if the heap contains a value for i
* @throws IndexOutOfBoundsException if i is outside [0, n)
*/
public boolean contains(int i) {
if (i < 0 || i >= itoh.length) {
throw new IndexOutOfBoundsException(String.valueOf(i));
}
return itoh[i] != -1;
}
/**
* Returns the value associated with an index.
*
* @param i the index
* @return the value associated with i or NaN if there is no such value
* @throws IndexOutOfBoundsException if i is outside [0, n)
*/
public double get(int i) {
return contains(i) ? a[i] : Double.NaN;
}
/**
* Inserts a value and associates it with an index unless there is already
* a value for the index.
*
* @param i the index
* @param val the value
* @return {@code true} if the heap does not already contain a value for i
* @throws IndexOutOfBoundsException if i is outside [0, n)
* @throws IllegalArgumentException if val is NaN
*/
public boolean insert(int i, double val) {
if (Double.isNaN(val)) {
throw new IllegalArgumentException("Value is NaN");
}
if (contains(i)) {
return false;
}
siftUp(size++, i, val);
a[i] = val;
return true;
}
/**
* Removes the minimum value.
*
* @return the index associated with the minimum value or -1 if the heap
* is empty
*/
public int delete() {
if (size == 0) {
return -1;
}
int min = htoi[0];
int i = htoi[--size];
siftDown(0, i, a[i]);
itoh[min] = -1;
return min;
}
/**
* Removes the value associated with an index.
*
* @param i the index
* @return the value associated with i or NaN if there is no such value
* @throws IndexOutOfBoundsException if i is outside [0, n)
*/
public double delete(int i) {
if (!contains(i)) {
return Double.NaN;
}
int last = htoi[--size];
double lv = a[last];
double val = a[i];
if (lv <= val) {
siftUp(itoh[i], last, lv);
} else {
siftDown(itoh[i], last, lv);
}
itoh[i] = -1;
return val;
}
/**
* Replaces the value associated with an index.
*
* @param i the index
* @param val the replacement value
* @return the old value or NaN if there is no value associated with i
* @throws IndexOutOfBoundsException if i is outside [0, n)
* @throws IllegalArgumentException if val is NaN
*/
public double update(int i, double val) {
if (Double.isNaN(val)) {
throw new IllegalArgumentException("Value is NaN");
}
if (!contains(i)) {
return Double.NaN;
}
double old = a[i];
if (val <= old) {
siftUp(itoh[i], i, val);
} else {
siftDown(itoh[i], i, val);
}
a[i] = val;
return old;
}
/** Empties the heap. */
public void clear() {
for (int i = 0; i < itoh.length; ++i) {
itoh[i] = -1;
}
size = 0;
}
private void siftUp(int h, int i, double val) {
while (h > 0) {
int parent = (h - 1) >> 1;
int p = htoi[parent];
if (val >= a[p]) {
break;
}
itoh[p] = h;
htoi[h] = p;
h = parent;
}
htoi[h] = i;
itoh[i] = h;
}
private void siftDown(int h, int i, double val) {
int limit = ((size - 1) - 1) >> 1;
while (h <= limit) {
int successor = (h << 1) + 1;
int s = htoi[successor];
double sv = a[s];
int right = successor + 1;
if (right < size) {
int r = htoi[right];
double rv = a[r];
if (rv < sv) {
successor = right;
sv = rv;
s = r;
}
}
if (val <= sv) {
break;
}
itoh[s] = h;
htoi[h] = s;
h = successor;
}
htoi[h] = i;
itoh[i] = h;
}
}
| Edited
| src/datastructures/MinHeap.java | Edited | <ide><path>rc/datastructures/MinHeap.java
<ide> int size;
<ide>
<ide> /**
<del> * Creates a min-heap with a maximum capacity of n.
<del> *
<del> * @param n the maximum capacity
<add> * Creates a min-heap with a capacity of n.
<add> *
<add> * @param n the capacity
<ide> * @throws IllegalArgumentException if n is negative
<ide> */
<ide> public MinHeap(int n) {
<ide> }
<ide> }
<ide>
<del> /**
<del> * Returns the number of values in the heap.
<del> *
<del> * @return the number of values in the heap
<del> */
<add> /** Returns the capacity of this heap. */
<add> public int capacity() {
<add> return a.length;
<add> }
<add>
<add> /** Returns the number of values in this heap. */
<ide> public int size() {
<ide> return size;
<ide> }
<ide>
<ide> /**
<del> * Returns true if the heap is empty.
<del> *
<del> * @return {@code true} if the heap is empty
<add> * Checks if this heap is empty.
<add> *
<add> * @return {@code true} if this heap is empty
<ide> */
<ide> public boolean isEmpty() {
<ide> return size == 0;
<ide> *
<ide> * @param i the index
<ide> * @return {@code true} if the heap contains a value for i
<del> * @throws IndexOutOfBoundsException if i is outside [0, n)
<add> * @throws IndexOutOfBoundsException if i is outside [0, capacity)
<ide> */
<ide> public boolean contains(int i) {
<ide> if (i < 0 || i >= itoh.length) {
<ide> *
<ide> * @param i the index
<ide> * @return the value associated with i or NaN if there is no such value
<del> * @throws IndexOutOfBoundsException if i is outside [0, n)
<add> * @throws IndexOutOfBoundsException if i is outside [0, capacity)
<ide> */
<ide> public double get(int i) {
<ide> return contains(i) ? a[i] : Double.NaN;
<ide> * @param i the index
<ide> * @param val the value
<ide> * @return {@code true} if the heap does not already contain a value for i
<del> * @throws IndexOutOfBoundsException if i is outside [0, n)
<add> * @throws IndexOutOfBoundsException if i is outside [0, capacity)
<ide> * @throws IllegalArgumentException if val is NaN
<ide> */
<ide> public boolean insert(int i, double val) {
<ide> *
<ide> * @param i the index
<ide> * @return the value associated with i or NaN if there is no such value
<del> * @throws IndexOutOfBoundsException if i is outside [0, n)
<add> * @throws IndexOutOfBoundsException if i is outside [0, capacity)
<ide> */
<ide> public double delete(int i) {
<ide> if (!contains(i)) {
<ide> * @param i the index
<ide> * @param val the replacement value
<ide> * @return the old value or NaN if there is no value associated with i
<del> * @throws IndexOutOfBoundsException if i is outside [0, n)
<add> * @throws IndexOutOfBoundsException if i is outside [0, capacity)
<ide> * @throws IllegalArgumentException if val is NaN
<ide> */
<ide> public double update(int i, double val) { |
|
JavaScript | mit | 9743fd7754ddaeb1e70e60787f0ffdb90b67c18f | 0 | PRX/Infrastructure,PRX/Infrastructure,PRX/Infrastructure,PRX/Infrastructure,PRX/Infrastructure | // Invoked by: API Gateway
// Returns: Error, or API Gateway proxy response object
//
// When a user acts on an interactive message in Slack (eg., clicks a button),
// Slack will send a request to a callback This function handles those requests,
// such as for approving CloudFormation deploys through CodePipeline.
//
// This handles all requsts to the Slack app's Action URL, which includes
// interactive messages, as well as dialogs and perhaps other requests as well.
const querystring = require('querystring');
const crypto = require('crypto');
const url = require('url');
const https = require('https');
const aws = require('aws-sdk');
const s3 = new aws.S3({apiVersion: '2006-03-01'});
const codepipeline = new aws.CodePipeline({apiVersion: '2015-07-09'});
const sns = new AWS.SNS({ apiVersion: '2010-03-31' });
const APPROVED = 'Approved';
const REJECTED = 'Rejected';
const CODEPIPELINE_MANUAL_APPROVAL_CALLBACK = 'codepipeline-approval-action';
const RELEASE_NOTES_DIALOG_CALLBACK = 'release-notes-dialog';
const ROLLBACK_VERSION_SELECTION_CALLBACK = 'rollback-version-selection-action';
const SLACK_API_DIALOG_OPEN = 'https://slack.com/api/dialog.open';
// Calls a method in the Slack Web API with a provided POST body. The payload
// argument is an object. If responseProperty is provided, rather than the
// entire response being resolved from the promise, only that property will be.
// https://api.slack.com/web
// https://api.slack.com/methods
function slackWebMethod(uri, responseProperty, payload) {
return new Promise((resolve, reject) => {
const urlencodedBody = querystring.stringify(payload);
// Setup request options
const options = url.parse(uri);
options.method = 'POST';
options.headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(urlencodedBody),
};
const method = uri.split('/').pop();
// Request with response handler
console.log(`[Slack] Calling ${method}`);
const req = https.request(options, (res) => {
res.setEncoding('utf8');
let json = '';
res.on('data', (chunk) => { json += chunk; });
res.on('end', () => {
try {
const resPayload = JSON.parse(json);
if (resPayload.ok) {
console.error(`[Slack] ${method} ok`);
resolve(resPayload[responseProperty] || resPayload);
} else {
console.error(`[Slack] ${method} error`);
reject(new Error(resPayload.error));
}
} catch (e) {
console.error(`[Slack] Error parsing ${method}`);
reject(e);
}
});
});
// Generic request error handling
req.on('error', e => reject(e));
req.write(urlencodedBody);
req.end();
});
}
exports.handler = (event, context, callback) => {
try {
processEvent(event, context, callback);
} catch (e) {
callback(e);
}
};
function processEvent(event, context, callback) {
const body = querystring.parse(event.body);
// The JSON object response from Slack
const payload = JSON.parse(body.payload);
// Top-level properties of the message action response object
const callbackId = payload.callback_id;
// Slack signing secret
const slackRequestTimestamp = event.headers['X-Slack-Request-Timestamp'];
const basestring = ['v0', slackRequestTimestamp, event.body].join(':');
const signingSecret = process.env.SLACK_SIGNING_SECRET;
const slackSignature = event.headers['X-Slack-Signature'];
const requestSignature = `v0=${crypto.createHmac('sha256', signingSecret).update(basestring).digest('hex')}`;
if (requestSignature !== slackSignature) {
// Bad request; bogus token
callback(null, { statusCode: 400, headers: {}, body: null });
} else {
// Handle each callback ID appropriately
switch (callbackId) {
case CODEPIPELINE_MANUAL_APPROVAL_CALLBACK:
handleReleaseButtons(payload, callback);
break;
case ROLLBACK_VERSION_SELECTION_CALLBACK:
handleRollbackCallback(payload, callback);
break;
case RELEASE_NOTES_DIALOG_CALLBACK:
handleReleaseNotesDialog(payload, callback);
break;
default:
// Unknown message callback
callback(null, { statusCode: 400, headers: {}, body: null });
}
}
}
function handleReleaseNotesDialog(payload, callback) {
console.log(JSON.stringify(payload));
sns.publish({
TopicArn: process.env.SLACK_MESSAGE_RELAY_TOPIC_ARN,
Message: JSON.stringify({
channel: '#tech-releases',
username: 'Release Notes',
icon_emoji: ':rabbit:',
text: `<@${payload.user.id}>: ${payload.submission.release_notes}`,
}),
}, () => {
callback(null, { statusCode: 200, headers: {}, body: null });
});
}
function handleRollbackCallback(payload, callback) {
const action = payload.actions[0];
switch (action.name) {
case 'selection':
triggerRollback(payload, callback)
break;
default:
cancelRollback(payload, callback);
}
}
function triggerRollback(payload, callback) {
const action = payload.actions[0];
const versionId = action.selected_options[0].value;
const configBucket = process.env.INFRASTRUCTURE_CONFIG_BUCKET;
const configKey = process.env.INFRASTRUCTURE_CONFIG_STAGING_KEY;
const sourceUrl = `${configBucket}/${configKey}?versionId=${versionId}`;
s3.copyObject({
Bucket: configBucket,
CopySource: encodeURI(sourceUrl),
Key: configKey
}, (e, data) => {
if (e) {
console.error(e);
callback(null, { statusCode: 400, headers: {}, body: null });
} else {
const msg = {
text: `Rolling back to config version: ${versionId}`
};
const body = JSON.stringify(msg);
callback(null, { statusCode: 200, headers: {}, body: body });
}
});
}
function cancelRollback(payload, callback) {
const msg = {
text: '_Rollback canceled_'
};
const body = JSON.stringify(msg);
callback(null, { statusCode: 200, headers: {}, body: body });
}
// This will get called for both the Approve and Approve With Notes buttons.
// Both will trigger an IMMEDIATE deploy, but the Aw/N button will also open a
// dialog prompting the user for release notes related to the deploy. (The
// reason the deploy is not delayed until after the release notes dialog is
// because of the added complexity with updating the message in Slack to
// reflect the deployment with the indirection introduced with the dialog. It
// is possible, but was not done to save time.)
function handleReleaseButtons(payload, callback) {
const action = payload.actions[0];
// The manual approval notifications params need to be extracted from
// the action value, where they are stored as stringified JSON data.
const extractedParams = JSON.parse(action.value);
// We're going to immediately update the message that triggered the
// action based on the action taken and the result of that action.
// We'll use the original message as a starting point, but need to
// remove some unnecessary properties before sending it back
const attachment = payload.original_message.attachments[0];
delete attachment.actions;
delete attachment.id;
delete attachment.callback_id;
// Build the params that get sent back to CodePipeline to approve or
// reject the pipeline
const approvalParams = {
pipelineName: extractedParams.pipelineName,
stageName: extractedParams.stageName,
actionName: extractedParams.actionName,
token: extractedParams.token,
result: {
status: extractedParams.value,
summary: 'Handled by Ike'
},
};
codepipeline.putApprovalResult(approvalParams, (err, data) => {
if (err) {
// There was an error making the putApprovalResult request to
// CodePipeline, so the user should be notified that their
// action was not successful
const body = JSON.stringify({ test: `Error: ${err}` });
callback(null, { statusCode: 200, headers: {}, body: body });
} else {
// The putApprovalResult request was successful, so the message
// in Slack should be updated to remove the buttons
const msg = { text: '', attachments: [attachment] };
switch (extractedParams.value) {
case REJECTED:
attachment.text = attachment.text + `\n*<@${payload.user.id}> rejected this deploy*`;
attachment.color = '#de0e0e';
break;
case APPROVED:
attachment.text = attachment.text + `\n:white_check_mark: *<@${payload.user.id}> approved this deploy*`;
attachment.color = '#15da34';
break;
default:
attachment.text = attachment.text + `\nUnknown action by <@${payload.user.id}>`;
attachment.color = '#cd0ede';
}
// The message to replace the one that included the Release buttons
const body = JSON.stringify(msg);
// If the Approve With Notes button was pressed open a dialog,
// otherwise we're done
if (action.name !== 'notes') {
callback(null, { statusCode: 200, headers: {}, body: body });
} else {
slackWebMethod(SLACK_API_DIALOG_OPEN, null, {
trigger_id: payload.trigger_id,
token: process.env.SLACK_ACCESS_TOKEN,
dialog: JSON.stringify({
callback_id: RELEASE_NOTES_DIALOG_CALLBACK,
state: action.value,
title: 'Release Notes',
submit_label: 'Post',
elements: [
{
type: 'textarea',
label: 'Release notes',
name: 'release_notes',
hint: 'These will be posted in #tech-releases.',
},
],
}),
}).then(res => {
callback(null, { statusCode: 200, headers: {}, body: body });
});
}
}
});
}
| notifications/lambdas/ike-interactive-messages-callback-handler/index.js | // Invoked by: API Gateway
// Returns: Error, or API Gateway proxy response object
//
// When a user acts on an interactive message in Slack (eg., clicks a button),
// Slack will send a request to a callback This function handles those requests,
// such as for approving CloudFormation deploys through CodePipeline.
//
// This handles all requsts to the Slack app's Action URL, which includes
// interactive messages, as well as dialogs and perhaps other requests as well.
const querystring = require('querystring');
const crypto = require('crypto');
const url = require('url');
const https = require('https');
const aws = require('aws-sdk');
const s3 = new aws.S3({apiVersion: '2006-03-01'});
const codepipeline = new aws.CodePipeline({apiVersion: '2015-07-09'});
const sns = new AWS.SNS({ apiVersion: '2010-03-31' });
const APPROVED = 'Approved';
const REJECTED = 'Rejected';
const CODEPIPELINE_MANUAL_APPROVAL_CALLBACK = 'codepipeline-approval-action';
const RELEASE_NOTES_DIALOG_CALLBACK = 'release-notes-dialog';
const ROLLBACK_VERSION_SELECTION_CALLBACK = 'rollback-version-selection-action';
const SLACK_API_DIALOG_OPEN = 'https://slack.com/api/dialog.open';
// Calls a method in the Slack Web API with a provided POST body. The payload
// argument is an object. If responseProperty is provided, rather than the
// entire response being resolved from the promise, only that property will be.
// https://api.slack.com/web
// https://api.slack.com/methods
function slackWebMethod(uri, responseProperty, payload) {
return new Promise((resolve, reject) => {
const urlencodedBody = querystring.stringify(payload);
// Setup request options
const options = url.parse(uri);
options.method = 'POST';
options.headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(urlencodedBody),
};
const method = uri.split('/').pop();
// Request with response handler
console.log(`[Slack] Calling ${method}`);
const req = https.request(options, (res) => {
res.setEncoding('utf8');
let json = '';
res.on('data', (chunk) => { json += chunk; });
res.on('end', () => {
try {
const resPayload = JSON.parse(json);
if (resPayload.ok) {
console.error(`[Slack] ${method} ok`);
resolve(resPayload[responseProperty] || resPayload);
} else {
console.error(`[Slack] ${method} error`);
reject(new Error(resPayload.error));
}
} catch (e) {
console.error(`[Slack] Error parsing ${method}`);
reject(e);
}
});
});
// Generic request error handling
req.on('error', e => reject(e));
req.write(urlencodedBody);
req.end();
});
}
exports.handler = (event, context, callback) => {
try {
processEvent(event, context, callback);
} catch (e) {
callback(e);
}
};
function processEvent(event, context, callback) {
const body = querystring.parse(event.body);
// The JSON object response from Slack
const payload = JSON.parse(body.payload);
// Top-level properties of the message action response object
const callbackId = payload.callback_id;
// Slack signing secret
const slackRequestTimestamp = event.headers['X-Slack-Request-Timestamp'];
const basestring = ['v0', slackRequestTimestamp, event.body].join(':');
const signingSecret = process.env.SLACK_SIGNING_SECRET;
const slackSignature = event.headers['X-Slack-Signature'];
const requestSignature = `v0=${crypto.createHmac('sha256', signingSecret).update(basestring).digest('hex')}`;
if (requestSignature !== slackSignature) {
// Bad request; bogus token
callback(null, { statusCode: 400, headers: {}, body: null });
} else {
// Handle each callback ID appropriately
switch (callbackId) {
case CODEPIPELINE_MANUAL_APPROVAL_CALLBACK:
handleReleaseButtons(payload, callback);
break;
case ROLLBACK_VERSION_SELECTION_CALLBACK:
handleRollbackCallback(payload, callback);
break;
case RELEASE_NOTES_DIALOG_CALLBACK:
handleReleaseNotesDialog(payload, callback);
break;
default:
// Unknown message callback
callback(null, { statusCode: 400, headers: {}, body: null });
}
}
}
function handleReleaseNotesDialog(payload, callback) {
console.log(JSON.stringify(payload));
sns.publish({
TopicArn: process.env.SLACK_MESSAGE_RELAY_TOPIC_ARN,
Message: JSON.stringify({
channel: '#tech-releses',
username: 'Release Notes',
icon_emoji: ':rabbit:',
text: `<@${payload.user.id}>: ${payload.submission.release_notes}`,
}),
}, () => {
callback(null, { statusCode: 200, headers: {}, body: null });
});
}
function handleRollbackCallback(payload, callback) {
const action = payload.actions[0];
switch (action.name) {
case 'selection':
triggerRollback(payload, callback)
break;
default:
cancelRollback(payload, callback);
}
}
function triggerRollback(payload, callback) {
const action = payload.actions[0];
const versionId = action.selected_options[0].value;
const configBucket = process.env.INFRASTRUCTURE_CONFIG_BUCKET;
const configKey = process.env.INFRASTRUCTURE_CONFIG_STAGING_KEY;
const sourceUrl = `${configBucket}/${configKey}?versionId=${versionId}`;
s3.copyObject({
Bucket: configBucket,
CopySource: encodeURI(sourceUrl),
Key: configKey
}, (e, data) => {
if (e) {
console.error(e);
callback(null, { statusCode: 400, headers: {}, body: null });
} else {
const msg = {
text: `Rolling back to config version: ${versionId}`
};
const body = JSON.stringify(msg);
callback(null, { statusCode: 200, headers: {}, body: body });
}
});
}
function cancelRollback(payload, callback) {
const msg = {
text: '_Rollback canceled_'
};
const body = JSON.stringify(msg);
callback(null, { statusCode: 200, headers: {}, body: body });
}
// This will get called for both the Approve and Approve With Notes buttons.
// Both will trigger an IMMEDIATE deploy, but the Aw/N button will also open a
// dialog prompting the user for release notes related to the deploy. (The
// reason the deploy is not delayed until after the release notes dialog is
// because of the added complexity with updating the message in Slack to
// reflect the deployment with the indirection introduced with the dialog. It
// is possible, but was not done to save time.)
function handleReleaseButtons(payload, callback) {
const action = payload.actions[0];
// The manual approval notifications params need to be extracted from
// the action value, where they are stored as stringified JSON data.
const extractedParams = JSON.parse(action.value);
// We're going to immediately update the message that triggered the
// action based on the action taken and the result of that action.
// We'll use the original message as a starting point, but need to
// remove some unnecessary properties before sending it back
const attachment = payload.original_message.attachments[0];
delete attachment.actions;
delete attachment.id;
delete attachment.callback_id;
// Build the params that get sent back to CodePipeline to approve or
// reject the pipeline
const approvalParams = {
pipelineName: extractedParams.pipelineName,
stageName: extractedParams.stageName,
actionName: extractedParams.actionName,
token: extractedParams.token,
result: {
status: extractedParams.value,
summary: 'Handled by Ike'
},
};
codepipeline.putApprovalResult(approvalParams, (err, data) => {
if (err) {
// There was an error making the putApprovalResult request to
// CodePipeline, so the user should be notified that their
// action was not successful
const body = JSON.stringify({ test: `Error: ${err}` });
callback(null, { statusCode: 200, headers: {}, body: body });
} else {
// The putApprovalResult request was successful, so the message
// in Slack should be updated to remove the buttons
const msg = { text: '', attachments: [attachment] };
switch (extractedParams.value) {
case REJECTED:
attachment.text = attachment.text + `\n*<@${payload.user.id}> rejected this deploy*`;
attachment.color = '#de0e0e';
break;
case APPROVED:
attachment.text = attachment.text + `\n:white_check_mark: *<@${payload.user.id}> approved this deploy*`;
attachment.color = '#15da34';
break;
default:
attachment.text = attachment.text + `\nUnknown action by <@${payload.user.id}>`;
attachment.color = '#cd0ede';
}
// The message to replace the one that included the Release buttons
const body = JSON.stringify(msg);
// If the Approve With Notes button was pressed open a dialog,
// otherwise we're done
if (action.name !== 'notes') {
callback(null, { statusCode: 200, headers: {}, body: body });
} else {
slackWebMethod(SLACK_API_DIALOG_OPEN, null, {
trigger_id: payload.trigger_id,
token: process.env.SLACK_ACCESS_TOKEN,
dialog: JSON.stringify({
callback_id: RELEASE_NOTES_DIALOG_CALLBACK,
state: action.value,
title: 'Release Notes',
submit_label: 'Post',
elements: [
{
type: 'textarea',
label: 'Release notes',
name: 'release_notes',
hint: 'These will be posted in #tech-releases.',
},
],
}),
}).then(res => {
callback(null, { statusCode: 200, headers: {}, body: body });
});
}
}
});
}
| Fix tech-releases channel name typo
| notifications/lambdas/ike-interactive-messages-callback-handler/index.js | Fix tech-releases channel name typo | <ide><path>otifications/lambdas/ike-interactive-messages-callback-handler/index.js
<ide> sns.publish({
<ide> TopicArn: process.env.SLACK_MESSAGE_RELAY_TOPIC_ARN,
<ide> Message: JSON.stringify({
<del> channel: '#tech-releses',
<add> channel: '#tech-releases',
<ide> username: 'Release Notes',
<ide> icon_emoji: ':rabbit:',
<ide> text: `<@${payload.user.id}>: ${payload.submission.release_notes}`, |
|
Java | agpl-3.0 | debaea24f3a65c3411c65540d3a1df12f1dabf57 | 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 | 3d00ec2c-2e62-11e5-9284-b827eb9e62be | hello.java | 3cfb79fe-2e62-11e5-9284-b827eb9e62be | 3d00ec2c-2e62-11e5-9284-b827eb9e62be | hello.java | 3d00ec2c-2e62-11e5-9284-b827eb9e62be | <ide><path>ello.java
<del>3cfb79fe-2e62-11e5-9284-b827eb9e62be
<add>3d00ec2c-2e62-11e5-9284-b827eb9e62be |
|
Java | apache-2.0 | b9bad3e9f11f914c3e91847697b9c80747100f8e | 0 | artem-aliev/tinkerpop,rmagen/incubator-tinkerpop,PommeVerte/incubator-tinkerpop,gdelafosse/incubator-tinkerpop,apache/tinkerpop,vtslab/incubator-tinkerpop,RedSeal-co/incubator-tinkerpop,krlohnes/tinkerpop,edgarRd/incubator-tinkerpop,robertdale/tinkerpop,n-tran/incubator-tinkerpop,rmagen/incubator-tinkerpop,artem-aliev/tinkerpop,pluradj/incubator-tinkerpop,apache/tinkerpop,robertdale/tinkerpop,BrynCooke/incubator-tinkerpop,BrynCooke/incubator-tinkerpop,vtslab/incubator-tinkerpop,mike-tr-adamson/incubator-tinkerpop,apache/incubator-tinkerpop,dalaro/incubator-tinkerpop,dalaro/incubator-tinkerpop,apache/tinkerpop,velo/incubator-tinkerpop,n-tran/incubator-tinkerpop,PommeVerte/incubator-tinkerpop,newkek/incubator-tinkerpop,krlohnes/tinkerpop,krlohnes/tinkerpop,samiunn/incubator-tinkerpop,newkek/incubator-tinkerpop,apache/tinkerpop,robertdale/tinkerpop,pluradj/incubator-tinkerpop,mike-tr-adamson/incubator-tinkerpop,gdelafosse/incubator-tinkerpop,apache/tinkerpop,jorgebay/tinkerpop,velo/incubator-tinkerpop,apache/tinkerpop,jorgebay/tinkerpop,samiunn/incubator-tinkerpop,krlohnes/tinkerpop,artem-aliev/tinkerpop,apache/incubator-tinkerpop,artem-aliev/tinkerpop,gdelafosse/incubator-tinkerpop,edgarRd/incubator-tinkerpop,RedSeal-co/incubator-tinkerpop,jorgebay/tinkerpop,BrynCooke/incubator-tinkerpop,newkek/incubator-tinkerpop,pluradj/incubator-tinkerpop,n-tran/incubator-tinkerpop,mike-tr-adamson/incubator-tinkerpop,edgarRd/incubator-tinkerpop,velo/incubator-tinkerpop,RussellSpitzer/incubator-tinkerpop,vtslab/incubator-tinkerpop,apache/tinkerpop,RussellSpitzer/incubator-tinkerpop,rmagen/incubator-tinkerpop,robertdale/tinkerpop,artem-aliev/tinkerpop,dalaro/incubator-tinkerpop,RussellSpitzer/incubator-tinkerpop,robertdale/tinkerpop,apache/incubator-tinkerpop,samiunn/incubator-tinkerpop,krlohnes/tinkerpop,RedSeal-co/incubator-tinkerpop,PommeVerte/incubator-tinkerpop,jorgebay/tinkerpop | package org.apache.tinkerpop.gremlin.process.traversal.strategy.decoration;
import org.apache.tinkerpop.gremlin.process.Traversal;
import org.apache.tinkerpop.gremlin.process.graph.traversal.DefaultGraphTraversal;
import org.apache.tinkerpop.gremlin.process.graph.traversal.__;
import org.apache.tinkerpop.gremlin.process.graph.traversal.step.filter.HasStep;
import org.apache.tinkerpop.gremlin.process.graph.traversal.step.map.AddEdgeByPathStep;
import org.apache.tinkerpop.gremlin.process.graph.traversal.step.map.AddEdgeStep;
import org.apache.tinkerpop.gremlin.process.graph.traversal.step.map.AddVertexStartStep;
import org.apache.tinkerpop.gremlin.process.graph.traversal.step.map.AddVertexStep;
import org.apache.tinkerpop.gremlin.process.graph.traversal.step.sideEffect.GraphStep;
import org.apache.tinkerpop.gremlin.process.graph.util.HasContainer;
import org.apache.tinkerpop.gremlin.process.traversal.util.TraversalHelper;
import org.apache.tinkerpop.gremlin.structure.Contains;
import org.apache.tinkerpop.gremlin.structure.Direction;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.structure.util.ElementHelper;
import org.apache.tinkerpop.gremlin.util.iterator.IteratorUtils;
import org.javatuples.Pair;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
/**
* @author Stephen Mallette (http://stephen.genoprime.com)
*/
@RunWith(Enclosed.class)
public class PartitionStrategyTest {
public static class PartitionKeyBehavior {
@Test(expected = IllegalStateException.class)
public void shouldNotConstructWithoutPartitionKey() {
PartitionStrategy.build().create();
}
@Test
public void shouldConstructPartitionStrategy() {
final PartitionStrategy strategy = PartitionStrategy.build()
.partitionKey("p").writePartition("a").addReadPartition("a").create();
assertEquals("a", strategy.getReadPartitions().iterator().next());
assertEquals(1, strategy.getReadPartitions().size());
assertEquals("p", strategy.getPartitionKey());
}
@Test
public void shouldConstructPartitionStrategyWithMultipleReadPartitions() {
final PartitionStrategy strategy = PartitionStrategy.build()
.partitionKey("p").writePartition("a")
.addReadPartition("a")
.addReadPartition("b")
.addReadPartition("c").create();
assertTrue(IteratorUtils.asList(strategy.getReadPartitions().iterator()).contains("a"));
assertTrue(IteratorUtils.asList(strategy.getReadPartitions().iterator()).contains("b"));
assertTrue(IteratorUtils.asList(strategy.getReadPartitions().iterator()).contains("c"));
assertEquals(3, strategy.getReadPartitions().size());
assertEquals("p", strategy.getPartitionKey());
}
}
@RunWith(Parameterized.class)
public static class TraverseBehavior {
private static Traversal traversalWithAddV;
static {
final Graph mockedGraph = mock(Graph.class);
final DefaultGraphTraversal t = new DefaultGraphTraversal<>(mockedGraph);
t.asAdmin().addStep(new GraphStep<>(t.asAdmin(), Vertex.class));
traversalWithAddV = t.addV();
}
@Parameterized.Parameters(name = "{0}")
public static Iterable<Object[]> data() {
return Arrays.asList(new Object[][]{
{"bothV()", __.bothV(), 1, false},
{"inV()", __.inV(), 1, false},
{"outV()", __.outV(), 1, false},
{"in()", __.in(), 1, false},
{"in(args)", __.in("test"), 1, false},
{"both()", __.both(), 1, false},
{"both(args)", __.both("test"), 1, false},
{"out()", __.out(), 1, false},
{"out(args)", __.out("test"), 1, false},
{"out().inE().otherV", __.out().inE().otherV(), 3, false},
{"addV()", traversalWithAddV, 1, true},
{"addInE()", __.addInE("test", "x"), 0, true},
{"addOutE()", __.addOutE("test", "x"), 0, true},
{"addInE()", __.addInE("test", "x", "other", "args"), 0, true},
{"addOutE()", __.addOutE("test", "x", "other", "args"), 0, true},
{"addE(OUT)", __.addE(Direction.OUT, "test", "x"), 0, true},
{"addE(IN)", __.addE(Direction.IN, "test", "x"), 0, true},
{"in().out()", __.in().out(), 2, false},
{"in().out().addInE()", __.in().out().addInE("test", "x"), 2, true},
{"in().out().addOutE()", __.in().out().addOutE("test", "x"), 2, true},
{"in().out().addE(OUT)", __.in().out().addE(Direction.OUT, "test", "x"), 2, true},
{"in().out().addE(IN)", __.in().out().addE(Direction.IN, "test", "x"), 2, true},
{"out().out().out()", __.out().out().out(), 3, false},
{"in().out().in()", __.in().out().in(), 3, false},
{"inE().outV().inE().outV()", __.inE().outV().inE().outV(), 4, false}});
}
@Parameterized.Parameter(value = 0)
public String name;
@Parameterized.Parameter(value = 1)
public Traversal traversal;
@Parameterized.Parameter(value = 2)
public int expectedInsertedSteps;
@Parameterized.Parameter(value = 3)
public boolean hasMutatingStep;
@Test
public void shouldIncludeAdditionalHasStepsAndAppendPartitionOnMutatingSteps() {
final PartitionStrategy strategy = PartitionStrategy.build()
.partitionKey("p").writePartition("a").addReadPartition("a").create();
if (hasMutatingStep) {
if (TraversalHelper.hasStepOfAssignableClass(AddEdgeStep.class, traversal.asAdmin())) {
final Direction d = TraversalHelper.getStepsOfClass(AddEdgeStep.class, traversal.asAdmin()).get(0).getDirection();
strategy.apply(traversal.asAdmin());
final List<AddEdgeStep> addEdgeSteps = TraversalHelper.getStepsOfAssignableClass(AddEdgeStep.class, traversal.asAdmin());
assertEquals(1, addEdgeSteps.size());
addEdgeSteps.forEach(s -> {
final Object[] keyValues = s.getKeyValues();
final List<Pair<String, Object>> pairs = ElementHelper.asPairs(keyValues);
assertEquals("test", s.getEdgeLabel());
assertEquals(d, s.getDirection());
assertTrue(pairs.stream().anyMatch(p -> p.getValue0().equals("p") && p.getValue1().equals("a")));
});
} else if (TraversalHelper.hasStepOfAssignableClass(AddEdgeByPathStep.class, traversal.asAdmin())) {
final Direction d = TraversalHelper.getStepsOfClass(AddEdgeByPathStep.class, traversal.asAdmin()).get(0).getDirection();
strategy.apply(traversal.asAdmin());
final List<AddEdgeByPathStep> addEdgeSteps = TraversalHelper.getStepsOfAssignableClass(AddEdgeByPathStep.class, traversal.asAdmin());
assertEquals(1, addEdgeSteps.size());
addEdgeSteps.forEach(s -> {
final Object[] keyValues = s.getKeyValues();
final List<Pair<String, Object>> pairs = ElementHelper.asPairs(keyValues);
assertEquals("test", s.getEdgeLabel());
assertEquals(d, s.getDirection());
assertTrue(pairs.stream().anyMatch(p -> p.getValue0().equals("p") && p.getValue1().equals("a")));
});
} else if (TraversalHelper.hasStepOfAssignableClass(AddVertexStep.class, traversal.asAdmin())) {
strategy.apply(traversal.asAdmin());
final List<AddVertexStep> addVertexSteps = TraversalHelper.getStepsOfAssignableClass(AddVertexStep.class, traversal.asAdmin());
assertEquals(1, addVertexSteps.size());
addVertexSteps.forEach(s -> {
final Object[] keyValues = s.getKeyValues();
final List<Pair<String, Object>> pairs = ElementHelper.asPairs(keyValues);
assertTrue(pairs.stream().anyMatch(p -> p.getValue0().equals("p") && p.getValue1().equals("a")));
});
} else if (TraversalHelper.hasStepOfAssignableClass(AddVertexStartStep.class, traversal.asAdmin())) {
strategy.apply(traversal.asAdmin());
final List<AddVertexStartStep> addVertexSteps = TraversalHelper.getStepsOfAssignableClass(AddVertexStartStep.class, traversal.asAdmin());
assertEquals(1, addVertexSteps.size());
addVertexSteps.forEach(s -> {
final Object[] keyValues = s.getKeyValues();
final List<Pair<String, Object>> pairs = ElementHelper.asPairs(keyValues);
assertTrue(pairs.stream().anyMatch(p -> p.getValue0().equals("p") && p.getValue1().equals("a")));
});
} else
fail("This test should not be marked as having a mutating step or there is something else amiss.");
} else {
strategy.apply(traversal.asAdmin());
}
final List<HasStep> steps = TraversalHelper.getStepsOfClass(HasStep.class, traversal.asAdmin());
assertEquals(expectedInsertedSteps, steps.size());
final List<String> keySet = new ArrayList<>(strategy.getReadPartitions());
steps.forEach(s -> {
assertEquals(1, s.getHasContainers().size());
final HasContainer hasContainer = (HasContainer) s.getHasContainers().get(0);
assertEquals("p", hasContainer.key);
assertEquals(keySet, hasContainer.value);
assertEquals(Contains.within, hasContainer.predicate);
});
}
}
}
| gremlin-core/src/test/java/org/apache/tinkerpop/gremlin/process/traversal/strategy/decoration/PartitionStrategyTest.java | package org.apache.tinkerpop.gremlin.process.traversal.strategy.decoration;
import org.apache.tinkerpop.gremlin.process.Traversal;
import org.apache.tinkerpop.gremlin.process.graph.traversal.DefaultGraphTraversal;
import org.apache.tinkerpop.gremlin.process.graph.traversal.__;
import org.apache.tinkerpop.gremlin.process.graph.traversal.step.filter.HasStep;
import org.apache.tinkerpop.gremlin.process.graph.traversal.step.map.AddEdgeByPathStep;
import org.apache.tinkerpop.gremlin.process.graph.traversal.step.map.AddEdgeStep;
import org.apache.tinkerpop.gremlin.process.graph.traversal.step.map.AddVertexStartStep;
import org.apache.tinkerpop.gremlin.process.graph.traversal.step.map.AddVertexStep;
import org.apache.tinkerpop.gremlin.process.graph.traversal.step.sideEffect.GraphStep;
import org.apache.tinkerpop.gremlin.process.graph.util.HasContainer;
import org.apache.tinkerpop.gremlin.process.traversal.util.TraversalHelper;
import org.apache.tinkerpop.gremlin.structure.Contains;
import org.apache.tinkerpop.gremlin.structure.Direction;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.structure.util.ElementHelper;
import org.apache.tinkerpop.gremlin.util.iterator.IteratorUtils;
import org.javatuples.Pair;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
/**
* @author Stephen Mallette (http://stephen.genoprime.com)
*/
@RunWith(Enclosed.class)
public class PartitionStrategyTest {
public static class PartitionKeyBehavior {
@Test(expected = IllegalStateException.class)
public void shouldNotConstructWithoutPartitionKey() {
PartitionStrategy.build().create();
}
@Test
public void shouldConstructPartitionStrategy() {
final PartitionStrategy strategy = PartitionStrategy.build()
.partitionKey("p").writePartition("a").addReadPartition("a").create();
assertEquals("a", strategy.getReadPartitions().iterator().next());
assertEquals(1, strategy.getReadPartitions().size());
assertEquals("p", strategy.getPartitionKey());
}
@Test
public void shouldConstructPartitionStrategyWithMultipleReadPartitions() {
final PartitionStrategy strategy = PartitionStrategy.build()
.partitionKey("p").writePartition("a")
.addReadPartition("a")
.addReadPartition("b")
.addReadPartition("c").create();
assertTrue(IteratorUtils.asList(strategy.getReadPartitions().iterator()).contains("a"));
assertTrue(IteratorUtils.asList(strategy.getReadPartitions().iterator()).contains("b"));
assertTrue(IteratorUtils.asList(strategy.getReadPartitions().iterator()).contains("c"));
assertEquals(3, strategy.getReadPartitions().size());
assertEquals("p", strategy.getPartitionKey());
}
}
@RunWith(Parameterized.class)
public static class TraverseBehavior {
private static Traversal traversalWithAddV;
static {
final Graph mockedGraph = mock(Graph.class);
final DefaultGraphTraversal t = new DefaultGraphTraversal<>(mockedGraph);
t.asAdmin().addStep(new GraphStep<>(t.asAdmin(), Vertex.class));
traversalWithAddV = t.addV();
}
@Parameterized.Parameters(name = "{0}")
public static Iterable<Object[]> data() {
return Arrays.asList(new Object[][]{
{"bothV()", __.bothV(), 1, false},
{"inV()", __.inV(), 1, false},
{"outV()", __.outV(), 1, false},
{"in()", __.in(), 1, false},
{"in(args)", __.in("test"), 1, false},
{"both()", __.both(), 1, false},
{"both(args)", __.both("test"), 1, false},
{"out()", __.out(), 1, false},
{"out(args)", __.out("test"), 1, false},
{"out().inE().otherV", __.out().inE().otherV(), 3, false},
{"addV()", traversalWithAddV, 1, true},
{"addInE()", __.addInE("test", "x"), 0, true},
{"addOutE()", __.addOutE("test", "x"), 0, true},
{"addInE()", __.addInE("test", "x", "other", "args"), 0, true},
{"addOutE()", __.addOutE("test", "x", "other", "args"), 0, true},
{"addBothE(OUT)", __.addE(Direction.OUT, "test", "x"), 0, true},
{"addBothE(IN)", __.addE(Direction.IN, "test", "x"), 0, true},
{"in().out()", __.in().out(), 2, false},
{"out().out().out()", __.out().out().out(), 3, false},
{"in().out().in()", __.in().out().in(), 3, false},
{"inE().outV().inE().outV()", __.inE().outV().inE().outV(), 4, false}});
}
@Parameterized.Parameter(value = 0)
public String name;
@Parameterized.Parameter(value = 1)
public Traversal traversal;
@Parameterized.Parameter(value = 2)
public int expectedInsertedSteps;
@Parameterized.Parameter(value = 3)
public boolean hasMutatingStep;
@Test
public void shouldIncludeAdditionalHasStepsAndAppendPartitionOnMutatingSteps() {
final PartitionStrategy strategy = PartitionStrategy.build()
.partitionKey("p").writePartition("a").addReadPartition("a").create();
if (hasMutatingStep) {
if (TraversalHelper.hasStepOfAssignableClass(AddEdgeStep.class, traversal.asAdmin())) {
final Direction d = TraversalHelper.getStepsOfClass(AddEdgeStep.class, traversal.asAdmin()).get(0).getDirection();
strategy.apply(traversal.asAdmin());
final List<AddEdgeStep> addEdgeSteps = TraversalHelper.getStepsOfAssignableClass(AddEdgeStep.class, traversal.asAdmin());
assertEquals(1, addEdgeSteps.size());
addEdgeSteps.forEach(s -> {
final Object[] keyValues = s.getKeyValues();
final List<Pair<String, Object>> pairs = ElementHelper.asPairs(keyValues);
assertEquals("test", s.getEdgeLabel());
assertEquals(d, s.getDirection());
assertTrue(pairs.stream().anyMatch(p -> p.getValue0().equals("p") && p.getValue1().equals("a")));
});
} else if (TraversalHelper.hasStepOfAssignableClass(AddEdgeByPathStep.class, traversal.asAdmin())) {
final Direction d = TraversalHelper.getStepsOfClass(AddEdgeByPathStep.class, traversal.asAdmin()).get(0).getDirection();
strategy.apply(traversal.asAdmin());
final List<AddEdgeByPathStep> addEdgeSteps = TraversalHelper.getStepsOfAssignableClass(AddEdgeByPathStep.class, traversal.asAdmin());
assertEquals(1, addEdgeSteps.size());
addEdgeSteps.forEach(s -> {
final Object[] keyValues = s.getKeyValues();
final List<Pair<String, Object>> pairs = ElementHelper.asPairs(keyValues);
assertEquals("test", s.getEdgeLabel());
assertEquals(d, s.getDirection());
assertTrue(pairs.stream().anyMatch(p -> p.getValue0().equals("p") && p.getValue1().equals("a")));
});
} else if (TraversalHelper.hasStepOfAssignableClass(AddVertexStep.class, traversal.asAdmin())) {
strategy.apply(traversal.asAdmin());
final List<AddVertexStep> addVertexSteps = TraversalHelper.getStepsOfAssignableClass(AddVertexStep.class, traversal.asAdmin());
assertEquals(1, addVertexSteps.size());
addVertexSteps.forEach(s -> {
final Object[] keyValues = s.getKeyValues();
final List<Pair<String, Object>> pairs = ElementHelper.asPairs(keyValues);
assertTrue(pairs.stream().anyMatch(p -> p.getValue0().equals("p") && p.getValue1().equals("a")));
});
} else if (TraversalHelper.hasStepOfAssignableClass(AddVertexStartStep.class, traversal.asAdmin())) {
strategy.apply(traversal.asAdmin());
final List<AddVertexStartStep> addVertexSteps = TraversalHelper.getStepsOfAssignableClass(AddVertexStartStep.class, traversal.asAdmin());
assertEquals(1, addVertexSteps.size());
addVertexSteps.forEach(s -> {
final Object[] keyValues = s.getKeyValues();
final List<Pair<String, Object>> pairs = ElementHelper.asPairs(keyValues);
assertTrue(pairs.stream().anyMatch(p -> p.getValue0().equals("p") && p.getValue1().equals("a")));
});
} else
fail("This test should not be marked as having a mutating step or there is something else amiss.");
} else {
strategy.apply(traversal.asAdmin());
}
final List<HasStep> steps = TraversalHelper.getStepsOfClass(HasStep.class, traversal.asAdmin());
assertEquals(expectedInsertedSteps, steps.size());
final List<String> keySet = new ArrayList<>(strategy.getReadPartitions());
steps.forEach(s -> {
assertEquals(1, s.getHasContainers().size());
final HasContainer hasContainer = (HasContainer) s.getHasContainers().get(0);
assertEquals("p", hasContainer.key);
assertEquals(keySet, hasContainer.value);
assertEquals(Contains.within, hasContainer.predicate);
});
}
}
}
| Add more tests for PartitionStrategy.
| gremlin-core/src/test/java/org/apache/tinkerpop/gremlin/process/traversal/strategy/decoration/PartitionStrategyTest.java | Add more tests for PartitionStrategy. | <ide><path>remlin-core/src/test/java/org/apache/tinkerpop/gremlin/process/traversal/strategy/decoration/PartitionStrategyTest.java
<ide> {"addOutE()", __.addOutE("test", "x"), 0, true},
<ide> {"addInE()", __.addInE("test", "x", "other", "args"), 0, true},
<ide> {"addOutE()", __.addOutE("test", "x", "other", "args"), 0, true},
<del> {"addBothE(OUT)", __.addE(Direction.OUT, "test", "x"), 0, true},
<del> {"addBothE(IN)", __.addE(Direction.IN, "test", "x"), 0, true},
<add> {"addE(OUT)", __.addE(Direction.OUT, "test", "x"), 0, true},
<add> {"addE(IN)", __.addE(Direction.IN, "test", "x"), 0, true},
<ide> {"in().out()", __.in().out(), 2, false},
<add> {"in().out().addInE()", __.in().out().addInE("test", "x"), 2, true},
<add> {"in().out().addOutE()", __.in().out().addOutE("test", "x"), 2, true},
<add> {"in().out().addE(OUT)", __.in().out().addE(Direction.OUT, "test", "x"), 2, true},
<add> {"in().out().addE(IN)", __.in().out().addE(Direction.IN, "test", "x"), 2, true},
<ide> {"out().out().out()", __.out().out().out(), 3, false},
<ide> {"in().out().in()", __.in().out().in(), 3, false},
<ide> {"inE().outV().inE().outV()", __.inE().outV().inE().outV(), 4, false}}); |
|
Java | apache-2.0 | ff34cee604a7e169515e54e8590c81197cd9ee7d | 0 | pcollaog/velocity-engine,diydyq/velocity-engine,pcollaog/velocity-engine,diydyq/velocity-engine | package org.apache.velocity.convert;
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 2001 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Velocity", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
import java.io.File;
import java.io.FileWriter;
import org.apache.oro.text.perl.Perl5Util;
import org.apache.velocity.util.StringUtils;
import org.apache.tools.ant.DirectoryScanner;
/**
* This class will convert a WebMacro template to
* a Velocity template. Uses the ORO Regexp package to do the
* rewrites. Note, it isn't 100% perfect, but will definitely get
* you about 99.99% of the way to a converted system. Please
* see the website documentation for more information on how to use
* this class.
*
* @author <a href="mailto:[email protected]">Jason van Zyl</a>
* @author <a href="mailto:[email protected]">Daniel Rall</a>
* @version $Id: WebMacro.java,v 1.15 2001/05/12 02:14:41 dlr Exp $
*/
public class WebMacro
{
protected static final String VM_EXT = ".vm";
protected static final String WM_EXT = ".wm";
/**
* The regexes to use for line by line substition. The regexes
* come in pairs. The first is the string to match, the second is
* the substitution to make.
*/
protected static String[] perLineREs =
{
// Make #if directive match the Velocity directive style.
"#if\\s*[(]\\s*(.*\\S)\\s*[)]\\s*(#begin|{)[ \\t]?",
"#if( $1 )",
// Remove the WM #end #else #begin usage.
"[ \\t]?(#end|})[ \\t]*\n(\\s*)#else\\s*(#begin|{)[ \\t]?(\\w)",
"$2#else#**#$4", // avoid touching followup word with embedded comment
"[ \\t]?(#end|})[ \\t]*\n(\\s*)#else\\s*(#begin|{)[ \\t]?",
"$2#else",
"(#end|})(\\s*#else)\\s*(#begin|{)[ \\t]?",
"$1\n$2",
// Convert WM style #foreach to Velocity directive style.
"#foreach\\s+(\\$\\w+)\\s+in\\s+(\\$[^\\s#]+)\\s*(#begin|{)[ \\t]?",
"#foreach( $1 in $2 )",
// Convert WM style #set to Velocity directive style.
"#set\\s+(\\$[^\\s=]+)\\s*=\\s*([\\S]+)[ \\t]*",
"#set( $1 = $2 )",
"(##[# \\t\\w]*)\\)", // fix comments included at end of line
")$1",
// Convert WM style #parse to Velocity directive style.
"#parse\\s+([^\\s#]+)[ \\t]?",
"#parse( $1 )",
// Convert WM style #include to Velocity directive style.
"#include\\s+([^\\s#]+)[ \\t]?",
"#include( $1 )",
// Convert WM formal reference to VTL syntax.
"\\$\\(([^\\)]+)\\)",
"${$1}",
"\\${([^}\\(]+)\\(([^}]+)}\\)", // fix encapsulated brakets: {(})
"${$1($2)}",
// Velocity currently does not permit leading underscore.
"\\$_",
"$l_",
"\\${(_[^}]+)}", // within a formal reference
"${l$1}",
// Convert explicitly terminated WM statements to VTL syntax.
"(^|[^\\\\])\\$([\\w]+);",
"$1${$2}",
// Change extensions when seen.
"\\.wm",
".vm"
};
/**
* Iterate through the set of find/replace regexes
* that will convert a given WM template to a VM template
*/
public void convert(String target)
{
File file = new File(target);
if (!file.exists())
{
System.err.println
("The specified template or directory does not exist");
System.exit(1);
}
if (file.isDirectory())
{
String basedir = file.getAbsolutePath();
String newBasedir = basedir + VM_EXT;
DirectoryScanner ds = new DirectoryScanner();
ds.setBasedir(basedir);
ds.addDefaultExcludes();
ds.scan();
String[] files = ds.getIncludedFiles();
for (int i = 0; i < files.length; i++)
{
writeTemplate(files[i], basedir, newBasedir);
}
}
else
{
writeTemplate(file.getAbsolutePath(), "", "");
}
}
/**
* Write out the converted template to the given named file
* and base directory.
*/
private boolean writeTemplate(String file, String basedir,
String newBasedir)
{
if (file.indexOf(WM_EXT) < 0)
{
return false;
}
System.out.println("Converting " + file + "...");
String template;
String templateDir;
String newTemplate;
File outputDirectory;
if (basedir.length() == 0)
{
template = file;
templateDir = "";
newTemplate = convertName(file);
}
else
{
template = basedir + File.separator + file;
templateDir = newBasedir + extractPath(file);
outputDirectory = new File(templateDir);
if (! outputDirectory.exists())
{
outputDirectory.mkdirs();
}
newTemplate = newBasedir + File.separator + convertName(file);
}
String convertedTemplate = convertTemplate(template);
try
{
FileWriter fw = new FileWriter(newTemplate);
fw.write(convertedTemplate);
fw.close();
}
catch (Exception e)
{
e.printStackTrace();
}
return true;
}
/**
* Gets the path segment of the full path to a file (i.e. one
* which originally included the file name).
*/
private final String extractPath(String file)
{
int lastSepPos = file.lastIndexOf(File.separator);
return (lastSepPos == -1 ? "" :
File.separator + file.substring(0, lastSepPos));
}
/**
* Simple extension conversion of .wm to .vm
*/
private String convertName(String name)
{
if (name.indexOf(WM_EXT) > 0)
{
return name.substring(0, name.indexOf(WM_EXT)) + VM_EXT;
}
else
{
return name;
}
}
/**
* How to use this little puppy :-)
*/
private static final void usage()
{
System.err.println("Usage: convert-wm <template.wm | directory>");
System.exit(1);
}
/**
* Apply find/replace regexes to our WM template
*/
public String convertTemplate(String template)
{
String contents = StringUtils.fileContentsToString(template);
// Overcome Velocity 0.71 limitation.
// HELP: Is this still necessary?
if (!contents.endsWith("\n"))
{
contents += "\n";
}
// Convert most markup.
Perl5Util perl = new Perl5Util();
for (int i = 0; i < perLineREs.length; i += 2)
{
contents = perl.substitute(makeSubstRE(i), contents);
}
// Convert closing curlies.
if (perl.match("m/javascript/i", contents))
{
// ASSUMPTION: JavaScript is indented, WM is not.
contents = perl.substitute("s/\n}/\n#end/g", contents);
}
else
{
contents = perl.substitute("s/(\n\\s*)}/$1#end/g", contents);
contents = perl.substitute("s/#end\\s*\n\\s*#else/#else/g",
contents);
}
return contents;
}
/**
* Makes a Perl 5 regular expression for use by ORO.
*/
private final String makeSubstRE(int i)
{
return ("s/" + perLineREs[i] + '/' + perLineREs[i + 1] + "/g");
}
/**
* Main hook for the conversion process.
*/
public static void main(String[] args)
{
if (args.length > 0)
{
WebMacro converter = new WebMacro();
converter.convert(args[0]);
}
else
{
usage();
}
}
}
| src/java/org/apache/velocity/convert/WebMacro.java | package org.apache.velocity.convert;
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 2001 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Velocity", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
import java.io.File;
import java.io.FileWriter;
import org.apache.oro.text.perl.Perl5Util;
import org.apache.velocity.util.StringUtils;
import org.apache.tools.ant.DirectoryScanner;
/**
* This class will convert a WebMacro template to
* a Velocity template. Uses the ORO Regexp package to do the
* rewrites. Note, it isn't 100% perfect, but will definitely get
* you about 99.99% of the way to a converted system. Please
* see the website documentation for more information on how to use
* this class.
*
* @author <a href="mailto:[email protected]">Jason van Zyl</a>
* @author <a href="mailto:[email protected]">Daniel Rall</a>
* @version $Id: WebMacro.java,v 1.14 2001/05/12 02:04:25 dlr Exp $
*/
public class WebMacro
{
protected static final String VM_EXT = ".vm";
protected static final String WM_EXT = ".wm";
/**
* The regexes to use for line by line substition. The regexes
* come in pairs. The first is the string to match, the second is
* the substitution to make.
*/
protected static String[] perLineREs =
{
// Make #if directive match the Velocity directive style.
"#if\\s*[(]\\s*(.*\\S)\\s*[)]\\s*(#begin|{)[ \\t]?",
"#if( $1 )",
// Remove the WM #end #else #begin usage.
"[ \\t]?(#end|})[ \\t]*\n(\\s*)#else\\s*(#begin|{)[ \\t]?(\\w)",
"$2#else#**#$4", // avoid touching followup word with embedded comment
"[ \\t]?(#end|})[ \\t]*\n(\\s*)#else\\s*(#begin|{)[ \\t]?",
"$2#else",
"(#end|})(\\s*#else)\\s*(#begin|{)[ \\t]?",
"$1\n$2",
// Convert WM style #foreach to Velocity directive style.
"#foreach\\s+(\\$\\w+)\\s+in\\s+(\\$[^\\s#]+)\\s*(#begin|{)[ \\t]?",
"#foreach( $1 in $2 )",
// Change the "}" to #end. Have to get more
// sophisticated here. Will assume either {}
// and no javascript, or #begin/#end with the
// possibility of javascript.
"\n}", // assumes that javascript is indented, WMs not!!!
"\n#end",
// Convert WM style #set to Velocity directive style.
"#set\\s+(\\$[^\\s=]+)\\s*=\\s*([\\S]+)[ \\t]*",
"#set( $1 = $2 )",
"(##[# \\t\\w]*)\\)", // fix comments included at end of line
")$1",
// Convert WM style #parse to Velocity directive style.
"#parse\\s+([^\\s#]+)[ \\t]?",
"#parse( $1 )",
// Convert WM style #include to Velocity directive style.
"#include\\s+([^\\s#]+)[ \\t]?",
"#include( $1 )",
// Convert WM formal reference to VTL syntax.
"\\$\\(([^\\)]+)\\)",
"${$1}",
"\\${([^}\\(]+)\\(([^}]+)}\\)", // fix encapsulated brakets: {(})
"${$1($2)}",
// Velocity currently does not permit leading underscore.
"\\$_",
"$l_",
"\\${(_[^}]+)}", // within a formal reference
"${l$1}",
// Convert explicitly terminated WM statements to VTL syntax.
"(^|[^\\\\])\\$([\\w]+);",
"$1${$2}",
// Change extensions when seen.
"\\.wm",
".vm"
};
/**
* Iterate through the set of find/replace regexes
* that will convert a given WM template to a VM template
*/
public void convert(String target)
{
File file = new File(target);
if (!file.exists())
{
System.err.println
("The specified template or directory does not exist");
System.exit(1);
}
if (file.isDirectory())
{
String basedir = file.getAbsolutePath();
String newBasedir = basedir + VM_EXT;
DirectoryScanner ds = new DirectoryScanner();
ds.setBasedir(basedir);
ds.addDefaultExcludes();
ds.scan();
String[] files = ds.getIncludedFiles();
for (int i = 0; i < files.length; i++)
{
writeTemplate(files[i], basedir, newBasedir);
}
}
else
{
writeTemplate(file.getAbsolutePath(), "", "");
}
}
/**
* Write out the converted template to the given named file
* and base directory.
*/
private boolean writeTemplate(String file, String basedir,
String newBasedir)
{
if (file.indexOf(WM_EXT) < 0)
{
return false;
}
System.out.println("Converting " + file + "...");
String template;
String templateDir;
String newTemplate;
File outputDirectory;
if (basedir.length() == 0)
{
template = file;
templateDir = "";
newTemplate = convertName(file);
}
else
{
template = basedir + File.separator + file;
templateDir = newBasedir + extractPath(file);
outputDirectory = new File(templateDir);
if (! outputDirectory.exists())
{
outputDirectory.mkdirs();
}
newTemplate = newBasedir + File.separator + convertName(file);
}
String convertedTemplate = convertTemplate(template);
try
{
FileWriter fw = new FileWriter(newTemplate);
fw.write(convertedTemplate);
fw.close();
}
catch (Exception e)
{
e.printStackTrace();
}
return true;
}
/**
* Gets the path segment of the full path to a file (i.e. one
* which originally included the file name).
*/
private final String extractPath(String file)
{
int lastSepPos = file.lastIndexOf(File.separator);
return (lastSepPos == -1 ? "" :
File.separator + file.substring(0, lastSepPos));
}
/**
* Simple extension conversion of .wm to .vm
*/
private String convertName(String name)
{
if (name.indexOf(WM_EXT) > 0)
{
return name.substring(0, name.indexOf(WM_EXT)) + VM_EXT;
}
else
{
return name;
}
}
/**
* How to use this little puppy :-)
*/
private static final void usage()
{
System.err.println("Usage: convert-wm <template.wm | directory>");
System.exit(1);
}
/**
* Apply find/replace regexes to our WM template
*/
public String convertTemplate(String template)
{
String contents = StringUtils.fileContentsToString(template);
// Overcome Velocity 0.71 limitation.
// HELP: Is this still necessary?
if (!contents.endsWith("\n"))
{
contents += "\n";
}
// Convert most markup.
Perl5Util perl = new Perl5Util();
for (int i = 0; i < perLineREs.length; i += 2)
{
contents = perl.substitute(makeSubstRE(i), contents);
}
// Convert closing curlies.
if (perl.match("m/javascript/i", contents))
{
// ASSUMPTION: JavaScript is indented, WM is not.
contents = perl.substitute("s/\n}/\n#end/g", contents);
}
else
{
contents = perl.substitute("s/(\n\\s*)}/$1#end/g", contents);
contents = perl.substitute("s/#end\\s*\n\\s*#else/#else/g",
contents);
}
return contents;
}
/**
* Makes a Perl 5 regular expression for use by ORO.
*/
private final String makeSubstRE(int i)
{
return ("s/" + perLineREs[i] + '/' + perLineREs[i + 1] + "/g");
}
/**
* Main hook for the conversion process.
*/
public static void main(String[] args)
{
if (args.length > 0)
{
WebMacro converter = new WebMacro();
converter.convert(args[0]);
}
else
{
usage();
}
}
}
| Removed regex from data set which is now executed in during a separate
pass (moved by last commit).
git-svn-id: 7267684f36935cb3df12efc1f4c0216d758271d4@74957 13f79535-47bb-0310-9956-ffa450edef68
| src/java/org/apache/velocity/convert/WebMacro.java | Removed regex from data set which is now executed in during a separate pass (moved by last commit). | <ide><path>rc/java/org/apache/velocity/convert/WebMacro.java
<ide> *
<ide> * @author <a href="mailto:[email protected]">Jason van Zyl</a>
<ide> * @author <a href="mailto:[email protected]">Daniel Rall</a>
<del> * @version $Id: WebMacro.java,v 1.14 2001/05/12 02:04:25 dlr Exp $
<add> * @version $Id: WebMacro.java,v 1.15 2001/05/12 02:14:41 dlr Exp $
<ide> */
<ide> public class WebMacro
<ide> {
<ide> // Convert WM style #foreach to Velocity directive style.
<ide> "#foreach\\s+(\\$\\w+)\\s+in\\s+(\\$[^\\s#]+)\\s*(#begin|{)[ \\t]?",
<ide> "#foreach( $1 in $2 )",
<del>
<del> // Change the "}" to #end. Have to get more
<del> // sophisticated here. Will assume either {}
<del> // and no javascript, or #begin/#end with the
<del> // possibility of javascript.
<del> "\n}", // assumes that javascript is indented, WMs not!!!
<del> "\n#end",
<ide>
<ide> // Convert WM style #set to Velocity directive style.
<ide> "#set\\s+(\\$[^\\s=]+)\\s*=\\s*([\\S]+)[ \\t]*", |
|
JavaScript | mit | 0ead1a16bb9d2d76f8aba95c15c95655919301e7 | 0 | kleinfreund/kleinfreund.de | const path = require('path');
const fs = require('fs');
const CleanCSS = require('clean-css');
const htmlMinifier = require('html-minifier');
const markdownIt = require('markdown-it');
// https://github.com/kangax/html-minifier#options-quick-reference
const htmlMinifierOptions = {
useShortDoctype: true,
removeComments: true,
collapseWhitespace: true
};
// https://github.com/markdown-it/markdown-it#init-with-presets-and-options
const markdownItOptions = {
html: true
};
// https://github.com/valeriangalliat/markdown-it-anchor#usage
const markdownItAnchorOptions = {
permalink: true,
permalinkSymbol: '��',
permalinkBefore: true
};
module.exports = function (eleventyConfig) {
eleventyConfig.setLiquidOptions({
dynamicPartials: true,
strict_filters: true
});
eleventyConfig.setDataDeepMerge(true);
// Copies static files as they are to the output directory
eleventyConfig
.addPassthroughCopy('src/img')
.addPassthroughCopy('src/css')
.addPassthroughCopy('src/favicon.ico')
.addPassthroughCopy('src/.htaccess')
.addPassthroughCopy('src/manifest.webmanifest');
const markdownLib = markdownIt(markdownItOptions)
.use(require('markdown-it-anchor'), markdownItAnchorOptions);
eleventyConfig.setLibrary('md', markdownLib);
// Defines shortcode for generating post excerpts
eleventyConfig.addShortcode('excerpt', post => extractExcerpt(post));
// Filter for compressing CSS
eleventyConfig.addFilter('resolve_css_imports', resolveCssImports);
eleventyConfig.addFilter('minify_css', minifyCss);
// Compresses output HTML
if (process.env.ELEVENTY_ENV === 'production') {
eleventyConfig.addTransform('minify_html', minifyHtml);
}
return {
dir: {
input: 'src',
// Setting `dir.includes` to the empty string effectively makes the project directory the
// include directory; thus, allowing to include files from across the project instead of
// just a dedicated includes directory.
includes: ''
},
templateFormats: ['md', 'liquid', 'html']
};
};
/**
* @param {String} mainCssPath
* @returns {String}
*/
function resolveCssImports(mainCssPath) {
const mainCssContent = fs.readFileSync(path.join('src', mainCssPath), 'utf8');
const importRules = mainCssContent.split('\n').filter(line => line.startsWith('@import'));
const importPaths = importRules.map(importRule => {
return path.join('src', importRule.replace('@import \'', '').replace('\';', ''));
});
let concatenatedCssContent = '';
for (const importPath of importPaths) {
concatenatedCssContent += fs.readFileSync(importPath, 'utf8');
}
return concatenatedCssContent;
}
/**
* Minifies CSS content.
*
* @param {String} concatenatedCssContent
* @returns {String} the minified CSS content
*/
function minifyCss(concatenatedCssContent) {
const minifyResult = new CleanCSS().minify(concatenatedCssContent);
if (minifyResult.errors.length > 0) {
console.error('❌ Could not minify CSS.');
minifyResult.errors.forEach(error => { console.error('❌', error) });
return concatenatedCssContent;
}
return minifyResult.styles;
}
/**
* Minifies HTML content.
*
* @param {String} content
* @param {String} outputPath
* @returns {String} the minified HTML content
*/
function minifyHtml(content, outputPath) {
if (outputPath.endsWith('.html')) {
return htmlMinifier.minify(content, htmlMinifierOptions);
}
return content;
}
/**
* Extracts the excerpt from a document.
*
* @param {*} doc A real big object full of all sorts of information about a document.
* @returns {String} the excerpt.
*/
function extractExcerpt(doc) {
if (!doc.hasOwnProperty('templateContent')) {
console.warn('❌ Failed to extract excerpt: Document has no property `templateContent`.');
return;
}
const excerptSeparator = '<!--more-->';
const content = doc.templateContent;
if (content.includes(excerptSeparator)) {
return content.substring(0, content.indexOf(excerptSeparator)).trim();
}
if (content.includes('</p>')) {
return content.substring(0, content.indexOf('</p>') + 4);
}
return content;
}
| .eleventy.js | const path = require('path');
const fs = require('fs');
const CleanCSS = require('clean-css');
const htmlMinifier = require('html-minifier');
const markdownIt = require('markdown-it');
// https://github.com/kangax/html-minifier#options-quick-reference
const htmlMinifierOptions = {
useShortDoctype: true,
removeComments: true,
collapseWhitespace: true
};
// https://github.com/markdown-it/markdown-it#init-with-presets-and-options
const markdownItOptions = {
html: true
};
// https://github.com/valeriangalliat/markdown-it-anchor#usage
const markdownItAnchorOptions = {
permalink: true,
permalinkSymbol: '��',
permalinkBefore: true
};
module.exports = function (eleventyConfig) {
eleventyConfig.setLiquidOptions({
dynamicPartials: true,
strict_filters: true
});
eleventyConfig.setDataDeepMerge(true);
// Copies static files as they are to the output directory
eleventyConfig
.addPassthroughCopy('src/img')
.addPassthroughCopy('src/css')
.addPassthroughCopy('src/favicon.ico')
.addPassthroughCopy('src/.htaccess')
.addPassthroughCopy('src/manifest.webmanifest');
const markdownLib = markdownIt(markdownItOptions)
.use(require('markdown-it-anchor'), markdownItAnchorOptions);
eleventyConfig.setLibrary('md', markdownLib);
// Defines shortcode for generating post excerpts
eleventyConfig.addShortcode('excerpt', post => extractExcerpt(post));
// Filter for compressing CSS
eleventyConfig.addFilter('resolve_css_imports', resolveCssImports);
eleventyConfig.addFilter('minify_css', minifyCss);
// Compresses output HTML
if (process.env.ELEVENTY_ENV === 'production') {
eleventyConfig.addTransform('minify_html', minifyHtml);
}
return {
dir: {
input: 'src',
// Setting `dir.includes` to the empty string effectively makes the project directory the
// include directory; thus, allowing to include files from across the project instead of
// just a dedicated includes directory.
includes: ''
},
templateFormats: ['md', 'liquid', 'html']
};
};
function resolveCssImports(mainCssPath) {
const mainCssContent = fs.readFileSync(path.join('src', mainCssPath), 'utf8');
const importRules = mainCssContent.split('\n').filter(line => line.startsWith('@import'));
const importPaths = importRules.map(importRule => {
return path.join('src', importRule.replace('@import \'', '').replace('\';', ''));
});
let concatenatedCssContent = '';
for (const importPath of importPaths) {
concatenatedCssContent += fs.readFileSync(importPath, 'utf8');
}
return concatenatedCssContent;
}
/**
* Minifies CSS content.
*
* @param {String} concatenatedCssContent
* @returns {String} the minified CSS content
*/
function minifyCss(concatenatedCssContent) {
const minifyResult = new CleanCSS().minify(concatenatedCssContent);
if (minifyResult.errors.length > 0) {
console.error('❌ Could not minify CSS.');
minifyResult.errors.forEach(error => { console.error('❌', error) });
return concatenatedCssContent;
}
return minifyResult.styles;
}
/**
* Minifies HTML content.
*
* @param {String} content
* @param {String} outputPath
* @returns {String} the minified HTML content
*/
function minifyHtml(content, outputPath) {
if (outputPath.endsWith('.html')) {
return htmlMinifier.minify(content, htmlMinifierOptions);
}
return content;
}
/**
* Extracts the excerpt from a document.
*
* @param {*} doc A real big object full of all sorts of information about a document.
* @returns {String} the excerpt.
*/
function extractExcerpt(doc) {
if (!doc.hasOwnProperty('templateContent')) {
console.warn('❌ Failed to extract excerpt: Document has no property `templateContent`.');
return;
}
const excerptSeparator = '<!--more-->';
const content = doc.templateContent;
if (content.includes(excerptSeparator)) {
return content.substring(0, content.indexOf(excerptSeparator)).trim();
}
if (content.includes('</p>')) {
return content.substring(0, content.indexOf('</p>') + 4);
}
return content;
}
| (Add type parameters to function)
| .eleventy.js | (Add type parameters to function) | <ide><path>eleventy.js
<ide> };
<ide> };
<ide>
<add>
<add>/**
<add> * @param {String} mainCssPath
<add> * @returns {String}
<add> */
<ide> function resolveCssImports(mainCssPath) {
<ide> const mainCssContent = fs.readFileSync(path.join('src', mainCssPath), 'utf8');
<ide> const importRules = mainCssContent.split('\n').filter(line => line.startsWith('@import')); |
|
Java | agpl-3.0 | f3df7ae665107beb362fdad9bb01ee38d25e78ea | 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 | 495a6e5a-2e60-11e5-9284-b827eb9e62be | hello.java | 4954f664-2e60-11e5-9284-b827eb9e62be | 495a6e5a-2e60-11e5-9284-b827eb9e62be | hello.java | 495a6e5a-2e60-11e5-9284-b827eb9e62be | <ide><path>ello.java
<del>4954f664-2e60-11e5-9284-b827eb9e62be
<add>495a6e5a-2e60-11e5-9284-b827eb9e62be |
|
Java | apache-2.0 | aafc3a975f2ee8229ae8207061164ad47234afec | 0 | heinousjay/JibbrJabbr,heinousjay/JibbrJabbr,heinousjay/JibbrJabbr | package jj.resource;
/**
* Inject this to get resources from the filesystem
* @author jason
*
*/
public interface ResourceFinder {
/**
* <p>
* looks in the resource cache for a resource matching the given spec,
* which is a resource dependent set of lookup parameters. returns null
* if no such resource is in the cache, which means it hasn't been loaded
* yet
*
* @param resourceClass The type of <code>Resource</code>
* @param base The {@link Location} of the <code>Resource</code>
* @param name The name of the <code>Resource</code>
* @param argument The creation argument of the <code>Resource</code>
* @return the {@link Resource}, or null if not found
*/
<T extends Resource<A>, A> T findResource(Class<T> resourceClass, Location base, String name, A argument);
<T extends Resource<Void>> T findResource(Class<T> resourceClass, Location base, String name);
<T extends Resource<A>, A> T findResource(ResourceIdentifier<T, A> identifier);
/**
* <p>
* loads a resource matching the given resource spec, if necessary, and populates
* the cache. can only be called via a {@link ResourceTask}. if the resource spec does
* not identify a valid resource, this returns null. if a resource is returned from this method,
* then it will be watched for changes and automatically updated, unless the watcher is shut off
*
* @param resourceClass The type of <code>Resource</code>
* @param base The {@link Location} of the <code>Resource</code>
* @param name The name of the <code>Resource</code>
* @param argument The creation argument of the <code>Resource</code>
* @return the {@link Resource}, or null if not found
*/
@ResourceThread
<T extends Resource<A>, A> T loadResource(Class<T> resourceClass, Location base, String name, A argument);
@ResourceThread
<T extends Resource<Void>> T loadResource(Class<T> resourceClass, Location base, String name);
<T extends Resource<A>, A> T loadResource(ResourceIdentifier<T, A> identifier);
}
| kernel/src/main/java/jj/resource/ResourceFinder.java | package jj.resource;
/**
* Inject this to get resources from the filesystem
* @author jason
*
*/
public interface ResourceFinder {
/**
* <p>
* looks in the resource cache for a resource matching the given spec,
* which is a resource dependent set of lookup parameters. returns null
* if no such resource is in the cache, which means it hasn't been loaded
* yet
*
* @param resourceClass The type of <code>Resource</code>
* @param base The {@link Location} of the <code>Resource</code>
* @param name The name of the <code>Resource</code>
* @param argument The creation argument of the <code>Resource</code>
* @return the {@link Resource}, or null if not found
*/
<T extends Resource<A>, A> T findResource(Class<T> resourceClass, Location base, String name, A argument);
<T extends Resource<Void>> T findResource(Class<T> resourceClass, Location base, String name);
<T extends Resource<A>, A> T findResource(ResourceIdentifier<T, A> identifier);
/**
* <p>
* loads a resource matching the given resource spec, if necessary, and populates
* the cache. can only be called via a {@link ResourceTask}. if the resource spec does
* not identify a valid resource, this returns null. if a resource is returned from this method,
* then it will be watched for changes and automatically updated
*
* @param resourceClass The type of <code>Resource</code>
* @param base The {@link Location} of the <code>Resource</code>
* @param name The name of the <code>Resource</code>
* @param argument The creation argument of the <code>Resource</code>
* @return the {@link Resource}, or null if not found
*/
@ResourceThread
<T extends Resource<A>, A> T loadResource(Class<T> resourceClass, Location base, String name, A argument);
@ResourceThread
<T extends Resource<Void>> T loadResource(Class<T> resourceClass, Location base, String name);
<T extends Resource<A>, A> T loadResource(ResourceIdentifier<T, A> identifier);
}
| documentation update
| kernel/src/main/java/jj/resource/ResourceFinder.java | documentation update | <ide><path>ernel/src/main/java/jj/resource/ResourceFinder.java
<ide> * loads a resource matching the given resource spec, if necessary, and populates
<ide> * the cache. can only be called via a {@link ResourceTask}. if the resource spec does
<ide> * not identify a valid resource, this returns null. if a resource is returned from this method,
<del> * then it will be watched for changes and automatically updated
<add> * then it will be watched for changes and automatically updated, unless the watcher is shut off
<ide> *
<ide> * @param resourceClass The type of <code>Resource</code>
<ide> * @param base The {@link Location} of the <code>Resource</code> |
|
Java | apache-2.0 | 82816bd88cc45f19b122d3d97295fb1f10bbb372 | 0 | paulk-asert/groovy,apache/groovy,apache/groovy,paulk-asert/groovy,apache/incubator-groovy,paulk-asert/incubator-groovy,apache/incubator-groovy,apache/incubator-groovy,apache/groovy,paulk-asert/incubator-groovy,paulk-asert/incubator-groovy,paulk-asert/groovy,paulk-asert/groovy,paulk-asert/incubator-groovy,apache/groovy,apache/incubator-groovy,paulk-asert/incubator-groovy | /*
* 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.codehaus.groovy.control;
import groovy.lang.GroovyClassLoader;
import java.security.AccessController;
import java.security.PrivilegedAction;
import static java.util.Objects.requireNonNull;
/**
* A base class for data structures that can collect messages and errors
* during processing.
*/
public abstract class ProcessingUnit {
/**
* The current phase
*/
protected int phase = Phases.INITIALIZATION;
/**
* True if phase is finished
*/
protected boolean phaseComplete;
/**
* Configuration and other settings that control processing
*/
protected CompilerConfiguration configuration;
/**
* The ClassLoader to use during processing
*/
protected GroovyClassLoader classLoader;
/**
* a helper to share errors and report them
*/
protected ErrorCollector errorCollector;
/**
* Initializes the ProcessingUnit to the empty state.
*/
public ProcessingUnit(final CompilerConfiguration configuration, final GroovyClassLoader classLoader, final ErrorCollector errorCollector) {
setConfiguration(configuration != null ? configuration : CompilerConfiguration.DEFAULT);
setClassLoader(classLoader);
this.errorCollector = errorCollector != null ? errorCollector : new ErrorCollector(getConfiguration());
configure(getConfiguration());
}
/**
* Reconfigures the ProcessingUnit.
*/
public void configure(CompilerConfiguration configuration) {
setConfiguration(configuration);
}
/**
* Gets the CompilerConfiguration for this ProcessingUnit.
*/
public CompilerConfiguration getConfiguration() {
return configuration;
}
/**
* Sets the CompilerConfiguration for this ProcessingUnit.
*/
public final void setConfiguration(CompilerConfiguration configuration) {
this.configuration = requireNonNull(configuration);
}
/**
* Returns the class loader in use by this ProcessingUnit.
*/
public GroovyClassLoader getClassLoader() {
return classLoader;
}
/**
* Sets the class loader for use by this ProcessingUnit.
*/
public void setClassLoader(final GroovyClassLoader loader) {
// ClassLoaders should only be created inside a doPrivileged block in case
// this method is invoked by code that does not have security permissions.
this.classLoader = loader != null ? loader : AccessController.doPrivileged((PrivilegedAction<GroovyClassLoader>) () -> {
ClassLoader parent = Thread.currentThread().getContextClassLoader();
if (parent == null) parent = ProcessingUnit.class.getClassLoader();
return new GroovyClassLoader(parent, getConfiguration());
});
}
/**
* Errors found during the compilation should be reported through the ErrorCollector.
*/
public ErrorCollector getErrorCollector() {
return errorCollector;
}
/**
* Returns the current phase.
*/
public int getPhase() {
return phase;
}
/**
* Returns the description for the current phase.
*/
public String getPhaseDescription() {
return Phases.getDescription(phase);
}
public boolean isPhaseComplete() {
return phaseComplete;
}
/**
* Marks the current phase complete and processes any errors.
*/
public void completePhase() throws CompilationFailedException {
errorCollector.failIfErrors();
phaseComplete = true;
}
/**
* A synonym for <code>gotoPhase(getPhase() + 1)</code>.
*/
public void nextPhase() throws CompilationFailedException {
gotoPhase(phase + 1);
}
/**
* Wraps up any pending operations for the current phase and switches to the given phase.
*/
public void gotoPhase(int phase) throws CompilationFailedException {
if (!phaseComplete) {
completePhase();
}
this.phase = phase;
phaseComplete = false;
}
}
| src/main/java/org/codehaus/groovy/control/ProcessingUnit.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.codehaus.groovy.control;
import groovy.lang.GroovyClassLoader;
import java.security.AccessController;
import java.security.PrivilegedAction;
import static java.util.Objects.requireNonNull;
/**
* A base class for data structures that can collect messages and errors
* during processing.
*/
public abstract class ProcessingUnit {
/**
* The current phase
*/
protected int phase = Phases.INITIALIZATION;
/**
* True if phase is finished
*/
protected boolean phaseComplete;
/**
* Configuration and other settings that control processing
*/
protected CompilerConfiguration configuration;
/**
* The ClassLoader to use during processing
*/
protected GroovyClassLoader classLoader;
/**
* a helper to share errors and report them
*/
protected ErrorCollector errorCollector;
/**
* Initializes the ProcessingUnit to the empty state.
*/
public ProcessingUnit(final CompilerConfiguration configuration, final GroovyClassLoader classLoader, final ErrorCollector errorCollector) {
setConfiguration(configuration != null ? configuration : CompilerConfiguration.DEFAULT); setClassLoader(classLoader);
this.errorCollector = errorCollector != null ? errorCollector : new ErrorCollector(getConfiguration());
configure(getConfiguration());
}
/**
* Reconfigures the ProcessingUnit.
*/
public void configure(CompilerConfiguration configuration) {
setConfiguration(configuration);
}
/**
* Gets the CompilerConfiguration for this ProcessingUnit.
*/
public CompilerConfiguration getConfiguration() {
return configuration;
}
/**
* Sets the CompilerConfiguration for this ProcessingUnit.
*/
public final void setConfiguration(CompilerConfiguration configuration) {
this.configuration = requireNonNull(configuration);
}
/**
* Returns the class loader in use by this ProcessingUnit.
*/
public GroovyClassLoader getClassLoader() {
return classLoader;
}
/**
* Sets the class loader for use by this ProcessingUnit.
*/
public void setClassLoader(final GroovyClassLoader loader) {
// ClassLoaders should only be created inside a doPrivileged block in case
// this method is invoked by code that does not have security permissions.
this.classLoader = loader != null ? loader : AccessController.doPrivileged((PrivilegedAction<GroovyClassLoader>) () -> {
ClassLoader parent = Thread.currentThread().getContextClassLoader();
if (parent == null) parent = ProcessingUnit.class.getClassLoader();
return new GroovyClassLoader(parent, getConfiguration());
});
}
/**
* Errors found during the compilation should be reported through the ErrorCollector.
*/
public ErrorCollector getErrorCollector() {
return errorCollector;
}
/**
* Returns the current phase.
*/
public int getPhase() {
return phase;
}
/**
* Returns the description for the current phase.
*/
public String getPhaseDescription() {
return Phases.getDescription(phase);
}
public boolean isPhaseComplete() {
return phaseComplete;
}
/**
* Marks the current phase complete and processes any errors.
*/
public void completePhase() throws CompilationFailedException {
errorCollector.failIfErrors();
phaseComplete = true;
}
/**
* A synonym for <code>gotoPhase(getPhase() + 1)</code>.
*/
public void nextPhase() throws CompilationFailedException {
gotoPhase(phase + 1);
}
/**
* Wraps up any pending operations for the current phase and switches to the given phase.
*/
public void gotoPhase(int phase) throws CompilationFailedException {
if (!phaseComplete) {
completePhase();
}
this.phase = phase;
phaseComplete = false;
}
}
| fix whitespace only
| src/main/java/org/codehaus/groovy/control/ProcessingUnit.java | fix whitespace only | <ide><path>rc/main/java/org/codehaus/groovy/control/ProcessingUnit.java
<ide> * Initializes the ProcessingUnit to the empty state.
<ide> */
<ide> public ProcessingUnit(final CompilerConfiguration configuration, final GroovyClassLoader classLoader, final ErrorCollector errorCollector) {
<del> setConfiguration(configuration != null ? configuration : CompilerConfiguration.DEFAULT); setClassLoader(classLoader);
<add> setConfiguration(configuration != null ? configuration : CompilerConfiguration.DEFAULT);
<add> setClassLoader(classLoader);
<ide> this.errorCollector = errorCollector != null ? errorCollector : new ErrorCollector(getConfiguration());
<ide> configure(getConfiguration());
<ide> } |
|
JavaScript | apache-2.0 | 7690ff9ba538f177034bc533220ddc5bc6e128cb | 0 | netfishx/new_react_rockstar | 596fb44a-2f86-11e5-bc51-34363bc765d8 | hello.js | 59693930-2f86-11e5-ba4a-34363bc765d8 | 596fb44a-2f86-11e5-bc51-34363bc765d8 | hello.js | 596fb44a-2f86-11e5-bc51-34363bc765d8 | <ide><path>ello.js
<del>59693930-2f86-11e5-ba4a-34363bc765d8
<add>596fb44a-2f86-11e5-bc51-34363bc765d8 |
|
Java | apache-2.0 | 59c8f9cd76f17354c91f0749be7099e93bcb0d42 | 0 | apache/solr,apache/solr,apache/solr,apache/solr,apache/solr | package org.apache.lucene.index;
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.store.LockObtainFailedException;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
/**
* <p>[Note that as of <b>2.1</b>, all but one of the
* methods in this class are available via {@link
* IndexWriter}. The one method that is not available is
* {@link #deleteDocument(int)}.]</p>
*
* A class to modify an index, i.e. to delete and add documents. This
* class hides {@link IndexReader} and {@link IndexWriter} so that you
* do not need to care about implementation details such as that adding
* documents is done via IndexWriter and deletion is done via IndexReader.
*
* <p>Note that you cannot create more than one <code>IndexModifier</code> object
* on the same directory at the same time.
*
* <p>Example usage:
*
<!-- ======================================================== -->
<!-- = Java Sourcecode to HTML automatically converted code = -->
<!-- = Java2Html Converter V4.1 2004 by Markus Gebhard [email protected] = -->
<!-- = Further information: http://www.java2html.de = -->
<div align="left" class="java">
<table border="0" cellpadding="3" cellspacing="0" bgcolor="#ffffff">
<tr>
<!-- start source code -->
<td nowrap="nowrap" valign="top" align="left">
<code>
<font color="#ffffff"> </font><font color="#000000">Analyzer analyzer = </font><font color="#7f0055"><b>new </b></font><font color="#000000">StandardAnalyzer</font><font color="#000000">()</font><font color="#000000">;</font><br/>
<font color="#ffffff"> </font><font color="#3f7f5f">// create an index in /tmp/index, overwriting an existing one:</font><br/>
<font color="#ffffff"> </font><font color="#000000">IndexModifier indexModifier = </font><font color="#7f0055"><b>new </b></font><font color="#000000">IndexModifier</font><font color="#000000">(</font><font color="#2a00ff">"/tmp/index"</font><font color="#000000">, analyzer, </font><font color="#7f0055"><b>true</b></font><font color="#000000">)</font><font color="#000000">;</font><br/>
<font color="#ffffff"> </font><font color="#000000">Document doc = </font><font color="#7f0055"><b>new </b></font><font color="#000000">Document</font><font color="#000000">()</font><font color="#000000">;</font><br/>
<font color="#ffffff"> </font><font color="#000000">doc.add</font><font color="#000000">(</font><font color="#7f0055"><b>new </b></font><font color="#000000">Field</font><font color="#000000">(</font><font color="#2a00ff">"id"</font><font color="#000000">, </font><font color="#2a00ff">"1"</font><font color="#000000">, Field.Store.YES, Field.Index.UN_TOKENIZED</font><font color="#000000">))</font><font color="#000000">;</font><br/>
<font color="#ffffff"> </font><font color="#000000">doc.add</font><font color="#000000">(</font><font color="#7f0055"><b>new </b></font><font color="#000000">Field</font><font color="#000000">(</font><font color="#2a00ff">"body"</font><font color="#000000">, </font><font color="#2a00ff">"a simple test"</font><font color="#000000">, Field.Store.YES, Field.Index.TOKENIZED</font><font color="#000000">))</font><font color="#000000">;</font><br/>
<font color="#ffffff"> </font><font color="#000000">indexModifier.addDocument</font><font color="#000000">(</font><font color="#000000">doc</font><font color="#000000">)</font><font color="#000000">;</font><br/>
<font color="#ffffff"> </font><font color="#7f0055"><b>int </b></font><font color="#000000">deleted = indexModifier.delete</font><font color="#000000">(</font><font color="#7f0055"><b>new </b></font><font color="#000000">Term</font><font color="#000000">(</font><font color="#2a00ff">"id"</font><font color="#000000">, </font><font color="#2a00ff">"1"</font><font color="#000000">))</font><font color="#000000">;</font><br/>
<font color="#ffffff"> </font><font color="#000000">System.out.println</font><font color="#000000">(</font><font color="#2a00ff">"Deleted " </font><font color="#000000">+ deleted + </font><font color="#2a00ff">" document"</font><font color="#000000">)</font><font color="#000000">;</font><br/>
<font color="#ffffff"> </font><font color="#000000">indexModifier.flush</font><font color="#000000">()</font><font color="#000000">;</font><br/>
<font color="#ffffff"> </font><font color="#000000">System.out.println</font><font color="#000000">(</font><font color="#000000">indexModifier.docCount</font><font color="#000000">() </font><font color="#000000">+ </font><font color="#2a00ff">" docs in index"</font><font color="#000000">)</font><font color="#000000">;</font><br/>
<font color="#ffffff"> </font><font color="#000000">indexModifier.close</font><font color="#000000">()</font><font color="#000000">;</font></code>
</td>
<!-- end source code -->
</tr>
</table>
</div>
<!-- = END of automatically generated HTML code = -->
<!-- ======================================================== -->
*
* <p>Not all methods of IndexReader and IndexWriter are offered by this
* class. If you need access to additional methods, either use those classes
* directly or implement your own class that extends <code>IndexModifier</code>.
*
* <p>Although an instance of this class can be used from more than one
* thread, you will not get the best performance. You might want to use
* IndexReader and IndexWriter directly for that (but you will need to
* care about synchronization yourself then).
*
* <p>While you can freely mix calls to add() and delete() using this class,
* you should batch you calls for best performance. For example, if you
* want to update 20 documents, you should first delete all those documents,
* then add all the new documents.
*
* @author Daniel Naber
* @deprecated Please use {@link IndexWriter} instead.
*/
public class IndexModifier {
protected IndexWriter indexWriter = null;
protected IndexReader indexReader = null;
protected Directory directory = null;
protected Analyzer analyzer = null;
protected boolean open = false;
// Lucene defaults:
protected PrintStream infoStream = null;
protected boolean useCompoundFile = true;
protected int maxBufferedDocs = IndexWriter.DEFAULT_MAX_BUFFERED_DOCS;
protected int maxFieldLength = IndexWriter.DEFAULT_MAX_FIELD_LENGTH;
protected int mergeFactor = IndexWriter.DEFAULT_MERGE_FACTOR;
/**
* Open an index with write access.
*
* @param directory the index directory
* @param analyzer the analyzer to use for adding new documents
* @param create <code>true</code> to create the index or overwrite the existing one;
* <code>false</code> to append to the existing index
* @throws CorruptIndexException if the index is corrupt
* @throws LockObtainFailedException if another writer
* has this index open (<code>write.lock</code> could not
* be obtained)
* @throws IOException if there is a low-level IO error
*/
public IndexModifier(Directory directory, Analyzer analyzer, boolean create) throws CorruptIndexException, LockObtainFailedException, IOException {
init(directory, analyzer, create);
}
/**
* Open an index with write access.
*
* @param dirName the index directory
* @param analyzer the analyzer to use for adding new documents
* @param create <code>true</code> to create the index or overwrite the existing one;
* <code>false</code> to append to the existing index
* @throws CorruptIndexException if the index is corrupt
* @throws LockObtainFailedException if another writer
* has this index open (<code>write.lock</code> could not
* be obtained)
* @throws IOException if there is a low-level IO error
*/
public IndexModifier(String dirName, Analyzer analyzer, boolean create) throws CorruptIndexException, LockObtainFailedException, IOException {
Directory dir = FSDirectory.getDirectory(dirName);
init(dir, analyzer, create);
}
/**
* Open an index with write access.
*
* @param file the index directory
* @param analyzer the analyzer to use for adding new documents
* @param create <code>true</code> to create the index or overwrite the existing one;
* <code>false</code> to append to the existing index
* @throws CorruptIndexException if the index is corrupt
* @throws LockObtainFailedException if another writer
* has this index open (<code>write.lock</code> could not
* be obtained)
* @throws IOException if there is a low-level IO error
*/
public IndexModifier(File file, Analyzer analyzer, boolean create) throws CorruptIndexException, LockObtainFailedException, IOException {
Directory dir = FSDirectory.getDirectory(file);
init(dir, analyzer, create);
}
/**
* Initialize an IndexWriter.
* @throws CorruptIndexException if the index is corrupt
* @throws LockObtainFailedException if another writer
* has this index open (<code>write.lock</code> could not
* be obtained)
* @throws IOException if there is a low-level IO error
*/
protected void init(Directory directory, Analyzer analyzer, boolean create) throws CorruptIndexException, LockObtainFailedException, IOException {
this.directory = directory;
synchronized(this.directory) {
this.analyzer = analyzer;
indexWriter = new IndexWriter(directory, analyzer, create, IndexWriter.MaxFieldLength.LIMITED);
open = true;
}
}
/**
* Throw an IllegalStateException if the index is closed.
* @throws IllegalStateException
*/
protected void assureOpen() {
if (!open) {
throw new IllegalStateException("Index is closed");
}
}
/**
* Close the IndexReader and open an IndexWriter.
* @throws CorruptIndexException if the index is corrupt
* @throws LockObtainFailedException if another writer
* has this index open (<code>write.lock</code> could not
* be obtained)
* @throws IOException if there is a low-level IO error
*/
protected void createIndexWriter() throws CorruptIndexException, LockObtainFailedException, IOException {
if (indexWriter == null) {
if (indexReader != null) {
indexReader.close();
indexReader = null;
}
indexWriter = new IndexWriter(directory, analyzer, false, new IndexWriter.MaxFieldLength(maxFieldLength));
// IndexModifier cannot use ConcurrentMergeScheduler
// because it synchronizes on the directory which can
// cause deadlock
indexWriter.setMergeScheduler(new SerialMergeScheduler());
indexWriter.setInfoStream(infoStream);
indexWriter.setUseCompoundFile(useCompoundFile);
if (maxBufferedDocs != IndexWriter.DISABLE_AUTO_FLUSH)
indexWriter.setMaxBufferedDocs(maxBufferedDocs);
indexWriter.setMergeFactor(mergeFactor);
}
}
/**
* Close the IndexWriter and open an IndexReader.
* @throws CorruptIndexException if the index is corrupt
* @throws IOException if there is a low-level IO error
*/
protected void createIndexReader() throws CorruptIndexException, IOException {
if (indexReader == null) {
if (indexWriter != null) {
indexWriter.close();
indexWriter = null;
}
indexReader = IndexReader.open(directory);
}
}
/**
* Make sure all changes are written to disk.
* @throws CorruptIndexException if the index is corrupt
* @throws LockObtainFailedException if another writer
* has this index open (<code>write.lock</code> could not
* be obtained)
* @throws IOException if there is a low-level IO error
*/
public void flush() throws CorruptIndexException, LockObtainFailedException, IOException {
synchronized(directory) {
assureOpen();
if (indexWriter != null) {
indexWriter.close();
indexWriter = null;
createIndexWriter();
} else {
indexReader.close();
indexReader = null;
createIndexReader();
}
}
}
/**
* Adds a document to this index, using the provided analyzer instead of the
* one specific in the constructor. If the document contains more than
* {@link #setMaxFieldLength(int)} terms for a given field, the remainder are
* discarded.
* @see IndexWriter#addDocument(Document, Analyzer)
* @throws IllegalStateException if the index is closed
* @throws CorruptIndexException if the index is corrupt
* @throws LockObtainFailedException if another writer
* has this index open (<code>write.lock</code> could not
* be obtained)
* @throws IOException if there is a low-level IO error
*/
public void addDocument(Document doc, Analyzer docAnalyzer) throws CorruptIndexException, LockObtainFailedException, IOException {
synchronized(directory) {
assureOpen();
createIndexWriter();
if (docAnalyzer != null)
indexWriter.addDocument(doc, docAnalyzer);
else
indexWriter.addDocument(doc);
}
}
/**
* Adds a document to this index. If the document contains more than
* {@link #setMaxFieldLength(int)} terms for a given field, the remainder are
* discarded.
* @see IndexWriter#addDocument(Document)
* @throws IllegalStateException if the index is closed
* @throws CorruptIndexException if the index is corrupt
* @throws LockObtainFailedException if another writer
* has this index open (<code>write.lock</code> could not
* be obtained)
* @throws IOException if there is a low-level IO error
*/
public void addDocument(Document doc) throws CorruptIndexException, LockObtainFailedException, IOException {
addDocument(doc, null);
}
/**
* Deletes all documents containing <code>term</code>.
* This is useful if one uses a document field to hold a unique ID string for
* the document. Then to delete such a document, one merely constructs a
* term with the appropriate field and the unique ID string as its text and
* passes it to this method. Returns the number of documents deleted.
* @return the number of documents deleted
* @see IndexReader#deleteDocuments(Term)
* @throws IllegalStateException if the index is closed
* @throws StaleReaderException if the index has changed
* since this reader was opened
* @throws CorruptIndexException if the index is corrupt
* @throws LockObtainFailedException if another writer
* has this index open (<code>write.lock</code> could not
* be obtained)
* @throws IOException if there is a low-level IO error
*/
public int deleteDocuments(Term term) throws StaleReaderException, CorruptIndexException, LockObtainFailedException, IOException {
synchronized(directory) {
assureOpen();
createIndexReader();
return indexReader.deleteDocuments(term);
}
}
/**
* Deletes the document numbered <code>docNum</code>.
* @see IndexReader#deleteDocument(int)
* @throws StaleReaderException if the index has changed
* since this reader was opened
* @throws CorruptIndexException if the index is corrupt
* @throws LockObtainFailedException if another writer
* has this index open (<code>write.lock</code> could not
* be obtained)
* @throws IllegalStateException if the index is closed
*/
public void deleteDocument(int docNum) throws StaleReaderException, CorruptIndexException, LockObtainFailedException, IOException {
synchronized(directory) {
assureOpen();
createIndexReader();
indexReader.deleteDocument(docNum);
}
}
/**
* Returns the number of documents currently in this
* index. If the writer is currently open, this returns
* {@link IndexWriter#docCount()}, else {@link
* IndexReader#numDocs()}. But, note that {@link
* IndexWriter#docCount()} does not take deletions into
* account, unlike {@link IndexReader#numDocs}.
* @throws IllegalStateException if the index is closed
*/
public int docCount() {
synchronized(directory) {
assureOpen();
if (indexWriter != null) {
return indexWriter.docCount();
} else {
return indexReader.numDocs();
}
}
}
/**
* Merges all segments together into a single segment, optimizing an index
* for search.
* @see IndexWriter#optimize()
* @throws IllegalStateException if the index is closed
* @throws CorruptIndexException if the index is corrupt
* @throws LockObtainFailedException if another writer
* has this index open (<code>write.lock</code> could not
* be obtained)
* @throws IOException if there is a low-level IO error
*/
public void optimize() throws CorruptIndexException, LockObtainFailedException, IOException {
synchronized(directory) {
assureOpen();
createIndexWriter();
indexWriter.optimize();
}
}
/**
* If non-null, information about merges and a message when
* {@link #getMaxFieldLength()} is reached will be printed to this.
* <p>Example: <tt>index.setInfoStream(System.err);</tt>
* @see IndexWriter#setInfoStream(PrintStream)
* @throws IllegalStateException if the index is closed
*/
public void setInfoStream(PrintStream infoStream) {
synchronized(directory) {
assureOpen();
if (indexWriter != null) {
indexWriter.setInfoStream(infoStream);
}
this.infoStream = infoStream;
}
}
/**
* @see IndexModifier#setInfoStream(PrintStream)
* @throws CorruptIndexException if the index is corrupt
* @throws LockObtainFailedException if another writer
* has this index open (<code>write.lock</code> could not
* be obtained)
* @throws IOException if there is a low-level IO error
*/
public PrintStream getInfoStream() throws CorruptIndexException, LockObtainFailedException, IOException {
synchronized(directory) {
assureOpen();
createIndexWriter();
return indexWriter.getInfoStream();
}
}
/**
* Setting to turn on usage of a compound file. When on, multiple files
* for each segment are merged into a single file once the segment creation
* is finished. This is done regardless of what directory is in use.
* @see IndexWriter#setUseCompoundFile(boolean)
* @throws IllegalStateException if the index is closed
*/
public void setUseCompoundFile(boolean useCompoundFile) {
synchronized(directory) {
assureOpen();
if (indexWriter != null) {
indexWriter.setUseCompoundFile(useCompoundFile);
}
this.useCompoundFile = useCompoundFile;
}
}
/**
* @see IndexModifier#setUseCompoundFile(boolean)
* @throws CorruptIndexException if the index is corrupt
* @throws LockObtainFailedException if another writer
* has this index open (<code>write.lock</code> could not
* be obtained)
* @throws IOException if there is a low-level IO error
*/
public boolean getUseCompoundFile() throws CorruptIndexException, LockObtainFailedException, IOException {
synchronized(directory) {
assureOpen();
createIndexWriter();
return indexWriter.getUseCompoundFile();
}
}
/**
* The maximum number of terms that will be indexed for a single field in a
* document. This limits the amount of memory required for indexing, so that
* collections with very large files will not crash the indexing process by
* running out of memory.<p/>
* Note that this effectively truncates large documents, excluding from the
* index terms that occur further in the document. If you know your source
* documents are large, be sure to set this value high enough to accomodate
* the expected size. If you set it to Integer.MAX_VALUE, then the only limit
* is your memory, but you should anticipate an OutOfMemoryError.<p/>
* By default, no more than 10,000 terms will be indexed for a field.
* @see IndexWriter#setMaxFieldLength(int)
* @throws IllegalStateException if the index is closed
*/
public void setMaxFieldLength(int maxFieldLength) {
synchronized(directory) {
assureOpen();
if (indexWriter != null) {
indexWriter.setMaxFieldLength(maxFieldLength);
}
this.maxFieldLength = maxFieldLength;
}
}
/**
* @see IndexModifier#setMaxFieldLength(int)
* @throws CorruptIndexException if the index is corrupt
* @throws LockObtainFailedException if another writer
* has this index open (<code>write.lock</code> could not
* be obtained)
* @throws IOException if there is a low-level IO error
*/
public int getMaxFieldLength() throws CorruptIndexException, LockObtainFailedException, IOException {
synchronized(directory) {
assureOpen();
createIndexWriter();
return indexWriter.getMaxFieldLength();
}
}
/**
* Determines the minimal number of documents required before the buffered
* in-memory documents are merging and a new Segment is created.
* Since Documents are merged in a {@link org.apache.lucene.store.RAMDirectory},
* large value gives faster indexing. At the same time, mergeFactor limits
* the number of files open in a FSDirectory.
*
* <p>The default value is 10.
*
* @see IndexWriter#setMaxBufferedDocs(int)
* @throws IllegalStateException if the index is closed
* @throws IllegalArgumentException if maxBufferedDocs is smaller than 2
*/
public void setMaxBufferedDocs(int maxBufferedDocs) {
synchronized(directory) {
assureOpen();
if (indexWriter != null) {
indexWriter.setMaxBufferedDocs(maxBufferedDocs);
}
this.maxBufferedDocs = maxBufferedDocs;
}
}
/**
* @see IndexModifier#setMaxBufferedDocs(int)
* @throws CorruptIndexException if the index is corrupt
* @throws LockObtainFailedException if another writer
* has this index open (<code>write.lock</code> could not
* be obtained)
* @throws IOException if there is a low-level IO error
*/
public int getMaxBufferedDocs() throws CorruptIndexException, LockObtainFailedException, IOException {
synchronized(directory) {
assureOpen();
createIndexWriter();
return indexWriter.getMaxBufferedDocs();
}
}
/**
* Determines how often segment indices are merged by addDocument(). With
* smaller values, less RAM is used while indexing, and searches on
* unoptimized indices are faster, but indexing speed is slower. With larger
* values, more RAM is used during indexing, and while searches on unoptimized
* indices are slower, indexing is faster. Thus larger values (> 10) are best
* for batch index creation, and smaller values (< 10) for indices that are
* interactively maintained.
* <p>This must never be less than 2. The default value is 10.
*
* @see IndexWriter#setMergeFactor(int)
* @throws IllegalStateException if the index is closed
*/
public void setMergeFactor(int mergeFactor) {
synchronized(directory) {
assureOpen();
if (indexWriter != null) {
indexWriter.setMergeFactor(mergeFactor);
}
this.mergeFactor = mergeFactor;
}
}
/**
* @see IndexModifier#setMergeFactor(int)
* @throws CorruptIndexException if the index is corrupt
* @throws LockObtainFailedException if another writer
* has this index open (<code>write.lock</code> could not
* be obtained)
* @throws IOException if there is a low-level IO error
*/
public int getMergeFactor() throws CorruptIndexException, LockObtainFailedException, IOException {
synchronized(directory) {
assureOpen();
createIndexWriter();
return indexWriter.getMergeFactor();
}
}
/**
* Close this index, writing all pending changes to disk.
*
* @throws IllegalStateException if the index has been closed before already
* @throws CorruptIndexException if the index is corrupt
* @throws IOException if there is a low-level IO error
*/
public void close() throws CorruptIndexException, IOException {
synchronized(directory) {
if (!open)
throw new IllegalStateException("Index is closed already");
if (indexWriter != null) {
indexWriter.close();
indexWriter = null;
} else if (indexReader != null) {
indexReader.close();
indexReader = null;
}
open = false;
}
}
public String toString() {
return "Index@" + directory;
}
/*
// used as an example in the javadoc:
public static void main(String[] args) throws IOException {
Analyzer analyzer = new StandardAnalyzer();
// create an index in /tmp/index, overwriting an existing one:
IndexModifier indexModifier = new IndexModifier("/tmp/index", analyzer, true);
Document doc = new Document();
doc.add(new Fieldable("id", "1", Fieldable.Store.YES, Fieldable.Index.UN_TOKENIZED));
doc.add(new Fieldable("body", "a simple test", Fieldable.Store.YES, Fieldable.Index.TOKENIZED));
indexModifier.addDocument(doc);
int deleted = indexModifier.delete(new Term("id", "1"));
System.out.println("Deleted " + deleted + " document");
indexModifier.flush();
System.out.println(indexModifier.docCount() + " docs in index");
indexModifier.close();
}*/
}
| src/java/org/apache/lucene/index/IndexModifier.java | package org.apache.lucene.index;
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.store.LockObtainFailedException;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
/**
* <p>[Note that as of <b>2.1</b>, all but one of the
* methods in this class are available via {@link
* IndexWriter}. The one method that is not available is
* {@link #deleteDocument(int)}.]</p>
*
* A class to modify an index, i.e. to delete and add documents. This
* class hides {@link IndexReader} and {@link IndexWriter} so that you
* do not need to care about implementation details such as that adding
* documents is done via IndexWriter and deletion is done via IndexReader.
*
* <p>Note that you cannot create more than one <code>IndexModifier</code> object
* on the same directory at the same time.
*
* <p>Example usage:
*
<!-- ======================================================== -->
<!-- = Java Sourcecode to HTML automatically converted code = -->
<!-- = Java2Html Converter V4.1 2004 by Markus Gebhard [email protected] = -->
<!-- = Further information: http://www.java2html.de = -->
<div align="left" class="java">
<table border="0" cellpadding="3" cellspacing="0" bgcolor="#ffffff">
<tr>
<!-- start source code -->
<td nowrap="nowrap" valign="top" align="left">
<code>
<font color="#ffffff"> </font><font color="#000000">Analyzer analyzer = </font><font color="#7f0055"><b>new </b></font><font color="#000000">StandardAnalyzer</font><font color="#000000">()</font><font color="#000000">;</font><br/>
<font color="#ffffff"> </font><font color="#3f7f5f">// create an index in /tmp/index, overwriting an existing one:</font><br/>
<font color="#ffffff"> </font><font color="#000000">IndexModifier indexModifier = </font><font color="#7f0055"><b>new </b></font><font color="#000000">IndexModifier</font><font color="#000000">(</font><font color="#2a00ff">"/tmp/index"</font><font color="#000000">, analyzer, </font><font color="#7f0055"><b>true</b></font><font color="#000000">)</font><font color="#000000">;</font><br/>
<font color="#ffffff"> </font><font color="#000000">Document doc = </font><font color="#7f0055"><b>new </b></font><font color="#000000">Document</font><font color="#000000">()</font><font color="#000000">;</font><br/>
<font color="#ffffff"> </font><font color="#000000">doc.add</font><font color="#000000">(</font><font color="#7f0055"><b>new </b></font><font color="#000000">Field</font><font color="#000000">(</font><font color="#2a00ff">"id"</font><font color="#000000">, </font><font color="#2a00ff">"1"</font><font color="#000000">, Field.Store.YES, Field.Index.UN_TOKENIZED</font><font color="#000000">))</font><font color="#000000">;</font><br/>
<font color="#ffffff"> </font><font color="#000000">doc.add</font><font color="#000000">(</font><font color="#7f0055"><b>new </b></font><font color="#000000">Field</font><font color="#000000">(</font><font color="#2a00ff">"body"</font><font color="#000000">, </font><font color="#2a00ff">"a simple test"</font><font color="#000000">, Field.Store.YES, Field.Index.TOKENIZED</font><font color="#000000">))</font><font color="#000000">;</font><br/>
<font color="#ffffff"> </font><font color="#000000">indexModifier.addDocument</font><font color="#000000">(</font><font color="#000000">doc</font><font color="#000000">)</font><font color="#000000">;</font><br/>
<font color="#ffffff"> </font><font color="#7f0055"><b>int </b></font><font color="#000000">deleted = indexModifier.delete</font><font color="#000000">(</font><font color="#7f0055"><b>new </b></font><font color="#000000">Term</font><font color="#000000">(</font><font color="#2a00ff">"id"</font><font color="#000000">, </font><font color="#2a00ff">"1"</font><font color="#000000">))</font><font color="#000000">;</font><br/>
<font color="#ffffff"> </font><font color="#000000">System.out.println</font><font color="#000000">(</font><font color="#2a00ff">"Deleted " </font><font color="#000000">+ deleted + </font><font color="#2a00ff">" document"</font><font color="#000000">)</font><font color="#000000">;</font><br/>
<font color="#ffffff"> </font><font color="#000000">indexModifier.flush</font><font color="#000000">()</font><font color="#000000">;</font><br/>
<font color="#ffffff"> </font><font color="#000000">System.out.println</font><font color="#000000">(</font><font color="#000000">indexModifier.docCount</font><font color="#000000">() </font><font color="#000000">+ </font><font color="#2a00ff">" docs in index"</font><font color="#000000">)</font><font color="#000000">;</font><br/>
<font color="#ffffff"> </font><font color="#000000">indexModifier.close</font><font color="#000000">()</font><font color="#000000">;</font></code>
</td>
<!-- end source code -->
</tr>
</table>
</div>
<!-- = END of automatically generated HTML code = -->
<!-- ======================================================== -->
*
* <p>Not all methods of IndexReader and IndexWriter are offered by this
* class. If you need access to additional methods, either use those classes
* directly or implement your own class that extends <code>IndexModifier</code>.
*
* <p>Although an instance of this class can be used from more than one
* thread, you will not get the best performance. You might want to use
* IndexReader and IndexWriter directly for that (but you will need to
* care about synchronization yourself then).
*
* <p>While you can freely mix calls to add() and delete() using this class,
* you should batch you calls for best performance. For example, if you
* want to update 20 documents, you should first delete all those documents,
* then add all the new documents.
*
* @author Daniel Naber
* @deprecated Please use {@link IndexWriter} instead.
*/
public class IndexModifier {
protected IndexWriter indexWriter = null;
protected IndexReader indexReader = null;
protected Directory directory = null;
protected Analyzer analyzer = null;
protected boolean open = false;
// Lucene defaults:
protected PrintStream infoStream = null;
protected boolean useCompoundFile = true;
protected int maxBufferedDocs = IndexWriter.DEFAULT_MAX_BUFFERED_DOCS;
protected int maxFieldLength = IndexWriter.DEFAULT_MAX_FIELD_LENGTH;
protected int mergeFactor = IndexWriter.DEFAULT_MERGE_FACTOR;
/**
* Open an index with write access.
*
* @param directory the index directory
* @param analyzer the analyzer to use for adding new documents
* @param create <code>true</code> to create the index or overwrite the existing one;
* <code>false</code> to append to the existing index
* @throws CorruptIndexException if the index is corrupt
* @throws LockObtainFailedException if another writer
* has this index open (<code>write.lock</code> could not
* be obtained)
* @throws IOException if there is a low-level IO error
*/
public IndexModifier(Directory directory, Analyzer analyzer, boolean create) throws CorruptIndexException, LockObtainFailedException, IOException {
init(directory, analyzer, create);
}
/**
* Open an index with write access.
*
* @param dirName the index directory
* @param analyzer the analyzer to use for adding new documents
* @param create <code>true</code> to create the index or overwrite the existing one;
* <code>false</code> to append to the existing index
* @throws CorruptIndexException if the index is corrupt
* @throws LockObtainFailedException if another writer
* has this index open (<code>write.lock</code> could not
* be obtained)
* @throws IOException if there is a low-level IO error
*/
public IndexModifier(String dirName, Analyzer analyzer, boolean create) throws CorruptIndexException, LockObtainFailedException, IOException {
Directory dir = FSDirectory.getDirectory(dirName);
init(dir, analyzer, create);
}
/**
* Open an index with write access.
*
* @param file the index directory
* @param analyzer the analyzer to use for adding new documents
* @param create <code>true</code> to create the index or overwrite the existing one;
* <code>false</code> to append to the existing index
* @throws CorruptIndexException if the index is corrupt
* @throws LockObtainFailedException if another writer
* has this index open (<code>write.lock</code> could not
* be obtained)
* @throws IOException if there is a low-level IO error
*/
public IndexModifier(File file, Analyzer analyzer, boolean create) throws CorruptIndexException, LockObtainFailedException, IOException {
Directory dir = FSDirectory.getDirectory(file);
init(dir, analyzer, create);
}
/**
* Initialize an IndexWriter.
* @throws CorruptIndexException if the index is corrupt
* @throws LockObtainFailedException if another writer
* has this index open (<code>write.lock</code> could not
* be obtained)
* @throws IOException if there is a low-level IO error
*/
protected void init(Directory directory, Analyzer analyzer, boolean create) throws CorruptIndexException, LockObtainFailedException, IOException {
this.directory = directory;
synchronized(this.directory) {
this.analyzer = analyzer;
indexWriter = new IndexWriter(directory, analyzer, create, IndexWriter.MaxFieldLength.LIMITED);
open = true;
}
}
/**
* Throw an IllegalStateException if the index is closed.
* @throws IllegalStateException
*/
protected void assureOpen() {
if (!open) {
throw new IllegalStateException("Index is closed");
}
}
/**
* Close the IndexReader and open an IndexWriter.
* @throws CorruptIndexException if the index is corrupt
* @throws LockObtainFailedException if another writer
* has this index open (<code>write.lock</code> could not
* be obtained)
* @throws IOException if there is a low-level IO error
*/
protected void createIndexWriter() throws CorruptIndexException, LockObtainFailedException, IOException {
if (indexWriter == null) {
if (indexReader != null) {
indexReader.close();
indexReader = null;
}
indexWriter = new IndexWriter(directory, analyzer, false, new IndexWriter.MaxFieldLength(maxFieldLength));
// IndexModifier cannot use ConcurrentMergeScheduler
// because it synchronizes on the directory which can
// cause deadlock
indexWriter.setMergeScheduler(new SerialMergeScheduler());
indexWriter.setInfoStream(infoStream);
indexWriter.setUseCompoundFile(useCompoundFile);
if (maxBufferedDocs != IndexWriter.DISABLE_AUTO_FLUSH)
indexWriter.setMaxBufferedDocs(maxBufferedDocs);
indexWriter.setMergeFactor(mergeFactor);
}
}
/**
* Close the IndexWriter and open an IndexReader.
* @throws CorruptIndexException if the index is corrupt
* @throws IOException if there is a low-level IO error
*/
protected void createIndexReader() throws CorruptIndexException, IOException {
if (indexReader == null) {
if (indexWriter != null) {
indexWriter.close();
indexWriter = null;
}
indexReader = IndexReader.open(directory);
}
}
/**
* Make sure all changes are written to disk.
* @throws CorruptIndexException if the index is corrupt
* @throws LockObtainFailedException if another writer
* has this index open (<code>write.lock</code> could not
* be obtained)
* @throws IOException if there is a low-level IO error
*/
public void flush() throws CorruptIndexException, LockObtainFailedException, IOException {
synchronized(directory) {
assureOpen();
if (indexWriter != null) {
indexWriter.close();
indexWriter = null;
createIndexWriter();
} else {
indexReader.close();
indexReader = null;
createIndexReader();
}
}
}
/**
* Adds a document to this index, using the provided analyzer instead of the
* one specific in the constructor. If the document contains more than
* {@link #setMaxFieldLength(int)} terms for a given field, the remainder are
* discarded.
* @see IndexWriter#addDocument(Document, Analyzer)
* @throws IllegalStateException if the index is closed
* @throws CorruptIndexException if the index is corrupt
* @throws LockObtainFailedException if another writer
* has this index open (<code>write.lock</code> could not
* be obtained)
* @throws IOException if there is a low-level IO error
*/
public void addDocument(Document doc, Analyzer docAnalyzer) throws CorruptIndexException, LockObtainFailedException, IOException {
synchronized(directory) {
assureOpen();
createIndexWriter();
if (docAnalyzer != null)
indexWriter.addDocument(doc, docAnalyzer);
else
indexWriter.addDocument(doc);
}
}
/**
* Adds a document to this index. If the document contains more than
* {@link #setMaxFieldLength(int)} terms for a given field, the remainder are
* discarded.
* @see IndexWriter#addDocument(Document)
* @throws IllegalStateException if the index is closed
* @throws CorruptIndexException if the index is corrupt
* @throws LockObtainFailedException if another writer
* has this index open (<code>write.lock</code> could not
* be obtained)
* @throws IOException if there is a low-level IO error
*/
public void addDocument(Document doc) throws CorruptIndexException, LockObtainFailedException, IOException {
addDocument(doc, null);
}
/**
* Deletes all documents containing <code>term</code>.
* This is useful if one uses a document field to hold a unique ID string for
* the document. Then to delete such a document, one merely constructs a
* term with the appropriate field and the unique ID string as its text and
* passes it to this method. Returns the number of documents deleted.
* @return the number of documents deleted
* @see IndexReader#deleteDocuments(Term)
* @throws IllegalStateException if the index is closed
* @throws StaleReaderException if the index has changed
* since this reader was opened
* @throws CorruptIndexException if the index is corrupt
* @throws LockObtainFailedException if another writer
* has this index open (<code>write.lock</code> could not
* be obtained)
* @throws IOException if there is a low-level IO error
*/
public int deleteDocuments(Term term) throws StaleReaderException, CorruptIndexException, LockObtainFailedException, IOException {
synchronized(directory) {
assureOpen();
createIndexReader();
return indexReader.deleteDocuments(term);
}
}
/**
* Deletes the document numbered <code>docNum</code>.
* @see IndexReader#deleteDocument(int)
* @throws StaleReaderException if the index has changed
* since this reader was opened
* @throws CorruptIndexException if the index is corrupt
* @throws LockObtainFailedException if another writer
* has this index open (<code>write.lock</code> could not
* be obtained)
* @throws IllegalStateException if the index is closed
*/
public void deleteDocument(int docNum) throws StaleReaderException, CorruptIndexException, LockObtainFailedException, IOException {
synchronized(directory) {
assureOpen();
createIndexReader();
indexReader.deleteDocument(docNum);
}
}
/**
* Returns the number of documents currently in this index.
* @see IndexWriter#docCount()
* @see IndexReader#numDocs()
* @throws IllegalStateException if the index is closed
*/
public int docCount() {
synchronized(directory) {
assureOpen();
if (indexWriter != null) {
return indexWriter.docCount();
} else {
return indexReader.numDocs();
}
}
}
/**
* Merges all segments together into a single segment, optimizing an index
* for search.
* @see IndexWriter#optimize()
* @throws IllegalStateException if the index is closed
* @throws CorruptIndexException if the index is corrupt
* @throws LockObtainFailedException if another writer
* has this index open (<code>write.lock</code> could not
* be obtained)
* @throws IOException if there is a low-level IO error
*/
public void optimize() throws CorruptIndexException, LockObtainFailedException, IOException {
synchronized(directory) {
assureOpen();
createIndexWriter();
indexWriter.optimize();
}
}
/**
* If non-null, information about merges and a message when
* {@link #getMaxFieldLength()} is reached will be printed to this.
* <p>Example: <tt>index.setInfoStream(System.err);</tt>
* @see IndexWriter#setInfoStream(PrintStream)
* @throws IllegalStateException if the index is closed
*/
public void setInfoStream(PrintStream infoStream) {
synchronized(directory) {
assureOpen();
if (indexWriter != null) {
indexWriter.setInfoStream(infoStream);
}
this.infoStream = infoStream;
}
}
/**
* @see IndexModifier#setInfoStream(PrintStream)
* @throws CorruptIndexException if the index is corrupt
* @throws LockObtainFailedException if another writer
* has this index open (<code>write.lock</code> could not
* be obtained)
* @throws IOException if there is a low-level IO error
*/
public PrintStream getInfoStream() throws CorruptIndexException, LockObtainFailedException, IOException {
synchronized(directory) {
assureOpen();
createIndexWriter();
return indexWriter.getInfoStream();
}
}
/**
* Setting to turn on usage of a compound file. When on, multiple files
* for each segment are merged into a single file once the segment creation
* is finished. This is done regardless of what directory is in use.
* @see IndexWriter#setUseCompoundFile(boolean)
* @throws IllegalStateException if the index is closed
*/
public void setUseCompoundFile(boolean useCompoundFile) {
synchronized(directory) {
assureOpen();
if (indexWriter != null) {
indexWriter.setUseCompoundFile(useCompoundFile);
}
this.useCompoundFile = useCompoundFile;
}
}
/**
* @see IndexModifier#setUseCompoundFile(boolean)
* @throws CorruptIndexException if the index is corrupt
* @throws LockObtainFailedException if another writer
* has this index open (<code>write.lock</code> could not
* be obtained)
* @throws IOException if there is a low-level IO error
*/
public boolean getUseCompoundFile() throws CorruptIndexException, LockObtainFailedException, IOException {
synchronized(directory) {
assureOpen();
createIndexWriter();
return indexWriter.getUseCompoundFile();
}
}
/**
* The maximum number of terms that will be indexed for a single field in a
* document. This limits the amount of memory required for indexing, so that
* collections with very large files will not crash the indexing process by
* running out of memory.<p/>
* Note that this effectively truncates large documents, excluding from the
* index terms that occur further in the document. If you know your source
* documents are large, be sure to set this value high enough to accomodate
* the expected size. If you set it to Integer.MAX_VALUE, then the only limit
* is your memory, but you should anticipate an OutOfMemoryError.<p/>
* By default, no more than 10,000 terms will be indexed for a field.
* @see IndexWriter#setMaxFieldLength(int)
* @throws IllegalStateException if the index is closed
*/
public void setMaxFieldLength(int maxFieldLength) {
synchronized(directory) {
assureOpen();
if (indexWriter != null) {
indexWriter.setMaxFieldLength(maxFieldLength);
}
this.maxFieldLength = maxFieldLength;
}
}
/**
* @see IndexModifier#setMaxFieldLength(int)
* @throws CorruptIndexException if the index is corrupt
* @throws LockObtainFailedException if another writer
* has this index open (<code>write.lock</code> could not
* be obtained)
* @throws IOException if there is a low-level IO error
*/
public int getMaxFieldLength() throws CorruptIndexException, LockObtainFailedException, IOException {
synchronized(directory) {
assureOpen();
createIndexWriter();
return indexWriter.getMaxFieldLength();
}
}
/**
* Determines the minimal number of documents required before the buffered
* in-memory documents are merging and a new Segment is created.
* Since Documents are merged in a {@link org.apache.lucene.store.RAMDirectory},
* large value gives faster indexing. At the same time, mergeFactor limits
* the number of files open in a FSDirectory.
*
* <p>The default value is 10.
*
* @see IndexWriter#setMaxBufferedDocs(int)
* @throws IllegalStateException if the index is closed
* @throws IllegalArgumentException if maxBufferedDocs is smaller than 2
*/
public void setMaxBufferedDocs(int maxBufferedDocs) {
synchronized(directory) {
assureOpen();
if (indexWriter != null) {
indexWriter.setMaxBufferedDocs(maxBufferedDocs);
}
this.maxBufferedDocs = maxBufferedDocs;
}
}
/**
* @see IndexModifier#setMaxBufferedDocs(int)
* @throws CorruptIndexException if the index is corrupt
* @throws LockObtainFailedException if another writer
* has this index open (<code>write.lock</code> could not
* be obtained)
* @throws IOException if there is a low-level IO error
*/
public int getMaxBufferedDocs() throws CorruptIndexException, LockObtainFailedException, IOException {
synchronized(directory) {
assureOpen();
createIndexWriter();
return indexWriter.getMaxBufferedDocs();
}
}
/**
* Determines how often segment indices are merged by addDocument(). With
* smaller values, less RAM is used while indexing, and searches on
* unoptimized indices are faster, but indexing speed is slower. With larger
* values, more RAM is used during indexing, and while searches on unoptimized
* indices are slower, indexing is faster. Thus larger values (> 10) are best
* for batch index creation, and smaller values (< 10) for indices that are
* interactively maintained.
* <p>This must never be less than 2. The default value is 10.
*
* @see IndexWriter#setMergeFactor(int)
* @throws IllegalStateException if the index is closed
*/
public void setMergeFactor(int mergeFactor) {
synchronized(directory) {
assureOpen();
if (indexWriter != null) {
indexWriter.setMergeFactor(mergeFactor);
}
this.mergeFactor = mergeFactor;
}
}
/**
* @see IndexModifier#setMergeFactor(int)
* @throws CorruptIndexException if the index is corrupt
* @throws LockObtainFailedException if another writer
* has this index open (<code>write.lock</code> could not
* be obtained)
* @throws IOException if there is a low-level IO error
*/
public int getMergeFactor() throws CorruptIndexException, LockObtainFailedException, IOException {
synchronized(directory) {
assureOpen();
createIndexWriter();
return indexWriter.getMergeFactor();
}
}
/**
* Close this index, writing all pending changes to disk.
*
* @throws IllegalStateException if the index has been closed before already
* @throws CorruptIndexException if the index is corrupt
* @throws IOException if there is a low-level IO error
*/
public void close() throws CorruptIndexException, IOException {
synchronized(directory) {
if (!open)
throw new IllegalStateException("Index is closed already");
if (indexWriter != null) {
indexWriter.close();
indexWriter = null;
} else if (indexReader != null) {
indexReader.close();
indexReader = null;
}
open = false;
}
}
public String toString() {
return "Index@" + directory;
}
/*
// used as an example in the javadoc:
public static void main(String[] args) throws IOException {
Analyzer analyzer = new StandardAnalyzer();
// create an index in /tmp/index, overwriting an existing one:
IndexModifier indexModifier = new IndexModifier("/tmp/index", analyzer, true);
Document doc = new Document();
doc.add(new Fieldable("id", "1", Fieldable.Store.YES, Fieldable.Index.UN_TOKENIZED));
doc.add(new Fieldable("body", "a simple test", Fieldable.Store.YES, Fieldable.Index.TOKENIZED));
indexModifier.addDocument(doc);
int deleted = indexModifier.delete(new Term("id", "1"));
System.out.println("Deleted " + deleted + " document");
indexModifier.flush();
System.out.println(indexModifier.docCount() + " docs in index");
indexModifier.close();
}*/
}
| add warnings to javadoc for IndexModifier.docCount
git-svn-id: 4c5078813df38efa56971a28e09a55254294f104@649598 13f79535-47bb-0310-9956-ffa450edef68
| src/java/org/apache/lucene/index/IndexModifier.java | add warnings to javadoc for IndexModifier.docCount | <ide><path>rc/java/org/apache/lucene/index/IndexModifier.java
<ide>
<ide>
<ide> /**
<del> * Returns the number of documents currently in this index.
<del> * @see IndexWriter#docCount()
<del> * @see IndexReader#numDocs()
<add> * Returns the number of documents currently in this
<add> * index. If the writer is currently open, this returns
<add> * {@link IndexWriter#docCount()}, else {@link
<add> * IndexReader#numDocs()}. But, note that {@link
<add> * IndexWriter#docCount()} does not take deletions into
<add> * account, unlike {@link IndexReader#numDocs}.
<ide> * @throws IllegalStateException if the index is closed
<ide> */
<ide> public int docCount() { |
|
Java | epl-1.0 | 0c73bab0fee973d18d3dd4f33f5dea913b8fa2b7 | 0 | windup/windup,windup/windup,johnsteele/windup,mareknovotny/windup,mareknovotny/windup,jsight/windup,windup/windup,jsight/windup,windup/windup,OndraZizka/windup,Maarc/windup,johnsteele/windup,johnsteele/windup,OndraZizka/windup,d-s/windup,Maarc/windup,mareknovotny/windup,OndraZizka/windup,Maarc/windup,d-s/windup,jsight/windup,jsight/windup,johnsteele/windup,Maarc/windup,mareknovotny/windup,d-s/windup,d-s/windup,OndraZizka/windup | package org.jboss.windup.rules.apps.java.scan.provider;
import java.util.ArrayList;
import java.util.List;
import com.tinkerpop.blueprints.Direction;
import org.jboss.windup.config.AbstractRuleProvider;
import org.jboss.windup.config.GraphRewrite;
import org.jboss.windup.config.metadata.MetadataBuilder;
import org.jboss.windup.config.operation.Iteration;
import org.jboss.windup.config.operation.IterationProgress;
import org.jboss.windup.config.operation.iteration.AbstractIterationFilter;
import org.jboss.windup.config.operation.iteration.AbstractIterationOperation;
import org.jboss.windup.config.phase.DiscoverProjectStructurePhase;
import org.jboss.windup.config.query.Query;
import org.jboss.windup.graph.GraphContext;
import org.jboss.windup.graph.model.ArchiveModel;
import org.jboss.windup.graph.model.ProjectModel;
import org.jboss.windup.graph.model.resource.FileModel;
import org.jboss.windup.graph.service.ProjectService;
import org.jboss.windup.util.ZipUtil;
import org.ocpsoft.rewrite.config.Configuration;
import org.ocpsoft.rewrite.config.ConfigurationBuilder;
import org.ocpsoft.rewrite.context.EvaluationContext;
/**
* Finds Archives that were not classified as Maven archives/projects, and adds some generic project information for
* them.
*
* @author <a href="mailto:[email protected]">Lincoln Baxter, III</a>
*/
public class DiscoverNonMavenArchiveProjectsRuleProvider extends AbstractRuleProvider
{
public DiscoverNonMavenArchiveProjectsRuleProvider()
{
super(MetadataBuilder.forProvider(DiscoverNonMavenArchiveProjectsRuleProvider.class)
.setPhase(DiscoverProjectStructurePhase.class)
.addExecuteAfter(DiscoverMavenProjectsRuleProvider.class));
}
@Override
public Configuration getConfiguration(GraphContext arg0)
{
// @formatter:off
return ConfigurationBuilder.begin()
.addRule()
.when(
Query.fromType(ArchiveModel.class)
).perform(
Iteration.over(ArchiveModel.class)
.when(new AbstractIterationFilter<ArchiveModel>(){
@Override
public boolean evaluate(GraphRewrite event, EvaluationContext context, ArchiveModel payload)
{
return payload.getProjectModel() == null;
}
@Override
public String toString()
{
return "ProjectModel == null";
}
})
.perform(
new AbstractIterationOperation<ArchiveModel>()
{
@Override
public void perform(GraphRewrite event, EvaluationContext context, ArchiveModel payload)
{
List<ArchiveModel> hierarchy = new ArrayList<>();
ArchiveModel parentArchive = payload;
while(parentArchive != null)
{
hierarchy.add(parentArchive);
// break once we have added a parent with a project model
if (parentArchive.getProjectModel() != null)
{
break;
}
parentArchive = parentArchive.getParentArchive();
}
ProjectModel childProjectModel = null;
ProjectService projectModelService = new ProjectService(event.getGraphContext());
for (ArchiveModel archiveModel : hierarchy)
{
ProjectModel projectModel = archiveModel.getProjectModel();
// create the project if we don't already have one
if (projectModel == null) {
projectModel = projectModelService.create();
projectModel.setName(archiveModel.getArchiveName());
projectModel.setRootFileModel(archiveModel);
projectModel.setDescription("Unidentified Archive");
if(ZipUtil.endsWithZipExtension(archiveModel.getArchiveName()))
{
for (String extension : ZipUtil.getZipExtensions())
{
if(archiveModel.getArchiveName().endsWith(extension))
projectModel.setProjectType(extension);
}
}
archiveModel.setProjectModel(projectModel);
// Attach the project to all files within the archive
for (FileModel f : archiveModel.getContainedFileModels())
{
// don't add archive models, as those really are separate projects...
if (f instanceof ArchiveModel)
continue;
// also, don't set the project model if one is already set
// this uses the edge directly to improve performance
if (f.asVertex().getVertices(Direction.OUT, FileModel.FILE_TO_PROJECT_MODEL).iterator().hasNext())
continue;
// only set it if it has not already been set
f.setProjectModel(projectModel);
projectModel.addFileModel(f);
}
}
if(childProjectModel != null)
{
childProjectModel.setParentProject(projectModel);
}
childProjectModel = projectModel;
}
}
public String toString() {
return "ScanAsNonMavenProject";
}
}
.and(IterationProgress.monitoring("Checking for non-Maven archive", 1))
)
.endIteration()
);
// @formatter:on
}
}
| rules-java/api/src/main/java/org/jboss/windup/rules/apps/java/scan/provider/DiscoverNonMavenArchiveProjectsRuleProvider.java | package org.jboss.windup.rules.apps.java.scan.provider;
import java.util.ArrayList;
import java.util.List;
import org.jboss.windup.config.AbstractRuleProvider;
import org.jboss.windup.config.GraphRewrite;
import org.jboss.windup.config.metadata.MetadataBuilder;
import org.jboss.windup.config.operation.Iteration;
import org.jboss.windup.config.operation.IterationProgress;
import org.jboss.windup.config.operation.iteration.AbstractIterationFilter;
import org.jboss.windup.config.operation.iteration.AbstractIterationOperation;
import org.jboss.windup.config.phase.DiscoverProjectStructurePhase;
import org.jboss.windup.config.query.Query;
import org.jboss.windup.graph.GraphContext;
import org.jboss.windup.graph.model.ArchiveModel;
import org.jboss.windup.graph.model.ProjectModel;
import org.jboss.windup.graph.model.resource.FileModel;
import org.jboss.windup.graph.service.ProjectService;
import org.jboss.windup.util.ZipUtil;
import org.ocpsoft.rewrite.config.Configuration;
import org.ocpsoft.rewrite.config.ConfigurationBuilder;
import org.ocpsoft.rewrite.context.EvaluationContext;
/**
* Finds Archives that were not classified as Maven archives/projects, and adds some generic project information for
* them.
*
* @author <a href="mailto:[email protected]">Lincoln Baxter, III</a>
*/
public class DiscoverNonMavenArchiveProjectsRuleProvider extends AbstractRuleProvider
{
public DiscoverNonMavenArchiveProjectsRuleProvider()
{
super(MetadataBuilder.forProvider(DiscoverNonMavenArchiveProjectsRuleProvider.class)
.setPhase(DiscoverProjectStructurePhase.class)
.addExecuteAfter(DiscoverMavenProjectsRuleProvider.class));
}
@Override
public Configuration getConfiguration(GraphContext arg0)
{
// @formatter:off
return ConfigurationBuilder.begin()
.addRule()
.when(
Query.fromType(ArchiveModel.class)
).perform(
Iteration.over(ArchiveModel.class)
.when(new AbstractIterationFilter<ArchiveModel>(){
@Override
public boolean evaluate(GraphRewrite event, EvaluationContext context, ArchiveModel payload)
{
return payload.getProjectModel() == null;
}
@Override
public String toString()
{
return "ProjectModel == null";
}
})
.perform(
new AbstractIterationOperation<ArchiveModel>()
{
@Override
public void perform(GraphRewrite event, EvaluationContext context, ArchiveModel payload)
{
List<ArchiveModel> hierarchy = new ArrayList<>();
ArchiveModel parentArchive = payload;
while(parentArchive != null)
{
hierarchy.add(parentArchive);
// break once we have added a parent with a project model
if (parentArchive.getProjectModel() != null)
{
break;
}
parentArchive = parentArchive.getParentArchive();
}
ProjectModel childProjectModel = null;
ProjectService projectModelService = new ProjectService(event.getGraphContext());
for (ArchiveModel archiveModel : hierarchy)
{
ProjectModel projectModel = archiveModel.getProjectModel();
// create the project if we don't already have one
if (projectModel == null) {
projectModel = projectModelService.create();
projectModel.setName(archiveModel.getArchiveName());
projectModel.setRootFileModel(archiveModel);
projectModel.setDescription("Unidentified Archive");
if(ZipUtil.endsWithZipExtension(archiveModel.getArchiveName()))
{
for (String extension : ZipUtil.getZipExtensions())
{
if(archiveModel.getArchiveName().endsWith(extension))
projectModel.setProjectType(extension);
}
}
archiveModel.setProjectModel(projectModel);
// Attach the project to all files within the archive
for (FileModel f : archiveModel.getContainedFileModels())
{
// don't add archive models, as those really are separate projects...
// also, don't set the project model if one is already set
if (!(f instanceof ArchiveModel) && f.getProjectModel() == null)
{
// only set it if it has not already been set
f.setProjectModel(projectModel);
projectModel.addFileModel(f);
}
}
}
if(childProjectModel != null)
{
childProjectModel.setParentProject(projectModel);
}
childProjectModel = projectModel;
}
}
public String toString() {
return "ScanAsNonMavenProject";
}
}
.and(IterationProgress.monitoring("Checking for non-Maven archive", 1))
)
.endIteration()
);
// @formatter:on
}
}
| Changed getProject() == null to a more efficient check.
| rules-java/api/src/main/java/org/jboss/windup/rules/apps/java/scan/provider/DiscoverNonMavenArchiveProjectsRuleProvider.java | Changed getProject() == null to a more efficient check. | <ide><path>ules-java/api/src/main/java/org/jboss/windup/rules/apps/java/scan/provider/DiscoverNonMavenArchiveProjectsRuleProvider.java
<ide> import java.util.ArrayList;
<ide> import java.util.List;
<ide>
<add>import com.tinkerpop.blueprints.Direction;
<ide> import org.jboss.windup.config.AbstractRuleProvider;
<ide> import org.jboss.windup.config.GraphRewrite;
<ide> import org.jboss.windup.config.metadata.MetadataBuilder;
<ide> for (FileModel f : archiveModel.getContainedFileModels())
<ide> {
<ide> // don't add archive models, as those really are separate projects...
<add> if (f instanceof ArchiveModel)
<add> continue;
<add>
<ide> // also, don't set the project model if one is already set
<del> if (!(f instanceof ArchiveModel) && f.getProjectModel() == null)
<del> {
<del> // only set it if it has not already been set
<del> f.setProjectModel(projectModel);
<del> projectModel.addFileModel(f);
<del> }
<add> // this uses the edge directly to improve performance
<add> if (f.asVertex().getVertices(Direction.OUT, FileModel.FILE_TO_PROJECT_MODEL).iterator().hasNext())
<add> continue;
<add>
<add> // only set it if it has not already been set
<add> f.setProjectModel(projectModel);
<add> projectModel.addFileModel(f);
<ide> }
<ide> }
<ide> |
|
JavaScript | mit | 64a281a19e31385b285d9849fd1ac9dbd898fde4 | 0 | phetsims/scenery-phet,phetsims/scenery-phet,phetsims/scenery-phet | // Copyright 2017-2018, University of Colorado Boulder
/**
* The lattice is a 2D grid with a value in each cell that represents the wave amplitude at that point.
*
* @author Sam Reid (PhET Interactive Simulations)
*/
define( require => {
'use strict';
// modules
const Bounds2 = require( 'DOT/Bounds2' );
const Emitter = require( 'AXON/Emitter' );
const Matrix = require( 'DOT/Matrix' );
const waveInterference = require( 'WAVE_INTERFERENCE/waveInterference' );
// constants
// The wave speed in the coordinate frame of the lattice, see http://www.mtnmath.com/whatth/node47.html. We tried
// different values, but they do not have the properer emergent behavior. WAVE_SPEED=1 propagates out as a diamond
// rather than a circle, and WAVE_SPEED=0.1 is too slow and throws off the frequency of light.
const WAVE_SPEED = 0.5;
const WAVE_SPEED_SQUARED = WAVE_SPEED * WAVE_SPEED; // precompute to avoid work in the inner loop
const NUMBER_OF_MATRICES = 3; // The algorithm we use for the discretized wave equation requires current value + 2 history points
// This is the threshold for the wave value that determines if the light has visited. If the value is higher,
// it will track the wavefront of the light more accurately (and hence could be used for more accurate computation of
// the speed of light), but will generate more artifacts in the initial wave. If the value is lower, it will generate
// fewer artifacts in the initial propagation, but will lead the initial wavefront by too far and make it seem like
// light is faster than it should be measured (based on the propagation of wavefronts).
const LIGHT_VISIT_THRESHOLD = 0.06;
class Lattice {
/**
* @param {number} width - width of the lattice
* @param {number} height - height of the lattice
* @param {number} dampX - number of cells on the left and again on the right to use for damping
* @param {number} dampY - number of cells on the top and again on the bottom to use for damping
*/
constructor( width, height, dampX, dampY ) {
// @public (read-only) {number} - number of cells on the left and again on the right to use for damping
this.dampX = dampX;
// @public (read-only) {number} - number of cells on the top and again on the bottom to use for damping
this.dampY = dampY;
// @private {Matrix[]} - matrices for current value, previous value and value before previous
this.matrices = [];
for ( let i = 0; i < NUMBER_OF_MATRICES; i++ ) {
this.matrices.push( new Matrix( width, height ) );
}
// @private {Matrix} - keeps track of which cells have been visited by the wave
this.visitedMatrix = new Matrix( width, height );
// @private {number} - indicates the current matrix. Previous matrix is one higher (with correct modulus)
this.currentMatrixIndex = 0;
// @public {Emitter} - sends a notification each time the lattice updates.
this.changedEmitter = new Emitter();
// @public (read-only) {number} - width of the lattice (includes damping regions)
this.width = width;
// @public (read-only) {number} - height of the lattice (includes damping regions)
this.height = height;
// @public {number} - Determines how far we have animated between the "last" and "current" matrices, so that we
// can use getInterpolatedValue to update the view at 60fps even though the model is running at a slower rate
this.interpolationRatio = 0;
// @public (read-only) {Bounds2} - a Bounds2 representing the visible (non-damping) region of the lattice.
this.visibleBounds = new Bounds2( this.dampX, this.dampY, this.width - this.dampX, this.height - this.dampY );
}
/**
* Gets a Bounds2 representing the full region of the lattice, including damping regions.
* @returns {Bounds2}
*/
getBounds() {
return new Bounds2( 0, 0, this.width, this.height );
}
/**
* Returns true if the visible bounds contains the lattice coordinate
* @param {number} i integer for the horizontal coordinate
* @param {number} j integer for the vertical coordinate
* @returns {boolean}
*/
visibleBoundsContains( i, j ) {
const b = this.visibleBounds;
// Note this differs from the standand Bounds2.containsCoordinate because we must exclude right and bottom edge
// from reading one cell off the visible lattice, see https://github.com/phetsims/wave-interference/issues/86
return b.minX <= i && i < b.maxX && b.minY <= j && j < b.maxY;
}
/**
* Returns true if the given coordinate is within the lattice
* @param {number} i integer for the horizontal coordinate
* @param {number} j integer for the vertical coordinate
* @returns {boolean}
* @public
*/
contains( i, j ) {
return i >= 0 && i < this.width && j >= 0 && j < this.height;
}
/**
* Read the values on the center line of the lattice (omits the out-of-bounds damping regions), for display in the
* WaveAreaGraphNode
* @param {number[]} array - array to fill with the values for performance/memory, will be resized if necessary
* @public
*/
getCenterLineValues( array ) {
const samplingWidth = this.width - this.dampX * 2;
// Resize array if necessary
if ( array.length !== samplingWidth ) {
array.length = 0;
}
const samplingVerticalLocation = Math.round( this.height / 2 );
for ( let i = 0; i < this.width - this.dampX * 2; i++ ) {
array[ i ] = this.getCurrentValue( i + this.dampX, samplingVerticalLocation );
}
return array;
}
/**
* Returns the current value in the given cell
* @param {number} i - horizontal integer coordinate
* @param {number} j - vertical integer coordinate
* @returns {number}
* @public
*/
getCurrentValue( i, j ) {
return this.matrices[ this.currentMatrixIndex ].get( i, j );
}
/**
* Returns the interpolated value of the given cell
* @param {number} i - horizontal integer coordinate
* @param {number} j - vertical integer coordinate
* @returns {number}
* @public
*/
getInterpolatedValue( i, j ) {
return this.getCurrentValue( i, j ) * this.interpolationRatio + this.getLastValue( i, j ) * ( 1 - this.interpolationRatio );
}
/**
* Sets the current value in the given cell
* @param {number} i - horizontal integer coordinate
* @param {number} j - vertical integer coordinate
* @param {number} value
* @public
*/
setCurrentValue( i, j, value ) {
this.matrices[ this.currentMatrixIndex ].set( i, j, value );
}
/**
* Returns the previous value in the given cell
* @param {number} i - horizontal integer coordinate
* @param {number} j - vertical integer coordinate
* @private
*/
getLastValue( i, j ) {
return this.matrices[ ( this.currentMatrixIndex + 1 ) % this.matrices.length ].get( i, j );
}
/**
* Sets the previous value in the given cell
* @param {number} i - horizontal integer coordinate
* @param {number} j - vertical integer coordinate
* @param {number} value
* @private
*/
setLastValue( i, j, value ) {
this.matrices[ ( this.currentMatrixIndex + 1 ) % this.matrices.length ].set( i, j, value );
}
/**
* Across a horizontal line, dampen the waveform based on past adjacent values. Developed in the Java version as
* one step in preventing artifacts near the edge of the visible part of the lattice.
* @param {number} j - y coordinate for the lattice
* @param {number} dj - distance above or below to look
* @param {Matrix} matrix0 - current matrix
* @param {Matrix} matrix2 - two time steps ago
* @private
*/
dampHorizontalTemporal( j, dj, matrix0, matrix2 ) {
for ( let i = 0; i < this.width; i++ ) {
matrix0.set( i, j, matrix2.get( i, j + dj ) );
}
}
/**
* Across a vertical line, dampen the waveform based on past adjacent values. Developed in the Java version as
* one step in preventing artifacts near the edge of the visible part of the lattice.
* @param {number} i - x coordinate for the lattice
* @param {number} di - distance left or right to look
* @param {Matrix} matrix0 - current matrix
* @param {Matrix} matrix2 - two time steps ago
* @private
*/
dampVerticalTemporal( i, di, matrix0, matrix2 ) {
for ( let j = 0; j < this.height; j++ ) {
matrix0.set( i, j, matrix2.get( i + di, j ) );
}
}
/**
* Exponential decay in a vertical band to prevent reflections or artifacts from the sides of the lattice.
* @param {number} i0 - x coordinate of the damping region
* @param {number} sign - +1 or -1 depending on which way the damping moves
* @param {number} width - width of the damping region
* @private
*/
decayVertical( i0, sign, width ) {
for ( let j = 0; j < this.height; j++ ) {
for ( let step = 0; step < width; step++ ) {
const distFromDampBoundary = width - step;
const damp = this.getDamp( distFromDampBoundary );
const i = i0 + step * sign;
this.setCurrentValue( i, j, this.getCurrentValue( i, j ) * damp );
this.setLastValue( i, j, this.getLastValue( i, j ) * damp );
}
}
}
/**
* Exponential decay in a horizontal band to prevent reflections or artifacts from the sides of the lattice.
* @param {number} j0 - y coordinate of the damping region
* @param {number} sign - +1 or -1 depending on which way the damping moves
* @param {number} height - height of the damping region
* @private
*/
decayHorizontal( j0, sign, height ) {
for ( let i = 0; i < this.width; i++ ) {
for ( let step = 0; step < height; step++ ) {
const distFromDampBoundary = height - step;
const damp = this.getDamp( distFromDampBoundary );
const j = j0 + step * sign;
this.setCurrentValue( i, j, this.getCurrentValue( i, j ) * damp );
this.setLastValue( i, j, this.getLastValue( i, j ) * damp );
}
}
}
/**
* Determines whether the incoming wave has reached the cell.
* @param {number} i - horizontal coordinate to check
* @param {number} j - vertical coordinate to check
* @returns {boolean}
*/
hasCellBeenVisited( i, j ) {
return this.visitedMatrix.get( i, j ) === 1;
}
/**
* Damp more aggressively further from the edge of the visible lattice
* @param {number} depthInDampRegion - number of cells into the damping region
* @returns {number} scale factor for dampening the wave
* @private
*/
getDamp( depthInDampRegion ) {
return ( 1 - depthInDampRegion * 0.0001 );
}
/**
* Resets all of the wave values to 0
* @public
*/
clear() {
for ( let i = 0; i < this.matrices.length; i++ ) {
this.matrices[ i ].timesEquals( 0 );
}
this.visitedMatrix.timesEquals( 0 );
}
/**
* Gets the values on the right hand side of the wave (before the damping region), for determining intensity.
* @returns {number[]}
* @public
*/
getOutputColumn() {
// This could be implemented in garbage-free from by require preallocating the entire intensitySample matrix and
// using an index pointer like a circular array. However, profiling in Mac Chrome did not show a significant
// amount of time spent in this function, hence we use the simpler implementation.
const column = [];
for ( let j = this.dampY; j < this.height - this.dampY; j++ ) {
column.push( this.getCurrentValue( this.width - this.dampX - 1, j ) );
}
return column;
}
/**
* Propagates the wave by one step. This is a discrete algorithm and cannot use dt.
* @param {function} forcingFunction - sets values before and after the wave equation
* @public
*/
step( forcingFunction ) {
// Apply values before lattice step so the values will be used to propagate
forcingFunction();
this.currentMatrixIndex = ( this.currentMatrixIndex - 1 + this.matrices.length ) % this.matrices.length;
const matrix0 = this.matrices[ ( this.currentMatrixIndex + 0 ) % this.matrices.length ];
const matrix1 = this.matrices[ ( this.currentMatrixIndex + 1 ) % this.matrices.length ];
const matrix2 = this.matrices[ ( this.currentMatrixIndex + 2 ) % this.matrices.length ];
const width = matrix0.getRowDimension();
const height = matrix0.getColumnDimension();
// Main loop, doesn't update cells on the edges
for ( let i = 1; i < width - 1; i++ ) {
for ( let j = 1; j < height - 1; j++ ) {
const neighborSum = matrix1.get( i + 1, j ) + matrix1.get( i - 1, j ) + matrix1.get( i, j + 1 ) + matrix1.get( i, j - 1 );
const m1ij = matrix1.get( i, j );
const value = m1ij * 2 - matrix2.get( i, j ) + WAVE_SPEED_SQUARED * ( neighborSum + m1ij * -4 );
matrix0.set( i, j, value );
if ( Math.abs( value ) > LIGHT_VISIT_THRESHOLD ) {
this.visitedMatrix.set( i, j, 1 );
}
}
}
// temporal dampen on the visible region
this.dampHorizontalTemporal( 0, 1, matrix0, matrix2 );
this.dampHorizontalTemporal( this.height - 1, -1, matrix0, matrix2 );
this.dampVerticalTemporal( 0, +1, matrix0, matrix2 );
this.dampVerticalTemporal( this.width - 1, -1, matrix0, matrix2 );
// decay the wave outside of the visible part
this.decayVertical( 0, +1, this.dampY / 2 );
this.decayVertical( this.width - 1, -1, this.dampY / 2 );
this.decayHorizontal( 0, +1, this.dampX / 2 );
this.decayHorizontal( this.height - 1, -1, this.dampX / 2 );
// Apply values on top of the computed lattice values so there is no noise at the point sources
forcingFunction();
}
}
return waveInterference.register( 'Lattice', Lattice );
} ); | js/common/model/Lattice.js | // Copyright 2017-2018, University of Colorado Boulder
/**
* The lattice is a 2D grid with a value in each cell that represents the wave amplitude at that point.
*
* @author Sam Reid (PhET Interactive Simulations)
*/
define( require => {
'use strict';
// modules
const Bounds2 = require( 'DOT/Bounds2' );
const Emitter = require( 'AXON/Emitter' );
const Matrix = require( 'DOT/Matrix' );
const waveInterference = require( 'WAVE_INTERFERENCE/waveInterference' );
// constants
// The wave speed in the coordinate frame of the lattice, see http://www.mtnmath.com/whatth/node47.html. We tried
// different values, but they do not have the properer emergent behavior. WAVE_SPEED=1 propagates out as a diamond
// rather than a circle, and WAVE_SPEED=0.1 is too slow and throws off the frequency of light.
const WAVE_SPEED = 0.5;
const WAVE_SPEED_SQUARED = WAVE_SPEED * WAVE_SPEED; // precompute to avoid work in the inner loop
const NUMBER_OF_MATRICES = 3; // The algorithm we use for the discretized wave equation requires current value + 2 history points
// This is the threshold for the wave value that determines if the light has visited. If the value is higher,
// it will track the wavefront of the light more accurately (and hence could be used for more accurate computation of
// the speed of light), but will generate more artifacts in the initial wave. If the value is lower, it will generate
// fewer artifacts in the initial propagation, but will lead the initial wavefront by too far and make it seem like
// light is faster than it should be measured (based on the propagation of wavefronts).
const LIGHT_VISIT_THRESHOLD = 0.06;
class Lattice {
/**
* @param {number} width - width of the lattice
* @param {number} height - height of the lattice
* @param {number} dampX - number of cells on the left and again on the right to use for damping
* @param {number} dampY - number of cells on the top and again on the bottom to use for damping
*/
constructor( width, height, dampX, dampY ) {
// @public (read-only) {number} - number of cells on the left and again on the right to use for damping
this.dampX = dampX;
// @public (read-only) {number} - number of cells on the top and again on the bottom to use for damping
this.dampY = dampY;
// @private {Matrix[]} - matrices for current value, previous value and value before previous
this.matrices = [];
for ( let i = 0; i < NUMBER_OF_MATRICES; i++ ) {
this.matrices.push( new Matrix( width, height ) );
}
// @private {Matrix} - keeps track of which cells have been visited by the wave
this.visitedMatrix = new Matrix( width, height );
// @private {number} - indicates the current matrix. Previous matrix is one higher (with correct modulus)
this.currentMatrixIndex = 0;
// @public {Emitter} - sends a notification each time the lattice updates.
this.changedEmitter = new Emitter();
// @public (read-only) {number} - width of the lattice (includes damping regions)
this.width = width;
// @public (read-only) {number} - height of the lattice (includes damping regions)
this.height = height;
// @public {number} - Determines how far we have animated between the "last" and "current" matrices, so that we
// can use getInterpolatedValue to update the view at 60fps even though the model is running at a slower rate
this.interpolationRatio = 0;
// @public (read-only) {Bounds2} - a Bounds2 representing the visible (non-damping) region of the lattice.
this.visibleBounds = new Bounds2( this.dampX, this.dampY, this.width - this.dampX, this.height - this.dampY );
}
/**
* Gets a Bounds2 representing the full region of the lattice, including damping regions.
* @returns {Bounds2}
*/
getBounds() {
return new Bounds2( 0, 0, this.width, this.height );
}
/**
* Returns true if the visible bounds contains the lattice coordinate
* @param {number} i integer for the horizontal coordinate
* @param {number} j integer for the vertical coordinate
* @returns {boolean}
*/
visibleBoundsContains( i, j ) {
const b = this.visibleBounds;
// Note this differs from the standand Bounds2.containsCoordinate because we must exclude right and bottom edge
// from reading one cell off the visible lattice, see https://github.com/phetsims/wave-interference/issues/86
return b.minX <= i && i < b.maxX && b.minY <= j && j < b.maxY;
}
/**
* Read the values on the center line of the lattice (omits the out-of-bounds damping regions), for display in the
* WaveAreaGraphNode
* @param {number[]} array - array to fill with the values for performance/memory, will be resized if necessary
* @public
*/
getCenterLineValues( array ) {
const samplingWidth = this.width - this.dampX * 2;
// Resize array if necessary
if ( array.length !== samplingWidth ) {
array.length = 0;
}
const samplingVerticalLocation = Math.round( this.height / 2 );
for ( let i = 0; i < this.width - this.dampX * 2; i++ ) {
array[ i ] = this.getCurrentValue( i + this.dampX, samplingVerticalLocation );
}
return array;
}
/**
* Returns the current value in the given cell
* @param {number} i - horizontal integer coordinate
* @param {number} j - vertical integer coordinate
* @returns {number}
* @public
*/
getCurrentValue( i, j ) {
return this.matrices[ this.currentMatrixIndex ].get( i, j );
}
/**
* Returns the interpolated value of the given cell
* @param {number} i - horizontal integer coordinate
* @param {number} j - vertical integer coordinate
* @returns {number}
* @public
*/
getInterpolatedValue( i, j ) {
return this.getCurrentValue( i, j ) * this.interpolationRatio + this.getLastValue( i, j ) * ( 1 - this.interpolationRatio );
}
/**
* Sets the current value in the given cell
* @param {number} i - horizontal integer coordinate
* @param {number} j - vertical integer coordinate
* @param {number} value
* @public
*/
setCurrentValue( i, j, value ) {
this.matrices[ this.currentMatrixIndex ].set( i, j, value );
}
/**
* Returns the previous value in the given cell
* @param {number} i - horizontal integer coordinate
* @param {number} j - vertical integer coordinate
* @private
*/
getLastValue( i, j ) {
return this.matrices[ ( this.currentMatrixIndex + 1 ) % this.matrices.length ].get( i, j );
}
/**
* Sets the previous value in the given cell
* @param {number} i - horizontal integer coordinate
* @param {number} j - vertical integer coordinate
* @param {number} value
* @private
*/
setLastValue( i, j, value ) {
this.matrices[ ( this.currentMatrixIndex + 1 ) % this.matrices.length ].set( i, j, value );
}
/**
* Across a horizontal line, dampen the waveform based on past adjacent values. Developed in the Java version as
* one step in preventing artifacts near the edge of the visible part of the lattice.
* @param {number} j - y coordinate for the lattice
* @param {number} dj - distance above or below to look
* @param {Matrix} matrix0 - current matrix
* @param {Matrix} matrix2 - two time steps ago
* @private
*/
dampHorizontalTemporal( j, dj, matrix0, matrix2 ) {
for ( let i = 0; i < this.width; i++ ) {
matrix0.set( i, j, matrix2.get( i, j + dj ) );
}
}
/**
* Across a vertical line, dampen the waveform based on past adjacent values. Developed in the Java version as
* one step in preventing artifacts near the edge of the visible part of the lattice.
* @param {number} i - x coordinate for the lattice
* @param {number} di - distance left or right to look
* @param {Matrix} matrix0 - current matrix
* @param {Matrix} matrix2 - two time steps ago
* @private
*/
dampVerticalTemporal( i, di, matrix0, matrix2 ) {
for ( let j = 0; j < this.height; j++ ) {
matrix0.set( i, j, matrix2.get( i + di, j ) );
}
}
/**
* Exponential decay in a vertical band to prevent reflections or artifacts from the sides of the lattice.
* @param {number} i0 - x coordinate of the damping region
* @param {number} sign - +1 or -1 depending on which way the damping moves
* @param {number} width - width of the damping region
* @private
*/
decayVertical( i0, sign, width ) {
for ( let j = 0; j < this.height; j++ ) {
for ( let step = 0; step < width; step++ ) {
const distFromDampBoundary = width - step;
const damp = this.getDamp( distFromDampBoundary );
const i = i0 + step * sign;
this.setCurrentValue( i, j, this.getCurrentValue( i, j ) * damp );
this.setLastValue( i, j, this.getLastValue( i, j ) * damp );
}
}
}
/**
* Exponential decay in a horizontal band to prevent reflections or artifacts from the sides of the lattice.
* @param {number} j0 - y coordinate of the damping region
* @param {number} sign - +1 or -1 depending on which way the damping moves
* @param {number} height - height of the damping region
* @private
*/
decayHorizontal( j0, sign, height ) {
for ( let i = 0; i < this.width; i++ ) {
for ( let step = 0; step < height; step++ ) {
const distFromDampBoundary = height - step;
const damp = this.getDamp( distFromDampBoundary );
const j = j0 + step * sign;
this.setCurrentValue( i, j, this.getCurrentValue( i, j ) * damp );
this.setLastValue( i, j, this.getLastValue( i, j ) * damp );
}
}
}
/**
* Determines whether the incoming wave has reached the cell.
* @param {number} i - horizontal coordinate to check
* @param {number} j - vertical coordinate to check
* @returns {boolean}
*/
hasCellBeenVisited( i, j ) {
return this.visitedMatrix.get( i, j ) === 1;
}
/**
* Damp more aggressively further from the edge of the visible lattice
* @param {number} depthInDampRegion - number of cells into the damping region
* @returns {number} scale factor for dampening the wave
* @private
*/
getDamp( depthInDampRegion ) {
return ( 1 - depthInDampRegion * 0.0001 );
}
/**
* Resets all of the wave values to 0
* @public
*/
clear() {
for ( let i = 0; i < this.matrices.length; i++ ) {
this.matrices[ i ].timesEquals( 0 );
}
this.visitedMatrix.timesEquals( 0 );
}
/**
* Gets the values on the right hand side of the wave (before the damping region), for determining intensity.
* @returns {number[]}
* @public
*/
getOutputColumn() {
// This could be implemented in garbage-free from by require preallocating the entire intensitySample matrix and
// using an index pointer like a circular array. However, profiling in Mac Chrome did not show a significant
// amount of time spent in this function, hence we use the simpler implementation.
const column = [];
for ( let j = this.dampY; j < this.height - this.dampY; j++ ) {
column.push( this.getCurrentValue( this.width - this.dampX - 1, j ) );
}
return column;
}
/**
* Propagates the wave by one step. This is a discrete algorithm and cannot use dt.
* @param {function} forcingFunction - sets values before and after the wave equation
* @public
*/
step( forcingFunction ) {
// Apply values before lattice step so the values will be used to propagate
forcingFunction();
this.currentMatrixIndex = ( this.currentMatrixIndex - 1 + this.matrices.length ) % this.matrices.length;
const matrix0 = this.matrices[ ( this.currentMatrixIndex + 0 ) % this.matrices.length ];
const matrix1 = this.matrices[ ( this.currentMatrixIndex + 1 ) % this.matrices.length ];
const matrix2 = this.matrices[ ( this.currentMatrixIndex + 2 ) % this.matrices.length ];
const width = matrix0.getRowDimension();
const height = matrix0.getColumnDimension();
// Main loop, doesn't update cells on the edges
for ( let i = 1; i < width - 1; i++ ) {
for ( let j = 1; j < height - 1; j++ ) {
const neighborSum = matrix1.get( i + 1, j ) + matrix1.get( i - 1, j ) + matrix1.get( i, j + 1 ) + matrix1.get( i, j - 1 );
const m1ij = matrix1.get( i, j );
const value = m1ij * 2 - matrix2.get( i, j ) + WAVE_SPEED_SQUARED * ( neighborSum + m1ij * -4 );
matrix0.set( i, j, value );
if ( Math.abs( value ) > LIGHT_VISIT_THRESHOLD ) {
this.visitedMatrix.set( i, j, 1 );
}
}
}
// temporal dampen on the visible region
this.dampHorizontalTemporal( 0, 1, matrix0, matrix2 );
this.dampHorizontalTemporal( this.height - 1, -1, matrix0, matrix2 );
this.dampVerticalTemporal( 0, +1, matrix0, matrix2 );
this.dampVerticalTemporal( this.width - 1, -1, matrix0, matrix2 );
// decay the wave outside of the visible part
this.decayVertical( 0, +1, this.dampY / 2 );
this.decayVertical( this.width - 1, -1, this.dampY / 2 );
this.decayHorizontal( 0, +1, this.dampX / 2 );
this.decayHorizontal( this.height - 1, -1, this.dampX / 2 );
// Apply values on top of the computed lattice values so there is no noise at the point sources
forcingFunction();
}
}
return waveInterference.register( 'Lattice', Lattice );
} ); | Use entire search area for applied forces, see https://github.com/phetsims/wave-interference/issues/39
| js/common/model/Lattice.js | Use entire search area for applied forces, see https://github.com/phetsims/wave-interference/issues/39 | <ide><path>s/common/model/Lattice.js
<ide> // Note this differs from the standand Bounds2.containsCoordinate because we must exclude right and bottom edge
<ide> // from reading one cell off the visible lattice, see https://github.com/phetsims/wave-interference/issues/86
<ide> return b.minX <= i && i < b.maxX && b.minY <= j && j < b.maxY;
<add> }
<add>
<add> /**
<add> * Returns true if the given coordinate is within the lattice
<add> * @param {number} i integer for the horizontal coordinate
<add> * @param {number} j integer for the vertical coordinate
<add> * @returns {boolean}
<add> * @public
<add> */
<add> contains( i, j ) {
<add> return i >= 0 && i < this.width && j >= 0 && j < this.height;
<ide> }
<ide>
<ide> /** |
|
JavaScript | mit | 7fa949f2025c10971dbab6730bebc8abe09c0b51 | 0 | rosamcgee/tangram,zerebubuth/tangram,ceseale/tangram,xvilan/tangram,TitoAgudelo/tangram,TitoAgudelo/tangram,taylorhxu/tangram,tangrams/tangram,TitoAgudelo/tangram,rosamcgee/tangram,zerebubuth/tangram,rosamcgee/tangram,xvilan/tangram,tangrams/tangram,DHaylock/tangram,DHaylock/tangram,ceseale/tangram,taylorhxu/tangram,ceseale/tangram,DHaylock/tangram,xvilan/tangram,zerebubuth/tangram,taylorhxu/tangram | // Rendering modes
var GL = require('./gl.js');
var GLBuilders = require('./gl_builders.js');
var GLGeometry = require('./gl_geom.js');
var GLVertexLayout = require('./gl_vertex_layout.js');
var GLProgram = require('./gl_program.js');
var GLTexture = require('./gl_texture.js');
var shader_sources = require('./gl_shaders.js'); // built-in shaders
var Queue = require('queue-async');
// Base
var RenderMode = {
init: function (gl) {
this.gl = gl;
this.makeGLProgram();
if (typeof this._init == 'function') {
this._init();
}
},
refresh: function () { // TODO: should this be async/non-blocking?
this.makeGLProgram();
},
defines: {},
selection: false,
buildPolygons: function(){}, // build functions are no-ops until overriden
buildLines: function(){},
buildPoints: function(){},
makeGLGeometry: function (vertex_data) {
return new GLGeometry(this.gl, vertex_data, this.vertex_layout);
}
};
// TODO: should this entire operation be async/non-blocking?
// TODO: don't re-create GLProgram instance every time, just update existing one
RenderMode.makeGLProgram = function ()
{
// Add any custom defines to built-in mode defines
var defines = {}; // create a new object to avoid mutating a prototype value that may be shared with other modes
if (this.defines != null) {
for (var d in this.defines) {
defines[d] = this.defines[d];
}
}
if (this.shaders != null && this.shaders.defines != null) {
for (var d in this.shaders.defines) {
defines[d] = this.shaders.defines[d];
}
}
// Alter defines for selection (need to create a new object since the first is stored as a reference by the program)
if (this.selection) {
var selection_defines = Object.create(defines);
selection_defines['FEATURE_SELECTION'] = true;
}
// Get any custom code transforms
var transforms = (this.shaders && this.shaders.transforms);
// Create shader from custom URLs
var program, selection_program;
var queue = Queue();
if (this.shaders && this.shaders.vertex_url && this.shaders.fragment_url) {
queue.defer(function(complete) {
program = GLProgram.createProgramFromURLs(
this.gl,
this.shaders.vertex_url,
this.shaders.fragment_url,
{ defines: defines, transforms: transforms, name: this.name, callback: complete }
);
}.bind(this));
if (this.selection) {
queue.defer(function(complete) {
selection_program = new GLProgram(
this.gl,
this.gl_program.vertex_shader_source,
shader_sources['selection_fragment'],
{ defines: selection_defines, transforms: transforms, name: (this.name + ' (selection)'), callback: complete }
);
}.bind(this));
}
}
// Create shader from built-in source
else {
queue.defer(function(complete) {
program = new GLProgram(
this.gl,
shader_sources[this.vertex_shader_key],
shader_sources[this.fragment_shader_key],
{ defines: defines, transforms: transforms, name: this.name, callback: complete }
);
}.bind(this));
if (this.selection) {
queue.defer(function(complete) {
selection_program = new GLProgram(
this.gl,
shader_sources[this.vertex_shader_key],
shader_sources['selection_fragment'],
{ defines: selection_defines, transforms: transforms, name: (this.name + ' (selection)'), callback: complete }
);
}.bind(this));
}
}
// Wait for program(s) to compile before replacing them
queue.await(function() {
if (program) {
this.gl_program = program;
}
if (selection_program) {
this.selection_gl_program = selection_program;
}
}.bind(this));
};
// TODO: make this a generic ORM-like feature for setting uniforms via JS objects on GLProgram
RenderMode.setUniforms = function (options)
{
options = options || {};
var gl_program = GLProgram.current; // operate on currently bound program
// TODO: only update uniforms when changed
if (this.shaders != null && this.shaders.uniforms != null) {
var texture_unit = 0;
for (var u in this.shaders.uniforms) {
var uniform = this.shaders.uniforms[u];
// Single float
if (typeof uniform == 'number') {
gl_program.uniform('1f', u, uniform);
}
// Multiple floats - vector or array
else if (typeof uniform == 'object') {
// float vectors (vec2, vec3, vec4)
if (uniform.length >= 2 && uniform.length <= 4) {
gl_program.uniform(uniform.length + 'fv', u, uniform);
}
// float array
else if (uniform.length > 4) {
gl_program.uniform('1fv', u + '[0]', uniform);
}
// TODO: assume matrix for (typeof == Float32Array && length == 16)?
}
// Boolean
else if (typeof this.shaders.uniforms[u] == 'boolean') {
gl_program.uniform('1i', u, uniform);
}
// Texture
else if (typeof uniform == 'string') {
var texture = GLTexture.textures[uniform];
if (texture == null) {
texture = new GLTexture(this.gl, uniform);
texture.load(uniform);
}
texture.bind(texture_unit);
gl_program.uniform('1i', u, texture_unit);
texture_unit++;
}
// TODO: support other non-float types? (int, etc.)
}
}
};
RenderMode.update = function ()
{
// Mode-specific animation
if (typeof this.animation == 'function') {
this.animation();
}
};
var Modes = {};
var ModeManager = {};
// Update built-in mode or create a new one
ModeManager.configureMode = function (name, settings)
{
Modes[name] = Modes[name] || Object.create(Modes[settings.extends] || RenderMode);
if (Modes[settings.extends]) {
Modes[name].parent = Modes[settings.extends]; // explicit 'super' class access
}
for (var s in settings) {
Modes[name][s] = settings[s];
}
Modes[name].name = name;
return Modes[name];
};
// Built-in rendering modes
/*** Plain polygons ***/
Modes.polygons = Object.create(RenderMode);
Modes.polygons.name = 'polygons';
Modes.polygons.vertex_shader_key = 'polygon_vertex';
Modes.polygons.fragment_shader_key = 'polygon_fragment';
Modes.polygons.defines = {
'WORLD_POSITION_WRAP': 100000 // default world coords to wrap every 100,000 meters, can turn off by setting this to 'false'
};
Modes.polygons.selection = true;
Modes.polygons._init = function () {
this.vertex_layout = new GLVertexLayout(this.gl, [
{ name: 'a_position', size: 3, type: this.gl.FLOAT, normalized: false },
{ name: 'a_normal', size: 3, type: this.gl.FLOAT, normalized: false },
{ name: 'a_color', size: 3, type: this.gl.FLOAT, normalized: false },
{ name: 'a_selection_color', size: 4, type: this.gl.FLOAT, normalized: false },
{ name: 'a_layer', size: 1, type: this.gl.FLOAT, normalized: false }
]);
};
Modes.polygons.buildPolygons = function (polygons, style, vertex_data)
{
// Color and layer number are currently constant across vertices
var vertex_constants = [
style.color[0], style.color[1], style.color[2],
style.selection.color[0], style.selection.color[1], style.selection.color[2], style.selection.color[3],
style.layer_num
];
// Outlines have a slightly different set of constants, because the layer number is modified
if (style.outline.color) {
var outline_vertex_constants = [
style.outline.color[0], style.outline.color[1], style.outline.color[2],
style.selection.color[0], style.selection.color[1], style.selection.color[2], style.selection.color[3],
style.layer_num - 0.5 // outlines sit between layers, underneath current layer but above the one below
];
}
// Extruded polygons (e.g. 3D buildings)
if (style.extrude && style.height) {
GLBuilders.buildExtrudedPolygons(
polygons,
style.z,
style.height,
style.min_height,
vertex_data,
{
vertex_constants: vertex_constants
}
);
}
// Regular polygons
else {
GLBuilders.buildPolygons(
polygons,
style.z,
vertex_data,
{
normals: true,
vertex_constants: vertex_constants
}
);
// Callback-base builder (for future exploration)
// var normal_vertex_constants = [0, 0, 1].concat(vertex_constants);
// GLBuilders.buildPolygons2(
// polygons,
// z,
// function (vertices) {
// // var vs = vertices.positions;
// // for (var v in vs) {
// // // var bc = [(v % 3) ? 0 : 1, ((v + 1) % 3) ? 0 : 1, ((v + 2) % 3) ? 0 : 1];
// // // var bc = [centroid.x, centroid.y, 0];
// // // vs[v] = vertices.positions[v].concat(z, 0, 0, 1, bc);
// // // vs[v] = vertices.positions[v].concat(z, 0, 0, 1);
// // vs[v] = vertices.positions[v].concat(0, 0, 1);
// // }
// GL.addVertices(vertices.positions, normal_vertex_constants, vertex_data);
// // GL.addVerticesByAttributeLayout(
// // [
// // { name: 'a_position', data: vertices.positions },
// // { name: 'a_normal', data: [0, 0, 1] },
// // { name: 'a_color', data: [style.color[0], style.color[1], style.color[2]] },
// // { name: 'a_layer', data: style.layer_num }
// // ],
// // vertex_data
// // );
// // GL.addVerticesMultipleAttributes([vertices.positions], normal_vertex_constants, vertex_data);
// }
// );
}
// Polygon outlines
if (style.outline.color && style.outline.width) {
for (var mpc=0; mpc < polygons.length; mpc++) {
GLBuilders.buildPolylines(
polygons[mpc],
style.z,
style.outline.width,
vertex_data,
{
closed_polygon: true,
remove_tile_edges: true,
vertex_constants: outline_vertex_constants
}
);
}
}
};
Modes.polygons.buildLines = function (lines, style, vertex_data)
{
// TOOD: reduce redundancy of constant calc between builders
// Color and layer number are currently constant across vertices
var vertex_constants = [
style.color[0], style.color[1], style.color[2],
style.selection.color[0], style.selection.color[1], style.selection.color[2], style.selection.color[3],
style.layer_num
];
// Outlines have a slightly different set of constants, because the layer number is modified
if (style.outline.color) {
var outline_vertex_constants = [
style.outline.color[0], style.outline.color[1], style.outline.color[2],
style.selection.color[0], style.selection.color[1], style.selection.color[2], style.selection.color[3],
style.layer_num - 0.5 // outlines sit between layers, underneath current layer but above the one below
];
}
// Main lines
GLBuilders.buildPolylines(
lines,
style.z,
style.width,
vertex_data,
{
vertex_constants: vertex_constants
}
);
// Line outlines
if (style.outline.color && style.outline.width) {
GLBuilders.buildPolylines(
lines,
style.z,
style.width + 2 * style.outline.width,
vertex_data,
{
vertex_constants: outline_vertex_constants
}
);
}
};
Modes.polygons.buildPoints = function (points, style, vertex_data)
{
// TOOD: reduce redundancy of constant calc between builders
// Color and layer number are currently constant across vertices
var vertex_constants = [
style.color[0], style.color[1], style.color[2],
style.selection.color[0], style.selection.color[1], style.selection.color[2], style.selection.color[3],
style.layer_num
];
GLBuilders.buildQuadsForPoints(
points,
style.size * 2,
style.size * 2,
style.z,
vertex_data,
{
normals: true,
texcoords: false,
vertex_constants: vertex_constants
}
);
};
/*** Points w/simple distance field rendering ***/
Modes.points = Object.create(RenderMode);
Modes.points.name = 'points';
Modes.points.vertex_shader_key = 'point_vertex';
Modes.points.fragment_shader_key = 'point_fragment';
Modes.points.defines = {
'EFFECT_SCREEN_COLOR': true
};
Modes.points.selection = true;
Modes.points._init = function () {
this.vertex_layout = new GLVertexLayout(this.gl, [
{ name: 'a_position', size: 3, type: this.gl.FLOAT, normalized: false },
{ name: 'a_texcoord', size: 2, type: this.gl.FLOAT, normalized: false },
{ name: 'a_color', size: 3, type: this.gl.FLOAT, normalized: false },
{ name: 'a_selection_color', size: 4, type: this.gl.FLOAT, normalized: false },
{ name: 'a_layer', size: 1, type: this.gl.FLOAT, normalized: false }
]);
};
Modes.points.buildPoints = function (points, style, vertex_data)
{
// TOOD: reduce redundancy of constant calc between builders
// Color and layer number are currently constant across vertices
var vertex_constants = [
style.color[0], style.color[1], style.color[2],
style.selection.color[0], style.selection.color[1], style.selection.color[2], style.selection.color[3],
style.layer_num
];
GLBuilders.buildQuadsForPoints(
points,
style.size * 2,
style.size * 2,
style.z,
vertex_data,
{
normals: false,
texcoords: true,
vertex_constants: vertex_constants
}
);
};
if (module !== undefined) {
module.exports = {
ModeManager: ModeManager,
Modes: Modes
};
}
| src/gl/gl_modes.js | // Rendering modes
var GL = require('./gl.js');
var GLBuilders = require('./gl_builders.js');
var GLGeometry = require('./gl_geom.js');
var GLVertexLayout = require('./gl_vertex_layout.js');
var GLProgram = require('./gl_program.js');
var GLTexture = require('./gl_texture.js');
var shader_sources = require('./gl_shaders.js'); // built-in shaders
// Base
var RenderMode = {
init: function (gl) {
this.gl = gl;
this.makeGLProgram();
if (typeof this._init == 'function') {
this._init();
}
},
refresh: function () {
this.makeGLProgram();
},
defines: {},
selection: false,
buildPolygons: function(){}, // build functions are no-ops until overriden
buildLines: function(){},
buildPoints: function(){},
makeGLGeometry: function (vertex_data) {
return new GLGeometry(this.gl, vertex_data, this.vertex_layout);
}
};
RenderMode.makeGLProgram = function ()
{
// Add any custom defines to built-in mode defines
var defines = {}; // create a new object to avoid mutating a prototype value that may be shared with other modes
if (this.defines != null) {
for (var d in this.defines) {
defines[d] = this.defines[d];
}
}
if (this.shaders != null && this.shaders.defines != null) {
for (var d in this.shaders.defines) {
defines[d] = this.shaders.defines[d];
}
}
// Alter defines for selection (need to create a new object since the first is stored as a reference by the program)
if (this.selection) {
var selection_defines = Object.create(defines);
selection_defines['FEATURE_SELECTION'] = true;
}
// Get any custom code transforms
var transforms = (this.shaders && this.shaders.transforms);
// Create shader from custom URLs
if (this.shaders && this.shaders.vertex_url && this.shaders.fragment_url) {
this.gl_program = GLProgram.createProgramFromURLs(
this.gl,
this.shaders.vertex_url,
this.shaders.fragment_url,
{ defines: defines, transforms: transforms, name: this.name }
);
if (this.selection) {
this.selection_gl_program = new GLProgram(
this.gl,
this.gl_program.vertex_shader_source,
shader_sources['selection_fragment'],
{ defines: selection_defines, transforms: transforms, name: (this.name + ' (selection)') }
);
}
}
// Create shader from built-in source
else {
this.gl_program = new GLProgram(
this.gl,
shader_sources[this.vertex_shader_key],
shader_sources[this.fragment_shader_key],
{ defines: defines, transforms: transforms, name: this.name }
);
if (this.selection) {
this.selection_gl_program = new GLProgram(
this.gl,
shader_sources[this.vertex_shader_key],
shader_sources['selection_fragment'],
{ defines: selection_defines, transforms: transforms, name: (this.name + ' (selection)') }
);
}
}
};
// TODO: make this a generic ORM-like feature for setting uniforms via JS objects on GLProgram
RenderMode.setUniforms = function (options)
{
options = options || {};
var gl_program = GLProgram.current; // operate on currently bound program
// TODO: only update uniforms when changed
if (this.shaders != null && this.shaders.uniforms != null) {
var texture_unit = 0;
for (var u in this.shaders.uniforms) {
var uniform = this.shaders.uniforms[u];
// Single float
if (typeof uniform == 'number') {
gl_program.uniform('1f', u, uniform);
}
// Multiple floats - vector or array
else if (typeof uniform == 'object') {
// float vectors (vec2, vec3, vec4)
if (uniform.length >= 2 && uniform.length <= 4) {
gl_program.uniform(uniform.length + 'fv', u, uniform);
}
// float array
else if (uniform.length > 4) {
gl_program.uniform('1fv', u + '[0]', uniform);
}
// TODO: assume matrix for (typeof == Float32Array && length == 16)?
}
// Boolean
else if (typeof this.shaders.uniforms[u] == 'boolean') {
gl_program.uniform('1i', u, uniform);
}
// Texture
else if (typeof uniform == 'string') {
var texture = GLTexture.textures[uniform];
if (texture == null) {
texture = new GLTexture(this.gl, uniform);
texture.load(uniform);
}
texture.bind(texture_unit);
gl_program.uniform('1i', u, texture_unit);
texture_unit++;
}
// TODO: support other non-float types? (int, etc.)
}
}
};
RenderMode.update = function ()
{
// Mode-specific animation
if (typeof this.animation == 'function') {
this.animation();
}
};
var Modes = {};
var ModeManager = {};
// Update built-in mode or create a new one
ModeManager.configureMode = function (name, settings)
{
Modes[name] = Modes[name] || Object.create(Modes[settings.extends] || RenderMode);
if (Modes[settings.extends]) {
Modes[name].parent = Modes[settings.extends]; // explicit 'super' class access
}
for (var s in settings) {
Modes[name][s] = settings[s];
}
Modes[name].name = name;
return Modes[name];
};
// Built-in rendering modes
/*** Plain polygons ***/
Modes.polygons = Object.create(RenderMode);
Modes.polygons.name = 'polygons';
Modes.polygons.vertex_shader_key = 'polygon_vertex';
Modes.polygons.fragment_shader_key = 'polygon_fragment';
Modes.polygons.defines = {
'WORLD_POSITION_WRAP': 100000 // default world coords to wrap every 100,000 meters, can turn off by setting this to 'false'
};
Modes.polygons.selection = true;
Modes.polygons._init = function () {
this.vertex_layout = new GLVertexLayout(this.gl, [
{ name: 'a_position', size: 3, type: this.gl.FLOAT, normalized: false },
{ name: 'a_normal', size: 3, type: this.gl.FLOAT, normalized: false },
{ name: 'a_color', size: 3, type: this.gl.FLOAT, normalized: false },
{ name: 'a_selection_color', size: 4, type: this.gl.FLOAT, normalized: false },
{ name: 'a_layer', size: 1, type: this.gl.FLOAT, normalized: false }
]);
};
Modes.polygons.buildPolygons = function (polygons, style, vertex_data)
{
// Color and layer number are currently constant across vertices
var vertex_constants = [
style.color[0], style.color[1], style.color[2],
style.selection.color[0], style.selection.color[1], style.selection.color[2], style.selection.color[3],
style.layer_num
];
// Outlines have a slightly different set of constants, because the layer number is modified
if (style.outline.color) {
var outline_vertex_constants = [
style.outline.color[0], style.outline.color[1], style.outline.color[2],
style.selection.color[0], style.selection.color[1], style.selection.color[2], style.selection.color[3],
style.layer_num - 0.5 // outlines sit between layers, underneath current layer but above the one below
];
}
// Extruded polygons (e.g. 3D buildings)
if (style.extrude && style.height) {
GLBuilders.buildExtrudedPolygons(
polygons,
style.z,
style.height,
style.min_height,
vertex_data,
{
vertex_constants: vertex_constants
}
);
}
// Regular polygons
else {
GLBuilders.buildPolygons(
polygons,
style.z,
vertex_data,
{
normals: true,
vertex_constants: vertex_constants
}
);
// Callback-base builder (for future exploration)
// var normal_vertex_constants = [0, 0, 1].concat(vertex_constants);
// GLBuilders.buildPolygons2(
// polygons,
// z,
// function (vertices) {
// // var vs = vertices.positions;
// // for (var v in vs) {
// // // var bc = [(v % 3) ? 0 : 1, ((v + 1) % 3) ? 0 : 1, ((v + 2) % 3) ? 0 : 1];
// // // var bc = [centroid.x, centroid.y, 0];
// // // vs[v] = vertices.positions[v].concat(z, 0, 0, 1, bc);
// // // vs[v] = vertices.positions[v].concat(z, 0, 0, 1);
// // vs[v] = vertices.positions[v].concat(0, 0, 1);
// // }
// GL.addVertices(vertices.positions, normal_vertex_constants, vertex_data);
// // GL.addVerticesByAttributeLayout(
// // [
// // { name: 'a_position', data: vertices.positions },
// // { name: 'a_normal', data: [0, 0, 1] },
// // { name: 'a_color', data: [style.color[0], style.color[1], style.color[2]] },
// // { name: 'a_layer', data: style.layer_num }
// // ],
// // vertex_data
// // );
// // GL.addVerticesMultipleAttributes([vertices.positions], normal_vertex_constants, vertex_data);
// }
// );
}
// Polygon outlines
if (style.outline.color && style.outline.width) {
for (var mpc=0; mpc < polygons.length; mpc++) {
GLBuilders.buildPolylines(
polygons[mpc],
style.z,
style.outline.width,
vertex_data,
{
closed_polygon: true,
remove_tile_edges: true,
vertex_constants: outline_vertex_constants
}
);
}
}
};
Modes.polygons.buildLines = function (lines, style, vertex_data)
{
// TOOD: reduce redundancy of constant calc between builders
// Color and layer number are currently constant across vertices
var vertex_constants = [
style.color[0], style.color[1], style.color[2],
style.selection.color[0], style.selection.color[1], style.selection.color[2], style.selection.color[3],
style.layer_num
];
// Outlines have a slightly different set of constants, because the layer number is modified
if (style.outline.color) {
var outline_vertex_constants = [
style.outline.color[0], style.outline.color[1], style.outline.color[2],
style.selection.color[0], style.selection.color[1], style.selection.color[2], style.selection.color[3],
style.layer_num - 0.5 // outlines sit between layers, underneath current layer but above the one below
];
}
// Main lines
GLBuilders.buildPolylines(
lines,
style.z,
style.width,
vertex_data,
{
vertex_constants: vertex_constants
}
);
// Line outlines
if (style.outline.color && style.outline.width) {
GLBuilders.buildPolylines(
lines,
style.z,
style.width + 2 * style.outline.width,
vertex_data,
{
vertex_constants: outline_vertex_constants
}
);
}
};
Modes.polygons.buildPoints = function (points, style, vertex_data)
{
// TOOD: reduce redundancy of constant calc between builders
// Color and layer number are currently constant across vertices
var vertex_constants = [
style.color[0], style.color[1], style.color[2],
style.selection.color[0], style.selection.color[1], style.selection.color[2], style.selection.color[3],
style.layer_num
];
GLBuilders.buildQuadsForPoints(
points,
style.size * 2,
style.size * 2,
style.z,
vertex_data,
{
normals: true,
texcoords: false,
vertex_constants: vertex_constants
}
);
};
/*** Points w/simple distance field rendering ***/
Modes.points = Object.create(RenderMode);
Modes.points.name = 'points';
Modes.points.vertex_shader_key = 'point_vertex';
Modes.points.fragment_shader_key = 'point_fragment';
Modes.points.defines = {
'EFFECT_SCREEN_COLOR': true
};
Modes.points.selection = true;
Modes.points._init = function () {
this.vertex_layout = new GLVertexLayout(this.gl, [
{ name: 'a_position', size: 3, type: this.gl.FLOAT, normalized: false },
{ name: 'a_texcoord', size: 2, type: this.gl.FLOAT, normalized: false },
{ name: 'a_color', size: 3, type: this.gl.FLOAT, normalized: false },
{ name: 'a_selection_color', size: 4, type: this.gl.FLOAT, normalized: false },
{ name: 'a_layer', size: 1, type: this.gl.FLOAT, normalized: false }
]);
};
Modes.points.buildPoints = function (points, style, vertex_data)
{
// TOOD: reduce redundancy of constant calc between builders
// Color and layer number are currently constant across vertices
var vertex_constants = [
style.color[0], style.color[1], style.color[2],
style.selection.color[0], style.selection.color[1], style.selection.color[2], style.selection.color[3],
style.layer_num
];
GLBuilders.buildQuadsForPoints(
points,
style.size * 2,
style.size * 2,
style.z,
vertex_data,
{
normals: false,
texcoords: true,
vertex_constants: vertex_constants
}
);
};
if (module !== undefined) {
module.exports = {
ModeManager: ModeManager,
Modes: Modes
};
}
| don't update GL program instance vars for modes until programs finish compiling
| src/gl/gl_modes.js | don't update GL program instance vars for modes until programs finish compiling | <ide><path>rc/gl/gl_modes.js
<ide> var GLTexture = require('./gl_texture.js');
<ide> var shader_sources = require('./gl_shaders.js'); // built-in shaders
<ide>
<add>var Queue = require('queue-async');
<add>
<ide> // Base
<ide>
<ide> var RenderMode = {
<ide> this._init();
<ide> }
<ide> },
<del> refresh: function () {
<add> refresh: function () { // TODO: should this be async/non-blocking?
<ide> this.makeGLProgram();
<ide> },
<ide> defines: {},
<ide> }
<ide> };
<ide>
<add>// TODO: should this entire operation be async/non-blocking?
<add>// TODO: don't re-create GLProgram instance every time, just update existing one
<ide> RenderMode.makeGLProgram = function ()
<ide> {
<ide> // Add any custom defines to built-in mode defines
<ide> var transforms = (this.shaders && this.shaders.transforms);
<ide>
<ide> // Create shader from custom URLs
<add> var program, selection_program;
<add> var queue = Queue();
<add>
<ide> if (this.shaders && this.shaders.vertex_url && this.shaders.fragment_url) {
<del> this.gl_program = GLProgram.createProgramFromURLs(
<del> this.gl,
<del> this.shaders.vertex_url,
<del> this.shaders.fragment_url,
<del> { defines: defines, transforms: transforms, name: this.name }
<del> );
<add> queue.defer(function(complete) {
<add> program = GLProgram.createProgramFromURLs(
<add> this.gl,
<add> this.shaders.vertex_url,
<add> this.shaders.fragment_url,
<add> { defines: defines, transforms: transforms, name: this.name, callback: complete }
<add> );
<add> }.bind(this));
<ide>
<ide> if (this.selection) {
<del> this.selection_gl_program = new GLProgram(
<del> this.gl,
<del> this.gl_program.vertex_shader_source,
<del> shader_sources['selection_fragment'],
<del> { defines: selection_defines, transforms: transforms, name: (this.name + ' (selection)') }
<del> );
<add> queue.defer(function(complete) {
<add> selection_program = new GLProgram(
<add> this.gl,
<add> this.gl_program.vertex_shader_source,
<add> shader_sources['selection_fragment'],
<add> { defines: selection_defines, transforms: transforms, name: (this.name + ' (selection)'), callback: complete }
<add> );
<add> }.bind(this));
<ide> }
<ide> }
<ide> // Create shader from built-in source
<ide> else {
<del> this.gl_program = new GLProgram(
<del> this.gl,
<del> shader_sources[this.vertex_shader_key],
<del> shader_sources[this.fragment_shader_key],
<del> { defines: defines, transforms: transforms, name: this.name }
<del> );
<del>
<del> if (this.selection) {
<del> this.selection_gl_program = new GLProgram(
<add> queue.defer(function(complete) {
<add> program = new GLProgram(
<ide> this.gl,
<ide> shader_sources[this.vertex_shader_key],
<del> shader_sources['selection_fragment'],
<del> { defines: selection_defines, transforms: transforms, name: (this.name + ' (selection)') }
<add> shader_sources[this.fragment_shader_key],
<add> { defines: defines, transforms: transforms, name: this.name, callback: complete }
<ide> );
<del> }
<del> }
<add> }.bind(this));
<add>
<add> if (this.selection) {
<add> queue.defer(function(complete) {
<add> selection_program = new GLProgram(
<add> this.gl,
<add> shader_sources[this.vertex_shader_key],
<add> shader_sources['selection_fragment'],
<add> { defines: selection_defines, transforms: transforms, name: (this.name + ' (selection)'), callback: complete }
<add> );
<add> }.bind(this));
<add> }
<add> }
<add>
<add> // Wait for program(s) to compile before replacing them
<add> queue.await(function() {
<add> if (program) {
<add> this.gl_program = program;
<add> }
<add>
<add> if (selection_program) {
<add> this.selection_gl_program = selection_program;
<add> }
<add> }.bind(this));
<ide> };
<ide>
<ide> // TODO: make this a generic ORM-like feature for setting uniforms via JS objects on GLProgram |
|
Java | apache-2.0 | bdd29120c89d79b804d85edef8eff82d087de306 | 0 | kamalaboulhosn/pubsub,GoogleCloudPlatform/pubsub,GoogleCloudPlatform/pubsub,GoogleCloudPlatform/pubsub,GoogleCloudPlatform/pubsub,kamalaboulhosn/pubsub,kamalaboulhosn/pubsub,kamalaboulhosn/pubsub,GoogleCloudPlatform/pubsub,kamalaboulhosn/pubsub | package com.google.pubsub.flic.output;
import com.google.pubsub.flic.controllers.Client.ClientType;
import com.google.pubsub.flic.controllers.ClientParams;
import com.google.pubsub.flic.controllers.Controller;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/*
* Tests for {@link SheetsService}.
*/
public class SheetsServiceTest {
@Test
public void testClientSwitch() {
Map<String, Map<ClientParams, Integer>> types =
new HashMap<String, Map<ClientParams, Integer>>();
int expectedCpsCount = 0;
int expectedKafkaCount = 0;
Map<ClientParams, Integer> paramsMap = new HashMap<ClientParams, Integer>();
for (ClientType type : ClientType.values()) {
paramsMap.put(new ClientParams(type, ""), 1);
if (type.toString().startsWith("cps")) {
expectedCpsCount++;
} else if (type.toString().startsWith("kafka")) {
expectedKafkaCount++;
} else {
fail("ClientType toString didn't start with cps or kafka");
}
}
types.put("zone-test", paramsMap);
SheetsService service = new SheetsService(null, types);
assertEquals(
service.getCpsPublisherCount() + service.getCpsSubscriberCount(), expectedCpsCount);
assertEquals(
service.getKafkaPublisherCount() + service.getKafkaSubscriberCount(), expectedKafkaCount);
Map<ClientType, Controller.LoadtestStats> stats =
new HashMap<ClientType, Controller.LoadtestStats>();
for (ClientType type : ClientType.values()) {
stats.put(type, null);
try {
service.getValuesList(stats);
} catch(Exception e) {
assertTrue(e instanceof NullPointerException);
}
// Remove type so only the next type in the enum will be tested.
stats.remove(type);
}
}
}
| load-test-framework/src/test/java/com/google/pubsub/flic/output/SheetsServiceTest.java | package com.google.pubsub.flic.output;
import com.google.pubsub.flic.controllers.Client.ClientType;
import com.google.pubsub.flic.controllers.ClientParams;
import com.google.pubsub.flic.controllers.Controller;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/*
* Tests for {@link SheetsService}.
*/
public class SheetsServiceTest {
@Test
public void testClientSwitch() {
Map<String, Map<ClientParams, Integer>> types =
new HashMap<String, Map<ClientParams, Integer>>();
int expectedCpsCount = 0;
int expectedKafkaCount = 0;
Map<ClientParams, Integer> paramsMap = new HashMap<ClientParams, Integer>();
for (ClientType type : ClientType.values()) {
paramsMap.put(new ClientParams(type, ""), 1);
if (type.toString().startsWith("cps")) {
expectedCpsCount++;
} else if (type.toString().startsWith("kafka")) {
expectedKafkaCount++;
} else {
fail("ClientType toString didn't start with cps or kafka");
}
}
types.put("zone-test", paramsMap);
SheetsService service = new SheetsService("", types);
assertEquals(
service.getCpsPublisherCount() + service.getCpsSubscriberCount(), expectedCpsCount);
assertEquals(
service.getKafkaPublisherCount() + service.getKafkaSubscriberCount(), expectedKafkaCount);
Map<ClientType, Controller.LoadtestStats> stats =
new HashMap<ClientType, Controller.LoadtestStats>();
for (ClientType type : ClientType.values()) {
stats.put(type, null);
try {
service.getValuesList(stats);
} catch(Exception e) {
assertTrue(e instanceof NullPointerException);
}
// Remove type so only the next type in the enum will be tested.
stats.remove(type);
}
}
}
| Made change to null to avoid test attempting to authorize sheet
| load-test-framework/src/test/java/com/google/pubsub/flic/output/SheetsServiceTest.java | Made change to null to avoid test attempting to authorize sheet | <ide><path>oad-test-framework/src/test/java/com/google/pubsub/flic/output/SheetsServiceTest.java
<ide> }
<ide> }
<ide> types.put("zone-test", paramsMap);
<del> SheetsService service = new SheetsService("", types);
<add> SheetsService service = new SheetsService(null, types);
<ide>
<ide> assertEquals(
<ide> service.getCpsPublisherCount() + service.getCpsSubscriberCount(), expectedCpsCount); |
|
Java | apache-2.0 | 55d4243ed154666df3d271ac108491a75e74f486 | 0 | wix/wix-restaurants-availability | package com.wix.restaurants.availability;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import java.io.Serializable;
import java.util.*;
@JsonIgnoreProperties(ignoreUnknown = true)
public class Status implements Serializable, Cloneable {
private static final long serialVersionUID = 1L;
/** Available. */
public static final String STATUS_AVAILABLE = "available";
/** Unavailable. */
public static final String STATUS_UNAVAILABLE = "unavailable";
/** Unknown. */
public static final String STATUS_UNKNOWN = "unknown";
/** All known statuses. */
public static final Set<String> ALL_STATUSES = new HashSet<>(Arrays.asList(new String[] {
STATUS_AVAILABLE, STATUS_UNAVAILABLE
}));
public static final Status UNKNOWN = new Status(STATUS_UNKNOWN, null);
public Status(String status, java.util.Date until, String reason, Map<String, String> comment) {
this.status = status;
this.until = ((until != null) ? until.getTime() : null);
this.reason = reason;
this.comment = comment;
}
public Status(String status, java.util.Date until) {
this(status, until, null, new HashMap<String, String>());
}
/** Default constructor for JSON deserialization. */
public Status() {}
@Override
public Object clone() {
return new Status(status, until(), reason,
((comment != null) ? new LinkedHashMap<>(comment) : null));
}
public java.util.Date until() {
return ((until != null) ? new java.util.Date(until) : null);
}
public boolean available() {
return STATUS_AVAILABLE.equals(status);
}
@JsonInclude(Include.NON_NULL)
public String status;
@JsonInclude(Include.NON_NULL)
public Long until;
/** @see DateTimeWindow#reason */
@JsonInclude(Include.NON_NULL)
public String reason;
/** @see DateTimeWindow#comment */
@JsonInclude(Include.NON_DEFAULT)
public Map<String, String> comment = new LinkedHashMap<>();
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((comment == null) ? 0 : comment.hashCode());
result = prime * result + ((reason == null) ? 0 : reason.hashCode());
result = prime * result + ((status == null) ? 0 : status.hashCode());
result = prime * result + ((until == null) ? 0 : until.hashCode());
return result;
}
public boolean equalsIgnoreUntil(Status other) {
if (comment == null) {
if (other.comment != null)
return false;
} else if (!comment.equals(other.comment))
return false;
if (reason == null) {
if (other.reason != null)
return false;
} else if (!reason.equals(other.reason))
return false;
if (status == null) {
if (other.status != null)
return false;
} else if (!status.equals(other.status))
return false;
return true;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Status other = (Status) obj;
if (until == null) {
if (other.until != null)
return false;
} else if (!until.equals(other.until))
return false;
return equalsIgnoreUntil(other);
}
}
| wix-restaurants-availability-api/src/main/java/com/wix/restaurants/availability/Status.java | package com.wix.restaurants.availability;
import java.io.Serializable;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
@JsonIgnoreProperties(ignoreUnknown = true)
public class Status implements Serializable, Cloneable {
private static final long serialVersionUID = 1L;
/** Available. */
public static final String STATUS_AVAILABLE = "available";
/** Unavailable. */
public static final String STATUS_UNAVAILABLE = "unavailable";
/** Unknown. */
public static final String STATUS_UNKNOWN = "unknown";
/** All known statuses. */
public static final Set<String> ALL_STATUSES = new HashSet<String>(Arrays.asList(new String[] {
STATUS_AVAILABLE, STATUS_UNAVAILABLE
}));
public static final Status UNKNOWN = new Status(STATUS_UNKNOWN, null);
public Status(String status, java.util.Date until, String reason, Map<String, String> comment) {
this.status = status;
this.until = ((until != null) ? until.getTime() : null);
this.reason = reason;
this.comment = comment;
}
public Status(String status, java.util.Date until) {
this(status, until, null, new HashMap<String, String>());
}
/** Default constructor for JSON deserialization. */
public Status() {}
@Override
public Object clone() {
return new Status(status, until(), reason,
((comment != null) ? new HashMap<String, String>(comment) : null));
}
public java.util.Date until() {
return ((until != null) ? new java.util.Date(until) : null);
}
public boolean available() {
return STATUS_AVAILABLE.equals(status);
}
@JsonInclude(Include.NON_NULL)
public String status;
@JsonInclude(Include.NON_NULL)
public Long until;
/** @see DateTimeWindow.reason */
@JsonInclude(Include.NON_NULL)
public String reason;
/** @see DateTimeWindow.comment */
@JsonInclude(Include.NON_DEFAULT)
public Map<String, String> comment = new HashMap<String, String>();
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((comment == null) ? 0 : comment.hashCode());
result = prime * result + ((reason == null) ? 0 : reason.hashCode());
result = prime * result + ((status == null) ? 0 : status.hashCode());
result = prime * result + ((until == null) ? 0 : until.hashCode());
return result;
}
public boolean equalsIgnoreUntil(Status other) {
if (comment == null) {
if (other.comment != null)
return false;
} else if (!comment.equals(other.comment))
return false;
if (reason == null) {
if (other.reason != null)
return false;
} else if (!reason.equals(other.reason))
return false;
if (status == null) {
if (other.status != null)
return false;
} else if (!status.equals(other.status))
return false;
return true;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Status other = (Status) obj;
if (until == null) {
if (other.until != null)
return false;
} else if (!until.equals(other.until))
return false;
return equalsIgnoreUntil(other);
}
}
| Less warnings.
| wix-restaurants-availability-api/src/main/java/com/wix/restaurants/availability/Status.java | Less warnings. | <ide><path>ix-restaurants-availability-api/src/main/java/com/wix/restaurants/availability/Status.java
<ide> package com.wix.restaurants.availability;
<del>
<del>import java.io.Serializable;
<del>import java.util.Arrays;
<del>import java.util.HashMap;
<del>import java.util.HashSet;
<del>import java.util.Map;
<del>import java.util.Set;
<ide>
<ide> import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
<ide> import com.fasterxml.jackson.annotation.JsonInclude;
<ide> import com.fasterxml.jackson.annotation.JsonInclude.Include;
<add>
<add>import java.io.Serializable;
<add>import java.util.*;
<ide>
<ide> @JsonIgnoreProperties(ignoreUnknown = true)
<ide> public class Status implements Serializable, Cloneable {
<ide> public static final String STATUS_UNKNOWN = "unknown";
<ide>
<ide> /** All known statuses. */
<del> public static final Set<String> ALL_STATUSES = new HashSet<String>(Arrays.asList(new String[] {
<add> public static final Set<String> ALL_STATUSES = new HashSet<>(Arrays.asList(new String[] {
<ide> STATUS_AVAILABLE, STATUS_UNAVAILABLE
<ide> }));
<ide>
<ide> @Override
<ide> public Object clone() {
<ide> return new Status(status, until(), reason,
<del> ((comment != null) ? new HashMap<String, String>(comment) : null));
<add> ((comment != null) ? new LinkedHashMap<>(comment) : null));
<ide> }
<ide>
<ide> public java.util.Date until() {
<ide> @JsonInclude(Include.NON_NULL)
<ide> public Long until;
<ide>
<del> /** @see DateTimeWindow.reason */
<add> /** @see DateTimeWindow#reason */
<ide> @JsonInclude(Include.NON_NULL)
<ide> public String reason;
<ide>
<del> /** @see DateTimeWindow.comment */
<add> /** @see DateTimeWindow#comment */
<ide> @JsonInclude(Include.NON_DEFAULT)
<del> public Map<String, String> comment = new HashMap<String, String>();
<add> public Map<String, String> comment = new LinkedHashMap<>();
<ide>
<ide> @Override
<ide> public int hashCode() { |
|
JavaScript | mit | cb527a457d16b8d2077a4d398c59b82e2149d0ce | 0 | chadxz/vanilla-webrtc,chadxz/vanilla-webrtc | /**
*
* Create a peer
*
* @param opts
* @param opts.socket,
* @param opts.socketId,
* @param opts.$localVideo,
* @param opts.$localScreenShare,
* @param opts.$remoteVideo,
* @param opts.$remoteScreenShare
* @returns {{peerId: *, startVideoCall: startVideoCall}}
*/
export default function Peer(opts) {
const { socket, $localVideo, $localScreenShare, $remoteVideo, $remoteScreenShare } = opts;
const peerId = opts.socketId;
const pc = new RTCPeerConnection();
let videoCallStream = null;
let screenShareStream = null;
let didSetRemoteDescription = false;
let queuedIceCandidates = [];
function errorHandler(processName) {
return console.error.bind(console, `${processName} failed`);
}
function drainQueuedCandidates() {
while (queuedIceCandidates.length > 0) {
pc.addIceCandidate(queuedIceCandidates.shift());
}
console.log('processed all queued ice candidates');
}
function handleIceCandidate(signal) {
const { icecandidate } = signal;
console.log('received ice candidate', icecandidate);
if (pc.didSetRemoteDescription) {
pc.addIceCandidate(new RTCIceCandidate(icecandidate));
} else {
queuedIceCandidates.push(new RTCIceCandidate(icecandidate));
}
}
function handleOffer(signal) {
const { offer } = signal;
console.log('received offer', offer);
return new Promise((resolve, reject) => {
if (!signal.wantsRemoteVideo) {
return resolve();
}
const constraints = { audio: true, video: true };
getUserMedia(constraints, resolve, reject);
}).then((stream) => {
if (!stream) {
return;
}
attachMediaStream($localVideo, stream);
pc.addStream(stream);
$localVideo.play();
}).then(() => {
pc.setRemoteDescription(new RTCSessionDescription(offer)).then(() => {
didSetRemoteDescription = true;
drainQueuedCandidates();
pc.createAnswer().then(answer => {
console.log('calling setLocalDescription after createAnswer');
pc.setLocalDescription(answer).then(() => {
socket.emit('signal', {
type: 'answer',
from: socket.id,
to: peerId,
answer
});
console.log('sent answer', answer);
}, errorHandler('setLocalDescription'));
});
});
});
}
function handleAnswer(signal) {
const { answer } = signal;
pc.setRemoteDescription(new RTCSessionDescription(answer)).then(() => {
didSetRemoteDescription = true;
drainQueuedCandidates();
console.log('set answer', answer);
});
}
function onCreateOfferSuccess(offer) {
console.log('calling setLocalDescription in createOfferSuccess');
pc.setLocalDescription(offer).then(() => {
socket.emit('signal', {
type: 'offer',
from: socket.id,
to: peerId,
wantsRemoteVideo: true,
offer
});
console.trace('sent offer', offer);
}, errorHandler('setLocalDescription'));
}
function startVideoCall() {
const videoConstraints = { audio: true, video: true };
getUserMedia(videoConstraints, stream => {
videoCallStream = stream;
attachMediaStream($localVideo, stream);
$localVideo.play();
pc.addStream(stream);
pc.createOffer(onCreateOfferSuccess, errorHandler('renegotiation createOffer'));
}, console.error.bind(console, 'getUserMedia failed'));
}
/**
* handle ice candidate generation from webrtc peer connection
*
* @param {*} obj.candidate The ice candidate
*/
pc.onicecandidate = (obj) => {
if (!obj.candidate) {
console.log('received end-of-ice signal');
return;
}
console.log('onicecandidate', obj.candidate);
socket.emit('signal', {
type: 'icecandidate',
from: socket.id,
to: peerId,
icecandidate: obj.candidate
});
};
pc.oniceconnectionstatechange = () => {
if (pc.iceConnectionState == 'connected') {
console.log('connected.');
}
};
pc.onnegotiationneeded = () => {
if (pc.iceConnectionState == 'connected') {
console.log('onnegotiationneeded');
pc.createOffer(onCreateOfferSuccess, errorHandler('renegotiation createOffer'))
}
};
pc.onaddstream = obj => {
const stream = obj.stream;
const hasAudioTracks = stream.getAudioTracks().length > 0;
console.log([
`onaddstream. remote stream has ${stream.getAudioTracks().length} audio tracks`,
`and ${stream.getVideoTracks().length} video tracks`].join(' ')
);
const element = hasAudioTracks ? $remoteVideo : $remoteScreenShare;
attachMediaStream(element, stream);
element.play();
};
socket.on('signal', signal => {
if (signal.from !== peerId) {
return;
}
console.log(`received '${signal.type}' signal from ${signal.from} destined for ${signal.to}`);
switch (signal.type) {
case 'icecandidate':
handleIceCandidate(signal);
break;
case 'offer':
handleOffer(signal);
break;
case 'answer':
handleAnswer(signal);
break;
default:
console.warn('received signal I have no idea what to do with', signal);
}
});
return {
peerId,
startVideoCall,
handleOffer
};
}
| client/peer.js | /**
*
* Create a peer
*
* @param opts
* @param opts.socket,
* @param opts.socketId,
* @param opts.$localVideo,
* @param opts.$localScreenShare,
* @param opts.$remoteVideo,
* @param opts.$remoteScreenShare
* @returns {{peerId: *, startVideoCall: startVideoCall}}
*/
export default function Peer(opts) {
const { socket, $localVideo, $localScreenShare, $remoteVideo, $remoteScreenShare } = opts;
const peerId = opts.socketId;
const pc = new RTCPeerConnection();
let videoCallStream = null;
let screenShareStream = null;
let didSetRemoteDescription = false;
let queuedIceCandidates = [];
function errorHandler(processName) {
return console.error.bind(console, `${processName} failed`);
}
function drainQueuedCandidates() {
while (queuedIceCandidates.length > 0) {
pc.addIceCandidate(queuedIceCandidates.shift());
}
console.log('processed all queued ice candidates');
}
function handleIceCandidate(signal) {
const { icecandidate } = signal;
console.log('received ice candidate', icecandidate);
if (pc.didSetRemoteDescription) {
pc.addIceCandidate(new RTCIceCandidate(icecandidate));
} else {
queuedIceCandidates.push(new RTCIceCandidate(icecandidate));
}
}
function handleOffer(signal) {
const { offer } = signal;
console.log('received offer', offer);
pc.setRemoteDescription(new RTCSessionDescription(offer)).then(() => {
didSetRemoteDescription = true;
drainQueuedCandidates();
pc.createAnswer().then(answer => {
pc.setLocalDescription(answer).then(() => {
socket.emit('signal', {
type: 'answer',
from: socket.id,
to: peerId,
answer
});
console.log('sent answer', answer);
}, errorHandler('setLocalDescription'));
});
})
}
function handleAnswer(signal) {
const { answer } = signal;
pc.setRemoteDescription(new RTCSessionDescription(answer)).then(() => {
didSetRemoteDescription = true;
drainQueuedCandidates();
console.log('set answer', answer);
});
}
function onCreateOfferSuccess(offer) {
pc.setLocalDescription(offer).then(() => {
socket.emit('signal', {
type: 'offer',
from: socket.id,
to: peerId,
offer
});
console.trace('sent offer', offer);
}, errorHandler('setLocalDescription'));
}
function startVideoCall() {
const videoConstraints = { audio: true, video: true };
getUserMedia(videoConstraints, stream => {
videoCallStream = stream;
attachMediaStream($localVideo, stream);
$localVideo.play();
pc.addStream(stream);
}, console.error.bind(console, 'getUserMedia failed'));
}
/**
* handle ice candidate generation from webrtc peer connection
*
* @param {*} obj.candidate The ice candidate
*/
pc.onicecandidate = (obj) => {
if (!obj.candidate) {
console.log('received end-of-ice signal');
return;
}
console.log('onicecandidate', obj.candidate);
socket.emit('signal', {
type: 'icecandidate',
from: socket.id,
to: peerId,
icecandidate: obj.candidate
});
};
pc.oniceconnectionstatechange = () => {
if (pc.iceConnectionState == 'connected') {
console.log('connected.');
}
};
pc.onnegotiationneeded = () => {
console.log('onnegotiationneeded');
pc.createOffer(onCreateOfferSuccess, errorHandler('renegotiation createOffer'))
};
pc.onaddstream = obj => {
const stream = obj.stream;
const hasAudioTracks = stream.getAudioTracks().length > 0;
console.log([
`onaddstream. remote stream has ${stream.getAudioTracks().length} audio tracks`,
`and ${stream.getVideoTracks().length} video tracks`].join(' ')
);
const element = hasAudioTracks ? $remoteVideo : $remoteScreenShare;
attachMediaStream(element, stream);
element.play();
};
socket.on('signal', signal => {
if (signal.from !== peerId) {
return;
}
console.log(`received '${signal.type}' signal from ${signal.from} destined for ${signal.to}`);
switch (signal.type) {
case 'icecandidate':
handleIceCandidate(signal);
break;
case 'offer':
handleOffer(signal);
break;
case 'answer':
handleAnswer(signal);
break;
default:
console.warn('received signal I have no idea what to do with', signal);
}
});
return {
peerId,
startVideoCall,
handleOffer
};
}
| fixed bugs yo
| client/peer.js | fixed bugs yo | <ide><path>lient/peer.js
<ide> function handleOffer(signal) {
<ide> const { offer } = signal;
<ide> console.log('received offer', offer);
<del> pc.setRemoteDescription(new RTCSessionDescription(offer)).then(() => {
<del> didSetRemoteDescription = true;
<del> drainQueuedCandidates();
<ide>
<del> pc.createAnswer().then(answer => {
<del> pc.setLocalDescription(answer).then(() => {
<del> socket.emit('signal', {
<del> type: 'answer',
<del> from: socket.id,
<del> to: peerId,
<del> answer
<del> });
<del> console.log('sent answer', answer);
<del> }, errorHandler('setLocalDescription'));
<add> return new Promise((resolve, reject) => {
<add> if (!signal.wantsRemoteVideo) {
<add> return resolve();
<add> }
<add>
<add> const constraints = { audio: true, video: true };
<add> getUserMedia(constraints, resolve, reject);
<add> }).then((stream) => {
<add> if (!stream) {
<add> return;
<add> }
<add>
<add> attachMediaStream($localVideo, stream);
<add> pc.addStream(stream);
<add> $localVideo.play();
<add> }).then(() => {
<add> pc.setRemoteDescription(new RTCSessionDescription(offer)).then(() => {
<add> didSetRemoteDescription = true;
<add> drainQueuedCandidates();
<add>
<add> pc.createAnswer().then(answer => {
<add> console.log('calling setLocalDescription after createAnswer');
<add> pc.setLocalDescription(answer).then(() => {
<add> socket.emit('signal', {
<add> type: 'answer',
<add> from: socket.id,
<add> to: peerId,
<add> answer
<add> });
<add> console.log('sent answer', answer);
<add> }, errorHandler('setLocalDescription'));
<add> });
<ide> });
<del> })
<add> });
<ide> }
<ide>
<ide> function handleAnswer(signal) {
<ide> }
<ide>
<ide> function onCreateOfferSuccess(offer) {
<add> console.log('calling setLocalDescription in createOfferSuccess');
<ide> pc.setLocalDescription(offer).then(() => {
<ide> socket.emit('signal', {
<ide> type: 'offer',
<ide> from: socket.id,
<ide> to: peerId,
<add> wantsRemoteVideo: true,
<ide> offer
<ide> });
<ide> console.trace('sent offer', offer);
<ide> attachMediaStream($localVideo, stream);
<ide> $localVideo.play();
<ide> pc.addStream(stream);
<add> pc.createOffer(onCreateOfferSuccess, errorHandler('renegotiation createOffer'));
<ide> }, console.error.bind(console, 'getUserMedia failed'));
<ide> }
<ide>
<ide> };
<ide>
<ide> pc.onnegotiationneeded = () => {
<del> console.log('onnegotiationneeded');
<del> pc.createOffer(onCreateOfferSuccess, errorHandler('renegotiation createOffer'))
<add> if (pc.iceConnectionState == 'connected') {
<add> console.log('onnegotiationneeded');
<add> pc.createOffer(onCreateOfferSuccess, errorHandler('renegotiation createOffer'))
<add> }
<ide> };
<ide>
<ide> pc.onaddstream = obj => { |
|
Java | mit | 253c1834299474516b7569186ce6d99548152d78 | 0 | core9/module-ogone | package io.core9.module.commerce.ogone;
import io.core9.commerce.checkout.Order;
import io.core9.module.auth.AuthenticationPlugin;
import io.core9.plugin.server.request.Request;
import io.core9.plugin.widgets.datahandler.DataHandler;
import io.core9.plugin.widgets.datahandler.DataHandlerFactoryConfig;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import net.xeoh.plugins.base.annotations.PluginImplementation;
import net.xeoh.plugins.base.annotations.injections.InjectPlugin;
/**
* Ogone DataHandler
* Handles Ogone payments via the widgets flow.
*
* TODO: Handle Ogone return URL (success/failure)
*
* @author [email protected]
*
*/
@PluginImplementation
public class OgoneDataHandlerImpl implements OgoneDataHandler {
@InjectPlugin
private AuthenticationPlugin auth;
@Override
public String getName() {
return "Payment-Ogone";
}
@Override
public Class<? extends DataHandlerFactoryConfig> getConfigClass() {
return OgoneDataHandlerConfig.class;
}
@Override
public DataHandler<OgoneDataHandlerConfig> createDataHandler(final DataHandlerFactoryConfig options) {
final OgoneDataHandlerConfig config = (OgoneDataHandlerConfig) options;
return new DataHandler<OgoneDataHandlerConfig>() {
@Override
public Map<String, Object> handle(Request req) {
Order order = (Order) auth.getUser(req).getSession().getAttribute("order");
TreeMap<String, String> values = addOrderContent(config.retrieveFields(), order);
generateSignature(req, config, values);
Map<String, Object> result = new HashMap<String, Object>();
result.put("link", config.isTest() ? " https://secure.ogone.com/ncol/test/orderstandard.asp" : " https://secure.ogone.com/ncol/prod/orderstandard.asp");
result.put("amount", order.getCart().getTotal());
result.put("orderid", order.getId());
result.put("ogoneconfig", values);
return result;
}
@Override
public OgoneDataHandlerConfig getOptions() {
return (OgoneDataHandlerConfig) options;
}
};
}
private TreeMap<String,String> addOrderContent(TreeMap<String,String> fields, Order order) {
fields.put("AMOUNT", "" + order.getCart().getTotal());
fields.put("ORDERID", order.getId());
return fields;
}
/**
* Generate a SHA-1 Signature for ogone
* TODO Make more dynamic, to allow additional fields (use CommerceEncryptionPlugin)
* @param req
* @param config
* @param order
* @return
*/
private String generateSignature(Request req, OgoneDataHandlerConfig config, TreeMap<String,String> fields) {
String shaInValue = config.getShaInValue();
String input = "";
for(Map.Entry<String,String> entry : fields.entrySet()) {
input += entry.getKey() + "=" + entry.getValue() + shaInValue;
}
byte[] bytes = input.getBytes();
MessageDigest md = null;
try {
md = MessageDigest.getInstance("SHA-1");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
String result = bytesToHex(md.digest(bytes)).toUpperCase();
fields.put("SHASIGN", result);
return result;
}
private String bytesToHex(byte[] bytes) {
char[] hexArray = "0123456789ABCDEF".toCharArray();
char[] hexChars = new char[bytes.length * 2];
for ( int j = 0; j < bytes.length; j++ ) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
}
| src/impl/java/io/core9/module/commerce/ogone/OgoneDataHandlerImpl.java | package io.core9.module.commerce.ogone;
import io.core9.commerce.checkout.Order;
import io.core9.module.auth.AuthenticationPlugin;
import io.core9.plugin.server.request.Request;
import io.core9.plugin.widgets.datahandler.DataHandler;
import io.core9.plugin.widgets.datahandler.DataHandlerFactoryConfig;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import net.xeoh.plugins.base.annotations.PluginImplementation;
import net.xeoh.plugins.base.annotations.injections.InjectPlugin;
@PluginImplementation
public class OgoneDataHandlerImpl implements OgoneDataHandler {
@InjectPlugin
private AuthenticationPlugin auth;
@Override
public String getName() {
return "Payment-Ogone";
}
@Override
public Class<? extends DataHandlerFactoryConfig> getConfigClass() {
return OgoneDataHandlerConfig.class;
}
@Override
public DataHandler<OgoneDataHandlerConfig> createDataHandler(final DataHandlerFactoryConfig options) {
final OgoneDataHandlerConfig config = (OgoneDataHandlerConfig) options;
return new DataHandler<OgoneDataHandlerConfig>() {
@Override
public Map<String, Object> handle(Request req) {
Order order = (Order) auth.getUser(req).getSession().getAttribute("order");
TreeMap<String, String> values = addOrderContent(config.retrieveFields(), order);
generateSignature(req, config, values);
Map<String, Object> result = new HashMap<String, Object>();
result.put("link", config.isTest() ? " https://secure.ogone.com/ncol/test/orderstandard.asp" : " https://secure.ogone.com/ncol/prod/orderstandard.asp");
result.put("amount", order.getCart().getTotal());
result.put("orderid", order.getId());
result.put("ogoneconfig", values);
return result;
}
@Override
public OgoneDataHandlerConfig getOptions() {
return (OgoneDataHandlerConfig) options;
}
};
}
private TreeMap<String,String> addOrderContent(TreeMap<String,String> fields, Order order) {
fields.put("AMOUNT", "" + order.getCart().getTotal());
fields.put("ORDERID", order.getId());
return fields;
}
/**
* Generate a SHA-1 Signature for ogone
* TODO Make more dynamic, to allow additional fields (use CommerceEncryptionPlugin)
* @param req
* @param config
* @param order
* @return
*/
private String generateSignature(Request req, OgoneDataHandlerConfig config, TreeMap<String,String> fields) {
String shaInValue = config.getShaInValue();
String input = "";
for(Map.Entry<String,String> entry : fields.entrySet()) {
input += entry.getKey() + "=" + entry.getValue() + shaInValue;
}
byte[] bytes = input.getBytes();
MessageDigest md = null;
try {
md = MessageDigest.getInstance("SHA-1");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
String result = bytesToHex(md.digest(bytes)).toUpperCase();
fields.put("SHASIGN", result);
return result;
}
private String bytesToHex(byte[] bytes) {
char[] hexArray = "0123456789ABCDEF".toCharArray();
char[] hexChars = new char[bytes.length * 2];
for ( int j = 0; j < bytes.length; j++ ) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
}
| todo statement | src/impl/java/io/core9/module/commerce/ogone/OgoneDataHandlerImpl.java | todo statement | <ide><path>rc/impl/java/io/core9/module/commerce/ogone/OgoneDataHandlerImpl.java
<ide> import net.xeoh.plugins.base.annotations.PluginImplementation;
<ide> import net.xeoh.plugins.base.annotations.injections.InjectPlugin;
<ide>
<add>/**
<add> * Ogone DataHandler
<add> * Handles Ogone payments via the widgets flow.
<add> *
<add> * TODO: Handle Ogone return URL (success/failure)
<add> *
<add> * @author [email protected]
<add> *
<add> */
<ide> @PluginImplementation
<ide> public class OgoneDataHandlerImpl implements OgoneDataHandler {
<ide> |
|
Java | mit | ee6e7659c08206d9dab3194fe947a26c10ac2ff7 | 0 | InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service | package org.innovateuk.ifs.transactional;
import org.innovateuk.ifs.commons.service.ServiceResult;
import org.innovateuk.ifs.user.domain.Role;
import org.innovateuk.ifs.user.domain.User;
import org.innovateuk.ifs.user.repository.RoleRepository;
import org.innovateuk.ifs.user.repository.UserRepository;
import org.innovateuk.ifs.user.resource.UserRoleType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import java.util.function.Supplier;
import static org.innovateuk.ifs.commons.error.CommonErrors.notFoundError;
import static org.innovateuk.ifs.util.EntityLookupCallbacks.find;
/**
* This class represents the base class for user transactional services.
* Method calls within this service will have transaction boundaries
* provided to allow for safe atomic operations and persistence cascading.
*/
@Transactional
public abstract class UserTransactionalService {
@Autowired
protected UserRepository userRepository;
@Autowired
protected RoleRepository roleRepository;
protected Supplier<ServiceResult<User>> user(final Long id) {
return () -> getUser(id);
}
protected ServiceResult<User> getUser(final Long id) {
return find(userRepository.findOne(id), notFoundError(User.class, id));
}
protected Supplier<ServiceResult<Role>> role(UserRoleType roleType) {
return () -> getRole(roleType);
}
protected Supplier<ServiceResult<Role>> role(String roleName) {
return () -> getRole(roleName);
}
protected ServiceResult<Role> getRole(UserRoleType roleType) {
return getRole(roleType.getName());
}
protected ServiceResult<Role> getRole(String roleName) {
return find(roleRepository.findOneByName(roleName), notFoundError(Role.class, roleName));
}
}
| ifs-data-layer/data-service-commons/src/main/java/org/innovateuk/ifs/transactional/UserTransactionalService.java | package org.innovateuk.ifs.transactional;
import org.innovateuk.ifs.commons.service.ServiceResult;
import org.innovateuk.ifs.user.domain.Role;
import org.innovateuk.ifs.user.domain.User;
import org.innovateuk.ifs.user.repository.RoleRepository;
import org.innovateuk.ifs.user.repository.UserRepository;
import org.innovateuk.ifs.user.resource.UserResource;
import org.innovateuk.ifs.user.resource.UserRoleType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.transaction.annotation.Transactional;
import java.util.function.Supplier;
import static org.innovateuk.ifs.commons.error.CommonErrors.forbiddenError;
import static org.innovateuk.ifs.commons.error.CommonErrors.notFoundError;
import static org.innovateuk.ifs.commons.service.ServiceResult.serviceFailure;
import static org.innovateuk.ifs.util.EntityLookupCallbacks.find;
/**
* This class represents the base class for user transactional services.
* Method calls within this service will have transaction boundaries
* provided to allow for safe atomic operations and persistence cascading.
*/
@Transactional
public abstract class UserTransactionalService {
@Autowired
protected UserRepository userRepository;
@Autowired
protected RoleRepository roleRepository;
protected Supplier<ServiceResult<User>> user(final Long id) {
return () -> getUser(id);
}
protected ServiceResult<User> getUser(final Long id) {
return find(userRepository.findOne(id), notFoundError(User.class, id));
}
protected Supplier<ServiceResult<Role>> role(UserRoleType roleType) {
return () -> getRole(roleType);
}
protected Supplier<ServiceResult<Role>> role(String roleName) {
return () -> getRole(roleName);
}
protected ServiceResult<Role> getRole(UserRoleType roleType) {
return getRole(roleType.getName());
}
protected ServiceResult<Role> getRole(String roleName) {
return find(roleRepository.findOneByName(roleName), notFoundError(Role.class, roleName));
}
public ServiceResult<User> getCurrentlyLoggedInUser() {
UserResource currentUser = (UserResource) SecurityContextHolder.getContext().getAuthentication().getDetails();
if (currentUser == null) {
return serviceFailure(forbiddenError());
}
return getUser(currentUser.getId());
}
}
| IFS-2769-Remove-getCurrentlyLoggedInUser-GenericThreadService
Deleted the existing getCurrentlyLoggedInUser() from
UserTransactionalService.
Change-Id: I59b5019635d1c1539c618d10b85036ebb0e63e64
| ifs-data-layer/data-service-commons/src/main/java/org/innovateuk/ifs/transactional/UserTransactionalService.java | IFS-2769-Remove-getCurrentlyLoggedInUser-GenericThreadService | <ide><path>fs-data-layer/data-service-commons/src/main/java/org/innovateuk/ifs/transactional/UserTransactionalService.java
<ide> import org.innovateuk.ifs.user.domain.User;
<ide> import org.innovateuk.ifs.user.repository.RoleRepository;
<ide> import org.innovateuk.ifs.user.repository.UserRepository;
<del>import org.innovateuk.ifs.user.resource.UserResource;
<ide> import org.innovateuk.ifs.user.resource.UserRoleType;
<ide> import org.springframework.beans.factory.annotation.Autowired;
<del>import org.springframework.security.core.context.SecurityContextHolder;
<ide> import org.springframework.transaction.annotation.Transactional;
<ide>
<ide> import java.util.function.Supplier;
<ide>
<del>import static org.innovateuk.ifs.commons.error.CommonErrors.forbiddenError;
<ide> import static org.innovateuk.ifs.commons.error.CommonErrors.notFoundError;
<del>import static org.innovateuk.ifs.commons.service.ServiceResult.serviceFailure;
<ide> import static org.innovateuk.ifs.util.EntityLookupCallbacks.find;
<ide>
<ide> /**
<ide> protected ServiceResult<Role> getRole(String roleName) {
<ide> return find(roleRepository.findOneByName(roleName), notFoundError(Role.class, roleName));
<ide> }
<del>
<del> public ServiceResult<User> getCurrentlyLoggedInUser() {
<del> UserResource currentUser = (UserResource) SecurityContextHolder.getContext().getAuthentication().getDetails();
<del>
<del> if (currentUser == null) {
<del> return serviceFailure(forbiddenError());
<del> }
<del>
<del> return getUser(currentUser.getId());
<del> }
<ide> } |
|
Java | apache-2.0 | 809f988eb61b3a5fdeb024064e0daa300c44d72f | 0 | scriptella/scriptella-etl,scriptella/scriptella-etl,scriptella/scriptella-etl | /*
* Copyright 2006 The Scriptella Project Team.
*
* 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 scriptella.configuration;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
/**
* TODO: Refactor this class to support unicode convertion similar to native2ascii works
*
* @author Fyodor Kupolov
* @version 1.0
*/
class ReaderInputStream extends InputStream {
private Reader reader;
public ReaderInputStream(Reader reader) {
this.reader = reader;
}
public int read() throws IOException {
return reader.read();
}
private char[] tmpBuf;//used to minimize memory allocations
public int read(final byte b[], final int off, final int len)
throws IOException {
char[] c;
if (tmpBuf != null && tmpBuf.length >= len) {
c = tmpBuf;
} else {
c = new char[len];
}
int n = reader.read(c, 0, len);
tmpBuf = c;
if (n > 0) {
for (int i = 0; i < n; i++) {
b[off + i] = (byte) c[i];
}
}
return n;
}
public void close() throws IOException {
tmpBuf = null;
reader.close();
}
}
| core/src/java/scriptella/configuration/ReaderInputStream.java | /*
* Copyright 2006 The Scriptella Project Team.
*
* 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 scriptella.configuration;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
/**
* TODO: Add documentation
*
* @author Fyodor Kupolov
* @version 1.0
*/
public class ReaderInputStream extends InputStream {
private Reader reader;
public ReaderInputStream(Reader reader) {
this.reader = reader;
}
public int read() throws IOException {
return reader.read();
}
private char[] tmpBuf;//used to minimize memory allocations
public int read(final byte b[], final int off, final int len)
throws IOException {
char[] c = null;
if (tmpBuf != null && tmpBuf.length >= len) {
c = tmpBuf;
} else {
c = new char[len];
}
int n = reader.read(c, 0, len);
tmpBuf = c;
if (n > 0) {
for (int i = 0; i < n; i++) {
b[off + i] = (byte) c[i];
}
}
return n;
}
public void close() throws IOException {
tmpBuf = null;
reader.close();
}
}
| TODO - Add support for unicode and possible add CharsetEncoder | core/src/java/scriptella/configuration/ReaderInputStream.java | TODO - Add support for unicode and possible add CharsetEncoder | <ide><path>ore/src/java/scriptella/configuration/ReaderInputStream.java
<ide>
<ide>
<ide> /**
<del> * TODO: Add documentation
<add> * TODO: Refactor this class to support unicode convertion similar to native2ascii works
<ide> *
<ide> * @author Fyodor Kupolov
<ide> * @version 1.0
<ide> */
<del>public class ReaderInputStream extends InputStream {
<add>class ReaderInputStream extends InputStream {
<ide> private Reader reader;
<ide>
<ide> public ReaderInputStream(Reader reader) {
<ide>
<ide> public int read(final byte b[], final int off, final int len)
<ide> throws IOException {
<del> char[] c = null;
<add> char[] c;
<ide> if (tmpBuf != null && tmpBuf.length >= len) {
<ide> c = tmpBuf;
<ide> } else { |
|
JavaScript | mit | 3a3860ccd4f8bdd77a6389d0e94fc90674a5b61f | 0 | PeachScript/vue-infinite-loading,PeachScript/vue-infinite-loading | import Vue from 'vue';
import InfiniteLoading from '../../../src/components/InfiniteLoading';
function isShow(elm) {
const styles = getComputedStyle(elm);
return styles.getPropertyValue('display') !== 'none';
}
describe('InfiniteLoading.vue', () => {
let vm;
const initConf = {
data() {
return {
list: [],
distance: 50,
isLoadedAll: false,
isDivScroll: true,
isCustomSpinner: false,
listContainerHeight: 200,
listItemHeight: 20,
direction: 'bottom',
};
},
render(createElement) {
return createElement(
'div',
{
style: {
height: `${this.listContainerHeight}px`,
overflow: this.isDivScroll ? 'auto' : 'visible',
},
},
[
createElement('ul', {
style: {
margin: 0,
padding: 0,
},
}, this.list.map((item) => createElement('li', {
style: {
height: `${this.listItemHeight}px`,
},
}, item))),
this.isLoadedAll ? undefined : createElement(InfiniteLoading,
{
props: {
distance: this.distance,
onInfinite: this.onInfinite,
direction: this.direction,
},
ref: 'infiniteLoading',
},
[
this.isCustomSpinner ? createElement('span',
{
slot: 'spinner',
},
[
createElement('i', {
attrs: {
class: 'custom-spinner',
},
}),
]
) : undefined,
]
),
]
);
},
};
// create new Vue instance for every test case
beforeEach(() => {
const container = document.createElement('div');
container.setAttribute('id', 'app');
document.body.appendChild(container);
vm = new Vue(initConf);
});
afterEach(() => {
/**
* because of call the $destroy method of parent cannot trigger
* destroy event for child component in Vue.js 2.0.0-rc6
*/
vm.$refs.infiniteLoading && vm.$refs.infiniteLoading.$destroy();
vm.$destroy(true);
/**
* because of pass true as the argument for destroy method cannot
* remove element from DOM in Vue.js 2.0.0-rc6
*/
vm.$el && vm.$el.remove();
});
it('should render a basic template', (done) => {
vm.isDivScroll = false;
setTimeout(() => {
vm.$mount('#app');
expect(vm.$el.querySelector('.loading-default')).to.be.ok;
done();
}, 1);
});
it('should execute callback and display a spinner immediately after initialize', (done) => {
vm.onInfinite = function test() {
Vue.nextTick(() => {
expect(isShow(vm.$el.querySelector('.loading-default'))).to.be.true;
done();
});
};
vm.$mount('#app');
});
it('should not to execute callback if the previous loading has not be completed', (done) => {
vm.onInfinite = function test() {
const len = this.list.length + 1;
for (let i = len; i < len + 20; i++) {
this.list.push(i);
}
Vue.nextTick(() => {
if (this.list.length === 20) {
vm.$el.addEventListener('scroll', () => {
expect(this.list).to.have.lengthOf(20);
done();
});
// trigger scroll event manually
vm.$el.scrollTop = vm.$el.scrollHeight;
}
});
}.bind(vm);
vm.$mount('#app');
});
it('should be destroyed completely by v-if', (done) => {
vm.onInfinite = function test() {
this.isLoadedAll = true;
Vue.nextTick(() => {
expect(vm.$el.querySelector('.loading-default')).to.not.be.ok;
done();
});
}.bind(vm);
vm.$mount('#app');
});
it('should display no results prompt', (done) => {
vm.onInfinite = function test() {
this.$refs.infiniteLoading.$emit('$InfiniteLoading:complete');
Vue.nextTick(() => {
expect(isShow(vm.$el.querySelectorAll('.infinite-status-prompt')[0])).to.be.true;
done();
});
}.bind(vm);
vm.$mount('#app');
});
it('should display no more data prompt', (done) => {
vm.onInfinite = function test() {
this.$refs.infiniteLoading.$emit('$InfiniteLoading:loaded');
this.$refs.infiniteLoading.$emit('$InfiniteLoading:complete');
// test for whether trigger again after complete
this.$refs.infiniteLoading.$emit('$InfiniteLoading:loaded');
Vue.nextTick(() => {
expect(isShow(vm.$el.querySelectorAll('.infinite-status-prompt')[1])).to.be.true;
done();
});
}.bind(vm);
vm.$mount('#app');
});
it('should load results to fill up the container', (done) => {
const expectedCount = Math.floor(vm.listContainerHeight / vm.listItemHeight);
let i = 0;
let timer;
vm.onInfinite = function test() {
setTimeout(() => {
this.list.push(++i);
this.$refs.infiniteLoading.$emit('$InfiniteLoading:loaded');
clearTimeout(timer);
timer = setTimeout(() => {
if (i >= expectedCount) {
done();
} else {
done(new Error('List not be fill up!'));
}
}, 100);
}, 1);
}.bind(vm);
vm.$mount('#app');
});
it('should reset component and call onInfinite again', (done) => {
let callCount = 0;
vm.onInfinite = function test() {
if (!callCount++) {
this.$refs.infiniteLoading.$emit('$InfiniteLoading:reset');
} else {
done();
}
}.bind(vm);
vm.$mount('#app');
});
it('should display the custom spinner if customize it with slot', (done) => {
vm.isCustomSpinner = true;
delete vm.distance;
vm.$mount('#app');
Vue.nextTick(() => {
expect(vm.$el.querySelector('.custom-spinner')).to.be.ok;
done();
});
});
it('should load data when scroll top (direction attribute)', (done) => {
vm.direction = 'top';
vm.onInfinite = function test() {
Vue.nextTick(() => {
expect(isShow(vm.$el.querySelector('.loading-default'))).to.be.true;
done();
});
};
vm.$mount('#app');
});
});
| test/unit/specs/InfiniteLoading.spec.js | import Vue from 'vue';
import InfiniteLoading from '../../../src/components/InfiniteLoading';
function isShow(elm) {
const styles = getComputedStyle(elm);
return styles.getPropertyValue('display') !== 'none';
}
describe('InfiniteLoading.vue', () => {
let vm;
const initConf = {
data() {
return {
list: [],
distance: 50,
isLoadedAll: false,
isDivScroll: true,
isCustomSpinner: false,
listContainerHeight: 200,
listItemHeight: 20,
direction: 'bottom',
};
},
render(createElement) {
return createElement(
'div',
{
style: {
height: `${this.listContainerHeight}px`,
overflow: this.isDivScroll ? 'auto' : 'visible',
},
},
[
createElement('ul', {
style: {
margin: 0,
padding: 0,
},
}, this.list.map((item) => createElement('li', {
style: {
height: `${this.listItemHeight}px`,
},
}, item))),
this.isLoadedAll ? undefined : createElement(InfiniteLoading,
{
props: {
distance: this.distance,
onInfinite: this.onInfinite,
direction: this.direction,
},
ref: 'infiniteLoading',
},
[
this.isCustomSpinner ? createElement('span',
{
slot: 'spinner',
},
[
createElement('i', {
attrs: {
class: 'custom-spinner',
},
}),
]
) : undefined,
]
),
]
);
},
};
// create new Vue instance for every test case
beforeEach(() => {
const container = document.createElement('div');
container.setAttribute('id', 'app');
document.body.appendChild(container);
vm = new Vue(initConf);
});
afterEach(() => {
/**
* because of call the $destroy method of parent cannot trigger
* destroy event for child component in Vue.js 2.0.0-rc6
*/
vm.$refs.infiniteLoading && vm.$refs.infiniteLoading.$destroy();
vm.$destroy(true);
/**
* because of pass true as the argument for destroy method cannot
* remove element from DOM in Vue.js 2.0.0-rc6
*/
vm.$el && vm.$el.remove();
});
it('should render a basic template', (done) => {
vm.isDivScroll = false;
setTimeout(() => {
vm.$mount('#app');
expect(vm.$el.querySelector('.loading-default')).to.be.ok;
done();
}, 1);
});
it('should execute callback and display a spinner immediately after initialize', (done) => {
vm.onInfinite = function test() {
Vue.nextTick(() => {
expect(isShow(vm.$el.querySelector('.loading-default'))).to.be.true;
done();
});
};
vm.$mount('#app');
});
it('should not to execute callback if the previous loading has not be completed', (done) => {
vm.onInfinite = function test() {
const len = this.list.length + 1;
for (let i = len; i < len + 20; i++) {
this.list.push(i);
}
Vue.nextTick(() => {
if (this.list.length === 20) {
vm.$el.addEventListener('scroll', () => {
expect(this.list).to.have.lengthOf(20);
done();
});
// trigger scroll event manually
vm.$el.scrollTop = vm.$el.scrollHeight;
}
});
}.bind(vm);
vm.$mount('#app');
});
it('should be destroyed completely by v-if', (done) => {
vm.onInfinite = function test() {
this.isLoadedAll = true;
Vue.nextTick(() => {
expect(vm.$el.querySelector('.loading-default')).to.not.be.ok;
done();
});
}.bind(vm);
vm.$mount('#app');
});
it('should display no results prompt', (done) => {
vm.onInfinite = function test() {
this.$refs.infiniteLoading.$emit('$InfiniteLoading:complete');
Vue.nextTick(() => {
expect(isShow(vm.$el.querySelectorAll('.infinite-status-prompt')[0])).to.be.true;
done();
});
}.bind(vm);
vm.$mount('#app');
});
it('should display no more data prompt', (done) => {
vm.onInfinite = function test() {
this.$refs.infiniteLoading.$emit('$InfiniteLoading:loaded');
this.$refs.infiniteLoading.$emit('$InfiniteLoading:complete');
// test for whether trigger again after complete
this.$refs.infiniteLoading.$emit('$InfiniteLoading:loaded');
Vue.nextTick(() => {
expect(isShow(vm.$el.querySelectorAll('.infinite-status-prompt')[1])).to.be.true;
done();
});
}.bind(vm);
vm.$mount('#app');
});
it('should load results to fill up the container', (done) => {
const expectedCount = Math.floor(vm.listContainerHeight / vm.listItemHeight);
let i = 0;
let timer;
vm.onInfinite = function test() {
setTimeout(() => {
this.list.push(++i);
this.$refs.infiniteLoading.$emit('$InfiniteLoading:loaded');
clearTimeout(timer);
timer = setTimeout(() => {
if (i >= expectedCount) {
done();
} else {
done(new Error('List not be fill up!'));
}
}, 100);
}, 1);
}.bind(vm);
vm.$mount('#app');
});
it('should reset component and call onInfinite again', (done) => {
let callCount = 0;
vm.onInfinite = function test() {
if (!callCount++) {
this.$refs.infiniteLoading.$emit('$InfiniteLoading:reset');
} else {
done();
}
}.bind(vm);
vm.$mount('#app');
});
it('should display the custom spinner if customize it with slot', () => {
vm.isCustomSpinner = true;
delete vm.distance;
vm.$mount('#app');
expect(vm.$el.querySelector('.custom-spinner')).to.be.ok;
});
it('should load data when scroll top (direction attribute)', (done) => {
vm.direction = 'top';
vm.onInfinite = function test() {
Vue.nextTick(() => {
expect(isShow(vm.$el.querySelector('.loading-default'))).to.be.true;
done();
});
};
vm.$mount('#app');
});
});
| Modify unit test to adapto to the new way that calculate distance
| test/unit/specs/InfiniteLoading.spec.js | Modify unit test to adapto to the new way that calculate distance | <ide><path>est/unit/specs/InfiniteLoading.spec.js
<ide> vm.$mount('#app');
<ide> });
<ide>
<del> it('should display the custom spinner if customize it with slot', () => {
<add> it('should display the custom spinner if customize it with slot', (done) => {
<ide> vm.isCustomSpinner = true;
<ide> delete vm.distance;
<ide> vm.$mount('#app');
<ide>
<del> expect(vm.$el.querySelector('.custom-spinner')).to.be.ok;
<add> Vue.nextTick(() => {
<add> expect(vm.$el.querySelector('.custom-spinner')).to.be.ok;
<add> done();
<add> });
<ide> });
<ide>
<ide> it('should load data when scroll top (direction attribute)', (done) => { |
|
Java | apache-2.0 | d0a8d89baec22946bdccc546b501250375c8ce0d | 0 | mdogan/hazelcast,mdogan/hazelcast,dsukhoroslov/hazelcast,mesutcelik/hazelcast,dsukhoroslov/hazelcast,Donnerbart/hazelcast,mesutcelik/hazelcast,emre-aydin/hazelcast,tkountis/hazelcast,emre-aydin/hazelcast,tombujok/hazelcast,lmjacksoniii/hazelcast,tufangorel/hazelcast,dbrimley/hazelcast,juanavelez/hazelcast,dbrimley/hazelcast,tkountis/hazelcast,dbrimley/hazelcast,tombujok/hazelcast,tkountis/hazelcast,mdogan/hazelcast,emrahkocaman/hazelcast,emrahkocaman/hazelcast,tufangorel/hazelcast,tufangorel/hazelcast,juanavelez/hazelcast,mesutcelik/hazelcast,Donnerbart/hazelcast,lmjacksoniii/hazelcast,Donnerbart/hazelcast,emre-aydin/hazelcast | /*
* Copyright (c) 2008-2016, Hazelcast, Inc. 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.internal.cluster.impl;
import com.hazelcast.config.Config;
import com.hazelcast.config.JoinConfig;
import com.hazelcast.config.MulticastConfig;
import com.hazelcast.instance.Node;
import com.hazelcast.instance.OutOfMemoryErrorDispatcher;
import com.hazelcast.logging.ILogger;
import com.hazelcast.nio.Address;
import com.hazelcast.nio.BufferObjectDataInput;
import com.hazelcast.nio.BufferObjectDataOutput;
import com.hazelcast.nio.Packet;
import com.hazelcast.nio.serialization.HazelcastSerializationException;
import com.hazelcast.util.EmptyStatement;
import java.io.EOFException;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.MulticastSocket;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
public final class MulticastService implements Runnable {
private static final int SEND_OUTPUT_SIZE = 1024;
private static final int DATAGRAM_BUFFER_SIZE = 64 * 1024;
private static final int SOCKET_BUFFER_SIZE = 64 * 1024;
private static final int SOCKET_TIMEOUT = 1000;
private static final int SHUTDOWN_TIMEOUT_SECONDS = 5;
private static final int JOIN_SERIALIZATION_ERROR_SUPPRESSION_MILLIS = 60000;
private final List<MulticastListener> listeners = new CopyOnWriteArrayList<MulticastListener>();
private final Object sendLock = new Object();
private final CountDownLatch stopLatch = new CountDownLatch(1);
private final ILogger logger;
private final Node node;
private final MulticastSocket multicastSocket;
private final BufferObjectDataOutput sendOutput;
private final DatagramPacket datagramPacketSend;
private final DatagramPacket datagramPacketReceive;
private long lastLoggedJoinSerializationFailure;
private volatile boolean running = true;
private MulticastService(Node node, MulticastSocket multicastSocket) throws Exception {
this.logger = node.getLogger(MulticastService.class.getName());
this.node = node;
this.multicastSocket = multicastSocket;
this.sendOutput = node.getSerializationService().createObjectDataOutput(SEND_OUTPUT_SIZE);
Config config = node.getConfig();
MulticastConfig multicastConfig = config.getNetworkConfig().getJoin().getMulticastConfig();
this.datagramPacketSend = new DatagramPacket(new byte[0], 0, InetAddress.getByName(multicastConfig.getMulticastGroup()),
multicastConfig.getMulticastPort());
this.datagramPacketReceive = new DatagramPacket(new byte[DATAGRAM_BUFFER_SIZE], DATAGRAM_BUFFER_SIZE);
}
public static MulticastService createMulticastService(Address bindAddress, Node node, Config config, ILogger logger) {
JoinConfig join = config.getNetworkConfig().getJoin();
MulticastConfig multicastConfig = join.getMulticastConfig();
if (!multicastConfig.isEnabled()) {
return null;
}
MulticastService mcService = null;
try {
MulticastSocket multicastSocket = new MulticastSocket(null);
multicastSocket.setReuseAddress(true);
// bind to receive interface
multicastSocket.bind(new InetSocketAddress(multicastConfig.getMulticastPort()));
multicastSocket.setTimeToLive(multicastConfig.getMulticastTimeToLive());
try {
// http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4417033
// http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6402758
if (!bindAddress.getInetAddress().isLoopbackAddress()) {
multicastSocket.setInterface(bindAddress.getInetAddress());
} else if (multicastConfig.isLoopbackModeEnabled()) {
multicastSocket.setLoopbackMode(true);
multicastSocket.setInterface(bindAddress.getInetAddress());
} else {
// If LoopBack is not enabled but its the selected interface from the given
// bind address, then we rely on Default Network Interface.
logger.warning("Hazelcast is bound to " + bindAddress.getHost() + " and loop-back mode is disabled in "
+ "the configuration. This could cause multicast auto-discovery issues and render it unable to work. "
+ "Check you network connectivity, try to enable the loopback mode and/or "
+ "force -Djava.net.preferIPv4Stack=true on your JVM.");
}
} catch (Exception e) {
logger.warning(e);
}
multicastSocket.setReceiveBufferSize(SOCKET_BUFFER_SIZE);
multicastSocket.setSendBufferSize(SOCKET_BUFFER_SIZE);
String multicastGroup = System.getProperty("hazelcast.multicast.group");
if (multicastGroup == null) {
multicastGroup = multicastConfig.getMulticastGroup();
}
multicastConfig.setMulticastGroup(multicastGroup);
multicastSocket.joinGroup(InetAddress.getByName(multicastGroup));
multicastSocket.setSoTimeout(SOCKET_TIMEOUT);
mcService = new MulticastService(node, multicastSocket);
mcService.addMulticastListener(new NodeMulticastListener(node));
} catch (Exception e) {
logger.severe(e);
}
return mcService;
}
public void addMulticastListener(MulticastListener multicastListener) {
listeners.add(multicastListener);
}
public void removeMulticastListener(MulticastListener multicastListener) {
listeners.remove(multicastListener);
}
public void stop() {
try {
if (!running && multicastSocket.isClosed()) {
return;
}
try {
multicastSocket.close();
} catch (Throwable ignored) {
EmptyStatement.ignore(ignored);
}
running = false;
if (!stopLatch.await(SHUTDOWN_TIMEOUT_SECONDS, TimeUnit.SECONDS)) {
logger.warning("Failed to shutdown MulticastService in " + SHUTDOWN_TIMEOUT_SECONDS + " seconds!");
}
} catch (Throwable e) {
logger.warning(e);
}
}
private void cleanup() {
running = false;
try {
sendOutput.close();
datagramPacketReceive.setData(new byte[0]);
datagramPacketSend.setData(new byte[0]);
} catch (Throwable ignored) {
EmptyStatement.ignore(ignored);
}
stopLatch.countDown();
}
@SuppressWarnings("WhileLoopSpinsOnField")
@Override
public void run() {
try {
while (running) {
try {
final JoinMessage joinMessage = receive();
if (joinMessage != null) {
for (MulticastListener multicastListener : listeners) {
try {
multicastListener.onMessage(joinMessage);
} catch (Exception e) {
logger.warning(e);
}
}
}
} catch (OutOfMemoryError e) {
OutOfMemoryErrorDispatcher.onOutOfMemory(e);
} catch (Exception e) {
logger.warning(e);
}
}
} finally {
cleanup();
}
}
private JoinMessage receive() {
try {
try {
multicastSocket.receive(datagramPacketReceive);
} catch (IOException ignore) {
return null;
}
try {
final byte[] data = datagramPacketReceive.getData();
final int offset = datagramPacketReceive.getOffset();
final BufferObjectDataInput input = node.getSerializationService().createObjectDataInput(data);
input.position(offset);
final byte packetVersion = input.readByte();
if (packetVersion != Packet.VERSION) {
logger.warning("Received a JoinRequest with a different packet version! This -> "
+ Packet.VERSION + ", Incoming -> " + packetVersion
+ ", Sender -> " + datagramPacketReceive.getAddress());
return null;
}
try {
return input.readObject();
} finally {
input.close();
}
} catch (Exception e) {
if (e instanceof EOFException || e instanceof HazelcastSerializationException) {
long now = System.currentTimeMillis();
if (now - lastLoggedJoinSerializationFailure > JOIN_SERIALIZATION_ERROR_SUPPRESSION_MILLIS) {
lastLoggedJoinSerializationFailure = now;
logger.warning("Received a JoinRequest with an incompatible binary-format. "
+ "An old version of Hazelcast may be using the same multicast discovery port. "
+ "Are you running multiple Hazelcast clusters on this host? "
+ "(This message will be suppressed for 60 seconds). ");
}
} else {
throw e;
}
}
} catch (Exception e) {
logger.warning(e);
}
return null;
}
public void send(JoinMessage joinMessage) {
if (!running) {
return;
}
final BufferObjectDataOutput out = sendOutput;
synchronized (sendLock) {
try {
out.writeByte(Packet.VERSION);
out.writeObject(joinMessage);
datagramPacketSend.setData(out.toByteArray());
multicastSocket.send(datagramPacketSend);
out.clear();
} catch (IOException e) {
logger.warning("You probably have too long Hazelcast configuration!", e);
}
}
}
}
| hazelcast/src/main/java/com/hazelcast/internal/cluster/impl/MulticastService.java | /*
* Copyright (c) 2008-2016, Hazelcast, Inc. 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.internal.cluster.impl;
import com.hazelcast.config.Config;
import com.hazelcast.config.JoinConfig;
import com.hazelcast.config.MulticastConfig;
import com.hazelcast.instance.Node;
import com.hazelcast.instance.OutOfMemoryErrorDispatcher;
import com.hazelcast.logging.ILogger;
import com.hazelcast.nio.Address;
import com.hazelcast.nio.BufferObjectDataInput;
import com.hazelcast.nio.BufferObjectDataOutput;
import com.hazelcast.nio.Packet;
import com.hazelcast.nio.serialization.HazelcastSerializationException;
import com.hazelcast.util.EmptyStatement;
import java.io.EOFException;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.MulticastSocket;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
public final class MulticastService implements Runnable {
private static final int SEND_OUTPUT_SIZE = 1024;
private static final int DATAGRAM_BUFFER_SIZE = 64 * 1024;
private static final int SOCKET_BUFFER_SIZE = 64 * 1024;
private static final int SOCKET_TIMEOUT = 1000;
private static final int SHUTDOWN_TIMEOUT_SECONDS = 5;
private final List<MulticastListener> listeners = new CopyOnWriteArrayList<MulticastListener>();
private final Object sendLock = new Object();
private final CountDownLatch stopLatch = new CountDownLatch(1);
private final ILogger logger;
private final Node node;
private final MulticastSocket multicastSocket;
private final BufferObjectDataOutput sendOutput;
private final DatagramPacket datagramPacketSend;
private final DatagramPacket datagramPacketReceive;
private volatile boolean running = true;
private MulticastService(Node node, MulticastSocket multicastSocket) throws Exception {
this.logger = node.getLogger(MulticastService.class.getName());
this.node = node;
this.multicastSocket = multicastSocket;
this.sendOutput = node.getSerializationService().createObjectDataOutput(SEND_OUTPUT_SIZE);
Config config = node.getConfig();
MulticastConfig multicastConfig = config.getNetworkConfig().getJoin().getMulticastConfig();
this.datagramPacketSend = new DatagramPacket(new byte[0], 0, InetAddress.getByName(multicastConfig.getMulticastGroup()),
multicastConfig.getMulticastPort());
this.datagramPacketReceive = new DatagramPacket(new byte[DATAGRAM_BUFFER_SIZE], DATAGRAM_BUFFER_SIZE);
}
public static MulticastService createMulticastService(Address bindAddress, Node node, Config config, ILogger logger) {
JoinConfig join = config.getNetworkConfig().getJoin();
MulticastConfig multicastConfig = join.getMulticastConfig();
if (!multicastConfig.isEnabled()) {
return null;
}
MulticastService mcService = null;
try {
MulticastSocket multicastSocket = new MulticastSocket(null);
multicastSocket.setReuseAddress(true);
// bind to receive interface
multicastSocket.bind(new InetSocketAddress(multicastConfig.getMulticastPort()));
multicastSocket.setTimeToLive(multicastConfig.getMulticastTimeToLive());
try {
// http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4417033
// http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6402758
if (!bindAddress.getInetAddress().isLoopbackAddress()) {
multicastSocket.setInterface(bindAddress.getInetAddress());
} else if (multicastConfig.isLoopbackModeEnabled()) {
multicastSocket.setLoopbackMode(true);
multicastSocket.setInterface(bindAddress.getInetAddress());
} else {
// If LoopBack is not enabled but its the selected interface from the given
// bind address, then we rely on Default Network Interface.
logger.warning("Hazelcast is bound to " + bindAddress.getHost() + " and loop-back mode is disabled in "
+ "the configuration. This could cause multicast auto-discovery issues and render it unable to work. "
+ "Check you network connectivity, try to enable the loopback mode and/or "
+ "force -Djava.net.preferIPv4Stack=true on your JVM.");
}
} catch (Exception e) {
logger.warning(e);
}
multicastSocket.setReceiveBufferSize(SOCKET_BUFFER_SIZE);
multicastSocket.setSendBufferSize(SOCKET_BUFFER_SIZE);
String multicastGroup = System.getProperty("hazelcast.multicast.group");
if (multicastGroup == null) {
multicastGroup = multicastConfig.getMulticastGroup();
}
multicastConfig.setMulticastGroup(multicastGroup);
multicastSocket.joinGroup(InetAddress.getByName(multicastGroup));
multicastSocket.setSoTimeout(SOCKET_TIMEOUT);
mcService = new MulticastService(node, multicastSocket);
mcService.addMulticastListener(new NodeMulticastListener(node));
} catch (Exception e) {
logger.severe(e);
}
return mcService;
}
public void addMulticastListener(MulticastListener multicastListener) {
listeners.add(multicastListener);
}
public void removeMulticastListener(MulticastListener multicastListener) {
listeners.remove(multicastListener);
}
public void stop() {
try {
if (!running && multicastSocket.isClosed()) {
return;
}
try {
multicastSocket.close();
} catch (Throwable ignored) {
EmptyStatement.ignore(ignored);
}
running = false;
if (!stopLatch.await(SHUTDOWN_TIMEOUT_SECONDS, TimeUnit.SECONDS)) {
logger.warning("Failed to shutdown MulticastService in " + SHUTDOWN_TIMEOUT_SECONDS + " seconds!");
}
} catch (Throwable e) {
logger.warning(e);
}
}
private void cleanup() {
running = false;
try {
sendOutput.close();
datagramPacketReceive.setData(new byte[0]);
datagramPacketSend.setData(new byte[0]);
} catch (Throwable ignored) {
EmptyStatement.ignore(ignored);
}
stopLatch.countDown();
}
@SuppressWarnings("WhileLoopSpinsOnField")
@Override
public void run() {
try {
while (running) {
try {
final JoinMessage joinMessage = receive();
if (joinMessage != null) {
for (MulticastListener multicastListener : listeners) {
try {
multicastListener.onMessage(joinMessage);
} catch (Exception e) {
logger.warning(e);
}
}
}
} catch (OutOfMemoryError e) {
OutOfMemoryErrorDispatcher.onOutOfMemory(e);
} catch (Exception e) {
logger.warning(e);
}
}
} finally {
cleanup();
}
}
private JoinMessage receive() {
try {
try {
multicastSocket.receive(datagramPacketReceive);
} catch (IOException ignore) {
return null;
}
try {
final byte[] data = datagramPacketReceive.getData();
final int offset = datagramPacketReceive.getOffset();
final BufferObjectDataInput input = node.getSerializationService().createObjectDataInput(data);
input.position(offset);
final byte packetVersion = input.readByte();
if (packetVersion != Packet.VERSION) {
logger.warning("Received a JoinRequest with a different packet version! This -> "
+ Packet.VERSION + ", Incoming -> " + packetVersion
+ ", Sender -> " + datagramPacketReceive.getAddress());
return null;
}
try {
return input.readObject();
} finally {
input.close();
}
} catch (Exception e) {
if (e instanceof EOFException || e instanceof HazelcastSerializationException) {
logger.warning("Received data format is invalid. (An old version of Hazelcast may be running here.)", e);
} else {
throw e;
}
}
} catch (Exception e) {
logger.warning(e);
}
return null;
}
public void send(JoinMessage joinMessage) {
if (!running) {
return;
}
final BufferObjectDataOutput out = sendOutput;
synchronized (sendLock) {
try {
out.writeByte(Packet.VERSION);
out.writeObject(joinMessage);
datagramPacketSend.setData(out.toByteArray());
multicastSocket.send(datagramPacketSend);
out.clear();
} catch (IOException e) {
logger.warning("You probably have too long Hazelcast configuration!", e);
}
}
}
}
| Suppressing excessive logging on serialization failure during a cluster multicast discovery. Fixes #8867 (or at least makes it less verbose) (#9686)
| hazelcast/src/main/java/com/hazelcast/internal/cluster/impl/MulticastService.java | Suppressing excessive logging on serialization failure during a cluster multicast discovery. Fixes #8867 (or at least makes it less verbose) (#9686) | <ide><path>azelcast/src/main/java/com/hazelcast/internal/cluster/impl/MulticastService.java
<ide> private static final int SOCKET_BUFFER_SIZE = 64 * 1024;
<ide> private static final int SOCKET_TIMEOUT = 1000;
<ide> private static final int SHUTDOWN_TIMEOUT_SECONDS = 5;
<add> private static final int JOIN_SERIALIZATION_ERROR_SUPPRESSION_MILLIS = 60000;
<ide>
<ide> private final List<MulticastListener> listeners = new CopyOnWriteArrayList<MulticastListener>();
<ide> private final Object sendLock = new Object();
<ide> private final DatagramPacket datagramPacketSend;
<ide> private final DatagramPacket datagramPacketReceive;
<ide>
<add> private long lastLoggedJoinSerializationFailure;
<ide> private volatile boolean running = true;
<add>
<ide>
<ide> private MulticastService(Node node, MulticastSocket multicastSocket) throws Exception {
<ide> this.logger = node.getLogger(MulticastService.class.getName());
<ide> }
<ide> } catch (Exception e) {
<ide> if (e instanceof EOFException || e instanceof HazelcastSerializationException) {
<del> logger.warning("Received data format is invalid. (An old version of Hazelcast may be running here.)", e);
<add> long now = System.currentTimeMillis();
<add> if (now - lastLoggedJoinSerializationFailure > JOIN_SERIALIZATION_ERROR_SUPPRESSION_MILLIS) {
<add> lastLoggedJoinSerializationFailure = now;
<add> logger.warning("Received a JoinRequest with an incompatible binary-format. "
<add> + "An old version of Hazelcast may be using the same multicast discovery port. "
<add> + "Are you running multiple Hazelcast clusters on this host? "
<add> + "(This message will be suppressed for 60 seconds). ");
<add> }
<ide> } else {
<ide> throw e;
<ide> } |
|
Java | epl-1.0 | 748dae9ec055d4564b302f842b9a713938d787f7 | 0 | phat-trien-phan-mem-phan-tan/dynamicpool,phat-trien-phan-mem-phan-tan/dynamicpool,phat-trien-phan-mem-phan-tan/dynamicpool,phat-trien-phan-mem-phan-tan/dynamicpool | package vn.edu.hust.student.dynamicpool.tests.presentation;
import java.util.ArrayList;
import java.util.List;
import com.badlogic.gdx.utils.Timer;
import com.badlogic.gdx.utils.Timer.Task;
import vn.edu.hust.student.dynamicpool.bll.BusinessLogicLayer;
import vn.edu.hust.student.dynamicpool.bll.ETrajectoryType;
import vn.edu.hust.student.dynamicpool.bll.FishFactory;
import vn.edu.hust.student.dynamicpool.bll.FishType;
import vn.edu.hust.student.dynamicpool.bll.IFish;
import vn.edu.hust.student.dynamicpool.model.DeviceInfo;
import vn.edu.hust.student.dynamicpool.presentation.PresentationBooleanCallback;
import vn.edu.hust.student.dynamicpool.utils.AppConst;
public class BLLTest implements BusinessLogicLayer {
private Timer timmer = new Timer();
private List<IFish> fishs = new ArrayList<IFish>();
public BLLTest() {
fishs.add(FishFactory.createFishWithLineTrajectory(AppConst.width, AppConst.height));
}
@Override
public void joinHost(String key, PresentationBooleanCallback callback) {
final PresentationBooleanCallback newcallback = callback;
this.timmer.scheduleTask(new Task() {
@Override
public void run() {
newcallback.callback(true, null);
}
}, 3);
}
@Override
public void createHost(PresentationBooleanCallback callback) {
final PresentationBooleanCallback newcallback = callback;
this.timmer.scheduleTask(new Task() {
@Override
public void run() {
newcallback.callback(true, null);
}
}, 3);
}
@Override
public void intialDevide(DeviceInfo devideInfor,
PresentationBooleanCallback callback) {
// TODO Aut1o-generated method stub
}
@Override
public void addDevide(DeviceInfo devideInfor,
final PresentationBooleanCallback callback) {
timmer.scheduleTask(new Task() {
@Override
public void run() {
callback.callback(true, null);
}
}, 2);
}
@Override
public java.util.List<IFish> getFishs() {
return fishs;
}
@Override
public void update(float deltaTime) {
for (IFish fish : fishs) {
fish.update(deltaTime);
}
}
@Override
public void exit() {
}
@Override
public void createFish(FishType fishType, ETrajectoryType trajectoryType,
int width, int height) {
// TODO Auto-generated method stub
}
@Override
public void synchronization() {
// TODO Auto-generated method stub
}
} | DynamicPool/core/src/vn/edu/hust/student/dynamicpool/tests/presentation/BLLTest.java | package vn.edu.hust.student.dynamicpool.tests.presentation;
import java.util.ArrayList;
import java.util.List;
import com.badlogic.gdx.utils.Timer;
import com.badlogic.gdx.utils.Timer.Task;
import vn.edu.hust.student.dynamicpool.bll.BusinessLogicLayer;
import vn.edu.hust.student.dynamicpool.bll.ETrajectoryType;
import vn.edu.hust.student.dynamicpool.bll.FishFactory;
import vn.edu.hust.student.dynamicpool.bll.FishType;
import vn.edu.hust.student.dynamicpool.bll.IFish;
import vn.edu.hust.student.dynamicpool.model.DeviceInfo;
import vn.edu.hust.student.dynamicpool.presentation.PresentationBooleanCallback;
import vn.edu.hust.student.dynamicpool.utils.AppConst;
public class BLLTest implements BusinessLogicLayer {
private Timer timmer = new Timer();
private List<IFish> fishs = new ArrayList<IFish>();
public BLLTest() {
fishs.add(FishFactory.createFishWithLineTrajectory(AppConst.width, AppConst.height));
}
@Override
public void joinHost(String key, PresentationBooleanCallback callback) {
final PresentationBooleanCallback newcallback = callback;
this.timmer.scheduleTask(new Task() {
@Override
public void run() {
newcallback.callback(true, null);
}
}, 3);
}
@Override
public void createHost(PresentationBooleanCallback callback) {
final PresentationBooleanCallback newcallback = callback;
this.timmer.scheduleTask(new Task() {
@Override
public void run() {
newcallback.callback(true, null);
}
}, 3);
}
@Override
public void intialDevide(DeviceInfo devideInfor,
PresentationBooleanCallback callback) {
// TODO Aut1o-generated method stub
}
@Override
public void addDevide(DeviceInfo devideInfor,
final PresentationBooleanCallback callback) {
timmer.scheduleTask(new Task() {
@Override
public void run() {
callback.callback(true, null);
}
}, 2);
}
@Override
public java.util.List<IFish> getFishs() {
return fishs;
}
@Override
public void update(float deltaTime) {
for (IFish fish : fishs) {
fish.update(deltaTime);
}
}
@Override
public void exit() {
}
@Override
public void createFish(FishType fishType, ETrajectoryType trajectoryType,
int width, int height) {
// TODO Auto-generated method stub
}
} | new update | DynamicPool/core/src/vn/edu/hust/student/dynamicpool/tests/presentation/BLLTest.java | new update | <ide><path>ynamicPool/core/src/vn/edu/hust/student/dynamicpool/tests/presentation/BLLTest.java
<ide> // TODO Auto-generated method stub
<ide>
<ide> }
<add> @Override
<add> public void synchronization() {
<add> // TODO Auto-generated method stub
<add>
<add> }
<ide> } |
|
Java | apache-2.0 | 48c71b3a77cc426116bddabe324aee601681fab9 | 0 | EvilMcJerkface/atlasdb,palantir/atlasdb,palantir/atlasdb,EvilMcJerkface/atlasdb,EvilMcJerkface/atlasdb,palantir/atlasdb | /**
* Copyright 2016 Palantir Technologies
*
* Licensed under the BSD-3 License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://opensource.org/licenses/BSD-3-Clause
*
* 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.palantir.atlasdb.keyvalue.cassandra;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.locks.ReentrantLock;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.cassandra.thrift.CASResult;
import org.apache.cassandra.thrift.Cassandra.Client;
import org.apache.cassandra.thrift.Column;
import org.apache.cassandra.thrift.ColumnOrSuperColumn;
import org.apache.cassandra.thrift.ColumnPath;
import org.apache.cassandra.thrift.ConsistencyLevel;
import org.apache.thrift.TException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.base.Stopwatch;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.primitives.Longs;
import com.palantir.atlasdb.AtlasDbConstants;
import com.palantir.atlasdb.cassandra.CassandraKeyValueServiceConfigManager;
import com.palantir.atlasdb.keyvalue.api.TableReference;
import com.palantir.common.base.FunctionCheckedException;
import com.palantir.common.base.Throwables;
final class SchemaMutationLock {
private static final Logger log = LoggerFactory.getLogger(SchemaMutationLock.class);
private static final Pattern GLOBAL_DDL_LOCK_FORMAT_PATTERN = Pattern.compile(
"^(?<lockId>\\d+)_(?<heartbeatCount>\\d+)$");
private static final String GLOBAL_DDL_LOCK_FORMAT = "%1$d_%2$d";
private static final long GLOBAL_DDL_LOCK_CLEARED_ID = Long.MAX_VALUE;
private static final String GLOBAL_DDL_LOCK_CLEARED_VALUE =
lockValueFromIdAndHeartbeat(GLOBAL_DDL_LOCK_CLEARED_ID, 0);
private static final int INITIAL_TIME_BETWEEN_LOCK_ATTEMPT_ROUNDS_MILLIS = 1000;
private static final int TIME_BETWEEN_LOCK_ATTEMPT_ROUNDS_MILLIS_CAP = 5000;
private static final int MAX_UNLOCK_RETRY_COUNT = 5;
public static final int DEFAULT_DEAD_HEARTBEAT_TIMEOUT_THRESHOLD_MILLIS = 60000;
private final boolean supportsCas;
private final CassandraKeyValueServiceConfigManager configManager;
private final CassandraClientPool clientPool;
private final TracingQueryRunner queryRunner;
private final ConsistencyLevel writeConsistency;
private final UniqueSchemaMutationLockTable lockTable;
private final ReentrantLock schemaMutationLockForEarlierVersionsOfCassandra = new ReentrantLock(true);
private final HeartbeatService heartbeatService;
private final int deadHeartbeatTimeoutThreshold;
SchemaMutationLock(
boolean supportsCas,
CassandraKeyValueServiceConfigManager configManager,
CassandraClientPool clientPool,
TracingQueryRunner queryRunner,
ConsistencyLevel writeConsistency,
UniqueSchemaMutationLockTable lockTable,
HeartbeatService heartbeatService,
int deadHeartbeatTimeoutThreshold) {
this.supportsCas = supportsCas;
this.configManager = configManager;
this.clientPool = clientPool;
this.queryRunner = queryRunner;
this.writeConsistency = writeConsistency;
this.lockTable = lockTable;
this.heartbeatService = heartbeatService;
this.deadHeartbeatTimeoutThreshold = deadHeartbeatTimeoutThreshold;
}
public interface Action {
void execute() throws Exception;
}
void runWithLock(Action action) {
if (!supportsCas) {
runWithLockWithoutCas(action);
return;
}
long lockId = waitForSchemaMutationLock();
try {
runActionWithHeartbeat(action, lockId);
} finally {
schemaMutationUnlock(lockId);
}
}
private void runActionWithHeartbeat(Action action, long lockId) {
try {
heartbeatService.startBeatingForLock(lockId);
action.execute();
} catch (Exception e) {
throw Throwables.throwUncheckedException(e);
} finally {
heartbeatService.stopBeating();
}
}
private void runWithLockWithoutCas(Action action) {
log.info("Because your version of Cassandra does not support check and set,"
+ " we will use a java level lock to synchronise schema mutations."
+ " If this is a clustered service, this could lead to corruption.");
try {
waitForSchemaMutationLockWithoutCas();
} catch (TimeoutException e) {
throw Throwables.throwUncheckedException(e);
}
try {
action.execute();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw Throwables.throwUncheckedException(e);
} catch (Exception e) {
throw Throwables.throwUncheckedException(e);
} finally {
schemaMutationUnlockWithoutCas();
}
}
/**
* Each locker generates a random ID per operation and uses a CAS operation as a DB-side lock.
*
* There are two special ID values used for book-keeping
* - one representing the lock being cleared
* - one representing a remote ID that is guaranteed to never be generated
* This is required because Cassandra CAS does not treat setting to null / empty as a delete,
* (though there is a to-do in their code to possibly add this)
* though it accepts an empty expected column to mean that non-existance was expected
* (see putUnlessExists for example, which has the luck of not having to ever deal with deleted values)
*
* I can't hold this against them though, because Atlas has a semi-similar problem with empty byte[] values
* meaning deleted internally.
*
* @return an ID to be passed into a subsequent unlock call
*/
private long waitForSchemaMutationLock() {
final long perOperationNodeId = ThreadLocalRandom.current().nextLong(Long.MAX_VALUE - 2);
try {
clientPool.runWithRetry((FunctionCheckedException<Client, Void, Exception>) client -> {
Column ourUpdate = lockColumnFromIdAndHeartbeat(perOperationNodeId, 0);
List<Column> expected = ImmutableList.of(lockColumnWithValue(GLOBAL_DDL_LOCK_CLEARED_VALUE));
CASResult casResult = writeDdlLockWithCas(client, expected, ourUpdate);
Column lastSeenColumn = null;
long lastSeenColumnUpdateTs = 0;
int currentTimeBetweenLockAttemptsMillis = INITIAL_TIME_BETWEEN_LOCK_ATTEMPT_ROUNDS_MILLIS;
// We use schemaMutationTimeoutMillis to wait for schema mutations to agree as well as
// to specify the timeout period before we give up trying to acquire the schema mutation lock
int mutationTimeoutMillis = configManager.getConfig().schemaMutationTimeoutMillis()
* CassandraConstants.SCHEMA_MUTATION_LOCK_TIMEOUT_MULTIPLIER;
Stopwatch stopwatch = Stopwatch.createStarted();
// could have a timeout controlling this level, confusing for users to set both timeouts though
while (!casResult.isSuccess()) {
if (casResult.getCurrent_valuesSize() == 0) { // never has been an existing lock
// special case, no one has ever made a lock ever before
// this becomes analogous to putUnlessExists now
expected = ImmutableList.of();
} else {
Column existingColumn = Iterables.getOnlyElement(casResult.getCurrent_values(), null);
if (existingColumn == null) {
throw new IllegalStateException("Something is wrong with underlying locks."
+ " Contact support for guidance on manually examining and clearing"
+ " locks from " + lockTable.getOnlyTable() + " table.");
}
if (!existingColumn.equals(lastSeenColumn)) {
lastSeenColumn = existingColumn;
lastSeenColumnUpdateTs = System.currentTimeMillis();
} else if (deadHeartbeatThresholdReached(lastSeenColumnUpdateTs)) {
throw generateDeadHeartbeatException();
}
expected = getExpectedCasResult(existingColumn);
}
// lock holder taking unreasonable amount of time, signal something's wrong
if (stopwatch.elapsed(TimeUnit.MILLISECONDS) > mutationTimeoutMillis) {
TimeoutException schemaLockTimeoutError = generateSchemaLockTimeoutException(stopwatch);
log.error(schemaLockTimeoutError.getMessage(), schemaLockTimeoutError);
throw Throwables.rewrapAndThrowUncheckedException(schemaLockTimeoutError);
}
currentTimeBetweenLockAttemptsMillis = getCappedTimeBetweenLockAttemptsWithBackoff(
currentTimeBetweenLockAttemptsMillis);
Thread.sleep(currentTimeBetweenLockAttemptsMillis);
casResult = writeDdlLockWithCas(client, expected, ourUpdate);
}
// we won the lock!
log.info("Successfully acquired schema mutation lock.");
return null;
});
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw Throwables.throwUncheckedException(e);
} catch (Exception e) {
throw Throwables.throwUncheckedException(e);
}
return perOperationNodeId;
}
private boolean deadHeartbeatThresholdReached(long lastSeenColumnUpdateTs) {
return (System.currentTimeMillis() - lastSeenColumnUpdateTs) > deadHeartbeatTimeoutThreshold;
}
private List<Column> getExpectedCasResult(Column existingColumn) {
// handle old (pre-heartbeat) cleared lock values encountered during migrations
if (Longs.fromByteArray(existingColumn.getValue()) == GLOBAL_DDL_LOCK_CLEARED_ID) {
return ImmutableList.of(lockColumnWithValue(
Longs.toByteArray(GLOBAL_DDL_LOCK_CLEARED_ID)));
} else {
return ImmutableList.of(lockColumnWithValue(GLOBAL_DDL_LOCK_CLEARED_VALUE));
}
}
private RuntimeException generateDeadHeartbeatException() {
return new RuntimeException("The current lock holder has failed to update its heartbeat."
+ " We suspect that this might be due to a node crashing while holding the"
+ " schema mutation lock. If this is indeed the case, run the clean-cass-locks-state"
+ " cli command.");
}
private TimeoutException generateSchemaLockTimeoutException(Stopwatch stopwatch) {
return new TimeoutException(
String.format("We have timed out waiting on the current"
+ " schema mutation lock holder. We have tried to grab the lock for %d milliseconds"
+ " unsuccessfully. This indicates that the current lock holder has died without"
+ " releasing the lock and will require manual intervention. Shut down all AtlasDB"
+ " clients operating on the %s keyspace and then run the clean-cass-locks-state"
+ " cli command.",
stopwatch.elapsed(TimeUnit.MILLISECONDS),
configManager.getConfig().keyspace()));
}
private void waitForSchemaMutationLockWithoutCas() throws TimeoutException {
String message = "AtlasDB was unable to get a lock on Cassandra system schema mutations"
+ " for your cluster. Likely cause: Service(s) performing heavy schema mutations"
+ " in parallel, or extremely heavy Cassandra cluster load.";
try {
if (!schemaMutationLockForEarlierVersionsOfCassandra.tryLock(
configManager.getConfig().schemaMutationTimeoutMillis(),
TimeUnit.MILLISECONDS)) {
throw new TimeoutException(message);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new TimeoutException(message);
}
}
private void schemaMutationUnlock(long perOperationNodeId) {
boolean unlockDone = false;
boolean isInterrupted = false;
int currentSleepMillis = INITIAL_TIME_BETWEEN_LOCK_ATTEMPT_ROUNDS_MILLIS;
for (int unlockRetryCount = 0; unlockRetryCount < MAX_UNLOCK_RETRY_COUNT; unlockRetryCount++) {
unlockDone = trySchemaMutationUnlockOnce(perOperationNodeId);
if (unlockDone) {
break;
}
currentSleepMillis = getCappedTimeBetweenLockAttemptsWithBackoff(currentSleepMillis);
try {
Thread.sleep(currentSleepMillis);
} catch (InterruptedException e) {
isInterrupted = true;
}
}
if (isInterrupted) {
Thread.currentThread().interrupt();
}
Preconditions.checkState(unlockDone, "Unable to unlock despite retrying.");
}
private boolean trySchemaMutationUnlockOnce(long perOperationNodeId) {
CASResult result;
try {
result = clientPool.runWithRetry(client -> {
Column existingColumn = queryExistingLockColumn(client);
long existingLockId = getLockIdFromColumn(existingColumn);
if (existingLockId != GLOBAL_DDL_LOCK_CLEARED_ID) {
Preconditions.checkState(existingLockId == perOperationNodeId,
String.format("Trying to unlock unowned lock. Expected [%d], but got [%d]",
perOperationNodeId, existingLockId));
}
List<Column> ourExpectedLock = ImmutableList.of(existingColumn);
Column clearedLock = lockColumnWithValue(GLOBAL_DDL_LOCK_CLEARED_VALUE);
return writeDdlLockWithCas(client, ourExpectedLock, clearedLock);
});
} catch (TException e) {
throw Throwables.throwUncheckedException(e);
}
return result.isSuccess();
}
private Column queryExistingLockColumn(Client client) throws TException {
TableReference lockTableRef = lockTable.getOnlyTable();
ColumnPath columnPath = new ColumnPath(lockTableRef.getQualifiedName());
columnPath.setColumn(getGlobalDdlLockColumnName());
ColumnOrSuperColumn result = queryRunner.run(client, lockTableRef,
() -> client.get(getGlobalDdlLockRowName(), columnPath, ConsistencyLevel.LOCAL_QUORUM));
return result.getColumn();
}
private void schemaMutationUnlockWithoutCas() {
schemaMutationLockForEarlierVersionsOfCassandra.unlock();
}
private CASResult writeDdlLockWithCas(
Client client,
List<Column> expectedLockValue,
Column newLockValue) throws TException {
TableReference lockTableRef = lockTable.getOnlyTable();
return queryRunner.run(client, lockTableRef,
() -> client.cas(
getGlobalDdlLockRowName(),
lockTableRef.getQualifiedName(),
expectedLockValue,
ImmutableList.of(newLockValue),
ConsistencyLevel.SERIAL,
writeConsistency));
}
static void handleForcedLockClear(CASResult casResult, long perOperationNodeId, int heartbeatCount) {
Preconditions.checkState(casResult.getCurrent_valuesSize() == 1,
"Something is wrong with the underlying locks. Contact support for guidance.");
String remoteLock = "(unknown)";
Column column = Iterables.getOnlyElement(casResult.getCurrent_values(), null);
if (column != null) {
String remoteValue = new String(column.getValue(), StandardCharsets.UTF_8);
long remoteId = Long.parseLong(remoteValue.split("_")[0]);
remoteLock = (remoteId == GLOBAL_DDL_LOCK_CLEARED_ID)
? "(Cleared Value)"
: remoteValue;
}
String expectedLock = lockValueFromIdAndHeartbeat(perOperationNodeId, heartbeatCount);
throw new IllegalStateException(String.format("Another process cleared our schema mutation lock from"
+ " underneath us. Our ID, which we expected, was %s, the value we saw in the database"
+ " was instead %s.", expectedLock, remoteLock));
}
private static Column lockColumnWithValue(byte[] value) {
return new Column()
.setName(getGlobalDdlLockColumnName())
.setValue(value) // expected previous
.setTimestamp(AtlasDbConstants.TRANSACTION_TS);
}
private static Column lockColumnWithValue(String strValue) {
return lockColumnWithValue(strValue.getBytes(StandardCharsets.UTF_8));
}
private static long getLockIdFromColumn(Column column) {
String columnStringValue = new String(column.getValue(), StandardCharsets.UTF_8);
Matcher columnStringMatcher = GLOBAL_DDL_LOCK_FORMAT_PATTERN.matcher(columnStringValue);
Preconditions.checkState(columnStringMatcher.matches(), "Invalid format for a lock column");
return Long.parseLong(columnStringMatcher.group("lockId"));
}
@VisibleForTesting
static long getHeartbeatCountFromColumn(Column column) {
String columnStringValue = new String(column.getValue(), StandardCharsets.UTF_8);
Matcher columnStringMatcher = GLOBAL_DDL_LOCK_FORMAT_PATTERN.matcher(columnStringValue);
Preconditions.checkState(columnStringMatcher.matches(), "Invalid format for a lock column");
return Long.parseLong(columnStringMatcher.group("heartbeatCount"));
}
private static byte[] getGlobalDdlLockColumnName() {
return CassandraKeyValueServices.makeCompositeBuffer(
CassandraConstants.GLOBAL_DDL_LOCK_COLUMN_NAME.getBytes(StandardCharsets.UTF_8),
AtlasDbConstants.TRANSACTION_TS).array();
}
private static int getCappedTimeBetweenLockAttemptsWithBackoff(int currentTimeValue) {
return Math.min(2 * currentTimeValue, TIME_BETWEEN_LOCK_ATTEMPT_ROUNDS_MILLIS_CAP);
}
static String lockValueFromIdAndHeartbeat(long id, int heartbeatCount) {
return String.format(GLOBAL_DDL_LOCK_FORMAT, id, heartbeatCount);
}
static ByteBuffer getGlobalDdlLockRowName() {
return ByteBuffer.wrap(CassandraConstants.GLOBAL_DDL_LOCK_ROW_NAME.getBytes(StandardCharsets.UTF_8));
}
static Column lockColumnFromIdAndHeartbeat(long id, int heartbeatCount) {
return lockColumnWithValue(lockValueFromIdAndHeartbeat(id, heartbeatCount));
}
}
| atlasdb-cassandra/src/main/java/com/palantir/atlasdb/keyvalue/cassandra/SchemaMutationLock.java | /**
* Copyright 2016 Palantir Technologies
*
* Licensed under the BSD-3 License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://opensource.org/licenses/BSD-3-Clause
*
* 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.palantir.atlasdb.keyvalue.cassandra;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.locks.ReentrantLock;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.cassandra.thrift.CASResult;
import org.apache.cassandra.thrift.Cassandra.Client;
import org.apache.cassandra.thrift.Column;
import org.apache.cassandra.thrift.ColumnOrSuperColumn;
import org.apache.cassandra.thrift.ColumnPath;
import org.apache.cassandra.thrift.ConsistencyLevel;
import org.apache.thrift.TException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.base.Stopwatch;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.primitives.Longs;
import com.palantir.atlasdb.AtlasDbConstants;
import com.palantir.atlasdb.cassandra.CassandraKeyValueServiceConfigManager;
import com.palantir.atlasdb.keyvalue.api.TableReference;
import com.palantir.common.base.FunctionCheckedException;
import com.palantir.common.base.Throwables;
final class SchemaMutationLock {
private static final Logger log = LoggerFactory.getLogger(SchemaMutationLock.class);
private static final Pattern GLOBAL_DDL_LOCK_FORMAT_PATTERN = Pattern.compile(
"^(?<lockId>\\d+)_(?<heartbeatCount>\\d+)$");
private static final String GLOBAL_DDL_LOCK_FORMAT = "%1$d_%2$d";
private static final long GLOBAL_DDL_LOCK_CLEARED_ID = Long.MAX_VALUE;
private static final String GLOBAL_DDL_LOCK_CLEARED_VALUE =
lockValueFromIdAndHeartbeat(GLOBAL_DDL_LOCK_CLEARED_ID, 0);
private static final int INITIAL_TIME_BETWEEN_LOCK_ATTEMPT_ROUNDS_MILLIS = 1000;
private static final int TIME_BETWEEN_LOCK_ATTEMPT_ROUNDS_MILLIS_CAP = 5000;
private static final int MAX_UNLOCK_RETRY_COUNT = 5;
public static final int DEFAULT_DEAD_HEARTBEAT_TIMEOUT_THRESHOLD_MILLIS = 60000;
private final boolean supportsCas;
private final CassandraKeyValueServiceConfigManager configManager;
private final CassandraClientPool clientPool;
private final TracingQueryRunner queryRunner;
private final ConsistencyLevel writeConsistency;
private final UniqueSchemaMutationLockTable lockTable;
private final ReentrantLock schemaMutationLockForEarlierVersionsOfCassandra = new ReentrantLock(true);
private final HeartbeatService heartbeatService;
private final int deadHeartbeatTimeoutThreshold;
SchemaMutationLock(
boolean supportsCas,
CassandraKeyValueServiceConfigManager configManager,
CassandraClientPool clientPool,
TracingQueryRunner queryRunner,
ConsistencyLevel writeConsistency,
UniqueSchemaMutationLockTable lockTable,
HeartbeatService heartbeatService,
int deadHeartbeatTimeoutThreshold) {
this.supportsCas = supportsCas;
this.configManager = configManager;
this.clientPool = clientPool;
this.queryRunner = queryRunner;
this.writeConsistency = writeConsistency;
this.lockTable = lockTable;
this.heartbeatService = heartbeatService;
this.deadHeartbeatTimeoutThreshold = deadHeartbeatTimeoutThreshold;
}
public interface Action {
void execute() throws Exception;
}
void runWithLock(Action action) {
if (!supportsCas) {
runWithLockWithoutCas(action);
return;
}
long lockId = waitForSchemaMutationLock();
try {
runActionWithHeartbeat(action, lockId);
} finally {
schemaMutationUnlock(lockId);
}
}
private void runActionWithHeartbeat(Action action, long lockId) {
try {
heartbeatService.startBeatingForLock(lockId);
action.execute();
} catch (Exception e) {
throw Throwables.throwUncheckedException(e);
} finally {
heartbeatService.stopBeating();
}
}
private void runWithLockWithoutCas(Action action) {
log.info("Because your version of Cassandra does not support check and set,"
+ " we will use a java level lock to synchronise schema mutations."
+ " If this is a clustered service, this could lead to corruption.");
try {
waitForSchemaMutationLockWithoutCas();
} catch (TimeoutException e) {
throw Throwables.throwUncheckedException(e);
}
try {
action.execute();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw Throwables.throwUncheckedException(e);
} catch (Exception e) {
throw Throwables.throwUncheckedException(e);
} finally {
schemaMutationUnlockWithoutCas();
}
}
/**
* Each locker generates a random ID per operation and uses a CAS operation as a DB-side lock.
*
* There are two special ID values used for book-keeping
* - one representing the lock being cleared
* - one representing a remote ID that is guaranteed to never be generated
* This is required because Cassandra CAS does not treat setting to null / empty as a delete,
* (though there is a to-do in their code to possibly add this)
* though it accepts an empty expected column to mean that non-existance was expected
* (see putUnlessExists for example, which has the luck of not having to ever deal with deleted values)
*
* I can't hold this against them though, because Atlas has a semi-similar problem with empty byte[] values
* meaning deleted internally.
*
* @return an ID to be passed into a subsequent unlock call
*/
private long waitForSchemaMutationLock() {
final long perOperationNodeId = ThreadLocalRandom.current().nextLong(Long.MAX_VALUE - 2);
try {
clientPool.runWithRetry((FunctionCheckedException<Client, Void, Exception>) client -> {
Column ourUpdate = lockColumnFromIdAndHeartbeat(perOperationNodeId, 0);
List<Column> expected = ImmutableList.of(lockColumnWithValue(GLOBAL_DDL_LOCK_CLEARED_VALUE));
CASResult casResult = writeDdlLockWithCas(client, expected, ourUpdate);
Column lastSeenColumn = null;
long lastSeenColumnUpdateTs = 0;
int currentTimeBetweenLockAttemptsMillis = INITIAL_TIME_BETWEEN_LOCK_ATTEMPT_ROUNDS_MILLIS;
// We use schemaMutationTimeoutMillis to wait for schema mutations to agree as well as
// to specify the timeout period before we give up trying to acquire the schema mutation lock
int mutationTimeoutMillis = configManager.getConfig().schemaMutationTimeoutMillis()
* CassandraConstants.SCHEMA_MUTATION_LOCK_TIMEOUT_MULTIPLIER;
Stopwatch stopwatch = Stopwatch.createStarted();
// could have a timeout controlling this level, confusing for users to set both timeouts though
while (!casResult.isSuccess()) {
if (casResult.getCurrent_valuesSize() == 0) { // never has been an existing lock
// special case, no one has ever made a lock ever before
// this becomes analogous to putUnlessExists now
expected = ImmutableList.of();
} else {
Column existingColumn = Iterables.getOnlyElement(casResult.getCurrent_values(), null);
if (existingColumn == null) {
throw new IllegalStateException("Something is wrong with underlying locks."
+ " Contact support for guidance on manually examining and clearing"
+ " locks from " + lockTable.getOnlyTable() + " table.");
}
if (!existingColumn.equals(lastSeenColumn)) {
lastSeenColumn = existingColumn;
lastSeenColumnUpdateTs = System.currentTimeMillis();
} else if (deadHeartbeatThresholdReached(lastSeenColumnUpdateTs)) {
throw generateDeadHeartbeatException();
}
expected = getExpectedCasResult(existingColumn);
}
// lock holder taking unreasonable amount of time, signal something's wrong
if (stopwatch.elapsed(TimeUnit.MILLISECONDS) > mutationTimeoutMillis) {
TimeoutException schemaLockTimeoutError = generateSchemaLockTimeoutException(stopwatch);
log.error(schemaLockTimeoutError.getMessage(), schemaLockTimeoutError);
throw Throwables.rewrapAndThrowUncheckedException(schemaLockTimeoutError);
}
currentTimeBetweenLockAttemptsMillis = getCappedTimeBetweenLockAttemptsWithBackoff(
currentTimeBetweenLockAttemptsMillis);
Thread.sleep(currentTimeBetweenLockAttemptsMillis);
casResult = writeDdlLockWithCas(client, expected, ourUpdate);
}
// we won the lock!
log.info("Successfully acquired schema mutation lock.");
return null;
});
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw Throwables.throwUncheckedException(e);
} catch (Exception e) {
throw Throwables.throwUncheckedException(e);
}
return perOperationNodeId;
}
private boolean deadHeartbeatThresholdReached(long lastSeenColumnUpdateTs) {
return (System.currentTimeMillis() - lastSeenColumnUpdateTs) > deadHeartbeatTimeoutThreshold;
}
private List<Column> getExpectedCasResult(Column existingColumn) {
// handle old (pre-heartbeat) cleared lock values encountered during migrations
if (Longs.fromByteArray(existingColumn.getValue()) == GLOBAL_DDL_LOCK_CLEARED_ID) {
return ImmutableList.of(lockColumnWithValue(
Longs.toByteArray(GLOBAL_DDL_LOCK_CLEARED_ID)));
} else {
return ImmutableList.of(lockColumnWithValue(GLOBAL_DDL_LOCK_CLEARED_VALUE));
}
}
private RuntimeException generateDeadHeartbeatException() {
return new RuntimeException("The current lock holder has failed to update its heartbeat."
+ " We suspect that this might be due to a node crashing while holding the"
+ " schema mutation lock. If this is indeed the case, run the clean-cass-locks-state"
+ " cli command.");
}
private TimeoutException generateSchemaLockTimeoutException(Stopwatch stopwatch) {
return new TimeoutException(
String.format("We have timed out waiting on the current"
+ " schema mutation lock holder. We have tried to grab the lock for %d milliseconds"
+ " unsuccessfully. This indicates that the current lock holder has died without"
+ " releasing the lock and will require manual intervention. Shut down all AtlasDB"
+ " clients operating on the %s keyspace and then run the clean-cass-locks-state"
+ " cli command.",
stopwatch.elapsed(TimeUnit.MILLISECONDS),
configManager.getConfig().keyspace()));
}
private void waitForSchemaMutationLockWithoutCas() throws TimeoutException {
String message = "AtlasDB was unable to get a lock on Cassandra system schema mutations"
+ " for your cluster. Likely cause: Service(s) performing heavy schema mutations"
+ " in parallel, or extremely heavy Cassandra cluster load.";
try {
if (!schemaMutationLockForEarlierVersionsOfCassandra.tryLock(
configManager.getConfig().schemaMutationTimeoutMillis(),
TimeUnit.MILLISECONDS)) {
throw new TimeoutException(message);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new TimeoutException(message);
}
}
private void schemaMutationUnlock(long perOperationNodeId) {
boolean unlockDone = false;
boolean isInterrupted = false;
int currentSleepMillis = INITIAL_TIME_BETWEEN_LOCK_ATTEMPT_ROUNDS_MILLIS;
for (int unlockRetryCount = 0; unlockRetryCount < MAX_UNLOCK_RETRY_COUNT; unlockRetryCount++) {
unlockDone = trySchemaMutationUnlockOnce(perOperationNodeId);
if (unlockDone) {
break;
}
currentSleepMillis = getCappedTimeBetweenLockAttemptsWithBackoff(currentSleepMillis);
try {
Thread.sleep(currentSleepMillis);
} catch (InterruptedException e) {
isInterrupted = true;
}
}
if (isInterrupted) {
Thread.currentThread().interrupt();
}
Preconditions.checkState(unlockDone, "Unable to unlock despite retrying.");
}
private boolean trySchemaMutationUnlockOnce(long perOperationNodeId) {
CASResult result;
try {
result = clientPool.runWithRetry(client -> {
Column existingColumn = queryExistingLockColumn(client);
Preconditions.checkState(isValidColumnForLockId(existingColumn, perOperationNodeId),
"Trying to unlock unowned lock");
List<Column> ourExpectedLock = ImmutableList.of(existingColumn);
Column clearedLock = lockColumnWithValue(GLOBAL_DDL_LOCK_CLEARED_VALUE);
return writeDdlLockWithCas(client, ourExpectedLock, clearedLock);
});
} catch (TException e) {
throw Throwables.throwUncheckedException(e);
}
return result.isSuccess();
}
private Column queryExistingLockColumn(Client client) throws TException {
TableReference lockTableRef = lockTable.getOnlyTable();
ColumnPath columnPath = new ColumnPath(lockTableRef.getQualifiedName());
columnPath.setColumn(getGlobalDdlLockColumnName());
ColumnOrSuperColumn result = queryRunner.run(client, lockTableRef,
() -> client.get(getGlobalDdlLockRowName(), columnPath, ConsistencyLevel.LOCAL_QUORUM));
return result.getColumn();
}
private void schemaMutationUnlockWithoutCas() {
schemaMutationLockForEarlierVersionsOfCassandra.unlock();
}
private CASResult writeDdlLockWithCas(
Client client,
List<Column> expectedLockValue,
Column newLockValue) throws TException {
TableReference lockTableRef = lockTable.getOnlyTable();
return queryRunner.run(client, lockTableRef,
() -> client.cas(
getGlobalDdlLockRowName(),
lockTableRef.getQualifiedName(),
expectedLockValue,
ImmutableList.of(newLockValue),
ConsistencyLevel.SERIAL,
writeConsistency));
}
static void handleForcedLockClear(CASResult casResult, long perOperationNodeId, int heartbeatCount) {
Preconditions.checkState(casResult.getCurrent_valuesSize() == 1,
"Something is wrong with the underlying locks. Contact support for guidance.");
String remoteLock = "(unknown)";
Column column = Iterables.getOnlyElement(casResult.getCurrent_values(), null);
if (column != null) {
String remoteValue = new String(column.getValue(), StandardCharsets.UTF_8);
long remoteId = Long.parseLong(remoteValue.split("_")[0]);
remoteLock = (remoteId == GLOBAL_DDL_LOCK_CLEARED_ID)
? "(Cleared Value)"
: remoteValue;
}
String expectedLock = lockValueFromIdAndHeartbeat(perOperationNodeId, heartbeatCount);
throw new IllegalStateException(String.format("Another process cleared our schema mutation lock from"
+ " underneath us. Our ID, which we expected, was %s, the value we saw in the database"
+ " was instead %s.", expectedLock, remoteLock));
}
private static boolean isValidColumnForLockId(Column column, long lockId) {
return getLockIdFromColumn(column) == lockId;
}
private static Column lockColumnWithValue(byte[] value) {
return new Column()
.setName(getGlobalDdlLockColumnName())
.setValue(value) // expected previous
.setTimestamp(AtlasDbConstants.TRANSACTION_TS);
}
private static Column lockColumnWithValue(String strValue) {
return lockColumnWithValue(strValue.getBytes(StandardCharsets.UTF_8));
}
private static long getLockIdFromColumn(Column column) {
String columnStringValue = new String(column.getValue(), StandardCharsets.UTF_8);
Matcher columnStringMatcher = GLOBAL_DDL_LOCK_FORMAT_PATTERN.matcher(columnStringValue);
Preconditions.checkState(columnStringMatcher.matches(), "Invalid format for a lock column");
return Long.parseLong(columnStringMatcher.group("lockId"));
}
@VisibleForTesting
static long getHeartbeatCountFromColumn(Column column) {
String columnStringValue = new String(column.getValue(), StandardCharsets.UTF_8);
Matcher columnStringMatcher = GLOBAL_DDL_LOCK_FORMAT_PATTERN.matcher(columnStringValue);
Preconditions.checkState(columnStringMatcher.matches(), "Invalid format for a lock column");
return Long.parseLong(columnStringMatcher.group("heartbeatCount"));
}
private static byte[] getGlobalDdlLockColumnName() {
return CassandraKeyValueServices.makeCompositeBuffer(
CassandraConstants.GLOBAL_DDL_LOCK_COLUMN_NAME.getBytes(StandardCharsets.UTF_8),
AtlasDbConstants.TRANSACTION_TS).array();
}
private static int getCappedTimeBetweenLockAttemptsWithBackoff(int currentTimeValue) {
return Math.min(2 * currentTimeValue, TIME_BETWEEN_LOCK_ATTEMPT_ROUNDS_MILLIS_CAP);
}
static String lockValueFromIdAndHeartbeat(long id, int heartbeatCount) {
return String.format(GLOBAL_DDL_LOCK_FORMAT, id, heartbeatCount);
}
static ByteBuffer getGlobalDdlLockRowName() {
return ByteBuffer.wrap(CassandraConstants.GLOBAL_DDL_LOCK_ROW_NAME.getBytes(StandardCharsets.UTF_8));
}
static Column lockColumnFromIdAndHeartbeat(long id, int heartbeatCount) {
return lockColumnWithValue(lockValueFromIdAndHeartbeat(id, heartbeatCount));
}
}
| Update exception to provide more info + Ignore cleared IDs for unlocks
| atlasdb-cassandra/src/main/java/com/palantir/atlasdb/keyvalue/cassandra/SchemaMutationLock.java | Update exception to provide more info + Ignore cleared IDs for unlocks | <ide><path>tlasdb-cassandra/src/main/java/com/palantir/atlasdb/keyvalue/cassandra/SchemaMutationLock.java
<ide> try {
<ide> result = clientPool.runWithRetry(client -> {
<ide> Column existingColumn = queryExistingLockColumn(client);
<del>
<del> Preconditions.checkState(isValidColumnForLockId(existingColumn, perOperationNodeId),
<del> "Trying to unlock unowned lock");
<add> long existingLockId = getLockIdFromColumn(existingColumn);
<add>
<add> if (existingLockId != GLOBAL_DDL_LOCK_CLEARED_ID) {
<add> Preconditions.checkState(existingLockId == perOperationNodeId,
<add> String.format("Trying to unlock unowned lock. Expected [%d], but got [%d]",
<add> perOperationNodeId, existingLockId));
<add> }
<ide>
<ide> List<Column> ourExpectedLock = ImmutableList.of(existingColumn);
<ide> Column clearedLock = lockColumnWithValue(GLOBAL_DDL_LOCK_CLEARED_VALUE);
<ide> + " was instead %s.", expectedLock, remoteLock));
<ide> }
<ide>
<del> private static boolean isValidColumnForLockId(Column column, long lockId) {
<del> return getLockIdFromColumn(column) == lockId;
<del> }
<del>
<ide> private static Column lockColumnWithValue(byte[] value) {
<ide> return new Column()
<ide> .setName(getGlobalDdlLockColumnName()) |
|
Java | mit | d09886adfa6eb7619ba7252e59e43ff80db88f89 | 0 | kits-ab/gakusei,kits-ab/gakusei,kits-ab/gakusei | package se.kits.gakusei.controller;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
import se.kits.gakusei.config.UserDetailsServiceImpl;
import se.kits.gakusei.user.model.User;
import se.kits.gakusei.user.repository.UserRepository;
@RestController
@Api(value = "UserController", description = "Operations for handling users")
public class UserController {
@Autowired
private UserRepository ur;
@Autowired
UserDetailsServiceImpl userDetailsService;
@Autowired
PasswordEncoder passwordEncoder;
private Logger logger = LoggerFactory.getLogger(this.getClass());
/* @ApiOperation(value="Creating a user", response = ResponseEntity.class)
@RequestMapping(
value = "/api/users",
method = RequestMethod.POST,
consumes = MediaType.APPLICATION_JSON_UTF8_VALUE,
produces = MediaType.APPLICATION_JSON_UTF8_VALUE
)
public ResponseEntity<User> createUser(
@RequestBody
User user
) {
final String userRole = "ROLE_USER";
user.setPassword(passwordEncoder.encode(user.getPassword()));
user.setRole(userRole);
return new ResponseEntity<User>(ur.save(user), HttpStatus.CREATED);
}*/
@ApiOperation(value = "Getting all the users", response = ResponseEntity.class)
@RequestMapping(
value = "/api/users",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_UTF8_VALUE
)
public ResponseEntity<Iterable<User>> getUsers() {
Iterable<User> users = ur.findAll();
return (users == null) ? new ResponseEntity<Iterable<User>>(
HttpStatus.FORBIDDEN
) : new ResponseEntity<Iterable<User>>(users, HttpStatus.OK);
}
@ApiOperation(value = "Getting the current username", response = ResponseEntity.class)
@RequestMapping(
value = "/username",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_UTF8_VALUE
)
@ResponseBody
public Map<String, Object> currentUserName(Authentication authentication) {
Map<String, Object> values = new HashMap<>();
String nameKey = "username";
String authenticatedKey = "loggedIn";
String authoritiesKey = "authorities";
values.put(nameKey, "");
values.put(authenticatedKey, Boolean.FALSE);
values.put(authoritiesKey, new ArrayList<>());
if (authentication != null && authentication.isAuthenticated()) {
values.put(nameKey, authentication.getName());
values.put(authenticatedKey, Boolean.TRUE);
values.put(authoritiesKey, authentication.getAuthorities());
}
return values;
}
@RequestMapping(value = "/api/changepassword", method = RequestMethod.POST)
public ResponseEntity<?> changePassword(@RequestBody String userData) {
JSONObject jsonData = new JSONObject();
JSONParser jsonParser = new JSONParser();
try {
jsonData = (JSONObject) jsonParser.parse(userData);
} catch (Exception e) {
e.printStackTrace();
}
User user = ur.findByUsername(jsonData.get("username").toString());
if (user == null) {
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
} else if (!passwordEncoder.matches(jsonData.get("oldPass").toString(), user.getPassword())) {
return new ResponseEntity<>(HttpStatus.NOT_ACCEPTABLE);
} else {
user.setPassword(passwordEncoder.encode(jsonData.get("newPass").toString()));
ur.save(user);
return new ResponseEntity<>(HttpStatus.OK);
}
}
@RequestMapping(value = "/api/checkNewUser", method = RequestMethod.POST)
public ResponseEntity<?> checkNewUser(@RequestBody String username) {
try {
User user = ur.findByUsername(username);
if (user.isNewUser()) {
user.setNewUser(false);
ur.save(user);
return new ResponseEntity<>(HttpStatus.OK);
} else {
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
} catch (NullPointerException n){
n.printStackTrace();
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}
| src/main/java/se/kits/gakusei/controller/UserController.java | package se.kits.gakusei.controller;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
import se.kits.gakusei.config.UserDetailsServiceImpl;
import se.kits.gakusei.user.model.User;
import se.kits.gakusei.user.repository.UserRepository;
@RestController
@Api(value = "UserController", description = "Operations for handling users")
public class UserController {
@Autowired
private UserRepository ur;
@Autowired
UserDetailsServiceImpl userDetailsService;
@Autowired
PasswordEncoder passwordEncoder;
private Logger logger = LoggerFactory.getLogger(this.getClass());
/* @ApiOperation(value="Creating a user", response = ResponseEntity.class)
@RequestMapping(
value = "/api/users",
method = RequestMethod.POST,
consumes = MediaType.APPLICATION_JSON_UTF8_VALUE,
produces = MediaType.APPLICATION_JSON_UTF8_VALUE
)
public ResponseEntity<User> createUser(
@RequestBody
User user
) {
final String userRole = "ROLE_USER";
user.setPassword(passwordEncoder.encode(user.getPassword()));
user.setRole(userRole);
return new ResponseEntity<User>(ur.save(user), HttpStatus.CREATED);
}*/
@ApiOperation(value = "Getting all the users", response = ResponseEntity.class)
@RequestMapping(
value = "/api/users",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_UTF8_VALUE
)
public ResponseEntity<Iterable<User>> getUsers() {
Iterable<User> users = ur.findAll();
return (users == null) ? new ResponseEntity<Iterable<User>>(
HttpStatus.FORBIDDEN
) : new ResponseEntity<Iterable<User>>(users, HttpStatus.OK);
}
@ApiOperation(value = "Getting the current username", response = ResponseEntity.class)
@RequestMapping(
value = "/username",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_UTF8_VALUE
)
@ResponseBody
public Map<String, Object> currentUserName(Authentication authentication) {
Map<String, Object> values = new HashMap<>();
String nameKey = "username";
String authenticatedKey = "loggedIn";
String authoritiesKey = "authorities";
values.put(nameKey, "");
values.put(authenticatedKey, Boolean.FALSE);
values.put(authoritiesKey, new ArrayList<>());
if (authentication != null && authentication.isAuthenticated()) {
values.put(nameKey, authentication.getName());
values.put(authenticatedKey, Boolean.TRUE);
values.put(authoritiesKey, authentication.getAuthorities());
}
return values;
}
@RequestMapping(value = "/api/changepassword", method = RequestMethod.POST)
public ResponseEntity<?> changePassword(@RequestBody String userData) {
JSONObject jsonData = new JSONObject();
JSONParser jsonParser = new JSONParser();
try {
jsonData = (JSONObject) jsonParser.parse(userData);
} catch (Exception e) {
e.printStackTrace();
}
User user = ur.findByUsername(jsonData.get("username").toString());
if (user == null) {
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
} else if (!passwordEncoder.matches(jsonData.get("oldPass").toString(), user.getPassword())) {
return new ResponseEntity<>(HttpStatus.NOT_ACCEPTABLE);
} else {
user.setPassword(passwordEncoder.encode(jsonData.get("newPass").toString()));
ur.save(user);
return new ResponseEntity<>(HttpStatus.OK);
}
}
@RequestMapping(value = "/api/checkNewUser", method = RequestMethod.POST)
public ResponseEntity<?> checkNewUser(@RequestBody String username) {
try {
User user = ur.findByUsername(username);
if (user.isNewUser()) {
user.setNewUser(false);
ur.save(user);
return new ResponseEntity<>(HttpStatus.OK);
} else {
return new ResponseEntity<>(HttpStatus.NOT_ACCEPTABLE);
}
} catch (NullPointerException n){
n.printStackTrace();
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}
| Update UserController.java | src/main/java/se/kits/gakusei/controller/UserController.java | Update UserController.java | <ide><path>rc/main/java/se/kits/gakusei/controller/UserController.java
<ide> ur.save(user);
<ide> return new ResponseEntity<>(HttpStatus.OK);
<ide> } else {
<del> return new ResponseEntity<>(HttpStatus.NOT_ACCEPTABLE);
<add> return new ResponseEntity<>(HttpStatus.NO_CONTENT);
<ide> }
<ide> } catch (NullPointerException n){
<ide> n.printStackTrace(); |
|
Java | apache-2.0 | e5eb1e14a2167377550ea86d05f06fd8252fd0bb | 0 | recruit-tech/redpen,redpen-cc/redpen,recruit-tech/redpen,redpen-cc/redpen,redpen-cc/redpen,recruit-tech/redpen,redpen-cc/redpen,recruit-tech/redpen,redpen-cc/redpen | /**
* redpen: a text inspection tool
* Copyright (c) 2014-2015 Recruit Technologies Co., Ltd. and contributors
* (see CONTRIBUTORS.md)
* <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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 cc.redpen.validator.document;
import cc.redpen.model.*;
import cc.redpen.tokenizer.TokenElement;
import cc.redpen.validator.Validator;
import java.util.*;
import static java.util.Collections.singletonList;
public class JapaneseExpressionVariationValidator extends Validator {
private Map<String, List<TokenElement>> words = new HashMap<>();
private Map<Document, List<Sentence>> sentenceMap = new HashMap<>();
@Override
public void validate(Document document) {
if (!sentenceMap.containsKey(document)) {
throw new IllegalStateException("Document " + document.getFileName() + " does not have any sentence");
}
for (Sentence sentence : sentenceMap.get(document)) {
for (TokenElement token : sentence.getTokens()) {
String reading = token.getTags().get(7);
if (this.words.containsKey(reading)) {
List<TokenElement> tokens = this.words.get(reading);
for (TokenElement candidate : tokens) {
if (candidate != token && !token.getSurface().equals(candidate.getSurface())) {
addLocalizedErrorFromToken(sentence, token);
}
}
}
}
}
}
@Override
public void preValidate(Document document) {
sentenceMap.put(document, extractSentences(document));
List<Sentence> sentences = sentenceMap.get(document);
for (Sentence sentence : sentences) {
for (TokenElement token : sentence.getTokens()) {
String reading = token.getTags().get(7);
if (!this.words.containsKey(reading)) {
this.words.put(reading, new LinkedList<TokenElement>());
}
this.words.get(reading).add(token);
}
}
}
private List<Sentence> extractSentences(Document document) {
List<Sentence> sentences = new ArrayList<>();
for (Section section : document) {
for (Paragraph paragraph : section.getParagraphs()) {
sentences.addAll(paragraph.getSentences());
}
sentences.addAll(section.getHeaderContents());
for (ListBlock listBlock : section.getListBlocks()) {
for (ListElement listElement : listBlock.getListElements()) {
sentences.addAll(listElement.getSentences());
}
}
}
return sentences;
}
@Override
public List<String> getSupportedLanguages() {
return singletonList(Locale.JAPANESE.getLanguage());
}
}
| redpen-core/src/main/java/cc/redpen/validator/document/JapaneseExpressionVariationValidator.java | /**
* redpen: a text inspection tool
* Copyright (c) 2014-2015 Recruit Technologies Co., Ltd. and contributors
* (see CONTRIBUTORS.md)
* <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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 cc.redpen.validator.document;
import cc.redpen.model.Sentence;
import cc.redpen.tokenizer.TokenElement;
import cc.redpen.validator.Validator;
import java.util.*;
import static java.util.Collections.singletonList;
public class JapaneseExpressionVariationValidator extends Validator {
private Map<String, List<TokenElement>> words = new HashMap<>();
@Override
public void validate(Sentence sentence) {
for (TokenElement token : sentence.getTokens()) {
String reading = token.getTags().get(7);
if (this.words.containsKey(reading)) {
List<TokenElement> tokens = this.words.get(reading);
for (TokenElement candidate : tokens) {
if (candidate != token && !token.getSurface().equals(candidate.getSurface())) {
addLocalizedErrorFromToken(sentence, token);
}
}
}
}
}
@Override
public void preValidate(Sentence sentence) {
for (TokenElement token : sentence.getTokens()) {
String reading = token.getTags().get(7);
if (!this.words.containsKey(reading)) {
this.words.put(reading, new LinkedList<TokenElement>());
}
this.words.get(reading).add(token);
}
}
@Override
public List<String> getSupportedLanguages() {
return singletonList(Locale.JAPANESE.getLanguage());
}
}
| Make parameter of validate Document object
| redpen-core/src/main/java/cc/redpen/validator/document/JapaneseExpressionVariationValidator.java | Make parameter of validate Document object | <ide><path>edpen-core/src/main/java/cc/redpen/validator/document/JapaneseExpressionVariationValidator.java
<ide> */
<ide> package cc.redpen.validator.document;
<ide>
<del>import cc.redpen.model.Sentence;
<add>import cc.redpen.model.*;
<ide> import cc.redpen.tokenizer.TokenElement;
<ide> import cc.redpen.validator.Validator;
<ide>
<ide>
<ide> public class JapaneseExpressionVariationValidator extends Validator {
<ide> private Map<String, List<TokenElement>> words = new HashMap<>();
<add> private Map<Document, List<Sentence>> sentenceMap = new HashMap<>();
<ide>
<ide> @Override
<del> public void validate(Sentence sentence) {
<del> for (TokenElement token : sentence.getTokens()) {
<del> String reading = token.getTags().get(7);
<del> if (this.words.containsKey(reading)) {
<del> List<TokenElement> tokens = this.words.get(reading);
<del> for (TokenElement candidate : tokens) {
<del> if (candidate != token && !token.getSurface().equals(candidate.getSurface())) {
<del> addLocalizedErrorFromToken(sentence, token);
<add> public void validate(Document document) {
<add> if (!sentenceMap.containsKey(document)) {
<add> throw new IllegalStateException("Document " + document.getFileName() + " does not have any sentence");
<add> }
<add>
<add> for (Sentence sentence : sentenceMap.get(document)) {
<add> for (TokenElement token : sentence.getTokens()) {
<add> String reading = token.getTags().get(7);
<add> if (this.words.containsKey(reading)) {
<add> List<TokenElement> tokens = this.words.get(reading);
<add> for (TokenElement candidate : tokens) {
<add> if (candidate != token && !token.getSurface().equals(candidate.getSurface())) {
<add> addLocalizedErrorFromToken(sentence, token);
<add> }
<ide> }
<ide> }
<ide> }
<ide> }
<ide> }
<ide>
<add>
<ide> @Override
<del> public void preValidate(Sentence sentence) {
<del> for (TokenElement token : sentence.getTokens()) {
<del> String reading = token.getTags().get(7);
<del> if (!this.words.containsKey(reading)) {
<del> this.words.put(reading, new LinkedList<TokenElement>());
<add> public void preValidate(Document document) {
<add> sentenceMap.put(document, extractSentences(document));
<add> List<Sentence> sentences = sentenceMap.get(document);
<add> for (Sentence sentence : sentences) {
<add> for (TokenElement token : sentence.getTokens()) {
<add> String reading = token.getTags().get(7);
<add> if (!this.words.containsKey(reading)) {
<add> this.words.put(reading, new LinkedList<TokenElement>());
<add> }
<add> this.words.get(reading).add(token);
<ide> }
<del> this.words.get(reading).add(token);
<add> }
<add> }
<ide>
<add> private List<Sentence> extractSentences(Document document) {
<add> List<Sentence> sentences = new ArrayList<>();
<add> for (Section section : document) {
<add> for (Paragraph paragraph : section.getParagraphs()) {
<add> sentences.addAll(paragraph.getSentences());
<add> }
<add> sentences.addAll(section.getHeaderContents());
<add> for (ListBlock listBlock : section.getListBlocks()) {
<add> for (ListElement listElement : listBlock.getListElements()) {
<add> sentences.addAll(listElement.getSentences());
<add> }
<add> }
<ide> }
<add> return sentences;
<ide> }
<ide>
<ide> @Override |
|
Java | apache-2.0 | error: pathspec 'src/com/effectivejava/classinterface/ForwardingSet.java' did not match any file(s) known to git
| fbfde2be5408503285e45f877f53eaeaa65fb489 | 1 | haokaibo/AlgorithmHelper | /**
* Implementation of prefer to composite to inherence.
*/
package com.effectivejava.classinterface;
import java.util.Collection;
import java.util.Iterator;
import java.util.Set;
/**
* @author Kaibo
*
*/
// Reusable forwarding class
public class ForwardingSet<E> implements Set<E> {
private final Set<E> s;
public ForwardingSet(Set<E> s) {
this.s = s;
}
public void clear() {
s.clear();
}
public boolean contains(Object o) {
return s.contains(o);
}
public boolean isEmpty() {
return s.isEmpty();
}
public int size() {
return s.size();
}
public Iterator<E> iterator() {
return s.iterator();
}
public boolean add(E e) {
return s.add(e);
}
public boolean remove(Object o) {
return s.remove(o);
}
public boolean containsAll(Collection<?> c) {
return s.containsAll(c);
}
public boolean addAll(Collection<? extends E> c) {
return s.addAll(c);
}
public boolean removeAll(Collection<?> c) {
return s.removeAll(c);
}
public boolean retainAll(Collection<?> c) {
return s.retainAll(c);
}
public Object[] toArray() {
return s.toArray();
}
public <T> T[] toArray(T[] a) {
return s.toArray(a);
}
@Override
public boolean equals(Object o) {
return s.equals(o);
}
@Override
public int hashCode() {
return s.hashCode();
}
@Override
public String toString() {
return s.toString();
}
} | src/com/effectivejava/classinterface/ForwardingSet.java | Added Example code for perfering composite to inherence. | src/com/effectivejava/classinterface/ForwardingSet.java | Added Example code for perfering composite to inherence. | <ide><path>rc/com/effectivejava/classinterface/ForwardingSet.java
<add>/**
<add> * Implementation of prefer to composite to inherence.
<add> */
<add>package com.effectivejava.classinterface;
<add>
<add>import java.util.Collection;
<add>import java.util.Iterator;
<add>import java.util.Set;
<add>
<add>/**
<add> * @author Kaibo
<add> *
<add> */
<add>// Reusable forwarding class
<add>public class ForwardingSet<E> implements Set<E> {
<add> private final Set<E> s;
<add>
<add> public ForwardingSet(Set<E> s) {
<add> this.s = s;
<add> }
<add>
<add> public void clear() {
<add> s.clear();
<add> }
<add>
<add> public boolean contains(Object o) {
<add> return s.contains(o);
<add> }
<add>
<add> public boolean isEmpty() {
<add> return s.isEmpty();
<add> }
<add>
<add> public int size() {
<add> return s.size();
<add> }
<add>
<add> public Iterator<E> iterator() {
<add> return s.iterator();
<add> }
<add>
<add> public boolean add(E e) {
<add> return s.add(e);
<add> }
<add>
<add> public boolean remove(Object o) {
<add> return s.remove(o);
<add> }
<add>
<add> public boolean containsAll(Collection<?> c) {
<add> return s.containsAll(c);
<add> }
<add>
<add> public boolean addAll(Collection<? extends E> c) {
<add> return s.addAll(c);
<add> }
<add>
<add> public boolean removeAll(Collection<?> c) {
<add> return s.removeAll(c);
<add> }
<add>
<add> public boolean retainAll(Collection<?> c) {
<add> return s.retainAll(c);
<add> }
<add>
<add> public Object[] toArray() {
<add> return s.toArray();
<add> }
<add>
<add> public <T> T[] toArray(T[] a) {
<add> return s.toArray(a);
<add> }
<add>
<add> @Override
<add> public boolean equals(Object o) {
<add> return s.equals(o);
<add> }
<add>
<add> @Override
<add> public int hashCode() {
<add> return s.hashCode();
<add> }
<add>
<add> @Override
<add> public String toString() {
<add> return s.toString();
<add> }
<add>} |
|
JavaScript | mit | 25c342c5c5055cd105aaff92a5d9df0727cd3589 | 0 | nickgermyn/node-dogte-chat | /**
* Dota game organisation handlers
*/
'use strict';
var Promise = require('bluebird');
var Game = require('../models/game');
var winston = require('winston');
const noGame = 'No game scheduled for today';
module.exports = function(bot) {
// *****************************
// Game creation / reschedule
// *****************************
bot.onText(/^\/dog?t[ea]s?(?:@\w*)?\b\s*(?=(?:.*\b(\d{2})[:.;-]?(\d{2})\b)?)/i, function(msg, match) {
winston.info('handler.game - game creation request received');
var chatId = msg.chat.id;
var details = match[2];
var userName = msg.from.username;
var displayName = msg.from.first_name;
if(msg.from.last_name) {
displayName += ' ' + msg.from.last_name;
}
if (!match[1] && !match[2]) {
// no valid time found, let the user know
return bot.sendMessage(chatId, 'Unrecognised command. Usage example: `/dota at 1730`');
}
var gameTime = new Date();
if (match[1]) gameTime.setHours(match[1]);
if (match[2]) gameTime.setHours(match[2]);
gameTime.setSeconds(0);
// Find game
return Game.findOne({complete: false}).exec()
.then(game => {
if(game) {
// Update the existing game
winston.info(' Game already exists. Updating');
game.gameTime = gameTime;
game.notified = false;
game.shotgun(displayName);
winston.info(' saving...');
return game.save()
.then(saved => bot.sendMessage(chatId, 'Dogte time modified'))
.then(sent => game.sendTimeUpdate(bot, chatId));
} else {
// Create a new game
game = new Game({
gameTime: gameTime,
chatId: chatId,
complete: false,
shotguns: [displayName]
});
return game.save()
.then(sent => game.sendTimeUpdate(bot, chatId));
}
}).catch(err => handleError(err, chatId));
});
// *****************************
// Delete game
// *****************************
bot.onText(/^\/delete_dog?t[ae]s?(?:@\w*)?/i, function(msg) {
winston.info('handler.game - game deletion request received');
var chatId = msg.chat.id;
// Find game
var a = Game.findOne({complete: false}).exec();
var b = a.then(game => {
if(game) {
var messageText = 'Are you sure you wish to delete the game at '+game.gameTime+' (yes/no)?';
return bot.sendMessage(chatId, messageText, {
reply_markup: {
force_reply: true
}
});
}
return null;
});
return Promise.join(a, b, (game, sent) => {
if(!sent) {
return bot.sendMessage(chatId, noGame);
}
winston.info(' waiting for message reply');
return bot.onReplyToMessage(chatId, sent.message_id, reply => {
winston.info(' reply received: '+reply.text);
if(reply.text == 'yes') {
return Game.remove({ _id: game._id }).exec().then(() => {
bot.sendMessage(chatId, 'Dota event deleted');
winston.info(' dota event deleted!');
});
}
});
}).catch(err => handleError(err, chatId));
});
// *****************************
// shotgun
// *****************************
bot.onText(/^\/shotgun(?:@\w*)?/i, function(msg) {
winston.info('handler.game - shotgun received');
var chatId = msg.chat.id;
var userName = msg.from.username;
var displayName = msg.from.first_name;
if(msg.from.last_name) {
displayName += ' ' + msg.from.last_name;
}
// Find game
return Game.findOne({complete: false}).exec()
.then(game => {
if(!game) { return bot.sendMessage(chatId, noGame); }
game.shotgun(displayName);
return game.save()
.then(saved => game.sendShotgunUpdate(bot, chatId));
}).catch(err => handleError(err, chatId));
});
// *****************************
// unshotgun
// *****************************
bot.onText(/^\/unshotgun(?:@\w*)?/i, function(msg) {
winston.info('handler.game - unshotgun received');
var chatId = msg.chat.id;
var userName = msg.from.username;
var displayName = msg.from.first_name;
if(msg.from.last_name) {
displayName += ' ' + msg.from.last_name;
}
// Find game
return Game.findOne({complete: false}).exec()
.then(game => {
if(!game) { return bot.sendMessage(chatId, noGame); }
game.unshotgun(displayName);
return game.save()
.then(saved => bot.sendMessage(chatId, displayName + ', your shotgun has been cancelled'));
}).catch(err => handleError(err, chatId));
});
// *****************************
// rdy
// *****************************
bot.onText(/^\/re?a?dy(?:@\w*)?/i, function(msg) {
winston.info('handler.game - rdy received');
var chatId = msg.chat.id;
var userName = msg.from.username;
var displayName = msg.from.first_name;
if(msg.from.last_name) {
displayName += ' ' + msg.from.last_name;
}
// Find game
return Game.findOne({complete: false}).exec()
.then(game => {
if(!game) { return bot.sendMessage(chatId, noGame); }
var response = game.readyup(displayName);
return game.save()
.then(saved => game.sendStackUpdate(bot, chatId));
}).catch(err => handleError(err, chatId));
});
// *****************************
// undry
// *****************************
bot.onText(/^\/unre?a?dy(?:@\w*)?/i, function(msg) {
winston.info('handler.game - unrdy received');
var chatId = msg.chat.id;
var userName = msg.from.username;
var displayName = msg.from.first_name;
if(msg.from.last_name) {
displayName += ' ' + msg.from.last_name;
}
// Find game
return Game.findOne({complete: false}).exec()
.then(game => {
if(!game) { return bot.sendMessage(chatId, noGame); }
game.unreadyup(displayName);
return game.save()
.then(saved => bot.sendMessage(chatId, displayName + ', your rdy has been cancelled'));
}).catch(err => handleError(err, chatId));
});
// *****************************
// Error handler
function handleError(err, chatId, msg) {
winston.error('An error occurred: ',err);
msg = msg || 'Oh noes! An error occurred';
return bot.sendMessage(chatId, msg+': \n'+err);
}
}
| handlers/handler.game.js | /**
* Dota game organisation handlers
*/
'use strict';
var Promise = require('bluebird');
var Game = require('../models/game');
var winston = require('winston');
const noGame = 'No game scheduled for today';
module.exports = function(bot) {
// *****************************
// Game creation / reschedule
// *****************************
bot.onText(/^\/dog?t[ea]s?(?:@\w*)?\b\s*(.+)/i, function(msg, match) {
winston.info('handler.game - game creation request received');
var chatId = msg.chat.id;
var details = match[2];
var userName = msg.from.username;
var displayName = msg.from.first_name;
if(msg.from.last_name) {
displayName += ' ' + msg.from.last_name;
}
// Parse dates and users
var time = getTime(details);
var gameTime = new Date();
if(time) {
gameTime.setHours(time.substring(0,2));
gameTime.setMinutes(time.substring(2,4));
gameTime.setSeconds(0);
} else {
// no valid time found, let the user know
return bot.sendMessage(chatId, 'Unrecognised command. Usage example: `/dota at 1730`');
}
// Find game
return Game.findOne({complete: false}).exec()
.then(game => {
if(game) {
// Update the existing game
winston.info(' Game already exists. Updating');
game.gameTime = gameTime;
game.notified = false;
game.shotgun(displayName);
winston.info(' saving...');
return game.save()
.then(saved => bot.sendMessage(chatId, 'Dogte time modified'))
.then(sent => game.sendTimeUpdate(bot, chatId));
} else {
// Create a new game
game = new Game({
gameTime: gameTime,
chatId: chatId,
complete: false,
shotguns: [displayName]
});
return game.save()
.then(sent => game.sendTimeUpdate(bot, chatId));
}
}).catch(err => handleError(err, chatId));
});
// *****************************
// Delete game
// *****************************
bot.onText(/^\/delete_dog?t[ae]s?(?:@\w*)?/i, function(msg) {
winston.info('handler.game - game deletion request received');
var chatId = msg.chat.id;
// Find game
var a = Game.findOne({complete: false}).exec();
var b = a.then(game => {
if(game) {
var messageText = 'Are you sure you wish to delete the game at '+game.gameTime+' (yes/no)?';
return bot.sendMessage(chatId, messageText, {
reply_markup: {
force_reply: true
}
});
}
return null;
});
return Promise.join(a, b, (game, sent) => {
if(!sent) {
return bot.sendMessage(chatId, noGame);
}
winston.info(' waiting for message reply');
return bot.onReplyToMessage(chatId, sent.message_id, reply => {
winston.info(' reply received: '+reply.text);
if(reply.text == 'yes') {
return Game.remove({ _id: game._id }).exec().then(() => {
bot.sendMessage(chatId, 'Dota event deleted');
winston.info(' dota event deleted!');
});
}
});
}).catch(err => handleError(err, chatId));
});
// *****************************
// shotgun
// *****************************
bot.onText(/^\/shotgun(?:@\w*)?/i, function(msg) {
winston.info('handler.game - shotgun received');
var chatId = msg.chat.id;
var userName = msg.from.username;
var displayName = msg.from.first_name;
if(msg.from.last_name) {
displayName += ' ' + msg.from.last_name;
}
// Find game
return Game.findOne({complete: false}).exec()
.then(game => {
if(!game) { return bot.sendMessage(chatId, noGame); }
game.shotgun(displayName);
return game.save()
.then(saved => game.sendShotgunUpdate(bot, chatId));
}).catch(err => handleError(err, chatId));
});
// *****************************
// unshotgun
// *****************************
bot.onText(/^\/unshotgun(?:@\w*)?/i, function(msg) {
winston.info('handler.game - unshotgun received');
var chatId = msg.chat.id;
var userName = msg.from.username;
var displayName = msg.from.first_name;
if(msg.from.last_name) {
displayName += ' ' + msg.from.last_name;
}
// Find game
return Game.findOne({complete: false}).exec()
.then(game => {
if(!game) { return bot.sendMessage(chatId, noGame); }
game.unshotgun(displayName);
return game.save()
.then(saved => bot.sendMessage(chatId, displayName + ', your shotgun has been cancelled'));
}).catch(err => handleError(err, chatId));
});
// *****************************
// rdy
// *****************************
bot.onText(/^\/re?a?dy(?:@\w*)?/i, function(msg) {
winston.info('handler.game - rdy received');
var chatId = msg.chat.id;
var userName = msg.from.username;
var displayName = msg.from.first_name;
if(msg.from.last_name) {
displayName += ' ' + msg.from.last_name;
}
// Find game
return Game.findOne({complete: false}).exec()
.then(game => {
if(!game) { return bot.sendMessage(chatId, noGame); }
var response = game.readyup(displayName);
return game.save()
.then(saved => game.sendStackUpdate(bot, chatId));
}).catch(err => handleError(err, chatId));
});
// *****************************
// undry
// *****************************
bot.onText(/^\/unre?a?dy(?:@\w*)?/i, function(msg) {
winston.info('handler.game - unrdy received');
var chatId = msg.chat.id;
var userName = msg.from.username;
var displayName = msg.from.first_name;
if(msg.from.last_name) {
displayName += ' ' + msg.from.last_name;
}
// Find game
return Game.findOne({complete: false}).exec()
.then(game => {
if(!game) { return bot.sendMessage(chatId, noGame); }
game.unreadyup(displayName);
return game.save()
.then(saved => bot.sendMessage(chatId, displayName + ', your rdy has been cancelled'));
}).catch(err => handleError(err, chatId));
});
// *****************************
// Error handler
function handleError(err, chatId, msg) {
winston.error('An error occurred: ',err);
msg = msg || 'Oh noes! An error occurred';
return bot.sendMessage(chatId, msg+': \n'+err);
}
// *****************************
// Time parser
function getTime(msg) {
var replaced = msg.replace(/:|\.|;|-/gi, '');
var match = /(?:at)\s*(\d{4})/.exec(replaced);
if(match) {
return match[1];
} else {
return null;
}
}
}
| dota-command regex and cleanup
| handlers/handler.game.js | dota-command regex and cleanup | <ide><path>andlers/handler.game.js
<ide> // *****************************
<ide> // Game creation / reschedule
<ide> // *****************************
<del> bot.onText(/^\/dog?t[ea]s?(?:@\w*)?\b\s*(.+)/i, function(msg, match) {
<add> bot.onText(/^\/dog?t[ea]s?(?:@\w*)?\b\s*(?=(?:.*\b(\d{2})[:.;-]?(\d{2})\b)?)/i, function(msg, match) {
<ide> winston.info('handler.game - game creation request received');
<ide> var chatId = msg.chat.id;
<ide> var details = match[2];
<ide> displayName += ' ' + msg.from.last_name;
<ide> }
<ide>
<del> // Parse dates and users
<del> var time = getTime(details);
<del> var gameTime = new Date();
<del> if(time) {
<del> gameTime.setHours(time.substring(0,2));
<del> gameTime.setMinutes(time.substring(2,4));
<del> gameTime.setSeconds(0);
<del> } else {
<add> if (!match[1] && !match[2]) {
<ide> // no valid time found, let the user know
<ide> return bot.sendMessage(chatId, 'Unrecognised command. Usage example: `/dota at 1730`');
<ide> }
<add>
<add> var gameTime = new Date();
<add> if (match[1]) gameTime.setHours(match[1]);
<add> if (match[2]) gameTime.setHours(match[2]);
<add> gameTime.setSeconds(0);
<ide>
<ide> // Find game
<ide> return Game.findOne({complete: false}).exec()
<ide> msg = msg || 'Oh noes! An error occurred';
<ide> return bot.sendMessage(chatId, msg+': \n'+err);
<ide> }
<del>
<del> // *****************************
<del> // Time parser
<del> function getTime(msg) {
<del> var replaced = msg.replace(/:|\.|;|-/gi, '');
<del> var match = /(?:at)\s*(\d{4})/.exec(replaced);
<del> if(match) {
<del> return match[1];
<del> } else {
<del> return null;
<del> }
<del> }
<ide> } |
|
Java | bsd-2-clause | 33740db15907b41caf86b468b4b8965532c98228 | 0 | bioinform/varsim,bioinform/varsim,bioinform/varsim,bioinform/varsim | package com.bina.varsim.util;
//--- Java imports ---
import com.bina.varsim.types.ChrString;
import com.bina.varsim.types.FlexSeq;
import com.bina.varsim.types.VCFInfo;
import com.bina.varsim.types.variant.Variant;
import org.apache.log4j.Logger;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.rmi.UnexpectedException;
import java.util.Random;
import java.util.StringTokenizer;
public class VCFparser extends GzFileParser<Variant> {
public static final String DEFAULT_FILTER = "."; //default value for many columns
private final static Logger log = Logger.getLogger(VCFparser.class.getName());
private Random random = null;
private int sampleIndex = -1;
private String sampleId = null;
private boolean isPassFilterRequired = false;
private boolean chromLineSeen = false;
public VCFparser() {
sampleIndex = 10; // the first sample
}
/**
* Reads a VCF file line by line
*
* @param fileName VCF file, doesn't have to be sorted or indexed
* @param id ID of individual, essentially selects a column, null to use first ID column
* @param pass If true, only output pass lines
*/
public VCFparser(String fileName, String id, boolean pass, Random rand) {
random = rand;
try {
bufferedReader = new BufferedReader(new InputStreamReader(decompressStream(fileName)));
readLine();
} catch (Exception ex) {
log.error("Can't open file " + fileName);
log.error(ex.toString());
}
sampleId = id;
isPassFilterRequired = pass;
if (sampleId == null) {
sampleIndex = 10; // the first sample
}
}
/**
* Reads a VCF file line by line
*
* @param fileName VCF file, doesn't have to be sorted or indexed
* @param id ID of individual, essentially selects a column, null to use first ID column
* @param pass If true, only output pass lines
*/
public VCFparser(String fileName, String id, boolean pass) {
this(fileName, id, pass, null);
}
//TODO: remove unused constructor
/**
* Reads a VCF file line by line, if there are multiple individuals, takes the first one
*
* @param fileName VCF file, doesn't have to be sorted or indexed
* @param pass If true, only output pass lines
*/
public VCFparser(String fileName, boolean pass, Random rand) {
this(fileName, null, pass, rand);
}
//TODO: remove unused constructor
/**
* Reads a VCF file line by line, if there are multiple individuals, takes the first one
*
* @param fileName VCF file, doesn't have to be sorted or indexed
* @param pass If true, only output pass lines
*/
public VCFparser(String fileName, boolean pass) {
this(fileName, null, pass, null);
}
/**
* finds where "GT" or similar is in the VCF string so that the genotype can be read
*
* @param record The column in VCF that contains GT, CN, etc..
* @param key The key to be found "GT" or "CN" or other
* @return the index of the key
*/
private int getFormatKeyIndex(final String record, final String key) {
StringTokenizer words = new StringTokenizer(record, ":");
int ret = 0;
while (words.hasMoreTokens()) {
if (words.nextToken().equals(key))
return ret;
else
ret++;
}
return -1;
}
/**
* Takes genotype string and splits it into alleles, supports a maximum of two
*
* @param geno genotype string corresponding to the GT tag (field index 9)
* @param vals Return the genotypes read here [paternal,maternal]
* @param chr chromosome we are dealing with, some are haploid, need to assign parent
* @return true if the variant is phased
*/
boolean isPhased(String geno, byte[] vals, ChrString chr) {
boolean isPhased = false;
geno = geno.trim();
boolean strangePhase = false;
if (geno.matches("^[0-9]+$")) {
// phase is only a single number, for haploid chromosomes
byte val = (byte) Integer.parseInt(geno);
if (chr.isX()) {
vals[1] = val; // maternal
isPhased = true;
} else if (chr.isY()) {
vals[0] = val; // paternal
isPhased = true;
} else if (chr.isMT()) {
vals[1] = val;
isPhased = true;
} else {
vals[0] = vals[1] = val;
}
} else if (geno.length() >= 3) {
// this is the case where phase looks like "1|0" or "10|4"
String[] ll = geno.split("[\\|/]");
int c1 = -1;
int c2 = -1;
char phasing = '/';
if (ll.length == 2) {
try {
c1 = Integer.parseInt(ll[0]);
c2 = Integer.parseInt(ll[1]);
phasing = geno.charAt(ll[0].length());
} catch (NumberFormatException e) {
strangePhase = true;
}
} else {
strangePhase = true;
}
if (c1 >= 0 && c2 >= 0) {
vals[0] = (byte) c1;
vals[1] = (byte) c2;
if (phasing == '|') {
isPhased = true;
}
} else {
strangePhase = true;
}
} else {
strangePhase = true;
}
if (strangePhase) {
// System.err.println("Unrecognized phasing '" + phase + "'.");
vals[0] = -1;
vals[1] = -1;
isPhased = false;
}
return isPhased;
}
/**
* takes a line from a VCF file, parse it,
* return a Variant object
*
* right now the meta-info lines (beginning with ##) are
* not tied with data line parsing. This will be corrected
* in the future (perhaps with help of HTSJDK).
* @param line
* @return
*/
public Variant processLine(String line) throws UnexpectedException {
// try to determine the column we should read for the genotype
StringTokenizer toks = new StringTokenizer(line);
if (line.startsWith("#")) {
if (sampleId != null && line.startsWith("#CHROM")) {
chromLineSeen = true;
int index = 0;
while (toks.hasMoreTokens()) {
index++;
String tok = toks.nextToken();
if (tok.equals(sampleId))
sampleIndex = index;
}
} else if (sampleId == null) {
sampleIndex = 10; // the first sample
}
return null;
}
// If we cannot determine, then use the first one
if (sampleIndex < 0 && !chromLineSeen) {
sampleIndex = 10;
} else if (sampleIndex < 0) {
sampleIndex = 10;
log.warn("Warning!!! ID (" + sampleId + ") does not exist... ");
}
int index = 0, genotypeIndex = -1, copyNumberIndex = -1;
int pos = -1;
ChrString chr = null;
String REF = "", FILTER = "", ALT = "", variantId = "";
String phase = ".", copyNumber = "0/0", infoString = "", FORMAT;
String[] sampleInfo;
while (toks.hasMoreTokens()) {
index++;
if (index == 1) { // Parsing chromosome
chr = new ChrString(toks.nextToken());
} else if (index == 2) // Parsing position
pos = Integer.parseInt(toks.nextToken());
else if (index == 3) // Parsing position
variantId = toks.nextToken();
else if (index == 4) // Parsing reference allele
REF = toks.nextToken();
else if (index == 5) // Parsing alternative allele
ALT = toks.nextToken();
else if (index == 7) // FILTER field
FILTER = toks.nextToken();
else if (index == 8) // INFO field
infoString = toks.nextToken();
else if (index == 9) { // Output format
FORMAT = toks.nextToken();
genotypeIndex = getFormatKeyIndex(FORMAT, "GT");
copyNumberIndex = getFormatKeyIndex(FORMAT, "CN");
} else if (index == sampleIndex) { // phased or unphased genotype
sampleInfo = (toks.nextToken()).split(":");
if (genotypeIndex >= 0) {
phase = sampleInfo[genotypeIndex];
}
if (copyNumberIndex >= 0) {
copyNumber = sampleInfo[copyNumberIndex];
}
break;
} else {
toks.nextToken();
}
}
// unknown chromosome
// TODO: throw an exception for unknown chromosome name
if (chr == null) {
log.warn("Bad chromosome name: " + line);
return null;
}
if (isPassFilterRequired && !(FILTER.contains("PASS") || FILTER.equals(DEFAULT_FILTER))) {
//log.warn("not pass line" + line);
return null; // Filtered out
}
// parse the phased or unphased genotype
byte[] genotypeArray = new byte[2]; // paternal-maternal
boolean isGenotypePhased = isPhased(phase, genotypeArray, chr);
if (genotypeIndex >= 0 && genotypeArray[0] == 0 && genotypeArray[1] == 0) {
//return null; // reference alleles... ignore them for now....
}
// determine copy-number
// TODO need to be able to deal with unphased copy-numbers?
byte[] copyNumberArray = new byte[2]; // paternal-maternal
boolean isCopyNumberPhased;
if (copyNumberIndex >= 0) {
isCopyNumberPhased = isPhased(copyNumber, copyNumberArray, chr);
if (isCopyNumberPhased != isGenotypePhased) {
// TODO maybe don't throw error, this is not standard format
// anyways
log.error("Inconsistent copy number:");
log.error(line);
return null;
}
}
// Upper casing
REF = REF.toUpperCase();
ALT = ALT.toUpperCase();
String deletedReference = "";
FlexSeq alts[];
VCFInfo info = new VCFInfo(infoString);
/*if symbolic alleles are present,
make sure # of alleles equal # of
SV lengths. For non-symbolic alleles, SV lengths
are not really used or checked.
*/
/*!!!!!!!!!!
CAUTION: we assume symbolic alleles are not mixed
with non-symbolic alleles.
*/
if (ALT.indexOf('<') != -1) {
String[] alternativeAlleles = ALT.split(",");
int[] svlen = (int[]) info.getValue("SVLEN");
if (alternativeAlleles.length != svlen.length) {
throw new IllegalArgumentException("ERROR: number of symbolic alleles is unequal to number of SV lengths.\n" + line);
}
for (int i = 0; i < alternativeAlleles.length; i++) {
if (!alternativeAlleles[i].startsWith("<")) {
throw new IllegalArgumentException("ERROR: symbolic alleles are mixed with non-symbolic alleles.\n" + line);
}
}
}
if (ALT.startsWith("<INV>")) {
// inversion SV
int[] end = (int[]) info.getValue("END");
int[] svlen = (int[]) info.getValue("SVLEN");
deletedReference = REF;
byte[] refs = new byte[0];
pos++;
if (svlen.length > 0) {
alts = new FlexSeq[svlen.length];
for (int i = 0; i < svlen.length; i++) {
int alternativeAlleleLength = Math.max(Math.abs(svlen[i]), 1);
alts[i] = new FlexSeq(FlexSeq.Type.INV, alternativeAlleleLength);
}
// TODO this assumes only one alt
/*return new Variant(chr, pos, Math.abs(svlen[0]), refs, alts,
genotypeArray, isGenotypePhased, variantId, FILTER, deletedReference, random);
*/
return new Variant.Builder().chr(chr).pos(pos).referenceAlleleLength(Math.abs(svlen[0])).
ref(refs).alts(alts).phase(genotypeArray).isPhased(isGenotypePhased).
varId(variantId).filter(FILTER).refDeleted(deletedReference).
randomNumberGenerator(random).build();
//TODO: this assumes only one alt, might not be true
} else if (end[0] > 0) {
int alternativeAlleleLength = Math.max(Math.abs(end[0] - pos + 1), 1);
alts = new FlexSeq[1];
alts[0] = new FlexSeq(FlexSeq.Type.INV, alternativeAlleleLength);
/*return new Variant(chr, pos, alternativeAlleleLength, refs, alts,
genotypeArray, isGenotypePhased, variantId, FILTER, deletedReference, random);
*/
return new Variant.Builder().chr(chr).pos(pos).referenceAlleleLength(alternativeAlleleLength).
ref(refs).alts(alts).phase(genotypeArray).isPhased(isGenotypePhased).
varId(variantId).filter(FILTER).refDeleted(deletedReference).
randomNumberGenerator(random).build();
} else {
log.error("No length information for INV:");
log.error(line);
log.error("skipping...");
return null;
}
} else if (ALT.startsWith("<DUP>") || ALT.startsWith("<DUP:TANDEM>")) {
// duplication or tandem duplication SV
int[] svlens = (int[]) info.getValue("SVLEN");
// may need to check inconsistency
int[] ends = (int[]) info.getValue("END");
// btw length and end location
deletedReference = REF;
byte[] refs = new byte[0];
pos++;
if (svlens.length > 0) {
alts = new FlexSeq[svlens.length];
for (int i = 0; i < svlens.length; i++) {
// TODO this is temporary, how to encode copy number?
int currentCopyNumber = 1;
for (int j = 0; j < 2; j++) {
if ((i + 1) == genotypeArray[j]) {
/*
if i = 0, genotype[0] = 1, genotype[1] = 1
copyNumberArray[0] = 3, copyNumberArray[1] = 2
then currentCopyNumber = 2.
what does currentCopyNumber mean in real world?
*/
if (copyNumberArray[j] > 0) {
currentCopyNumber = copyNumberArray[j];
}
}
}
int alternativeAlleleLength = Math.max(Math.abs(svlens[i]), 1);
alts[i] = new FlexSeq(FlexSeq.Type.DUP, alternativeAlleleLength, currentCopyNumber);
}
/*return new Variant(chr, pos, Math.abs(svlens[0]), refs, alts,
genotypeArray, isGenotypePhased, variantId, FILTER, deletedReference, random);
*/
return new Variant.Builder().chr(chr).pos(pos).referenceAlleleLength(Math.abs(svlens[0])).
ref(refs).alts(alts).phase(genotypeArray).isPhased(isGenotypePhased).
varId(variantId).filter(FILTER).refDeleted(deletedReference).
randomNumberGenerator(random).build();
//TODO: this assumes only one alt, which might not be true
} else if (ends[0] > 0) {
int alternativeAlleleLength = Math.max(Math.abs(ends[0] - pos + 1), 1);
alts = new FlexSeq[1];
alts[0] = new FlexSeq(FlexSeq.Type.DUP, alternativeAlleleLength, Math.max(
copyNumberArray[0], copyNumberArray[1]));
/*return new Variant(chr, pos, alternativeAlleleLength, refs, alts,
genotypeArray, isGenotypePhased, variantId, FILTER, deletedReference, random);
*/
return new Variant.Builder().chr(chr).pos(pos).referenceAlleleLength(alternativeAlleleLength).
ref(refs).alts(alts).phase(genotypeArray).isPhased(isGenotypePhased).
varId(variantId).filter(FILTER).refDeleted(deletedReference).
randomNumberGenerator(random).build();
} else {
log.error("No length information for DUP:");
log.error(line);
log.error("skipping...");
return null;
}
} else if (ALT.startsWith("<INS>")) {
// insertion SV
int[] ends = (int[]) info.getValue("END");
// TODO may need to check
int[] svlens = (int[]) info.getValue("SVLEN");
deletedReference = REF;
byte[] refs = new byte[0];
pos++;
if (svlens.length > 0) {
alts = new FlexSeq[svlens.length];
for (int i = 0; i < svlens.length; i++) {
int alternativeAlleleLength;
if (svlens[i] == 0) {
alternativeAlleleLength = Integer.MAX_VALUE;
} else {
alternativeAlleleLength = Math.max(Math.abs(svlens[i]), 1);
}
alts[i] = new FlexSeq(FlexSeq.Type.INS, alternativeAlleleLength);
}
/*return new Variant(chr, pos, 0, refs, alts,
genotypeArray, isGenotypePhased, variantId, FILTER, deletedReference, random);
*/
return new Variant.Builder().chr(chr).pos(pos).referenceAlleleLength(0).
ref(refs).alts(alts).phase(genotypeArray).isPhased(isGenotypePhased).
varId(variantId).filter(FILTER).refDeleted(deletedReference).
randomNumberGenerator(random).build();
} else if (ends[0] > 0) {
int alternativeAlleleLength = Math.max(Math.abs(ends[0] - pos), 1);
alts = new FlexSeq[1];
alts[0] = new FlexSeq(FlexSeq.Type.INS, alternativeAlleleLength);
/*return new Variant(chr, pos, 0, refs, alts,
genotypeArray, isGenotypePhased, variantId, FILTER, deletedReference, random);
*/
return new Variant.Builder().chr(chr).pos(pos).referenceAlleleLength(0).
ref(refs).alts(alts).phase(genotypeArray).isPhased(isGenotypePhased).
varId(variantId).filter(FILTER).refDeleted(deletedReference).
randomNumberGenerator(random).build();
} else {
log.error("No length information for INS:");
log.error(line);
log.error("skipping...");
return null;
}
} else if (ALT.startsWith("<DEL>")) {
// deletion SV
// but... we don't have the reference... so we add some random sequence?
int[] ends = (int[]) info.getValue("END");
// TODO may need to check
int[] svlens = (int[]) info.getValue("SVLEN");
deletedReference = REF;
byte[] refs = new byte[0];
pos++;
if (svlens.length > 0) {
alts = new FlexSeq[svlens.length];
for (int i = 0; i < svlens.length; i++) {
// deletion has no alt
alts[i] = new FlexSeq(FlexSeq.Type.DEL, 0);
}
/*return new Variant(chr, pos, Math.abs(svlens[0]), refs, alts,
genotypeArray, isGenotypePhased, variantId, FILTER, deletedReference, random);
*/
return new Variant.Builder().chr(chr).pos(pos).referenceAlleleLength(Math.abs(svlens[0])).
ref(refs).alts(alts).phase(genotypeArray).isPhased(isGenotypePhased).
varId(variantId).filter(FILTER).refDeleted(deletedReference).
randomNumberGenerator(random).build();
} else if (ends[0] > 0) {
int alternativeAlleleLength = ends[0] - pos + 1;
alts = new FlexSeq[1];
alts[0] = new FlexSeq(FlexSeq.Type.DEL, 0);
/*return new Variant(chr, pos, alternativeAlleleLength, refs, alts,
genotypeArray, isGenotypePhased, variantId, FILTER, deletedReference, random);
*/
return new Variant.Builder().chr(chr).pos(pos).referenceAlleleLength(alternativeAlleleLength).
ref(refs).alts(alts).phase(genotypeArray).isPhased(isGenotypePhased).
varId(variantId).filter(FILTER).refDeleted(deletedReference).
randomNumberGenerator(random).build();
} else {
log.error("No length information for DEL:");
log.error(line);
log.error("skipping...");
return null;
}
} else if (ALT.startsWith("<TRA>")) {
//translocation SV
//1-based end for reference allele
int[] end = (int[]) info.getValue("END");
int[] end2 = (int[]) info.getValue("END2");
int[] pos2 = (int[]) info.getValue("POS2");
//SVLEN for alternative allele length
int[] svlen = (int[]) info.getValue("SVLEN");
String[] chr2 = (String[]) info.getValue("CHR2");
String[] subtype = (String[]) info.getValue("TRASUBTYPE");
deletedReference = REF;
byte[] refs = new byte[0];
pos++; //1-based start
if (svlen.length > 0) {
//0 is for reference allele
alts = new FlexSeq[svlen.length];
//alternative allele is numbered 1,2,... per VCFSpec
for (int altAlleleIndex = 1; altAlleleIndex <= svlen.length; altAlleleIndex++) {
int currentCopyNumber = 1;
/*
implicit assumption here: genotype[0] == genotype[1] => copyNumberArray[0] == copyNumberArray[1]
*/
//check paternal
if (altAlleleIndex == genotypeArray[0]) {
currentCopyNumber = copyNumberArray[0];
}
//check maternal
if (altAlleleIndex == genotypeArray[1]) {
currentCopyNumber = copyNumberArray[1];
}
currentCopyNumber = Math.max(1, currentCopyNumber);
int altAllelelength = Math.max(Math.abs(svlen[altAlleleIndex - 1]), 1);
/*Not sure if INS is the most appropriate FlexSeq.Type
use it unless it breaks things.
*/
if (subtype[altAlleleIndex - 1].equals("ACCEPT")) {
alts[altAlleleIndex - 1] = new FlexSeq(FlexSeq.Type.TRA, altAllelelength, currentCopyNumber);
} else if (subtype[altAlleleIndex - 1].equals("REJECT")){
alts[altAlleleIndex - 1] = new FlexSeq(FlexSeq.Type.DEL, 0);
} else {
throw new IllegalArgumentException("ERROR: only ACCEPT and REJECT allowed.\n" + line);
}
}
//TODO: there could be multiple SVLEN values, but for now we only use one
//make sure all SVLEN values are equal if we only use the first one
//per VCFv4.1 spec, SVLEN should be length of alternative allele rather than
//reference allele
for (int i = 1; i < svlen.length; i++) {
if (svlen[i] != svlen[0]) {
throw new IllegalArgumentException("ERROR: SVLEN values not equal.\n" + line);
}
}
//pos is incremented by 1, so it becomes 1-based start
/*return new Variant(chr, pos, Math.abs(end[0] - pos + 1), refs, alts,
genotypeArray, isGenotypePhased, variantId, FILTER, deletedReference, random, ChrString.string2ChrString(chr2), pos2, end2, end[0], subtype);
*/
return new Variant.Builder().chr(chr).pos(pos).referenceAlleleLength(Math.abs(end[0] - pos + 1)).
ref(refs).alts(alts).phase(genotypeArray).isPhased(isGenotypePhased).
varId(variantId).filter(FILTER).refDeleted(deletedReference).
randomNumberGenerator(random).chr2(ChrString.string2ChrString(chr2)).
pos2(pos2).end2(end2).end(end[0]).translocationSubtype(subtype).build();
//TODO: this assumes only one alt, which might not be true
} else {
log.error("No length information for TRA:");
log.error(line);
log.error("skipping...");
return null;
}
} else if (ALT.indexOf('<') >= 0) {
// imprecise variant
log.warn("Imprecise line: " + line);
return null;
} else {
// Splitting
String[] alternativeAlleles = ALT.split(",");
int n = alternativeAlleles.length; // number of alts
alts = new FlexSeq[n];
for (int i = 0; i < n; i++) {
byte[] temp = new byte[alternativeAlleles[i].length()];
for (int j = 0; j < alternativeAlleles[i].length(); j++) {
temp[j] = (byte) alternativeAlleles[i].charAt(j);
}
alts[i] = new FlexSeq(temp);
}
// Check
for (int i = 0; i < n; i++) {
if (REF.length() == 1 && alts[i].length() == 1) {
// SNP
} else if (REF.length() == 0 || alts[i].length() == 0) {
log.warn("Skipping invalid record:");
log.warn(line);
return null;
}
}
/* Adjustment of first base
basically if first base of ref and alt match, first base of
ref and alt will both be removed, pos will increment by 1 to
account for the removal.
*/
// TODO: This needs to be updated to account for multiple matching reference bases
//e.g. ref=AT alt=ATC (VCFv4.1 spec requires only 1-bp before event, but it might
//not be the case all the time.
if (REF.length() > 0) {
boolean same = true;
for (int i = 0; i < n; i++) {
if (alts[i].length() == 0
|| REF.charAt(0) != alts[i].charAt(0)) {
same = false;
break;
}
}
if (same) {
pos++;
deletedReference = String.valueOf(REF.charAt(0));
REF = REF.substring(1);
//System.err.println(varId + " before :" + deletedReference);
for (int i = 0; i < n; i++) {
alts[i] = new FlexSeq(alts[i].substring(1));
}
}
}
// TODO this needs to be done
// but if we want to preserve the original VCF record, then this
// needs modification
if (REF.length() > 0) {
int referenceAlleleLength = REF.length();
int minClipLength = Integer.MAX_VALUE;
for (int i = 0; i < n; i++) {
int alternativeAlleleLength = alts[i].length();
//what does clipLength represent?
int clipLength = 0;
for (int j = 0; j < alternativeAlleleLength; j++) {
// make sure there is at least something in alt
if (referenceAlleleLength - j <= 0 || alternativeAlleleLength - j <= 0) {
clipLength = j;
break;
}
if (REF.charAt(referenceAlleleLength - j - 1) != alts[i].charAt(alternativeAlleleLength - j - 1)) {
clipLength = j;
break;
}
clipLength = j + 1;
}
if (minClipLength > clipLength) {
minClipLength = clipLength;
}
}
/*
apparently this code block is part of normalization.
is this working properly, though? e.g. it converts
CGTG,CG => GT,""
*/
if (minClipLength > 0) {
REF = REF.substring(0, referenceAlleleLength - minClipLength);
for (int i = 0; i < n; i++) {
alts[i] = new FlexSeq(alts[i].substring(0,
alts[i].length() - minClipLength));
}
}
}
byte[] refs = new byte[REF.length()];
for (int i = 0; i < REF.length(); i++) {
refs[i] = (byte) REF.charAt(i);
}
/*return new Variant(chr, pos, refs.length, refs, alts,
genotypeArray, isGenotypePhased, variantId, FILTER, deletedReference, random);
*/
return new Variant.Builder().chr(chr).pos(pos).referenceAlleleLength(refs.length).
ref(refs).alts(alts).phase(genotypeArray).isPhased(isGenotypePhased).
varId(variantId).filter(FILTER).refDeleted(deletedReference).
randomNumberGenerator(random).build();
}
}
public Variant parseLine() {
/*
TODO: line reading should be handled in a loop calling
*/
String line = this.line;
readLine();
if (line == null || line.length() == 0) {
log.info("blank line");
return null;
}
try {
return processLine(line);
} catch (Exception e) {
//TODO: right now just be lazy, die on any error
log.error(e.getMessage());
System.exit(255);
}
return null;
}
}
| src/main/java/com/bina/varsim/util/VCFparser.java | package com.bina.varsim.util;
//--- Java imports ---
import com.bina.varsim.types.ChrString;
import com.bina.varsim.types.FlexSeq;
import com.bina.varsim.types.VCFInfo;
import com.bina.varsim.types.variant.Variant;
import org.apache.log4j.Logger;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.rmi.UnexpectedException;
import java.util.Random;
import java.util.StringTokenizer;
public class VCFparser extends GzFileParser<Variant> {
public static final String DEFAULT_FILTER = "."; //default value for many columns
private final static Logger log = Logger.getLogger(VCFparser.class.getName());
private Random random = null;
private int sampleIndex = -1;
private String sampleId = null;
private boolean isPassFilterRequired = false;
private boolean chromLineSeen = false;
public VCFparser() {
sampleIndex = 10; // the first sample
}
/**
* Reads a VCF file line by line
*
* @param fileName VCF file, doesn't have to be sorted or indexed
* @param id ID of individual, essentially selects a column, null to use first ID column
* @param pass If true, only output pass lines
*/
public VCFparser(String fileName, String id, boolean pass, Random rand) {
random = rand;
try {
bufferedReader = new BufferedReader(new InputStreamReader(decompressStream(fileName)));
readLine();
} catch (Exception ex) {
log.error("Can't open file " + fileName);
log.error(ex.toString());
}
sampleId = id;
isPassFilterRequired = pass;
if (sampleId == null) {
sampleIndex = 10; // the first sample
}
}
/**
* Reads a VCF file line by line
*
* @param fileName VCF file, doesn't have to be sorted or indexed
* @param id ID of individual, essentially selects a column, null to use first ID column
* @param pass If true, only output pass lines
*/
public VCFparser(String fileName, String id, boolean pass) {
this(fileName, id, pass, null);
}
//TODO: remove unused constructor
/**
* Reads a VCF file line by line, if there are multiple individuals, takes the first one
*
* @param fileName VCF file, doesn't have to be sorted or indexed
* @param pass If true, only output pass lines
*/
public VCFparser(String fileName, boolean pass, Random rand) {
this(fileName, null, pass, rand);
}
//TODO: remove unused constructor
/**
* Reads a VCF file line by line, if there are multiple individuals, takes the first one
*
* @param fileName VCF file, doesn't have to be sorted or indexed
* @param pass If true, only output pass lines
*/
public VCFparser(String fileName, boolean pass) {
this(fileName, null, pass, null);
}
/**
* finds where "GT" or similar is in the VCF string so that the genotype can be read
*
* @param record The column in VCF that contains GT, CN, etc..
* @param key The key to be found "GT" or "CN" or other
* @return the index of the key
*/
private int getFormatKeyIndex(final String record, final String key) {
StringTokenizer words = new StringTokenizer(record, ":");
int ret = 0;
while (words.hasMoreTokens()) {
if (words.nextToken().equals(key))
return ret;
else
ret++;
}
return -1;
}
/**
* Takes genotype string and splits it into alleles, supports a maximum of two
*
* @param geno genotype string corresponding to the GT tag (field index 9)
* @param vals Return the genotypes read here [paternal,maternal]
* @param chr chromosome we are dealing with, some are haploid, need to assign parent
* @return true if the variant is phased
*/
boolean isPhased(String geno, byte[] vals, ChrString chr) {
boolean isPhased = false;
geno = geno.trim();
boolean strangePhase = false;
if (geno.matches("^[0-9]+$")) {
// phase is only a single number, for haploid chromosomes
byte val = (byte) Integer.parseInt(geno);
if (chr.isX()) {
vals[1] = val; // maternal
isPhased = true;
} else if (chr.isY()) {
vals[0] = val; // paternal
isPhased = true;
} else if (chr.isMT()) {
vals[1] = val;
isPhased = true;
} else {
vals[0] = vals[1] = val;
}
} else if (geno.length() >= 3) {
// this is the case where phase looks like "1|0" or "10|4"
String[] ll = geno.split("[\\|/]");
int c1 = -1;
int c2 = -1;
char phasing = '/';
if (ll.length == 2) {
try {
c1 = Integer.parseInt(ll[0]);
c2 = Integer.parseInt(ll[1]);
phasing = geno.charAt(ll[0].length());
} catch (NumberFormatException e) {
strangePhase = true;
}
} else {
strangePhase = true;
}
if (c1 >= 0 && c2 >= 0) {
vals[0] = (byte) c1;
vals[1] = (byte) c2;
if (phasing == '|') {
isPhased = true;
}
} else {
strangePhase = true;
}
} else {
strangePhase = true;
}
if (strangePhase) {
// System.err.println("Unrecognized phasing '" + phase + "'.");
vals[0] = -1;
vals[1] = -1;
isPhased = false;
}
return isPhased;
}
/**
* takes a line from a VCF file, parse it,
* return a Variant object
*
* right now the meta-info lines (beginning with ##) are
* not tied with data line parsing. This will be corrected
* in the future (perhaps with help of HTSJDK).
* @param line
* @return
*/
public Variant processLine(String line) throws UnexpectedException {
// try to determine the column we should read for the genotype
StringTokenizer toks = new StringTokenizer(line);
if (line.startsWith("#")) {
if (sampleId != null && line.startsWith("#CHROM")) {
chromLineSeen = true;
int index = 0;
while (toks.hasMoreTokens()) {
index++;
String tok = toks.nextToken();
if (tok.equals(sampleId))
sampleIndex = index;
}
} else if (sampleId == null) {
sampleIndex = 10; // the first sample
}
return null;
}
// If we cannot determine, then use the first one
if (sampleIndex < 0 && !chromLineSeen) {
sampleIndex = 10;
} else if (sampleIndex < 0) {
sampleIndex = 10;
log.warn("Warning!!! ID (" + sampleId + ") does not exist... ");
}
int index = 0, genotypeIndex = -1, copyNumberIndex = -1;
int pos = -1;
ChrString chr = null;
String REF = "", FILTER = "", ALT = "", variantId = "";
String phase = ".", copyNumber = "0/0", infoString = "", FORMAT;
String[] sampleInfo;
while (toks.hasMoreTokens()) {
index++;
if (index == 1) { // Parsing chromosome
chr = new ChrString(toks.nextToken());
} else if (index == 2) // Parsing position
pos = Integer.parseInt(toks.nextToken());
else if (index == 3) // Parsing position
variantId = toks.nextToken();
else if (index == 4) // Parsing reference allele
REF = toks.nextToken();
else if (index == 5) // Parsing alternative allele
ALT = toks.nextToken();
else if (index == 7) // FILTER field
FILTER = toks.nextToken();
else if (index == 8) // INFO field
infoString = toks.nextToken();
else if (index == 9) { // Output format
FORMAT = toks.nextToken();
genotypeIndex = getFormatKeyIndex(FORMAT, "GT");
copyNumberIndex = getFormatKeyIndex(FORMAT, "CN");
} else if (index == sampleIndex) { // phased or unphased genotype
sampleInfo = (toks.nextToken()).split(":");
if (genotypeIndex >= 0) {
phase = sampleInfo[genotypeIndex];
}
if (copyNumberIndex >= 0) {
copyNumber = sampleInfo[copyNumberIndex];
}
break;
} else {
toks.nextToken();
}
}
// unknown chromosome
// TODO: throw an exception for unknown chromosome name
if (chr == null) {
log.warn("Bad chromosome name: " + line);
return null;
}
if (isPassFilterRequired && !(FILTER.contains("PASS") || FILTER.equals(DEFAULT_FILTER))) {
//log.warn("not pass line" + line);
return null; // Filtered out
}
// parse the phased or unphased genotype
byte[] genotypeArray = new byte[2]; // paternal-maternal
boolean isGenotypePhased = isPhased(phase, genotypeArray, chr);
if (genotypeIndex >= 0 && genotypeArray[0] == 0 && genotypeArray[1] == 0) {
//return null; // reference alleles... ignore them for now....
}
// determine copy-number
// TODO need to be able to deal with unphased copy-numbers?
byte[] copyNumberArray = new byte[2]; // paternal-maternal
boolean isCopyNumberPhased;
if (copyNumberIndex >= 0) {
isCopyNumberPhased = isPhased(copyNumber, copyNumberArray, chr);
if (isCopyNumberPhased != isGenotypePhased) {
// TODO maybe don't throw error, this is not standard format
// anyways
log.error("Inconsistent copy number:");
log.error(line);
return null;
}
if ((genotypeArray[0] == genotypeArray[1]) != (copyNumberArray[0] == copyNumberArray[1])) {
throw new IllegalArgumentException("ERROR: genotype does not agree with copy number.\n" + line);
}
}
// Upper casing
REF = REF.toUpperCase();
ALT = ALT.toUpperCase();
String deletedReference = "";
FlexSeq alts[];
VCFInfo info = new VCFInfo(infoString);
/*if symbolic alleles are present,
make sure # of alleles equal # of
SV lengths. For non-symbolic alleles, SV lengths
are not really used or checked.
*/
/*!!!!!!!!!!
CAUTION: we assume symbolic alleles are not mixed
with non-symbolic alleles.
*/
if (ALT.indexOf('<') != -1) {
String[] alternativeAlleles = ALT.split(",");
int[] svlen = (int[]) info.getValue("SVLEN");
if (alternativeAlleles.length != svlen.length) {
throw new IllegalArgumentException("ERROR: number of symbolic alleles is unequal to number of SV lengths.\n" + line);
}
for (int i = 0; i < alternativeAlleles.length; i++) {
if (!alternativeAlleles[i].startsWith("<")) {
throw new IllegalArgumentException("ERROR: symbolic alleles are mixed with non-symbolic alleles.\n" + line);
}
}
}
if (ALT.startsWith("<INV>")) {
// inversion SV
int[] end = (int[]) info.getValue("END");
int[] svlen = (int[]) info.getValue("SVLEN");
deletedReference = REF;
byte[] refs = new byte[0];
pos++;
if (svlen.length > 0) {
alts = new FlexSeq[svlen.length];
for (int i = 0; i < svlen.length; i++) {
int alternativeAlleleLength = Math.max(Math.abs(svlen[i]), 1);
alts[i] = new FlexSeq(FlexSeq.Type.INV, alternativeAlleleLength);
}
// TODO this assumes only one alt
/*return new Variant(chr, pos, Math.abs(svlen[0]), refs, alts,
genotypeArray, isGenotypePhased, variantId, FILTER, deletedReference, random);
*/
return new Variant.Builder().chr(chr).pos(pos).referenceAlleleLength(Math.abs(svlen[0])).
ref(refs).alts(alts).phase(genotypeArray).isPhased(isGenotypePhased).
varId(variantId).filter(FILTER).refDeleted(deletedReference).
randomNumberGenerator(random).build();
//TODO: this assumes only one alt, might not be true
} else if (end[0] > 0) {
int alternativeAlleleLength = Math.max(Math.abs(end[0] - pos + 1), 1);
alts = new FlexSeq[1];
alts[0] = new FlexSeq(FlexSeq.Type.INV, alternativeAlleleLength);
/*return new Variant(chr, pos, alternativeAlleleLength, refs, alts,
genotypeArray, isGenotypePhased, variantId, FILTER, deletedReference, random);
*/
return new Variant.Builder().chr(chr).pos(pos).referenceAlleleLength(alternativeAlleleLength).
ref(refs).alts(alts).phase(genotypeArray).isPhased(isGenotypePhased).
varId(variantId).filter(FILTER).refDeleted(deletedReference).
randomNumberGenerator(random).build();
} else {
log.error("No length information for INV:");
log.error(line);
log.error("skipping...");
return null;
}
} else if (ALT.startsWith("<DUP>") || ALT.startsWith("<DUP:TANDEM>")) {
// duplication or tandem duplication SV
int[] svlens = (int[]) info.getValue("SVLEN");
// may need to check inconsistency
int[] ends = (int[]) info.getValue("END");
// btw length and end location
deletedReference = REF;
byte[] refs = new byte[0];
pos++;
if (svlens.length > 0) {
alts = new FlexSeq[svlens.length];
for (int i = 0; i < svlens.length; i++) {
// TODO this is temporary, how to encode copy number?
int currentCopyNumber = 1;
for (int j = 0; j < 2; j++) {
if ((i + 1) == genotypeArray[j]) {
/*
if i = 0, genotype[0] = 1, genotype[1] = 1
copyNumberArray[0] = 3, copyNumberArray[1] = 2
then currentCopyNumber = 2.
what does currentCopyNumber mean in real world?
*/
if (copyNumberArray[j] > 0) {
currentCopyNumber = copyNumberArray[j];
}
}
}
int alternativeAlleleLength = Math.max(Math.abs(svlens[i]), 1);
alts[i] = new FlexSeq(FlexSeq.Type.DUP, alternativeAlleleLength, currentCopyNumber);
}
/*return new Variant(chr, pos, Math.abs(svlens[0]), refs, alts,
genotypeArray, isGenotypePhased, variantId, FILTER, deletedReference, random);
*/
return new Variant.Builder().chr(chr).pos(pos).referenceAlleleLength(Math.abs(svlens[0])).
ref(refs).alts(alts).phase(genotypeArray).isPhased(isGenotypePhased).
varId(variantId).filter(FILTER).refDeleted(deletedReference).
randomNumberGenerator(random).build();
//TODO: this assumes only one alt, which might not be true
} else if (ends[0] > 0) {
int alternativeAlleleLength = Math.max(Math.abs(ends[0] - pos + 1), 1);
alts = new FlexSeq[1];
alts[0] = new FlexSeq(FlexSeq.Type.DUP, alternativeAlleleLength, Math.max(
copyNumberArray[0], copyNumberArray[1]));
/*return new Variant(chr, pos, alternativeAlleleLength, refs, alts,
genotypeArray, isGenotypePhased, variantId, FILTER, deletedReference, random);
*/
return new Variant.Builder().chr(chr).pos(pos).referenceAlleleLength(alternativeAlleleLength).
ref(refs).alts(alts).phase(genotypeArray).isPhased(isGenotypePhased).
varId(variantId).filter(FILTER).refDeleted(deletedReference).
randomNumberGenerator(random).build();
} else {
log.error("No length information for DUP:");
log.error(line);
log.error("skipping...");
return null;
}
} else if (ALT.startsWith("<INS>")) {
// insertion SV
int[] ends = (int[]) info.getValue("END");
// TODO may need to check
int[] svlens = (int[]) info.getValue("SVLEN");
deletedReference = REF;
byte[] refs = new byte[0];
pos++;
if (svlens.length > 0) {
alts = new FlexSeq[svlens.length];
for (int i = 0; i < svlens.length; i++) {
int alternativeAlleleLength;
if (svlens[i] == 0) {
alternativeAlleleLength = Integer.MAX_VALUE;
} else {
alternativeAlleleLength = Math.max(Math.abs(svlens[i]), 1);
}
alts[i] = new FlexSeq(FlexSeq.Type.INS, alternativeAlleleLength);
}
/*return new Variant(chr, pos, 0, refs, alts,
genotypeArray, isGenotypePhased, variantId, FILTER, deletedReference, random);
*/
return new Variant.Builder().chr(chr).pos(pos).referenceAlleleLength(0).
ref(refs).alts(alts).phase(genotypeArray).isPhased(isGenotypePhased).
varId(variantId).filter(FILTER).refDeleted(deletedReference).
randomNumberGenerator(random).build();
} else if (ends[0] > 0) {
int alternativeAlleleLength = Math.max(Math.abs(ends[0] - pos), 1);
alts = new FlexSeq[1];
alts[0] = new FlexSeq(FlexSeq.Type.INS, alternativeAlleleLength);
/*return new Variant(chr, pos, 0, refs, alts,
genotypeArray, isGenotypePhased, variantId, FILTER, deletedReference, random);
*/
return new Variant.Builder().chr(chr).pos(pos).referenceAlleleLength(0).
ref(refs).alts(alts).phase(genotypeArray).isPhased(isGenotypePhased).
varId(variantId).filter(FILTER).refDeleted(deletedReference).
randomNumberGenerator(random).build();
} else {
log.error("No length information for INS:");
log.error(line);
log.error("skipping...");
return null;
}
} else if (ALT.startsWith("<DEL>")) {
// deletion SV
// but... we don't have the reference... so we add some random sequence?
int[] ends = (int[]) info.getValue("END");
// TODO may need to check
int[] svlens = (int[]) info.getValue("SVLEN");
deletedReference = REF;
byte[] refs = new byte[0];
pos++;
if (svlens.length > 0) {
alts = new FlexSeq[svlens.length];
for (int i = 0; i < svlens.length; i++) {
// deletion has no alt
alts[i] = new FlexSeq(FlexSeq.Type.DEL, 0);
}
/*return new Variant(chr, pos, Math.abs(svlens[0]), refs, alts,
genotypeArray, isGenotypePhased, variantId, FILTER, deletedReference, random);
*/
return new Variant.Builder().chr(chr).pos(pos).referenceAlleleLength(Math.abs(svlens[0])).
ref(refs).alts(alts).phase(genotypeArray).isPhased(isGenotypePhased).
varId(variantId).filter(FILTER).refDeleted(deletedReference).
randomNumberGenerator(random).build();
} else if (ends[0] > 0) {
int alternativeAlleleLength = ends[0] - pos + 1;
alts = new FlexSeq[1];
alts[0] = new FlexSeq(FlexSeq.Type.DEL, 0);
/*return new Variant(chr, pos, alternativeAlleleLength, refs, alts,
genotypeArray, isGenotypePhased, variantId, FILTER, deletedReference, random);
*/
return new Variant.Builder().chr(chr).pos(pos).referenceAlleleLength(alternativeAlleleLength).
ref(refs).alts(alts).phase(genotypeArray).isPhased(isGenotypePhased).
varId(variantId).filter(FILTER).refDeleted(deletedReference).
randomNumberGenerator(random).build();
} else {
log.error("No length information for DEL:");
log.error(line);
log.error("skipping...");
return null;
}
} else if (ALT.startsWith("<TRA>")) {
//translocation SV
//1-based end for reference allele
int[] end = (int[]) info.getValue("END");
int[] end2 = (int[]) info.getValue("END2");
int[] pos2 = (int[]) info.getValue("POS2");
//SVLEN for alternative allele length
int[] svlen = (int[]) info.getValue("SVLEN");
String[] chr2 = (String[]) info.getValue("CHR2");
String[] subtype = (String[]) info.getValue("TRASUBTYPE");
deletedReference = REF;
byte[] refs = new byte[0];
pos++; //1-based start
if (svlen.length > 0) {
//0 is for reference allele
alts = new FlexSeq[svlen.length];
//alternative allele is numbered 1,2,... per VCFSpec
for (int altAlleleIndex = 1; altAlleleIndex <= svlen.length; altAlleleIndex++) {
int currentCopyNumber = 1;
/*
implicit assumption here: genotype[0] == genotype[1] => copyNumberArray[0] == copyNumberArray[1]
*/
//check paternal
if (altAlleleIndex == genotypeArray[0]) {
currentCopyNumber = copyNumberArray[0];
}
//check maternal
if (altAlleleIndex == genotypeArray[1]) {
currentCopyNumber = copyNumberArray[1];
}
currentCopyNumber = Math.max(1, currentCopyNumber);
int altAllelelength = Math.max(Math.abs(svlen[altAlleleIndex - 1]), 1);
/*Not sure if INS is the most appropriate FlexSeq.Type
use it unless it breaks things.
*/
if (subtype[altAlleleIndex - 1].equals("ACCEPT")) {
alts[altAlleleIndex - 1] = new FlexSeq(FlexSeq.Type.TRA, altAllelelength, currentCopyNumber);
} else if (subtype[altAlleleIndex - 1].equals("REJECT")){
alts[altAlleleIndex - 1] = new FlexSeq(FlexSeq.Type.DEL, 0);
} else {
throw new IllegalArgumentException("ERROR: only ACCEPT and REJECT allowed.\n" + line);
}
}
//TODO: there could be multiple SVLEN values, but for now we only use one
//make sure all SVLEN values are equal if we only use the first one
//per VCFv4.1 spec, SVLEN should be length of alternative allele rather than
//reference allele
for (int i = 1; i < svlen.length; i++) {
if (svlen[i] != svlen[0]) {
throw new IllegalArgumentException("ERROR: SVLEN values not equal.\n" + line);
}
}
//pos is incremented by 1, so it becomes 1-based start
/*return new Variant(chr, pos, Math.abs(end[0] - pos + 1), refs, alts,
genotypeArray, isGenotypePhased, variantId, FILTER, deletedReference, random, ChrString.string2ChrString(chr2), pos2, end2, end[0], subtype);
*/
return new Variant.Builder().chr(chr).pos(pos).referenceAlleleLength(Math.abs(end[0] - pos + 1)).
ref(refs).alts(alts).phase(genotypeArray).isPhased(isGenotypePhased).
varId(variantId).filter(FILTER).refDeleted(deletedReference).
randomNumberGenerator(random).chr2(ChrString.string2ChrString(chr2)).
pos2(pos2).end2(end2).end(end[0]).translocationSubtype(subtype).build();
//TODO: this assumes only one alt, which might not be true
} else {
log.error("No length information for TRA:");
log.error(line);
log.error("skipping...");
return null;
}
} else if (ALT.indexOf('<') >= 0) {
// imprecise variant
log.warn("Imprecise line: " + line);
return null;
} else {
// Splitting
String[] alternativeAlleles = ALT.split(",");
int n = alternativeAlleles.length; // number of alts
alts = new FlexSeq[n];
for (int i = 0; i < n; i++) {
byte[] temp = new byte[alternativeAlleles[i].length()];
for (int j = 0; j < alternativeAlleles[i].length(); j++) {
temp[j] = (byte) alternativeAlleles[i].charAt(j);
}
alts[i] = new FlexSeq(temp);
}
// Check
for (int i = 0; i < n; i++) {
if (REF.length() == 1 && alts[i].length() == 1) {
// SNP
} else if (REF.length() == 0 || alts[i].length() == 0) {
log.warn("Skipping invalid record:");
log.warn(line);
return null;
}
}
/* Adjustment of first base
basically if first base of ref and alt match, first base of
ref and alt will both be removed, pos will increment by 1 to
account for the removal.
*/
// TODO: This needs to be updated to account for multiple matching reference bases
//e.g. ref=AT alt=ATC (VCFv4.1 spec requires only 1-bp before event, but it might
//not be the case all the time.
if (REF.length() > 0) {
boolean same = true;
for (int i = 0; i < n; i++) {
if (alts[i].length() == 0
|| REF.charAt(0) != alts[i].charAt(0)) {
same = false;
break;
}
}
if (same) {
pos++;
deletedReference = String.valueOf(REF.charAt(0));
REF = REF.substring(1);
//System.err.println(varId + " before :" + deletedReference);
for (int i = 0; i < n; i++) {
alts[i] = new FlexSeq(alts[i].substring(1));
}
}
}
// TODO this needs to be done
// but if we want to preserve the original VCF record, then this
// needs modification
if (REF.length() > 0) {
int referenceAlleleLength = REF.length();
int minClipLength = Integer.MAX_VALUE;
for (int i = 0; i < n; i++) {
int alternativeAlleleLength = alts[i].length();
//what does clipLength represent?
int clipLength = 0;
for (int j = 0; j < alternativeAlleleLength; j++) {
// make sure there is at least something in alt
if (referenceAlleleLength - j <= 0 || alternativeAlleleLength - j <= 0) {
clipLength = j;
break;
}
if (REF.charAt(referenceAlleleLength - j - 1) != alts[i].charAt(alternativeAlleleLength - j - 1)) {
clipLength = j;
break;
}
clipLength = j + 1;
}
if (minClipLength > clipLength) {
minClipLength = clipLength;
}
}
/*
apparently this code block is part of normalization.
is this working properly, though? e.g. it converts
CGTG,CG => GT,""
*/
if (minClipLength > 0) {
REF = REF.substring(0, referenceAlleleLength - minClipLength);
for (int i = 0; i < n; i++) {
alts[i] = new FlexSeq(alts[i].substring(0,
alts[i].length() - minClipLength));
}
}
}
byte[] refs = new byte[REF.length()];
for (int i = 0; i < REF.length(); i++) {
refs[i] = (byte) REF.charAt(i);
}
/*return new Variant(chr, pos, refs.length, refs, alts,
genotypeArray, isGenotypePhased, variantId, FILTER, deletedReference, random);
*/
return new Variant.Builder().chr(chr).pos(pos).referenceAlleleLength(refs.length).
ref(refs).alts(alts).phase(genotypeArray).isPhased(isGenotypePhased).
varId(variantId).filter(FILTER).refDeleted(deletedReference).
randomNumberGenerator(random).build();
}
}
public Variant parseLine() {
/*
TODO: line reading should be handled in a loop calling
*/
String line = this.line;
readLine();
if (line == null || line.length() == 0) {
log.info("blank line");
return null;
}
try {
return processLine(line);
} catch (Exception e) {
//TODO: right now just be lazy, die on any error
log.error(e.getMessage());
System.exit(255);
}
return null;
}
}
| Remove incorrect CN check
| src/main/java/com/bina/varsim/util/VCFparser.java | Remove incorrect CN check | <ide><path>rc/main/java/com/bina/varsim/util/VCFparser.java
<ide> log.error(line);
<ide> return null;
<ide> }
<del> if ((genotypeArray[0] == genotypeArray[1]) != (copyNumberArray[0] == copyNumberArray[1])) {
<del> throw new IllegalArgumentException("ERROR: genotype does not agree with copy number.\n" + line);
<del> }
<ide> }
<ide>
<ide> // Upper casing |
|
Java | mit | 7aa489632d7704099ef464f34e881dff1de48165 | 0 | SpongePowered/SpongeAPI,SpongePowered/SpongeAPI,SpongePowered/SpongeAPI | /*
* This file is part of SpongeAPI, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.api.event;
/**
* Order that {@link Listener}d methods may be registered at.
*
* <p>Event handlers are called the order given in the following table.</p>
*
* <table summary="Order Recommendations">
* <tr><td>Order</td>
* <td>Recommendation</td></tr>
* <tr><td>PRE</td>
* <td>Initialisation and registration actions</td></tr>
* <tr><td>AFTER_PRE</td>
* <td>Immediate responses to actions in PRE</td></tr>
* <tr><td>FIRST</td>
* <td>
* Cancellation by protection plugins for informational purposes
* </td>
* </tr>
* <tr><td>EARLY</td>
* <td>Standard actions that should happen before other plugins react to
* the event</td>
* </tr>
* <tr><td>DEFAULT</td>
* <td>The default action order</td></tr>
* <tr><td>LATE</td>
* <td>Standard actions that should happen after other plugins react to
* the event</td>
* </tr>
* <tr><td>LAST</td>
* <td>Final cancellation by protection plugins</td></tr>
* <tr><td>BEFORE_POST</td>
* <td>Actions that need to respond to cancelled events before POST</td>
* </tr>
* <tr><td>POST</td>
* <td>Actions that need to react to the final and stable effects of
* event</td>
* </tr>
* </table>
*/
public enum Order {
/**
* The order point of PRE handles setting up things that need to be done
* before other things are handled.
*/
PRE,
/**
* The order point of AFTER_PRE handles things that need to be done after
* PRE.
*/
AFTER_PRE,
/**
* The order point of FIRST handles cancellation by protection plugins for
* informational responses.
*/
FIRST,
/**
* The order point of EARLY handles standard actions that need to be done
* before other plugins.
*/
EARLY,
/**
* The order point of DEFAULT handles just standard event handlings, you
* should use this unless you know you need otherwise.
*/
DEFAULT,
/**
* The order point of LATE handles standard actions that need to be done
* after other plugins.
*/
LATE,
/**
* The order point of LAST handles last minute cancellations by protection
* plugins.
*/
LAST,
/**
* The order point of BEFORE_POST handles preparation for things needing
* to be done in post.
*/
BEFORE_POST,
/**
* The order point of POST handles last minute things and monitoring
* of events for rollback or logging.
*/
POST
}
| src/main/java/org/spongepowered/api/event/Order.java | /*
* This file is part of SpongeAPI, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.api.event;
/**
* Order that {@link Listener}d methods may be registered at.
*
* <p>Event handlers are called the order given in the following table.</p>
*
* <table summary="Order Recommendations">
* <tr><td>Order</td> <td>Read Only</td> <td>Cancellation Allowed</td>
* <td>Recommendation</td></tr>
* <tr><td>PRE</td> <td>YES</td> <td>NO</td>
* <td>Initialisation and registration actions</td></tr>
* <tr><td>AFTER_PRE</td> <td>YES</td> <td>NO</td>
* <td>Immediate responses to actions in PRE</td></tr>
* <tr><td>FIRST</td> <td>YES</td> <td>YES</td>
* <td>
* Cancellation by protection plugins for informational purposes
* </td>
* </tr>
* <tr><td>EARLY</td> <td>NO</td> <td>YES</td>
* <td>Standard actions that should happen before other plugins react to
* the event</td>
* </tr>
* <tr><td>DEFAULT</td> <td>NO</td> <td>YES</td>
* <td>The default action order</td></tr>
* <tr><td>LATE</td> <td>NO</td> <td>YES</td>
* <td>Standard actions that should happen after other plugins react to
* the event</td>
* </tr>
* <tr><td>LAST</td> <td>YES</td> <td>YES</td>
* <td>Final cancellation by protection plugins</td></tr>
* <tr><td>BEFORE_POST</td> <td>YES</td> <td>NO</td>
* <td>Actions that need to respond to cancelled events before POST</td>
* </tr>
* <tr><td>POST</td> <td>YES</td> <td>NO</td>
* <td>Actions that need to react to the final and stable effects of
* event</td>
* </tr>
* </table>
*/
public enum Order {
/**
* The order point of PRE handles setting up things that need to be done
* before other things are handled PRE is read only and cannot cancel the
* events.
*/
PRE,
/**
* The order point of AFTER_PRE handles things that need to be done after
* PRE AFTER_PRE is read only and cannot cancel the events.
*/
AFTER_PRE,
/**
* The order point of FIRST handles cancellation by protection plugins for
* informational responses FIRST is read only but can cancel events.
*/
FIRST,
/**
* The order point of EARLY handles standard actions that need to be done
* before other plugins EARLY is not read only and can cancel events.
*/
EARLY,
/**
* The order point of DEFAULT handles just standard event handlings, you
* should use this unless you know you need otherwise DEFAULT is not read
* only and can cancel events.
*/
DEFAULT,
/**
* The order point of LATE handles standard actions that need to be done
* after other plugins LATE is not read only and can cancel the event.
*/
LATE,
/**
* The order point of LAST handles last minute cancellations by protection
* plugins LAST is read only but can cancel events.
*/
LAST,
/**
* The order point of BEFORE_POST handles preparation for things needing
* to be done in post BEFORE_POST is read only and cannot cancel events.
*/
BEFORE_POST,
/**
* The order point of POST handles last minute things and monitoring
* of events for rollback or logging POST is read only and
* cannot cancel events.
*/
POST
}
| Remove the concept of read-only orders (#2189)
* Remove the concept of read-only orders
* Remove cancellable | src/main/java/org/spongepowered/api/event/Order.java | Remove the concept of read-only orders (#2189) | <ide><path>rc/main/java/org/spongepowered/api/event/Order.java
<ide> * <p>Event handlers are called the order given in the following table.</p>
<ide> *
<ide> * <table summary="Order Recommendations">
<del> * <tr><td>Order</td> <td>Read Only</td> <td>Cancellation Allowed</td>
<add> * <tr><td>Order</td>
<ide> * <td>Recommendation</td></tr>
<del> * <tr><td>PRE</td> <td>YES</td> <td>NO</td>
<add> * <tr><td>PRE</td>
<ide> * <td>Initialisation and registration actions</td></tr>
<del> * <tr><td>AFTER_PRE</td> <td>YES</td> <td>NO</td>
<add> * <tr><td>AFTER_PRE</td>
<ide> * <td>Immediate responses to actions in PRE</td></tr>
<del> * <tr><td>FIRST</td> <td>YES</td> <td>YES</td>
<add> * <tr><td>FIRST</td>
<ide> * <td>
<ide> * Cancellation by protection plugins for informational purposes
<ide> * </td>
<ide> * </tr>
<del> * <tr><td>EARLY</td> <td>NO</td> <td>YES</td>
<add> * <tr><td>EARLY</td>
<ide> * <td>Standard actions that should happen before other plugins react to
<ide> * the event</td>
<ide> * </tr>
<del> * <tr><td>DEFAULT</td> <td>NO</td> <td>YES</td>
<add> * <tr><td>DEFAULT</td>
<ide> * <td>The default action order</td></tr>
<del> * <tr><td>LATE</td> <td>NO</td> <td>YES</td>
<add> * <tr><td>LATE</td>
<ide> * <td>Standard actions that should happen after other plugins react to
<ide> * the event</td>
<ide> * </tr>
<del> * <tr><td>LAST</td> <td>YES</td> <td>YES</td>
<add> * <tr><td>LAST</td>
<ide> * <td>Final cancellation by protection plugins</td></tr>
<del> * <tr><td>BEFORE_POST</td> <td>YES</td> <td>NO</td>
<add> * <tr><td>BEFORE_POST</td>
<ide> * <td>Actions that need to respond to cancelled events before POST</td>
<ide> * </tr>
<del> * <tr><td>POST</td> <td>YES</td> <td>NO</td>
<add> * <tr><td>POST</td>
<ide> * <td>Actions that need to react to the final and stable effects of
<ide> * event</td>
<ide> * </tr>
<ide>
<ide> /**
<ide> * The order point of PRE handles setting up things that need to be done
<del> * before other things are handled PRE is read only and cannot cancel the
<del> * events.
<add> * before other things are handled.
<ide> */
<ide> PRE,
<ide>
<ide> /**
<ide> * The order point of AFTER_PRE handles things that need to be done after
<del> * PRE AFTER_PRE is read only and cannot cancel the events.
<add> * PRE.
<ide> */
<ide> AFTER_PRE,
<ide>
<ide> /**
<ide> * The order point of FIRST handles cancellation by protection plugins for
<del> * informational responses FIRST is read only but can cancel events.
<add> * informational responses.
<ide> */
<ide> FIRST,
<ide>
<ide> /**
<ide> * The order point of EARLY handles standard actions that need to be done
<del> * before other plugins EARLY is not read only and can cancel events.
<add> * before other plugins.
<ide> */
<ide> EARLY,
<ide>
<ide> /**
<ide> * The order point of DEFAULT handles just standard event handlings, you
<del> * should use this unless you know you need otherwise DEFAULT is not read
<del> * only and can cancel events.
<add> * should use this unless you know you need otherwise.
<ide> */
<ide> DEFAULT,
<ide>
<ide> /**
<ide> * The order point of LATE handles standard actions that need to be done
<del> * after other plugins LATE is not read only and can cancel the event.
<add> * after other plugins.
<ide> */
<ide> LATE,
<ide>
<ide> /**
<ide> * The order point of LAST handles last minute cancellations by protection
<del> * plugins LAST is read only but can cancel events.
<add> * plugins.
<ide> */
<ide> LAST,
<ide>
<ide> /**
<ide> * The order point of BEFORE_POST handles preparation for things needing
<del> * to be done in post BEFORE_POST is read only and cannot cancel events.
<add> * to be done in post.
<ide> */
<ide> BEFORE_POST,
<ide>
<ide> /**
<ide> * The order point of POST handles last minute things and monitoring
<del> * of events for rollback or logging POST is read only and
<del> * cannot cancel events.
<add> * of events for rollback or logging.
<ide> */
<ide> POST
<ide> |
|
JavaScript | mit | c21aeb6c1dcc4a928206ffbec69df673997d9040 | 0 | compedit/react-youtube,troybetz/react-youtube,danieldiekmeier/react-youtube,shobith/react-youtube,compedit/react-youtube,denisnazarov/react-youtube,gaearon/react-youtube,troybetz/react-youtube,ymortazavi/react-youtube,amsardesai/react-youtube | /** @jsx React.DOM */
/**
* Module dependencies
*/
var React = require('react');
var sdk = require('require-sdk')('https://www.youtube.com/iframe_api', 'YT');
var loadTrigger = sdk.trigger();
// YT API requires global ready event handler
window.onYouTubeIframeAPIReady = function () {
loadTrigger();
delete window.onYouTubeIframeAPIReady;
};
function noop() {}
/**
* Separates video ID from valid YouTube URL
*
* @param {string} url
* @return {string}
*/
function getVideoId(url) {
var regex = /(youtu\.be\/|youtube\.com\/(watch\?(.*&)?v=|(embed|v)\/))([^\?&"'>]+)/;
if (url) return url.match(regex)[5];
}
/**
* Simple wrapper over YouTube JavaScript API
*/
module.exports = React.createClass({
propTypes: {
id: React.PropTypes.string,
url: React.PropTypes.string,
autoplay: React.PropTypes.bool,
playing: React.PropTypes.func,
stopped: React.PropTypes.func,
ended: React.PropTypes.func
},
getDefaultProps: function() {
return {
id: 'react-yt-player',
url: undefined,
autoplay: false,
playing: noop,
stopped: noop,
ended: noop
};
},
/**
* Once YouTube API had loaded, a new YT.Player
* instance will be created and its events bound.
*/
componentDidMount: function() {
var _this = this;
// called once API has loaded.
sdk(function(err, youtube) {
var player = new youtube.Player(_this.props.id, {
videoId: getVideoId(_this.props.url),
events: {
'onStateChange': _this._handlePlayerStateChange
}
});
_this.setState({player: player});
});
},
componentWillUpdate: function(nextProps) {
if (this.props.url !== nextProps.url) {
this._loadNewUrl(nextProps.url);
}
},
/**
* Start a new video
*
* @param {string} url
*/
_loadNewUrl: function(url) {
this.props.autoplay
? this.state.player.loadVideoById(getVideoId(url))
: this.state.player.cueVideoById(getVideoId(url));
},
/**
* Respond to player events
*
* @param {object} event
*/
_handlePlayerStateChange: function(event) {
switch(event.data) {
case 0:
this.props.ended();
break;
case 1:
this.props.playing();
break;
case 2:
this.props.stopped();
break;
default:
return;
}
},
render: function() {
return (
<div id={this.props.id}></div>
);
}
});
| index.js | /** @jsx React.DOM */
/**
* Module dependencies
*/
var React = require('react');
var sdk = require('require-sdk')('https://www.youtube.com/iframe_api', 'YT');
var loadTrigger = sdk.trigger();
// YT API requires global ready event handler
window.onYouTubeIframeAPIReady = function () {
loadTrigger();
delete window.onYouTubeIframeAPIReady;
};
function noop() {}
/**
* Separates video ID from valid YouTube URL
*
* @param {string} url
* @return {string}
*/
function getVideoId(url) {
var regex = /(youtu\.be\/|youtube\.com\/(watch\?(.*&)?v=|(embed|v)\/))([^\?&"'>]+)/;
if (url) return url.match(regex)[5];
}
/**
* Simple wrapper over YouTube JavaScript API
*/
module.exports = React.createClass({
propTypes: {
id: React.PropTypes.string,
url: React.PropTypes.string,
autoplau: React.PropTypes.boolean,
playing: React.PropTypes.func,
stopped: React.PropTypes.func,
ended: React.PropTypes.func
},
getDefaultProps: function() {
return {
id: 'react-yt-player',
url: undefined,
autoplay: false,
playing: noop,
stopped: noop,
ended: noop
};
},
/**
* Once YouTube API had loaded, a new YT.Player
* instance will be created and its events bound.
*/
componentDidMount: function() {
var _this = this;
// called once API has loaded.
sdk(function(err, youtube) {
var player = new youtube.Player(_this.props.id, {
videoId: getVideoId(_this.props.url),
events: {
'onStateChange': _this._handlePlayerStateChange
}
});
_this.setState({player: player});
});
},
componentWillUpdate: function(nextProps) {
if (this.props.url !== nextProps.url) {
this._loadNewUrl(nextProps.url);
}
},
/**
* Start a new video
*
* @param {string} url
*/
_loadNewUrl: function(url) {
this.props.autoplay
? this.state.player.loadVideoById(getVideoId(url))
: this.state.player.cueVideoById(getVideoId(url));
},
/**
* Respond to player events
*
* @param {object} event
*/
_handlePlayerStateChange: function(event) {
switch(event.data) {
case 0:
this.props.ended();
break;
case 1:
this.props.playing();
break;
case 2:
this.props.stopped();
break;
default:
return;
}
},
render: function() {
return (
<div id={this.props.id}></div>
);
}
});
| typos
| index.js | typos | <ide><path>ndex.js
<ide> propTypes: {
<ide> id: React.PropTypes.string,
<ide> url: React.PropTypes.string,
<del> autoplau: React.PropTypes.boolean,
<add> autoplay: React.PropTypes.bool,
<ide> playing: React.PropTypes.func,
<ide> stopped: React.PropTypes.func,
<ide> ended: React.PropTypes.func |
|
JavaScript | unknown | 42bd252be5a769c1fcb0df6af8bfe86eabcf3e94 | 0 | scrollback/io.scrollback.neighborhoods,wesley1001/io.scrollback.neighborhoods,wesley1001/io.scrollback.neighborhoods,scrollback/io.scrollback.neighborhoods | import React from "react-native";
import ChatBubble from "./chat-bubble";
import Avatar from "./avatar";
import Embed from "./embed";
import textUtils from "../lib/text-utils";
import timeUtils from "../lib/time-utils";
import oembed from "../lib/oembed";
const {
StyleSheet,
View,
Text,
Image
} = React;
const styles = StyleSheet.create({
container: {
marginHorizontal: 16,
marginVertical: 4
},
chat: {
flex: 0,
flexDirection: "column",
alignItems: "flex-end"
},
received: {
alignItems: "flex-start",
marginLeft: 44
},
timestamp: {
fontSize: 12,
marginTop: 4,
paddingHorizontal: 8,
opacity: 0.5
},
timestampLeft: { marginLeft: 52 },
timestampRight: { alignSelf: "flex-end" },
avatar: {
position: "absolute",
left: -44,
top: 0,
height: 36,
width: 36,
borderRadius: 18,
marginRight: 4,
backgroundColor: "#999",
alignSelf: "flex-end"
},
embed: {
width: 240,
height: 160,
marginVertical: 4
},
image: {
flex: 1,
resizeMode: "cover",
borderRadius: 36
}
});
export default class ChatItem extends React.Component {
render() {
const { text, previousText } = this.props;
const received = Math.random() < 0.7;
const links = textUtils.getLinks(text.text);
const pictures = textUtils.getPictures(text.text);
let cover;
if (pictures.length) {
cover = <Image style={null} source={{ uri: pictures[0] }} />;
} else if (links.length) {
const uri = links[0];
const endpoint = oembed(uri);
if (endpoint) {
cover = <Embed uri={uri} endpoint={endpoint} style={styles.embed} />;
}
}
let showAuthor = received,
showTime = false;
if (previousText) {
if (received) {
showAuthor = text.from !== previousText.from;
}
showTime = (text.time - previousText.time) > 300000;
}
return (
<View {...this.props} style={[ styles.container, this.props.style ]}>
<View style={[ styles.chat, received ? styles.received : null ]}>
{received ?
<View style={styles.avatar}>
<Avatar nick={text.from} size={48} style={styles.image} />
</View> :
null
}
<ChatBubble text={text} type={received ? "left" : "right"} showAuthor={showAuthor} style={styles.bubble}>
{cover}
</ChatBubble>
</View>
{showTime ?
<Text style={[ styles.timestamp, received ? styles.timestampLeft : styles.timestampRight ]}>{timeUtils.long(text.time)}</Text> :
null
}
</View>
);
}
}
ChatItem.propTypes = {
text: React.PropTypes.shape({
text: React.PropTypes.string.isRequired,
from: React.PropTypes.string.isRequired,
time: React.PropTypes.number.isRequired
}).isRequired,
previousText: React.PropTypes.shape({
from: React.PropTypes.string.isRequired,
time: React.PropTypes.number.isRequired
})
};
| views/chat-item.js | import React from "react-native";
import ChatBubble from "./chat-bubble";
import Avatar from "./avatar";
import Embed from "./embed";
import textUtils from "../lib/text-utils";
import timeUtils from "../lib/time-utils";
import oembed from "../lib/oembed";
const {
StyleSheet,
View,
Text,
Image
} = React;
const styles = StyleSheet.create({
container: {
marginHorizontal: 16,
marginVertical: 4
},
chat: {
flex: 0,
flexDirection: "column",
alignItems: "flex-end"
},
received: {
alignItems: "flex-start",
marginLeft: 48
},
timestamp: {
fontSize: 12,
marginTop: 4,
paddingHorizontal: 8,
opacity: 0.5
},
timestampLeft: { marginLeft: 52 },
timestampRight: { alignSelf: "flex-end" },
avatar: {
position: "absolute",
left: -48,
top: 0,
height: 36,
width: 36,
borderRadius: 18,
marginVertical: 2,
marginRight: 4,
backgroundColor: "#999",
alignSelf: "flex-end"
},
embed: {
width: 240,
height: 160,
marginVertical: 4
},
image: {
flex: 1,
resizeMode: "cover",
borderRadius: 36
}
});
export default class ChatItem extends React.Component {
render() {
const { text, previousText } = this.props;
const received = Math.random() < 0.7;
const links = textUtils.getLinks(text.text);
const pictures = textUtils.getPictures(text.text);
let cover;
if (pictures.length) {
cover = <Image style={null} source={{ uri: pictures[0] }} />;
} else if (links.length) {
const uri = links[0];
const endpoint = oembed(uri);
if (endpoint) {
cover = <Embed uri={uri} endpoint={endpoint} style={styles.embed} />;
}
}
let showAuthor = received,
showTime = false;
if (previousText) {
if (received) {
showAuthor = text.from !== previousText.from;
}
showTime = (text.time - previousText.time) > 300000;
}
return (
<View {...this.props} style={[ styles.container, this.props.style ]}>
<View style={[ styles.chat, received ? styles.received : null ]}>
{received ?
<View style={styles.avatar}>
<Avatar nick={text.from} size={48} style={styles.image} />
</View> :
null
}
<ChatBubble text={text} type={received ? "left" : "right"} showAuthor={showAuthor} style={styles.bubble}>
{cover}
</ChatBubble>
</View>
{showTime ?
<Text style={[ styles.timestamp, received ? styles.timestampLeft : styles.timestampRight ]}>{timeUtils.long(text.time)}</Text> :
null
}
</View>
);
}
}
ChatItem.propTypes = {
text: React.PropTypes.shape({
text: React.PropTypes.string.isRequired,
from: React.PropTypes.string.isRequired,
time: React.PropTypes.number.isRequired
}).isRequired,
previousText: React.PropTypes.shape({
from: React.PropTypes.string.isRequired,
time: React.PropTypes.number.isRequired
})
};
| Reduce spacing between avatar and chat bubble
| views/chat-item.js | Reduce spacing between avatar and chat bubble | <ide><path>iews/chat-item.js
<ide> },
<ide> received: {
<ide> alignItems: "flex-start",
<del> marginLeft: 48
<add> marginLeft: 44
<ide> },
<ide> timestamp: {
<ide> fontSize: 12,
<ide> timestampRight: { alignSelf: "flex-end" },
<ide> avatar: {
<ide> position: "absolute",
<del> left: -48,
<add> left: -44,
<ide> top: 0,
<ide> height: 36,
<ide> width: 36,
<ide> borderRadius: 18,
<del> marginVertical: 2,
<ide> marginRight: 4,
<ide> backgroundColor: "#999",
<ide> alignSelf: "flex-end" |
|
Java | mit | 8caa0a93b60742a39f5e319362c9cf7a764b7145 | 0 | gmessner/gitlab4j-api | /*
* The MIT License (MIT)
*
* Copyright (c) 2017 Greg Messner <[email protected]>
*
* 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 org.gitlab4j.api;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import javax.ws.rs.core.Form;
import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.Response;
import org.gitlab4j.api.GitLabApi.ApiVersion;
import org.gitlab4j.api.models.Event;
import org.gitlab4j.api.models.Issue;
import org.gitlab4j.api.models.Member;
import org.gitlab4j.api.models.Project;
import org.gitlab4j.api.models.ProjectHook;
import org.gitlab4j.api.models.Snippet;
import org.gitlab4j.api.models.Visibility;
/**
* This class provides an entry point to all the GitLab API project calls.
*/
public class ProjectApi extends AbstractApi implements Constants {
public ProjectApi(GitLabApi gitLabApi) {
super(gitLabApi);
}
/**
* Get a list of projects accessible by the authenticated user.
*
* GET /projects
*
* @return a list of projects accessible by the authenticated user
* @throws GitLabApiException if any exception occurs
*/
public List<Project> getProjects() throws GitLabApiException {
Response response = get(Response.Status.OK, getDefaultPerPageParam(), "projects");
return (response.readEntity(new GenericType<List<Project>>() {}));
}
/**
* Get a list of projects accessible by the authenticated user and in the specified page range.
*
* GET /projects
*
* @param page the page to get
* @param perPage the number of projects per page
* @return a list of projects accessible by the authenticated user
* @throws GitLabApiException if any exception occurs
*/
public List<Project> getProjects(int page, int perPage) throws GitLabApiException {
Response response = get(Response.Status.OK, getPageQueryParams(page, perPage), "projects");
return (response.readEntity(new GenericType<List<Project>>() { }));
}
/**
* Get a Pager instance of projects accessible by the authenticated user.
*
* GET /projects
*
* @param itemsPerPage the number of Project instances that will be fetched per page
* @return a Pager instance of projects accessible by the authenticated user
* @throws GitLabApiException if any exception occurs
*/
public Pager<Project> getProjects(int itemsPerPage) throws GitLabApiException {
return (new Pager<Project>(this, Project.class, itemsPerPage, null, "projects"));
}
/**
* Get a list of projects accessible by the authenticated user and matching the supplied filter parameters.
* All filter parameters are optional.
*
* GET /projects
*
* @param archived limit by archived status
* @param visibility limit by visibility public, internal, or private
* @param orderBy return projects ordered by id, name, path, created_at, updated_at, or last_activity_at fields, default is created_at
* @param sort return projects sorted in asc or desc order. Default is desc
* @param search return list of projects matching the search criteria
* @param simple return only the ID, URL, name, and path of each project
* @param owned limit by projects owned by the current user
* @param membership limit by projects that the current user is a member of
* @param starred limit by projects starred by the current user
* @param statistics include project statistics
* @return a list of projects accessible by the authenticated user and matching the supplied parameters
* @throws GitLabApiException if any exception occurs
* @deprecated Will be removed in version 5.0, replaced by {@link #getProjects(Boolean, Visibility,
* Constants.ProjectOrderBy, Constants.SortOrder, String, Boolean, Boolean, Boolean, Boolean, Boolean)}
*/
public List<Project> getProjects(Boolean archived, Visibility visibility, String orderBy,
String sort, String search, Boolean simple, Boolean owned, Boolean membership,
Boolean starred, Boolean statistics) throws GitLabApiException {
GitLabApiForm formData = new GitLabApiForm()
.withParam("archived", archived)
.withParam("visibility", visibility)
.withParam("order_by", orderBy)
.withParam("sort", sort)
.withParam("search", search)
.withParam("simple", simple)
.withParam("owned", owned)
.withParam("membership", membership)
.withParam("starred", starred)
.withParam("statistics", statistics)
.withParam(PER_PAGE_PARAM, getDefaultPerPage());
Response response = get(Response.Status.OK, formData.asMap(), "projects");
return (response.readEntity(new GenericType<List<Project>>() {}));
}
/**
* Get a list of projects accessible by the authenticated user and matching the supplied filter parameters.
* All filter parameters are optional.
*
* GET /projects
*
* @param archived limit by archived status
* @param visibility limit by visibility public, internal, or private
* @param orderBy return projects ordered by ID, NAME, PATH, CREATED_AT, UPDATED_AT, or
* LAST_ACTIVITY_AT fields, default is CREATED_AT
* @param sort return projects sorted in asc or desc order. Default is desc
* @param search return list of projects matching the search criteria
* @param simple return only the ID, URL, name, and path of each project
* @param owned limit by projects owned by the current user
* @param membership limit by projects that the current user is a member of
* @param starred limit by projects starred by the current user
* @param statistics include project statistics
* @return a list of projects accessible by the authenticated user and matching the supplied parameters
* @throws GitLabApiException if any exception occurs
*/
public List<Project> getProjects(Boolean archived, Visibility visibility, ProjectOrderBy orderBy,
SortOrder sort, String search, Boolean simple, Boolean owned, Boolean membership,
Boolean starred, Boolean statistics) throws GitLabApiException {
GitLabApiForm formData = new GitLabApiForm()
.withParam("archived", archived)
.withParam("visibility", visibility)
.withParam("order_by", orderBy)
.withParam("sort", sort)
.withParam("search", search)
.withParam("simple", simple)
.withParam("owned", owned)
.withParam("membership", membership)
.withParam("starred", starred)
.withParam("statistics", statistics)
.withParam(PER_PAGE_PARAM, getDefaultPerPage());
Response response = get(Response.Status.OK, formData.asMap(), "projects");
return (response.readEntity(new GenericType<List<Project>>() {}));
}
/**
* Get a list of projects accessible by the authenticated user and matching the supplied filter parameters.
* All filter parameters are optional.
*
* GET /projects
*
* @param archived limit by archived status
* @param visibility limit by visibility public, internal, or private
* @param orderBy return projects ordered by ID, NAME, PATH, CREATED_AT, UPDATED_AT, or
* LAST_ACTIVITY_AT fields, default is CREATED_AT
* @param sort return projects sorted in asc or desc order. Default is desc
* @param search return list of projects matching the search criteria
* @param simple return only the ID, URL, name, and path of each project
* @param owned limit by projects owned by the current user
* @param membership limit by projects that the current user is a member of
* @param starred limit by projects starred by the current user
* @param statistics include project statistics
* @param page the page to get
* @param perPage the number of projects per page
* @return a list of projects accessible by the authenticated user and matching the supplied parameters
* @throws GitLabApiException if any exception occurs
*/
public List<Project> getProjects(Boolean archived, Visibility visibility, ProjectOrderBy orderBy,
SortOrder sort, String search, Boolean simple, Boolean owned, Boolean membership,
Boolean starred, Boolean statistics, int page, int perPage) throws GitLabApiException {
GitLabApiForm formData = new GitLabApiForm()
.withParam("archived", archived)
.withParam("visibility", visibility)
.withParam("order_by", orderBy)
.withParam("sort", sort)
.withParam("search", search)
.withParam("simple", simple)
.withParam("owned", owned)
.withParam("membership", membership)
.withParam("starred", starred)
.withParam("statistics", statistics)
.withParam(PAGE_PARAM, page)
.withParam(PER_PAGE_PARAM, perPage);
Response response = get(Response.Status.OK, formData.asMap(), "projects");
return (response.readEntity(new GenericType<List<Project>>() {}));
}
/**
* Get a Pager of projects accessible by the authenticated user and matching the supplied filter parameters.
* All filter parameters are optional.
*
* GET /projects
*
* @param archived limit by archived status
* @param visibility limit by visibility public, internal, or private
* @param orderBy return projects ordered by ID, NAME, PATH, CREATED_AT, UPDATED_AT, or
* LAST_ACTIVITY_AT fields, default is CREATED_AT
* @param sort return projects sorted in asc or desc order. Default is desc
* @param search return list of projects matching the search criteria
* @param simple return only the ID, URL, name, and path of each project
* @param owned limit by projects owned by the current user
* @param membership limit by projects that the current user is a member of
* @param starred limit by projects starred by the current user
* @param statistics include project statistics
* @param itemsPerPage the number of Project instances that will be fetched per page
* @return a Pager of projects accessible by the authenticated user and matching the supplied parameters
* @throws GitLabApiException if any exception occurs
*/
public Pager<Project> getProjects(Boolean archived, Visibility visibility, ProjectOrderBy orderBy,
SortOrder sort, String search, Boolean simple, Boolean owned, Boolean membership,
Boolean starred, Boolean statistics, int itemsPerPage) throws GitLabApiException {
GitLabApiForm formData = new GitLabApiForm()
.withParam("archived", archived)
.withParam("visibility", visibility)
.withParam("order_by", orderBy)
.withParam("sort", sort)
.withParam("search", search)
.withParam("simple", simple)
.withParam("owned", owned)
.withParam("membership", membership)
.withParam("starred", starred)
.withParam("statistics", statistics);
return (new Pager<Project>(this, Project.class, itemsPerPage, formData.asMap(), "projects"));
}
/**
* Get a list of projects accessible by the authenticated user that match the provided search string.
*
* GET /projects?search=search
*
* @param search the project name search criteria
* @return a list of projects accessible by the authenticated user that match the provided search string
* @throws GitLabApiException if any exception occurs
*/
public List<Project> getProjects(String search) throws GitLabApiException {
Form formData = new GitLabApiForm().withParam("search", search).withParam(PER_PAGE_PARAM, getDefaultPerPage());
Response response = get(Response.Status.OK, formData.asMap(), "projects");
return (response.readEntity(new GenericType<List<Project>>() {}));
}
/**
* Get a list of projects accessible by the authenticated user that match the provided search string.
*
* GET /projects?search=search
*
* @param search the project name search criteria
* @param page the page to get
* @param perPage the number of projects per page
* @return a list of projects accessible by the authenticated user that match the provided search string
* @throws GitLabApiException if any exception occurs
*/
public List<Project> getProjects(String search, int page, int perPage) throws GitLabApiException {
Form formData = new GitLabApiForm().withParam("search", search).withParam(PAGE_PARAM, page).withParam(PER_PAGE_PARAM, perPage);
Response response = get(Response.Status.OK, formData.asMap(), "projects");
return (response.readEntity(new GenericType<List<Project>>() {}));
}
/**
* Get a Pager of projects accessible by the authenticated user that match the provided search string.
*
* GET /projects?search=search
*
* @param search the project name search criteria
* @param itemsPerPage the number of Project instances that will be fetched per page
* @return a Pager of projects accessible by the authenticated user that match the provided search string
* @throws GitLabApiException if any exception occurs
*/
public Pager<Project> getProjects(String search, int itemsPerPage) throws GitLabApiException {
Form formData = new GitLabApiForm().withParam("search", search);
return (new Pager<Project>(this, Project.class, itemsPerPage, formData.asMap(), "projects"));
}
/**
* Get a list of projects that the authenticated user is a member of.
*
* GET /projects
*
* @return a list of projects that the authenticated user is a member of
* @throws GitLabApiException if any exception occurs
*/
public List<Project> getMemberProjects() throws GitLabApiException {
Form formData = new GitLabApiForm().withParam("membership", true).withParam(PER_PAGE_PARAM, getDefaultPerPage());
Response response = get(Response.Status.OK, formData.asMap(), "projects");
return (response.readEntity(new GenericType<List<Project>>() {}));
}
/**
* Get a list of projects that the authenticated user is a member of in the specified page range.
*
* GET /projects
*
* @param page the page to get
* @param perPage the number of projects per page
* @return a list of projects that the authenticated user is a member of
* @throws GitLabApiException if any exception occurs
*/
public List<Project> getMemberProjects(int page, int perPage) throws GitLabApiException {
Form formData = new GitLabApiForm().withParam("membership", true).withParam(PAGE_PARAM, page).withParam(PER_PAGE_PARAM, perPage);
Response response = get(Response.Status.OK, formData.asMap(), "projects");
return (response.readEntity(new GenericType<List<Project>>() {}));
}
/**
* Get a Pager of projects that the authenticated user is a member of.
*
* GET /projects
*
* @param itemsPerPage the number of Project instances that will be fetched per page
* @return a Pager o Project instances that the authenticated user is a member of
* @throws GitLabApiException if any exception occurs
*/
public Pager<Project> getMemberProjects(int itemsPerPage) throws GitLabApiException {
Form formData = new GitLabApiForm().withParam("membership", true);
return (new Pager<Project>(this, Project.class, itemsPerPage, formData.asMap(), "projects"));
}
/**
* Get a list of all GitLab projects (admin only).
*
* GET /projects/all
*
* @return a list of all GitLab projects
* @throws GitLabApiException if any exception occurs
* @deprecated Will be removed, no longer supported by the GitLab API
*/
public List<Project> getAllProjects() throws GitLabApiException {
if (!isApiVersion(ApiVersion.V3)) {
throw new GitLabApiException("Not supported by GitLab API version " + this.getApiVersion());
}
Form formData = new GitLabApiForm().withParam(PER_PAGE_PARAM, getDefaultPerPage());
Response response = get(Response.Status.OK, formData.asMap(), "projects", "all");
return (response.readEntity(new GenericType<List<Project>>() {}));
}
/**
* Get a list of projects owned by the authenticated user.
*
* GET /projects
*
* @return a list of projects owned by the authenticated user
* @throws GitLabApiException if any exception occurs
*/
public List<Project> getOwnedProjects() throws GitLabApiException {
Form formData = new GitLabApiForm().withParam("owned", true).withParam(PER_PAGE_PARAM, getDefaultPerPage());
Response response = get(Response.Status.OK, formData.asMap(), "projects");
return (response.readEntity(new GenericType<List<Project>>() { }));
}
/**
* Get a list of projects owned by the authenticated user in the specified page range.
*
* GET /projects
*
* @param page the page to get
* @param perPage the number of projects per page
* @return a list of projects owned by the authenticated user
* @throws GitLabApiException if any exception occurs
*/
public List<Project> getOwnedProjects(int page, int perPage) throws GitLabApiException {
Form formData = new GitLabApiForm().withParam("owned", true).withParam(PAGE_PARAM, page).withParam(PER_PAGE_PARAM, perPage);
Response response = get(Response.Status.OK, formData.asMap(), "projects");
return (response.readEntity(new GenericType<List<Project>>() {}));
}
/**
* Get a Pager of projects owned by the authenticated user.
*
* GET /projects
*
* @param itemsPerPage the number of Project instances that will be fetched per page
* @return a list of projects owned by the authenticated user
* @throws GitLabApiException if any exception occurs
*/
public Pager<Project> getOwnedProjects(int itemsPerPage) throws GitLabApiException {
Form formData = new GitLabApiForm().withParam("owned", true);
return (new Pager<Project>(this, Project.class, itemsPerPage, formData.asMap(), "projects"));
}
/**
* Get a list of projects starred by the authenticated user.
*
* GET /projects
*
* @return a list of projects starred by the authenticated user
* @throws GitLabApiException if any exception occurs
*/
public List<Project> getStarredProjects() throws GitLabApiException {
Form formData = new GitLabApiForm().withParam("starred", true).withParam(PER_PAGE_PARAM, getDefaultPerPage());
Response response = get(Response.Status.OK, formData.asMap(), "projects");
return (response.readEntity(new GenericType<List<Project>>() {}));
}
/**
* Get a list of projects starred by the authenticated user in the specified page range.
*
* GET /projects
*
* @param page the page to get
* @param perPage the number of projects per page
* @return a list of projects starred by the authenticated user
* @throws GitLabApiException if any exception occurs
*/
public List<Project> getStarredProjects(int page, int perPage) throws GitLabApiException {
Form formData = new GitLabApiForm().withParam("starred", true).withParam(PAGE_PARAM, page).withParam(PER_PAGE_PARAM, perPage);
Response response = get(Response.Status.OK, formData.asMap(), "projects");
return (response.readEntity(new GenericType<List<Project>>() {}));
}
/**
* Get a Pager of projects starred by the authenticated user.
*
* GET /projects
*
* @param itemsPerPage the number of Project instances that will be fetched per page
* @return a Pager of projects starred by the authenticated user
* @throws GitLabApiException if any exception occurs
*/
public Pager<Project> getStarredProjects(int itemsPerPage) throws GitLabApiException {
Form formData = new GitLabApiForm().withParam("starred", true).withParam(PER_PAGE_PARAM, getDefaultPerPage());
return (new Pager<Project>(this, Project.class, itemsPerPage, formData.asMap(), "projects"));
}
/**
* Get a specific project, which is owned by the authentication user.
*
* GET /projects/:id
*
* @param projectId the ID of the project to get
* @return the specified project
* @throws GitLabApiException if any exception occurs
*/
public Project getProject(Integer projectId) throws GitLabApiException {
Response response = get(Response.Status.OK, null, "projects", projectId);
return (response.readEntity(Project.class));
}
/**
* Get a specific project, which is owned by the authentication user.
*
* GET /projects/:id
*
* @param namespace the name of the project namespace or group
* @param project the name of the project to get
* @return the specified project
* @throws GitLabApiException if any exception occurs
*/
public Project getProject(String namespace, String project) throws GitLabApiException {
if (namespace == null) {
throw new RuntimeException("namespace cannot be null");
}
if (project == null) {
throw new RuntimeException("project cannot be null");
}
String projectPath = null;
try {
projectPath = URLEncoder.encode(namespace + "/" + project, "UTF-8");
} catch (UnsupportedEncodingException uee) {
throw (new GitLabApiException(uee));
}
Response response = get(Response.Status.OK, null, "projects", projectPath);
return (response.readEntity(Project.class));
}
/**
* Create a new project in the specified group.
*
* @param groupId the group ID to create the project under
* @param projectName the name of the project top create
* @return the created project
* @throws GitLabApiException if any exception occurs
*/
public Project createProject(Integer groupId, String projectName) throws GitLabApiException {
GitLabApiForm formData = new GitLabApiForm().withParam("namespace_id", groupId).withParam("name", projectName, true);
Response response = post(Response.Status.CREATED, formData, "projects");
return (response.readEntity(Project.class));
}
/**
* Create a new project with the current user's namespace.
*
* @param projectName the name of the project top create
* @return the created project
* @throws GitLabApiException if any exception occurs
*/
public Project createProject(String projectName) throws GitLabApiException {
GitLabApiForm formData = new GitLabApiForm().withParam("name", projectName, true);
Response response = post(Response.Status.CREATED, formData, "projects");
return (response.readEntity(Project.class));
}
/**
* Creates new project owned by the current user.
*
* @param project the Project instance with the configuration for the new project
* @return a Project instance with the newly created project info
* @throws GitLabApiException if any exception occurs
*/
public Project createProject(Project project) throws GitLabApiException {
return (createProject(project, null));
}
/**
* Creates new project owned by the current user. The following properties on the Project instance
* are utilized in the creation of the project:
*
* name (name or path are required) - new project name
* path (name or path are required) - new project path
* defaultBranch (optional) - master by default
* description (optional) - short project description
* visibility (optional) - Limit by visibility public, internal, or private
* visibilityLevel (optional)
* issuesEnabled (optional) - Enable issues for this project
* mergeRequestsEnabled (optional) - Enable merge requests for this project
* wikiEnabled (optional) - Enable wiki for this project
* snippetsEnabled (optional) - Enable snippets for this project
* jobsEnabled (optional) - Enable jobs for this project
* containerRegistryEnabled (optional) - Enable container registry for this project
* sharedRunnersEnabled (optional) - Enable shared runners for this project
* publicJobs (optional) - If true, jobs can be viewed by non-project-members
* onlyAllowMergeIfPipelineSucceeds (optional) - Set whether merge requests can only be merged with successful jobs
* onlyAllowMergeIfAllDiscussionsAreResolved (optional) - Set whether merge requests can only be merged when all the discussions are resolved
* lLfsEnabled (optional) - Enable LFS
* requestAccessEnabled (optional) - Allow users to request member access
* repositoryStorage (optional) - Which storage shard the repository is on. Available only to admins
* approvalsBeforeMerge (optional) - How many approvers should approve merge request by default
*
* @param project the Project instance with the configuration for the new project
* @param importUrl the URL to import the repository from
* @return a Project instance with the newly created project info
* @throws GitLabApiException if any exception occurs
*/
public Project createProject(Project project, String importUrl) throws GitLabApiException {
if (project == null) {
return (null);
}
String name = project.getName();
String path = project.getPath();
if ((name == null || name.trim().length() == 0) && (path == null || path.trim().length() == 0)) {
return (null);
}
GitLabApiForm formData = new GitLabApiForm()
.withParam("name", name)
.withParam("path", path)
.withParam("default_branch", project.getDefaultBranch())
.withParam("description", project.getDescription())
.withParam("issues_enabled", project.getIssuesEnabled())
.withParam("merge_requests_enabled", project.getMergeRequestsEnabled())
.withParam("jobs_enabled", project.getJobsEnabled())
.withParam("wiki_enabled", project.getWikiEnabled())
.withParam("container_registry_enabled", project.getContainerRegistryEnabled())
.withParam("snippets_enabled", project.getSnippetsEnabled())
.withParam("shared_runners_enabled", project.getSharedRunnersEnabled())
.withParam("public_jobs", project.getPublicJobs())
.withParam("visibility_level", project.getVisibilityLevel())
.withParam("only_allow_merge_if_pipeline_succeeds", project.getOnlyAllowMergeIfPipelineSucceeds())
.withParam("only_allow_merge_if_all_discussions_are_resolved", project.getOnlyAllowMergeIfAllDiscussionsAreResolved())
.withParam("lfs_enabled", project.getLfsEnabled())
.withParam("request_access_enabled", project.getRequestAccessEnabled())
.withParam("repository_storage", project.getRepositoryStorage())
.withParam("approvals_before_merge", project.getApprovalsBeforeMerge())
.withParam("import_url", importUrl);
if (isApiVersion(ApiVersion.V3)) {
boolean isPublic = (project.getPublic() != null ? project.getPublic() : project.getVisibility() == Visibility.PUBLIC);
formData.withParam("public", isPublic);
} else {
Visibility visibility = (project.getVisibility() != null ? project.getVisibility() :
project.getPublic() == Boolean.TRUE ? Visibility.PUBLIC : null);
formData.withParam("visibility", visibility);
}
if (project.getNamespace() != null) {
formData.withParam("namespace_id", project.getNamespace().getId());
}
Response response = post(Response.Status.CREATED, formData, "projects");
return (response.readEntity(Project.class));
}
/**
* Creates a Project
*
* @param name The name of the project
* @param namespaceId The Namespace for the new project, otherwise null indicates to use the GitLab default (user)
* @param description A description for the project, null otherwise
* @param issuesEnabled Whether Issues should be enabled, otherwise null indicates to use GitLab default
* @param mergeRequestsEnabled Whether Merge Requests should be enabled, otherwise null indicates to use GitLab default
* @param wikiEnabled Whether a Wiki should be enabled, otherwise null indicates to use GitLab default
* @param snippetsEnabled Whether Snippets should be enabled, otherwise null indicates to use GitLab default
* @param visibility The visibility of the project, otherwise null indicates to use GitLab default
* @param visibilityLevel The visibility level of the project, otherwise null indicates to use GitLab default
* @param importUrl The Import URL for the project, otherwise null
* @return the GitLab Project
* @throws GitLabApiException if any exception occurs
*/
public Project createProject(String name, Integer namespaceId, String description, Boolean issuesEnabled, Boolean mergeRequestsEnabled,
Boolean wikiEnabled, Boolean snippetsEnabled, Visibility visibility, Integer visibilityLevel, String importUrl) throws GitLabApiException {
if (isApiVersion(ApiVersion.V3)) {
Boolean isPublic = Visibility.PUBLIC == visibility;
return (createProject(name, namespaceId, description, issuesEnabled, mergeRequestsEnabled,
wikiEnabled, snippetsEnabled, isPublic, visibilityLevel, importUrl));
}
if (name == null || name.trim().length() == 0) {
return (null);
}
GitLabApiForm formData = new GitLabApiForm()
.withParam("name", name, true)
.withParam("namespace_id", namespaceId)
.withParam("description", description)
.withParam("issues_enabled", issuesEnabled)
.withParam("merge_requests_enabled", mergeRequestsEnabled)
.withParam("wiki_enabled", wikiEnabled)
.withParam("snippets_enabled", snippetsEnabled)
.withParam("visibility_level", visibilityLevel)
.withParam("visibility", visibility)
.withParam("import_url", importUrl);
Response response = post(Response.Status.CREATED, formData, "projects");
return (response.readEntity(Project.class));
}
/**
* Creates a Project
*
* @param name The name of the project
* @param namespaceId The Namespace for the new project, otherwise null indicates to use the GitLab default (user)
* @param description A description for the project, null otherwise
* @param issuesEnabled Whether Issues should be enabled, otherwise null indicates to use GitLab default
* @param mergeRequestsEnabled Whether Merge Requests should be enabled, otherwise null indicates to use GitLab default
* @param wikiEnabled Whether a Wiki should be enabled, otherwise null indicates to use GitLab default
* @param snippetsEnabled Whether Snippets should be enabled, otherwise null indicates to use GitLab default
* @param isPublic Whether the project is public or private, if true same as setting visibilityLevel = 20, otherwise null indicates to use GitLab default
* @param visibilityLevel The visibility level of the project, otherwise null indicates to use GitLab default
* @param importUrl The Import URL for the project, otherwise null
* @return the GitLab Project
* @throws GitLabApiException if any exception occurs
* @deprecated As of release 4.2.0, replaced by {@link #createProject(String, Integer, String, Boolean, Boolean,
* Boolean, Boolean, Visibility, Integer, String)}
*/
@Deprecated
public Project createProject(String name, Integer namespaceId, String description, Boolean issuesEnabled, Boolean mergeRequestsEnabled,
Boolean wikiEnabled, Boolean snippetsEnabled, Boolean isPublic, Integer visibilityLevel, String importUrl) throws GitLabApiException {
if (name == null || name.trim().length() == 0) {
return (null);
}
GitLabApiForm formData = new GitLabApiForm()
.withParam("name", name, true)
.withParam("namespace_id", namespaceId)
.withParam("description", description)
.withParam("issues_enabled", issuesEnabled)
.withParam("merge_requests_enabled", mergeRequestsEnabled)
.withParam("wiki_enabled", wikiEnabled)
.withParam("snippets_enabled", snippetsEnabled)
.withParam("visibility_level", visibilityLevel)
.withParam("import_url", importUrl);
if (isApiVersion(ApiVersion.V3)) {
formData.withParam("public", isPublic);
} else if (isPublic) {
formData.withParam("visibility", Visibility.PUBLIC);
}
Response response = post(Response.Status.CREATED, formData, "projects");
return (response.readEntity(Project.class));
}
/**
* Updates a project. The following properties on the Project instance
* are utilized in the edit of the project, null values are not updated:
*
* id (required) - existing project id
* name (required) - project name
* path (optional) - project path
* defaultBranch (optional) - master by default
* description (optional) - short project description
* visibility (optional) - Limit by visibility public, internal, or private
* issuesEnabled (optional) - Enable issues for this project
* mergeRequestsEnabled (optional) - Enable merge requests for this project
* wikiEnabled (optional) - Enable wiki for this project
* snippetsEnabled (optional) - Enable snippets for this project
* jobsEnabled (optional) - Enable jobs for this project
* containerRegistryEnabled (optional) - Enable container registry for this project
* sharedRunnersEnabled (optional) - Enable shared runners for this project
* publicJobs (optional) - If true, jobs can be viewed by non-project-members
* onlyAllowMergeIfPipelineSucceeds (optional) - Set whether merge requests can only be merged with successful jobs
* onlyAllowMergeIfAllDiscussionsAreResolved (optional) - Set whether merge requests can only be merged when all the discussions are resolved
* lLfsEnabled (optional) - Enable LFS
* requestAccessEnabled (optional) - Allow users to request member access
* repositoryStorage (optional) - Which storage shard the repository is on. Available only to admins
* approvalsBeforeMerge (optional) - How many approvers should approve merge request by default
*
* NOTE: The following parameters specified by the GitLab API edit project are not supported:
* import_url
* tag_list array
* avatar
* ci_config_path
*
* @param project the Project instance with the configuration for the new project
* @return a Project instance with the newly updated project info
* @throws GitLabApiException if any exception occurs
*/
public Project updateProject(Project project) throws GitLabApiException {
if (project == null) {
throw new RuntimeException("Project instance cannot be null.");
}
Integer id = project.getId();
if (id == null) {
throw new RuntimeException("Project ID cannot be null.");
}
String name = project.getName();
if (name == null || name.trim().length() == 0) {
throw new RuntimeException("Project name cannot be null or empty.");
}
GitLabApiForm formData = new GitLabApiForm()
.withParam("name", name, true)
.withParam("path", project.getPath())
.withParam("default_branch", project.getDefaultBranch())
.withParam("description", project.getDescription())
.withParam("issues_enabled", project.getIssuesEnabled())
.withParam("merge_requests_enabled", project.getMergeRequestsEnabled())
.withParam("jobs_enabled", project.getJobsEnabled())
.withParam("wiki_enabled", project.getWikiEnabled())
.withParam("snippets_enabled", project.getSnippetsEnabled())
.withParam("container_registry_enabled", project.getContainerRegistryEnabled())
.withParam("shared_runners_enabled", project.getSharedRunnersEnabled())
.withParam("public_jobs", project.getPublicJobs())
.withParam("only_allow_merge_if_pipeline_succeeds", project.getOnlyAllowMergeIfPipelineSucceeds())
.withParam("only_allow_merge_if_all_discussions_are_resolved", project.getOnlyAllowMergeIfAllDiscussionsAreResolved())
.withParam("lfs_enabled", project.getLfsEnabled())
.withParam("request_access_enabled", project.getRequestAccessEnabled())
.withParam("repository_storage", project.getRepositoryStorage())
.withParam("approvals_before_merge", project.getApprovalsBeforeMerge());
if (isApiVersion(ApiVersion.V3)) {
formData.withParam("visibility_level", project.getVisibilityLevel());
boolean isPublic = (project.getPublic() != null ? project.getPublic() : project.getVisibility() == Visibility.PUBLIC);
formData.withParam("public", isPublic);
} else {
Visibility visibility = (project.getVisibility() != null ? project.getVisibility() :
project.getPublic() == Boolean.TRUE ? Visibility.PUBLIC : null);
formData.withParam("visibility", visibility);
}
Response response = putWithFormData(Response.Status.OK, formData, "projects", id);
return (response.readEntity(Project.class));
}
/**
* Removes project with all resources(issues, merge requests etc).
*
* DELETE /projects/:id
*
* @param projectId the project ID to remove
* @throws GitLabApiException if any exception occurs
*/
public void deleteProject(Integer projectId) throws GitLabApiException {
if (projectId == null) {
throw new RuntimeException("projectId cannot be null");
}
Response.Status expectedStatus = (isApiVersion(ApiVersion.V3) ? Response.Status.OK : Response.Status.ACCEPTED);
delete(expectedStatus, null, "projects", projectId);
}
/**
* Removes project with all resources(issues, merge requests etc).
*
* DELETE /projects/:id
*
* @param project the Project instance to remove
* @throws GitLabApiException if any exception occurs
*/
public void deleteProject(Project project) throws GitLabApiException {
deleteProject(project.getId());
}
/**
* Get a list of project team members.
*
* GET /projects/:id/members
*
* @param projectId the project ID to get team members for
* @return the members belonging to the specified project
* @throws GitLabApiException if any exception occurs
*/
public List<Member> getMembers(Integer projectId) throws GitLabApiException {
Response response = get(Response.Status.OK, this.getDefaultPerPageParam(), "projects", projectId, "members");
return (response.readEntity(new GenericType<List<Member>>() {}));
}
/**
* Get a list of project team members in the specified page range.
*
* GET /projects/:id/members
*
* @param projectId the project ID to get team members for
* @param page the page to get
* @param perPage the number of Member instances per page
* @return the members belonging to the specified project
* @throws GitLabApiException if any exception occurs
*/
public List<Member> getMembers(Integer projectId, int page, int perPage) throws GitLabApiException {
Response response = get(Response.Status.OK, getPageQueryParams(page, perPage), "projects", projectId, "members");
return (response.readEntity(new GenericType<List<Member>>() {}));
}
/**
* Get a Pager of project team members.
*
* GET /projects/:id/members
*
* @param projectId the project ID to get team members for
* @param itemsPerPage the number of Project instances that will be fetched per page
* @return the members belonging to the specified project
* @throws GitLabApiException if any exception occurs
*/
public Pager<Member> getMembers(Integer projectId, int itemsPerPage) throws GitLabApiException {
return (new Pager<Member>(this, Member.class, itemsPerPage, null, "projects", projectId, "members"));
}
/**
* Gets a project team member.
*
* GET /projects/:id/members/:user_id
*
* @param projectId the project ID to get team member for
* @param userId the user ID of the member
* @return the member specified by the project ID/user ID pair
* @throws GitLabApiException if any exception occurs
*/
public Member getMember(Integer projectId, Integer userId) throws GitLabApiException {
Response response = get(Response.Status.OK, null, "projects", projectId, "members", userId);
return (response.readEntity(Member.class));
}
/**
* Adds a user to a project team. This is an idempotent method and can be called multiple times
* with the same parameters. Adding team membership to a user that is already a member does not
* affect the existing membership.
*
* POST /projects/:id/members
*
* @param projectId the project ID to add the team member to
* @param userId the user ID of the member to add
* @param accessLevel the access level for the new member
* @return the added member
* @throws GitLabApiException if any exception occurs
*/
public Member addMember(Integer projectId, Integer userId, Integer accessLevel) throws GitLabApiException {
GitLabApiForm formData = new GitLabApiForm().withParam("user_id", userId, true).withParam("access_level", accessLevel, true);
Response response = post(Response.Status.CREATED, formData, "projects", projectId, "members");
return (response.readEntity(Member.class));
}
/**
* Removes user from project team.
*
* DELETE /projects/:id/members/:user_id
*
* @param projectId the project ID to remove the team member from
* @param userId the user ID of the member to remove
* @throws GitLabApiException if any exception occurs
*/
public void removeMember(Integer projectId, Integer userId) throws GitLabApiException {
Response.Status expectedStatus = (isApiVersion(ApiVersion.V3) ? Response.Status.OK : Response.Status.NO_CONTENT);
delete(expectedStatus, null, "projects", projectId, "members", userId);
}
/**
* Get the project events for specific project. Sorted from newest to latest.
*
* GET /projects/:id/events
*
* @param projectId the project ID to get events for
* @return the project events for the specified project
* @throws GitLabApiException if any exception occurs
*/
public List<Event> getProjectEvents(Integer projectId) throws GitLabApiException {
Response response = get(Response.Status.OK, getDefaultPerPageParam(), "projects", projectId, "events");
return (response.readEntity(new GenericType<List<Event>>() {}));
}
/**
* Get the project events for specific project. Sorted from newest to latest in the specified page range.
*
* GET /projects/:id/events
*
* @param projectId the project ID to get events for
* @param page the page to get
* @param perPage the number of Event instances per page
* @return the project events for the specified project
* @throws GitLabApiException if any exception occurs
*/
public List<Event> getProjectEvents(Integer projectId, int page, int perPage) throws GitLabApiException {
Response response = get(Response.Status.OK, getPageQueryParams(page, perPage), "projects", projectId, "events");
return (response.readEntity(new GenericType<List<Event>>() {}));
}
/**
* Get a Pager of project events for specific project. Sorted from newest to latest.
*
* GET /projects/:id/events
*
* @param projectId the project ID to get events for
* @param itemsPerPage the number of Project instances that will be fetched per page
* @return a Pager of project events for the specified project
* @throws GitLabApiException if any exception occurs
*/
public Pager<Event> getProjectEvents(Integer projectId, int itemsPerPage) throws GitLabApiException {
return (new Pager<Event>(this, Event.class, itemsPerPage, null, "projects", projectId, "events"));
}
/**
* Get list of project hooks.
*
* GET /projects/:id/hooks
*
* @param projectId the project ID to get project hooks for
* @return a list of project hooks for the specified project
* @throws GitLabApiException if any exception occurs
*/
public List<ProjectHook> getHooks(Integer projectId) throws GitLabApiException {
Response response = get(Response.Status.OK, getDefaultPerPageParam(), "projects", projectId, "hooks");
return (response.readEntity(new GenericType<List<ProjectHook>>() {}));
}
/**
* Get list of project hooks in the specified page range.
*
* GET /projects/:id/hooks
*
* @param projectId the project ID to get project hooks for
* @param page the page to get
* @param perPage the number of ProjectHook instances per page
* @return a list of project hooks for the specified project in the specified page range
* @throws GitLabApiException if any exception occurs
*/
public List<ProjectHook> getHooks(Integer projectId, int page, int perPage) throws GitLabApiException {
Response response = get(Response.Status.OK, getPageQueryParams(page, perPage), "projects", projectId, "hooks");
return (response.readEntity(new GenericType<List<ProjectHook>>() {}));
}
/**
* Get Pager of project hooks.
*
* GET /projects/:id/hooks
*
* @param projectId the project ID to get project hooks for
* @param itemsPerPage the number of Project instances that will be fetched per page
* @return a Pager of project hooks for the specified project
* @throws GitLabApiException if any exception occurs
*/
public Pager<ProjectHook> getHooks(Integer projectId, int itemsPerPage) throws GitLabApiException {
return (new Pager<ProjectHook>(this, ProjectHook.class, itemsPerPage, null, "projects", projectId, "hooks"));
}
/**
* Get a specific hook for project.
*
* GET /projects/:id/hooks/:hook_id
*
* @param projectId the project ID to get the hook for
* @param hookId the ID of the hook to get
* @return the project hook for the specified project ID/hook ID pair
* @throws GitLabApiException if any exception occurs
*/
public ProjectHook getHook(Integer projectId, Integer hookId) throws GitLabApiException {
Response response = get(Response.Status.OK, null, "projects", projectId, "hooks", hookId);
return (response.readEntity(ProjectHook.class));
}
/**
* Adds a hook to project.
*
* POST /projects/:id/hooks
*
* @param projectName the name of the project
* @param url the callback URL for the hook
* @param enabledHooks a ProjectHook instance specifying which hooks to enable
* @param enableSslVerification enable SSL verification
* @param secretToken the secret token to pass back to the hook
* @return the added ProjectHook instance
* @throws GitLabApiException if any exception occurs
*/
public ProjectHook addHook(String projectName, String url, ProjectHook enabledHooks, boolean enableSslVerification, String secretToken) throws GitLabApiException {
if (projectName == null) {
return (null);
}
GitLabApiForm formData = new GitLabApiForm()
.withParam("url", url, true)
.withParam("push_events", enabledHooks.getPushEvents(), false)
.withParam("issues_events", enabledHooks.getIssuesEvents(), false)
.withParam("merge_requests_events", enabledHooks.getMergeRequestsEvents(), false)
.withParam("tag_push_events", enabledHooks.getTagPushEvents(), false)
.withParam("note_events", enabledHooks.getNoteEvents(), false)
.withParam("job_events", enabledHooks.getJobEvents(), false)
.withParam("pipeline_events", enabledHooks.getPipelineEvents(), false)
.withParam("wiki_events", enabledHooks.getWikiPageEvents(), false)
.withParam("enable_ssl_verification", enabledHooks.getEnableSslVerification())
.withParam("token", secretToken, false);
Response response = post(Response.Status.CREATED, formData, "projects", projectName, "hooks");
return (response.readEntity(ProjectHook.class));
}
/**
* Adds a hook to project.
*
* POST /projects/:id/hooks
*
* @param projectId the project ID to add the project hook to
* @param url the callback URL for the hook
* @param enabledHooks a ProjectHook instance specifying which hooks to enable
* @param enableSslVerification enable SSL verification
* @param secretToken the secret token to pass back to the hook
* @return the added ProjectHook instance
* @throws GitLabApiException if any exception occurs
*/
public ProjectHook addHook(Integer projectId, String url, ProjectHook enabledHooks, boolean enableSslVerification, String secretToken) throws GitLabApiException {
if (projectId == null) {
return (null);
}
GitLabApiForm formData = new GitLabApiForm()
.withParam("url", url, true)
.withParam("push_events", enabledHooks.getPushEvents(), false)
.withParam("issues_events", enabledHooks.getIssuesEvents(), false)
.withParam("merge_requests_events", enabledHooks.getMergeRequestsEvents(), false)
.withParam("tag_push_events", enabledHooks.getTagPushEvents(), false)
.withParam("note_events", enabledHooks.getNoteEvents(), false)
.withParam("job_events", enabledHooks.getJobEvents(), false)
.withParam("pipeline_events", enabledHooks.getPipelineEvents(), false)
.withParam("wiki_events", enabledHooks.getWikiPageEvents(), false)
.withParam("enable_ssl_verification", enabledHooks.getEnableSslVerification())
.withParam("token", secretToken, false);
Response response = post(Response.Status.CREATED, formData, "projects", projectId, "hooks");
return (response.readEntity(ProjectHook.class));
}
/**
* Adds a hook to project.
*
* POST /projects/:id/hooks
*
* @param project the Project instance to add the project hook to
* @param url the callback URL for the hook
* @param enabledHooks a ProjectHook instance specifying which hooks to enable
* @param enableSslVerification enable SSL verification
* @param secretToken the secret token to pass back to the hook
* @return the added ProjectHook instance
* @throws GitLabApiException if any exception occurs
*/
public ProjectHook addHook(Project project, String url, ProjectHook enabledHooks, boolean enableSslVerification, String secretToken) throws GitLabApiException {
if (project == null) {
return (null);
}
return (addHook(project.getId(), url, enabledHooks, enableSslVerification, secretToken));
}
/**
* Adds a hook to project.
*
* POST /projects/:id/hooks
*
* @param project the Project instance to add the project hook to
* @param url the callback URL for the hook
* @param doPushEvents flag specifying whether to do push events
* @param doIssuesEvents flag specifying whether to do issues events
* @param doMergeRequestsEvents flag specifying whether to do merge requests events
* @return the added ProjectHook instance
* @throws GitLabApiException if any exception occurs
*/
public ProjectHook addHook(Project project, String url, boolean doPushEvents, boolean doIssuesEvents, boolean doMergeRequestsEvents) throws GitLabApiException {
if (project == null) {
return (null);
}
return (addHook(project.getId(), url, doPushEvents, doIssuesEvents, doMergeRequestsEvents));
}
/**
* Adds a hook to project.
*
* POST /projects/:id/hooks
*
* @param projectId the project ID to add the project hook to
* @param url the callback URL for the hook
* @param doPushEvents flag specifying whether to do push events
* @param doIssuesEvents flag specifying whether to do issues events
* @param doMergeRequestsEvents flag specifying whether to do merge requests events
* @return the added ProjectHook instance
* @throws GitLabApiException if any exception occurs
*/
public ProjectHook addHook(Integer projectId, String url, boolean doPushEvents, boolean doIssuesEvents, boolean doMergeRequestsEvents) throws GitLabApiException {
GitLabApiForm formData = new GitLabApiForm()
.withParam("url", url)
.withParam("push_events", doPushEvents)
.withParam("issues_enabled", doIssuesEvents)
.withParam("merge_requests_events", doMergeRequestsEvents);
Response response = post(Response.Status.CREATED, formData, "projects", projectId, "hooks");
return (response.readEntity(ProjectHook.class));
}
/**
* Deletes a hook from the project.
*
* DELETE /projects/:id/hooks/:hook_id
*
* @param projectId the project ID to delete the project hook from
* @param hookId the project hook ID to delete
* @throws GitLabApiException if any exception occurs
*/
public void deleteHook(Integer projectId, Integer hookId) throws GitLabApiException {
Response.Status expectedStatus = (isApiVersion(ApiVersion.V3) ? Response.Status.OK : Response.Status.NO_CONTENT);
delete(expectedStatus, null, "projects", projectId, "hooks", hookId);
}
/**
* Deletes a hook from the project.
*
* DELETE /projects/:id/hooks/:hook_id
*
* @param hook the ProjectHook instance to remove
* @throws GitLabApiException if any exception occurs
*/
public void deleteHook(ProjectHook hook) throws GitLabApiException {
deleteHook(hook.getProjectId(), hook.getId());
}
/**
* Modifies a hook for project.
*
* PUT /projects/:id/hooks/:hook_id
*
* @param hook the ProjectHook instance that contains the project hook info to modify
* @return the modified project hook
* @throws GitLabApiException if any exception occurs
*/
public ProjectHook modifyHook(ProjectHook hook) throws GitLabApiException {
GitLabApiForm formData = new GitLabApiForm()
.withParam("url", hook.getUrl(), true)
.withParam("push_events", hook.getPushEvents(), false)
.withParam("issues_events", hook.getIssuesEvents(), false)
.withParam("merge_requests_events", hook.getMergeRequestsEvents(), false)
.withParam("tag_push_events", hook.getTagPushEvents(), false)
.withParam("note_events", hook.getNoteEvents(), false)
.withParam("job_events", hook.getJobEvents(), false)
.withParam("pipeline_events", hook.getPipelineEvents(), false)
.withParam("wiki_events", hook.getWikiPageEvents(), false)
.withParam("enable_ssl_verification", hook.getEnableSslVerification(), false)
.withParam("token", hook.getToken(), false);
Response response = put(Response.Status.OK, formData.asMap(), "projects", hook.getProjectId(), "hooks", hook.getId());
return (response.readEntity(ProjectHook.class));
}
/**
* Get a list of project's issues. Only returns the first page
*
* GET /projects/:id/issues
*
* @param projectId the project ID to get the issues for
* @return a list of project's issues
* @throws GitLabApiException if any exception occurs
*/
public List<Issue> getIssues(Integer projectId) throws GitLabApiException {
Response response = get(Response.Status.OK, getDefaultPerPageParam(), "projects", projectId, "issues");
return (response.readEntity(new GenericType<List<Issue>>() {}));
}
/**
* Get a list of project's issues using the specified page and per page settings.
*
* GET /projects/:id/issues
*
* @param projectId the project ID to get the issues for
* @param page the page to get
* @param perPage the number of issues per page
* @return the list of issues in the specified range
* @throws GitLabApiException if any exception occurs
*/
public List<Issue> getIssues(Integer projectId, int page, int perPage) throws GitLabApiException {
Response response = get(Response.Status.OK, getPageQueryParams(page, perPage), "projects", projectId, "issues");
return (response.readEntity(new GenericType<List<Issue>>() {}));
}
/**
* Get a Pager of project's issues.
*
* GET /projects/:id/issues
*
* @param projectId the project ID to get the issues for
* @param itemsPerPage the number of issues per page
* @return the list of issues in the specified range
* @throws GitLabApiException if any exception occurs
*/
public Pager<Issue> getIssues(Integer projectId, int itemsPerPage) throws GitLabApiException {
return (new Pager<Issue>(this, Issue.class, itemsPerPage, null, "projects", projectId, "issues"));
}
/**
* Get a single project issues.
*
* GET /projects/:id/issues/:issue_iid
*
* @param projectId the project ID to get the issue for
* @param issueId the internal ID of a project's issue
* @return the specified Issue instance
* @throws GitLabApiException if any exception occurs
*/
public Issue getIssue(Integer projectId, Integer issueId) throws GitLabApiException {
Response response = get(Response.Status.OK, getDefaultPerPageParam(), "projects", projectId, "issues", issueId);
return (response.readEntity(Issue.class));
}
/**
* Delete a project issue.
*
* DELETE /projects/:id/issues/:issue_iid
*
* @param projectId the project ID to delete the issue from
* @param issueId the internal ID of a project's issue
* @throws GitLabApiException if any exception occurs
*/
public void deleteIssue(Integer projectId, Integer issueId) throws GitLabApiException {
Response.Status expectedStatus = (isApiVersion(ApiVersion.V3) ? Response.Status.OK : Response.Status.NO_CONTENT);
delete(expectedStatus, getDefaultPerPageParam(), "projects", projectId, "issues", issueId);
}
/**
* Get a list of project snippets. This only returns the first page of snippets.
*
* GET /projects/:id/snippets
*
* @param projectId the project ID to get the snippets for
* @return a list of project's snippets
* @throws GitLabApiException if any exception occurs
*/
public List<Snippet> getSnippets(Integer projectId) throws GitLabApiException {
return (getSnippets(projectId, 1, this.getDefaultPerPage()));
}
/**
* Get a list of project snippets. This only returns the first page of snippets.
*
* GET /projects/:id/snippets
*
* @param projectId the project ID to get the snippets for
* @param page the page to get
* @param perPage the number of snippets per page
* @return a list of project's snippets for the specified range
* @throws GitLabApiException if any exception occurs
*/
public List<Snippet> getSnippets(Integer projectId, int page, int perPage) throws GitLabApiException {
Response response = get(Response.Status.OK, getPageQueryParams(page, perPage), "projects", projectId, "snippets");
return (response.readEntity(new GenericType<List<Snippet>>() {}));
}
/**
* Get a Pager of project's snippets.
*
* GET /projects/:id/snippets
*
* @param projectId the project ID to get the issues for
* @param itemsPerPage the number of snippets per page
* @return the Pager of snippets
* @throws GitLabApiException if any exception occurs
*/
public Pager<Snippet> getSnippets(Integer projectId, int itemsPerPage) throws GitLabApiException {
return (new Pager<Snippet>(this, Snippet.class, itemsPerPage, null, "projects", projectId, "snippets"));
}
/**
* Get a single of project snippet.
*
* GET /projects/:id/snippets/:snippet_id
*
* @param projectId the project ID to get the snippet for
* @param snippetId the ID of the project's snippet
* @return the specified project Snippet
* @throws GitLabApiException if any exception occurs
*/
public Snippet getSnippet(Integer projectId, Integer snippetId) throws GitLabApiException {
Response response = get(Response.Status.OK, null, "projects", projectId, "snippets", snippetId);
return (response.readEntity(Snippet.class));
}
/**
* Creates a new project snippet. The user must have permission to create new snippets.
*
* POST /projects/:id/snippets
*
* @param projectId the ID of the project owned by the authenticated user, required
* @param title the title of a snippet, required
* @param filename the name of a snippet file, required
* @param description the description of a snippet, optional
* @param code the content of a snippet, required
* @param visibility the snippet's visibility, required
* @return a Snippet instance with info on the created snippet
* @throws GitLabApiException if any exception occurs
*/
public Snippet createSnippet(Integer projectId, String title, String filename, String description,
String code, Visibility visibility) throws GitLabApiException {
GitLabApiForm formData = new GitLabApiForm()
.withParam("title", title, true)
.withParam("file_name", filename, true)
.withParam("description", description)
.withParam("code", code, true)
.withParam("visibility", visibility, true);
Response response = post(Response.Status.CREATED, formData, "projects", projectId, "snippets");
return (response.readEntity(Snippet.class));
}
/**
* Updates an existing project snippet. The user must have permission to change an existing snippet.
*
* PUT /projects/:id/snippets/:snippet_id
*
* @param projectId the ID of the project owned by the authenticated user, required
* @param snippetId the ID of a project's snippet, required
* @param title the title of a snippet, optional
* @param filename the name of a snippet file, optional
* @param description the description of a snippet, optioptionalonal
* @param code the content of a snippet, optional
* @param visibility the snippet's visibility, reqoptionaluired
* @return a Snippet instance with info on the updated snippet
* @throws GitLabApiException if any exception occurs
*/
public Snippet updateSnippet(Integer projectId, Integer snippetId, String title, String filename, String description,
String code, Visibility visibility) throws GitLabApiException {
GitLabApiForm formData = new GitLabApiForm()
.withParam("title", title)
.withParam("file_name", filename)
.withParam("description", description)
.withParam("code", code)
.withParam("visibility", visibility);
Response response = put(Response.Status.OK, formData.asMap(), "projects", projectId, "snippets", snippetId);
return (response.readEntity(Snippet.class));
}
/*
* Deletes an existing project snippet. This is an idempotent function and deleting a
* non-existent snippet does not cause an error.
*
* DELETE /projects/:id/snippets/:snippet_id
*
* @param projectId the project ID of the snippet
* @param snippetId the ID of the project's snippet
* @throws GitLabApiException if any exception occurs
*/
public void deleteSnippet(Integer projectId, Integer snippetId) throws GitLabApiException {
delete(Response.Status.NO_CONTENT, null, "projects", projectId, "snippets", snippetId);
}
/*
* Get the raw project snippet as plain text.
*
* GET /projects/:id/snippets/:snippet_id/raw
*
* @param projectId the project ID of the snippet
* @param snippetId the ID of the project's snippet
* @throws GitLabApiException if any exception occurs
*/
public String getRawSnippetContent(Integer projectId, Integer snippetId) throws GitLabApiException {
Response response = get(Response.Status.OK, null, "projects", projectId, "snippets", snippetId, "raw");
return (response.readEntity(String.class));
}
}
| src/main/java/org/gitlab4j/api/ProjectApi.java | /*
* The MIT License (MIT)
*
* Copyright (c) 2017 Greg Messner <[email protected]>
*
* 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 org.gitlab4j.api;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import javax.ws.rs.core.Form;
import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.Response;
import org.gitlab4j.api.GitLabApi.ApiVersion;
import org.gitlab4j.api.models.Event;
import org.gitlab4j.api.models.Issue;
import org.gitlab4j.api.models.Member;
import org.gitlab4j.api.models.Project;
import org.gitlab4j.api.models.ProjectHook;
import org.gitlab4j.api.models.Snippet;
import org.gitlab4j.api.models.Visibility;
/**
* This class provides an entry point to all the GitLab API project calls.
*/
public class ProjectApi extends AbstractApi implements Constants {
public ProjectApi(GitLabApi gitLabApi) {
super(gitLabApi);
}
/**
* Get a list of projects accessible by the authenticated user.
*
* GET /projects
*
* @return a list of projects accessible by the authenticated user
* @throws GitLabApiException if any exception occurs
*/
public List<Project> getProjects() throws GitLabApiException {
Response response = get(Response.Status.OK, getDefaultPerPageParam(), "projects");
return (response.readEntity(new GenericType<List<Project>>() {}));
}
/**
* Get a list of projects accessible by the authenticated user and in the specified page range.
*
* GET /projects
*
* @param page the page to get
* @param perPage the number of projects per page
* @return a list of projects accessible by the authenticated user
* @throws GitLabApiException if any exception occurs
*/
public List<Project> getProjects(int page, int perPage) throws GitLabApiException {
Response response = get(Response.Status.OK, getPageQueryParams(page, perPage), "projects");
return (response.readEntity(new GenericType<List<Project>>() { }));
}
/**
* Get a Pager instance of projects accessible by the authenticated user.
*
* GET /projects
*
* @param itemsPerPage the number of Project instances that will be fetched per page
* @return a Pager instance of projects accessible by the authenticated user
* @throws GitLabApiException if any exception occurs
*/
public Pager<Project> getProjects(int itemsPerPage) throws GitLabApiException {
return (new Pager<Project>(this, Project.class, itemsPerPage, null, "projects"));
}
/**
* Get a list of projects accessible by the authenticated user and matching the supplied filter parameters.
* All filter parameters are optional.
*
* GET /projects
*
* @param archived limit by archived status
* @param visibility limit by visibility public, internal, or private
* @param orderBy return projects ordered by id, name, path, created_at, updated_at, or last_activity_at fields, default is created_at
* @param sort return projects sorted in asc or desc order. Default is desc
* @param search return list of projects matching the search criteria
* @param simple return only the ID, URL, name, and path of each project
* @param owned limit by projects owned by the current user
* @param membership limit by projects that the current user is a member of
* @param starred limit by projects starred by the current user
* @param statistics include project statistics
* @return a list of projects accessible by the authenticated user and matching the supplied parameters
* @throws GitLabApiException if any exception occurs
* @deprecated Will be removed in version 5.0, replaced by {@link #getProjects(Boolean, Visibility,
* Constants.ProjectOrderBy, Constants.SortOrder, String, Boolean, Boolean, Boolean, Boolean, Boolean)}
*/
public List<Project> getProjects(Boolean archived, Visibility visibility, String orderBy,
String sort, String search, Boolean simple, Boolean owned, Boolean membership,
Boolean starred, Boolean statistics) throws GitLabApiException {
GitLabApiForm formData = new GitLabApiForm()
.withParam("archived", archived)
.withParam("visibility", visibility)
.withParam("order_by", orderBy)
.withParam("sort", sort)
.withParam("search", search)
.withParam("simple", simple)
.withParam("owned", owned)
.withParam("membership", membership)
.withParam("starred", starred)
.withParam("statistics", statistics)
.withParam(PER_PAGE_PARAM, getDefaultPerPage());
Response response = get(Response.Status.OK, formData.asMap(), "projects");
return (response.readEntity(new GenericType<List<Project>>() {}));
}
/**
* Get a list of projects accessible by the authenticated user and matching the supplied filter parameters.
* All filter parameters are optional.
*
* GET /projects
*
* @param archived limit by archived status
* @param visibility limit by visibility public, internal, or private
* @param orderBy return projects ordered by ID, NAME, PATH, CREATED_AT, UPDATED_AT, or
* LAST_ACTIVITY_AT fields, default is CREATED_AT
* @param sort return projects sorted in asc or desc order. Default is desc
* @param search return list of projects matching the search criteria
* @param simple return only the ID, URL, name, and path of each project
* @param owned limit by projects owned by the current user
* @param membership limit by projects that the current user is a member of
* @param starred limit by projects starred by the current user
* @param statistics include project statistics
* @return a list of projects accessible by the authenticated user and matching the supplied parameters
* @throws GitLabApiException if any exception occurs
*/
public List<Project> getProjects(Boolean archived, Visibility visibility, ProjectOrderBy orderBy,
SortOrder sort, String search, Boolean simple, Boolean owned, Boolean membership,
Boolean starred, Boolean statistics) throws GitLabApiException {
GitLabApiForm formData = new GitLabApiForm()
.withParam("archived", archived)
.withParam("visibility", visibility)
.withParam("order_by", orderBy)
.withParam("sort", sort)
.withParam("search", search)
.withParam("simple", simple)
.withParam("owned", owned)
.withParam("membership", membership)
.withParam("starred", starred)
.withParam("statistics", statistics)
.withParam(PER_PAGE_PARAM, getDefaultPerPage());
Response response = get(Response.Status.OK, formData.asMap(), "projects");
return (response.readEntity(new GenericType<List<Project>>() {}));
}
/**
* Get a list of projects accessible by the authenticated user and matching the supplied filter parameters.
* All filter parameters are optional.
*
* GET /projects
*
* @param archived limit by archived status
* @param visibility limit by visibility public, internal, or private
* @param orderBy return projects ordered by ID, NAME, PATH, CREATED_AT, UPDATED_AT, or
* LAST_ACTIVITY_AT fields, default is CREATED_AT
* @param sort return projects sorted in asc or desc order. Default is desc
* @param search return list of projects matching the search criteria
* @param simple return only the ID, URL, name, and path of each project
* @param owned limit by projects owned by the current user
* @param membership limit by projects that the current user is a member of
* @param starred limit by projects starred by the current user
* @param statistics include project statistics
* @param page the page to get
* @param perPage the number of projects per page
* @return a list of projects accessible by the authenticated user and matching the supplied parameters
* @throws GitLabApiException if any exception occurs
*/
public List<Project> getProjects(Boolean archived, Visibility visibility, ProjectOrderBy orderBy,
SortOrder sort, String search, Boolean simple, Boolean owned, Boolean membership,
Boolean starred, Boolean statistics, int page, int perPage) throws GitLabApiException {
GitLabApiForm formData = new GitLabApiForm()
.withParam("archived", archived)
.withParam("visibility", visibility)
.withParam("order_by", orderBy)
.withParam("sort", sort)
.withParam("search", search)
.withParam("simple", simple)
.withParam("owned", owned)
.withParam("membership", membership)
.withParam("starred", starred)
.withParam("statistics", statistics)
.withParam(PAGE_PARAM, page)
.withParam(PER_PAGE_PARAM, perPage);
Response response = get(Response.Status.OK, formData.asMap(), "projects");
return (response.readEntity(new GenericType<List<Project>>() {}));
}
/**
* Get a Pager of projects accessible by the authenticated user and matching the supplied filter parameters.
* All filter parameters are optional.
*
* GET /projects
*
* @param archived limit by archived status
* @param visibility limit by visibility public, internal, or private
* @param orderBy return projects ordered by ID, NAME, PATH, CREATED_AT, UPDATED_AT, or
* LAST_ACTIVITY_AT fields, default is CREATED_AT
* @param sort return projects sorted in asc or desc order. Default is desc
* @param search return list of projects matching the search criteria
* @param simple return only the ID, URL, name, and path of each project
* @param owned limit by projects owned by the current user
* @param membership limit by projects that the current user is a member of
* @param starred limit by projects starred by the current user
* @param statistics include project statistics
* @param itemsPerPage the number of Project instances that will be fetched per page
* @return a Pager of projects accessible by the authenticated user and matching the supplied parameters
* @throws GitLabApiException if any exception occurs
*/
public Pager<Project> getProjects(Boolean archived, Visibility visibility, ProjectOrderBy orderBy,
SortOrder sort, String search, Boolean simple, Boolean owned, Boolean membership,
Boolean starred, Boolean statistics, int itemsPerPage) throws GitLabApiException {
GitLabApiForm formData = new GitLabApiForm()
.withParam("archived", archived)
.withParam("visibility", visibility)
.withParam("order_by", orderBy)
.withParam("sort", sort)
.withParam("search", search)
.withParam("simple", simple)
.withParam("owned", owned)
.withParam("membership", membership)
.withParam("starred", starred)
.withParam("statistics", statistics);
return (new Pager<Project>(this, Project.class, itemsPerPage, formData.asMap(), "projects"));
}
/**
* Get a list of projects accessible by the authenticated user that match the provided search string.
*
* GET /projects?search=search
*
* @param search the project name search criteria
* @return a list of projects accessible by the authenticated user that match the provided search string
* @throws GitLabApiException if any exception occurs
*/
public List<Project> getProjects(String search) throws GitLabApiException {
Form formData = new GitLabApiForm().withParam("search", search).withParam(PER_PAGE_PARAM, getDefaultPerPage());
Response response = get(Response.Status.OK, formData.asMap(), "projects");
return (response.readEntity(new GenericType<List<Project>>() {}));
}
/**
* Get a list of projects accessible by the authenticated user that match the provided search string.
*
* GET /projects?search=search
*
* @param search the project name search criteria
* @param page the page to get
* @param perPage the number of projects per page
* @return a list of projects accessible by the authenticated user that match the provided search string
* @throws GitLabApiException if any exception occurs
*/
public List<Project> getProjects(String search, int page, int perPage) throws GitLabApiException {
Form formData = new GitLabApiForm().withParam("search", search).withParam(PAGE_PARAM, page).withParam(PER_PAGE_PARAM, perPage);
Response response = get(Response.Status.OK, formData.asMap(), "projects");
return (response.readEntity(new GenericType<List<Project>>() {}));
}
/**
* Get a Pager of projects accessible by the authenticated user that match the provided search string.
*
* GET /projects?search=search
*
* @param search the project name search criteria
* @param itemsPerPage the number of Project instances that will be fetched per page
* @return a Pager of projects accessible by the authenticated user that match the provided search string
* @throws GitLabApiException if any exception occurs
*/
public Pager<Project> getProjects(String search, int itemsPerPage) throws GitLabApiException {
Form formData = new GitLabApiForm().withParam("search", search);
return (new Pager<Project>(this, Project.class, itemsPerPage, formData.asMap(), "projects"));
}
/**
* Get a list of projects that the authenticated user is a member of.
*
* GET /projects
*
* @return a list of projects that the authenticated user is a member of
* @throws GitLabApiException if any exception occurs
*/
public List<Project> getMemberProjects() throws GitLabApiException {
Form formData = new GitLabApiForm().withParam("membership", true).withParam(PER_PAGE_PARAM, getDefaultPerPage());
Response response = get(Response.Status.OK, formData.asMap(), "projects");
return (response.readEntity(new GenericType<List<Project>>() {}));
}
/**
* Get a list of projects that the authenticated user is a member of in the specified page range.
*
* GET /projects
*
* @param page the page to get
* @param perPage the number of projects per page
* @return a list of projects that the authenticated user is a member of
* @throws GitLabApiException if any exception occurs
*/
public List<Project> getMemberProjects(int page, int perPage) throws GitLabApiException {
Form formData = new GitLabApiForm().withParam("membership", true).withParam(PAGE_PARAM, page).withParam(PER_PAGE_PARAM, perPage);
Response response = get(Response.Status.OK, formData.asMap(), "projects");
return (response.readEntity(new GenericType<List<Project>>() {}));
}
/**
* Get a Pager of projects that the authenticated user is a member of.
*
* GET /projects
*
* @param itemsPerPage the number of Project instances that will be fetched per page
* @return a Pager o Project instances that the authenticated user is a member of
* @throws GitLabApiException if any exception occurs
*/
public Pager<Project> getMemberProjects(int itemsPerPage) throws GitLabApiException {
Form formData = new GitLabApiForm().withParam("membership", true);
return (new Pager<Project>(this, Project.class, itemsPerPage, formData.asMap(), "projects"));
}
/**
* Get a list of all GitLab projects (admin only).
*
* GET /projects/all
*
* @return a list of all GitLab projects
* @throws GitLabApiException if any exception occurs
* @deprecated Will be removed, no longer supported by the GitLab API
*/
public List<Project> getAllProjects() throws GitLabApiException {
if (!isApiVersion(ApiVersion.V3)) {
throw new GitLabApiException("Not supported by GitLab API version " + this.getApiVersion());
}
Form formData = new GitLabApiForm().withParam(PER_PAGE_PARAM, getDefaultPerPage());
Response response = get(Response.Status.OK, formData.asMap(), "projects", "all");
return (response.readEntity(new GenericType<List<Project>>() {}));
}
/**
* Get a list of projects owned by the authenticated user.
*
* GET /projects
*
* @return a list of projects owned by the authenticated user
* @throws GitLabApiException if any exception occurs
*/
public List<Project> getOwnedProjects() throws GitLabApiException {
Form formData = new GitLabApiForm().withParam("owned", true).withParam(PER_PAGE_PARAM, getDefaultPerPage());
Response response = get(Response.Status.OK, formData.asMap(), "projects");
return (response.readEntity(new GenericType<List<Project>>() { }));
}
/**
* Get a list of projects owned by the authenticated user in the specified page range.
*
* GET /projects
*
* @param page the page to get
* @param perPage the number of projects per page
* @return a list of projects owned by the authenticated user
* @throws GitLabApiException if any exception occurs
*/
public List<Project> getOwnedProjects(int page, int perPage) throws GitLabApiException {
Form formData = new GitLabApiForm().withParam("owned", true).withParam(PAGE_PARAM, page).withParam(PER_PAGE_PARAM, perPage);
Response response = get(Response.Status.OK, formData.asMap(), "projects");
return (response.readEntity(new GenericType<List<Project>>() {}));
}
/**
* Get a Pager of projects owned by the authenticated user.
*
* GET /projects
*
* @param itemsPerPage the number of Project instances that will be fetched per page
* @return a list of projects owned by the authenticated user
* @throws GitLabApiException if any exception occurs
*/
public Pager<Project> getOwnedProjects(int itemsPerPage) throws GitLabApiException {
Form formData = new GitLabApiForm().withParam("owned", true);
return (new Pager<Project>(this, Project.class, itemsPerPage, formData.asMap(), "projects"));
}
/**
* Get a list of projects starred by the authenticated user.
*
* GET /projects
*
* @return a list of projects starred by the authenticated user
* @throws GitLabApiException if any exception occurs
*/
public List<Project> getStarredProjects() throws GitLabApiException {
Form formData = new GitLabApiForm().withParam("starred", true).withParam(PER_PAGE_PARAM, getDefaultPerPage());
Response response = get(Response.Status.OK, formData.asMap(), "projects");
return (response.readEntity(new GenericType<List<Project>>() {}));
}
/**
* Get a list of projects starred by the authenticated user in the specified page range.
*
* GET /projects
*
* @param page the page to get
* @param perPage the number of projects per page
* @return a list of projects starred by the authenticated user
* @throws GitLabApiException if any exception occurs
*/
public List<Project> getStarredProjects(int page, int perPage) throws GitLabApiException {
Form formData = new GitLabApiForm().withParam("starred", true).withParam(PAGE_PARAM, page).withParam(PER_PAGE_PARAM, perPage);
Response response = get(Response.Status.OK, formData.asMap(), "projects");
return (response.readEntity(new GenericType<List<Project>>() {}));
}
/**
* Get a Pager of projects starred by the authenticated user.
*
* GET /projects
*
* @param itemsPerPage the number of Project instances that will be fetched per page
* @return a Pager of projects starred by the authenticated user
* @throws GitLabApiException if any exception occurs
*/
public Pager<Project> getStarredProjects(int itemsPerPage) throws GitLabApiException {
Form formData = new GitLabApiForm().withParam("starred", true).withParam(PER_PAGE_PARAM, getDefaultPerPage());
return (new Pager<Project>(this, Project.class, itemsPerPage, formData.asMap(), "projects"));
}
/**
* Get a specific project, which is owned by the authentication user.
*
* GET /projects/:id
*
* @param projectId the ID of the project to get
* @return the specified project
* @throws GitLabApiException if any exception occurs
*/
public Project getProject(Integer projectId) throws GitLabApiException {
Response response = get(Response.Status.OK, null, "projects", projectId);
return (response.readEntity(Project.class));
}
/**
* Get a specific project, which is owned by the authentication user.
*
* GET /projects/:id
*
* @param namespace the name of the project namespace or group
* @param project the name of the project to get
* @return the specified project
* @throws GitLabApiException if any exception occurs
*/
public Project getProject(String namespace, String project) throws GitLabApiException {
if (namespace == null) {
throw new RuntimeException("namespace cannot be null");
}
if (project == null) {
throw new RuntimeException("project cannot be null");
}
String projectPath = null;
try {
projectPath = URLEncoder.encode(namespace + "/" + project, "UTF-8");
} catch (UnsupportedEncodingException uee) {
throw (new GitLabApiException(uee));
}
Response response = get(Response.Status.OK, null, "projects", projectPath);
return (response.readEntity(Project.class));
}
/**
* Create a new project in the specified group.
*
* @param groupId the group ID to create the project under
* @param projectName the name of the project top create
* @return the created project
* @throws GitLabApiException if any exception occurs
*/
public Project createProject(Integer groupId, String projectName) throws GitLabApiException {
GitLabApiForm formData = new GitLabApiForm().withParam("namespace_id", groupId).withParam("name", projectName, true);
Response response = post(Response.Status.CREATED, formData, "projects");
return (response.readEntity(Project.class));
}
/**
* Create a new project with the current user's namespace.
*
* @param projectName the name of the project top create
* @return the created project
* @throws GitLabApiException if any exception occurs
*/
public Project createProject(String projectName) throws GitLabApiException {
GitLabApiForm formData = new GitLabApiForm().withParam("name", projectName, true);
Response response = post(Response.Status.CREATED, formData, "projects");
return (response.readEntity(Project.class));
}
/**
* Creates new project owned by the current user.
*
* @param project the Project instance with the configuration for the new project
* @return a Project instance with the newly created project info
* @throws GitLabApiException if any exception occurs
*/
public Project createProject(Project project) throws GitLabApiException {
return (createProject(project, null));
}
/**
* Creates new project owned by the current user. The following properties on the Project instance
* are utilized in the creation of the project:
*
* name (name or path are required) - new project name
* path (name or path are required) - new project path
* defaultBranch (optional) - master by default
* description (optional) - short project description
* visibility (optional) - Limit by visibility public, internal, or private
* visibilityLevel (optional)
* issuesEnabled (optional) - Enable issues for this project
* mergeRequestsEnabled (optional) - Enable merge requests for this project
* wikiEnabled (optional) - Enable wiki for this project
* snippetsEnabled (optional) - Enable snippets for this project
* jobsEnabled (optional) - Enable jobs for this project
* containerRegistryEnabled (optional) - Enable container registry for this project
* sharedRunnersEnabled (optional) - Enable shared runners for this project
* publicJobs (optional) - If true, jobs can be viewed by non-project-members
* onlyAllowMergeIfPipelineSucceeds (optional) - Set whether merge requests can only be merged with successful jobs
* onlyAllowMergeIfAllDiscussionsAreResolved (optional) - Set whether merge requests can only be merged when all the discussions are resolved
* lLfsEnabled (optional) - Enable LFS
* requestAccessEnabled (optional) - Allow users to request member access
* repositoryStorage (optional) - Which storage shard the repository is on. Available only to admins
* approvalsBeforeMerge (optional) - How many approvers should approve merge request by default
*
* @param project the Project instance with the configuration for the new project
* @param importUrl the URL to import the repository from
* @return a Project instance with the newly created project info
* @throws GitLabApiException if any exception occurs
*/
public Project createProject(Project project, String importUrl) throws GitLabApiException {
if (project == null) {
return (null);
}
String name = project.getName();
String path = project.getPath();
if ((name == null || name.trim().length() == 0) && (path == null || path.trim().length() == 0)) {
return (null);
}
GitLabApiForm formData = new GitLabApiForm()
.withParam("name", name)
.withParam("path", path)
.withParam("default_branch", project.getDefaultBranch())
.withParam("description", project.getDescription())
.withParam("issues_enabled", project.getIssuesEnabled())
.withParam("merge_requests_enabled", project.getMergeRequestsEnabled())
.withParam("jobs_enabled", project.getJobsEnabled())
.withParam("wiki_enabled", project.getWikiEnabled())
.withParam("container_registry_enabled", project.getContainerRegistryEnabled())
.withParam("snippets_enabled", project.getSnippetsEnabled())
.withParam("shared_runners_enabled", project.getSharedRunnersEnabled())
.withParam("public_jobs", project.getPublicJobs())
.withParam("visibility_level", project.getVisibilityLevel())
.withParam("only_allow_merge_if_pipeline_succeeds", project.getOnlyAllowMergeIfPipelineSucceeds())
.withParam("only_allow_merge_if_all_discussions_are_resolved", project.getOnlyAllowMergeIfAllDiscussionsAreResolved())
.withParam("lfs_enabled", project.getLfsEnabled())
.withParam("request_access_enabled", project.getRequestAccessEnabled())
.withParam("repository_storage", project.getRepositoryStorage())
.withParam("approvals_before_merge", project.getApprovalsBeforeMerge())
.withParam("import_url", importUrl);
if (isApiVersion(ApiVersion.V3)) {
boolean isPublic = (project.getPublic() != null ? project.getPublic() : project.getVisibility() == Visibility.PUBLIC);
formData.withParam("public", isPublic);
} else {
Visibility visibility = (project.getVisibility() != null ? project.getVisibility() :
project.getPublic() == Boolean.TRUE ? Visibility.PUBLIC : null);
formData.withParam("visibility", visibility);
}
if (project.getNamespace() != null) {
formData.withParam("namespace_id", project.getNamespace().getId());
}
Response response = post(Response.Status.CREATED, formData, "projects");
return (response.readEntity(Project.class));
}
/**
* Creates a Project
*
* @param name The name of the project
* @param namespaceId The Namespace for the new project, otherwise null indicates to use the GitLab default (user)
* @param description A description for the project, null otherwise
* @param issuesEnabled Whether Issues should be enabled, otherwise null indicates to use GitLab default
* @param mergeRequestsEnabled Whether Merge Requests should be enabled, otherwise null indicates to use GitLab default
* @param wikiEnabled Whether a Wiki should be enabled, otherwise null indicates to use GitLab default
* @param snippetsEnabled Whether Snippets should be enabled, otherwise null indicates to use GitLab default
* @param visibility The visibility of the project, otherwise null indicates to use GitLab default
* @param visibilityLevel The visibility level of the project, otherwise null indicates to use GitLab default
* @param importUrl The Import URL for the project, otherwise null
* @return the GitLab Project
* @throws GitLabApiException if any exception occurs
*/
public Project createProject(String name, Integer namespaceId, String description, Boolean issuesEnabled, Boolean mergeRequestsEnabled,
Boolean wikiEnabled, Boolean snippetsEnabled, Visibility visibility, Integer visibilityLevel, String importUrl) throws GitLabApiException {
if (isApiVersion(ApiVersion.V3)) {
Boolean isPublic = Visibility.PUBLIC == visibility;
return (createProject(name, namespaceId, description, issuesEnabled, mergeRequestsEnabled,
wikiEnabled, snippetsEnabled, isPublic, visibilityLevel, importUrl));
}
if (name == null || name.trim().length() == 0) {
return (null);
}
GitLabApiForm formData = new GitLabApiForm()
.withParam("name", name, true)
.withParam("namespace_id", namespaceId)
.withParam("description", description)
.withParam("issues_enabled", issuesEnabled)
.withParam("merge_requests_enabled", mergeRequestsEnabled)
.withParam("wiki_enabled", wikiEnabled)
.withParam("snippets_enabled", snippetsEnabled)
.withParam("visibility_level", visibilityLevel)
.withParam("visibility", visibility)
.withParam("import_url", importUrl);
Response response = post(Response.Status.CREATED, formData, "projects");
return (response.readEntity(Project.class));
}
/**
* Creates a Project
*
* @param name The name of the project
* @param namespaceId The Namespace for the new project, otherwise null indicates to use the GitLab default (user)
* @param description A description for the project, null otherwise
* @param issuesEnabled Whether Issues should be enabled, otherwise null indicates to use GitLab default
* @param mergeRequestsEnabled Whether Merge Requests should be enabled, otherwise null indicates to use GitLab default
* @param wikiEnabled Whether a Wiki should be enabled, otherwise null indicates to use GitLab default
* @param snippetsEnabled Whether Snippets should be enabled, otherwise null indicates to use GitLab default
* @param isPublic Whether the project is public or private, if true same as setting visibilityLevel = 20, otherwise null indicates to use GitLab default
* @param visibilityLevel The visibility level of the project, otherwise null indicates to use GitLab default
* @param importUrl The Import URL for the project, otherwise null
* @return the GitLab Project
* @throws GitLabApiException if any exception occurs
* @deprecated As of release 4.2.0, replaced by {@link #createProject(String, Integer, String, Boolean, Boolean,
* Boolean, Boolean, Visibility, Integer, String)}
*/
@Deprecated
public Project createProject(String name, Integer namespaceId, String description, Boolean issuesEnabled, Boolean mergeRequestsEnabled,
Boolean wikiEnabled, Boolean snippetsEnabled, Boolean isPublic, Integer visibilityLevel, String importUrl) throws GitLabApiException {
if (name == null || name.trim().length() == 0) {
return (null);
}
GitLabApiForm formData = new GitLabApiForm()
.withParam("name", name, true)
.withParam("namespace_id", namespaceId)
.withParam("description", description)
.withParam("issues_enabled", issuesEnabled)
.withParam("merge_requests_enabled", mergeRequestsEnabled)
.withParam("wiki_enabled", wikiEnabled)
.withParam("snippets_enabled", snippetsEnabled)
.withParam("visibility_level", visibilityLevel)
.withParam("import_url", importUrl);
if (isApiVersion(ApiVersion.V3)) {
formData.withParam("public", isPublic);
} else if (isPublic) {
formData.withParam("visibility", Visibility.PUBLIC);
}
Response response = post(Response.Status.CREATED, formData, "projects");
return (response.readEntity(Project.class));
}
/**
* Updates a project. The following properties on the Project instance
* are utilized in the edit of the project, null values are not updated:
*
* id (required) - existing project id
* name (required) - project name
* path (optional) - project path
* defaultBranch (optional) - master by default
* description (optional) - short project description
* visibility (optional) - Limit by visibility public, internal, or private
* issuesEnabled (optional) - Enable issues for this project
* mergeRequestsEnabled (optional) - Enable merge requests for this project
* wikiEnabled (optional) - Enable wiki for this project
* snippetsEnabled (optional) - Enable snippets for this project
* jobsEnabled (optional) - Enable jobs for this project
* containerRegistryEnabled (optional) - Enable container registry for this project
* sharedRunnersEnabled (optional) - Enable shared runners for this project
* publicJobs (optional) - If true, jobs can be viewed by non-project-members
* onlyAllowMergeIfPipelineSucceeds (optional) - Set whether merge requests can only be merged with successful jobs
* onlyAllowMergeIfAllDiscussionsAreResolved (optional) - Set whether merge requests can only be merged when all the discussions are resolved
* lLfsEnabled (optional) - Enable LFS
* requestAccessEnabled (optional) - Allow users to request member access
* repositoryStorage (optional) - Which storage shard the repository is on. Available only to admins
* approvalsBeforeMerge (optional) - How many approvers should approve merge request by default
*
* NOTE: The following parameters specified by the GitLab API edit project are not supported:
* import_url
* tag_list array
* avatar
* ci_config_path
*
* @param project the Project instance with the configuration for the new project
* @return a Project instance with the newly updated project info
* @throws GitLabApiException if any exception occurs
*/
public Project updateProject(Project project) throws GitLabApiException {
if (project == null) {
throw new RuntimeException("Project instance cannot be null.");
}
Integer id = project.getId();
if (id == null) {
throw new RuntimeException("Project ID cannot be null.");
}
String name = project.getName();
if (name == null || name.trim().length() == 0) {
throw new RuntimeException("Project name cannot be null or empty.");
}
GitLabApiForm formData = new GitLabApiForm()
.withParam("name", name, true)
.withParam("path", project.getPath())
.withParam("default_branch", project.getDefaultBranch())
.withParam("description", project.getDescription())
.withParam("issues_enabled", project.getIssuesEnabled())
.withParam("merge_requests_enabled", project.getMergeRequestsEnabled())
.withParam("jobs_enabled", project.getJobsEnabled())
.withParam("wiki_enabled", project.getWikiEnabled())
.withParam("snippets_enabled", project.getSnippetsEnabled())
.withParam("container_registry_enabled", project.getContainerRegistryEnabled())
.withParam("shared_runners_enabled", project.getSharedRunnersEnabled())
.withParam("public_jobs", project.getPublicJobs())
.withParam("only_allow_merge_if_pipeline_succeeds", project.getOnlyAllowMergeIfPipelineSucceeds())
.withParam("only_allow_merge_if_all_discussions_are_resolved", project.getOnlyAllowMergeIfAllDiscussionsAreResolved())
.withParam("lfs_enabled", project.getLfsEnabled())
.withParam("request_access_enabled", project.getRequestAccessEnabled())
.withParam("repository_storage", project.getRepositoryStorage())
.withParam("approvals_before_merge", project.getApprovalsBeforeMerge());
if (isApiVersion(ApiVersion.V3)) {
formData.withParam("visibility_level", project.getVisibilityLevel());
boolean isPublic = (project.getPublic() != null ? project.getPublic() : project.getVisibility() == Visibility.PUBLIC);
formData.withParam("public", isPublic);
} else {
Visibility visibility = (project.getVisibility() != null ? project.getVisibility() :
project.getPublic() == Boolean.TRUE ? Visibility.PUBLIC : null);
formData.withParam("visibility", visibility);
}
Response response = putWithFormData(Response.Status.OK, formData, "projects", id);
return (response.readEntity(Project.class));
}
/**
* Removes project with all resources(issues, merge requests etc).
*
* DELETE /projects/:id
*
* @param projectId the project ID to remove
* @throws GitLabApiException if any exception occurs
*/
public void deleteProject(Integer projectId) throws GitLabApiException {
if (projectId == null) {
throw new RuntimeException("projectId cannot be null");
}
Response.Status expectedStatus = (isApiVersion(ApiVersion.V3) ? Response.Status.OK : Response.Status.ACCEPTED);
delete(expectedStatus, null, "projects", projectId);
}
/**
* Removes project with all resources(issues, merge requests etc).
*
* DELETE /projects/:id
*
* @param project the Project instance to remove
* @throws GitLabApiException if any exception occurs
*/
public void deleteProject(Project project) throws GitLabApiException {
deleteProject(project.getId());
}
/**
* Get a list of project team members.
*
* GET /projects/:id/members
*
* @param projectId the project ID to get team members for
* @return the members belonging to the specified project
* @throws GitLabApiException if any exception occurs
*/
public List<Member> getMembers(Integer projectId) throws GitLabApiException {
Response response = get(Response.Status.OK, this.getDefaultPerPageParam(), "projects", projectId, "members");
return (response.readEntity(new GenericType<List<Member>>() {}));
}
/**
* Get a list of project team members in the specified page range.
*
* GET /projects/:id/members
*
* @param projectId the project ID to get team members for
* @param page the page to get
* @param perPage the number of Member instances per page
* @return the members belonging to the specified project
* @throws GitLabApiException if any exception occurs
*/
public List<Member> getMembers(Integer projectId, int page, int perPage) throws GitLabApiException {
Response response = get(Response.Status.OK, getPageQueryParams(page, perPage), "projects", projectId, "members");
return (response.readEntity(new GenericType<List<Member>>() {}));
}
/**
* Get a Pager of project team members.
*
* GET /projects/:id/members
*
* @param projectId the project ID to get team members for
* @param itemsPerPage the number of Project instances that will be fetched per page
* @return the members belonging to the specified project
* @throws GitLabApiException if any exception occurs
*/
public Pager<Member> getMembers(Integer projectId, int itemsPerPage) throws GitLabApiException {
return (new Pager<Member>(this, Member.class, itemsPerPage, null, "projects", projectId, "members"));
}
/**
* Gets a project team member.
*
* GET /projects/:id/members/:user_id
*
* @param projectId the project ID to get team member for
* @param userId the user ID of the member
* @return the member specified by the project ID/user ID pair
* @throws GitLabApiException if any exception occurs
*/
public Member getMember(Integer projectId, Integer userId) throws GitLabApiException {
Response response = get(Response.Status.OK, null, "projects", projectId, "members", userId);
return (response.readEntity(Member.class));
}
/**
* Adds a user to a project team. This is an idempotent method and can be called multiple times
* with the same parameters. Adding team membership to a user that is already a member does not
* affect the existing membership.
*
* POST /projects/:id/members
*
* @param projectId the project ID to add the team member to
* @param userId the user ID of the member to add
* @param accessLevel the access level for the new member
* @return the added member
* @throws GitLabApiException if any exception occurs
*/
public Member addMember(Integer projectId, Integer userId, Integer accessLevel) throws GitLabApiException {
GitLabApiForm formData = new GitLabApiForm().withParam("user_id", userId, true).withParam("access_level", accessLevel, true);
Response response = post(Response.Status.CREATED, formData, "projects", projectId, "members");
return (response.readEntity(Member.class));
}
/**
* Removes user from project team.
*
* DELETE /projects/:id/members/:user_id
*
* @param projectId the project ID to remove the team member from
* @param userId the user ID of the member to remove
* @throws GitLabApiException if any exception occurs
*/
public void removeMember(Integer projectId, Integer userId) throws GitLabApiException {
Response.Status expectedStatus = (isApiVersion(ApiVersion.V3) ? Response.Status.OK : Response.Status.NO_CONTENT);
delete(expectedStatus, null, "projects", projectId, "members", userId);
}
/**
* Get the project events for specific project. Sorted from newest to latest.
*
* GET /projects/:id/events
*
* @param projectId the project ID to get events for
* @return the project events for the specified project
* @throws GitLabApiException if any exception occurs
*/
public List<Event> getProjectEvents(Integer projectId) throws GitLabApiException {
Response response = get(Response.Status.OK, getDefaultPerPageParam(), "projects", projectId, "events");
return (response.readEntity(new GenericType<List<Event>>() {}));
}
/**
* Get the project events for specific project. Sorted from newest to latest in the specified page range.
*
* GET /projects/:id/events
*
* @param projectId the project ID to get events for
* @param page the page to get
* @param perPage the number of Event instances per page
* @return the project events for the specified project
* @throws GitLabApiException if any exception occurs
*/
public List<Event> getProjectEvents(Integer projectId, int page, int perPage) throws GitLabApiException {
Response response = get(Response.Status.OK, getPageQueryParams(page, perPage), "projects", projectId, "events");
return (response.readEntity(new GenericType<List<Event>>() {}));
}
/**
* Get a Pager of project events for specific project. Sorted from newest to latest.
*
* GET /projects/:id/events
*
* @param projectId the project ID to get events for
* @param itemsPerPage the number of Project instances that will be fetched per page
* @return a Pager of project events for the specified project
* @throws GitLabApiException if any exception occurs
*/
public Pager<Event> getProjectEvents(Integer projectId, int itemsPerPage) throws GitLabApiException {
return (new Pager<Event>(this, Event.class, itemsPerPage, null, "projects", projectId, "events"));
}
/**
* Get list of project hooks.
*
* GET /projects/:id/hooks
*
* @param projectId the project ID to get project hooks for
* @return a list of project hooks for the specified project
* @throws GitLabApiException if any exception occurs
*/
public List<ProjectHook> getHooks(Integer projectId) throws GitLabApiException {
Response response = get(Response.Status.OK, getDefaultPerPageParam(), "projects", projectId, "hooks");
return (response.readEntity(new GenericType<List<ProjectHook>>() {}));
}
/**
* Get list of project hooks in the specified page range.
*
* GET /projects/:id/hooks
*
* @param projectId the project ID to get project hooks for
* @param page the page to get
* @param perPage the number of ProjectHook instances per page
* @return a list of project hooks for the specified project in the specified page range
* @throws GitLabApiException if any exception occurs
*/
public List<ProjectHook> getHooks(Integer projectId, int page, int perPage) throws GitLabApiException {
Response response = get(Response.Status.OK, getPageQueryParams(page, perPage), "projects", projectId, "hooks");
return (response.readEntity(new GenericType<List<ProjectHook>>() {}));
}
/**
* Get Pager of project hooks.
*
* GET /projects/:id/hooks
*
* @param projectId the project ID to get project hooks for
* @param itemsPerPage the number of Project instances that will be fetched per page
* @return a Pager of project hooks for the specified project
* @throws GitLabApiException if any exception occurs
*/
public Pager<ProjectHook> getHooks(Integer projectId, int itemsPerPage) throws GitLabApiException {
return (new Pager<ProjectHook>(this, ProjectHook.class, itemsPerPage, null, "projects", projectId, "hooks"));
}
/**
* Get a specific hook for project.
*
* GET /projects/:id/hooks/:hook_id
*
* @param projectId the project ID to get the hook for
* @param hookId the ID of the hook to get
* @return the project hook for the specified project ID/hook ID pair
* @throws GitLabApiException if any exception occurs
*/
public ProjectHook getHook(Integer projectId, Integer hookId) throws GitLabApiException {
Response response = get(Response.Status.OK, null, "projects", projectId, "hooks", hookId);
return (response.readEntity(ProjectHook.class));
}
/**
* Adds a hook to project.
*
* POST /projects/:id/hooks
*
* @param projectName the name of the project
* @param url the callback URL for the hook
* @param enabledHooks a ProjectHook instance specifying which hooks to enable
* @param enableSslVerification enable SSL verification
* @param secretToken the secret token to pass back to the hook
* @return the added ProjectHook instance
* @throws GitLabApiException if any exception occurs
*/
public ProjectHook addHook(String projectName, String url, ProjectHook enabledHooks, boolean enableSslVerification, String secretToken) throws GitLabApiException {
if (projectName == null) {
return (null);
}
GitLabApiForm formData = new GitLabApiForm()
.withParam("url", url, true)
.withParam("push_events", enabledHooks.getPushEvents(), false)
.withParam("issues_events", enabledHooks.getIssuesEvents(), false)
.withParam("merge_requests_events", enabledHooks.getMergeRequestsEvents(), false)
.withParam("tag_push_events", enabledHooks.getTagPushEvents(), false)
.withParam("note_events", enabledHooks.getNoteEvents(), false)
.withParam("job_events", enabledHooks.getJobEvents(), false)
.withParam("pipeline_events", enabledHooks.getPipelineEvents(), false)
.withParam("wiki_events", enabledHooks.getWikiPageEvents(), false)
.withParam("enable_ssl_verification", enabledHooks.getEnableSslVerification())
.withParam("token", secretToken, false);
Response response = post(Response.Status.CREATED, formData, "projects", projectName, "hooks");
return (response.readEntity(ProjectHook.class));
}
/**
* Adds a hook to project.
*
* POST /projects/:id/hooks
*
* @param projectId the project ID to add the project hook to
* @param url the callback URL for the hook
* @param enabledHooks a ProjectHook instance specifying which hooks to enable
* @param enableSslVerification enable SSL verification
* @param secretToken the secret token to pass back to the hook
* @return the added ProjectHook instance
* @throws GitLabApiException if any exception occurs
*/
public ProjectHook addHook(Integer projectId, String url, ProjectHook enabledHooks, boolean enableSslVerification, String secretToken) throws GitLabApiException {
if (projectId == null) {
return (null);
}
GitLabApiForm formData = new GitLabApiForm()
.withParam("url", url, true)
.withParam("push_events", enabledHooks.getPushEvents(), false)
.withParam("issues_events", enabledHooks.getIssuesEvents(), false)
.withParam("merge_requests_events", enabledHooks.getMergeRequestsEvents(), false)
.withParam("tag_push_events", enabledHooks.getTagPushEvents(), false)
.withParam("note_events", enabledHooks.getNoteEvents(), false)
.withParam("job_events", enabledHooks.getJobEvents(), false)
.withParam("pipeline_events", enabledHooks.getPipelineEvents(), false)
.withParam("wiki_events", enabledHooks.getWikiPageEvents(), false)
.withParam("enable_ssl_verification", enabledHooks.getEnableSslVerification())
.withParam("token", secretToken, false);
Response response = post(Response.Status.CREATED, formData, "projects", projectId, "hooks");
return (response.readEntity(ProjectHook.class));
}
/**
* Adds a hook to project.
*
* POST /projects/:id/hooks
*
* @param project the Project instance to add the project hook to
* @param url the callback URL for the hook
* @param enabledHooks a ProjectHook instance specifying which hooks to enable
* @param enableSslVerification enable SSL verification
* @param secretToken the secret token to pass back to the hook
* @return the added ProjectHook instance
* @throws GitLabApiException if any exception occurs
*/
public ProjectHook addHook(Project project, String url, ProjectHook enabledHooks, boolean enableSslVerification, String secretToken) throws GitLabApiException {
if (project == null) {
return (null);
}
return (addHook(project.getId(), url, enabledHooks, enableSslVerification, secretToken));
}
/**
* Adds a hook to project.
*
* POST /projects/:id/hooks
*
* @param project the Project instance to add the project hook to
* @param url the callback URL for the hook
* @param doPushEvents flag specifying whether to do push events
* @param doIssuesEvents flag specifying whether to do issues events
* @param doMergeRequestsEvents flag specifying whether to do merge requests events
* @return the added ProjectHook instance
* @throws GitLabApiException if any exception occurs
*/
public ProjectHook addHook(Project project, String url, boolean doPushEvents, boolean doIssuesEvents, boolean doMergeRequestsEvents) throws GitLabApiException {
if (project == null) {
return (null);
}
return (addHook(project.getId(), url, doPushEvents, doIssuesEvents, doMergeRequestsEvents));
}
/**
* Adds a hook to project.
*
* POST /projects/:id/hooks
*
* @param projectId the project ID to add the project hook to
* @param url the callback URL for the hook
* @param doPushEvents flag specifying whether to do push events
* @param doIssuesEvents flag specifying whether to do issues events
* @param doMergeRequestsEvents flag specifying whether to do merge requests events
* @return the added ProjectHook instance
* @throws GitLabApiException if any exception occurs
*/
public ProjectHook addHook(Integer projectId, String url, boolean doPushEvents, boolean doIssuesEvents, boolean doMergeRequestsEvents) throws GitLabApiException {
GitLabApiForm formData = new GitLabApiForm()
.withParam("url", url)
.withParam("push_events", doPushEvents)
.withParam("issues_enabled", doIssuesEvents)
.withParam("merge_requests_events", doMergeRequestsEvents);
Response response = post(Response.Status.CREATED, formData, "projects", projectId, "hooks");
return (response.readEntity(ProjectHook.class));
}
/**
* Deletes a hook from the project.
*
* DELETE /projects/:id/hooks/:hook_id
*
* @param projectId the project ID to delete the project hook from
* @param hookId the project hook ID to delete
* @throws GitLabApiException if any exception occurs
*/
public void deleteHook(Integer projectId, Integer hookId) throws GitLabApiException {
Response.Status expectedStatus = (isApiVersion(ApiVersion.V3) ? Response.Status.OK : Response.Status.NO_CONTENT);
delete(expectedStatus, null, "projects", projectId, "hooks", hookId);
}
/**
* Deletes a hook from the project.
*
* DELETE /projects/:id/hooks/:hook_id
*
* @param hook the ProjectHook instance to remove
* @throws GitLabApiException if any exception occurs
*/
public void deleteHook(ProjectHook hook) throws GitLabApiException {
deleteHook(hook.getProjectId(), hook.getId());
}
/**
* Modifies a hook for project.
*
* PUT /projects/:id/hooks/:hook_id
*
* @param hook the ProjectHook instance that contains the project hook info to modify
* @return the modified project hook
* @throws GitLabApiException if any exception occurs
*/
public ProjectHook modifyHook(ProjectHook hook) throws GitLabApiException {
GitLabApiForm formData = new GitLabApiForm()
.withParam("url", hook.getUrl(), true)
.withParam("push_events", hook.getPushEvents(), false)
.withParam("issues_events", hook.getIssuesEvents(), false)
.withParam("merge_requests_events", hook.getMergeRequestsEvents(), false)
.withParam("tag_push_events", hook.getTagPushEvents(), false)
.withParam("note_events", hook.getNoteEvents(), false)
.withParam("job_events", hook.getJobEvents(), false)
.withParam("pipeline_events", hook.getPipelineEvents(), false)
.withParam("wiki_events", hook.getWikiPageEvents(), false)
.withParam("enable_ssl_verification", hook.getEnableSslVerification(), false)
.withParam("token", hook.getToken(), false);
Response response = put(Response.Status.OK, formData.asMap(), "projects", hook.getProjectId(), "hooks", hook.getId());
return (response.readEntity(ProjectHook.class));
}
/**
* Get a list of project's issues. Only returns the first page
*
* GET /projects/:id/issues
*
* @param projectId the project ID to get the issues for
* @return a list of project's issues
* @throws GitLabApiException if any exception occurs
*/
public List<Issue> getIssues(Integer projectId) throws GitLabApiException {
Response response = get(Response.Status.OK, getDefaultPerPageParam(), "projects", projectId, "issues");
return (response.readEntity(new GenericType<List<Issue>>() {}));
}
/**
* Get a list of project's issues using the specified page and per page settings.
*
* GET /projects/:id/issues
*
* @param projectId the project ID to get the issues for
* @param page the page to get
* @param perPage the number of issues per page
* @return the list of issues in the specified range
* @throws GitLabApiException if any exception occurs
*/
public List<Issue> getIssues(Integer projectId, int page, int perPage) throws GitLabApiException {
Response response = get(Response.Status.OK, getPageQueryParams(page, perPage), "projects", projectId, "issues");
return (response.readEntity(new GenericType<List<Issue>>() {}));
}
/**
* Get a Pager of project's issues.
*
* GET /projects/:id/issues
*
* @param projectId the project ID to get the issues for
* @param itemsPerPage the number of issues per page
* @return the list of issues in the specified range
* @throws GitLabApiException if any exception occurs
*/
public Pager<Issue> getIssues(Integer projectId, int itemsPerPage) throws GitLabApiException {
return (new Pager<Issue>(this, Issue.class, itemsPerPage, null, "projects", projectId, "issues"));
}
/**
* Get a single project issues.
*
* GET /projects/:id/issues/:issue_iid
*
* @param projectId the project ID to get the issue for
* @param issueId the internal ID of a project's issue
* @return the specified Issue instance
* @throws GitLabApiException if any exception occurs
*/
public Issue getIssue(Integer projectId, Integer issueId) throws GitLabApiException {
Response response = get(Response.Status.OK, getDefaultPerPageParam(), "projects", projectId, "issues", issueId);
return (response.readEntity(Issue.class));
}
/**
* Delete a project issue.
*
* DELETE /projects/:id/issues/:issue_iid
*
* @param projectId the project ID to delete the issue from
* @param issueId the internal ID of a project's issue
* @throws GitLabApiException if any exception occurs
*/
public void deleteIssue(Integer projectId, Integer issueId) throws GitLabApiException {
Response.Status expectedStatus = (isApiVersion(ApiVersion.V3) ? Response.Status.OK : Response.Status.NO_CONTENT);
delete(expectedStatus, getDefaultPerPageParam(), "projects", projectId, "issues", issueId);
}
/**
* Get a list of project snippets. This only returns the first page of snippets.
*
* GET /projects/:id/snippets
*
* @param projectId the project ID to get the snippets for
* @return a list of project's snippets
* @throws GitLabApiException if any exception occurs
*/
public List<Snippet> getSnippets(Integer projectId) throws GitLabApiException {
return (getSnippets(projectId, 1, this.getDefaultPerPage()));
}
/**
* Get a list of project snippets. This only returns the first page of snippets.
*
* GET /projects/:id/snippets
*
* @param projectId the project ID to get the snippets for
* @param page the page to get
* @param perPage the number of snippets per page
* @return a list of project's snippets for the specified range
* @throws GitLabApiException if any exception occurs
*/
public List<Snippet> getSnippets(Integer projectId, int page, int perPage) throws GitLabApiException {
Response response = get(Response.Status.OK, getPageQueryParams(page, perPage), "projects", projectId, "snippets");
return (response.readEntity(new GenericType<List<Snippet>>() {}));
}
/**
* Get a Pager of project's snippets.
*
* GET /projects/:id/snippets
*
* @param projectId the project ID to get the issues for
* @param itemsPerPage the number of snippets per page
* @return the Pager of snippets
* @throws GitLabApiException if any exception occurs
*/
public Pager<Snippet> getSnippets(Integer projectId, int itemsPerPage) throws GitLabApiException {
return (new Pager<Snippet>(this, Snippet.class, itemsPerPage, null, "projects", projectId, "snippets"));
}
/**
* Get a single of project snippet.
*
* GET /projects/:id/snippets/:snippet_id
*
* @param projectId the project ID to get the snippet for
* @param snippetId the ID of the project's snippet
* @return the specified project Snippet
* @throws GitLabApiException if any exception occurs
*/
public Snippet getSnippet(Integer projectId, Integer snippetId) throws GitLabApiException {
Response response = get(Response.Status.OK, null, "projects", projectId, "snippets", snippetId);
return (response.readEntity(Snippet.class));
}
/**
* Creates a new project snippet. The user must have permission to create new snippets.
*
* POST /projects/:id/snippets
*
* @param id the ID of the project owned by the authenticated user, required
* @param title the title of a snippet, required
* @param fileName the name of a snippet file, required
* @param description the description of a snippet, optional
* @param code the content of a snippet, required
* @param visibility the snippet's visibility, required
* @return a Snippet instance with info on the created snippet
* @throws GitLabApiException if any exception occurs
*/
public Snippet createSnippet(Integer projectId, String title, String filename, String description,
String code, Visibility visibility) throws GitLabApiException {
GitLabApiForm formData = new GitLabApiForm()
.withParam("title", title, true)
.withParam("file_name", filename, true)
.withParam("description", description)
.withParam("code", code, true)
.withParam("visibility", visibility, true);
Response response = post(Response.Status.CREATED, formData, "projects", projectId, "snippets");
return (response.readEntity(Snippet.class));
}
/**
* Updates an existing project snippet. The user must have permission to change an existing snippet.
*
* PUT /projects/:id/snippets/:snippet_id
*
* @param id the ID of the project owned by the authenticated user, required
* @param snippetId the ID of a project's snippet, required
* @param title the title of a snippet, optional
* @param fileName the name of a snippet file, optional
* @param description the description of a snippet, optioptionalonal
* @param code the content of a snippet, optional
* @param visibility the snippet's visibility, reqoptionaluired
* @return a Snippet instance with info on the updated snippet
* @throws GitLabApiException if any exception occurs
*/
public Snippet updateSnippet(Integer projectId, Integer snippetId, String title, String filename, String description,
String code, Visibility visibility) throws GitLabApiException {
GitLabApiForm formData = new GitLabApiForm()
.withParam("title", title)
.withParam("file_name", filename)
.withParam("description", description)
.withParam("code", code)
.withParam("visibility", visibility);
Response response = put(Response.Status.OK, formData.asMap(), "projects", projectId, "snippets", snippetId);
return (response.readEntity(Snippet.class));
}
/*
* Deletes an existing project snippet. This is an idempotent function and deleting a
* non-existent snippet does not cause an error.
*
* DELETE /projects/:id/snippets/:snippet_id
*
* @param projectId the project ID of the snippet
* @param snippetId the ID of the project's snippet
* @throws GitLabApiException if any exception occurs
*/
public void deleteSnippet(Integer projectId, Integer snippetId) throws GitLabApiException {
delete(Response.Status.NO_CONTENT, null, "projects", projectId, "snippets", snippetId);
}
/*
* Get the raw project snippet as plain text.
*
* GET /projects/:id/snippets/:snippet_id/raw
*
* @param projectId the project ID of the snippet
* @param snippetId the ID of the project's snippet
* @throws GitLabApiException if any exception occurs
*/
public String getRawSnippetContent(Integer projectId, Integer snippetId) throws GitLabApiException {
Response response = get(Response.Status.OK, null, "projects", projectId, "snippets", snippetId, "raw");
return (response.readEntity(String.class));
}
}
| Fixed javadoc problems related to project snippets.
| src/main/java/org/gitlab4j/api/ProjectApi.java | Fixed javadoc problems related to project snippets. | <ide><path>rc/main/java/org/gitlab4j/api/ProjectApi.java
<ide> *
<ide> * POST /projects/:id/snippets
<ide> *
<del> * @param id the ID of the project owned by the authenticated user, required
<add> * @param projectId the ID of the project owned by the authenticated user, required
<ide> * @param title the title of a snippet, required
<del> * @param fileName the name of a snippet file, required
<add> * @param filename the name of a snippet file, required
<ide> * @param description the description of a snippet, optional
<ide> * @param code the content of a snippet, required
<ide> * @param visibility the snippet's visibility, required
<ide> *
<ide> * PUT /projects/:id/snippets/:snippet_id
<ide> *
<del> * @param id the ID of the project owned by the authenticated user, required
<add> * @param projectId the ID of the project owned by the authenticated user, required
<ide> * @param snippetId the ID of a project's snippet, required
<ide> * @param title the title of a snippet, optional
<del> * @param fileName the name of a snippet file, optional
<add> * @param filename the name of a snippet file, optional
<ide> * @param description the description of a snippet, optioptionalonal
<ide> * @param code the content of a snippet, optional
<ide> * @param visibility the snippet's visibility, reqoptionaluired |
|
Java | apache-2.0 | 05d0b745a165e8b09c9286a0f2afba8ec402f829 | 0 | factoryfx/factoryfx,factoryfx/factoryfx,factoryfx/factoryfx,factoryfx/factoryfx | package io.github.factoryfx.javafx.factoryviewmanager;
import io.github.factoryfx.factory.builder.FactoryContext;
import io.github.factoryfx.factory.jackson.ObjectMapperBuilder;
import io.github.factoryfx.factory.merge.DataMerger;
import io.github.factoryfx.factory.merge.MergeDiffInfo;
import io.github.factoryfx.factory.storage.migration.MigrationManager;
import io.github.factoryfx.factory.builder.FactoryTreeBuilder;
import io.github.factoryfx.factory.testfactories.ExampleFactoryA;
import io.github.factoryfx.factory.testfactories.ExampleFactoryB;
import io.github.factoryfx.factory.testfactories.ExampleLiveObjectA;
import io.github.factoryfx.microservice.rest.client.MicroserviceRestClient;
import io.github.factoryfx.server.Microservice;
import io.github.factoryfx.factory.storage.DataUpdate;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.mockito.Mockito;
import org.mockito.stubbing.Answer;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.function.Function;
public class FactoryEditManagerTest {
@TempDir
public Path tmpFolder;
@Test
@SuppressWarnings("unchecked")
public void test_export_import() throws IOException {
FactoryTreeBuilder<ExampleLiveObjectA, ExampleFactoryA> builder = new FactoryTreeBuilder<>(ExampleFactoryA.class, ctx->{
ExampleFactoryA initialFactory = new ExampleFactoryA();
initialFactory.stringAttribute.set("123");
return initialFactory;
});
Microservice<ExampleLiveObjectA, ExampleFactoryA> microservice = builder.microservice().build();
microservice.start();
MicroserviceRestClient<ExampleFactoryA> client = Mockito.mock(MicroserviceRestClient.class);
Mockito.when(client.prepareNewFactory()).then(invocation -> microservice.prepareNewFactory());
Mockito.when(client.updateCurrentFactory(Mockito.any(DataUpdate.class),Mockito.anyString())).then(invocation -> microservice.updateCurrentFactory(invocation.getArgument(0)));
FactoryEditManager<ExampleFactoryA> factoryEditManager = new FactoryEditManager<>(client, createDataMigrationManager());
factoryEditManager.runLaterExecuter= Runnable::run;
factoryEditManager.load();
Path target = Files.createFile(tmpFolder.resolve("fghfh.json"));
factoryEditManager.saveToFile(target);
// System.out.println(Files.readString(target));
Assertions.assertTrue(target.toFile().exists());
factoryEditManager.loadFromFile(target);
Assertions.assertEquals("123", factoryEditManager.getLoadedFactory().get().stringAttribute.get());
}
private MigrationManager<ExampleFactoryA> createDataMigrationManager() {
return new MigrationManager<>(ExampleFactoryA.class, ObjectMapperBuilder.build(), (root, d) -> { });
}
@Test
public void test_root_merge() {
ExampleFactoryA currentFactory = new ExampleFactoryA();
currentFactory = currentFactory.internal().finalise();
ExampleFactoryA updateFactory = new ExampleFactoryA();
updateFactory.referenceAttribute.set(new ExampleFactoryB());
updateFactory = updateFactory.internal().finalise();
DataMerger<ExampleFactoryA> dataMerger = new DataMerger<>(currentFactory,currentFactory.utility().copy(),updateFactory);
Assertions.assertNull(currentFactory.referenceAttribute.get());
Assertions.assertNotNull(updateFactory.referenceAttribute.get());
MergeDiffInfo<ExampleFactoryA> diff = dataMerger.mergeIntoCurrent((p) -> true);
Assertions.assertNotNull(currentFactory.referenceAttribute.get());
Assertions.assertEquals(1,diff.mergeInfos.size());
}
@Test
@SuppressWarnings("unchecked")
public void test_import_save_differentSystem() throws IOException {
Path target = Files.createFile(tmpFolder.resolve("fghfh.json"));
{
FactoryTreeBuilder<ExampleLiveObjectA, ExampleFactoryA> builder = new FactoryTreeBuilder<>(ExampleFactoryA.class,ctx->{
ExampleFactoryA factory = new ExampleFactoryA();
factory.referenceAttribute.set(ctx.get(ExampleFactoryB.class));
return factory;
});
builder.addSingleton(ExampleFactoryB.class, ctx-> {
return new ExampleFactoryB();
});
Microservice<ExampleLiveObjectA, ExampleFactoryA> microservice = builder.microservice().build();
microservice.start();
MicroserviceRestClient<ExampleFactoryA> client = Mockito.mock(MicroserviceRestClient.class);
Mockito.when(client.prepareNewFactory()).thenReturn(microservice.prepareNewFactory());
FactoryEditManager<ExampleFactoryA> factoryEditManager = new FactoryEditManager<>(client, createDataMigrationManager());
factoryEditManager.runLaterExecuter = Runnable::run;
factoryEditManager.load();
factoryEditManager.saveToFile(target);
}
{
FactoryTreeBuilder<ExampleLiveObjectA, ExampleFactoryA> builder = new FactoryTreeBuilder<>(ExampleFactoryA.class,ctx->{
ExampleFactoryA factory = new ExampleFactoryA();
return factory;
});
Microservice<ExampleLiveObjectA, ExampleFactoryA> microservice = builder.microservice().build();
microservice.start();
MicroserviceRestClient<ExampleFactoryA> client = Mockito.mock(MicroserviceRestClient.class);
Mockito.when(client.prepareNewFactory()).thenAnswer(invocation -> microservice.prepareNewFactory());
Mockito.when(client.updateCurrentFactory(Mockito.any(DataUpdate.class),Mockito.anyString())).thenAnswer((Answer) invocation -> {
Object[] args = invocation.getArguments();
return microservice.updateCurrentFactory((DataUpdate<ExampleFactoryA>) args[0]);
});
FactoryEditManager<ExampleFactoryA> factoryEditManager = new FactoryEditManager<>(client, createDataMigrationManager());
factoryEditManager.runLaterExecuter = Runnable::run;
factoryEditManager.load();
Assertions.assertNull(factoryEditManager.getLoadedFactory().get().referenceAttribute.get());
factoryEditManager.loadFromFile(target);
Assertions.assertNotNull(factoryEditManager.getLoadedFactory().get().referenceAttribute.get());
factoryEditManager.save("blub");
Assertions.assertNotNull(microservice.prepareNewFactory().root.referenceAttribute.get());
Assertions.assertNotNull(factoryEditManager.getLoadedFactory().get().referenceAttribute.get());
}
}
} | javafxFactoryEditing/src/test/java/io/github/factoryfx/javafx/factoryviewmanager/FactoryEditManagerTest.java | package io.github.factoryfx.javafx.factoryviewmanager;
import io.github.factoryfx.factory.jackson.ObjectMapperBuilder;
import io.github.factoryfx.factory.merge.DataMerger;
import io.github.factoryfx.factory.merge.MergeDiffInfo;
import io.github.factoryfx.factory.storage.migration.MigrationManager;
import io.github.factoryfx.factory.builder.FactoryTreeBuilder;
import io.github.factoryfx.factory.testfactories.ExampleFactoryA;
import io.github.factoryfx.factory.testfactories.ExampleFactoryB;
import io.github.factoryfx.factory.testfactories.ExampleLiveObjectA;
import io.github.factoryfx.microservice.rest.client.MicroserviceRestClient;
import io.github.factoryfx.server.Microservice;
import io.github.factoryfx.factory.storage.DataUpdate;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.mockito.Mockito;
import org.mockito.stubbing.Answer;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class FactoryEditManagerTest {
@TempDir
public Path tmpFolder;
@Test
@SuppressWarnings("unchecked")
public void test_export_import() throws IOException {
FactoryTreeBuilder<ExampleLiveObjectA, ExampleFactoryA> builder = new FactoryTreeBuilder<>(ExampleFactoryA.class, ctx->{
ExampleFactoryA initialFactory = new ExampleFactoryA();
initialFactory.stringAttribute.set("123");
return initialFactory;
});
Microservice<ExampleLiveObjectA, ExampleFactoryA> microservice = builder.microservice().build();
microservice.start();
MicroserviceRestClient<ExampleFactoryA> client = Mockito.mock(MicroserviceRestClient.class);
Mockito.when(client.prepareNewFactory()).then(invocation -> microservice.prepareNewFactory());
Mockito.when(client.updateCurrentFactory(Mockito.any(DataUpdate.class),Mockito.anyString())).then(invocation -> microservice.updateCurrentFactory(invocation.getArgument(0)));
FactoryEditManager<ExampleFactoryA> factoryEditManager = new FactoryEditManager<>(client, createDataMigrationManager());
factoryEditManager.runLaterExecuter= Runnable::run;
factoryEditManager.load();
Path target = Files.createFile(tmpFolder.resolve("fghfh.json"));
factoryEditManager.saveToFile(target);
// System.out.println(Files.readString(target));
Assertions.assertTrue(target.toFile().exists());
factoryEditManager.loadFromFile(target);
Assertions.assertEquals("123", factoryEditManager.getLoadedFactory().get().stringAttribute.get());
}
private MigrationManager<ExampleFactoryA> createDataMigrationManager() {
return new MigrationManager<>(ExampleFactoryA.class, ObjectMapperBuilder.build(), (root, d) -> { });
}
@Test
public void test_root_merge() {
ExampleFactoryA currentFactory = new ExampleFactoryA();
currentFactory = currentFactory.internal().finalise();
ExampleFactoryA updateFactory = new ExampleFactoryA();
updateFactory.referenceAttribute.set(new ExampleFactoryB());
updateFactory = updateFactory.internal().finalise();
DataMerger<ExampleFactoryA> dataMerger = new DataMerger<>(currentFactory,currentFactory.utility().copy(),updateFactory);
Assertions.assertNull(currentFactory.referenceAttribute.get());
Assertions.assertNotNull(updateFactory.referenceAttribute.get());
MergeDiffInfo<ExampleFactoryA> diff = dataMerger.mergeIntoCurrent((p) -> true);
Assertions.assertNotNull(currentFactory.referenceAttribute.get());
Assertions.assertEquals(1,diff.mergeInfos.size());
}
@Test
@SuppressWarnings("unchecked")
public void test_import_save_differentSystem() throws IOException {
Path target = Files.createFile(tmpFolder.resolve("fghfh.json"));
{
FactoryTreeBuilder<ExampleLiveObjectA, ExampleFactoryA> builder = new FactoryTreeBuilder<>(ExampleFactoryA.class,ctx->{
ExampleFactoryA factory = new ExampleFactoryA();
factory.referenceAttribute.set(new ExampleFactoryB());
return factory;
});
Microservice<ExampleLiveObjectA, ExampleFactoryA> microservice = builder.microservice().build();
microservice.start();
MicroserviceRestClient<ExampleFactoryA> client = Mockito.mock(MicroserviceRestClient.class);
Mockito.when(client.prepareNewFactory()).thenReturn(microservice.prepareNewFactory());
FactoryEditManager<ExampleFactoryA> factoryEditManager = new FactoryEditManager<>(client, createDataMigrationManager());
factoryEditManager.runLaterExecuter = Runnable::run;
factoryEditManager.load();
factoryEditManager.saveToFile(target);
}
{
FactoryTreeBuilder<ExampleLiveObjectA, ExampleFactoryA> builder = new FactoryTreeBuilder<>(ExampleFactoryA.class,ctx->{
ExampleFactoryA factory = new ExampleFactoryA();
return factory;
});
Microservice<ExampleLiveObjectA, ExampleFactoryA> microservice = builder.microservice().build();
microservice.start();
MicroserviceRestClient<ExampleFactoryA> client = Mockito.mock(MicroserviceRestClient.class);
Mockito.when(client.prepareNewFactory()).thenAnswer(invocation -> microservice.prepareNewFactory());
Mockito.when(client.updateCurrentFactory(Mockito.any(DataUpdate.class),Mockito.anyString())).thenAnswer((Answer) invocation -> {
Object[] args = invocation.getArguments();
return microservice.updateCurrentFactory((DataUpdate<ExampleFactoryA>) args[0]);
});
FactoryEditManager<ExampleFactoryA> factoryEditManager = new FactoryEditManager<>(client, createDataMigrationManager());
factoryEditManager.runLaterExecuter = Runnable::run;
factoryEditManager.load();
Assertions.assertNull(factoryEditManager.getLoadedFactory().get().referenceAttribute.get());
factoryEditManager.loadFromFile(target);
Assertions.assertNotNull(factoryEditManager.getLoadedFactory().get().referenceAttribute.get());
factoryEditManager.save("blub");
Assertions.assertNotNull(microservice.prepareNewFactory().root.referenceAttribute.get());
Assertions.assertNotNull(factoryEditManager.getLoadedFactory().get().referenceAttribute.get());
}
}
} | testfix
| javafxFactoryEditing/src/test/java/io/github/factoryfx/javafx/factoryviewmanager/FactoryEditManagerTest.java | testfix | <ide><path>avafxFactoryEditing/src/test/java/io/github/factoryfx/javafx/factoryviewmanager/FactoryEditManagerTest.java
<ide> package io.github.factoryfx.javafx.factoryviewmanager;
<ide>
<add>import io.github.factoryfx.factory.builder.FactoryContext;
<ide> import io.github.factoryfx.factory.jackson.ObjectMapperBuilder;
<ide> import io.github.factoryfx.factory.merge.DataMerger;
<ide> import io.github.factoryfx.factory.merge.MergeDiffInfo;
<ide> import java.io.IOException;
<ide> import java.nio.file.Files;
<ide> import java.nio.file.Path;
<add>import java.util.function.Function;
<ide>
<ide>
<ide> public class FactoryEditManagerTest {
<ide> {
<ide> FactoryTreeBuilder<ExampleLiveObjectA, ExampleFactoryA> builder = new FactoryTreeBuilder<>(ExampleFactoryA.class,ctx->{
<ide> ExampleFactoryA factory = new ExampleFactoryA();
<del> factory.referenceAttribute.set(new ExampleFactoryB());
<add> factory.referenceAttribute.set(ctx.get(ExampleFactoryB.class));
<ide> return factory;
<add> });
<add> builder.addSingleton(ExampleFactoryB.class, ctx-> {
<add> return new ExampleFactoryB();
<ide> });
<ide> Microservice<ExampleLiveObjectA, ExampleFactoryA> microservice = builder.microservice().build();
<ide> |
|
Java | apache-2.0 | 500c133d97ca5da0cc64da39785c4976452f56c4 | 0 | rmetzger/flink,tillrohrmann/flink,StephanEwen/incubator-flink,zjureel/flink,tony810430/flink,lincoln-lil/flink,wwjiang007/flink,clarkyzl/flink,twalthr/flink,jinglining/flink,godfreyhe/flink,apache/flink,rmetzger/flink,lincoln-lil/flink,lincoln-lil/flink,gyfora/flink,jinglining/flink,shaoxuan-wang/flink,aljoscha/flink,bowenli86/flink,twalthr/flink,jinglining/flink,tillrohrmann/flink,hequn8128/flink,tony810430/flink,tony810430/flink,bowenli86/flink,aljoscha/flink,zjureel/flink,wwjiang007/flink,twalthr/flink,tillrohrmann/flink,jinglining/flink,tony810430/flink,aljoscha/flink,shaoxuan-wang/flink,rmetzger/flink,hequn8128/flink,fhueske/flink,kaibozhou/flink,twalthr/flink,tony810430/flink,tzulitai/flink,xccui/flink,zentol/flink,godfreyhe/flink,GJL/flink,kl0u/flink,apache/flink,godfreyhe/flink,shaoxuan-wang/flink,twalthr/flink,bowenli86/flink,shaoxuan-wang/flink,GJL/flink,zjureel/flink,tillrohrmann/flink,clarkyzl/flink,kl0u/flink,tony810430/flink,wwjiang007/flink,GJL/flink,StephanEwen/incubator-flink,fhueske/flink,StephanEwen/incubator-flink,godfreyhe/flink,zjureel/flink,gyfora/flink,kl0u/flink,zentol/flink,darionyaphet/flink,mbode/flink,gyfora/flink,kaibozhou/flink,rmetzger/flink,fhueske/flink,fhueske/flink,xccui/flink,jinglining/flink,zjureel/flink,sunjincheng121/flink,tony810430/flink,kl0u/flink,fhueske/flink,lincoln-lil/flink,bowenli86/flink,zentol/flink,apache/flink,aljoscha/flink,StephanEwen/incubator-flink,mbode/flink,wwjiang007/flink,hequn8128/flink,tzulitai/flink,sunjincheng121/flink,hequn8128/flink,rmetzger/flink,sunjincheng121/flink,tzulitai/flink,rmetzger/flink,StephanEwen/incubator-flink,kaibozhou/flink,tzulitai/flink,wwjiang007/flink,xccui/flink,twalthr/flink,zentol/flink,darionyaphet/flink,wwjiang007/flink,kaibozhou/flink,sunjincheng121/flink,bowenli86/flink,sunjincheng121/flink,clarkyzl/flink,darionyaphet/flink,godfreyhe/flink,kaibozhou/flink,tillrohrmann/flink,GJL/flink,GJL/flink,gyfora/flink,greghogan/flink,tzulitai/flink,mbode/flink,gyfora/flink,greghogan/flink,gyfora/flink,kl0u/flink,lincoln-lil/flink,hequn8128/flink,shaoxuan-wang/flink,tillrohrmann/flink,tillrohrmann/flink,aljoscha/flink,clarkyzl/flink,twalthr/flink,lincoln-lil/flink,xccui/flink,xccui/flink,StephanEwen/incubator-flink,zentol/flink,zentol/flink,darionyaphet/flink,zentol/flink,shaoxuan-wang/flink,mbode/flink,zjureel/flink,apache/flink,xccui/flink,apache/flink,greghogan/flink,GJL/flink,rmetzger/flink,darionyaphet/flink,hequn8128/flink,aljoscha/flink,godfreyhe/flink,sunjincheng121/flink,xccui/flink,apache/flink,bowenli86/flink,gyfora/flink,greghogan/flink,lincoln-lil/flink,godfreyhe/flink,tzulitai/flink,mbode/flink,greghogan/flink,apache/flink,wwjiang007/flink,clarkyzl/flink,fhueske/flink,jinglining/flink,kl0u/flink,zjureel/flink,kaibozhou/flink,greghogan/flink | /*
* 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.flink.configuration.description;
/**
* Represents a line break in the {@link Description}.
*/
public class LineBreakElement implements InlineElement, BlockElement {
/**
* Creates a line break in the description.
*/
public static LineBreakElement linebreak() {
return new LineBreakElement();
}
private LineBreakElement() {
}
@Override
public void format(Formatter formatter) {
formatter.format(this);
}
}
| flink-core/src/main/java/org/apache/flink/configuration/description/LineBreakElement.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.flink.configuration.description;
/**
* Represents a line break in the {@link Description}.
*/
public class LineBreakElement implements BlockElement {
/**
* Creates a line break in the description.
*/
public static LineBreakElement linebreak() {
return new LineBreakElement();
}
private LineBreakElement() {
}
@Override
public void format(Formatter formatter) {
formatter.format(this);
}
}
| [hotfix][docs] make LineBreakElement also implement InlineElement
This allows line breaks in text block elements and may be useful, for example,
in starting a new line inside a list description element.
| flink-core/src/main/java/org/apache/flink/configuration/description/LineBreakElement.java | [hotfix][docs] make LineBreakElement also implement InlineElement | <ide><path>link-core/src/main/java/org/apache/flink/configuration/description/LineBreakElement.java
<ide> /**
<ide> * Represents a line break in the {@link Description}.
<ide> */
<del>public class LineBreakElement implements BlockElement {
<add>public class LineBreakElement implements InlineElement, BlockElement {
<ide>
<ide> /**
<ide> * Creates a line break in the description. |
|
Java | apache-2.0 | 65a98300afa8e6c9e9a67766e9ae1b3ab6ab3759 | 0 | lukeorland/joshua,thammegowda/incubator-joshua,lukeorland/joshua,thammegowda/incubator-joshua,fhieber/incubator-joshua,fhieber/incubator-joshua,thammegowda/incubator-joshua,fhieber/incubator-joshua,fhieber/incubator-joshua,lukeorland/joshua,fhieber/incubator-joshua,thammegowda/incubator-joshua,lukeorland/joshua,thammegowda/incubator-joshua,fhieber/incubator-joshua,thammegowda/incubator-joshua,fhieber/incubator-joshua,thammegowda/incubator-joshua,lukeorland/joshua,fhieber/incubator-joshua,thammegowda/incubator-joshua,lukeorland/joshua,lukeorland/joshua,thammegowda/incubator-joshua,lukeorland/joshua,thammegowda/incubator-joshua,lukeorland/joshua,fhieber/incubator-joshua | package joshua.decoder.ff.tm.hash_based;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import joshua.corpus.Vocabulary;
import joshua.decoder.Decoder;
import joshua.decoder.JoshuaConfiguration;
import joshua.decoder.JoshuaConfiguration.OOVItem;
import joshua.decoder.ff.FeatureFunction;
import joshua.decoder.ff.tm.AbstractGrammar;
import joshua.decoder.ff.tm.Rule;
import joshua.decoder.ff.tm.GrammarReader;
import joshua.decoder.ff.tm.Trie;
import joshua.decoder.ff.tm.format.HieroFormatReader;
import joshua.decoder.ff.tm.format.MosesFormatReader;
import joshua.decoder.ff.tm.format.SamtFormatReader;
import joshua.util.FormatUtils;
/**
* This class implements a memory-based bilingual BatchGrammar.
* <p>
* The rules are stored in a trie. Each trie node has: (1) RuleBin: a list of rules matching the
* french sides so far (2) A HashMap of next-layer trie nodes, the next french word used as the key
* in HashMap
*
* @author Zhifei Li <[email protected]>
* @author Matt Post <[email protected]
*/
public class MemoryBasedBatchGrammar extends AbstractGrammar {
// ===============================================================
// Instance Fields
// ===============================================================
/* The number of rules read. */
private int qtyRulesRead = 0;
/* The number of distinct source sides. */
private int qtyRuleBins = 0;
/* The trie root. */
private MemoryBasedTrie root = null;
/* The file containing the grammar. */
private String grammarFile;
private GrammarReader<Rule> modelReader;
/* Maximum source phrase length */
protected int maxSourcePhraseLength = 0;
/* Whether the grammar's rules contain regular expressions. */
private boolean isRegexpGrammar = false;
// ===============================================================
// Static Fields
// ===============================================================
// ===============================================================
// Constructors
// ===============================================================
public MemoryBasedBatchGrammar(JoshuaConfiguration joshuaConfiguration) {
super(joshuaConfiguration);
this.root = new MemoryBasedTrie();
this.joshuaConfiguration = joshuaConfiguration;
}
public MemoryBasedBatchGrammar(String owner, JoshuaConfiguration joshuaConfiguration) {
this(joshuaConfiguration);
this.owner = Vocabulary.id(owner);
}
public MemoryBasedBatchGrammar(GrammarReader<Rule> gr,JoshuaConfiguration joshuaConfiguration) {
// this.defaultOwner = Vocabulary.id(defaultOwner);
// this.defaultLHS = Vocabulary.id(defaultLHSSymbol);
this(joshuaConfiguration);
modelReader = gr;
}
public MemoryBasedBatchGrammar(String formatKeyword, String grammarFile, String owner,
String defaultLHSSymbol, int spanLimit, JoshuaConfiguration joshuaConfiguration) throws IOException {
this(joshuaConfiguration);
this.owner = Vocabulary.id(owner);
Vocabulary.id(defaultLHSSymbol);
this.spanLimit = spanLimit;
this.grammarFile = grammarFile;
this.setRegexpGrammar(formatKeyword.equals("regexp"));
// ==== loading grammar
this.modelReader = createReader(formatKeyword, grammarFile);
if (modelReader != null) {
modelReader.initialize();
for (Rule rule : modelReader)
if (rule != null) {
addRule(rule);
}
} else {
Decoder.LOG(1, "Couldn't create a GrammarReader for file " + grammarFile + " with format "
+ formatKeyword);
}
this.printGrammar();
}
protected GrammarReader<Rule> createReader(String format, String grammarFile) {
if (grammarFile != null) {
if ("hiero".equals(format) || "thrax".equals(format) || "regexp".equals(format)) {
return new HieroFormatReader(grammarFile);
} else if ("samt".equals(format)) {
return new SamtFormatReader(grammarFile);
} else if ("phrase".equals(format) || "moses".equals(format)) {
return new MosesFormatReader(grammarFile);
} else {
throw new RuntimeException(String.format("* FATAL: unknown grammar format '%s'", format));
}
}
return null;
}
// ===============================================================
// Methods
// ===============================================================
public void setSpanLimit(int spanLimit) {
this.spanLimit = spanLimit;
}
@Override
public int getNumRules() {
return this.qtyRulesRead;
}
@Override
public Rule constructManualRule(int lhs, int[] sourceWords, int[] targetWords,
float[] denseScores, int arity) {
return null;
}
/**
* if the span covered by the chart bin is greater than the limit, then return false
*/
public boolean hasRuleForSpan(int i, int j, int pathLength) {
if (this.spanLimit == -1) { // mono-glue grammar
return (i == 0);
} else {
// System.err.println(String.format("%s HASRULEFORSPAN(%d,%d,%d)/%d = %s", Vocabulary.word(this.owner), i, j, pathLength, spanLimit, pathLength <= this.spanLimit));
return (pathLength <= this.spanLimit);
}
}
public Trie getTrieRoot() {
return this.root;
}
/**
* Adds a rule to the grammar.
*/
public void addRule(Rule rule) {
// TODO: Why two increments?
this.qtyRulesRead++;
// if (owner == -1) {
// System.err.println("* FATAL: MemoryBasedBatchGrammar::addRule(): owner not set for grammar");
// System.exit(1);
// }
rule.setOwner(owner);
// === identify the position, and insert the trie nodes as necessary
MemoryBasedTrie pos = root;
int[] french = rule.getFrench();
maxSourcePhraseLength = Math.max(maxSourcePhraseLength, french.length);
for (int k = 0; k < french.length; k++) {
int curSymID = french[k];
/*
* Note that the nonTerminal symbol in the french is not cleaned (i.e., will be sth like
* [X,1]), but the symbol in the Trie has to be cleaned, so that the match does not care about
* the markup (i.e., [X,1] or [X,2] means the same thing, that is X) if
* (Vocabulary.nt(french[k])) { curSymID = modelReader.cleanNonTerminal(french[k]); if
* (logger.isLoggable(Level.FINEST)) logger.finest("Amended to: " + curSymID); }
*/
MemoryBasedTrie nextLayer = (MemoryBasedTrie) pos.match(curSymID);
if (null == nextLayer) {
nextLayer = new MemoryBasedTrie();
if (pos.hasExtensions() == false) {
pos.childrenTbl = new HashMap<Integer, MemoryBasedTrie>();
}
pos.childrenTbl.put(curSymID, nextLayer);
}
pos = nextLayer;
}
// === add the rule into the trie node
if (!pos.hasRules()) {
pos.ruleBin = new MemoryBasedRuleBin(rule.getArity(), rule.getFrench());
this.qtyRuleBins++;
}
pos.ruleBin.addRule(rule);
}
protected void printGrammar() {
Decoder.LOG(1, String.format("MemoryBasedBatchGrammar: Read %d rules with %d distinct source sides from '%s'",
this.qtyRulesRead, this.qtyRuleBins, grammarFile));
}
/**
* This returns true if the grammar contains rules that are regular expressions, possibly matching
* many different inputs.
*
* @return true if the grammar's rules may contain regular expressions.
*/
@Override
public boolean isRegexpGrammar() {
return this.isRegexpGrammar;
}
public void setRegexpGrammar(boolean value) {
this.isRegexpGrammar = value;
}
/**
* Returns the longest source phrase read.
*
* @return the longest source phrase read (nonterminal + terminal symbols).
*/
public int getMaxSourcePhraseLength() {
return maxSourcePhraseLength;
}
/***
* Takes an input word and creates an OOV rule in the current grammar for that word.
*
* @param sourceWord
* @param featureFunctions
*/
@Override
public void addOOVRules(int sourceWord, List<FeatureFunction> featureFunctions) {
// TODO: _OOV shouldn't be outright added, since the word might not be OOV for the LM (but now almost
// certainly is)
final int targetWord = this.joshuaConfiguration.mark_oovs
? Vocabulary.id(Vocabulary.word(sourceWord) + "_OOV")
: sourceWord;
int[] sourceWords = { sourceWord };
int[] targetWords = { targetWord };
final String oovAlignment = "0-0";
if (this.joshuaConfiguration.oovList != null && this.joshuaConfiguration.oovList.size() != 0) {
for (OOVItem item: this.joshuaConfiguration.oovList) {
Rule oovRule = new Rule(
Vocabulary.id(item.label), sourceWords, targetWords, "", 0,
oovAlignment);
addRule(oovRule);
oovRule.estimateRuleCost(featureFunctions);
}
} else {
int nt_i = Vocabulary.id(this.joshuaConfiguration.default_non_terminal);
Rule oovRule = new Rule(nt_i, sourceWords, targetWords, "", 0,
oovAlignment);
addRule(oovRule);
oovRule.estimateRuleCost(featureFunctions);
}
}
/**
* Adds a default set of glue rules.
*
* @param featureFunctions
*/
public void addGlueRules(ArrayList<FeatureFunction> featureFunctions) {
HieroFormatReader reader = new HieroFormatReader();
String goalNT = FormatUtils.cleanNonterminal(joshuaConfiguration.goal_symbol);
String defaultNT = FormatUtils.cleanNonterminal(joshuaConfiguration.default_non_terminal);
String[] ruleStrings = new String[] {
String.format("[%s] ||| %s ||| %s ||| 0", goalNT, Vocabulary.START_SYM,
Vocabulary.START_SYM),
String.format("[%s] ||| [%s,1] [%s,2] ||| [%s,1] [%s,2] ||| -1",
goalNT, goalNT, defaultNT, goalNT, defaultNT),
String.format("[%s] ||| [%s,1] %s ||| [%s,1] %s ||| 0",
goalNT, goalNT, Vocabulary.STOP_SYM, goalNT, Vocabulary.STOP_SYM)
};
for (String ruleString: ruleStrings) {
Rule rule = reader.parseLine(ruleString);
addRule(rule);
rule.estimateRuleCost(featureFunctions);
}
}
}
| src/joshua/decoder/ff/tm/hash_based/MemoryBasedBatchGrammar.java | package joshua.decoder.ff.tm.hash_based;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import joshua.corpus.Vocabulary;
import joshua.decoder.Decoder;
import joshua.decoder.JoshuaConfiguration;
import joshua.decoder.JoshuaConfiguration.OOVItem;
import joshua.decoder.ff.FeatureFunction;
import joshua.decoder.ff.tm.AbstractGrammar;
import joshua.decoder.ff.tm.Rule;
import joshua.decoder.ff.tm.GrammarReader;
import joshua.decoder.ff.tm.Trie;
import joshua.decoder.ff.tm.format.HieroFormatReader;
import joshua.decoder.ff.tm.format.MosesFormatReader;
import joshua.decoder.ff.tm.format.SamtFormatReader;
import joshua.util.FormatUtils;
/**
* This class implements a memory-based bilingual BatchGrammar.
* <p>
* The rules are stored in a trie. Each trie node has: (1) RuleBin: a list of rules matching the
* french sides so far (2) A HashMap of next-layer trie nodes, the next french word used as the key
* in HashMap
*
* @author Zhifei Li <[email protected]>
* @author Matt Post <[email protected]
*/
public class MemoryBasedBatchGrammar extends AbstractGrammar {
// ===============================================================
// Instance Fields
// ===============================================================
/* The number of rules read. */
private int qtyRulesRead = 0;
/* The number of distinct source sides. */
private int qtyRuleBins = 0;
/* The trie root. */
private MemoryBasedTrie root = null;
/* The file containing the grammar. */
private String grammarFile;
private GrammarReader<Rule> modelReader;
/* Maximum source phrase length */
protected int maxSourcePhraseLength = 0;
/* Whether the grammar's rules contain regular expressions. */
private boolean isRegexpGrammar = false;
// ===============================================================
// Static Fields
// ===============================================================
// ===============================================================
// Constructors
// ===============================================================
public MemoryBasedBatchGrammar(JoshuaConfiguration joshuaConfiguration) {
super(joshuaConfiguration);
this.root = new MemoryBasedTrie();
this.joshuaConfiguration = joshuaConfiguration;
}
public MemoryBasedBatchGrammar(String owner, JoshuaConfiguration joshuaConfiguration) {
this(joshuaConfiguration);
this.owner = Vocabulary.id(owner);
}
public MemoryBasedBatchGrammar(GrammarReader<Rule> gr,JoshuaConfiguration joshuaConfiguration) {
// this.defaultOwner = Vocabulary.id(defaultOwner);
// this.defaultLHS = Vocabulary.id(defaultLHSSymbol);
this(joshuaConfiguration);
modelReader = gr;
}
public MemoryBasedBatchGrammar(String formatKeyword, String grammarFile, String owner,
String defaultLHSSymbol, int spanLimit, JoshuaConfiguration joshuaConfiguration) throws IOException {
this(joshuaConfiguration);
this.owner = Vocabulary.id(owner);
Vocabulary.id(defaultLHSSymbol);
this.spanLimit = spanLimit;
this.grammarFile = grammarFile;
this.setRegexpGrammar(formatKeyword.equals("regexp"));
// ==== loading grammar
this.modelReader = createReader(formatKeyword, grammarFile);
if (modelReader != null) {
modelReader.initialize();
for (Rule rule : modelReader)
if (rule != null) {
addRule(rule);
}
} else {
Decoder.LOG(1, "Couldn't create a GrammarReader for file " + grammarFile + " with format "
+ formatKeyword);
}
this.printGrammar();
}
protected GrammarReader<Rule> createReader(String format, String grammarFile) {
if (grammarFile != null) {
if ("hiero".equals(format) || "thrax".equals(format) || "regexp".equals(format)) {
return new HieroFormatReader(grammarFile);
} else if ("samt".equals(format)) {
return new SamtFormatReader(grammarFile);
} else if ("phrase".equals(format) || "moses".equals(format)) {
return new MosesFormatReader(grammarFile);
} else {
throw new RuntimeException(String.format("* FATAL: unknown grammar format '%s'", format));
}
}
return null;
}
// ===============================================================
// Methods
// ===============================================================
public void setSpanLimit(int spanLimit) {
this.spanLimit = spanLimit;
}
@Override
public int getNumRules() {
return this.qtyRulesRead;
}
@Override
public Rule constructManualRule(int lhs, int[] sourceWords, int[] targetWords,
float[] denseScores, int arity) {
return null;
}
/**
* if the span covered by the chart bin is greater than the limit, then return false
*/
public boolean hasRuleForSpan(int i, int j, int pathLength) {
if (this.spanLimit == -1) { // mono-glue grammar
return (i == 0);
} else {
// System.err.println(String.format("%s HASRULEFORSPAN(%d,%d,%d)/%d = %s", Vocabulary.word(this.owner), i, j, pathLength, spanLimit, pathLength <= this.spanLimit));
return (pathLength <= this.spanLimit);
}
}
public Trie getTrieRoot() {
return this.root;
}
/**
* Adds a rule to the grammar.
*/
public void addRule(Rule rule) {
// TODO: Why two increments?
this.qtyRulesRead++;
// if (owner == -1) {
// System.err.println("* FATAL: MemoryBasedBatchGrammar::addRule(): owner not set for grammar");
// System.exit(1);
// }
rule.setOwner(owner);
// === identify the position, and insert the trie nodes as necessary
MemoryBasedTrie pos = root;
int[] french = rule.getFrench();
maxSourcePhraseLength = Math.max(maxSourcePhraseLength, french.length);
for (int k = 0; k < french.length; k++) {
int curSymID = french[k];
/*
* Note that the nonTerminal symbol in the french is not cleaned (i.e., will be sth like
* [X,1]), but the symbol in the Trie has to be cleaned, so that the match does not care about
* the markup (i.e., [X,1] or [X,2] means the same thing, that is X) if
* (Vocabulary.nt(french[k])) { curSymID = modelReader.cleanNonTerminal(french[k]); if
* (logger.isLoggable(Level.FINEST)) logger.finest("Amended to: " + curSymID); }
*/
MemoryBasedTrie nextLayer = (MemoryBasedTrie) pos.match(curSymID);
if (null == nextLayer) {
nextLayer = new MemoryBasedTrie();
if (pos.hasExtensions() == false) {
pos.childrenTbl = new HashMap<Integer, MemoryBasedTrie>();
}
pos.childrenTbl.put(curSymID, nextLayer);
}
pos = nextLayer;
}
// === add the rule into the trie node
if (!pos.hasRules()) {
pos.ruleBin = new MemoryBasedRuleBin(rule.getArity(), rule.getFrench());
this.qtyRuleBins++;
}
pos.ruleBin.addRule(rule);
}
protected void printGrammar() {
Decoder.LOG(1, String.format("MemoryBasedBatchGrammar: Read %d rules with %d distinct source sides from '%s'",
this.qtyRulesRead, this.qtyRuleBins, grammarFile));
}
/**
* This returns true if the grammar contains rules that are regular expressions, possibly matching
* many different inputs.
*
* @return true if the grammar's rules may contain regular expressions.
*/
@Override
public boolean isRegexpGrammar() {
return this.isRegexpGrammar;
}
public void setRegexpGrammar(boolean value) {
this.isRegexpGrammar = value;
}
/**
* Returns the longest source phrase read.
*
* @return the longest source phrase read (nonterminal + terminal symbols).
*/
public int getMaxSourcePhraseLength() {
/* We added a nonterminal to all source sides, so subtract that off. */
return maxSourcePhraseLength - 1;
}
/***
* Takes an input word and creates an OOV rule in the current grammar for that word.
*
* @param sourceWord
* @param featureFunctions
*/
@Override
public void addOOVRules(int sourceWord, List<FeatureFunction> featureFunctions) {
// TODO: _OOV shouldn't be outright added, since the word might not be OOV for the LM (but now almost
// certainly is)
final int targetWord = this.joshuaConfiguration.mark_oovs
? Vocabulary.id(Vocabulary.word(sourceWord) + "_OOV")
: sourceWord;
int[] sourceWords = { sourceWord };
int[] targetWords = { targetWord };
final String oovAlignment = "0-0";
if (this.joshuaConfiguration.oovList != null && this.joshuaConfiguration.oovList.size() != 0) {
for (OOVItem item: this.joshuaConfiguration.oovList) {
Rule oovRule = new Rule(
Vocabulary.id(item.label), sourceWords, targetWords, "", 0,
oovAlignment);
addRule(oovRule);
oovRule.estimateRuleCost(featureFunctions);
}
} else {
int nt_i = Vocabulary.id(this.joshuaConfiguration.default_non_terminal);
Rule oovRule = new Rule(nt_i, sourceWords, targetWords, "", 0,
oovAlignment);
addRule(oovRule);
oovRule.estimateRuleCost(featureFunctions);
}
}
/**
* Adds a default set of glue rules.
*
* @param featureFunctions
*/
public void addGlueRules(ArrayList<FeatureFunction> featureFunctions) {
HieroFormatReader reader = new HieroFormatReader();
String goalNT = FormatUtils.cleanNonterminal(joshuaConfiguration.goal_symbol);
String defaultNT = FormatUtils.cleanNonterminal(joshuaConfiguration.default_non_terminal);
String[] ruleStrings = new String[] {
String.format("[%s] ||| %s ||| %s ||| 0", goalNT, Vocabulary.START_SYM,
Vocabulary.START_SYM),
String.format("[%s] ||| [%s,1] [%s,2] ||| [%s,1] [%s,2] ||| -1",
goalNT, goalNT, defaultNT, goalNT, defaultNT),
String.format("[%s] ||| [%s,1] %s ||| [%s,1] %s ||| 0",
goalNT, goalNT, Vocabulary.STOP_SYM, goalNT, Vocabulary.STOP_SYM)
};
for (String ruleString: ruleStrings) {
Rule rule = reader.parseLine(ruleString);
addRule(rule);
rule.estimateRuleCost(featureFunctions);
}
}
}
| Bugfix: one-off error on max source phrase len
| src/joshua/decoder/ff/tm/hash_based/MemoryBasedBatchGrammar.java | Bugfix: one-off error on max source phrase len | <ide><path>rc/joshua/decoder/ff/tm/hash_based/MemoryBasedBatchGrammar.java
<ide> * @return the longest source phrase read (nonterminal + terminal symbols).
<ide> */
<ide> public int getMaxSourcePhraseLength() {
<del> /* We added a nonterminal to all source sides, so subtract that off. */
<del> return maxSourcePhraseLength - 1;
<add> return maxSourcePhraseLength;
<ide> }
<ide>
<ide> /*** |
|
Java | apache-2.0 | 1bac369b5d45dbe6824fd692a7e86a96c5b540dd | 0 | ecsec/open-ecard,ecsec/open-ecard,ecsec/open-ecard | /****************************************************************************
* Copyright (C) 2019 ecsec GmbH.
* All rights reserved.
* Contact: ecsec GmbH ([email protected])
*
* This file is part of the Open eCard App.
*
* GNU General Public License Usage
* This file may be used under the terms of the GNU General Public
* License version 3.0 as published by the Free Software Foundation
* and appearing in the file LICENSE.GPL included in the packaging of
* this file. Please review the following information to ensure the
* GNU General Public License version 3.0 requirements will be met:
* http://www.gnu.org/copyleft/gpl.html.
*
* Other Usage
* Alternatively, this file may be used in accordance with the terms
* and conditions contained in a signed written agreement between
* you and ecsec GmbH.
*
***************************************************************************/
package org.openecard.ios.activation;
import java.security.Provider;
import java.security.Security;
import org.openecard.bouncycastle.jce.provider.BouncyCastleProvider;
import org.openecard.common.util.SysUtils;
import org.openecard.mobile.activation.ContextManager;
import org.openecard.mobile.activation.common.CommonActivationUtils;
import org.openecard.mobile.system.OpeneCardContextConfig;
import org.openecard.robovm.annotations.FrameworkObject;
import org.openecard.scio.IOSNFCFactory;
import org.openecard.ws.android.AndroidMarshaller;
import org.openecard.mobile.activation.common.NFCDialogMsgSetter;
import org.openecard.scio.IOSConfig;
/**
*
* @author Neil Crossley
*/
@FrameworkObject(factoryMethod = "createOpenEcard")
public class OpenEcardImp implements OpenEcard {
static {
// define that this system is iOS
SysUtils.setIsIOS();
Provider provider = new BouncyCastleProvider();
try {
Security.removeProvider(provider.getName());
Security.removeProvider("BC");
} catch (Exception e) {
}
Security.addProvider(provider);
}
private final CommonActivationUtils utils;
private final ContextManager context;
private String defaultNFCDialogMsg;
private String defaultNFCCardRecognizedMessage;
public OpenEcardImp() {
IOSNFCCapabilities capabilities = new IOSNFCCapabilities();
OpeneCardContextConfig config = new OpeneCardContextConfig(IOSNFCFactory.class.getCanonicalName(), AndroidMarshaller.class.getCanonicalName());
CommonActivationUtils activationUtils = new CommonActivationUtils(config, new IOSNFCDialogMsgSetter());
this.utils = activationUtils;
this.context = this.utils.context(capabilities);
}
@Override
public void triggerNFC() {
try {
IOSNFCFactory.triggerNFC(new IOSConfig() {
public String getDefaultProviderCardMSG() {
return defaultNFCDialogMsg;
}
public String getDefaultCardRecognizedMSG() {
return defaultNFCCardRecognizedMessage;
}
});
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
@Override
public ContextManager context(String defaultNFCDialgoMsg, String defaultNFCCardRecognizedMessage) {
this.defaultNFCDialogMsg = defaultNFCDialgoMsg;
this.defaultNFCCardRecognizedMessage = defaultNFCCardRecognizedMessage;
return context;
}
}
| clients/ios-lib/src/main/java/org/openecard/ios/activation/OpenEcardImp.java | /****************************************************************************
* Copyright (C) 2019 ecsec GmbH.
* All rights reserved.
* Contact: ecsec GmbH ([email protected])
*
* This file is part of the Open eCard App.
*
* GNU General Public License Usage
* This file may be used under the terms of the GNU General Public
* License version 3.0 as published by the Free Software Foundation
* and appearing in the file LICENSE.GPL included in the packaging of
* this file. Please review the following information to ensure the
* GNU General Public License version 3.0 requirements will be met:
* http://www.gnu.org/copyleft/gpl.html.
*
* Other Usage
* Alternatively, this file may be used in accordance with the terms
* and conditions contained in a signed written agreement between
* you and ecsec GmbH.
*
***************************************************************************/
package org.openecard.ios.activation;
import java.security.Provider;
import java.security.Security;
import org.openecard.bouncycastle.jce.provider.BouncyCastleProvider;
import org.openecard.common.util.SysUtils;
import org.openecard.mobile.activation.ContextManager;
import org.openecard.mobile.activation.common.CommonActivationUtils;
import org.openecard.mobile.system.OpeneCardContextConfig;
import org.openecard.robovm.annotations.FrameworkObject;
import org.openecard.scio.IOSNFCFactory;
import org.openecard.ws.android.AndroidMarshaller;
import org.openecard.mobile.activation.common.NFCDialogMsgSetter;
import org.openecard.scio.IOSConfig;
/**
*
* @author Neil Crossley
*/
@FrameworkObject(factoryMethod = "createOpenEcard")
public class OpenEcardImp implements OpenEcard {
static {
// define that this system is iOS
SysUtils.setIsIOS();
Provider provider = new BouncyCastleProvider();
try {
Security.removeProvider(provider.getName());
} catch (Exception e) {
}
Security.addProvider(provider);
}
private final CommonActivationUtils utils;
private final ContextManager context;
private String defaultNFCDialogMsg;
private String defaultNFCCardRecognizedMessage;
public OpenEcardImp() {
IOSNFCCapabilities capabilities = new IOSNFCCapabilities();
OpeneCardContextConfig config = new OpeneCardContextConfig(IOSNFCFactory.class.getCanonicalName(), AndroidMarshaller.class.getCanonicalName());
CommonActivationUtils activationUtils = new CommonActivationUtils(config, new IOSNFCDialogMsgSetter());
this.utils = activationUtils;
this.context = this.utils.context(capabilities);
}
@Override
public void triggerNFC() {
try {
IOSNFCFactory.triggerNFC(new IOSConfig() {
public String getDefaultProviderCardMSG() {
return defaultNFCDialogMsg;
}
public String getDefaultCardRecognizedMSG() {
return defaultNFCCardRecognizedMessage;
}
});
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
@Override
public ContextManager context(String defaultNFCDialgoMsg, String defaultNFCCardRecognizedMessage) {
this.defaultNFCDialogMsg = defaultNFCDialgoMsg;
this.defaultNFCCardRecognizedMessage = defaultNFCCardRecognizedMessage;
return context;
}
}
| Remove more versions of BC as Provider
| clients/ios-lib/src/main/java/org/openecard/ios/activation/OpenEcardImp.java | Remove more versions of BC as Provider | <ide><path>lients/ios-lib/src/main/java/org/openecard/ios/activation/OpenEcardImp.java
<ide> Provider provider = new BouncyCastleProvider();
<ide> try {
<ide> Security.removeProvider(provider.getName());
<add> Security.removeProvider("BC");
<ide> } catch (Exception e) {
<ide> }
<ide> Security.addProvider(provider); |
|
JavaScript | mit | fb50e0dbef448934ed1a11f3a46ab262587d36c6 | 0 | npmcomponent/cristiandouce-sizzle,mzgol/sizzle | /*!
* Sizzle CSS Selector Engine
* Copyright 2011, The Dojo Foundation
* Released under the MIT, BSD, and GPL Licenses.
* More information: http://sizzlejs.com/
*/
(function( window, undefined ) {
var document = window.document,
docElem = document.documentElement,
expando = "sizcache" + (Math.random() + '').replace('.', ''),
done = 0,
toString = Object.prototype.toString,
strundefined = "undefined",
hasDuplicate = false,
baseHasDuplicate = true,
// Regex
rquickExpr = /^#([\w\-]+$)|^(\w+$)|^\.([\w\-]+$)/,
chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,
rbackslash = /\\/g,
rnonWord = /\W/,
rstartsWithWord = /^\w/,
rnonDigit = /\D/,
rnth = /(-?)(\d*)(?:n([+\-]?\d*))?/,
radjacent = /^\+|\s*/g,
rheader = /h\d/i,
rinputs = /input|select|textarea|button/i,
rtnfr = /[\t\n\f\r]/g,
characterEncoding = "(?:[-\\w]|[^\\x00-\\xa0]|\\\\.)",
matchExpr = {
ID: new RegExp("#(" + characterEncoding + "+)"),
CLASS: new RegExp("\\.(" + characterEncoding + "+)"),
NAME: new RegExp("\\[name=['\"]*(" + characterEncoding + "+)['\"]*\\]"),
TAG: new RegExp("^(" + characterEncoding.replace( "[-", "[-\\*" ) + "+)"),
ATTR: new RegExp("\\[\\s*(" + characterEncoding + "+)\\s*(?:(\\S?=)\\s*(?:(['\"])(.*?)\\3|(#?" + characterEncoding + "*)|)|)\\s*\\]"),
PSEUDO: new RegExp(":(" + characterEncoding + "+)(?:\\((['\"]?)((?:\\([^\\)]+\\)|[^\\(\\)]*)+)\\2\\))?"),
CHILD: /:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/,
POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/
},
origPOS = matchExpr.POS,
leftMatchExpr = (function() {
var type,
// Increments parenthetical references
// for leftMatch creation
fescape = function( all, num ) {
return "\\" + ( num - 0 + 1 );
},
leftMatch = {};
for ( type in matchExpr ) {
// Modify the regexes ensuring the matches do not end in brackets/parens
matchExpr[ type ] = new RegExp( matchExpr[ type ].source + (/(?![^\[]*\])(?![^\(]*\))/.source) );
// Adds a capture group for characters left of the match
leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + matchExpr[ type ].source.replace( /\\(\d+)/g, fescape ) );
}
// Expose origPOS
// "global" as in regardless of relation to brackets/parens
matchExpr.globalPOS = origPOS;
return leftMatch;
})(),
// Used for testing something on an element
assert = function( fn ) {
var pass = false,
div = document.createElement("div");
try {
pass = fn( div );
} catch (e) {}
// release memory in IE
div = null;
return pass;
},
// Check to see if the browser returns elements by name when
// querying by getElementById (and provide a workaround)
assertGetIdNotName = assert(function( div ) {
var pass = true,
id = "script" + (new Date()).getTime();
div.innerHTML = "<a name ='" + id + "'/>";
// Inject it into the root element, check its status, and remove it quickly
docElem.insertBefore( div, docElem.firstChild );
if ( document.getElementById( id ) ) {
pass = false;
}
docElem.removeChild( div );
return pass;
}),
// Check to see if the browser returns only elements
// when doing getElementsByTagName("*")
assertTagNameNoComments = assert(function( div ) {
div.appendChild( document.createComment("") );
return div.getElementsByTagName("*").length === 0;
}),
// Check to see if an attribute returns normalized href attributes
assertHrefNotNormalized = assert(function( div ) {
div.innerHTML = "<a href='#'></a>";
if ( div.firstChild && typeof div.firstChild.getAttribute !== strundefined &&
div.firstChild.getAttribute("href") !== "#" ) {
return false;
}
return true;
}),
// Determines a buggy getElementsByClassName
assertUsableClassName = assert(function( div ) {
// Opera can't find a second classname (in 9.6)
div.innerHTML = "<div class='test e'></div><div class='test'></div>";
if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) {
return false;
}
// Safari caches class attributes, doesn't catch changes (in 3.2)
div.lastChild.className = "e";
return div.getElementsByClassName("e").length !== 1;
});
// Check if the JavaScript engine is using some sort of
// optimization where it does not always call our comparision
// function. If that is the case, discard the hasDuplicate value.
// Thus far that includes Google Chrome.
[0, 0].sort(function() {
baseHasDuplicate = false;
return 0;
});
var Sizzle = function( selector, context, results ) {
results = results || [];
context = context || document;
var match, elem, contextXML,
nodeType = context.nodeType;
if ( nodeType !== 1 && nodeType !== 9 ) {
return [];
}
if ( !selector || typeof selector !== "string" ) {
return results;
}
contextXML = isXML( context );
if ( !contextXML ) {
if ( (match = rquickExpr.exec( selector )) ) {
// Speed-up: Sizzle("#ID")
if ( match[1] ) {
if ( nodeType === 9 ) {
elem = context.getElementById( match[1] );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE, Opera, and Webkit return items
// by name instead of ID
if ( elem.id === match[1] ) {
return makeArray( [ elem ], results );
}
} else {
return makeArray( [], results );
}
} else {
// Context is not a document
elem = context.ownerDocument && context.ownerDocument.getElementById( match[1] );
if ( contains(context, elem) && elem.id === match[1] ) {
return makeArray( [ elem ], results );
}
}
// Speed-up: Sizzle("TAG")
} else if ( match[2] ) {
// Speed-up: Sizzle("body")
if ( selector === "body" && context.body ) {
return makeArray( [ context.body ], results );
}
return makeArray( context.getElementsByTagName( selector ), results );
// Speed-up: Sizzle(".CLASS")
} else if ( assertUsableClassName && match[3] && context.getElementsByClassName ) {
return makeArray( context.getElementsByClassName( match[3] ), results );
}
}
}
// All others
return select( selector, context, results, undefined, contextXML );
};
var select = function( selector, context, results, seed, contextXML ) {
var m, set, checkSet, extra, ret, cur, pop, i,
origContext = context,
prune = true,
parts = [],
soFar = selector;
do {
// Reset the position of the chunker regexp (start from head)
chunker.exec( "" );
m = chunker.exec( soFar );
if ( m ) {
soFar = m[3];
parts.push( m[1] );
if ( m[2] ) {
extra = m[3];
break;
}
}
} while ( m );
if ( parts.length > 1 && origPOS.exec( selector ) ) {
if ( parts.length === 2 && Expr.relative[ parts[0] ] ) {
set = posProcess( parts[0] + parts[1], context, seed, contextXML );
} else {
set = Expr.relative[ parts[0] ] ?
[ context ] :
Sizzle( parts.shift(), context );
while ( parts.length ) {
selector = parts.shift();
if ( Expr.relative[ selector ] ) {
selector += parts.shift();
}
set = posProcess( selector, set, seed, contextXML );
}
}
} else {
// Take a shortcut and set the context if the root selector is an ID
// (but not if it'll be faster if the inner selector is an ID)
if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML &&
matchExpr.ID.test( parts[0] ) && !matchExpr.ID.test( parts[parts.length - 1] ) ) {
ret = Sizzle.find( parts.shift(), context, contextXML );
context = ret.expr ?
Sizzle.filter( ret.expr, ret.set )[0] :
ret.set[0];
}
if ( context ) {
ret = seed ?
{ expr: parts.pop(), set: makeArray( seed ) } :
Sizzle.find( parts.pop(), (parts.length >= 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode) || context, contextXML );
set = ret.expr ?
Sizzle.filter( ret.expr, ret.set ) :
ret.set;
if ( parts.length > 0 ) {
checkSet = makeArray( set );
} else {
prune = false;
}
while ( parts.length ) {
cur = parts.pop();
pop = cur;
if ( !Expr.relative[ cur ] ) {
cur = "";
} else {
pop = parts.pop();
}
if ( pop == null ) {
pop = context;
}
Expr.relative[ cur ]( checkSet, pop, contextXML );
}
} else {
checkSet = parts = [];
}
}
if ( !checkSet ) {
checkSet = set;
}
if ( !checkSet ) {
Sizzle.error( cur || selector );
}
if ( toString.call(checkSet) === "[object Array]" ) {
if ( !prune ) {
results.push.apply( results, checkSet );
} else if ( context && context.nodeType === 1 ) {
for ( i = 0; checkSet[i] != null; i++ ) {
if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && contains( context, checkSet[i] )) ) {
results.push( set[i] );
}
}
} else {
for ( i = 0; checkSet[i] != null; i++ ) {
if ( checkSet[i] && checkSet[i].nodeType === 1 ) {
results.push( set[i] );
}
}
}
} else {
makeArray( checkSet, results );
}
if ( extra ) {
select( extra, origContext, results, seed, contextXML );
uniqueSort( results );
}
return results;
};
var isXML = Sizzle.isXML = function( elem ) {
// documentElement is verified for cases where it doesn't yet exist
// (such as loading iframes in IE - #4833)
var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement;
return documentElement ? documentElement.nodeName !== "HTML" : false;
};
// Slice is no longer used
// It is not actually faster
// Results is expected to be an array or undefined
// typeof len is checked for if array is a form nodelist containing an element with name "length" (wow)
var makeArray = function( array, results ) {
results = results || [];
var i = 0,
len = array.length;
if ( typeof len === "number" ) {
for ( ; i < len; i++ ) {
results.push( array[i] );
}
} else {
for ( ; array[i]; i++ ) {
results.push( array[i] );
}
}
return results;
};
var uniqueSort = Sizzle.uniqueSort = function( results ) {
if ( sortOrder ) {
hasDuplicate = baseHasDuplicate;
results.sort( sortOrder );
if ( hasDuplicate ) {
for ( var i = 1; i < results.length; i++ ) {
if ( results[i] === results[ i - 1 ] ) {
results.splice( i--, 1 );
}
}
}
}
return results;
};
// Element contains another
var contains = Sizzle.contains = docElem.compareDocumentPosition ?
function( a, b ) {
return !!(a.compareDocumentPosition( b ) & 16);
} :
docElem.contains ?
function( a, b ) {
return a !== b && ( a.contains ? a.contains( b ) : false );
} :
function( a, b ) {
while ( (b = b.parentNode) ) {
if ( b === a ) {
return true;
}
}
return false;
};
Sizzle.matches = function( expr, set ) {
return select( expr, document, [], set, isXML( document ) );
};
Sizzle.matchesSelector = function( node, expr ) {
return select( expr, document, [], [ node ], isXML( document ) ).length > 0;
};
Sizzle.find = function( expr, context, contextXML ) {
var set, i, len, match, type, left;
if ( !expr ) {
return [];
}
for ( i = 0, len = Expr.order.length; i < len; i++ ) {
type = Expr.order[i];
if ( (match = leftMatchExpr[ type ].exec( expr )) ) {
left = match[1];
match.splice( 1, 1 );
if ( left.substr( left.length - 1 ) !== "\\" ) {
match[1] = (match[1] || "").replace( rbackslash, "" );
set = Expr.find[ type ]( match, context, contextXML );
if ( set != null ) {
expr = expr.replace( matchExpr[ type ], "" );
break;
}
}
}
}
if ( !set ) {
set = typeof context.getElementsByTagName !== strundefined ?
context.getElementsByTagName( "*" ) :
[];
}
return { set: set, expr: expr };
};
Sizzle.filter = function( expr, set, inplace, not ) {
var match, anyFound,
type, found, item, filter, left,
i, pass,
old = expr,
result = [],
curLoop = set,
isXMLFilter = set && set[0] && isXML( set[0] );
while ( expr && set.length ) {
for ( type in Expr.filter ) {
if ( (match = leftMatchExpr[ type ].exec( expr )) != null && match[2] ) {
filter = Expr.filter[ type ];
left = match[1];
anyFound = false;
match.splice( 1, 1 );
if ( left.substr( left.length - 1 ) === "\\" ) {
continue;
}
if ( curLoop === result ) {
result = [];
}
if ( Expr.preFilter[ type ] ) {
match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter );
if ( !match ) {
anyFound = found = true;
} else if ( match === true ) {
continue;
}
}
if ( match ) {
for ( i = 0; (item = curLoop[i]) != null; i++ ) {
if ( item ) {
found = filter( item, match, i, curLoop );
pass = not ^ found;
if ( inplace && found != null ) {
if ( pass ) {
anyFound = true;
} else {
curLoop[i] = false;
}
} else if ( pass ) {
result.push( item );
anyFound = true;
}
}
}
}
if ( found !== undefined ) {
if ( !inplace ) {
curLoop = result;
}
expr = expr.replace( matchExpr[ type ], "" );
if ( !anyFound ) {
return [];
}
break;
}
}
}
// Improper expression
if ( expr === old ) {
if ( anyFound == null ) {
Sizzle.error( expr );
} else {
break;
}
}
old = expr;
}
return curLoop;
};
Sizzle.error = function( msg ) {
throw new Error( "Syntax error, unrecognized expression: " + msg );
};
/**
* Utility function for retreiving the text value of an array of DOM nodes
* @param {Array|Element} elem
*/
var getText = Sizzle.getText = function( elem ) {
var i, node,
nodeType = elem.nodeType,
ret = "";
if ( nodeType ) {
if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
// Use textContent for elements
// innerText usage removed for consistency of new lines (see #11153)
if ( typeof elem.textContent === "string" ) {
return elem.textContent;
} else {
// Traverse it's children
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
ret += getText( elem );
}
}
} else if ( nodeType === 3 || nodeType === 4 ) {
return elem.nodeValue;
}
} else {
// If no nodeType, this is expected to be an array
for ( i = 0; (node = elem[i]); i++ ) {
// Do not traverse comment nodes
if ( node.nodeType !== 8 ) {
ret += getText( node );
}
}
}
return ret;
};
var Expr = Sizzle.selectors = {
match: matchExpr,
leftMatch: leftMatchExpr,
order: [ "ID", "NAME", "TAG" ],
attrMap: {
"class": "className",
"for": "htmlFor"
},
attrHandle: {
href: assertHrefNotNormalized ?
function( elem ) {
return elem.getAttribute( "href" );
} :
function( elem ) {
return elem.getAttribute( "href", 2 );
},
type: function( elem ) {
return elem.getAttribute( "type" );
}
},
relative: {
"+": function( checkSet, part ) {
var isPartStr = typeof part === "string",
isTag = isPartStr && !rnonWord.test( part ),
isPartStrNotTag = isPartStr && !isTag;
if ( isTag ) {
part = part.toLowerCase();
}
for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) {
if ( (elem = checkSet[i]) ) {
while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {}
checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ?
elem || false :
elem === part;
}
}
if ( isPartStrNotTag ) {
Sizzle.filter( part, checkSet, true );
}
},
">": function( checkSet, part ) {
var elem,
isPartStr = typeof part === "string",
i = 0,
l = checkSet.length;
if ( isPartStr && !rnonWord.test( part ) ) {
part = part.toLowerCase();
for ( ; i < l; i++ ) {
elem = checkSet[i];
if ( elem ) {
var parent = elem.parentNode;
checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false;
}
}
} else {
for ( ; i < l; i++ ) {
elem = checkSet[i];
if ( elem ) {
checkSet[i] = isPartStr ?
elem.parentNode :
elem.parentNode === part;
}
}
if ( isPartStr ) {
Sizzle.filter( part, checkSet, true );
}
}
},
"": function( checkSet, part, xml ) {
dirCheck( "parentNode", checkSet, part, xml );
},
"~": function( checkSet, part, xml ) {
dirCheck( "previousSibling", checkSet, part, xml );
}
},
find: {
ID: assertGetIdNotName ?
function( match, context, xml ) {
if ( typeof context.getElementById !== strundefined && !xml ) {
var m = context.getElementById( match[1] );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
return m && m.parentNode ? [m] : [];
}
} :
function( match, context, xml ) {
if ( typeof context.getElementById !== strundefined && !xml ) {
var m = context.getElementById( match[1] );
return m ?
m.id === match[1] || typeof m.getAttributeNode !== strundefined && m.getAttributeNode("id").nodeValue === match[1] ?
[m] :
undefined :
[];
}
},
NAME: function( match, context ) {
if ( typeof context.getElementsByName !== strundefined ) {
var ret = [],
results = context.getElementsByName( match[1] ),
i = 0,
len = results.length;
for ( ; i < len; i++ ) {
if ( results[i].getAttribute("name") === match[1] ) {
ret.push( results[i] );
}
}
return ret.length === 0 ? null : ret;
}
},
TAG: assertTagNameNoComments ?
function( match, context ) {
if ( typeof context.getElementsByTagName !== strundefined ) {
return context.getElementsByTagName( match[1] );
}
} :
function( match, context ) {
var results = context.getElementsByTagName( match[1] );
// Filter out possible comments
if ( match[1] === "*" ) {
var tmp = [],
i = 0;
for ( ; results[i]; i++ ) {
if ( results[i].nodeType === 1 ) {
tmp.push( results[i] );
}
}
results = tmp;
}
return results;
}
},
preFilter: {
CLASS: function( match, curLoop, inplace, result, not, xml ) {
match = " " + match[1].replace( rbackslash, "" ) + " ";
if ( xml ) {
return match;
}
for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) {
if ( elem ) {
if ( not ^ (elem.className && (" " + elem.className + " ").replace( rtnfr, " " ).indexOf( match ) >= 0) ) {
if ( !inplace ) {
result.push( elem );
}
} else if ( inplace ) {
curLoop[i] = false;
}
}
}
return false;
},
ID: function( match ) {
return match[1].replace( rbackslash, "" );
},
TAG: function( match, curLoop ) {
return match[1].replace( rbackslash, "" ).toLowerCase();
},
CHILD: function( match ) {
if ( match[1] === "nth" ) {
if ( !match[2] ) {
Sizzle.error( match[0] );
}
match[2] = match[2].replace( radjacent, "" );
// parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6'
var test = rnth.exec(
match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" ||
!rnonDigit.test( match[2] ) && "0n+" + match[2] || match[2] );
// calculate the numbers (first)n+(last) including if they are negative
match[2] = (test[1] + (test[2] || 1)) - 0;
match[3] = test[3] - 0;
} else if ( match[2] ) {
Sizzle.error( match[0] );
}
// TODO: Move to normal caching system
match[0] = done++;
return match;
},
ATTR: function( match, curLoop, inplace, result, not, xml ) {
var name = match[1] = match[1].replace( rbackslash, "" );
if ( !xml && Expr.attrMap[ name ] ) {
match[1] = Expr.attrMap[ name ];
}
// Handle if an un-quoted value was used
match[4] = ( match[4] || match[5] || "" ).replace( rbackslash, "" );
if ( match[2] === "~=" ) {
match[4] = " " + match[4] + " ";
}
return match;
},
PSEUDO: function( match, curLoop, inplace, result, not, xml ) {
if ( match[1] === "not" ) {
// If we're dealing with a complex expression, or a simple one
if ( ( chunker.exec( match[3] ) || "" ).length > 1 || rstartsWithWord.test( match[3] ) ) {
match[3] = select( match[3], document, [], curLoop, xml );
} else {
var ret = Sizzle.filter( match[3], curLoop, inplace, !not );
if ( !inplace ) {
result.push.apply( result, ret );
}
return false;
}
} else if ( matchExpr.POS.test( match[0] ) || matchExpr.CHILD.test( match[0] ) ) {
return true;
}
return match;
},
POS: function( match ) {
match.unshift( true );
return match;
}
},
filters: {
enabled: function( elem ) {
return elem.disabled === false;
},
disabled: function( elem ) {
return elem.disabled === true;
},
checked: function( elem ) {
// In CSS3, :checked should return both checked and selected elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
var nodeName = elem.nodeName.toLowerCase();
return (nodeName === "input" && !! elem.checked) || (nodeName === "option" && !!elem.selected);
},
selected: function( elem ) {
// Accessing this property makes selected-by-default
// options in Safari work properly
if ( elem.parentNode ) {
elem.parentNode.selectedIndex;
}
return elem.selected === true;
},
parent: function( elem ) {
return !!elem.firstChild;
},
empty: function( elem ) {
return !elem.firstChild;
},
has: function( elem, i, match ) {
return !!Sizzle( match[3], elem ).length;
},
header: function( elem ) {
return rheader.test( elem.nodeName );
},
text: function( elem ) {
var attr = elem.getAttribute( "type" ), type = elem.type;
// IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc)
// use getAttribute instead to test this case
return elem.nodeName.toLowerCase() === "input" && "text" === type && ( attr === null || attr.toLowerCase() === type );
},
radio: function( elem ) {
return elem.nodeName.toLowerCase() === "input" && "radio" === elem.type;
},
checkbox: function( elem ) {
return elem.nodeName.toLowerCase() === "input" && "checkbox" === elem.type;
},
file: function( elem ) {
return elem.nodeName.toLowerCase() === "input" && "file" === elem.type;
},
password: function( elem ) {
return elem.nodeName.toLowerCase() === "input" && "password" === elem.type;
},
submit: function( elem ) {
var name = elem.nodeName.toLowerCase();
return (name === "input" || name === "button") && "submit" === elem.type;
},
image: function( elem ) {
return elem.nodeName.toLowerCase() === "input" && "image" === elem.type;
},
reset: function( elem ) {
var name = elem.nodeName.toLowerCase();
return (name === "input" || name === "button") && "reset" === elem.type;
},
button: function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && "button" === elem.type || name === "button";
},
input: function( elem ) {
return rinputs.test( elem.nodeName );
},
focus: function( elem ) {
var doc = elem.ownerDocument;
return elem === doc.activeElement && (!doc.hasFocus || doc.hasFocus()) && !!(elem.type || elem.href);
},
active: function( elem ) {
return elem === elem.ownerDocument.activeElement;
},
contains: function( elem, i, match ) {
return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( match[3] ) >= 0;
}
},
setFilters: {
first: function( elem, i ) {
return i === 0;
},
last: function( elem, i, match, array ) {
return i === array.length - 1;
},
even: function( elem, i ) {
return i % 2 === 0;
},
odd: function( elem, i ) {
return i % 2 === 1;
},
lt: function( elem, i, match ) {
return i < match[3] - 0;
},
gt: function( elem, i, match ) {
return i > match[3] - 0;
},
nth: function( elem, i, match ) {
return match[3] - 0 === i;
},
eq: function( elem, i, match ) {
return match[3] - 0 === i;
}
},
filter: {
PSEUDO: function( elem, match, i, array ) {
var name = match[1],
filter = Expr.filters[ name ];
if ( filter ) {
return filter( elem, i, match, array );
} else if ( name === "not" ) {
var not = match[3],
j = 0,
len = not.length;
for ( ; j < len; j++ ) {
if ( not[j] === elem ) {
return false;
}
}
return true;
} else {
Sizzle.error( name );
}
},
CHILD: function( elem, match ) {
var first, last,
doneName, parent, cache,
count, diff,
type = match[1],
node = elem;
switch ( type ) {
case "only":
case "first":
while ( (node = node.previousSibling) ) {
if ( node.nodeType === 1 ) {
return false;
}
}
if ( type === "first" ) {
return true;
}
node = elem;
/* falls through */
case "last":
while ( (node = node.nextSibling) ) {
if ( node.nodeType === 1 ) {
return false;
}
}
return true;
case "nth":
first = match[2];
last = match[3];
if ( first === 1 && last === 0 ) {
return true;
}
doneName = match[0];
parent = elem.parentNode;
if ( parent && (parent[ expando ] !== doneName || !elem.nodeIndex) ) {
count = 0;
for ( node = parent.firstChild; node; node = node.nextSibling ) {
if ( node.nodeType === 1 ) {
node.nodeIndex = ++count;
}
}
parent[ expando ] = doneName;
}
diff = elem.nodeIndex - last;
if ( first === 0 ) {
return diff === 0;
} else {
return ( diff % first === 0 && diff / first >= 0 );
}
}
},
ID: assertGetIdNotName ?
function( elem, match ) {
return elem.nodeType === 1 && elem.getAttribute("id") === match;
} :
function( elem, match ) {
var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id");
return elem.nodeType === 1 && node && node.nodeValue === match;
},
TAG: function( elem, match ) {
return ( match === "*" && elem.nodeType === 1 ) || !!elem.nodeName && elem.nodeName.toLowerCase() === match;
},
CLASS: function( elem, match ) {
return ( " " + ( elem.className || elem.getAttribute("class") ) + " " ).indexOf( match ) > -1;
},
ATTR: function( elem, match ) {
var name = match[1],
result = Sizzle.attr ?
Sizzle.attr( elem, name ) :
Expr.attrHandle[ name ] ?
Expr.attrHandle[ name ]( elem ) :
elem[ name ] != null ?
elem[ name ] :
elem.getAttribute( name ),
value = result + "",
type = match[2],
check = match[4];
return result == null ?
type === "!=" :
!type && Sizzle.attr ?
result != null :
type === "=" ?
value === check :
type === "*=" ?
value.indexOf( check ) >= 0 :
type === "~=" ?
( " " + value + " " ).indexOf( check ) >= 0 :
!check ?
value && result !== false :
type === "!=" ?
value !== check :
type === "^=" ?
value.indexOf( check ) === 0 :
type === "$=" ?
value.substr( value.length - check.length ) === check :
type === "|=" ?
value === check || value.substr( 0, check.length + 1 ) === check + "-" :
false;
},
POS: function( elem, match, i, array ) {
var name = match[2],
filter = Expr.setFilters[ name ];
if ( filter ) {
return filter( elem, i, match, array );
}
}
}
};
// Add getElementsByClassName if usable
if ( assertUsableClassName ) {
Expr.order.splice( 1, 0, "CLASS" );
Expr.find.CLASS = function( match, context, xml ) {
if ( typeof context.getElementsByClassName !== strundefined && !xml ) {
return context.getElementsByClassName( match[1] );
}
};
}
var sortOrder, siblingCheck;
if ( docElem.compareDocumentPosition ) {
sortOrder = function( a, b ) {
if ( a === b ) {
hasDuplicate = true;
return 0;
}
if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) {
return a.compareDocumentPosition ? -1 : 1;
}
return a.compareDocumentPosition(b) & 4 ? -1 : 1;
};
} else {
sortOrder = function( a, b ) {
// The nodes are identical, we can exit early
if ( a === b ) {
hasDuplicate = true;
return 0;
// Fallback to using sourceIndex (in IE) if it's available on both nodes
} else if ( a.sourceIndex && b.sourceIndex ) {
return a.sourceIndex - b.sourceIndex;
}
var al, bl,
ap = [],
bp = [],
aup = a.parentNode,
bup = b.parentNode,
cur = aup;
// If the nodes are siblings (or identical) we can do a quick check
if ( aup === bup ) {
return siblingCheck( a, b );
// If no parents were found then the nodes are disconnected
} else if ( !aup ) {
return -1;
} else if ( !bup ) {
return 1;
}
// Otherwise they're somewhere else in the tree so we need
// to build up a full list of the parentNodes for comparison
while ( cur ) {
ap.unshift( cur );
cur = cur.parentNode;
}
cur = bup;
while ( cur ) {
bp.unshift( cur );
cur = cur.parentNode;
}
al = ap.length;
bl = bp.length;
// Start walking down the tree looking for a discrepancy
for ( var i = 0; i < al && i < bl; i++ ) {
if ( ap[i] !== bp[i] ) {
return siblingCheck( ap[i], bp[i] );
}
}
// We ended someplace up the tree so do a sibling check
return i === al ?
siblingCheck( a, bp[i], -1 ) :
siblingCheck( ap[i], b, 1 );
};
siblingCheck = function( a, b, ret ) {
if ( a === b ) {
return ret;
}
var cur = a.nextSibling;
while ( cur ) {
if ( cur === b ) {
return -1;
}
cur = cur.nextSibling;
}
return 1;
};
}
if ( document.querySelectorAll ) {
(function(){
var oldSelect = select,
id = "__sizzle__",
rrelativeHierarchy = /^\s*[+~]/,
rapostrophe = /'/g,
// Build QSA regex
// Regex strategy adopted from Diego Perini
rbuggyQSA = [];
assert(function( div ) {
div.innerHTML = "<select><option selected></option></select>";
// IE8 - Some boolean attributes are not treated correctly
if ( !div.querySelectorAll("[selected]").length ) {
rbuggyQSA.push("\\[[\\x20\\t\\n\\r\\f]*(?:checked|disabled|ismap|multiple|readonly|selected|value)");
}
// Webkit/Opera - :checked should return selected option elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
// IE8 throws error here (do not put tests after this one)
if ( !div.querySelectorAll(":checked").length ) {
rbuggyQSA.push(":checked");
}
});
assert(function( div ) {
// Opera 10/IE - ^= $= *= and empty values
div.innerHTML = "<p class=''></p>";
// Should not select anything
if ( div.querySelectorAll("[class^='']").length ) {
rbuggyQSA.push("[*^$]=[\\x20\\t\\n\\r\\f]*(?:\"\"|'')");
}
// FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled)
// IE8 throws error here (do not put tests after this one)
div.innerHTML = "<input type='hidden'>";
if ( !div.querySelectorAll(":enabled").length ) {
rbuggyQSA.push(":enabled", ":disabled");
}
});
rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") );
select = function( selector, context, results, seed, contextXML ) {
// Only use querySelectorAll when not filtering,
// when this is not xml,
// and when no QSA bugs apply
if ( !seed && !contextXML && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) {
if ( context.nodeType === 9 ) {
try {
return makeArray( context.querySelectorAll( selector ), results );
} catch(qsaError) {}
// qSA works strangely on Element-rooted queries
// We can work around this by specifying an extra ID on the root
// and working up from there (Thanks to Andrew Dupont for the technique)
// IE 8 doesn't work on object elements
} else if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
var oldContext = context,
old = context.getAttribute( "id" ),
nid = old || id,
parent = context.parentNode,
relativeHierarchySelector = rrelativeHierarchy.test( selector );
if ( !old ) {
context.setAttribute( "id", nid );
} else {
nid = nid.replace( rapostrophe, "\\$&" );
}
if ( relativeHierarchySelector && parent ) {
context = parent;
}
try {
if ( !relativeHierarchySelector || parent ) {
return makeArray( context.querySelectorAll( "[id='" + nid + "'] " + selector ), results );
}
} catch(qsaError) {
} finally {
if ( !old ) {
oldContext.removeAttribute( "id" );
}
}
}
}
return oldSelect( selector, context, results, seed, contextXML );
};
})();
}
function dirCheck( dir, checkSet, part, xml ) {
var elem, match, isElem, nodeCheck,
doneName = done++,
i = 0,
len = checkSet.length;
if ( typeof part === "string" && !rnonWord.test( part ) ) {
part = part.toLowerCase();
nodeCheck = part;
}
for ( ; i < len; i++ ) {
elem = checkSet[i];
if ( elem ) {
match = false;
elem = elem[ dir ];
while ( elem ) {
if ( elem[ expando ] === doneName ) {
match = checkSet[ elem.sizset ];
break;
}
isElem = elem.nodeType === 1;
if ( isElem && !xml ) {
elem[ expando ] = doneName;
elem.sizset = i;
}
if ( nodeCheck ) {
if ( elem.nodeName.toLowerCase() === part ) {
match = elem;
break;
}
} else if ( isElem ) {
if ( typeof part !== "string" ) {
if ( elem === part ) {
match = true;
break;
}
} else if ( Sizzle.filter( part, [elem] ).length > 0 ) {
match = elem;
break;
}
}
elem = elem[ dir ];
}
checkSet[i] = match;
}
}
}
var posProcess = function( selector, context, seed, contextXML ) {
var match,
tmpSet = [],
later = "",
root = context.nodeType ? [ context ] : context,
i = 0,
len = root.length;
// Position selectors must be done after the filter
// And so must :not(positional) so we move all PSEUDOs to the end
while ( (match = matchExpr.PSEUDO.exec( selector )) ) {
later += match[0];
selector = selector.replace( matchExpr.PSEUDO, "" );
}
if ( Expr.relative[ selector ] ) {
selector += "*";
}
for ( ; i < len; i++ ) {
select( selector, root[i], tmpSet, seed, contextXML );
}
return Sizzle.filter( later, tmpSet );
};
// EXPOSE
window.Sizzle = Sizzle;
})( window );
| sizzle.js | /*!
* Sizzle CSS Selector Engine
* Copyright 2011, The Dojo Foundation
* Released under the MIT, BSD, and GPL Licenses.
* More information: http://sizzlejs.com/
*/
(function( window, undefined ) {
var document = window.document,
docElem = document.documentElement,
expando = "sizcache" + (Math.random() + '').replace('.', ''),
done = 0,
toString = Object.prototype.toString,
strundefined = "undefined",
hasDuplicate = false,
baseHasDuplicate = true,
// Regex
rquickExpr = /^#([\w\-]+$)|^(\w+$)|^\.([\w\-]+$)/,
chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,
rbackslash = /\\/g,
rnonWord = /\W/,
rstartsWithWord = /^\w/,
rnonDigit = /\D/,
rnth = /(-?)(\d*)(?:n([+\-]?\d*))?/,
radjacent = /^\+|\s*/g,
rheader = /h\d/i,
rinputs = /input|select|textarea|button/i,
rtnfr = /[\t\n\f\r]/g,
characterEncoding = "(?:[-\\w]|[^\\x00-\\xa0]|\\\\.)",
matchExpr = {
ID: new RegExp("#(" + characterEncoding + "+)"),
CLASS: new RegExp("\\.(" + characterEncoding + "+)"),
NAME: new RegExp("\\[name=['\"]*(" + characterEncoding + "+)['\"]*\\]"),
TAG: new RegExp("^(" + characterEncoding.replace( "[-", "[-\\*" ) + "+)"),
ATTR: new RegExp("\\[\\s*(" + characterEncoding + "+)\\s*(?:(\\S?=)\\s*(?:(['\"])(.*?)\\3|(#?" + characterEncoding + "*)|)|)\\s*\\]"),
PSEUDO: new RegExp(":(" + characterEncoding + "+)(?:\\((['\"]?)((?:\\([^\\)]+\\)|[^\\(\\)]*)+)\\2\\))?"),
CHILD: /:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/,
POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/
},
// Expose origPOS
// "global" as in regardless of relation to brackets/parens
origPOS = matchExpr.globalPOS = matchExpr.POS,
leftMatchExpr = (function() {
var type,
// Increments parenthetical references
// for leftMatch creation
fescape = function( all, num ) {
return "\\" + (num - 0 + 1);
},
leftMatch = {};
for ( type in matchExpr ) {
// Modify the regexes ensuring the matches do not end in brackets/parens
matchExpr[ type ] = new RegExp( matchExpr[ type ].source + (/(?![^\[]*\])(?![^\(]*\))/.source) );
// Adds a capture group for characters left of the match
leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + matchExpr[ type ].source.replace( /\\(\d+)/g, fescape ) );
}
return leftMatch;
})(),
// Used for testing something on an element
assert = function( fn ) {
var pass = false,
div = document.createElement("div");
try {
pass = fn( div );
} catch (e) {}
// release memory in IE
div = null;
return pass;
},
// Check to see if the browser returns elements by name when
// querying by getElementById (and provide a workaround)
assertGetIdNotName = assert(function( div ) {
var pass = true,
id = "script" + (new Date()).getTime();
div.innerHTML = "<a name ='" + id + "'/>";
// Inject it into the root element, check its status, and remove it quickly
docElem.insertBefore( div, docElem.firstChild );
if ( document.getElementById( id ) ) {
pass = false;
}
docElem.removeChild( div );
return pass;
}),
// Check to see if the browser returns only elements
// when doing getElementsByTagName("*")
assertTagNameNoComments = assert(function( div ) {
div.appendChild( document.createComment("") );
return div.getElementsByTagName("*").length === 0;
}),
// Check to see if an attribute returns normalized href attributes
assertHrefNotNormalized = assert(function( div ) {
div.innerHTML = "<a href='#'></a>";
if ( div.firstChild && typeof div.firstChild.getAttribute !== strundefined &&
div.firstChild.getAttribute("href") !== "#" ) {
return false;
}
return true;
}),
// Determines a buggy getElementsByClassName
assertUsableClassName = assert(function( div ) {
// Opera can't find a second classname (in 9.6)
div.innerHTML = "<div class='test e'></div><div class='test'></div>";
if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) {
return false;
}
// Safari caches class attributes, doesn't catch changes (in 3.2)
div.lastChild.className = "e";
return div.getElementsByClassName("e").length !== 1;
});
// Check if the JavaScript engine is using some sort of
// optimization where it does not always call our comparision
// function. If that is the case, discard the hasDuplicate value.
// Thus far that includes Google Chrome.
[0, 0].sort(function() {
baseHasDuplicate = false;
return 0;
});
var Sizzle = function( selector, context, results ) {
results = results || [];
context = context || document;
var match, elem, contextXML,
nodeType = context.nodeType;
if ( nodeType !== 1 && nodeType !== 9 ) {
return [];
}
if ( !selector || typeof selector !== "string" ) {
return results;
}
contextXML = isXML( context );
if ( !contextXML ) {
if ( (match = rquickExpr.exec( selector )) ) {
// Speed-up: Sizzle("#ID")
if ( match[1] ) {
if ( nodeType === 9 ) {
elem = context.getElementById( match[1] );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE, Opera, and Webkit return items
// by name instead of ID
if ( elem.id === match[1] ) {
return makeArray( [ elem ], results );
}
} else {
return makeArray( [], results );
}
} else {
// Context is not a document
elem = context.ownerDocument && context.ownerDocument.getElementById( match[1] );
if ( contains(context, elem) && elem.id === match[1] ) {
return makeArray( [ elem ], results );
}
}
// Speed-up: Sizzle("TAG")
} else if ( match[2] ) {
// Speed-up: Sizzle("body")
if ( selector === "body" && context.body ) {
return makeArray( [ context.body ], results );
}
return makeArray( context.getElementsByTagName( selector ), results );
// Speed-up: Sizzle(".CLASS")
} else if ( assertUsableClassName && match[3] && context.getElementsByClassName ) {
return makeArray( context.getElementsByClassName( match[3] ), results );
}
}
}
// All others
return select( selector, context, results, undefined, contextXML );
};
var select = function( selector, context, results, seed, contextXML ) {
var m, set, checkSet, extra, ret, cur, pop, i,
origContext = context,
prune = true,
parts = [],
soFar = selector;
do {
// Reset the position of the chunker regexp (start from head)
chunker.exec( "" );
m = chunker.exec( soFar );
if ( m ) {
soFar = m[3];
parts.push( m[1] );
if ( m[2] ) {
extra = m[3];
break;
}
}
} while ( m );
if ( parts.length > 1 && origPOS.exec( selector ) ) {
if ( parts.length === 2 && Expr.relative[ parts[0] ] ) {
set = posProcess( parts[0] + parts[1], context, seed, contextXML );
} else {
set = Expr.relative[ parts[0] ] ?
[ context ] :
Sizzle( parts.shift(), context );
while ( parts.length ) {
selector = parts.shift();
if ( Expr.relative[ selector ] ) {
selector += parts.shift();
}
set = posProcess( selector, set, seed, contextXML );
}
}
} else {
// Take a shortcut and set the context if the root selector is an ID
// (but not if it'll be faster if the inner selector is an ID)
if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML &&
matchExpr.ID.test( parts[0] ) && !matchExpr.ID.test( parts[parts.length - 1] ) ) {
ret = Sizzle.find( parts.shift(), context, contextXML );
context = ret.expr ?
Sizzle.filter( ret.expr, ret.set )[0] :
ret.set[0];
}
if ( context ) {
ret = seed ?
{ expr: parts.pop(), set: makeArray( seed ) } :
Sizzle.find( parts.pop(), (parts.length >= 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode) || context, contextXML );
set = ret.expr ?
Sizzle.filter( ret.expr, ret.set ) :
ret.set;
if ( parts.length > 0 ) {
checkSet = makeArray( set );
} else {
prune = false;
}
while ( parts.length ) {
cur = parts.pop();
pop = cur;
if ( !Expr.relative[ cur ] ) {
cur = "";
} else {
pop = parts.pop();
}
if ( pop == null ) {
pop = context;
}
Expr.relative[ cur ]( checkSet, pop, contextXML );
}
} else {
checkSet = parts = [];
}
}
if ( !checkSet ) {
checkSet = set;
}
if ( !checkSet ) {
Sizzle.error( cur || selector );
}
if ( toString.call(checkSet) === "[object Array]" ) {
if ( !prune ) {
results.push.apply( results, checkSet );
} else if ( context && context.nodeType === 1 ) {
for ( i = 0; checkSet[i] != null; i++ ) {
if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && contains( context, checkSet[i] )) ) {
results.push( set[i] );
}
}
} else {
for ( i = 0; checkSet[i] != null; i++ ) {
if ( checkSet[i] && checkSet[i].nodeType === 1 ) {
results.push( set[i] );
}
}
}
} else {
makeArray( checkSet, results );
}
if ( extra ) {
select( extra, origContext, results, seed, contextXML );
uniqueSort( results );
}
return results;
};
var isXML = Sizzle.isXML = function( elem ) {
// documentElement is verified for cases where it doesn't yet exist
// (such as loading iframes in IE - #4833)
var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement;
return documentElement ? documentElement.nodeName !== "HTML" : false;
};
// Slice is no longer used
// It is not actually faster
// Results is expected to be an array or undefined
// typeof len is checked for if array is a form nodelist containing an element with name "length" (wow)
var makeArray = function( array, results ) {
results = results || [];
var i = 0,
len = array.length;
if ( typeof len === "number" ) {
for ( ; i < len; i++ ) {
results.push( array[i] );
}
} else {
for ( ; array[i]; i++ ) {
results.push( array[i] );
}
}
return results;
};
var uniqueSort = Sizzle.uniqueSort = function( results ) {
if ( sortOrder ) {
hasDuplicate = baseHasDuplicate;
results.sort( sortOrder );
if ( hasDuplicate ) {
for ( var i = 1; i < results.length; i++ ) {
if ( results[i] === results[ i - 1 ] ) {
results.splice( i--, 1 );
}
}
}
}
return results;
};
// Element contains another
var contains = Sizzle.contains = docElem.compareDocumentPosition ?
function( a, b ) {
return !!(a.compareDocumentPosition( b ) & 16);
} :
docElem.contains ?
function( a, b ) {
return a !== b && ( a.contains ? a.contains( b ) : false );
} :
function( a, b ) {
while ( (b = b.parentNode) ) {
if ( b === a ) {
return true;
}
}
return false;
};
Sizzle.matches = function( expr, set ) {
return select( expr, document, [], set, isXML( document ) );
};
Sizzle.matchesSelector = function( node, expr ) {
return select( expr, document, [], [ node ], isXML( document ) ).length > 0;
};
Sizzle.find = function( expr, context, contextXML ) {
var set, i, len, match, type, left;
if ( !expr ) {
return [];
}
for ( i = 0, len = Expr.order.length; i < len; i++ ) {
type = Expr.order[i];
if ( (match = leftMatchExpr[ type ].exec( expr )) ) {
left = match[1];
match.splice( 1, 1 );
if ( left.substr( left.length - 1 ) !== "\\" ) {
match[1] = (match[1] || "").replace( rbackslash, "" );
set = Expr.find[ type ]( match, context, contextXML );
if ( set != null ) {
expr = expr.replace( matchExpr[ type ], "" );
break;
}
}
}
}
if ( !set ) {
set = typeof context.getElementsByTagName !== strundefined ?
context.getElementsByTagName( "*" ) :
[];
}
return { set: set, expr: expr };
};
Sizzle.filter = function( expr, set, inplace, not ) {
var match, anyFound,
type, found, item, filter, left,
i, pass,
old = expr,
result = [],
curLoop = set,
isXMLFilter = set && set[0] && isXML( set[0] );
while ( expr && set.length ) {
for ( type in Expr.filter ) {
if ( (match = leftMatchExpr[ type ].exec( expr )) != null && match[2] ) {
filter = Expr.filter[ type ];
left = match[1];
anyFound = false;
match.splice(1,1);
if ( left.substr( left.length - 1 ) === "\\" ) {
continue;
}
if ( curLoop === result ) {
result = [];
}
if ( Expr.preFilter[ type ] ) {
match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter );
if ( !match ) {
anyFound = found = true;
} else if ( match === true ) {
continue;
}
}
if ( match ) {
for ( i = 0; (item = curLoop[i]) != null; i++ ) {
if ( item ) {
found = filter( item, match, i, curLoop );
pass = not ^ found;
if ( inplace && found != null ) {
if ( pass ) {
anyFound = true;
} else {
curLoop[i] = false;
}
} else if ( pass ) {
result.push( item );
anyFound = true;
}
}
}
}
if ( found !== undefined ) {
if ( !inplace ) {
curLoop = result;
}
expr = expr.replace( matchExpr[ type ], "" );
if ( !anyFound ) {
return [];
}
break;
}
}
}
// Improper expression
if ( expr === old ) {
if ( anyFound == null ) {
Sizzle.error( expr );
} else {
break;
}
}
old = expr;
}
return curLoop;
};
Sizzle.error = function( msg ) {
throw new Error( "Syntax error, unrecognized expression: " + msg );
};
/**
* Utility function for retreiving the text value of an array of DOM nodes
* @param {Array|Element} elem
*/
var getText = Sizzle.getText = function( elem ) {
var i, node,
nodeType = elem.nodeType,
ret = "";
if ( nodeType ) {
if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
// Use textContent for elements
// innerText usage removed for consistency of new lines (see #11153)
if ( typeof elem.textContent === "string" ) {
return elem.textContent;
} else {
// Traverse it's children
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
ret += getText( elem );
}
}
} else if ( nodeType === 3 || nodeType === 4 ) {
return elem.nodeValue;
}
} else {
// If no nodeType, this is expected to be an array
for ( i = 0; (node = elem[i]); i++ ) {
// Do not traverse comment nodes
if ( node.nodeType !== 8 ) {
ret += getText( node );
}
}
}
return ret;
};
var Expr = Sizzle.selectors = {
match: matchExpr,
leftMatch: leftMatchExpr,
order: [ "ID", "NAME", "TAG" ],
attrMap: {
"class": "className",
"for": "htmlFor"
},
attrHandle: {
href: assertHrefNotNormalized ?
function( elem ) {
return elem.getAttribute( "href" );
} :
function( elem ) {
return elem.getAttribute( "href", 2 );
},
type: function( elem ) {
return elem.getAttribute( "type" );
}
},
relative: {
"+": function( checkSet, part ) {
var isPartStr = typeof part === "string",
isTag = isPartStr && !rnonWord.test( part ),
isPartStrNotTag = isPartStr && !isTag;
if ( isTag ) {
part = part.toLowerCase();
}
for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) {
if ( (elem = checkSet[i]) ) {
while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {}
checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ?
elem || false :
elem === part;
}
}
if ( isPartStrNotTag ) {
Sizzle.filter( part, checkSet, true );
}
},
">": function( checkSet, part ) {
var elem,
isPartStr = typeof part === "string",
i = 0,
l = checkSet.length;
if ( isPartStr && !rnonWord.test( part ) ) {
part = part.toLowerCase();
for ( ; i < l; i++ ) {
elem = checkSet[i];
if ( elem ) {
var parent = elem.parentNode;
checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false;
}
}
} else {
for ( ; i < l; i++ ) {
elem = checkSet[i];
if ( elem ) {
checkSet[i] = isPartStr ?
elem.parentNode :
elem.parentNode === part;
}
}
if ( isPartStr ) {
Sizzle.filter( part, checkSet, true );
}
}
},
"": function( checkSet, part, xml ) {
dirCheck( "parentNode", checkSet, part, xml );
},
"~": function( checkSet, part, xml ) {
dirCheck( "previousSibling", checkSet, part, xml );
}
},
find: {
ID: assertGetIdNotName ?
function( match, context, xml ) {
if ( typeof context.getElementById !== strundefined && !xml ) {
var m = context.getElementById( match[1] );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
return m && m.parentNode ? [m] : [];
}
} :
function( match, context, xml ) {
if ( typeof context.getElementById !== strundefined && !xml ) {
var m = context.getElementById( match[1] );
return m ?
m.id === match[1] || typeof m.getAttributeNode !== strundefined && m.getAttributeNode("id").nodeValue === match[1] ?
[m] :
undefined :
[];
}
},
NAME: function( match, context ) {
if ( typeof context.getElementsByName !== strundefined ) {
var ret = [],
results = context.getElementsByName( match[1] ),
i = 0,
len = results.length;
for ( ; i < len; i++ ) {
if ( results[i].getAttribute("name") === match[1] ) {
ret.push( results[i] );
}
}
return ret.length === 0 ? null : ret;
}
},
TAG: assertTagNameNoComments ?
function( match, context ) {
if ( typeof context.getElementsByTagName !== strundefined ) {
return context.getElementsByTagName( match[1] );
}
} :
function( match, context ) {
var results = context.getElementsByTagName( match[1] );
// Filter out possible comments
if ( match[1] === "*" ) {
var tmp = [],
i = 0;
for ( ; results[i]; i++ ) {
if ( results[i].nodeType === 1 ) {
tmp.push( results[i] );
}
}
results = tmp;
}
return results;
}
},
preFilter: {
CLASS: function( match, curLoop, inplace, result, not, xml ) {
match = " " + match[1].replace( rbackslash, "" ) + " ";
if ( xml ) {
return match;
}
for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) {
if ( elem ) {
if ( not ^ (elem.className && (" " + elem.className + " ").replace( rtnfr, " " ).indexOf( match ) >= 0) ) {
if ( !inplace ) {
result.push( elem );
}
} else if ( inplace ) {
curLoop[i] = false;
}
}
}
return false;
},
ID: function( match ) {
return match[1].replace( rbackslash, "" );
},
TAG: function( match, curLoop ) {
return match[1].replace( rbackslash, "" ).toLowerCase();
},
CHILD: function( match ) {
if ( match[1] === "nth" ) {
if ( !match[2] ) {
Sizzle.error( match[0] );
}
match[2] = match[2].replace( radjacent, "" );
// parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6'
var test = rnth.exec(
match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" ||
!rnonDigit.test( match[2] ) && "0n+" + match[2] || match[2] );
// calculate the numbers (first)n+(last) including if they are negative
match[2] = (test[1] + (test[2] || 1)) - 0;
match[3] = test[3] - 0;
} else if ( match[2] ) {
Sizzle.error( match[0] );
}
// TODO: Move to normal caching system
match[0] = done++;
return match;
},
ATTR: function( match, curLoop, inplace, result, not, xml ) {
var name = match[1] = match[1].replace( rbackslash, "" );
if ( !xml && Expr.attrMap[ name ] ) {
match[1] = Expr.attrMap[ name ];
}
// Handle if an un-quoted value was used
match[4] = ( match[4] || match[5] || "" ).replace( rbackslash, "" );
if ( match[2] === "~=" ) {
match[4] = " " + match[4] + " ";
}
return match;
},
PSEUDO: function( match, curLoop, inplace, result, not, xml ) {
if ( match[1] === "not" ) {
// If we're dealing with a complex expression, or a simple one
if ( ( chunker.exec( match[3] ) || "" ).length > 1 || rstartsWithWord.test( match[3] ) ) {
match[3] = select( match[3], document, [], curLoop, xml );
} else {
var ret = Sizzle.filter( match[3], curLoop, inplace, !not );
if ( !inplace ) {
result.push.apply( result, ret );
}
return false;
}
} else if ( matchExpr.POS.test( match[0] ) || matchExpr.CHILD.test( match[0] ) ) {
return true;
}
return match;
},
POS: function( match ) {
match.unshift( true );
return match;
}
},
filters: {
enabled: function( elem ) {
return elem.disabled === false;
},
disabled: function( elem ) {
return elem.disabled === true;
},
checked: function( elem ) {
// In CSS3, :checked should return both checked and selected elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
var nodeName = elem.nodeName.toLowerCase();
return (nodeName === "input" && !! elem.checked) || (nodeName === "option" && !!elem.selected);
},
selected: function( elem ) {
// Accessing this property makes selected-by-default
// options in Safari work properly
if ( elem.parentNode ) {
elem.parentNode.selectedIndex;
}
return elem.selected === true;
},
parent: function( elem ) {
return !!elem.firstChild;
},
empty: function( elem ) {
return !elem.firstChild;
},
has: function( elem, i, match ) {
return !!Sizzle( match[3], elem ).length;
},
header: function( elem ) {
return rheader.test( elem.nodeName );
},
text: function( elem ) {
var attr = elem.getAttribute( "type" ), type = elem.type;
// IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc)
// use getAttribute instead to test this case
return elem.nodeName.toLowerCase() === "input" && "text" === type && ( attr === null || attr.toLowerCase() === type );
},
radio: function( elem ) {
return elem.nodeName.toLowerCase() === "input" && "radio" === elem.type;
},
checkbox: function( elem ) {
return elem.nodeName.toLowerCase() === "input" && "checkbox" === elem.type;
},
file: function( elem ) {
return elem.nodeName.toLowerCase() === "input" && "file" === elem.type;
},
password: function( elem ) {
return elem.nodeName.toLowerCase() === "input" && "password" === elem.type;
},
submit: function( elem ) {
var name = elem.nodeName.toLowerCase();
return (name === "input" || name === "button") && "submit" === elem.type;
},
image: function( elem ) {
return elem.nodeName.toLowerCase() === "input" && "image" === elem.type;
},
reset: function( elem ) {
var name = elem.nodeName.toLowerCase();
return (name === "input" || name === "button") && "reset" === elem.type;
},
button: function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && "button" === elem.type || name === "button";
},
input: function( elem ) {
return rinputs.test( elem.nodeName );
},
focus: function( elem ) {
var doc = elem.ownerDocument;
return elem === doc.activeElement && (!doc.hasFocus || doc.hasFocus()) && !!(elem.type || elem.href);
},
active: function( elem ) {
return elem === elem.ownerDocument.activeElement;
},
contains: function( elem, i, match ) {
return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( match[3] ) >= 0;
}
},
setFilters: {
first: function( elem, i ) {
return i === 0;
},
last: function( elem, i, match, array ) {
return i === array.length - 1;
},
even: function( elem, i ) {
return i % 2 === 0;
},
odd: function( elem, i ) {
return i % 2 === 1;
},
lt: function( elem, i, match ) {
return i < match[3] - 0;
},
gt: function( elem, i, match ) {
return i > match[3] - 0;
},
nth: function( elem, i, match ) {
return match[3] - 0 === i;
},
eq: function( elem, i, match ) {
return match[3] - 0 === i;
}
},
filter: {
PSEUDO: function( elem, match, i, array ) {
var name = match[1],
filter = Expr.filters[ name ];
if ( filter ) {
return filter( elem, i, match, array );
} else if ( name === "not" ) {
var not = match[3],
j = 0,
len = not.length;
for ( ; j < len; j++ ) {
if ( not[j] === elem ) {
return false;
}
}
return true;
} else {
Sizzle.error( name );
}
},
CHILD: function( elem, match ) {
var first, last,
doneName, parent, cache,
count, diff,
type = match[1],
node = elem;
switch ( type ) {
case "only":
case "first":
while ( (node = node.previousSibling) ) {
if ( node.nodeType === 1 ) {
return false;
}
}
if ( type === "first" ) {
return true;
}
node = elem;
/* falls through */
case "last":
while ( (node = node.nextSibling) ) {
if ( node.nodeType === 1 ) {
return false;
}
}
return true;
case "nth":
first = match[2];
last = match[3];
if ( first === 1 && last === 0 ) {
return true;
}
doneName = match[0];
parent = elem.parentNode;
if ( parent && (parent[ expando ] !== doneName || !elem.nodeIndex) ) {
count = 0;
for ( node = parent.firstChild; node; node = node.nextSibling ) {
if ( node.nodeType === 1 ) {
node.nodeIndex = ++count;
}
}
parent[ expando ] = doneName;
}
diff = elem.nodeIndex - last;
if ( first === 0 ) {
return diff === 0;
} else {
return ( diff % first === 0 && diff / first >= 0 );
}
}
},
ID: assertGetIdNotName ?
function( elem, match ) {
return elem.nodeType === 1 && elem.getAttribute("id") === match;
} :
function( elem, match ) {
var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id");
return elem.nodeType === 1 && node && node.nodeValue === match;
},
TAG: function( elem, match ) {
return ( match === "*" && elem.nodeType === 1 ) || !!elem.nodeName && elem.nodeName.toLowerCase() === match;
},
CLASS: function( elem, match ) {
return ( " " + ( elem.className || elem.getAttribute("class") ) + " " ).indexOf( match ) > -1;
},
ATTR: function( elem, match ) {
var name = match[1],
result = Sizzle.attr ?
Sizzle.attr( elem, name ) :
Expr.attrHandle[ name ] ?
Expr.attrHandle[ name ]( elem ) :
elem[ name ] != null ?
elem[ name ] :
elem.getAttribute( name ),
value = result + "",
type = match[2],
check = match[4];
return result == null ?
type === "!=" :
!type && Sizzle.attr ?
result != null :
type === "=" ?
value === check :
type === "*=" ?
value.indexOf( check ) >= 0 :
type === "~=" ?
( " " + value + " " ).indexOf( check ) >= 0 :
!check ?
value && result !== false :
type === "!=" ?
value !== check :
type === "^=" ?
value.indexOf( check ) === 0 :
type === "$=" ?
value.substr( value.length - check.length ) === check :
type === "|=" ?
value === check || value.substr( 0, check.length + 1 ) === check + "-" :
false;
},
POS: function( elem, match, i, array ) {
var name = match[2],
filter = Expr.setFilters[ name ];
if ( filter ) {
return filter( elem, i, match, array );
}
}
}
};
// Add getElementsByClassName if usable
if ( assertUsableClassName ) {
Expr.order.splice( 1, 0, "CLASS" );
Expr.find.CLASS = function( match, context, xml ) {
if ( typeof context.getElementsByClassName !== strundefined && !xml ) {
return context.getElementsByClassName( match[1] );
}
};
}
var sortOrder, siblingCheck;
if ( docElem.compareDocumentPosition ) {
sortOrder = function( a, b ) {
if ( a === b ) {
hasDuplicate = true;
return 0;
}
if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) {
return a.compareDocumentPosition ? -1 : 1;
}
return a.compareDocumentPosition(b) & 4 ? -1 : 1;
};
} else {
sortOrder = function( a, b ) {
// The nodes are identical, we can exit early
if ( a === b ) {
hasDuplicate = true;
return 0;
// Fallback to using sourceIndex (in IE) if it's available on both nodes
} else if ( a.sourceIndex && b.sourceIndex ) {
return a.sourceIndex - b.sourceIndex;
}
var al, bl,
ap = [],
bp = [],
aup = a.parentNode,
bup = b.parentNode,
cur = aup;
// If the nodes are siblings (or identical) we can do a quick check
if ( aup === bup ) {
return siblingCheck( a, b );
// If no parents were found then the nodes are disconnected
} else if ( !aup ) {
return -1;
} else if ( !bup ) {
return 1;
}
// Otherwise they're somewhere else in the tree so we need
// to build up a full list of the parentNodes for comparison
while ( cur ) {
ap.unshift( cur );
cur = cur.parentNode;
}
cur = bup;
while ( cur ) {
bp.unshift( cur );
cur = cur.parentNode;
}
al = ap.length;
bl = bp.length;
// Start walking down the tree looking for a discrepancy
for ( var i = 0; i < al && i < bl; i++ ) {
if ( ap[i] !== bp[i] ) {
return siblingCheck( ap[i], bp[i] );
}
}
// We ended someplace up the tree so do a sibling check
return i === al ?
siblingCheck( a, bp[i], -1 ) :
siblingCheck( ap[i], b, 1 );
};
siblingCheck = function( a, b, ret ) {
if ( a === b ) {
return ret;
}
var cur = a.nextSibling;
while ( cur ) {
if ( cur === b ) {
return -1;
}
cur = cur.nextSibling;
}
return 1;
};
}
if ( document.querySelectorAll ) {
(function(){
var oldSelect = select,
id = "__sizzle__",
rrelativeHierarchy = /^\s*[+~]/,
rapostrophe = /'/g,
// Build QSA regex
// Regex strategy adopted from Diego Perini
rbuggyQSA = [];
assert(function( div ) {
div.innerHTML = "<select><option selected></option></select>";
// IE8 - Some boolean attributes are not treated correctly
if ( !div.querySelectorAll("[selected]").length ) {
rbuggyQSA.push("\\[[\\x20\\t\\n\\r\\f]*(?:checked|disabled|ismap|multiple|readonly|selected|value)");
}
// Webkit/Opera - :checked should return selected option elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
// IE8 throws error here (do not put tests after this one)
if ( !div.querySelectorAll(":checked").length ) {
rbuggyQSA.push(":checked");
}
});
assert(function( div ) {
// Opera 10/IE - ^= $= *= and empty values
div.innerHTML = "<p class=''></p>";
// Should not select anything
if ( div.querySelectorAll("[class^='']").length ) {
rbuggyQSA.push("[*^$]=[\\x20\\t\\n\\r\\f]*(?:\"\"|'')");
}
// FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled)
// IE8 throws error here (do not put tests after this one)
div.innerHTML = "<input type='hidden'>";
if ( !div.querySelectorAll(":enabled").length ) {
rbuggyQSA.push(":enabled", ":disabled");
}
});
rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") );
select = function( selector, context, results, seed, contextXML ) {
// Only use querySelectorAll when not filtering,
// when this is not xml,
// and when no QSA bugs apply
if ( !seed && !contextXML && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) {
if ( context.nodeType === 9 ) {
try {
return makeArray( context.querySelectorAll( selector ), results );
} catch(qsaError) {}
// qSA works strangely on Element-rooted queries
// We can work around this by specifying an extra ID on the root
// and working up from there (Thanks to Andrew Dupont for the technique)
// IE 8 doesn't work on object elements
} else if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
var oldContext = context,
old = context.getAttribute( "id" ),
nid = old || id,
parent = context.parentNode,
relativeHierarchySelector = rrelativeHierarchy.test( selector );
if ( !old ) {
context.setAttribute( "id", nid );
} else {
nid = nid.replace( rapostrophe, "\\$&" );
}
if ( relativeHierarchySelector && parent ) {
context = parent;
}
try {
if ( !relativeHierarchySelector || parent ) {
return makeArray( context.querySelectorAll( "[id='" + nid + "'] " + selector ), results );
}
} catch(qsaError) {
} finally {
if ( !old ) {
oldContext.removeAttribute( "id" );
}
}
}
}
return oldSelect( selector, context, results, seed, contextXML );
};
})();
}
function dirCheck( dir, checkSet, part, xml ) {
var elem, match, isElem, nodeCheck,
doneName = done++,
i = 0,
len = checkSet.length;
if ( typeof part === "string" && !rnonWord.test( part ) ) {
part = part.toLowerCase();
nodeCheck = part;
}
for ( ; i < len; i++ ) {
elem = checkSet[i];
if ( elem ) {
match = false;
elem = elem[ dir ];
while ( elem ) {
if ( elem[ expando ] === doneName ) {
match = checkSet[ elem.sizset ];
break;
}
isElem = elem.nodeType === 1;
if ( isElem && !xml ) {
elem[ expando ] = doneName;
elem.sizset = i;
}
if ( nodeCheck ) {
if ( elem.nodeName.toLowerCase() === part ) {
match = elem;
break;
}
} else if ( isElem ) {
if ( typeof part !== "string" ) {
if ( elem === part ) {
match = true;
break;
}
} else if ( Sizzle.filter( part, [elem] ).length > 0 ) {
match = elem;
break;
}
}
elem = elem[ dir ];
}
checkSet[i] = match;
}
}
}
var posProcess = function( selector, context, seed, contextXML ) {
var match,
tmpSet = [],
later = "",
root = context.nodeType ? [context] : context;
// Position selectors must be done after the filter
// And so must :not(positional) so we move all PSEUDOs to the end
while ( (match = matchExpr.PSEUDO.exec( selector )) ) {
later += match[0];
selector = selector.replace( matchExpr.PSEUDO, "" );
}
selector = Expr.relative[selector] ? selector + "*" : selector;
for ( var i = 0, l = root.length; i < l; i++ ) {
select( selector, root[i], tmpSet, seed, contextXML );
}
return Sizzle.filter( later, tmpSet );
};
// EXPOSE
window.Sizzle = Sizzle;
})( window );
| Expose origPOS after generating leftMatch expressions. | sizzle.js | Expose origPOS after generating leftMatch expressions. | <ide><path>izzle.js
<ide> POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/
<ide> },
<ide>
<del> // Expose origPOS
<del> // "global" as in regardless of relation to brackets/parens
<del> origPOS = matchExpr.globalPOS = matchExpr.POS,
<add> origPOS = matchExpr.POS,
<ide>
<ide> leftMatchExpr = (function() {
<ide> var type,
<ide> // Increments parenthetical references
<ide> // for leftMatch creation
<ide> fescape = function( all, num ) {
<del> return "\\" + (num - 0 + 1);
<add> return "\\" + ( num - 0 + 1 );
<ide> },
<ide> leftMatch = {};
<ide>
<ide> // Adds a capture group for characters left of the match
<ide> leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + matchExpr[ type ].source.replace( /\\(\d+)/g, fescape ) );
<ide> }
<add>
<add> // Expose origPOS
<add> // "global" as in regardless of relation to brackets/parens
<add> matchExpr.globalPOS = origPOS;
<add>
<ide> return leftMatch;
<ide> })(),
<ide>
<ide>
<ide> anyFound = false;
<ide>
<del> match.splice(1,1);
<add> match.splice( 1, 1 );
<ide>
<ide> if ( left.substr( left.length - 1 ) === "\\" ) {
<ide> continue;
<ide> var match,
<ide> tmpSet = [],
<ide> later = "",
<del> root = context.nodeType ? [context] : context;
<add> root = context.nodeType ? [ context ] : context,
<add> i = 0,
<add> len = root.length;
<ide>
<ide> // Position selectors must be done after the filter
<ide> // And so must :not(positional) so we move all PSEUDOs to the end
<ide> selector = selector.replace( matchExpr.PSEUDO, "" );
<ide> }
<ide>
<del> selector = Expr.relative[selector] ? selector + "*" : selector;
<del>
<del> for ( var i = 0, l = root.length; i < l; i++ ) {
<add> if ( Expr.relative[ selector ] ) {
<add> selector += "*";
<add> }
<add>
<add> for ( ; i < len; i++ ) {
<ide> select( selector, root[i], tmpSet, seed, contextXML );
<ide> }
<ide> |
|
Java | apache-2.0 | cb075659a5e82686941904a9af6735196f4af1e4 | 0 | Jhuster/Android,Jhuster/Android,Jhuster/Android,Jhuster/Android | import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.util.Log;
public class AudioCapturer {
private static final String TAG = "AudioCapturer";
private static final int DEFAULT_SOURCE = MediaRecorder.AudioSource.MIC;
private static final int DEFAULT_SAMPLE_RATE = 44100;
private static final int DEFAULT_CHANNEL_CONFIG = AudioFormat.CHANNEL_IN_MONO;
private static final int DEFAULT_AUDIO_FORMAT = AudioFormat.ENCODING_PCM_16BIT;
private AudioRecord mAudioRecord;
private int mMinBufferSize = 0;
private Thread mCaptureThread;
private boolean mIsCaptureStarted = false;
private volatile boolean mIsLoopExit = false;
private OnAudioFrameCapturedListener mAudioFrameCapturedListener;
public interface OnAudioFrameCapturedListener {
public void onAudioFrameCaptured(byte[] audioData);
}
public boolean isCaptureStarted() {
return mIsCaptureStarted;
}
public void setOnAudioFrameCapturedListener(OnAudioFrameCapturedListener listener) {
mAudioFrameCapturedListener = listener;
}
public boolean startCapture() {
return startCapture(DEFAULT_SOURCE, DEFAULT_SAMPLE_RATE, DEFAULT_CHANNEL_CONFIG,
DEFAULT_AUDIO_FORMAT);
}
public boolean startCapture(int audioSource, int sampleRateInHz, int channelConfig, int audioFormat) {
if (mIsCaptureStarted) {
Log.e(TAG, "Capture already started !");
return false;
}
mMinBufferSize = AudioRecord.getMinBufferSize(sampleRateInHz,channelConfig,audioFormat);
if (mMinBufferSize == AudioRecord.ERROR_BAD_VALUE) {
Log.e(TAG, "Invalid parameter !");
return false;
}
Log.d(TAG , "getMinBufferSize = "+mMinBufferSize+" bytes !");
mAudioRecord = new AudioRecord(audioSource,sampleRateInHz,channelConfig,audioFormat,mMinBufferSize);
if (mAudioRecord.getState() == AudioRecord.STATE_UNINITIALIZED) {
Log.e(TAG, "AudioRecord initialize fail !");
return false;
}
mAudioRecord.startRecording();
mIsLoopExit = false;
mCaptureThread = new Thread(new AudioCaptureRunnable());
mCaptureThread.start();
mIsCaptureStarted = true;
Log.d(TAG, "Start audio capture success !");
return true;
}
public void stopCapture() {
if (!mIsCaptureStarted) {
return;
}
mIsLoopExit = false;
try {
mCaptureThread.interrupt();
mCaptureThread.join(1000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
if (mAudioRecord.getRecordingState() == AudioRecord.RECORDSTATE_RECORDING) {
mAudioRecord.stop();
}
mAudioRecord.release();
mIsCaptureStarted = false;
mAudioFrameCapturedListener = null;
Log.d(TAG, "Stop audio capture success !");
}
private class AudioCaptureRunnable implements Runnable {
@Override
public void run() {
while (!mIsLoopExit) {
byte[] buffer = new byte[mMinBufferSize];
int ret = mAudioRecord.read(buffer, 0, mMinBufferSize);
if (ret == AudioRecord.ERROR_INVALID_OPERATION) {
Log.e(TAG , "Error ERROR_INVALID_OPERATION");
}
else if (ret == AudioRecord.ERROR_BAD_VALUE) {
Log.e(TAG , "Error ERROR_BAD_VALUE");
}
else if (ret == AudioRecord.ERROR_INVALID_OPERATION) {
Log.e(TAG , "Error ERROR_INVALID_OPERATION");
}
else {
if (mAudioFrameCapturedListener != null) {
mAudioFrameCapturedListener.onAudioFrameCaptured(buffer);
}
Log.d(TAG , "OK, Captured "+ret+" bytes !");
}
}
}
}
}
| Audio/AudioCapturer.java | import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.util.Log;
public class AudioCapturer {
private static final String TAG = "AudioCapturer";
private static final int DEFAULT_SOURCE = MediaRecorder.AudioSource.MIC;
private static final int DEFAULT_SAMPLE_RATE = 44100;
private static final int DEFAULT_CHANNEL_CONFIG = AudioFormat.CHANNEL_IN_MONO;
private static final int DEFAULT_AUDIO_FORMAT = AudioFormat.ENCODING_PCM_16BIT;
private AudioRecord mAudioRecord;
private int mMinBufferSize = 0;
private Thread mCaptureThread;
private boolean mIsCaptureStarted = false;
private volatile boolean mIsLoopExit = false;
private OnAudioFrameCapturedListener mAudioFrameCapturedListener;
public interface OnAudioFrameCapturedListener {
public void onAudioFrameCaptured(byte[] audioData);
}
public boolean isCaptureStarted() {
return mIsCaptureStarted;
}
public void setOnAudioFrameCapturedListener(OnAudioFrameCapturedListener listener) {
mAudioFrameCapturedListener = listener;
}
public boolean startCapture() {
return startCapture(DEFAULT_SOURCE, DEFAULT_SAMPLE_RATE, DEFAULT_CHANNEL_CONFIG,
DEFAULT_AUDIO_FORMAT);
}
public boolean startCapture(int audioSource, int sampleRateInHz, int channelConfig, int audioFormat) {
if (mIsCaptureStarted) {
Log.e(TAG, "Capture already started !");
return false;
}
mMinBufferSize = AudioRecord.getMinBufferSize(sampleRateInHz,channelConfig,audioFormat);
if (mMinBufferSize == AudioRecord.ERROR_BAD_VALUE) {
Log.e(TAG, "Invalid parameter !");
return false;
}
Log.d(TAG , "getMinBufferSize = "+mMinBufferSize+" bytes !");
mAudioRecord = new AudioRecord(audioSource,sampleRateInHz,channelConfig,audioFormat,mMinBufferSize);
if (mAudioRecord.getState() == AudioRecord.STATE_UNINITIALIZED) {
Log.e(TAG, "AudioRecord initialize fail !");
return false;
}
mAudioRecord.startRecording();
mIsLoopExit = false;
mCaptureThread = new Thread(new AudioCaptureRunnable());
mCaptureThread.start();
mIsCaptureStarted = true;
Log.d(TAG, "Start audio capture success !");
return true;
}
public void stopCapture() {
if (!mIsCaptureStarted) {
return;
}
mIsLoopExit = false;
try {
mCaptureThread.interrupt();
mCaptureThread.join(1000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
if (mAudioRecord.getRecordingState() == AudioRecord.RECORDSTATE_RECORDING) {
mAudioRecord.stop();
}
mAudioRecord.release();
mIsCaptureStarted = false;
mAudioFrameCapturedListener = null;
Log.d(TAG, "Stop audio capture success !");
}
private class AudioCaptureRunnable implements Runnable {
@Override
public void run() {
while (!mIsLoopExit) {
byte[] buffer = new byte[mMinBufferSize];
int ret = mAudioRecord.read(buffer, 0, mMinBufferSize);
if (ret == AudioRecord.ERROR_INVALID_OPERATION) {
Log.e(TAG , "Error ERROR_INVALID_OPERATION");
}
else if (ret == AudioRecord.ERROR_BAD_VALUE) {
Log.e(TAG , "Error ERROR_BAD_VALUE");
}
else if (ret == AudioRecord.ERROR_INVALID_OPERATION) {
Log.e(TAG , "Error ERROR_INVALID_OPERATION");
}
else {
if (mAudioFrameCapturedListener != null) {
mAudioFrameCapturedListener.onAudioFrameCaptured(buffer);
}
Log.d(TAG , "OK, Captured "+ret+" bytes !");
}
}
}
}
}
| Update AudioCapturer.java | Audio/AudioCapturer.java | Update AudioCapturer.java | <ide><path>udio/AudioCapturer.java
<ide>
<ide> public class AudioCapturer {
<ide>
<del> private static final String TAG = "AudioCapturer";
<add> private static final String TAG = "AudioCapturer";
<ide>
<del> private static final int DEFAULT_SOURCE = MediaRecorder.AudioSource.MIC;
<del> private static final int DEFAULT_SAMPLE_RATE = 44100;
<del> private static final int DEFAULT_CHANNEL_CONFIG = AudioFormat.CHANNEL_IN_MONO;
<del> private static final int DEFAULT_AUDIO_FORMAT = AudioFormat.ENCODING_PCM_16BIT;
<add> private static final int DEFAULT_SOURCE = MediaRecorder.AudioSource.MIC;
<add> private static final int DEFAULT_SAMPLE_RATE = 44100;
<add> private static final int DEFAULT_CHANNEL_CONFIG = AudioFormat.CHANNEL_IN_MONO;
<add> private static final int DEFAULT_AUDIO_FORMAT = AudioFormat.ENCODING_PCM_16BIT;
<add>
<add> private AudioRecord mAudioRecord;
<add> private int mMinBufferSize = 0;
<ide>
<del> private AudioRecord mAudioRecord;
<del> private int mMinBufferSize = 0;
<add> private Thread mCaptureThread;
<add> private boolean mIsCaptureStarted = false;
<add> private volatile boolean mIsLoopExit = false;
<add>
<add> private OnAudioFrameCapturedListener mAudioFrameCapturedListener;
<add>
<add> public interface OnAudioFrameCapturedListener {
<add> public void onAudioFrameCaptured(byte[] audioData);
<add> }
<add>
<add> public boolean isCaptureStarted() {
<add> return mIsCaptureStarted;
<add> }
<add>
<add> public void setOnAudioFrameCapturedListener(OnAudioFrameCapturedListener listener) {
<add> mAudioFrameCapturedListener = listener;
<add> }
<add>
<add> public boolean startCapture() {
<add> return startCapture(DEFAULT_SOURCE, DEFAULT_SAMPLE_RATE, DEFAULT_CHANNEL_CONFIG,
<add> DEFAULT_AUDIO_FORMAT);
<add> }
<add>
<add> public boolean startCapture(int audioSource, int sampleRateInHz, int channelConfig, int audioFormat) {
<add>
<add> if (mIsCaptureStarted) {
<add> Log.e(TAG, "Capture already started !");
<add> return false;
<add> }
<add>
<add> mMinBufferSize = AudioRecord.getMinBufferSize(sampleRateInHz,channelConfig,audioFormat);
<add> if (mMinBufferSize == AudioRecord.ERROR_BAD_VALUE) {
<add> Log.e(TAG, "Invalid parameter !");
<add> return false;
<add> }
<add> Log.d(TAG , "getMinBufferSize = "+mMinBufferSize+" bytes !");
<ide>
<del> private Thread mCaptureThread;
<del> private boolean mIsCaptureStarted = false;
<del> private volatile boolean mIsLoopExit = false;
<add> mAudioRecord = new AudioRecord(audioSource,sampleRateInHz,channelConfig,audioFormat,mMinBufferSize);
<add> if (mAudioRecord.getState() == AudioRecord.STATE_UNINITIALIZED) {
<add> Log.e(TAG, "AudioRecord initialize fail !");
<add> return false;
<add> }
<add>
<add> mAudioRecord.startRecording();
<add>
<add> mIsLoopExit = false;
<add> mCaptureThread = new Thread(new AudioCaptureRunnable());
<add> mCaptureThread.start();
<add>
<add> mIsCaptureStarted = true;
<add>
<add> Log.d(TAG, "Start audio capture success !");
<add>
<add> return true;
<add> }
<add>
<add> public void stopCapture() {
<add>
<add> if (!mIsCaptureStarted) {
<add> return;
<add> }
<add>
<add> mIsLoopExit = false;
<add> try {
<add> mCaptureThread.interrupt();
<add> mCaptureThread.join(1000);
<add> }
<add> catch (InterruptedException e) {
<add> e.printStackTrace();
<add> }
<add>
<add> if (mAudioRecord.getRecordingState() == AudioRecord.RECORDSTATE_RECORDING) {
<add> mAudioRecord.stop();
<add> }
<add>
<add> mAudioRecord.release();
<ide>
<del> private OnAudioFrameCapturedListener mAudioFrameCapturedListener;
<add> mIsCaptureStarted = false;
<add> mAudioFrameCapturedListener = null;
<add>
<add> Log.d(TAG, "Stop audio capture success !");
<add> }
<add>
<add> private class AudioCaptureRunnable implements Runnable {
<ide>
<del> public interface OnAudioFrameCapturedListener {
<del> public void onAudioFrameCaptured(byte[] audioData);
<del> }
<del>
<del> public boolean isCaptureStarted() {
<del> return mIsCaptureStarted;
<del> }
<del>
<del> public void setOnAudioFrameCapturedListener(OnAudioFrameCapturedListener listener) {
<del> mAudioFrameCapturedListener = listener;
<del> }
<del>
<del> public boolean startCapture() {
<del> return startCapture(DEFAULT_SOURCE, DEFAULT_SAMPLE_RATE, DEFAULT_CHANNEL_CONFIG,
<del> DEFAULT_AUDIO_FORMAT);
<del> }
<del>
<del> public boolean startCapture(int audioSource, int sampleRateInHz, int channelConfig, int audioFormat) {
<add> @Override
<add> public void run() {
<ide>
<del> if (mIsCaptureStarted) {
<del> Log.e(TAG, "Capture already started !");
<del> return false;
<del> }
<del>
<del> mMinBufferSize = AudioRecord.getMinBufferSize(sampleRateInHz,channelConfig,audioFormat);
<del> if (mMinBufferSize == AudioRecord.ERROR_BAD_VALUE) {
<del> Log.e(TAG, "Invalid parameter !");
<del> return false;
<del> }
<del> Log.d(TAG , "getMinBufferSize = "+mMinBufferSize+" bytes !");
<del>
<del> mAudioRecord = new AudioRecord(audioSource,sampleRateInHz,channelConfig,audioFormat,mMinBufferSize);
<del> if (mAudioRecord.getState() == AudioRecord.STATE_UNINITIALIZED) {
<del> Log.e(TAG, "AudioRecord initialize fail !");
<del> return false;
<del> }
<del>
<del> mAudioRecord.startRecording();
<del>
<del> mIsLoopExit = false;
<del> mCaptureThread = new Thread(new AudioCaptureRunnable());
<del> mCaptureThread.start();
<del>
<del> mIsCaptureStarted = true;
<del>
<del> Log.d(TAG, "Start audio capture success !");
<del>
<del> return true;
<del> }
<del>
<del> public void stopCapture() {
<add> while (!mIsLoopExit) {
<ide>
<del> if (!mIsCaptureStarted) {
<del> return;
<del> }
<del>
<del> mIsLoopExit = false;
<del> try {
<del> mCaptureThread.interrupt();
<del> mCaptureThread.join(1000);
<del> }
<del> catch (InterruptedException e) {
<del> e.printStackTrace();
<del> }
<del>
<del> if (mAudioRecord.getRecordingState() == AudioRecord.RECORDSTATE_RECORDING) {
<del> mAudioRecord.stop();
<del> }
<del>
<del> mAudioRecord.release();
<del>
<del> mIsCaptureStarted = false;
<del> mAudioFrameCapturedListener = null;
<del>
<del> Log.d(TAG, "Stop audio capture success !");
<del> }
<del>
<del> private class AudioCaptureRunnable implements Runnable {
<del>
<del> @Override
<del> public void run() {
<add> byte[] buffer = new byte[mMinBufferSize];
<ide>
<del> while (!mIsLoopExit) {
<del>
<del> byte[] buffer = new byte[mMinBufferSize];
<del>
<del> int ret = mAudioRecord.read(buffer, 0, mMinBufferSize);
<del> if (ret == AudioRecord.ERROR_INVALID_OPERATION) {
<del> Log.e(TAG , "Error ERROR_INVALID_OPERATION");
<del> }
<del> else if (ret == AudioRecord.ERROR_BAD_VALUE) {
<del> Log.e(TAG , "Error ERROR_BAD_VALUE");
<del> }
<del> else if (ret == AudioRecord.ERROR_INVALID_OPERATION) {
<del> Log.e(TAG , "Error ERROR_INVALID_OPERATION");
<del> }
<del> else {
<del> if (mAudioFrameCapturedListener != null) {
<del> mAudioFrameCapturedListener.onAudioFrameCaptured(buffer);
<del> }
<del> Log.d(TAG , "OK, Captured "+ret+" bytes !");
<del> }
<del> }
<del> }
<del> }
<del>
<add> int ret = mAudioRecord.read(buffer, 0, mMinBufferSize);
<add> if (ret == AudioRecord.ERROR_INVALID_OPERATION) {
<add> Log.e(TAG , "Error ERROR_INVALID_OPERATION");
<add> }
<add> else if (ret == AudioRecord.ERROR_BAD_VALUE) {
<add> Log.e(TAG , "Error ERROR_BAD_VALUE");
<add> }
<add> else if (ret == AudioRecord.ERROR_INVALID_OPERATION) {
<add> Log.e(TAG , "Error ERROR_INVALID_OPERATION");
<add> }
<add> else {
<add> if (mAudioFrameCapturedListener != null) {
<add> mAudioFrameCapturedListener.onAudioFrameCaptured(buffer);
<add> }
<add> Log.d(TAG , "OK, Captured "+ret+" bytes !");
<add> }
<add> }
<add> }
<add> }
<ide> } |
|
Java | apache-2.0 | c322fe6fb8183e853a6fe263600ad39bb9788b2e | 0 | yukron/izpack,kanayo/izpack,codehaus/izpack,rkrell/izpack,yukron/izpack,tomas-forsman/izpack,Sage-ERP-X3/izpack,maichler/izpack,dasapich/izpack,mtjandra/izpack,akuhtz/izpack,izpack/izpack,Helpstone/izpack,izpack/izpack,bradcfisher/izpack,rsharipov/izpack,Helpstone/izpack,akuhtz/izpack,yukron/izpack,stenix71/izpack,optotronic/izpack,rsharipov/izpack,bradcfisher/izpack,awilhelm/izpack-with-ips,Sage-ERP-X3/izpack,dasapich/izpack,akuhtz/izpack,dasapich/izpack,Sage-ERP-X3/izpack,optotronic/izpack,Murdock01/izpack,rkrell/izpack,dasapich/izpack,Murdock01/izpack,bradcfisher/izpack,kanayo/izpack,dasapich/izpack,Helpstone/izpack,rkrell/izpack,izpack/izpack,bradcfisher/izpack,rsharipov/izpack,mtjandra/izpack,Sage-ERP-X3/izpack,rkrell/izpack,kanayo/izpack,stenix71/izpack,optotronic/izpack,akuhtz/izpack,awilhelm/izpack-with-ips,akuhtz/izpack,maichler/izpack,tomas-forsman/izpack,Murdock01/izpack,bradcfisher/izpack,tomas-forsman/izpack,kanayo/izpack,mtjandra/izpack,Sage-ERP-X3/izpack,Helpstone/izpack,stenix71/izpack,awilhelm/izpack-with-ips,yukron/izpack,mtjandra/izpack,akuhtz/izpack,codehaus/izpack,stenix71/izpack,izpack/izpack,kanayo/izpack,Murdock01/izpack,rkrell/izpack,maichler/izpack,dasapich/izpack,optotronic/izpack,Helpstone/izpack,awilhelm/izpack-with-ips,bradcfisher/izpack,Murdock01/izpack,maichler/izpack,Helpstone/izpack,tomas-forsman/izpack,yukron/izpack,Murdock01/izpack,tomas-forsman/izpack,stenix71/izpack,izpack/izpack,Sage-ERP-X3/izpack,rsharipov/izpack,awilhelm/izpack-with-ips,Murdock01/izpack,kanayo/izpack,maichler/izpack,izpack/izpack,codehaus/izpack,stenix71/izpack,stenix71/izpack,dasapich/izpack,Sage-ERP-X3/izpack,optotronic/izpack,akuhtz/izpack,codehaus/izpack,optotronic/izpack,codehaus/izpack,mtjandra/izpack,yukron/izpack,yukron/izpack,izpack/izpack,codehaus/izpack,mtjandra/izpack,rsharipov/izpack,optotronic/izpack,tomas-forsman/izpack,rsharipov/izpack,maichler/izpack,rsharipov/izpack,Helpstone/izpack,maichler/izpack,bradcfisher/izpack,mtjandra/izpack,codehaus/izpack,tomas-forsman/izpack,rkrell/izpack,rkrell/izpack | /*
* IzPack - Copyright 2001-2005 Julien Ponge, All Rights Reserved.
*
* http://www.izforge.com/izpack/
* http://developer.berlios.de/projects/izpack/
*
* Copyright 2002 Elmar Grom
*
* 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.izforge.izpack.panels;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileWriter;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Vector;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import net.n3.nanoxml.NonValidator;
import net.n3.nanoxml.StdXMLBuilder;
import net.n3.nanoxml.StdXMLParser;
import net.n3.nanoxml.StdXMLReader;
import net.n3.nanoxml.XMLElement;
import com.izforge.izpack.ExecutableFile;
import com.izforge.izpack.Pack;
import com.izforge.izpack.gui.ButtonFactory;
import com.izforge.izpack.gui.LabelFactory;
import com.izforge.izpack.installer.InstallData;
import com.izforge.izpack.installer.InstallerFrame;
import com.izforge.izpack.installer.IzPanel;
import com.izforge.izpack.installer.ResourceNotFoundException;
import com.izforge.izpack.installer.UninstallData;
import com.izforge.izpack.util.FileExecutor;
import com.izforge.izpack.util.MultiLineLabel;
import com.izforge.izpack.util.OsConstraint;
import com.izforge.izpack.util.TargetFactory;
import com.izforge.izpack.util.VariableSubstitutor;
import com.izforge.izpack.util.os.Shortcut;
//
//import com.izforge.izpack.panels.ShortcutData;
/*---------------------------------------------------------------------------*/
/**
* This class implements a panel for the creation of shortcuts. The panel prompts the user to select
* a program group for shortcuts, accept the creation of desktop shortcuts and actually creates the
* shortcuts.
*
* <h4>Important</h4>
* It is neccesary that the installation has been completed before this panel is called. To
* successfully create shortcuts this panel needs to have the following in place: <br>
* <br>
*
* <ul>
* <li>the launcher files that the shortcuts point to must exist</li>
* <li>it must be known which packs are installed</li>
* <li>where the launcher for the uninstaller is located</li>
* </ul>
*
* It is ok to present other panels after this one, as long as these conditions are met.
*
* @author Elmar Grom
* @version 0.0.1 / 2/26/02
*
* @see com.izforge.izpack.util.os.ShellLink
*
* @version 0.0.1 / 2/26/02
* @author Elmar Grom
*/
/*---------------------------------------------------------------------------*/
// !!! To Do !
//
// - see if I can't get multiple instances of the shortcut to work
// - need a clean way to get pack name
public class ShortcutPanel extends IzPanel implements ActionListener, ListSelectionListener
{
/**
*
*/
private static final long serialVersionUID = 3256722870838112311L;
/** a VectorList of Files wich should be make executable */
private Vector execFiles = new Vector();
/** SPEC_ATTRIBUTE_KDE_SUBST_UID = "KdeSubstUID" */
private final static String SPEC_ATTRIBUTE_KDE_SUBST_UID = "KdeSubstUID";
/** SPEC_ATTRIBUTE_URL = "url" */
private final static String SPEC_ATTRIBUTE_URL = "url";
/** SPEC_ATTRIBUTE_TYPE = "type" */
private final static String SPEC_ATTRIBUTE_TYPE = "type";
/** SPEC_ATTRIBUTE_TERMINAL_OPTIONS = "terminalOptions" */
private final static String SPEC_ATTRIBUTE_TERMINAL_OPTIONS = "terminalOptions";
/** SPEC_ATTRIBUTE_TERMINAL = "terminal" */
private final static String SPEC_ATTRIBUTE_TERMINAL = "terminal";
/** SPEC_ATTRIBUTE_MIMETYPE = "mimetype" */
private final static String SPEC_ATTRIBUTE_MIMETYPE = "mimetype";
/** SPEC_ATTRIBUTE_ENCODING = "encoding" */
private final static String SPEC_ATTRIBUTE_ENCODING = "encoding";
/** LOCATION_APPLICATIONS=applications */
private static final String LOCATION_APPLICATIONS = "applications";
/** LOCATION_START_MENU = "startMenu" */
private static final String LOCATION_START_MENU = "startMenu";
/**
* SEPARATOR_LINE =
* "--------------------------------------------------------------------------------";
*/
private static final String SEPARATOR_LINE = "--------------------------------------------------------------------------------";
/**
* The default file name for the text file in which the shortcut information should be stored,
* in case shortcuts can not be created on a particular target system. TEXT_FILE_NAME =
* "Shortcuts.txt"
*/
private static final String TEXT_FILE_NAME = "Shortcuts.txt";
/** The name of the XML file that specifies the shortcuts SPEC_FILE_NAME = "shortcutSpec.xml"; */
private static final String SPEC_FILE_NAME = "shortcutSpec.xml";
// ------------------------------------------------------
// spec file section keys
// ------------------------------------------------------
private static final String SPEC_KEY_SKIP_IFNOT_SUPPORTED = "skipIfNotSupported";
/** SPEC_KEY_NOT_SUPPORTED = "notSupported" */
private static final String SPEC_KEY_NOT_SUPPORTED = "notSupported";
/** SPEC_KEY_PROGRAM_GROUP = "programGroup" */
private static final String SPEC_KEY_PROGRAM_GROUP = "programGroup";
/** SPEC_KEY_SHORTCUT = "shortcut" */
private static final String SPEC_KEY_SHORTCUT = "shortcut";
/** SPEC_KEY_PACKS = "createForPack" */
private static final String SPEC_KEY_PACKS = "createForPack";
// ------------------------------------------------------
// spec file key attributes
// ------------------------------------------------------
/** SPEC_ATTRIBUTE_DEFAULT_GROUP = "defaultName" */
private static final String SPEC_ATTRIBUTE_DEFAULT_GROUP = "defaultName";
/** SPEC_ATTRIBUTE_LOCATION = "location" */
private static final String SPEC_ATTRIBUTE_LOCATION = "location";
/** SPEC_ATTRIBUTE_NAME = "name" */
private static final String SPEC_ATTRIBUTE_NAME = "name";
/** SPEC_ATTRIBUTE_SUBGROUP = "subgroup" */
private static final String SPEC_ATTRIBUTE_SUBGROUP = "subgroup";
/** SPEC_ATTRIBUTE_DESCRIPTION = "description" */
private static final String SPEC_ATTRIBUTE_DESCRIPTION = "description";
/** SPEC_ATTRIBUTE_TARGET = "target" */
private static final String SPEC_ATTRIBUTE_TARGET = "target";
/** SPEC_ATTRIBUTE_COMMAND = "commandLine" */
private static final String SPEC_ATTRIBUTE_COMMAND = "commandLine";
/** SPEC_ATTRIBUTE_ICON "iconFile" */
private static final String SPEC_ATTRIBUTE_ICON = "iconFile";
/** SPEC_ATTRIBUTE_ICON_INDEX "iconIndex" */
private static final String SPEC_ATTRIBUTE_ICON_INDEX = "iconIndex";
/** SPEC_ATTRIBUTE_WORKING_DIR = "workingDirectory" */
private static final String SPEC_ATTRIBUTE_WORKING_DIR = "workingDirectory";
/** SPEC_ATTRIBUTE_INITIAL_STATE = "initialState" */
private static final String SPEC_ATTRIBUTE_INITIAL_STATE = "initialState";
/** SPEC_ATTRIBUTE_DESKTOP = "desktop" */
private static final String SPEC_ATTRIBUTE_DESKTOP = "desktop";
/** SPEC_ATTRIBUTE_APPLICATIONS = "applications" */
private static final String SPEC_ATTRIBUTE_APPLICATIONS = "applications";
/** SPEC_ATTRIBUTE_START_MENU = "startMenu" */
private static final String SPEC_ATTRIBUTE_START_MENU = "startMenu";
/** SPEC_ATTRIBUTE_STARTUP = "startup" */
private static final String SPEC_ATTRIBUTE_STARTUP = "startup";
/** SPEC_ATTRIBUTE_PROGRAM_GROUP = "programGroup" */
private static final String SPEC_ATTRIBUTE_PROGRAM_GROUP = "programGroup";
// ------------------------------------------------------
// spec file attribute values
// ------------------------------------------------------
/** SPEC_VALUE_APPLICATIONS = "applications" */
private static final String SPEC_VALUE_APPLICATIONS = "applications";
/** SPEC_VALUE_START_MENU = "startMenu" */
private static final String SPEC_VALUE_START_MENU = "startMenu";
/** SPEC_VALUE_NO_SHOW = "noShow" */
private static final String SPEC_VALUE_NO_SHOW = "noShow";
/** SPEC_VALUE_NORMAL = "normal" */
private static final String SPEC_VALUE_NORMAL = "normal";
/** SPEC_VALUE_MAXIMIZED = "maximized" */
private static final String SPEC_VALUE_MAXIMIZED = "maximized";
/** SPEC_VALUE_MINIMIZED = "minimized" */
private static final String SPEC_VALUE_MINIMIZED = "minimized";
// ------------------------------------------------------
// automatic script section keys
// ------------------------------------------------------
/** */
/** AUTO_KEY_PROGRAM_GROUP = "programGroup" */
private static final String AUTO_KEY_PROGRAM_GROUP = "programGroup";
/** AUTO_KEY_SHORTCUT = "shortcut" */
private static final String AUTO_KEY_SHORTCUT = "shortcut";
// ------------------------------------------------------
// automatic script keys attributes
// ------------------------------------------------------
/** AUTO_ATTRIBUTE_NAME = "name" */
private static final String AUTO_ATTRIBUTE_NAME = "name";
/** AUTO_ATTRIBUTE_GROUP = "group" */
private static final String AUTO_ATTRIBUTE_GROUP = "group";
/** AUTO_ATTRIBUTE_TYPE "type" */
private static final String AUTO_ATTRIBUTE_TYPE = "type";
/** AUTO_ATTRIBUTE_COMMAND = "commandLine" */
private static final String AUTO_ATTRIBUTE_COMMAND = "commandLine";
/** AUTO_ATTRIBUTE_DESCRIPTION = "description" */
private static final String AUTO_ATTRIBUTE_DESCRIPTION = "description";
/** AUTO_ATTRIBUTE_ICON = "icon" */
private static final String AUTO_ATTRIBUTE_ICON = "icon";
/** AUTO_ATTRIBUTE_ICON_INDEX = "iconIndex" */
private static final String AUTO_ATTRIBUTE_ICON_INDEX = "iconIndex";
/** AUTO_ATTRIBUTE_INITIAL_STATE = "initialState" */
private static final String AUTO_ATTRIBUTE_INITIAL_STATE = "initialState";
/** AUTO_ATTRIBUTE_TARGET = "target" */
private static final String AUTO_ATTRIBUTE_TARGET = "target";
/** AUTO_ATTRIBUTE_WORKING_DIR = "workingDirectory" */
private static final String AUTO_ATTRIBUTE_WORKING_DIR = "workingDirectory";
// permission flags
private static final String CREATE_FOR_ALL = "createForAll";
// ------------------------------------------------------------------------
// Variable Declarations
// ------------------------------------------------------------------------
/** UI element to label the list of existing program groups */
private JLabel listLabel;
/** UI element to present the list of existing program groups for selection */
private JList groupList;
/** UI element for listing the intended shortcut targets */
private JList targetList;
/**
* UI element to present the default name for the program group and to support editing of this
* name.
*/
private JTextField programGroup;
/**
* UI element to allow the user to revert to the default name of the program group
*/
private JButton defaultButton;
/**
* UI element to allow the user to save a text file with the shortcut information
*/
private JButton saveButton;
/**
* UI element to allow the user to decide if shortcuts should be placed on the desktop or not.
*/
private JCheckBox allowDesktopShortcut;
private JCheckBox createShortcuts;
/**
* UI element instruct this panel to create shortcuts for the current user only
*/
private JRadioButton currentUser;
/** UI element instruct this panel to create shortcuts for all users */
private JRadioButton allUsers;
/** The layout for this panel */
private GridBagLayout layout;
/** The contraints object to use whan creating the layout */
private GridBagConstraints constraints;
/**
* The default name to use for the program group. This comes from the XML specification.
*/
private String suggestedProgramGroup;
/** The name chosen by the user for the program group, */
private String groupName;
/**
* The location for placign the program group. This is the same as the location (type) of a
* shortcut, only that it applies to the program group. Note that there are only two locations
* that make sense as location for a program group: <br>
*
* <ul>
* <li>applications</li>
* <li>start manu</li>
* </ul>
*
*/
private int groupLocation;
/** The parsed result from reading the XML specification from the file */
private XMLElement spec;
/**
* Set to <code>true</code> by <code>analyzeShortcutSpec()</code> if there are any desktop
* shortcuts to create.
*/
private boolean hasDesktopShortcuts = false;
/** Tells wether to skip if the platform is not supported. */
private boolean skipIfNotSupported = false;
/** the one shortcut instance for reuse in many locations */
private Shortcut shortcut;
/**
* A list of <code>ShortcutData</code> objects. Each object is the complete specification for
* one shortcut that must be created.
*/
private Vector shortcuts = new Vector();
/**
* Holds a list of all the shortcut files that have been created. <b>Note: </b> this variable
* contains valid data only after <code>createShortcuts()</code> has been called. This list is
* created so that the files can be added to the uninstaller.
*/
private Vector files = new Vector();
/**
* If <code>true</code> it indicates that there are shortcuts to create. The value is set by
* <code>analyzeShortcutSpec()</code>
*/
private boolean shortcutsToCreate = false;
/**
* If <code>true</code> it indicates that the spec file is existing and could be read.
*/
private boolean haveShortcutSpec = false;
/**
* This is set to true if the shortcut spec instructs to simulate running on an operating system
* that is not supported.
*/
private boolean simulteNotSupported = false;
/**
* Avoids bogus behaviour when the user goes back then returns to this panel.
*/
private boolean firstTime = true;
private File itsProgramFolder;
private int itsUserType;
static boolean create;
private static boolean isRootUser;
/*
* --------------------------------------------------------------------------
*/
/**
* Constructor.
*
* @param parent reference to the application frame
* @param installData shared information about the installation
*/
/*
* --------------------------------------------------------------------------
*/
public ShortcutPanel(InstallerFrame parent, InstallData installData)
{
super(parent, installData);
// read the XML file
try
{
readShortcutSpec();
}
catch (Throwable exception)
{
System.out.println("could not read shortcut spec!");
exception.printStackTrace();
}
layout = new GridBagLayout();
constraints = new GridBagConstraints();
setLayout(layout);
// Create the UI elements
try
{
shortcut = (Shortcut) (TargetFactory.getInstance()
.makeObject("com.izforge.izpack.util.os.Shortcut"));
shortcut.initialize(Shortcut.APPLICATIONS, "-");
}
catch (Throwable exception)
{
System.out.println("could not create shortcut instance");
exception.printStackTrace();
}
}
//~ Methods
// **************************************************************************************************************************************************
/*--------------------------------------------------------------------------*/
/**
* This method represents the <code>ActionListener</code> interface, invoked when an action
* occurs.
*
* @param event the action event.
*/
/*--------------------------------------------------------------------------*/
public void actionPerformed(ActionEvent event)
{
Object eventSource = event.getSource();
// ----------------------------------------------------
// create shortcut for the current user was selected
// refresh the list of program groups accordingly and
// reset the program group to the default setting.
// ----------------------------------------------------
if (eventSource.equals(currentUser))
{
groupList.setListData(shortcut.getProgramGroups(Shortcut.CURRENT_USER));
programGroup.setText(suggestedProgramGroup);
shortcut.setUserType(itsUserType = Shortcut.CURRENT_USER);
}
// ----------------------------------------------------
// create shortcut for all users was selected
// refresh the list of program groups accordingly and
// reset the program group to the default setting.
// ----------------------------------------------------
else if (eventSource.equals(allUsers))
{
groupList.setListData(shortcut.getProgramGroups(Shortcut.ALL_USERS));
programGroup.setText(suggestedProgramGroup);
shortcut.setUserType(itsUserType = Shortcut.ALL_USERS);
}
// ----------------------------------------------------
// The reset button was pressed.
// - clear the selection in the list box, because the
// selection is no longer valid
// - refill the program group edit control with the
// suggested program group name
// ----------------------------------------------------
else if (eventSource.equals(defaultButton))
{
groupList.getSelectionModel().clearSelection();
programGroup.setText(suggestedProgramGroup);
}
// ----------------------------------------------------
// the save button was pressed. This is a request to
// save shortcut information to a text file.
// ----------------------------------------------------
else if (eventSource.equals(saveButton))
{
saveToFile();
// add the file to the uninstaller
addToUninstaller();
}
else if (eventSource.equals(createShortcuts))
{
create = createShortcuts.isSelected();
groupList.setEnabled(create);
programGroup.setEnabled(create);
currentUser.setEnabled(create);
defaultButton.setEnabled(create);
allowDesktopShortcut.setEnabled(create);
if( isRootUser )
allUsers.setEnabled(create);
}
}
/*--------------------------------------------------------------------------*/
/**
* Returns <code>true</code> when all selections have valid settings. This indicates that it
* is legal to procede to the next panel.
*
* @return <code>true</code> if it is legal to procede to the next panel, otherwise
* <code>false</code>.
*/
/*--------------------------------------------------------------------------*/
public boolean isValidated()
{
try
{
groupName = programGroup.getText();
}
catch (Throwable exception)
{
groupName = "";
}
create = createShortcuts.isSelected();
createShortcuts();
// add files and directories to the uninstaller
addToUninstaller();
return (true);
}
/*--------------------------------------------------------------------------*/
/**
* Called when the panel is shown to the user.
*/
/*--------------------------------------------------------------------------*/
public void panelActivate()
{
if (firstTime)
firstTime = false;
else
return;
analyzeShortcutSpec();
if (shortcutsToCreate)
{
if (shortcut.supported() && !simulteNotSupported)
{
File allUsersProgramsFolder = getProgramsFolder(Shortcut.ALL_USERS);
isRootUser = allUsersProgramsFolder.canWrite();
if (isRootUser)
itsUserType = Shortcut.ALL_USERS;
else
itsUserType = Shortcut.CURRENT_USER;
buildUI( getProgramsFolder(isRootUser ? Shortcut.ALL_USERS : Shortcut.CURRENT_USER) );
}
else
{
if (skipIfNotSupported)
{
parent.skipPanel();
}
else
{
buildAlternateUI();
parent.unlockNextButton();
parent.lockPrevButton();
}
}
}
else
{
parent.skipPanel ();
}
}
/**
* Returns the ProgramsFolder for the current User
*
* @return The Basedir
*/
private File getProgramsFolder(int userType)
{
String path = shortcut.getProgramsFolder(userType);
return (new File(path));
//}
//else
//{
// TODO
// 0pt. Test if KDE is installed.
//boolean isKdeInstalled = UnixHelper.kdeIsInstalled();
// 1. Test if User can write into
// File kdeRootShareApplinkDir = getKDERootShareApplinkDir();
// if so: return getKDERootShareApplinkDir()
// else
// return getKDEUsersShareApplinkDir() +
//}
//return(result);
}
/**
* This method is called by the <code>groupList</code> when the user makes a selection. It
* updates the content of the <code>programGroup</code> with the result of the selection.
*
* @param event the list selection event
*/
/*--------------------------------------------------------------------------*/
public void valueChanged(ListSelectionEvent event)
{
if (programGroup == null) { return; }
String value = "";
try
{
value = (String) groupList.getSelectedValue();
}
catch (ClassCastException exception)
{}
if (value == null)
{
value = "";
}
programGroup.setText(value + File.separator + suggestedProgramGroup);
}
/*--------------------------------------------------------------------------*/
/**
* Reads the XML specification for the shortcuts to create. The result is stored in spec.
*
* @exception Exception for any problems in reading the specification
*/
/*--------------------------------------------------------------------------*/
private void readShortcutSpec() throws Exception
{
// open an input stream
InputStream input = null;
try
{
input = parent.getResource(TargetFactory.getCurrentOSPrefix() + SPEC_FILE_NAME);
}
catch (ResourceNotFoundException rnfE)
{
input = parent.getResource(SPEC_FILE_NAME);
if (input == null)
{
haveShortcutSpec = false;
return;
}
}
// if( input == null )
// {
// haveShortcutSpec = false;
// return;
// }
// initialize the parser
StdXMLParser parser = new StdXMLParser();
parser.setBuilder(new StdXMLBuilder());
parser.setValidator(new NonValidator());
parser.setReader(new StdXMLReader(input));
// get the data
spec = (XMLElement) parser.parse();
// close the stream
input.close();
haveShortcutSpec = true;
}
/*--------------------------------------------------------------------------*/
/**
* This method analyzes the specifications for creating shortcuts and builds a list of all the
* Shortcuts that need to be created.
*/
/*--------------------------------------------------------------------------*/
private void analyzeShortcutSpec()
{
if (!haveShortcutSpec)
{
shortcutsToCreate = false;
return;
}
XMLElement skipper = spec.getFirstChildNamed(SPEC_KEY_SKIP_IFNOT_SUPPORTED);
skipIfNotSupported = (skipper != null);
// ----------------------------------------------------
// find out if we should simulate a not supported
// scenario
// ----------------------------------------------------
XMLElement support = spec.getFirstChildNamed(SPEC_KEY_NOT_SUPPORTED);
if (support != null)
{
simulteNotSupported = true;
}
// ----------------------------------------------------
// find out in which program group the shortcuts should
// be placed and where this program group should be
// located
// ----------------------------------------------------
XMLElement group = spec.getFirstChildNamed(SPEC_KEY_PROGRAM_GROUP);
String location = null;
hasDesktopShortcuts = false;
if (group != null)
{
suggestedProgramGroup = group.getAttribute(SPEC_ATTRIBUTE_DEFAULT_GROUP, "");
location = group.getAttribute(SPEC_ATTRIBUTE_LOCATION, SPEC_VALUE_APPLICATIONS);
}
else
{
suggestedProgramGroup = "";
location = SPEC_VALUE_APPLICATIONS;
}
if (location.equals(SPEC_VALUE_APPLICATIONS))
{
groupLocation = Shortcut.APPLICATIONS;
}
else if (location.equals(SPEC_VALUE_START_MENU))
{
groupLocation = Shortcut.START_MENU;
}
// ----------------------------------------------------
// create a list of all shortcuts that need to be
// created, containing all details about each shortcut
// ----------------------------------------------------
VariableSubstitutor substitutor = new VariableSubstitutor(idata.getVariables());
String temp;
Vector shortcutSpecs = spec.getChildrenNamed(SPEC_KEY_SHORTCUT);
XMLElement shortcutSpec;
ShortcutData data;
for (int i = 0; i < shortcutSpecs.size(); i++)
{
shortcutSpec = (XMLElement) shortcutSpecs.elementAt(i);
if (!OsConstraint.oneMatchesCurrentSystem(shortcutSpec)) continue;
data = new ShortcutData();
data.name = shortcutSpec.getAttribute(SPEC_ATTRIBUTE_NAME);
data.subgroup = shortcutSpec.getAttribute(SPEC_ATTRIBUTE_SUBGROUP);
data.description = shortcutSpec.getAttribute(SPEC_ATTRIBUTE_DESCRIPTION, "");
//** Linux **//
data.deskTopEntryLinux_Encoding = shortcutSpec
.getAttribute(SPEC_ATTRIBUTE_ENCODING, "");
data.deskTopEntryLinux_MimeType = shortcutSpec
.getAttribute(SPEC_ATTRIBUTE_MIMETYPE, "");
data.deskTopEntryLinux_Terminal = shortcutSpec
.getAttribute(SPEC_ATTRIBUTE_TERMINAL, "");
data.deskTopEntryLinux_TerminalOptions = shortcutSpec.getAttribute(
SPEC_ATTRIBUTE_TERMINAL_OPTIONS, "");
data.deskTopEntryLinux_Type = shortcutSpec.getAttribute(SPEC_ATTRIBUTE_TYPE, "");
data.deskTopEntryLinux_URL = substitutor.substitute(shortcutSpec.getAttribute(
SPEC_ATTRIBUTE_URL, ""), null);
data.deskTopEntryLinux_X_KDE_SubstituteUID = shortcutSpec.getAttribute(
SPEC_ATTRIBUTE_KDE_SUBST_UID, "");
data.createForAll = new Boolean(shortcutSpec.getAttribute(CREATE_FOR_ALL, "false"));
//** EndOf LINUX **//
temp = fixSeparatorChar(shortcutSpec.getAttribute(SPEC_ATTRIBUTE_TARGET, ""));
data.target = substitutor.substitute(temp, null);
temp = shortcutSpec.getAttribute(SPEC_ATTRIBUTE_COMMAND, "");
data.commandLine = substitutor.substitute(temp, null);
temp = fixSeparatorChar(shortcutSpec.getAttribute(SPEC_ATTRIBUTE_ICON, ""));
data.iconFile = substitutor.substitute(temp, null);
data.iconIndex = Integer.parseInt(shortcutSpec.getAttribute(SPEC_ATTRIBUTE_ICON_INDEX,
"0"));
temp = fixSeparatorChar(shortcutSpec.getAttribute(SPEC_ATTRIBUTE_WORKING_DIR, ""));
data.workingDirectory = substitutor.substitute(temp, null);
String initialState = shortcutSpec.getAttribute(SPEC_ATTRIBUTE_INITIAL_STATE, "");
if (initialState.equals(SPEC_VALUE_NO_SHOW))
{
data.initialState = Shortcut.HIDE;
}
else if (initialState.equals(SPEC_VALUE_NORMAL))
{
data.initialState = Shortcut.NORMAL;
}
else if (initialState.equals(SPEC_VALUE_MAXIMIZED))
{
data.initialState = Shortcut.MAXIMIZED;
}
else if (initialState.equals(SPEC_VALUE_MINIMIZED))
{
data.initialState = Shortcut.MINIMIZED;
}
else
{
data.initialState = Shortcut.NORMAL;
}
// --------------------------------------------------
// if the minimal data requirements are met to create
// the shortcut, create one entry each for each of
// the requested types.
// Eventually this will cause the creation of one
// shortcut in each of the associated locations.
// --------------------------------------------------
// without a name we can not create a shortcut
if (data.name == null)
{
continue;
}
//1. Elmar: "Without a target we can not create a shortcut."
//2. Marc: "No, Even on Linux a Link can be an URL and has no target."
if (data.target == null)
{
continue;
}
// the shortcut is not actually required for any of the selected packs
Vector forPacks = shortcutSpec.getChildrenNamed(SPEC_KEY_PACKS);
if (!shortcutRequiredFor(forPacks))
{
continue;
}
// --------------------------------------------------
// This section is executed if we don't skip.
// --------------------------------------------------
// For each of the categories set the type and if
// the link should be placed in the program group,
// then clone the data set to obtain an independent
// instance and add this to the list of shortcuts
// to be created. In this way, we will set up an
// identical copy for each of the locations at which
// a shortcut should be placed. Therefore you must
// not use 'else if' statements!
// --------------------------------------------------
{
if (attributeIsTrue(shortcutSpec, SPEC_ATTRIBUTE_DESKTOP))
{
hasDesktopShortcuts = true;
data.addToGroup = false;
data.type = Shortcut.DESKTOP;
shortcuts.add(data.clone());
}
if (attributeIsTrue(shortcutSpec, SPEC_ATTRIBUTE_APPLICATIONS))
{
data.addToGroup = false;
data.type = Shortcut.APPLICATIONS;
shortcuts.add(data.clone());
}
if (attributeIsTrue(shortcutSpec, SPEC_ATTRIBUTE_START_MENU))
{
data.addToGroup = false;
data.type = Shortcut.START_MENU;
shortcuts.add(data.clone());
}
if (attributeIsTrue(shortcutSpec, SPEC_ATTRIBUTE_STARTUP))
{
data.addToGroup = false;
data.type = Shortcut.START_UP;
shortcuts.add(data.clone());
}
if (attributeIsTrue(shortcutSpec, SPEC_ATTRIBUTE_PROGRAM_GROUP))
{
data.addToGroup = true;
data.type = Shortcut.APPLICATIONS;
shortcuts.add(data.clone());
}
}
}
// ----------------------------------------------------
// signal if there are any shortcuts to create
// ----------------------------------------------------
if (shortcuts.size() > 0)
{
shortcutsToCreate = true;
}
}
/*--------------------------------------------------------------------------*/
/**
* Creates all shortcuts based on the information in <code>shortcuts</code>.
*/
/*--------------------------------------------------------------------------*/
private void createShortcuts()
{
if (!create) return;
ShortcutData data;
for (int i = 0; i < shortcuts.size(); i++)
{
data = (ShortcutData) shortcuts.elementAt(i);
try
{
groupName = groupName + data.subgroup;
shortcut.setUserType(itsUserType);
shortcut.setLinkName(data.name);
shortcut.setLinkType(data.type);
shortcut.setArguments(data.commandLine);
shortcut.setDescription(data.description);
shortcut.setIconLocation(data.iconFile, data.iconIndex);
shortcut.setShowCommand(data.initialState);
shortcut.setTargetPath(data.target);
shortcut.setWorkingDirectory(data.workingDirectory);
shortcut.setEncoding(data.deskTopEntryLinux_Encoding);
shortcut.setMimetype(data.deskTopEntryLinux_MimeType);
shortcut.setTerminal(data.deskTopEntryLinux_Terminal);
shortcut.setTerminalOptions(data.deskTopEntryLinux_TerminalOptions);
shortcut.setType(data.deskTopEntryLinux_Type);
shortcut.setKdeSubstUID(data.deskTopEntryLinux_X_KDE_SubstituteUID);
shortcut.setURL(data.deskTopEntryLinux_URL);
shortcut.setCreateForAll(data.createForAll);
if (data.addToGroup)
{
shortcut.setProgramGroup(groupName);
}
else
{
shortcut.setProgramGroup("");
}
try
{
// ----------------------------------------------
// save the shortcut only if it is either not on
// the desktop or if it is on the desktop and
// the user has signalled that it is ok to place
// shortcuts on the desktop.
// ----------------------------------------------
if ((data.type != Shortcut.DESKTOP)
|| ((data.type == Shortcut.DESKTOP) && allowDesktopShortcut
.isSelected()))
{
// save the shortcut
shortcut.save();
// add the file and directory name to the file list
String fileName = shortcut.getFileName();
files.add(0, fileName);
File file = new File(fileName);
File base = new File(shortcut.getBasePath());
Vector intermediates = new Vector();
//String directoryName = shortcut.getDirectoryCreated ();
execFiles.add(new ExecutableFile(fileName, 2, ExecutableFile.WARN,
new ArrayList(), false));
files.add(fileName);
while ((file = file.getParentFile()) != null)
{
if (file.equals(base)) break;
intermediates.add(file);
}
if (file != null)
{
for (Iterator iter = intermediates.iterator(); iter.hasNext();)
files.add(0, iter.next().toString());
}
}
}
catch (Exception exception)
{}
}
catch (Throwable exception)
{
continue;
}
}
//
try
{
if (execFiles != null)
{
FileExecutor executor = new FileExecutor(execFiles);
//
// TODO: Hi Guys,
// TODO The following commented-out line sometimes produces an uncatchable
// nullpointer Exception!
// TODO evaluate for what reason the files should exec.
// TODO if there is a serious explanation, why to do that,
// TODO the code must be more robust
//evaluate executor.executeFiles( ExecutableFile.NEVER, null );
}
}
catch (NullPointerException nep)
{
nep.printStackTrace();
}
catch (RuntimeException cannot)
{
cannot.printStackTrace();
}
parent.unlockNextButton();
}
/*--------------------------------------------------------------------------*/
/**
* Verifies if the shortcut is required for any of the packs listed. The shortcut is required
* for a pack in the list if that pack is actually selected for installation. <br>
* <br>
* <b>Note: </b> <br>
* If the list of selected packs is empty then <code>true</code> is always returnd. The same
* is true if the <code>packs</code> list is empty.
*
* @param packs a <code>Vector</code> of <code>String</code>s. Each of the strings denotes
* a pack for which the schortcut should be created if the pack is actually installed.
*
* @return <code>true</code> if the shortcut is required for at least on pack in the list,
* otherwise returns <code>false</code>.
*/
/*--------------------------------------------------------------------------*/
/*
* $ @design
*
* The information about the installed packs comes from InstallData.selectedPacks. This assumes
* that this panel is presented to the user AFTER the PacksPanel.
* --------------------------------------------------------------------------
*/
private boolean shortcutRequiredFor(Vector packs)
{
String selected;
String required;
if (packs.size() == 0) { return (true); }
for (int i = 0; i < idata.selectedPacks.size(); i++)
{
selected = ((Pack) idata.selectedPacks.get(i)).name;
for (int k = 0; k < packs.size(); k++)
{
required = (String) ((XMLElement) packs.elementAt(k)).getAttribute(
SPEC_ATTRIBUTE_NAME, "");
if (selected.equals(required)) { return (true); }
}
}
return (false);
}
/*--------------------------------------------------------------------------*/
/**
* Determines if the named attribute in true. True is represented by any of the following
* strings and is not case sensitive. <br>
*
* <ul>
* <li>yes</li>
* <li>1</li>
* <li>true</li>
* <li>on</li>
* </ul>
*
* <br>
* Every other string, including the empty string as well as the non-existence of the attribute
* will cuase <code>false</code> to be returned.
*
* @param element the <code>XMLElement</code> to search for the attribute.
* @param name the name of the attribute to test.
*
* @return <code>true</code> if the attribute value equals one of the pre-defined strings,
* <code>false</code> otherwise.
*/
/*--------------------------------------------------------------------------*/
private boolean attributeIsTrue(XMLElement element, String name)
{
String value = element.getAttribute(name, "").toUpperCase();
if (value.equals("YES"))
{
return (true);
}
else if (value.equals("TRUE"))
{
return (true);
}
else if (value.equals("ON"))
{
return (true);
}
else if (value.equals("1")) { return (true); }
return (false);
}
/*--------------------------------------------------------------------------*/
/**
* Replaces any ocurrence of '/' or '\' in a path string with the correct version for the
* operating system.
*
* @param path a system path
*
* @return a path string that uniformely uses the proper version of the separator character.
*/
/*--------------------------------------------------------------------------*/
private String fixSeparatorChar(String path)
{
String newPath = path.replace('/', File.separatorChar);
newPath = newPath.replace('\\', File.separatorChar);
return (newPath);
}
/*--------------------------------------------------------------------------*/
/**
* This method creates the UI for this panel.
*
* @param groups A <code>Vector</code> that contains <code>Strings</code> with all the names
* of the existing program groups. These will be placed in the <code>groupList</code>.
* @param currentUserList if <code>true</code> it indicates that the list of groups is valid
* for the current user, otherwise it is considered valid for all users.
*/
/*--------------------------------------------------------------------------*/
private void buildUI(File groups)//, boolean currentUserList)
{
itsProgramFolder = groups;
layout = new GridBagLayout();
constraints = new GridBagConstraints();
setLayout(layout);
// ----------------------------------------------------
// label a the top of the panel, that gives the
// basic instructions
// ----------------------------------------------------
listLabel = LabelFactory.create(parent.langpack.getString("ShortcutPanel.regular.list"),
JLabel.LEADING);
constraints.gridx = 0;
constraints.gridy = 0;
constraints.gridwidth = 1;
constraints.gridheight = 1;
constraints.weightx = 1.0;
constraints.weighty = 1.0;
constraints.insets = new Insets(5, 5, 5, 5);
constraints.fill = GridBagConstraints.NONE;
constraints.anchor = GridBagConstraints.WEST;
layout.addLayoutComponent(listLabel, constraints);
add(listLabel);
// ----------------------------------------------------
// list box to list all of already existing folders as program groups
// at the intended destination
// ----------------------------------------------------
Vector dirEntries = new Vector();
File[] entries = groups.listFiles();
for (int idx = 0; idx < entries.length; idx++)
{
if (entries[idx].isDirectory())
{
dirEntries.add(entries[idx].getName());
}
}
groupList = new JList(dirEntries);
groupList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
groupList.getSelectionModel().addListSelectionListener(this);
JScrollPane scrollPane = new JScrollPane(groupList);
constraints.gridx = 0;
constraints.gridy = 1;
constraints.gridwidth = 1;
constraints.gridheight = 1;
constraints.fill = GridBagConstraints.BOTH;
layout.addLayoutComponent(scrollPane, constraints);
add(scrollPane);
// ----------------------------------------------------
// radio buttons to select current user or all users.
// ----------------------------------------------------
if (shortcut.multipleUsers())
{
JPanel usersPanel = new JPanel(new GridLayout(2, 1));
ButtonGroup usersGroup = new ButtonGroup();
currentUser = new JRadioButton(parent.langpack
.getString("ShortcutPanel.regular.currentUser"), !isRootUser);
currentUser.addActionListener(this);
usersGroup.add(currentUser);
usersPanel.add(currentUser);
allUsers = new JRadioButton(
parent.langpack.getString("ShortcutPanel.regular.allUsers"), isRootUser);
if (!isRootUser) allUsers.setEnabled(false);
allUsers.addActionListener(this);
usersGroup.add(allUsers);
usersPanel.add(allUsers);
TitledBorder border = new TitledBorder(new EmptyBorder(2, 2, 2, 2), parent.langpack
.getString("ShortcutPanel.regular.userIntro"));
usersPanel.setBorder(border);
constraints.gridx = 1;
constraints.gridy = 1;
constraints.gridwidth = 1;
constraints.gridheight = 1;
constraints.fill = GridBagConstraints.NONE;
layout.addLayoutComponent(usersPanel, constraints);
add(usersPanel);
}
// ----------------------------------------------------
// edit box that contains the suggested program group
// name, which can be modfied or substituted from the
// list by the user
// ----------------------------------------------------
programGroup = new JTextField(suggestedProgramGroup, 40); // 40?
constraints.gridx = 0;
constraints.gridy = 2;
constraints.gridwidth = 1;
constraints.gridheight = 1;
constraints.fill = GridBagConstraints.HORIZONTAL;
layout.addLayoutComponent(programGroup, constraints);
add(programGroup);
// ----------------------------------------------------
// reset button that allows the user to revert to the
// original suggestion for the program group
// ----------------------------------------------------
defaultButton = ButtonFactory.createButton(parent.langpack
.getString("ShortcutPanel.regular.default"), idata.buttonsHColor);
defaultButton.addActionListener(this);
constraints.gridx = 1;
constraints.gridy = 2;
constraints.gridwidth = 1;
constraints.gridheight = 1;
constraints.fill = GridBagConstraints.NONE;
layout.addLayoutComponent(defaultButton, constraints);
add(defaultButton);
// ----------------------------------------------------
// check box to allow the user to decide if a desktop
// shortcut should be created.
// this should only be created if needed and requested
// in the definition file.
// ----------------------------------------------------
boolean initialAllowedFlag = idata.getVariable("DesktopShortcutCheckboxEnabled") == null ? false
: true;
allowDesktopShortcut = new JCheckBox(parent.langpack
.getString("ShortcutPanel.regular.desktop"), initialAllowedFlag);
constraints.gridx = 0;
constraints.gridy = 3;
constraints.gridwidth = 1;
constraints.gridheight = 1;
if (hasDesktopShortcuts)
{
layout.addLayoutComponent(allowDesktopShortcut, constraints);
add(allowDesktopShortcut);
}
// TODO add here
createShortcuts = new JCheckBox(parent.langpack.getString("ShortcutPanel.regular.create"),
true);
createShortcuts.addActionListener(this);
constraints.gridx = 0;
constraints.gridy = 4;
constraints.gridwidth = 1;
constraints.gridheight = 1;
if (hasDesktopShortcuts)
{
layout.addLayoutComponent(createShortcuts, constraints);
add(createShortcuts);
}
}
/*--------------------------------------------------------------------------*/
/**
* This method creates an alternative UI for this panel. This UI can be used when the creation
* of shortcuts is not supported on the target system. It displays an apology for the inability
* to create shortcuts on this system, along with information about the intended targets. In
* addition, there is a button that allows the user to save more complete information in a text
* file. Based on this information the user might be able to create the necessary shortcut him
* or herself. At least there will be information about how to launch the application.
*/
/*--------------------------------------------------------------------------*/
private void buildAlternateUI()
{
layout = new GridBagLayout();
constraints = new GridBagConstraints();
setLayout(layout);
// ----------------------------------------------------
// static text a the top of the panel, that apologizes
// about the fact that we can not create shortcuts on
// this particular target OS.
// ----------------------------------------------------
MultiLineLabel apologyLabel = new MultiLineLabel(parent.langpack
.getString("ShortcutPanel.alternate.apology"), 0, 0);
constraints.gridx = 0;
constraints.gridy = 0;
constraints.gridwidth = 1;
constraints.gridheight = 1;
constraints.weightx = 1.0;
constraints.weighty = 1.0;
constraints.insets = new Insets(5, 5, 5, 5);
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.anchor = GridBagConstraints.WEST;
layout.addLayoutComponent(apologyLabel, constraints);
add(apologyLabel);
// ----------------------------------------------------
// label that explains the significance ot the list box
// ----------------------------------------------------
MultiLineLabel listLabel = new MultiLineLabel(parent.langpack
.getString("ShortcutPanel.alternate.targetsLabel"), 0, 0);
constraints.gridx = 0;
constraints.gridy = 1;
constraints.gridwidth = 1;
constraints.gridheight = 1;
constraints.weightx = 1.0;
constraints.weighty = 1.0;
layout.addLayoutComponent(listLabel, constraints);
add(listLabel);
// ----------------------------------------------------
// list box to list all of the intended shortcut targets
// ----------------------------------------------------
Vector targets = new Vector();
for (int i = 0; i < shortcuts.size(); i++)
{
targets.add(((ShortcutData) shortcuts.elementAt(i)).target);
}
targetList = new JList(targets);
JScrollPane scrollPane = new JScrollPane(targetList);
constraints.gridx = 0;
constraints.gridy = 2;
constraints.fill = GridBagConstraints.BOTH;
layout.addLayoutComponent(scrollPane, constraints);
add(scrollPane);
// ----------------------------------------------------
// static text that explains about the text file
// ----------------------------------------------------
MultiLineLabel fileExplanation = new MultiLineLabel(parent.langpack
.getString("ShortcutPanel.alternate.textFileExplanation"), 0, 0);
constraints.gridx = 0;
constraints.gridy = 3;
constraints.weightx = 1.0;
constraints.weighty = 1.0;
constraints.fill = GridBagConstraints.HORIZONTAL;
layout.addLayoutComponent(fileExplanation, constraints);
add(fileExplanation);
// ----------------------------------------------------
// button to save the text file
// ----------------------------------------------------
saveButton = ButtonFactory.createButton(parent.langpack
.getString("ShortcutPanel.alternate.saveButton"), idata.buttonsHColor);
saveButton.addActionListener(this);
constraints.gridx = 0;
constraints.gridy = 4;
constraints.gridwidth = 1;
constraints.gridheight = 1;
constraints.fill = GridBagConstraints.NONE;
constraints.anchor = GridBagConstraints.CENTER;
layout.addLayoutComponent(saveButton, constraints);
add(saveButton);
}
/*--------------------------------------------------------------------------*/
/**
* Overriding the superclass implementation. This method returns the size of the container.
*
* @return the size of the container
*/
/*--------------------------------------------------------------------------*/
public Dimension getSize()
{
Dimension size = getParent().getSize();
Insets insets = getInsets();
Border border = getBorder();
Insets borderInsets = new Insets(0, 0, 0, 0);
if (border != null)
{
borderInsets = border.getBorderInsets(this);
}
size.height = size.height - insets.top - insets.bottom - borderInsets.top
- borderInsets.bottom - 50;
size.width = size.width - insets.left - insets.right - borderInsets.left
- borderInsets.right - 50;
return (size);
}
/*--------------------------------------------------------------------------*/
/**
* This method saves all shortcut information to a text file.
*/
/*--------------------------------------------------------------------------*/
private void saveToFile()
{
File file = null;
// ----------------------------------------------------
// open a file chooser dialog to get a path / file name
// ----------------------------------------------------
JFileChooser fileDialog = new JFileChooser(idata.getInstallPath());
fileDialog.setSelectedFile(new File(TEXT_FILE_NAME));
if (fileDialog.showSaveDialog(this) == JFileChooser.APPROVE_OPTION)
{
file = fileDialog.getSelectedFile();
}
else
{
return;
}
// ----------------------------------------------------
// save to the file
// ----------------------------------------------------
FileWriter output = null;
StringBuffer buffer = new StringBuffer();
String header = parent.langpack.getString("ShortcutPanel.textFile.header");
String newline = System.getProperty("line.separator", "\n");
try
{
output = new FileWriter(file);
}
catch (Throwable exception)
{
// !!! show an error dialog
return;
}
// ----------------------------------------------------
// break the header down into multiple lines based
// on '\n' line breaks.
// ----------------------------------------------------
int nextIndex = 0;
int currentIndex = 0;
do
{
nextIndex = header.indexOf("\\n", currentIndex);
if (nextIndex > -1)
{
buffer.append(header.substring(currentIndex, nextIndex));
buffer.append(newline);
currentIndex = nextIndex + 2;
}
else
{
buffer.append(header.substring(currentIndex, header.length()));
buffer.append(newline);
}
}
while (nextIndex > -1);
buffer.append(SEPARATOR_LINE);
buffer.append(newline);
buffer.append(newline);
for (int i = 0; i < shortcuts.size(); i++)
{
ShortcutData data = (ShortcutData) shortcuts.elementAt(i);
buffer.append(parent.langpack.getString("ShortcutPanel.textFile.name"));
buffer.append(data.name);
buffer.append(newline);
buffer.append(parent.langpack.getString("ShortcutPanel.textFile.location"));
switch (data.type)
{
case Shortcut.DESKTOP: {
buffer.append(parent.langpack.getString("ShortcutPanel.location.desktop"));
break;
}
case Shortcut.APPLICATIONS: {
buffer.append(parent.langpack.getString("ShortcutPanel.location.applications"));
break;
}
case Shortcut.START_MENU: {
buffer.append(parent.langpack.getString("ShortcutPanel.location.startMenu"));
break;
}
case Shortcut.START_UP: {
buffer.append(parent.langpack.getString("ShortcutPanel.location.startup"));
break;
}
}
buffer.append(newline);
buffer.append(parent.langpack.getString("ShortcutPanel.textFile.description"));
buffer.append(data.description);
buffer.append(newline);
buffer.append(parent.langpack.getString("ShortcutPanel.textFile.target"));
buffer.append(data.target);
buffer.append(newline);
buffer.append(parent.langpack.getString("ShortcutPanel.textFile.command"));
buffer.append(data.commandLine);
buffer.append(newline);
buffer.append(parent.langpack.getString("ShortcutPanel.textFile.iconName"));
buffer.append(data.iconFile);
buffer.append(newline);
buffer.append(parent.langpack.getString("ShortcutPanel.textFile.iconIndex"));
buffer.append(data.iconIndex);
buffer.append(newline);
buffer.append(parent.langpack.getString("ShortcutPanel.textFile.work"));
buffer.append(data.workingDirectory);
buffer.append(newline);
buffer.append(newline);
buffer.append(SEPARATOR_LINE);
buffer.append(newline);
buffer.append(newline);
}
try
{
output.write(buffer.toString());
}
catch (Throwable exception)
{}
finally
{
try
{
output.flush();
output.close();
files.add(file.getPath());
}
catch (Throwable exception)
{
// not really anything I can do here, maybe should show a dialog that
// tells the user that data might not have been saved completely!?
}
}
}
/*--------------------------------------------------------------------------*/
/**
* Adds all files and directories to the uninstaller.
*/
/*--------------------------------------------------------------------------*/
private void addToUninstaller()
{
UninstallData uninstallData = UninstallData.getInstance();
for (int i = 0; i < files.size(); i++)
{
uninstallData.addFile((String) files.elementAt(i));
}
}
/*--------------------------------------------------------------------------*/
/**
* Adds iformation about the shortcuts that have been created during the installation to the XML
* tree.
*
* @param panelRoot the root of the XML tree
*/
/*--------------------------------------------------------------------------*/
/*
* $ @design
*
* The information needed to create shortcuts has been collected in the Vector 'shortcuts'. Take
* the data from there and package it in XML form for storage by the installer. The group name
* is only stored once in a separate XML element, since there is only one.
* --------------------------------------------------------------------------
*/
public void makeXMLData(XMLElement panelRoot)
{
// ----------------------------------------------------
// if there are no shortcuts to create, shortcuts are
// not supported, or we should simulate that they are
// not supported, then we have nothing to add. Just
// return
// ----------------------------------------------------
if (!shortcutsToCreate || !shortcut.supported() || groupName == null || simulteNotSupported) { return; }
ShortcutData data;
XMLElement dataElement;
// ----------------------------------------------------
// add the item that defines the name of the program group
// ----------------------------------------------------
dataElement = new XMLElement(AUTO_KEY_PROGRAM_GROUP);
dataElement.setAttribute(AUTO_ATTRIBUTE_NAME, groupName);
panelRoot.addChild(dataElement);
// ----------------------------------------------------
// add the details for each of the shortcuts
// ----------------------------------------------------
for (int i = 0; i < shortcuts.size(); i++)
{
data = (ShortcutData) shortcuts.elementAt(i);
dataElement = new XMLElement(AUTO_KEY_SHORTCUT);
dataElement.setAttribute(AUTO_ATTRIBUTE_NAME, data.name);
dataElement.setAttribute(AUTO_ATTRIBUTE_GROUP, Boolean.valueOf(data.addToGroup)
.toString());
dataElement.setAttribute(AUTO_ATTRIBUTE_TYPE, Integer.toString(data.type));
dataElement.setAttribute(AUTO_ATTRIBUTE_COMMAND, data.commandLine);
dataElement.setAttribute(AUTO_ATTRIBUTE_DESCRIPTION, data.description);
dataElement.setAttribute(AUTO_ATTRIBUTE_ICON, data.iconFile);
dataElement.setAttribute(AUTO_ATTRIBUTE_ICON_INDEX, Integer.toString(data.iconIndex));
dataElement.setAttribute(AUTO_ATTRIBUTE_INITIAL_STATE, Integer
.toString(data.initialState));
dataElement.setAttribute(AUTO_ATTRIBUTE_TARGET, data.target);
dataElement.setAttribute(AUTO_ATTRIBUTE_WORKING_DIR, data.workingDirectory);
// ----------------------------------------------
// add the shortcut only if it is either not on
// the desktop or if it is on the desktop and
// the user has signalled that it is ok to place
// shortcuts on the desktop.
// ----------------------------------------------
if ((data.type != Shortcut.DESKTOP)
|| ((data.type == Shortcut.DESKTOP) && allowDesktopShortcut.isSelected()))
{
panelRoot.addChild(dataElement);
}
}
}
/*--------------------------------------------------------------------------*/
/**
* Creates shortcuts based on teh information in <code>panelRoot</code> without UI.
*
* @param panelRoot the root of the XML tree
*/
/*--------------------------------------------------------------------------*/
/*
* $ @design
*
* Reconstitute the information needed to create shortcuts from XML data that was previously
* stored by the installer through makeXMLData(). Create a new Vector containing this data and
* stroe it in 'shortcuts' for use by createShortcuts(). Once this has been completed, call
* createShortcuts() to complete the operation.
* --------------------------------------------------------------------------
*/
public void runAutomated(XMLElement panelRoot)
{
// ----------------------------------------------------
// if shortcuts are not supported, then we can not
// create shortcuts, even if there was any install
// data. Just return.
// ----------------------------------------------------
if (!shortcut.supported()) { return; }
if (!OsConstraint.oneMatchesCurrentSystem(panelRoot)) { return; }
shortcuts = new Vector();
Vector shortcutElements;
ShortcutData data;
XMLElement dataElement;
// ----------------------------------------------------
// set the name of the program group
// ----------------------------------------------------
dataElement = panelRoot.getFirstChildNamed(AUTO_KEY_PROGRAM_GROUP);
groupName = dataElement.getAttribute(AUTO_ATTRIBUTE_NAME);
if (groupName == null)
{
groupName = "";
}
// ----------------------------------------------------
// add the details for each of the shortcuts
// ----------------------------------------------------
shortcutElements = panelRoot.getChildrenNamed(AUTO_KEY_SHORTCUT);
for (int i = 0; i < shortcutElements.size(); i++)
{
data = new ShortcutData();
dataElement = (XMLElement) shortcutElements.elementAt(i);
data.name = dataElement.getAttribute(AUTO_ATTRIBUTE_NAME);
data.addToGroup = Boolean.valueOf(dataElement.getAttribute(AUTO_ATTRIBUTE_GROUP))
.booleanValue();
data.type = Integer.valueOf(dataElement.getAttribute(AUTO_ATTRIBUTE_TYPE)).intValue();
data.commandLine = dataElement.getAttribute(AUTO_ATTRIBUTE_COMMAND);
data.description = dataElement.getAttribute(AUTO_ATTRIBUTE_DESCRIPTION);
data.iconFile = dataElement.getAttribute(AUTO_ATTRIBUTE_ICON);
data.iconIndex = Integer.valueOf(dataElement.getAttribute(AUTO_ATTRIBUTE_ICON_INDEX))
.intValue();
data.initialState = Integer.valueOf(
dataElement.getAttribute(AUTO_ATTRIBUTE_INITIAL_STATE)).intValue();
data.target = dataElement.getAttribute(AUTO_ATTRIBUTE_TARGET);
data.workingDirectory = dataElement.getAttribute(AUTO_ATTRIBUTE_WORKING_DIR);
shortcuts.add(data);
}
createShortcuts();
}
}
/*---------------------------------------------------------------------------*/
| src/lib/com/izforge/izpack/panels/ShortcutPanel.java | /*
* IzPack - Copyright 2001-2005 Julien Ponge, All Rights Reserved.
*
* http://www.izforge.com/izpack/ http://developer.berlios.de/projects/izpack/
*
* Copyright 2002 Elmar Grom
*
* 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.izforge.izpack.panels;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileWriter;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Vector;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import net.n3.nanoxml.NonValidator;
import net.n3.nanoxml.StdXMLBuilder;
import net.n3.nanoxml.StdXMLParser;
import net.n3.nanoxml.StdXMLReader;
import net.n3.nanoxml.XMLElement;
import com.izforge.izpack.ExecutableFile;
import com.izforge.izpack.Pack;
import com.izforge.izpack.gui.ButtonFactory;
import com.izforge.izpack.gui.LabelFactory;
import com.izforge.izpack.installer.InstallData;
import com.izforge.izpack.installer.InstallerFrame;
import com.izforge.izpack.installer.IzPanel;
import com.izforge.izpack.installer.ResourceNotFoundException;
import com.izforge.izpack.installer.UninstallData;
import com.izforge.izpack.util.FileExecutor;
import com.izforge.izpack.util.MultiLineLabel;
import com.izforge.izpack.util.OsConstraint;
import com.izforge.izpack.util.TargetFactory;
import com.izforge.izpack.util.VariableSubstitutor;
import com.izforge.izpack.util.os.Shortcut;
//
//import com.izforge.izpack.panels.ShortcutData;
/*---------------------------------------------------------------------------*/
/**
* This class implements a panel for the creation of shortcuts. The panel prompts the user to select
* a program group for shortcuts, accept the creation of desktop shortcuts and actually creates the
* shortcuts.
*
* <h4>Important</h4>
* It is neccesary that the installation has been completed before this panel is called. To
* successfully create shortcuts this panel needs to have the following in place: <br>
* <br>
*
* <ul>
* <li>the launcher files that the shortcuts point to must exist</li>
* <li>it must be known which packs are installed</li>
* <li>where the launcher for the uninstaller is located</li>
* </ul>
*
* It is ok to present other panels after this one, as long as these conditions are met.
*
* @author Elmar Grom
* @version 0.0.1 / 2/26/02
*
* @see com.izforge.izpack.util.os.ShellLink
*
* @version 0.0.1 / 2/26/02
* @author Elmar Grom
*/
/*---------------------------------------------------------------------------*/
// !!! To Do !
//
// - see if I can't get multiple instances of the shortcut to work
// - need a clean way to get pack name
public class ShortcutPanel extends IzPanel implements ActionListener, ListSelectionListener
{
/** a VectorList of Files wich should be make executable */
private Vector execFiles = new Vector();
/** SPEC_ATTRIBUTE_KDE_SUBST_UID = "KdeSubstUID" */
private final static String SPEC_ATTRIBUTE_KDE_SUBST_UID = "KdeSubstUID";
/** SPEC_ATTRIBUTE_URL = "url" */
private final static String SPEC_ATTRIBUTE_URL = "url";
/** SPEC_ATTRIBUTE_TYPE = "type" */
private final static String SPEC_ATTRIBUTE_TYPE = "type";
/** SPEC_ATTRIBUTE_TERMINAL_OPTIONS = "terminalOptions" */
private final static String SPEC_ATTRIBUTE_TERMINAL_OPTIONS = "terminalOptions";
/** SPEC_ATTRIBUTE_TERMINAL = "terminal" */
private final static String SPEC_ATTRIBUTE_TERMINAL = "terminal";
/** SPEC_ATTRIBUTE_MIMETYPE = "mimetype" */
private final static String SPEC_ATTRIBUTE_MIMETYPE = "mimetype";
/** SPEC_ATTRIBUTE_ENCODING = "encoding" */
private final static String SPEC_ATTRIBUTE_ENCODING = "encoding";
/** LOCATION_APPLICATIONS=applications */
private static final String LOCATION_APPLICATIONS = "applications";
/** LOCATION_START_MENU = "startMenu" */
private static final String LOCATION_START_MENU = "startMenu";
/**
* SEPARATOR_LINE =
* "--------------------------------------------------------------------------------";
*/
private static final String SEPARATOR_LINE = "--------------------------------------------------------------------------------";
/**
* The default file name for the text file in which the shortcut information should be stored,
* in case shortcuts can not be created on a particular target system. TEXT_FILE_NAME =
* "Shortcuts.txt"
*/
private static final String TEXT_FILE_NAME = "Shortcuts.txt";
/** The name of the XML file that specifies the shortcuts SPEC_FILE_NAME = "shortcutSpec.xml"; */
private static final String SPEC_FILE_NAME = "shortcutSpec.xml";
// ------------------------------------------------------
// spec file section keys
// ------------------------------------------------------
private static final String SPEC_KEY_SKIP_IFNOT_SUPPORTED = "skipIfNotSupported";
/** SPEC_KEY_NOT_SUPPORTED = "notSupported" */
private static final String SPEC_KEY_NOT_SUPPORTED = "notSupported";
/** SPEC_KEY_PROGRAM_GROUP = "programGroup" */
private static final String SPEC_KEY_PROGRAM_GROUP = "programGroup";
/** SPEC_KEY_SHORTCUT = "shortcut" */
private static final String SPEC_KEY_SHORTCUT = "shortcut";
/** SPEC_KEY_PACKS = "createForPack" */
private static final String SPEC_KEY_PACKS = "createForPack";
// ------------------------------------------------------
// spec file key attributes
// ------------------------------------------------------
/** SPEC_ATTRIBUTE_DEFAULT_GROUP = "defaultName" */
private static final String SPEC_ATTRIBUTE_DEFAULT_GROUP = "defaultName";
/** SPEC_ATTRIBUTE_LOCATION = "location" */
private static final String SPEC_ATTRIBUTE_LOCATION = "location";
/** SPEC_ATTRIBUTE_NAME = "name" */
private static final String SPEC_ATTRIBUTE_NAME = "name";
/** SPEC_ATTRIBUTE_SUBGROUP = "subgroup" */
private static final String SPEC_ATTRIBUTE_SUBGROUP = "subgroup";
/** SPEC_ATTRIBUTE_DESCRIPTION = "description" */
private static final String SPEC_ATTRIBUTE_DESCRIPTION = "description";
/** SPEC_ATTRIBUTE_TARGET = "target" */
private static final String SPEC_ATTRIBUTE_TARGET = "target";
/** SPEC_ATTRIBUTE_COMMAND = "commandLine" */
private static final String SPEC_ATTRIBUTE_COMMAND = "commandLine";
/** SPEC_ATTRIBUTE_ICON "iconFile" */
private static final String SPEC_ATTRIBUTE_ICON = "iconFile";
/** SPEC_ATTRIBUTE_ICON_INDEX "iconIndex" */
private static final String SPEC_ATTRIBUTE_ICON_INDEX = "iconIndex";
/** SPEC_ATTRIBUTE_WORKING_DIR = "workingDirectory" */
private static final String SPEC_ATTRIBUTE_WORKING_DIR = "workingDirectory";
/** SPEC_ATTRIBUTE_INITIAL_STATE = "initialState" */
private static final String SPEC_ATTRIBUTE_INITIAL_STATE = "initialState";
/** SPEC_ATTRIBUTE_DESKTOP = "desktop" */
private static final String SPEC_ATTRIBUTE_DESKTOP = "desktop";
/** SPEC_ATTRIBUTE_APPLICATIONS = "applications" */
private static final String SPEC_ATTRIBUTE_APPLICATIONS = "applications";
/** SPEC_ATTRIBUTE_START_MENU = "startMenu" */
private static final String SPEC_ATTRIBUTE_START_MENU = "startMenu";
/** SPEC_ATTRIBUTE_STARTUP = "startup" */
private static final String SPEC_ATTRIBUTE_STARTUP = "startup";
/** SPEC_ATTRIBUTE_PROGRAM_GROUP = "programGroup" */
private static final String SPEC_ATTRIBUTE_PROGRAM_GROUP = "programGroup";
// ------------------------------------------------------
// spec file attribute values
// ------------------------------------------------------
/** SPEC_VALUE_APPLICATIONS = "applications" */
private static final String SPEC_VALUE_APPLICATIONS = "applications";
/** SPEC_VALUE_START_MENU = "startMenu" */
private static final String SPEC_VALUE_START_MENU = "startMenu";
/** SPEC_VALUE_NO_SHOW = "noShow" */
private static final String SPEC_VALUE_NO_SHOW = "noShow";
/** SPEC_VALUE_NORMAL = "normal" */
private static final String SPEC_VALUE_NORMAL = "normal";
/** SPEC_VALUE_MAXIMIZED = "maximized" */
private static final String SPEC_VALUE_MAXIMIZED = "maximized";
/** SPEC_VALUE_MINIMIZED = "minimized" */
private static final String SPEC_VALUE_MINIMIZED = "minimized";
// ------------------------------------------------------
// automatic script section keys
// ------------------------------------------------------
/** */
/** AUTO_KEY_PROGRAM_GROUP = "programGroup" */
private static final String AUTO_KEY_PROGRAM_GROUP = "programGroup";
/** AUTO_KEY_SHORTCUT = "shortcut" */
private static final String AUTO_KEY_SHORTCUT = "shortcut";
// ------------------------------------------------------
// automatic script keys attributes
// ------------------------------------------------------
/** AUTO_ATTRIBUTE_NAME = "name" */
private static final String AUTO_ATTRIBUTE_NAME = "name";
/** AUTO_ATTRIBUTE_GROUP = "group" */
private static final String AUTO_ATTRIBUTE_GROUP = "group";
/** AUTO_ATTRIBUTE_TYPE "type" */
private static final String AUTO_ATTRIBUTE_TYPE = "type";
/** AUTO_ATTRIBUTE_COMMAND = "commandLine" */
private static final String AUTO_ATTRIBUTE_COMMAND = "commandLine";
/** AUTO_ATTRIBUTE_DESCRIPTION = "description" */
private static final String AUTO_ATTRIBUTE_DESCRIPTION = "description";
/** AUTO_ATTRIBUTE_ICON = "icon" */
private static final String AUTO_ATTRIBUTE_ICON = "icon";
/** AUTO_ATTRIBUTE_ICON_INDEX = "iconIndex" */
private static final String AUTO_ATTRIBUTE_ICON_INDEX = "iconIndex";
/** AUTO_ATTRIBUTE_INITIAL_STATE = "initialState" */
private static final String AUTO_ATTRIBUTE_INITIAL_STATE = "initialState";
/** AUTO_ATTRIBUTE_TARGET = "target" */
private static final String AUTO_ATTRIBUTE_TARGET = "target";
/** AUTO_ATTRIBUTE_WORKING_DIR = "workingDirectory" */
private static final String AUTO_ATTRIBUTE_WORKING_DIR = "workingDirectory";
// permission flags
private static final String CREATE_FOR_ALL = "createForAll";
// ------------------------------------------------------------------------
// Variable Declarations
// ------------------------------------------------------------------------
/** UI element to label the list of existing program groups */
private JLabel listLabel;
/** UI element to present the list of existing program groups for selection */
private JList groupList;
/** UI element for listing the intended shortcut targets */
private JList targetList;
/**
* UI element to present the default name for the program group and to support editing of this
* name.
*/
private JTextField programGroup;
/**
* UI element to allow the user to revert to the default name of the program group
*/
private JButton defaultButton;
/**
* UI element to allow the user to save a text file with the shortcut information
*/
private JButton saveButton;
/**
* UI element to allow the user to decide if shortcuts should be placed on the desktop or not.
*/
private JCheckBox allowDesktopShortcut;
private JCheckBox createShortcuts;
/**
* UI element instruct this panel to create shortcuts for the current user only
*/
private JRadioButton currentUser;
/** UI element instruct this panel to create shortcuts for all users */
private JRadioButton allUsers;
/** The layout for this panel */
private GridBagLayout layout;
/** The contraints object to use whan creating the layout */
private GridBagConstraints constraints;
/**
* The default name to use for the program group. This comes from the XML specification.
*/
private String suggestedProgramGroup;
/** The name chosen by the user for the program group, */
private String groupName;
/**
* The location for placign the program group. This is the same as the location (type) of a
* shortcut, only that it applies to the program group. Note that there are only two locations
* that make sense as location for a program group: <br>
*
* <ul>
* <li>applications</li>
* <li>start manu</li>
* </ul>
*
*/
private int groupLocation;
/** The parsed result from reading the XML specification from the file */
private XMLElement spec;
/**
* Set to <code>true</code> by <code>analyzeShortcutSpec()</code> if there are any desktop
* shortcuts to create.
*/
private boolean hasDesktopShortcuts = false;
/** Tells wether to skip if the platform is not supported. */
private boolean skipIfNotSupported = false;
/** the one shortcut instance for reuse in many locations */
private Shortcut shortcut;
/**
* A list of <code>ShortcutData</code> objects. Each object is the complete specification for
* one shortcut that must be created.
*/
private Vector shortcuts = new Vector();
/**
* Holds a list of all the shortcut files that have been created. <b>Note: </b> this variable
* contains valid data only after <code>createShortcuts()</code> has been called. This list is
* created so that the files can be added to the uninstaller.
*/
private Vector files = new Vector();
/**
* If <code>true</code> it indicates that there are shortcuts to create. The value is set by
* <code>analyzeShortcutSpec()</code>
*/
private boolean shortcutsToCreate = false;
/**
* If <code>true</code> it indicates that the spec file is existing and could be read.
*/
private boolean haveShortcutSpec = false;
/**
* This is set to true if the shortcut spec instructs to simulate running on an operating system
* that is not supported.
*/
private boolean simulteNotSupported = false;
/**
* Avoids bogus behaviour when the user goes back then returns to this panel.
*/
private boolean firstTime = true;
private File itsProgramFolder;
private int itsUserType;
static boolean create;
private static boolean isRootUser;
/*
* --------------------------------------------------------------------------
*/
/**
* Constructor.
*
* @param parent reference to the application frame
* @param installData shared information about the installation
*/
/*
* --------------------------------------------------------------------------
*/
public ShortcutPanel(InstallerFrame parent, InstallData installData)
{
super(parent, installData);
// read the XML file
try
{
readShortcutSpec();
}
catch (Throwable exception)
{
System.out.println("could not read shortcut spec!");
exception.printStackTrace();
}
layout = new GridBagLayout();
constraints = new GridBagConstraints();
setLayout(layout);
// Create the UI elements
try
{
shortcut = (Shortcut) (TargetFactory.getInstance()
.makeObject("com.izforge.izpack.util.os.Shortcut"));
shortcut.initialize(Shortcut.APPLICATIONS, "-");
}
catch (Throwable exception)
{
System.out.println("could not create shortcut instance");
exception.printStackTrace();
}
}
//~ Methods
// **************************************************************************************************************************************************
/*--------------------------------------------------------------------------*/
/**
* This method represents the <code>ActionListener</code> interface, invoked when an action
* occurs.
*
* @param event the action event.
*/
/*--------------------------------------------------------------------------*/
public void actionPerformed(ActionEvent event)
{
Object eventSource = event.getSource();
// ----------------------------------------------------
// create shortcut for the current user was selected
// refresh the list of program groups accordingly and
// reset the program group to the default setting.
// ----------------------------------------------------
if (eventSource.equals(currentUser))
{
groupList.setListData(shortcut.getProgramGroups(Shortcut.CURRENT_USER));
programGroup.setText(suggestedProgramGroup);
shortcut.setUserType(itsUserType = Shortcut.CURRENT_USER);
}
// ----------------------------------------------------
// create shortcut for all users was selected
// refresh the list of program groups accordingly and
// reset the program group to the default setting.
// ----------------------------------------------------
else if (eventSource.equals(allUsers))
{
groupList.setListData(shortcut.getProgramGroups(Shortcut.ALL_USERS));
programGroup.setText(suggestedProgramGroup);
shortcut.setUserType(itsUserType = Shortcut.ALL_USERS);
}
// ----------------------------------------------------
// The reset button was pressed.
// - clear the selection in the list box, because the
// selection is no longer valid
// - refill the program group edit control with the
// suggested program group name
// ----------------------------------------------------
else if (eventSource.equals(defaultButton))
{
groupList.getSelectionModel().clearSelection();
programGroup.setText(suggestedProgramGroup);
}
// ----------------------------------------------------
// the save button was pressed. This is a request to
// save shortcut information to a text file.
// ----------------------------------------------------
else if (eventSource.equals(saveButton))
{
saveToFile();
// add the file to the uninstaller
addToUninstaller();
}
else if (eventSource.equals(createShortcuts))
{
create = createShortcuts.isSelected();
groupList.setEnabled(create);
programGroup.setEnabled(create);
currentUser.setEnabled(create);
defaultButton.setEnabled(create);
allowDesktopShortcut.setEnabled(create);
if( isRootUser )
allUsers.setEnabled(create);
}
}
/*--------------------------------------------------------------------------*/
/**
* Returns <code>true</code> when all selections have valid settings. This indicates that it
* is legal to procede to the next panel.
*
* @return <code>true</code> if it is legal to procede to the next panel, otherwise
* <code>false</code>.
*/
/*--------------------------------------------------------------------------*/
public boolean isValidated()
{
try
{
groupName = programGroup.getText();
}
catch (Throwable exception)
{
groupName = "";
}
create = createShortcuts.isSelected();
createShortcuts();
// add files and directories to the uninstaller
addToUninstaller();
return (true);
}
/*--------------------------------------------------------------------------*/
/**
* Called when the panel is shown to the user.
*/
/*--------------------------------------------------------------------------*/
public void panelActivate()
{
if (firstTime)
firstTime = false;
else
return;
analyzeShortcutSpec();
if (shortcutsToCreate)
{
if (shortcut.supported() && !simulteNotSupported)
{
File allUsersProgramsFolder = getProgramsFolder(Shortcut.ALL_USERS);
isRootUser = allUsersProgramsFolder.canWrite();
if (isRootUser)
itsUserType = Shortcut.ALL_USERS;
else
itsUserType = Shortcut.CURRENT_USER;
buildUI( getProgramsFolder(isRootUser ? Shortcut.ALL_USERS : Shortcut.CURRENT_USER) );
}
else
{
if (skipIfNotSupported)
{
parent.skipPanel();
}
else
{
buildAlternateUI();
parent.unlockNextButton();
parent.lockPrevButton();
}
}
}
else
{
; //parent.skipPanel ();
}
}
/**
* Returns the ProgramsFolder for the current User
*
* @return The Basedir
*/
private File getProgramsFolder(int userType)
{
String path = shortcut.getProgramsFolder(userType);
return (new File(path));
//}
//else
//{
// TODO
// 0pt. Test if KDE is installed.
//boolean isKdeInstalled = UnixHelper.kdeIsInstalled();
// 1. Test if User can write into
// File kdeRootShareApplinkDir = getKDERootShareApplinkDir();
// if so: return getKDERootShareApplinkDir()
// else
// return getKDEUsersShareApplinkDir() +
//}
//return(result);
}
/**
* This method is called by the <code>groupList</code> when the user makes a selection. It
* updates the content of the <code>programGroup</code> with the result of the selection.
*
* @param event the list selection event
*/
/*--------------------------------------------------------------------------*/
public void valueChanged(ListSelectionEvent event)
{
if (programGroup == null) { return; }
String value = "";
try
{
value = (String) groupList.getSelectedValue();
}
catch (ClassCastException exception)
{}
if (value == null)
{
value = "";
}
programGroup.setText(value + File.separator + suggestedProgramGroup);
}
/*--------------------------------------------------------------------------*/
/**
* Reads the XML specification for the shortcuts to create. The result is stored in spec.
*
* @exception Exception for any problems in reading the specification
*/
/*--------------------------------------------------------------------------*/
private void readShortcutSpec() throws Exception
{
// open an input stream
InputStream input = null;
try
{
input = parent.getResource(TargetFactory.getCurrentOSPrefix() + SPEC_FILE_NAME);
}
catch (ResourceNotFoundException rnfE)
{
input = parent.getResource(SPEC_FILE_NAME);
if (input == null)
{
haveShortcutSpec = false;
return;
}
}
// if( input == null )
// {
// haveShortcutSpec = false;
// return;
// }
// initialize the parser
StdXMLParser parser = new StdXMLParser();
parser.setBuilder(new StdXMLBuilder());
parser.setValidator(new NonValidator());
parser.setReader(new StdXMLReader(input));
// get the data
spec = (XMLElement) parser.parse();
// close the stream
input.close();
haveShortcutSpec = true;
}
/*--------------------------------------------------------------------------*/
/**
* This method analyzes the specifications for creating shortcuts and builds a list of all the
* Shortcuts that need to be created.
*/
/*--------------------------------------------------------------------------*/
private void analyzeShortcutSpec()
{
if (!haveShortcutSpec)
{
shortcutsToCreate = false;
return;
}
XMLElement skipper = spec.getFirstChildNamed(SPEC_KEY_SKIP_IFNOT_SUPPORTED);
skipIfNotSupported = (skipper != null);
// ----------------------------------------------------
// find out if we should simulate a not supported
// scenario
// ----------------------------------------------------
XMLElement support = spec.getFirstChildNamed(SPEC_KEY_NOT_SUPPORTED);
if (support != null)
{
simulteNotSupported = true;
}
// ----------------------------------------------------
// find out in which program group the shortcuts should
// be placed and where this program group should be
// located
// ----------------------------------------------------
XMLElement group = spec.getFirstChildNamed(SPEC_KEY_PROGRAM_GROUP);
String location = null;
hasDesktopShortcuts = false;
if (group != null)
{
suggestedProgramGroup = group.getAttribute(SPEC_ATTRIBUTE_DEFAULT_GROUP, "");
location = group.getAttribute(SPEC_ATTRIBUTE_LOCATION, SPEC_VALUE_APPLICATIONS);
}
else
{
suggestedProgramGroup = "";
location = SPEC_VALUE_APPLICATIONS;
}
if (location.equals(SPEC_VALUE_APPLICATIONS))
{
groupLocation = Shortcut.APPLICATIONS;
}
else if (location.equals(SPEC_VALUE_START_MENU))
{
groupLocation = Shortcut.START_MENU;
}
// ----------------------------------------------------
// create a list of all shortcuts that need to be
// created, containing all details about each shortcut
// ----------------------------------------------------
VariableSubstitutor substitutor = new VariableSubstitutor(idata.getVariables());
String temp;
Vector shortcutSpecs = spec.getChildrenNamed(SPEC_KEY_SHORTCUT);
XMLElement shortcutSpec;
ShortcutData data;
for (int i = 0; i < shortcutSpecs.size(); i++)
{
shortcutSpec = (XMLElement) shortcutSpecs.elementAt(i);
if (!OsConstraint.oneMatchesCurrentSystem(shortcutSpec)) continue;
data = new ShortcutData();
data.name = shortcutSpec.getAttribute(SPEC_ATTRIBUTE_NAME);
data.subgroup = shortcutSpec.getAttribute(SPEC_ATTRIBUTE_SUBGROUP);
data.description = shortcutSpec.getAttribute(SPEC_ATTRIBUTE_DESCRIPTION, "");
//** Linux **//
data.deskTopEntryLinux_Encoding = shortcutSpec
.getAttribute(SPEC_ATTRIBUTE_ENCODING, "");
data.deskTopEntryLinux_MimeType = shortcutSpec
.getAttribute(SPEC_ATTRIBUTE_MIMETYPE, "");
data.deskTopEntryLinux_Terminal = shortcutSpec
.getAttribute(SPEC_ATTRIBUTE_TERMINAL, "");
data.deskTopEntryLinux_TerminalOptions = shortcutSpec.getAttribute(
SPEC_ATTRIBUTE_TERMINAL_OPTIONS, "");
data.deskTopEntryLinux_Type = shortcutSpec.getAttribute(SPEC_ATTRIBUTE_TYPE, "");
data.deskTopEntryLinux_URL = substitutor.substitute(shortcutSpec.getAttribute(
SPEC_ATTRIBUTE_URL, ""), null);
data.deskTopEntryLinux_X_KDE_SubstituteUID = shortcutSpec.getAttribute(
SPEC_ATTRIBUTE_KDE_SUBST_UID, "");
data.createForAll = new Boolean(shortcutSpec.getAttribute(CREATE_FOR_ALL, "false"));
//** EndOf LINUX **//
temp = fixSeparatorChar(shortcutSpec.getAttribute(SPEC_ATTRIBUTE_TARGET, ""));
data.target = substitutor.substitute(temp, null);
temp = shortcutSpec.getAttribute(SPEC_ATTRIBUTE_COMMAND, "");
data.commandLine = substitutor.substitute(temp, null);
temp = fixSeparatorChar(shortcutSpec.getAttribute(SPEC_ATTRIBUTE_ICON, ""));
data.iconFile = substitutor.substitute(temp, null);
data.iconIndex = Integer.parseInt(shortcutSpec.getAttribute(SPEC_ATTRIBUTE_ICON_INDEX,
"0"));
temp = fixSeparatorChar(shortcutSpec.getAttribute(SPEC_ATTRIBUTE_WORKING_DIR, ""));
data.workingDirectory = substitutor.substitute(temp, null);
String initialState = shortcutSpec.getAttribute(SPEC_ATTRIBUTE_INITIAL_STATE, "");
if (initialState.equals(SPEC_VALUE_NO_SHOW))
{
data.initialState = Shortcut.HIDE;
}
else if (initialState.equals(SPEC_VALUE_NORMAL))
{
data.initialState = Shortcut.NORMAL;
}
else if (initialState.equals(SPEC_VALUE_MAXIMIZED))
{
data.initialState = Shortcut.MAXIMIZED;
}
else if (initialState.equals(SPEC_VALUE_MINIMIZED))
{
data.initialState = Shortcut.MINIMIZED;
}
else
{
data.initialState = Shortcut.NORMAL;
}
// --------------------------------------------------
// if the minimal data requirements are met to create
// the shortcut, create one entry each for each of
// the requested types.
// Eventually this will cause the creation of one
// shortcut in each of the associated locations.
// --------------------------------------------------
// without a name we can not create a shortcut
if (data.name == null)
{
continue;
}
//1. Elmar: "Without a target we can not create a shortcut."
//2. Marc: "No, Even on Linux a Link can be an URL and has no target."
if (data.target == null)
{
continue;
}
// the shortcut is not actually required for any of the selected packs
Vector forPacks = shortcutSpec.getChildrenNamed(SPEC_KEY_PACKS);
if (!shortcutRequiredFor(forPacks))
{
continue;
}
// --------------------------------------------------
// This section is executed if we don't skip.
// --------------------------------------------------
// For each of the categories set the type and if
// the link should be placed in the program group,
// then clone the data set to obtain an independent
// instance and add this to the list of shortcuts
// to be created. In this way, we will set up an
// identical copy for each of the locations at which
// a shortcut should be placed. Therefore you must
// not use 'else if' statements!
// --------------------------------------------------
{
if (attributeIsTrue(shortcutSpec, SPEC_ATTRIBUTE_DESKTOP))
{
hasDesktopShortcuts = true;
data.addToGroup = false;
data.type = Shortcut.DESKTOP;
shortcuts.add(data.clone());
}
if (attributeIsTrue(shortcutSpec, SPEC_ATTRIBUTE_APPLICATIONS))
{
data.addToGroup = false;
data.type = Shortcut.APPLICATIONS;
shortcuts.add(data.clone());
}
if (attributeIsTrue(shortcutSpec, SPEC_ATTRIBUTE_START_MENU))
{
data.addToGroup = false;
data.type = Shortcut.START_MENU;
shortcuts.add(data.clone());
}
if (attributeIsTrue(shortcutSpec, SPEC_ATTRIBUTE_STARTUP))
{
data.addToGroup = false;
data.type = Shortcut.START_UP;
shortcuts.add(data.clone());
}
if (attributeIsTrue(shortcutSpec, SPEC_ATTRIBUTE_PROGRAM_GROUP))
{
data.addToGroup = true;
data.type = Shortcut.APPLICATIONS;
shortcuts.add(data.clone());
}
}
}
// ----------------------------------------------------
// signal if there are any shortcuts to create
// ----------------------------------------------------
if (shortcuts.size() > 0)
{
shortcutsToCreate = true;
}
}
/*--------------------------------------------------------------------------*/
/**
* Creates all shortcuts based on the information in <code>shortcuts</code>.
*/
/*--------------------------------------------------------------------------*/
private void createShortcuts()
{
if (!create) return;
ShortcutData data;
for (int i = 0; i < shortcuts.size(); i++)
{
data = (ShortcutData) shortcuts.elementAt(i);
try
{
groupName = groupName + data.subgroup;
shortcut.setUserType(itsUserType);
shortcut.setLinkName(data.name);
shortcut.setLinkType(data.type);
shortcut.setArguments(data.commandLine);
shortcut.setDescription(data.description);
shortcut.setIconLocation(data.iconFile, data.iconIndex);
shortcut.setShowCommand(data.initialState);
shortcut.setTargetPath(data.target);
shortcut.setWorkingDirectory(data.workingDirectory);
shortcut.setEncoding(data.deskTopEntryLinux_Encoding);
shortcut.setMimetype(data.deskTopEntryLinux_MimeType);
shortcut.setTerminal(data.deskTopEntryLinux_Terminal);
shortcut.setTerminalOptions(data.deskTopEntryLinux_TerminalOptions);
shortcut.setType(data.deskTopEntryLinux_Type);
shortcut.setKdeSubstUID(data.deskTopEntryLinux_X_KDE_SubstituteUID);
shortcut.setURL(data.deskTopEntryLinux_URL);
shortcut.setCreateForAll(data.createForAll);
if (data.addToGroup)
{
shortcut.setProgramGroup(groupName);
}
else
{
shortcut.setProgramGroup("");
}
try
{
// ----------------------------------------------
// save the shortcut only if it is either not on
// the desktop or if it is on the desktop and
// the user has signalled that it is ok to place
// shortcuts on the desktop.
// ----------------------------------------------
if ((data.type != Shortcut.DESKTOP)
|| ((data.type == Shortcut.DESKTOP) && allowDesktopShortcut
.isSelected()))
{
// save the shortcut
shortcut.save();
// add the file and directory name to the file list
String fileName = shortcut.getFileName();
files.add(0, fileName);
File file = new File(fileName);
File base = new File(shortcut.getBasePath());
Vector intermediates = new Vector();
//String directoryName = shortcut.getDirectoryCreated ();
execFiles.add(new ExecutableFile(fileName, 2, ExecutableFile.WARN,
new ArrayList(), false));
files.add(fileName);
while ((file = file.getParentFile()) != null)
{
if (file.equals(base)) break;
intermediates.add(file);
}
if (file != null)
{
for (Iterator iter = intermediates.iterator(); iter.hasNext();)
files.add(0, iter.next().toString());
}
}
}
catch (Exception exception)
{}
}
catch (Throwable exception)
{
continue;
}
}
//
try
{
if (execFiles != null)
{
FileExecutor executor = new FileExecutor(execFiles);
//
// TODO: Hi Guys,
// TODO The following commented-out line sometimes produces an uncatchable
// nullpointer Exception!
// TODO evaluate for what reason the files should exec.
// TODO if there is a serious explanation, why to do that,
// TODO the code must be more robust
//evaluate executor.executeFiles( ExecutableFile.NEVER, null );
}
}
catch (NullPointerException nep)
{
nep.printStackTrace();
}
catch (RuntimeException cannot)
{
cannot.printStackTrace();
}
parent.unlockNextButton();
}
/*--------------------------------------------------------------------------*/
/**
* Verifies if the shortcut is required for any of the packs listed. The shortcut is required
* for a pack in the list if that pack is actually selected for installation. <br>
* <br>
* <b>Note: </b> <br>
* If the list of selected packs is empty then <code>true</code> is always returnd. The same
* is true if the <code>packs</code> list is empty.
*
* @param packs a <code>Vector</code> of <code>String</code>s. Each of the strings denotes
* a pack for which the schortcut should be created if the pack is actually installed.
*
* @return <code>true</code> if the shortcut is required for at least on pack in the list,
* otherwise returns <code>false</code>.
*/
/*--------------------------------------------------------------------------*/
/*
* $ @design
*
* The information about the installed packs comes from InstallData.selectedPacks. This assumes
* that this panel is presented to the user AFTER the PacksPanel.
* --------------------------------------------------------------------------
*/
private boolean shortcutRequiredFor(Vector packs)
{
String selected;
String required;
if (packs.size() == 0) { return (true); }
for (int i = 0; i < idata.selectedPacks.size(); i++)
{
selected = ((Pack) idata.selectedPacks.get(i)).name;
for (int k = 0; k < packs.size(); k++)
{
required = (String) ((XMLElement) packs.elementAt(k)).getAttribute(
SPEC_ATTRIBUTE_NAME, "");
if (selected.equals(required)) { return (true); }
}
}
return (false);
}
/*--------------------------------------------------------------------------*/
/**
* Determines if the named attribute in true. True is represented by any of the following
* strings and is not case sensitive. <br>
*
* <ul>
* <li>yes</li>
* <li>1</li>
* <li>true</li>
* <li>on</li>
* </ul>
*
* <br>
* Every other string, including the empty string as well as the non-existence of the attribute
* will cuase <code>false</code> to be returned.
*
* @param element the <code>XMLElement</code> to search for the attribute.
* @param name the name of the attribute to test.
*
* @return <code>true</code> if the attribute value equals one of the pre-defined strings,
* <code>false</code> otherwise.
*/
/*--------------------------------------------------------------------------*/
private boolean attributeIsTrue(XMLElement element, String name)
{
String value = element.getAttribute(name, "").toUpperCase();
if (value.equals("YES"))
{
return (true);
}
else if (value.equals("TRUE"))
{
return (true);
}
else if (value.equals("ON"))
{
return (true);
}
else if (value.equals("1")) { return (true); }
return (false);
}
/*--------------------------------------------------------------------------*/
/**
* Replaces any ocurrence of '/' or '\' in a path string with the correct version for the
* operating system.
*
* @param path a system path
*
* @return a path string that uniformely uses the proper version of the separator character.
*/
/*--------------------------------------------------------------------------*/
private String fixSeparatorChar(String path)
{
String newPath = path.replace('/', File.separatorChar);
newPath = newPath.replace('\\', File.separatorChar);
return (newPath);
}
/*--------------------------------------------------------------------------*/
/**
* This method creates the UI for this panel.
*
* @param groups A <code>Vector</code> that contains <code>Strings</code> with all the names
* of the existing program groups. These will be placed in the <code>groupList</code>.
* @param currentUserList if <code>true</code> it indicates that the list of groups is valid
* for the current user, otherwise it is considered valid for all users.
*/
/*--------------------------------------------------------------------------*/
private void buildUI(File groups)//, boolean currentUserList)
{
itsProgramFolder = groups;
layout = new GridBagLayout();
constraints = new GridBagConstraints();
setLayout(layout);
// ----------------------------------------------------
// label a the top of the panel, that gives the
// basic instructions
// ----------------------------------------------------
listLabel = LabelFactory.create(parent.langpack.getString("ShortcutPanel.regular.list"),
JLabel.LEADING);
constraints.gridx = 0;
constraints.gridy = 0;
constraints.gridwidth = 1;
constraints.gridheight = 1;
constraints.weightx = 1.0;
constraints.weighty = 1.0;
constraints.insets = new Insets(5, 5, 5, 5);
constraints.fill = GridBagConstraints.NONE;
constraints.anchor = GridBagConstraints.WEST;
layout.addLayoutComponent(listLabel, constraints);
add(listLabel);
// ----------------------------------------------------
// list box to list all of already existing folders as program groups
// at the intended destination
// ----------------------------------------------------
Vector dirEntries = new Vector();
File[] entries = groups.listFiles();
for (int idx = 0; idx < entries.length; idx++)
{
if (entries[idx].isDirectory())
{
dirEntries.add(entries[idx].getName());
}
}
groupList = new JList(dirEntries);
groupList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
groupList.getSelectionModel().addListSelectionListener(this);
JScrollPane scrollPane = new JScrollPane(groupList);
constraints.gridx = 0;
constraints.gridy = 1;
constraints.gridwidth = 1;
constraints.gridheight = 1;
constraints.fill = GridBagConstraints.BOTH;
layout.addLayoutComponent(scrollPane, constraints);
add(scrollPane);
// ----------------------------------------------------
// radio buttons to select current user or all users.
// ----------------------------------------------------
if (shortcut.multipleUsers())
{
JPanel usersPanel = new JPanel(new GridLayout(2, 1));
ButtonGroup usersGroup = new ButtonGroup();
currentUser = new JRadioButton(parent.langpack
.getString("ShortcutPanel.regular.currentUser"), !isRootUser);
currentUser.addActionListener(this);
usersGroup.add(currentUser);
usersPanel.add(currentUser);
allUsers = new JRadioButton(
parent.langpack.getString("ShortcutPanel.regular.allUsers"), isRootUser);
if (!isRootUser) allUsers.setEnabled(false);
allUsers.addActionListener(this);
usersGroup.add(allUsers);
usersPanel.add(allUsers);
TitledBorder border = new TitledBorder(new EmptyBorder(2, 2, 2, 2), parent.langpack
.getString("ShortcutPanel.regular.userIntro"));
usersPanel.setBorder(border);
constraints.gridx = 1;
constraints.gridy = 1;
constraints.gridwidth = 1;
constraints.gridheight = 1;
constraints.fill = GridBagConstraints.NONE;
layout.addLayoutComponent(usersPanel, constraints);
add(usersPanel);
}
// ----------------------------------------------------
// edit box that contains the suggested program group
// name, which can be modfied or substituted from the
// list by the user
// ----------------------------------------------------
programGroup = new JTextField(suggestedProgramGroup, 40); // 40?
constraints.gridx = 0;
constraints.gridy = 2;
constraints.gridwidth = 1;
constraints.gridheight = 1;
constraints.fill = GridBagConstraints.HORIZONTAL;
layout.addLayoutComponent(programGroup, constraints);
add(programGroup);
// ----------------------------------------------------
// reset button that allows the user to revert to the
// original suggestion for the program group
// ----------------------------------------------------
defaultButton = ButtonFactory.createButton(parent.langpack
.getString("ShortcutPanel.regular.default"), idata.buttonsHColor);
defaultButton.addActionListener(this);
constraints.gridx = 1;
constraints.gridy = 2;
constraints.gridwidth = 1;
constraints.gridheight = 1;
constraints.fill = GridBagConstraints.NONE;
layout.addLayoutComponent(defaultButton, constraints);
add(defaultButton);
// ----------------------------------------------------
// check box to allow the user to decide if a desktop
// shortcut should be created.
// this should only be created if needed and requested
// in the definition file.
// ----------------------------------------------------
boolean initialAllowedFlag = idata.getVariable("DesktopShortcutCheckboxEnabled") == null ? false
: true;
allowDesktopShortcut = new JCheckBox(parent.langpack
.getString("ShortcutPanel.regular.desktop"), initialAllowedFlag);
constraints.gridx = 0;
constraints.gridy = 3;
constraints.gridwidth = 1;
constraints.gridheight = 1;
if (hasDesktopShortcuts)
{
layout.addLayoutComponent(allowDesktopShortcut, constraints);
add(allowDesktopShortcut);
}
// TODO add here
createShortcuts = new JCheckBox(parent.langpack.getString("ShortcutPanel.regular.create"),
true);
createShortcuts.addActionListener(this);
constraints.gridx = 0;
constraints.gridy = 4;
constraints.gridwidth = 1;
constraints.gridheight = 1;
if (hasDesktopShortcuts)
{
layout.addLayoutComponent(createShortcuts, constraints);
add(createShortcuts);
}
}
/*--------------------------------------------------------------------------*/
/**
* This method creates an alternative UI for this panel. This UI can be used when the creation
* of shortcuts is not supported on the target system. It displays an apology for the inability
* to create shortcuts on this system, along with information about the intended targets. In
* addition, there is a button that allows the user to save more complete information in a text
* file. Based on this information the user might be able to create the necessary shortcut him
* or herself. At least there will be information about how to launch the application.
*/
/*--------------------------------------------------------------------------*/
private void buildAlternateUI()
{
layout = new GridBagLayout();
constraints = new GridBagConstraints();
setLayout(layout);
// ----------------------------------------------------
// static text a the top of the panel, that apologizes
// about the fact that we can not create shortcuts on
// this particular target OS.
// ----------------------------------------------------
MultiLineLabel apologyLabel = new MultiLineLabel(parent.langpack
.getString("ShortcutPanel.alternate.apology"), 0, 0);
constraints.gridx = 0;
constraints.gridy = 0;
constraints.gridwidth = 1;
constraints.gridheight = 1;
constraints.weightx = 1.0;
constraints.weighty = 1.0;
constraints.insets = new Insets(5, 5, 5, 5);
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.anchor = GridBagConstraints.WEST;
layout.addLayoutComponent(apologyLabel, constraints);
add(apologyLabel);
// ----------------------------------------------------
// label that explains the significance ot the list box
// ----------------------------------------------------
MultiLineLabel listLabel = new MultiLineLabel(parent.langpack
.getString("ShortcutPanel.alternate.targetsLabel"), 0, 0);
constraints.gridx = 0;
constraints.gridy = 1;
constraints.gridwidth = 1;
constraints.gridheight = 1;
constraints.weightx = 1.0;
constraints.weighty = 1.0;
layout.addLayoutComponent(listLabel, constraints);
add(listLabel);
// ----------------------------------------------------
// list box to list all of the intended shortcut targets
// ----------------------------------------------------
Vector targets = new Vector();
for (int i = 0; i < shortcuts.size(); i++)
{
targets.add(((ShortcutData) shortcuts.elementAt(i)).target);
}
targetList = new JList(targets);
JScrollPane scrollPane = new JScrollPane(targetList);
constraints.gridx = 0;
constraints.gridy = 2;
constraints.fill = GridBagConstraints.BOTH;
layout.addLayoutComponent(scrollPane, constraints);
add(scrollPane);
// ----------------------------------------------------
// static text that explains about the text file
// ----------------------------------------------------
MultiLineLabel fileExplanation = new MultiLineLabel(parent.langpack
.getString("ShortcutPanel.alternate.textFileExplanation"), 0, 0);
constraints.gridx = 0;
constraints.gridy = 3;
constraints.weightx = 1.0;
constraints.weighty = 1.0;
constraints.fill = GridBagConstraints.HORIZONTAL;
layout.addLayoutComponent(fileExplanation, constraints);
add(fileExplanation);
// ----------------------------------------------------
// button to save the text file
// ----------------------------------------------------
saveButton = ButtonFactory.createButton(parent.langpack
.getString("ShortcutPanel.alternate.saveButton"), idata.buttonsHColor);
saveButton.addActionListener(this);
constraints.gridx = 0;
constraints.gridy = 4;
constraints.gridwidth = 1;
constraints.gridheight = 1;
constraints.fill = GridBagConstraints.NONE;
constraints.anchor = GridBagConstraints.CENTER;
layout.addLayoutComponent(saveButton, constraints);
add(saveButton);
}
/*--------------------------------------------------------------------------*/
/**
* Overriding the superclass implementation. This method returns the size of the container.
*
* @return the size of the container
*/
/*--------------------------------------------------------------------------*/
public Dimension getSize()
{
Dimension size = getParent().getSize();
Insets insets = getInsets();
Border border = getBorder();
Insets borderInsets = new Insets(0, 0, 0, 0);
if (border != null)
{
borderInsets = border.getBorderInsets(this);
}
size.height = size.height - insets.top - insets.bottom - borderInsets.top
- borderInsets.bottom - 50;
size.width = size.width - insets.left - insets.right - borderInsets.left
- borderInsets.right - 50;
return (size);
}
/*--------------------------------------------------------------------------*/
/**
* This method saves all shortcut information to a text file.
*/
/*--------------------------------------------------------------------------*/
private void saveToFile()
{
File file = null;
// ----------------------------------------------------
// open a file chooser dialog to get a path / file name
// ----------------------------------------------------
JFileChooser fileDialog = new JFileChooser(idata.getInstallPath());
fileDialog.setSelectedFile(new File(TEXT_FILE_NAME));
if (fileDialog.showSaveDialog(this) == JFileChooser.APPROVE_OPTION)
{
file = fileDialog.getSelectedFile();
}
else
{
return;
}
// ----------------------------------------------------
// save to the file
// ----------------------------------------------------
FileWriter output = null;
StringBuffer buffer = new StringBuffer();
String header = parent.langpack.getString("ShortcutPanel.textFile.header");
String newline = System.getProperty("line.separator", "\n");
try
{
output = new FileWriter(file);
}
catch (Throwable exception)
{
// !!! show an error dialog
return;
}
// ----------------------------------------------------
// break the header down into multiple lines based
// on '\n' line breaks.
// ----------------------------------------------------
int nextIndex = 0;
int currentIndex = 0;
do
{
nextIndex = header.indexOf("\\n", currentIndex);
if (nextIndex > -1)
{
buffer.append(header.substring(currentIndex, nextIndex));
buffer.append(newline);
currentIndex = nextIndex + 2;
}
else
{
buffer.append(header.substring(currentIndex, header.length()));
buffer.append(newline);
}
}
while (nextIndex > -1);
buffer.append(SEPARATOR_LINE);
buffer.append(newline);
buffer.append(newline);
for (int i = 0; i < shortcuts.size(); i++)
{
ShortcutData data = (ShortcutData) shortcuts.elementAt(i);
buffer.append(parent.langpack.getString("ShortcutPanel.textFile.name"));
buffer.append(data.name);
buffer.append(newline);
buffer.append(parent.langpack.getString("ShortcutPanel.textFile.location"));
switch (data.type)
{
case Shortcut.DESKTOP: {
buffer.append(parent.langpack.getString("ShortcutPanel.location.desktop"));
break;
}
case Shortcut.APPLICATIONS: {
buffer.append(parent.langpack.getString("ShortcutPanel.location.applications"));
break;
}
case Shortcut.START_MENU: {
buffer.append(parent.langpack.getString("ShortcutPanel.location.startMenu"));
break;
}
case Shortcut.START_UP: {
buffer.append(parent.langpack.getString("ShortcutPanel.location.startup"));
break;
}
}
buffer.append(newline);
buffer.append(parent.langpack.getString("ShortcutPanel.textFile.description"));
buffer.append(data.description);
buffer.append(newline);
buffer.append(parent.langpack.getString("ShortcutPanel.textFile.target"));
buffer.append(data.target);
buffer.append(newline);
buffer.append(parent.langpack.getString("ShortcutPanel.textFile.command"));
buffer.append(data.commandLine);
buffer.append(newline);
buffer.append(parent.langpack.getString("ShortcutPanel.textFile.iconName"));
buffer.append(data.iconFile);
buffer.append(newline);
buffer.append(parent.langpack.getString("ShortcutPanel.textFile.iconIndex"));
buffer.append(data.iconIndex);
buffer.append(newline);
buffer.append(parent.langpack.getString("ShortcutPanel.textFile.work"));
buffer.append(data.workingDirectory);
buffer.append(newline);
buffer.append(newline);
buffer.append(SEPARATOR_LINE);
buffer.append(newline);
buffer.append(newline);
}
try
{
output.write(buffer.toString());
}
catch (Throwable exception)
{}
finally
{
try
{
output.flush();
output.close();
files.add(file.getPath());
}
catch (Throwable exception)
{
// not really anything I can do here, maybe should show a dialog that
// tells the user that data might not have been saved completely!?
}
}
}
/*--------------------------------------------------------------------------*/
/**
* Adds all files and directories to the uninstaller.
*/
/*--------------------------------------------------------------------------*/
private void addToUninstaller()
{
UninstallData uninstallData = UninstallData.getInstance();
for (int i = 0; i < files.size(); i++)
{
uninstallData.addFile((String) files.elementAt(i));
}
}
/*--------------------------------------------------------------------------*/
/**
* Adds iformation about the shortcuts that have been created during the installation to the XML
* tree.
*
* @param panelRoot the root of the XML tree
*/
/*--------------------------------------------------------------------------*/
/*
* $ @design
*
* The information needed to create shortcuts has been collected in the Vector 'shortcuts'. Take
* the data from there and package it in XML form for storage by the installer. The group name
* is only stored once in a separate XML element, since there is only one.
* --------------------------------------------------------------------------
*/
public void makeXMLData(XMLElement panelRoot)
{
// ----------------------------------------------------
// if there are no shortcuts to create, shortcuts are
// not supported, or we should simulate that they are
// not supported, then we have nothing to add. Just
// return
// ----------------------------------------------------
if (!shortcutsToCreate || !shortcut.supported() || groupName == null || simulteNotSupported) { return; }
ShortcutData data;
XMLElement dataElement;
// ----------------------------------------------------
// add the item that defines the name of the program group
// ----------------------------------------------------
dataElement = new XMLElement(AUTO_KEY_PROGRAM_GROUP);
dataElement.setAttribute(AUTO_ATTRIBUTE_NAME, groupName);
panelRoot.addChild(dataElement);
// ----------------------------------------------------
// add the details for each of the shortcuts
// ----------------------------------------------------
for (int i = 0; i < shortcuts.size(); i++)
{
data = (ShortcutData) shortcuts.elementAt(i);
dataElement = new XMLElement(AUTO_KEY_SHORTCUT);
dataElement.setAttribute(AUTO_ATTRIBUTE_NAME, data.name);
dataElement.setAttribute(AUTO_ATTRIBUTE_GROUP, Boolean.valueOf(data.addToGroup)
.toString());
dataElement.setAttribute(AUTO_ATTRIBUTE_TYPE, Integer.toString(data.type));
dataElement.setAttribute(AUTO_ATTRIBUTE_COMMAND, data.commandLine);
dataElement.setAttribute(AUTO_ATTRIBUTE_DESCRIPTION, data.description);
dataElement.setAttribute(AUTO_ATTRIBUTE_ICON, data.iconFile);
dataElement.setAttribute(AUTO_ATTRIBUTE_ICON_INDEX, Integer.toString(data.iconIndex));
dataElement.setAttribute(AUTO_ATTRIBUTE_INITIAL_STATE, Integer
.toString(data.initialState));
dataElement.setAttribute(AUTO_ATTRIBUTE_TARGET, data.target);
dataElement.setAttribute(AUTO_ATTRIBUTE_WORKING_DIR, data.workingDirectory);
// ----------------------------------------------
// add the shortcut only if it is either not on
// the desktop or if it is on the desktop and
// the user has signalled that it is ok to place
// shortcuts on the desktop.
// ----------------------------------------------
if ((data.type != Shortcut.DESKTOP)
|| ((data.type == Shortcut.DESKTOP) && allowDesktopShortcut.isSelected()))
{
panelRoot.addChild(dataElement);
}
}
}
/*--------------------------------------------------------------------------*/
/**
* Creates shortcuts based on teh information in <code>panelRoot</code> without UI.
*
* @param panelRoot the root of the XML tree
*/
/*--------------------------------------------------------------------------*/
/*
* $ @design
*
* Reconstitute the information needed to create shortcuts from XML data that was previously
* stored by the installer through makeXMLData(). Create a new Vector containing this data and
* stroe it in 'shortcuts' for use by createShortcuts(). Once this has been completed, call
* createShortcuts() to complete the operation.
* --------------------------------------------------------------------------
*/
public void runAutomated(XMLElement panelRoot)
{
// ----------------------------------------------------
// if shortcuts are not supported, then we can not
// create shortcuts, even if there was any install
// data. Just return.
// ----------------------------------------------------
if (!shortcut.supported()) { return; }
if (!OsConstraint.oneMatchesCurrentSystem(panelRoot)) { return; }
shortcuts = new Vector();
Vector shortcutElements;
ShortcutData data;
XMLElement dataElement;
// ----------------------------------------------------
// set the name of the program group
// ----------------------------------------------------
dataElement = panelRoot.getFirstChildNamed(AUTO_KEY_PROGRAM_GROUP);
groupName = dataElement.getAttribute(AUTO_ATTRIBUTE_NAME);
if (groupName == null)
{
groupName = "";
}
// ----------------------------------------------------
// add the details for each of the shortcuts
// ----------------------------------------------------
shortcutElements = panelRoot.getChildrenNamed(AUTO_KEY_SHORTCUT);
for (int i = 0; i < shortcutElements.size(); i++)
{
data = new ShortcutData();
dataElement = (XMLElement) shortcutElements.elementAt(i);
data.name = dataElement.getAttribute(AUTO_ATTRIBUTE_NAME);
data.addToGroup = Boolean.valueOf(dataElement.getAttribute(AUTO_ATTRIBUTE_GROUP))
.booleanValue();
data.type = Integer.valueOf(dataElement.getAttribute(AUTO_ATTRIBUTE_TYPE)).intValue();
data.commandLine = dataElement.getAttribute(AUTO_ATTRIBUTE_COMMAND);
data.description = dataElement.getAttribute(AUTO_ATTRIBUTE_DESCRIPTION);
data.iconFile = dataElement.getAttribute(AUTO_ATTRIBUTE_ICON);
data.iconIndex = Integer.valueOf(dataElement.getAttribute(AUTO_ATTRIBUTE_ICON_INDEX))
.intValue();
data.initialState = Integer.valueOf(
dataElement.getAttribute(AUTO_ATTRIBUTE_INITIAL_STATE)).intValue();
data.target = dataElement.getAttribute(AUTO_ATTRIBUTE_TARGET);
data.workingDirectory = dataElement.getAttribute(AUTO_ATTRIBUTE_WORKING_DIR);
shortcuts.add(data);
}
createShortcuts();
}
/*
* The Initial-State of the Button is diabled, bacause it makle no sense to go back.
*
* @see com.izforge.izpack.installer.IzPanel#forceLockPrevButton()
*/
public boolean forceLockPrevButton()
{
return true;
}
/**
* If there is No Shortcut-Specification, this must be skipped.
*
* @see com.izforge.izpack.installer.IzPanel#isToBeSkipped()
*/
/*
* (Kein Javadoc)
*
* @see com.izforge.izpack.installer.IzPanel#forceLockNextButton()
*/
public boolean forceLockNextButton()
{
// TODO Automatisch erstellter Methoden-Stub
return true;
}
}
/*---------------------------------------------------------------------------*/
| readded the serialVersionUID
also re-commented in the skipPanel-call.
git-svn-id: 408af81b9e4f0a5eaad229a6d9eed76d614c4af6@1207 7d736ef5-cfd4-0310-9c9a-b52d5c14b761
| src/lib/com/izforge/izpack/panels/ShortcutPanel.java | readded the serialVersionUID also re-commented in the skipPanel-call. | <ide><path>rc/lib/com/izforge/izpack/panels/ShortcutPanel.java
<ide> /*
<ide> * IzPack - Copyright 2001-2005 Julien Ponge, All Rights Reserved.
<ide> *
<del> * http://www.izforge.com/izpack/ http://developer.berlios.de/projects/izpack/
<add> * http://www.izforge.com/izpack/
<add> * http://developer.berlios.de/projects/izpack/
<ide> *
<ide> * Copyright 2002 Elmar Grom
<ide> *
<ide> // - need a clean way to get pack name
<ide> public class ShortcutPanel extends IzPanel implements ActionListener, ListSelectionListener
<ide> {
<del>
<add> /**
<add> *
<add> */
<add> private static final long serialVersionUID = 3256722870838112311L;
<add>
<ide> /** a VectorList of Files wich should be make executable */
<ide> private Vector execFiles = new Vector();
<ide>
<ide> }
<ide> else
<ide> {
<del> ; //parent.skipPanel ();
<add> parent.skipPanel ();
<ide> }
<ide> }
<ide>
<ide> createShortcuts();
<ide> }
<ide>
<del> /*
<del> * The Initial-State of the Button is diabled, bacause it makle no sense to go back.
<del> *
<del> * @see com.izforge.izpack.installer.IzPanel#forceLockPrevButton()
<del> */
<del> public boolean forceLockPrevButton()
<del> {
<del> return true;
<del> }
<del>
<del>
<del> /**
<del> * If there is No Shortcut-Specification, this must be skipped.
<del> *
<del> * @see com.izforge.izpack.installer.IzPanel#isToBeSkipped()
<del> */
<del>
<del> /*
<del> * (Kein Javadoc)
<del> *
<del> * @see com.izforge.izpack.installer.IzPanel#forceLockNextButton()
<del> */
<del> public boolean forceLockNextButton()
<del> {
<del> // TODO Automatisch erstellter Methoden-Stub
<del> return true;
<del> }
<add>
<ide> }
<ide>
<ide> /*---------------------------------------------------------------------------*/ |
|
Java | mit | d1ebb0d27efd5cf6c535e0f77f3e52413e5de59b | 0 | Jason0803/Cocoa-Note,Jason0803/Cocoa-Note,Jason0803/Cocoa-Note | package dao.diary;
// #00011 : import change required
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Vector;
import sql.StringQuery;
import util.CocoaDate;
import util.DataSourceManager;
import vo.diary.Memo;
import vo.diary.Note;
import vo.diary.Schedule;
public class DiaryDAO {
private static DiaryDAO dao = new DiaryDAO();
private DiaryDAO() {}
public static DiaryDAO getInstance() {
return dao;
}
public Connection getConnection() throws SQLException{
return DataSourceManager.getInstance().getConnection();
}
public void closeAll(PreparedStatement ps, Connection conn)throws SQLException{
if(ps!=null) ps.close();
if(conn!=null) conn.close();
}
public void closeAll(ResultSet rs,PreparedStatement ps, Connection conn)throws SQLException{
if(rs!=null){
rs.close();
closeAll(ps, conn);
}
}//
// ------------------------------ Logics ------------------------------ //
// ------------------------------ getAllMemo ------------------------------ //
public Vector<Memo> getAllMemo(String id) throws SQLException {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
Vector<Memo> v = null;
try {
conn = getConnection();
v = new Vector<Memo>();
ps = conn.prepareStatement(StringQuery.GET_ALL_MEMO);
rs = ps.executeQuery();
while(rs.next()) {
Memo m = new Memo(rs.getInt("note_no"),
rs.getString("id"),
new CocoaDate(rs.getDate("wrt_date")),
new CocoaDate(rs.getDate("curr_date")),
rs.getString("title"),
rs.getString("content"));
v.add(m);
}
} catch(SQLException e) {
System.out.println("ERROR : [DiaryDAO]@getAllMemo : SQLException Caught !");
e.printStackTrace();
} finally {
System.out.println("[DiaryDAO]@getAllMemo : Arrived finally clause");
closeAll(rs,ps,conn);
}
return v;
}
// ------------------------------ getAllSchedule ------------------------------ //
public Vector<Schedule> getAllSchedule(String id) throws SQLException {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
Vector<Schedule> sc = null;
String[] temp_str = {};
try {
conn = getConnection();
sc = new Vector<Schedule>();
ps= conn.prepareStatement(StringQuery.GET_ALL_SCHEDULE);
rs = ps.executeQuery();
while(rs.next()) {
sc.add(new Schedule(rs.getInt("schedule_no"), rs.getString("id"), rs.getString("title"), temp_str,
new CocoaDate(rs.getDate("start_date")), new CocoaDate(rs.getDate("end_date"))));
}
}catch(Exception e) {
System.out.println("ERROR : [DiaryDAO]@getAllSchedule : SQLException Caught !");
e.printStackTrace();
}finally {
closeAll(rs, ps, conn);
System.out.println("[DiaryDAO]@getAllSchedule : Arrived finally clause");
}
return null;
}
// ------------------------------ getAllNote ------------------------------ //
public Vector<Note> getAllNote(String id) throws SQLException {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
Vector<Note> n = null;
try {
conn = getConnection();
n = new Vector<Note>();
ps= conn.prepareStatement(StringQuery.GET_ALL_NOTE);
rs = ps.executeQuery();
while(rs.next()) {
}
}catch(Exception e) {
e.printStackTrace();
}finally {
closeAll(rs, ps, conn);
}
return null;
}
}
| src/dao/diary/DiaryDAO.java | package dao.diary;
// #00011 : import change required
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Vector;
import sql.StringQuery;
import util.CocoaDate;
import util.DataSourceManager;
import vo.diary.Memo;
import vo.diary.Note;
import vo.diary.Schedule;
public class DiaryDAO {
private static DiaryDAO dao = new DiaryDAO();
private DiaryDAO() {}
public static DiaryDAO getInstance() {
return dao;
}
public Connection getConnection() throws SQLException{
return DataSourceManager.getInstance().getConnection();
}
public void closeAll(PreparedStatement ps, Connection conn)throws SQLException{
if(ps!=null) ps.close();
if(conn!=null) conn.close();
}
public void closeAll(ResultSet rs,PreparedStatement ps, Connection conn)throws SQLException{
if(rs!=null){
rs.close();
closeAll(ps, conn);
}
}//
// ------------------------------ Logics ------------------------------ //
<<<<<<< HEAD
// ------------------------------ [TEMP TEST] ------------------------------ //
public void printMemoDate(String id) throws SQLException {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = getConnection();
ps = conn.prepareStatement("SELECT wrt_date FROM memo WHERE id = ?");
//ps.setString(parameterIndex, x);
} catch(SQLException e) {
} finally {
}
}
=======
>>>>>>> master
// ------------------------------ getAllMemo ------------------------------ //
public Vector<Memo> getAllMemo(String id) throws SQLException {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
Vector<Memo> v = null;
try {
conn = getConnection();
v = new Vector<Memo>();
ps = conn.prepareStatement(StringQuery.GET_ALL_MEMO);
rs = ps.executeQuery();
<<<<<<< HEAD
// #00053 : getAllMemo
=======
>>>>>>> master
while(rs.next()) {
Memo m = new Memo(rs.getInt("note_no"),
rs.getString("id"),
new CocoaDate(rs.getDate("wrt_date")),
new CocoaDate(rs.getDate("curr_date")),
rs.getString("title"),
rs.getString("content"));
v.add(m);
}
} catch(SQLException e) {
System.out.println("ERROR : [DiaryDAO]@getAllMemo : SQLException Caught !");
e.printStackTrace();
} finally {
System.out.println("[DiaryDAO]@getAllMemo : Arrived finally clause");
closeAll(rs,ps,conn);
}
return v;
}
// ------------------------------ getAllSchedule ------------------------------ //
public Vector<Schedule> getAllSchedule(String id) throws SQLException {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
Vector<Schedule> sc = null;
String[] temp_str = {};
try {
conn = getConnection();
sc = new Vector<Schedule>();
ps= conn.prepareStatement(StringQuery.GET_ALL_SCHEDULE);
rs = ps.executeQuery();
while(rs.next()) {
sc.add(new Schedule(rs.getInt("schedule_no"), rs.getString("id"), rs.getString("title"), temp_str,
new CocoaDate(rs.getDate("start_date")), new CocoaDate(rs.getDate("end_date"))));
}
}catch(Exception e) {
System.out.println("ERROR : [DiaryDAO]@getAllSchedule : SQLException Caught !");
e.printStackTrace();
}finally {
closeAll(rs, ps, conn);
System.out.println("[DiaryDAO]@getAllSchedule : Arrived finally clause");
}
return null;
}
// ------------------------------ getAllNote ------------------------------ //
public Vector<Note> getAllNote(String id) throws SQLException {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
Vector<Note> n = null;
try {
conn = getConnection();
n = new Vector<Note>();
ps= conn.prepareStatement(StringQuery.GET_ALL_NOTE);
rs = ps.executeQuery();
while(rs.next()) {
}
}catch(Exception e) {
e.printStackTrace();
}finally {
closeAll(rs, ps, conn);
}
return null;
}
}
| #00059 : Conflict Fix
| src/dao/diary/DiaryDAO.java | #00059 : Conflict Fix | <ide><path>rc/dao/diary/DiaryDAO.java
<ide>
<ide>
<ide> // ------------------------------ Logics ------------------------------ //
<del><<<<<<< HEAD
<del> // ------------------------------ [TEMP TEST] ------------------------------ //
<del> public void printMemoDate(String id) throws SQLException {
<del> Connection conn = null;
<del> PreparedStatement ps = null;
<del> ResultSet rs = null;
<del>
<del> try {
<del> conn = getConnection();
<del> ps = conn.prepareStatement("SELECT wrt_date FROM memo WHERE id = ?");
<del> //ps.setString(parameterIndex, x);
<del> } catch(SQLException e) {
<del>
<del> } finally {
<del>
<del> }
<del> }
<del>=======
<del>
<del>>>>>>>> master
<ide> // ------------------------------ getAllMemo ------------------------------ //
<ide> public Vector<Memo> getAllMemo(String id) throws SQLException {
<ide> Connection conn = null;
<ide> v = new Vector<Memo>();
<ide> ps = conn.prepareStatement(StringQuery.GET_ALL_MEMO);
<ide> rs = ps.executeQuery();
<del>
<del><<<<<<< HEAD
<del> // #00053 : getAllMemo
<del>=======
<del>>>>>>>> master
<add>
<ide> while(rs.next()) {
<ide> Memo m = new Memo(rs.getInt("note_no"),
<ide> rs.getString("id"), |
|
Java | bsd-3-clause | 01f3bd460085f3126bb4f1aae8f070849bb5b99e | 0 | JeffreyFalgout/ThrowingStream | package throwing.stream;
import static java.util.stream.Collectors.toList;
import static org.hamcrest.Matchers.contains;
import static org.junit.Assert.assertThat;
import java.util.List;
import java.util.stream.Stream;
import org.junit.Test;
public class ReadmeTest {
@SuppressWarnings("unchecked")
@Test
public void readme() throws ClassNotFoundException {
Stream<String> names = Stream.of("java.lang.Object", "java.util.stream.Stream");
ThrowingStream<String, ClassNotFoundException> s = ThrowingStream.of(names, ClassNotFoundException.class);
List<Class<?>> l = s.map(ClassLoader.getSystemClassLoader()::loadClass).collect(toList());
assertThat(l, contains(Object.class, Stream.class));
}
}
| src/test/java/throwing/stream/ReadmeTest.java | package throwing.stream;
import static java.util.stream.Collectors.toList;
import static org.hamcrest.Matchers.contains;
import static org.junit.Assert.assertThat;
import java.util.List;
import java.util.stream.Stream;
import org.junit.Test;
import throwing.bridge.ThrowingBridge;
public class ReadmeTest {
@SuppressWarnings("unchecked")
@Test
public void readme() throws ClassNotFoundException {
Stream<String> names = Stream.of("java.lang.Object", "java.util.stream.Stream");
ThrowingStream<String, ClassNotFoundException> s = ThrowingBridge.of(names, ClassNotFoundException.class);
List<Class<?>> l = s.map(ClassLoader.getSystemClassLoader()::loadClass).collect(toList());
assertThat(l, contains(Object.class, Stream.class));
}
}
| Update readme test | src/test/java/throwing/stream/ReadmeTest.java | Update readme test | <ide><path>rc/test/java/throwing/stream/ReadmeTest.java
<ide>
<ide> import org.junit.Test;
<ide>
<del>import throwing.bridge.ThrowingBridge;
<del>
<ide> public class ReadmeTest {
<ide> @SuppressWarnings("unchecked")
<ide> @Test
<ide> public void readme() throws ClassNotFoundException {
<ide> Stream<String> names = Stream.of("java.lang.Object", "java.util.stream.Stream");
<del> ThrowingStream<String, ClassNotFoundException> s = ThrowingBridge.of(names, ClassNotFoundException.class);
<add> ThrowingStream<String, ClassNotFoundException> s = ThrowingStream.of(names, ClassNotFoundException.class);
<ide> List<Class<?>> l = s.map(ClassLoader.getSystemClassLoader()::loadClass).collect(toList());
<ide> assertThat(l, contains(Object.class, Stream.class));
<ide> } |
|
Java | apache-2.0 | 5356ded021565fd6622eb69a411bb7cb96822b53 | 0 | pushy-me/pushy-cordova,pushy-me/pushy-cordova,pushy-me/pushy-cordova | package me.pushy.sdk;
import android.os.Build;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.Context;
import android.media.RingtoneManager;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.util.Log;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
public class PushReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// Notification title and text
String notificationTitle = getAppName(context);
String notificationText = "";
// Attempt to extract the notification text from the "message" property of the data payload
if (intent.getStringExtra("message") != null) {
notificationText = intent.getStringExtra("message");
}
// Prepare a notification with vibration and sound
Notification.Builder builder = new Notification.Builder(context)
.setAutoCancel(true)
.setContentTitle(notificationTitle)
.setContentText(notificationText)
.setVibrate(new long[]{0, 400, 250, 400})
.setSmallIcon(context.getApplicationInfo().icon)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setContentIntent(getMainActivityPendingIntent(context));
// Get an instance of the NotificationManager service
NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
// Device is Android O or newer?
if (Build.VERSION.SDK_INT >= 26) {
configureNotificationChannel(builder, notificationManager);
}
// Build the notification and display it
notificationManager.notify(1, builder.build());
}
private static String getAppName(Context context) {
// Attempt to determine app name via package manager
return context.getPackageManager().getApplicationLabel(context.getApplicationInfo()).toString();
}
private PendingIntent getMainActivityPendingIntent(Context context) {
// Get launcher activity intent
Intent launchIntent = context.getPackageManager().getLaunchIntentForPackage(context.getApplicationContext().getPackageName());
// Make sure to update the activity if it exists
launchIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Convert intent into pending intent
return PendingIntent.getActivity(context, 0, launchIntent, PendingIntent.FLAG_UPDATE_CURRENT);
}
private void configureNotificationChannel(Notification.Builder builder, NotificationManager notificationManager) {
// Channel details
String channelId = "pushy";
String channelName = "Push Notifications";
// Channel importance (4 means high importance)
int channelImportance = 4;
try {
// Get NotificationChannel class via reflection (only available on API level 26+)
Class notificationChannelClass = Class.forName("android.app.NotificationChannel");
// Get NotificationChannel constructor
Constructor<?> notificationChannelConstructor = notificationChannelClass.getDeclaredConstructor(String.class, CharSequence.class, int.class);
// Instantiate new notification channel
Object notificationChannel = notificationChannelConstructor.newInstance(channelId, channelName, channelImportance);
// Get notification channel creation method via reflection
Method createNotificationChannelMethod = notificationManager.getClass().getDeclaredMethod("createNotificationChannel", notificationChannelClass);
// Invoke method on NotificationManager, passing in the channel object
createNotificationChannelMethod.invoke(notificationManager, notificationChannel);
// Get "setChannelId" method for Notification.Builder (only for AppCompat v26+)
Method setChannelIdMethod = builder.getClass().getDeclaredMethod("setChannelId", String.class);
// Invoke method, passing in the channel ID
setChannelIdMethod.invoke(builder, channelId);
// Log success to console
Log.d("Pushy", "Notification channel set successfully");
} catch (Exception exc) {
// Log exception to console
Log.e("Pushy", "Creating notification channel failed", exc);
}
}
} | receiver/src/android/PushReceiver.java | package me.pushy.sdk;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.Context;
import android.media.RingtoneManager;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
public class PushReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// Notification title and text
String notificationTitle = getAppName(context);
String notificationText = "";
// Attempt to extract the notification text from the "message" property of the data payload
if (intent.getStringExtra("message") != null) {
notificationText = intent.getStringExtra("message");
}
// Prepare a notification with vibration and sound
Notification.Builder builder = new Notification.Builder(context)
.setAutoCancel(true)
.setContentTitle(notificationTitle)
.setContentText(notificationText)
.setVibrate(new long[]{0, 400, 250, 400})
.setSmallIcon(context.getApplicationInfo().icon)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setContentIntent(getMainActivityPendingIntent(context));
// Get an instance of the NotificationManager service
NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
// Build the notification and display it
notificationManager.notify(1, builder.build());
}
private static String getAppName(Context context) {
// Attempt to determine app name via package manager
return context.getPackageManager().getApplicationLabel(context.getApplicationInfo()).toString();
}
private PendingIntent getMainActivityPendingIntent(Context context) {
// Get launcher activity intent
Intent launchIntent = context.getPackageManager().getLaunchIntentForPackage(context.getApplicationContext().getPackageName());
// Make sure to update the activity if it exists
launchIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Convert intent into pending intent
return PendingIntent.getActivity(context, 0, launchIntent, PendingIntent.FLAG_UPDATE_CURRENT);
}
} | Support for Android O Notification Channels
| receiver/src/android/PushReceiver.java | Support for Android O Notification Channels | <ide><path>eceiver/src/android/PushReceiver.java
<ide> package me.pushy.sdk;
<ide>
<add>import android.os.Build;
<ide> import android.app.Notification;
<ide> import android.app.PendingIntent;
<ide> import android.content.Intent;
<ide> import android.media.RingtoneManager;
<ide> import android.app.NotificationManager;
<ide> import android.content.BroadcastReceiver;
<add>import android.util.Log;
<add>
<add>import java.lang.reflect.Constructor;
<add>import java.lang.reflect.Method;
<ide>
<ide> public class PushReceiver extends BroadcastReceiver {
<ide> @Override
<ide> // Get an instance of the NotificationManager service
<ide> NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
<ide>
<add> // Device is Android O or newer?
<add> if (Build.VERSION.SDK_INT >= 26) {
<add> configureNotificationChannel(builder, notificationManager);
<add> }
<add>
<ide> // Build the notification and display it
<ide> notificationManager.notify(1, builder.build());
<ide> }
<ide> // Convert intent into pending intent
<ide> return PendingIntent.getActivity(context, 0, launchIntent, PendingIntent.FLAG_UPDATE_CURRENT);
<ide> }
<add>
<add> private void configureNotificationChannel(Notification.Builder builder, NotificationManager notificationManager) {
<add> // Channel details
<add> String channelId = "pushy";
<add> String channelName = "Push Notifications";
<add>
<add> // Channel importance (4 means high importance)
<add> int channelImportance = 4;
<add>
<add> try {
<add> // Get NotificationChannel class via reflection (only available on API level 26+)
<add> Class notificationChannelClass = Class.forName("android.app.NotificationChannel");
<add>
<add> // Get NotificationChannel constructor
<add> Constructor<?> notificationChannelConstructor = notificationChannelClass.getDeclaredConstructor(String.class, CharSequence.class, int.class);
<add>
<add> // Instantiate new notification channel
<add> Object notificationChannel = notificationChannelConstructor.newInstance(channelId, channelName, channelImportance);
<add>
<add> // Get notification channel creation method via reflection
<add> Method createNotificationChannelMethod = notificationManager.getClass().getDeclaredMethod("createNotificationChannel", notificationChannelClass);
<add>
<add> // Invoke method on NotificationManager, passing in the channel object
<add> createNotificationChannelMethod.invoke(notificationManager, notificationChannel);
<add>
<add> // Get "setChannelId" method for Notification.Builder (only for AppCompat v26+)
<add> Method setChannelIdMethod = builder.getClass().getDeclaredMethod("setChannelId", String.class);
<add>
<add> // Invoke method, passing in the channel ID
<add> setChannelIdMethod.invoke(builder, channelId);
<add>
<add> // Log success to console
<add> Log.d("Pushy", "Notification channel set successfully");
<add> } catch (Exception exc) {
<add> // Log exception to console
<add> Log.e("Pushy", "Creating notification channel failed", exc);
<add> }
<add> }
<ide> } |
|
Java | apache-2.0 | 05a19452c31ceb0f947f8df8e6485b95cdeb007c | 0 | ryano144/intellij-community,xfournet/intellij-community,allotria/intellij-community,nicolargo/intellij-community,ryano144/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,allotria/intellij-community,gnuhub/intellij-community,alphafoobar/intellij-community,izonder/intellij-community,clumsy/intellij-community,gnuhub/intellij-community,samthor/intellij-community,Lekanich/intellij-community,supersven/intellij-community,vvv1559/intellij-community,TangHao1987/intellij-community,muntasirsyed/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,nicolargo/intellij-community,suncycheng/intellij-community,robovm/robovm-studio,signed/intellij-community,alphafoobar/intellij-community,slisson/intellij-community,alphafoobar/intellij-community,blademainer/intellij-community,MichaelNedzelsky/intellij-community,ahb0327/intellij-community,retomerz/intellij-community,apixandru/intellij-community,pwoodworth/intellij-community,salguarnieri/intellij-community,Distrotech/intellij-community,slisson/intellij-community,hurricup/intellij-community,vladmm/intellij-community,robovm/robovm-studio,petteyg/intellij-community,ftomassetti/intellij-community,pwoodworth/intellij-community,robovm/robovm-studio,FHannes/intellij-community,allotria/intellij-community,da1z/intellij-community,pwoodworth/intellij-community,alphafoobar/intellij-community,caot/intellij-community,ftomassetti/intellij-community,adedayo/intellij-community,allotria/intellij-community,pwoodworth/intellij-community,ThiagoGarciaAlves/intellij-community,SerCeMan/intellij-community,retomerz/intellij-community,Lekanich/intellij-community,izonder/intellij-community,TangHao1987/intellij-community,TangHao1987/intellij-community,ernestp/consulo,xfournet/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,blademainer/intellij-community,TangHao1987/intellij-community,consulo/consulo,petteyg/intellij-community,fnouama/intellij-community,holmes/intellij-community,adedayo/intellij-community,gnuhub/intellij-community,holmes/intellij-community,MichaelNedzelsky/intellij-community,muntasirsyed/intellij-community,retomerz/intellij-community,hurricup/intellij-community,ryano144/intellij-community,mglukhikh/intellij-community,kdwink/intellij-community,ftomassetti/intellij-community,ol-loginov/intellij-community,holmes/intellij-community,slisson/intellij-community,caot/intellij-community,mglukhikh/intellij-community,tmpgit/intellij-community,mglukhikh/intellij-community,michaelgallacher/intellij-community,wreckJ/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,salguarnieri/intellij-community,MER-GROUP/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,alphafoobar/intellij-community,salguarnieri/intellij-community,kool79/intellij-community,caot/intellij-community,SerCeMan/intellij-community,mglukhikh/intellij-community,clumsy/intellij-community,fnouama/intellij-community,xfournet/intellij-community,kool79/intellij-community,suncycheng/intellij-community,retomerz/intellij-community,fnouama/intellij-community,apixandru/intellij-community,gnuhub/intellij-community,akosyakov/intellij-community,pwoodworth/intellij-community,lucafavatella/intellij-community,signed/intellij-community,jagguli/intellij-community,dslomov/intellij-community,fnouama/intellij-community,SerCeMan/intellij-community,ryano144/intellij-community,petteyg/intellij-community,clumsy/intellij-community,ol-loginov/intellij-community,slisson/intellij-community,ahb0327/intellij-community,adedayo/intellij-community,robovm/robovm-studio,suncycheng/intellij-community,wreckJ/intellij-community,apixandru/intellij-community,ahb0327/intellij-community,diorcety/intellij-community,ol-loginov/intellij-community,kdwink/intellij-community,nicolargo/intellij-community,apixandru/intellij-community,ernestp/consulo,nicolargo/intellij-community,allotria/intellij-community,diorcety/intellij-community,hurricup/intellij-community,izonder/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,gnuhub/intellij-community,gnuhub/intellij-community,michaelgallacher/intellij-community,holmes/intellij-community,vladmm/intellij-community,slisson/intellij-community,ivan-fedorov/intellij-community,amith01994/intellij-community,apixandru/intellij-community,TangHao1987/intellij-community,blademainer/intellij-community,ivan-fedorov/intellij-community,kdwink/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,ivan-fedorov/intellij-community,lucafavatella/intellij-community,akosyakov/intellij-community,jagguli/intellij-community,fitermay/intellij-community,FHannes/intellij-community,amith01994/intellij-community,ibinti/intellij-community,kdwink/intellij-community,da1z/intellij-community,MichaelNedzelsky/intellij-community,robovm/robovm-studio,ernestp/consulo,caot/intellij-community,samthor/intellij-community,samthor/intellij-community,dslomov/intellij-community,jagguli/intellij-community,orekyuu/intellij-community,MER-GROUP/intellij-community,lucafavatella/intellij-community,ftomassetti/intellij-community,ahb0327/intellij-community,salguarnieri/intellij-community,akosyakov/intellij-community,consulo/consulo,suncycheng/intellij-community,tmpgit/intellij-community,fengbaicanhe/intellij-community,vladmm/intellij-community,MER-GROUP/intellij-community,ibinti/intellij-community,Distrotech/intellij-community,wreckJ/intellij-community,diorcety/intellij-community,caot/intellij-community,fnouama/intellij-community,diorcety/intellij-community,ibinti/intellij-community,diorcety/intellij-community,slisson/intellij-community,xfournet/intellij-community,consulo/consulo,retomerz/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,hurricup/intellij-community,ibinti/intellij-community,FHannes/intellij-community,TangHao1987/intellij-community,dslomov/intellij-community,robovm/robovm-studio,fitermay/intellij-community,petteyg/intellij-community,fnouama/intellij-community,xfournet/intellij-community,lucafavatella/intellij-community,xfournet/intellij-community,salguarnieri/intellij-community,consulo/consulo,semonte/intellij-community,hurricup/intellij-community,wreckJ/intellij-community,fengbaicanhe/intellij-community,apixandru/intellij-community,ryano144/intellij-community,vvv1559/intellij-community,supersven/intellij-community,suncycheng/intellij-community,ryano144/intellij-community,fnouama/intellij-community,samthor/intellij-community,amith01994/intellij-community,ryano144/intellij-community,SerCeMan/intellij-community,pwoodworth/intellij-community,allotria/intellij-community,FHannes/intellij-community,semonte/intellij-community,signed/intellij-community,kool79/intellij-community,samthor/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,amith01994/intellij-community,alphafoobar/intellij-community,SerCeMan/intellij-community,hurricup/intellij-community,ftomassetti/intellij-community,semonte/intellij-community,clumsy/intellij-community,petteyg/intellij-community,muntasirsyed/intellij-community,amith01994/intellij-community,akosyakov/intellij-community,asedunov/intellij-community,semonte/intellij-community,fengbaicanhe/intellij-community,ernestp/consulo,kdwink/intellij-community,slisson/intellij-community,slisson/intellij-community,da1z/intellij-community,semonte/intellij-community,MichaelNedzelsky/intellij-community,diorcety/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,TangHao1987/intellij-community,clumsy/intellij-community,semonte/intellij-community,ivan-fedorov/intellij-community,youdonghai/intellij-community,consulo/consulo,mglukhikh/intellij-community,michaelgallacher/intellij-community,vvv1559/intellij-community,vladmm/intellij-community,kool79/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,dslomov/intellij-community,kool79/intellij-community,slisson/intellij-community,vladmm/intellij-community,asedunov/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,wreckJ/intellij-community,fitermay/intellij-community,FHannes/intellij-community,fitermay/intellij-community,clumsy/intellij-community,ftomassetti/intellij-community,lucafavatella/intellij-community,da1z/intellij-community,nicolargo/intellij-community,orekyuu/intellij-community,caot/intellij-community,MichaelNedzelsky/intellij-community,jagguli/intellij-community,adedayo/intellij-community,ol-loginov/intellij-community,FHannes/intellij-community,wreckJ/intellij-community,semonte/intellij-community,gnuhub/intellij-community,Distrotech/intellij-community,petteyg/intellij-community,SerCeMan/intellij-community,orekyuu/intellij-community,MER-GROUP/intellij-community,Lekanich/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,ryano144/intellij-community,adedayo/intellij-community,jagguli/intellij-community,fnouama/intellij-community,alphafoobar/intellij-community,MER-GROUP/intellij-community,fnouama/intellij-community,akosyakov/intellij-community,caot/intellij-community,jagguli/intellij-community,xfournet/intellij-community,MER-GROUP/intellij-community,ftomassetti/intellij-community,akosyakov/intellij-community,ol-loginov/intellij-community,lucafavatella/intellij-community,ernestp/consulo,ThiagoGarciaAlves/intellij-community,MER-GROUP/intellij-community,pwoodworth/intellij-community,fengbaicanhe/intellij-community,allotria/intellij-community,salguarnieri/intellij-community,amith01994/intellij-community,fitermay/intellij-community,ahb0327/intellij-community,clumsy/intellij-community,lucafavatella/intellij-community,ibinti/intellij-community,retomerz/intellij-community,izonder/intellij-community,nicolargo/intellij-community,amith01994/intellij-community,adedayo/intellij-community,Distrotech/intellij-community,ivan-fedorov/intellij-community,adedayo/intellij-community,slisson/intellij-community,MichaelNedzelsky/intellij-community,ryano144/intellij-community,retomerz/intellij-community,consulo/consulo,asedunov/intellij-community,vvv1559/intellij-community,muntasirsyed/intellij-community,idea4bsd/idea4bsd,diorcety/intellij-community,akosyakov/intellij-community,michaelgallacher/intellij-community,tmpgit/intellij-community,dslomov/intellij-community,adedayo/intellij-community,Lekanich/intellij-community,vvv1559/intellij-community,samthor/intellij-community,vladmm/intellij-community,pwoodworth/intellij-community,asedunov/intellij-community,vladmm/intellij-community,petteyg/intellij-community,allotria/intellij-community,asedunov/intellij-community,salguarnieri/intellij-community,signed/intellij-community,SerCeMan/intellij-community,TangHao1987/intellij-community,idea4bsd/idea4bsd,supersven/intellij-community,ahb0327/intellij-community,jagguli/intellij-community,ibinti/intellij-community,kdwink/intellij-community,alphafoobar/intellij-community,semonte/intellij-community,muntasirsyed/intellij-community,ernestp/consulo,ThiagoGarciaAlves/intellij-community,wreckJ/intellij-community,holmes/intellij-community,gnuhub/intellij-community,tmpgit/intellij-community,apixandru/intellij-community,Distrotech/intellij-community,blademainer/intellij-community,lucafavatella/intellij-community,FHannes/intellij-community,MER-GROUP/intellij-community,orekyuu/intellij-community,nicolargo/intellij-community,petteyg/intellij-community,vvv1559/intellij-community,michaelgallacher/intellij-community,clumsy/intellij-community,amith01994/intellij-community,youdonghai/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,jagguli/intellij-community,youdonghai/intellij-community,clumsy/intellij-community,suncycheng/intellij-community,ftomassetti/intellij-community,holmes/intellij-community,akosyakov/intellij-community,fengbaicanhe/intellij-community,da1z/intellij-community,fitermay/intellij-community,ol-loginov/intellij-community,nicolargo/intellij-community,petteyg/intellij-community,mglukhikh/intellij-community,orekyuu/intellij-community,muntasirsyed/intellij-community,Distrotech/intellij-community,orekyuu/intellij-community,orekyuu/intellij-community,dslomov/intellij-community,supersven/intellij-community,adedayo/intellij-community,fitermay/intellij-community,fengbaicanhe/intellij-community,ibinti/intellij-community,ol-loginov/intellij-community,da1z/intellij-community,xfournet/intellij-community,salguarnieri/intellij-community,izonder/intellij-community,jagguli/intellij-community,MichaelNedzelsky/intellij-community,signed/intellij-community,fitermay/intellij-community,SerCeMan/intellij-community,michaelgallacher/intellij-community,Distrotech/intellij-community,youdonghai/intellij-community,dslomov/intellij-community,adedayo/intellij-community,amith01994/intellij-community,muntasirsyed/intellij-community,ol-loginov/intellij-community,blademainer/intellij-community,ibinti/intellij-community,FHannes/intellij-community,holmes/intellij-community,hurricup/intellij-community,wreckJ/intellij-community,caot/intellij-community,ryano144/intellij-community,asedunov/intellij-community,semonte/intellij-community,allotria/intellij-community,caot/intellij-community,adedayo/intellij-community,signed/intellij-community,ivan-fedorov/intellij-community,alphafoobar/intellij-community,TangHao1987/intellij-community,da1z/intellij-community,tmpgit/intellij-community,petteyg/intellij-community,ftomassetti/intellij-community,tmpgit/intellij-community,blademainer/intellij-community,robovm/robovm-studio,diorcety/intellij-community,ahb0327/intellij-community,blademainer/intellij-community,kool79/intellij-community,fengbaicanhe/intellij-community,muntasirsyed/intellij-community,ThiagoGarciaAlves/intellij-community,ahb0327/intellij-community,izonder/intellij-community,semonte/intellij-community,ivan-fedorov/intellij-community,apixandru/intellij-community,robovm/robovm-studio,MichaelNedzelsky/intellij-community,pwoodworth/intellij-community,ol-loginov/intellij-community,ahb0327/intellij-community,orekyuu/intellij-community,ryano144/intellij-community,apixandru/intellij-community,da1z/intellij-community,ryano144/intellij-community,supersven/intellij-community,retomerz/intellij-community,petteyg/intellij-community,amith01994/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,kdwink/intellij-community,youdonghai/intellij-community,ahb0327/intellij-community,signed/intellij-community,Distrotech/intellij-community,supersven/intellij-community,Lekanich/intellij-community,orekyuu/intellij-community,izonder/intellij-community,slisson/intellij-community,hurricup/intellij-community,MichaelNedzelsky/intellij-community,supersven/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,izonder/intellij-community,fnouama/intellij-community,izonder/intellij-community,ol-loginov/intellij-community,dslomov/intellij-community,mglukhikh/intellij-community,vladmm/intellij-community,michaelgallacher/intellij-community,idea4bsd/idea4bsd,clumsy/intellij-community,michaelgallacher/intellij-community,fengbaicanhe/intellij-community,caot/intellij-community,kdwink/intellij-community,muntasirsyed/intellij-community,Distrotech/intellij-community,Distrotech/intellij-community,vladmm/intellij-community,retomerz/intellij-community,supersven/intellij-community,mglukhikh/intellij-community,Lekanich/intellij-community,MichaelNedzelsky/intellij-community,gnuhub/intellij-community,apixandru/intellij-community,semonte/intellij-community,Lekanich/intellij-community,idea4bsd/idea4bsd,fengbaicanhe/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,samthor/intellij-community,holmes/intellij-community,vvv1559/intellij-community,ivan-fedorov/intellij-community,vladmm/intellij-community,muntasirsyed/intellij-community,TangHao1987/intellij-community,michaelgallacher/intellij-community,MER-GROUP/intellij-community,tmpgit/intellij-community,vladmm/intellij-community,kdwink/intellij-community,signed/intellij-community,nicolargo/intellij-community,ivan-fedorov/intellij-community,hurricup/intellij-community,ibinti/intellij-community,hurricup/intellij-community,Distrotech/intellij-community,diorcety/intellij-community,youdonghai/intellij-community,akosyakov/intellij-community,signed/intellij-community,wreckJ/intellij-community,fnouama/intellij-community,blademainer/intellij-community,FHannes/intellij-community,wreckJ/intellij-community,youdonghai/intellij-community,izonder/intellij-community,ahb0327/intellij-community,retomerz/intellij-community,apixandru/intellij-community,kool79/intellij-community,amith01994/intellij-community,jagguli/intellij-community,alphafoobar/intellij-community,retomerz/intellij-community,robovm/robovm-studio,tmpgit/intellij-community,fengbaicanhe/intellij-community,ThiagoGarciaAlves/intellij-community,SerCeMan/intellij-community,ftomassetti/intellij-community,orekyuu/intellij-community,da1z/intellij-community,retomerz/intellij-community,hurricup/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,kool79/intellij-community,Lekanich/intellij-community,da1z/intellij-community,asedunov/intellij-community,signed/intellij-community,Lekanich/intellij-community,pwoodworth/intellij-community,SerCeMan/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,robovm/robovm-studio,jagguli/intellij-community,suncycheng/intellij-community,orekyuu/intellij-community,holmes/intellij-community,fitermay/intellij-community,semonte/intellij-community,apixandru/intellij-community,Lekanich/intellij-community,SerCeMan/intellij-community,samthor/intellij-community,asedunov/intellij-community,FHannes/intellij-community,apixandru/intellij-community,ol-loginov/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,Distrotech/intellij-community,fengbaicanhe/intellij-community,akosyakov/intellij-community,izonder/intellij-community,nicolargo/intellij-community,signed/intellij-community,suncycheng/intellij-community,tmpgit/intellij-community,samthor/intellij-community,idea4bsd/idea4bsd,dslomov/intellij-community,fitermay/intellij-community,SerCeMan/intellij-community,asedunov/intellij-community,allotria/intellij-community,clumsy/intellij-community,alphafoobar/intellij-community,ThiagoGarciaAlves/intellij-community,pwoodworth/intellij-community,dslomov/intellij-community,kool79/intellij-community,nicolargo/intellij-community,kdwink/intellij-community,kdwink/intellij-community,izonder/intellij-community,adedayo/intellij-community,robovm/robovm-studio,tmpgit/intellij-community,MER-GROUP/intellij-community,ivan-fedorov/intellij-community,wreckJ/intellij-community,nicolargo/intellij-community,lucafavatella/intellij-community,ftomassetti/intellij-community,allotria/intellij-community,MER-GROUP/intellij-community,robovm/robovm-studio,Lekanich/intellij-community,TangHao1987/intellij-community,samthor/intellij-community,asedunov/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,supersven/intellij-community,fengbaicanhe/intellij-community,salguarnieri/intellij-community,MichaelNedzelsky/intellij-community,semonte/intellij-community,MichaelNedzelsky/intellij-community,xfournet/intellij-community,holmes/intellij-community,vladmm/intellij-community,ahb0327/intellij-community,akosyakov/intellij-community,vvv1559/intellij-community,kool79/intellij-community,blademainer/intellij-community,salguarnieri/intellij-community,clumsy/intellij-community,Lekanich/intellij-community,supersven/intellij-community,akosyakov/intellij-community,dslomov/intellij-community,retomerz/intellij-community,ibinti/intellij-community,diorcety/intellij-community,vvv1559/intellij-community,wreckJ/intellij-community,asedunov/intellij-community,muntasirsyed/intellij-community,ftomassetti/intellij-community,orekyuu/intellij-community,supersven/intellij-community,holmes/intellij-community,dslomov/intellij-community,ol-loginov/intellij-community,gnuhub/intellij-community,kdwink/intellij-community,samthor/intellij-community,supersven/intellij-community,pwoodworth/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,samthor/intellij-community,da1z/intellij-community,gnuhub/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,MER-GROUP/intellij-community,amith01994/intellij-community,FHannes/intellij-community,TangHao1987/intellij-community,slisson/intellij-community,kool79/intellij-community,kool79/intellij-community,alphafoobar/intellij-community,diorcety/intellij-community,fnouama/intellij-community,holmes/intellij-community,tmpgit/intellij-community,xfournet/intellij-community,blademainer/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,diorcety/intellij-community,ivan-fedorov/intellij-community,gnuhub/intellij-community,youdonghai/intellij-community,ivan-fedorov/intellij-community,tmpgit/intellij-community,blademainer/intellij-community,jagguli/intellij-community,petteyg/intellij-community,caot/intellij-community,caot/intellij-community,muntasirsyed/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,lucafavatella/intellij-community,blademainer/intellij-community | package org.jetbrains.io;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.util.Consumer;
import com.intellij.util.containers.ContainerUtil;
import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.*;
import org.jboss.netty.channel.group.ChannelGroup;
import org.jboss.netty.channel.group.DefaultChannelGroup;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import org.jboss.netty.handler.codec.http.*;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.List;
import java.util.concurrent.Executor;
import static org.jboss.netty.channel.Channels.pipeline;
import static org.jboss.netty.handler.codec.http.HttpResponseStatus.NOT_FOUND;
import static org.jboss.netty.handler.codec.http.HttpVersion.HTTP_1_1;
public class WebServer {
private final NioServerSocketChannelFactory channelFactory;
private final List<ChannelFutureListener> closingListeners = ContainerUtil.createEmptyCOWList();
private final ChannelGroup openChannels = new DefaultChannelGroup("web-server");
private static final Logger LOG = Logger.getInstance(WebServer.class);
@NonNls
private static final String PROPERTY_ONLY_ANY_HOST = "rpc.onlyAnyHost";
public WebServer() {
final Application application = ApplicationManager.getApplication();
final Executor pooledThreadExecutor = new Executor() {
@Override
public void execute(@NotNull Runnable command) {
application.executeOnPooledThread(command);
}
};
channelFactory = new NioServerSocketChannelFactory(pooledThreadExecutor, pooledThreadExecutor, 2);
}
public boolean isRunning() {
return !openChannels.isEmpty();
}
public void start(int port, Consumer<ChannelPipeline>... pipelineConsumers) {
start(port, new Computable.PredefinedValueComputable<Consumer<ChannelPipeline>[]>(pipelineConsumers));
}
public void start(int port, int portsCount, Consumer<ChannelPipeline>... pipelineConsumers) {
start(port, portsCount, false, new Computable.PredefinedValueComputable<Consumer<ChannelPipeline>[]>(pipelineConsumers));
}
public void start(int port, Computable<Consumer<ChannelPipeline>[]> pipelineConsumers) {
start(port, 1, false, pipelineConsumers);
}
public int start(int firstPort, int portsCount, boolean tryAnyPort, Computable<Consumer<ChannelPipeline>[]> pipelineConsumers) {
if (isRunning()) {
throw new IllegalStateException("server already started");
}
ServerBootstrap bootstrap = new ServerBootstrap(channelFactory);
bootstrap.setOption("child.tcpNoDelay", true);
bootstrap.setPipelineFactory(new ChannelPipelineFactoryImpl(pipelineConsumers, new DefaultHandler(openChannels)));
return bind(firstPort, portsCount, tryAnyPort, bootstrap);
}
// IDEA-91436 idea <121 binds to 127.0.0.1, but >=121 must be available not only from localhost
// but if we bind only to any local port (0.0.0.0), instance of idea <121 can bind to our ports and any request to us will be intercepted
// so, we bind to 127.0.0.1 and 0.0.0.0
private int bind(int firstPort, int portsCount, boolean tryAnyPort, ServerBootstrap bootstrap) {
String property = System.getProperty(PROPERTY_ONLY_ANY_HOST);
boolean onlyAnyHost = property == null ? SystemInfo.isLinux || SystemInfo.isWindowsXP : (property.isEmpty() || Boolean.valueOf(property));
for (int i = 0; i < portsCount; i++) {
int port = firstPort + i;
try {
openChannels.add(bootstrap.bind(new InetSocketAddress(port)));
if (!onlyAnyHost) {
openChannels.add(bootstrap.bind(new InetSocketAddress(InetAddress.getByName("127.0.0.1"), port)));
}
return port;
}
catch (ChannelException e) {
if (!openChannels.isEmpty()) {
openChannels.close();
openChannels.clear();
}
if (portsCount == 1) {
throw e;
}
else if (!tryAnyPort && i == (portsCount - 1)) {
LOG.error(e);
}
}
catch (UnknownHostException e) {
LOG.error(e);
}
}
if (tryAnyPort) {
try {
Channel channel = bootstrap.bind(new InetSocketAddress(0));
openChannels.add(channel);
return ((InetSocketAddress)channel.getLocalAddress()).getPort();
}
catch (ChannelException e) {
LOG.error(e);
}
}
return -1;
}
public void stop() {
try {
for (ChannelFutureListener listener : closingListeners) {
try {
listener.operationComplete(null);
}
catch (Exception e) {
LOG.error(e);
}
}
}
finally {
try {
openChannels.close().awaitUninterruptibly();
}
finally {
channelFactory.releaseExternalResources();
}
}
}
public void addClosingListener(ChannelFutureListener listener) {
closingListeners.add(listener);
}
public Runnable createShutdownTask() {
return new Runnable() {
@Override
public void run() {
if (isRunning()) {
stop();
}
}
};
}
public void addShutdownHook() {
Runtime.getRuntime().addShutdownHook(new Thread(createShutdownTask()));
}
public static void removePluggableHandlers(ChannelPipeline pipeline) {
for (String name : pipeline.getNames()) {
if (name.startsWith("pluggable_")) {
pipeline.remove(name);
}
}
}
private static class ChannelPipelineFactoryImpl implements ChannelPipelineFactory {
private final Computable<Consumer<ChannelPipeline>[]> pipelineConsumers;
private final DefaultHandler defaultHandler;
public ChannelPipelineFactoryImpl(Computable<Consumer<ChannelPipeline>[]> pipelineConsumers, DefaultHandler defaultHandler) {
this.pipelineConsumers = pipelineConsumers;
this.defaultHandler = defaultHandler;
}
@Override
public ChannelPipeline getPipeline() throws Exception {
ChannelPipeline pipeline = pipeline(new HttpRequestDecoder(), new HttpChunkAggregator(1048576), new HttpResponseEncoder());
for (Consumer<ChannelPipeline> consumer : pipelineConsumers.compute()) {
try {
consumer.consume(pipeline);
}
catch (Throwable e) {
LOG.error(e);
}
}
pipeline.addLast("defaultHandler", defaultHandler);
return pipeline;
}
}
@ChannelHandler.Sharable
private static class DefaultHandler extends SimpleChannelUpstreamHandler {
private final ChannelGroup openChannels;
public DefaultHandler(ChannelGroup openChannels) {
this.openChannels = openChannels;
}
@Override
public void channelOpen(ChannelHandlerContext context, ChannelStateEvent e) {
openChannels.add(e.getChannel());
}
@Override
public void messageReceived(ChannelHandlerContext context, MessageEvent e) throws Exception {
if (e.getMessage() instanceof HttpRequest) {
HttpResponse response = new DefaultHttpResponse(HTTP_1_1, NOT_FOUND);
context.getChannel().write(response).addListener(ChannelFutureListener.CLOSE);
}
}
}
}
| platform/platform-impl/src/org/jetbrains/io/WebServer.java | package org.jetbrains.io;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.util.Consumer;
import com.intellij.util.containers.ContainerUtil;
import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.*;
import org.jboss.netty.channel.group.ChannelGroup;
import org.jboss.netty.channel.group.DefaultChannelGroup;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import org.jboss.netty.handler.codec.http.*;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.List;
import java.util.concurrent.Executor;
import static org.jboss.netty.channel.Channels.pipeline;
import static org.jboss.netty.handler.codec.http.HttpResponseStatus.NOT_FOUND;
import static org.jboss.netty.handler.codec.http.HttpVersion.HTTP_1_1;
public class WebServer {
private final NioServerSocketChannelFactory channelFactory;
private final List<ChannelFutureListener> closingListeners = ContainerUtil.createEmptyCOWList();
private final ChannelGroup openChannels = new DefaultChannelGroup("web-server");
private static final Logger LOG = Logger.getInstance(WebServer.class);
@NonNls
private static final String PROPERTY_ONLY_ANY_HOST = "rpc.onlyAnyHost";
public WebServer() {
final Application application = ApplicationManager.getApplication();
final Executor pooledThreadExecutor = new Executor() {
@Override
public void execute(@NotNull Runnable command) {
application.executeOnPooledThread(command);
}
};
channelFactory = new NioServerSocketChannelFactory(pooledThreadExecutor, pooledThreadExecutor, 2);
}
public boolean isRunning() {
return !openChannels.isEmpty();
}
public void start(int port, Consumer<ChannelPipeline>... pipelineConsumers) {
start(port, new Computable.PredefinedValueComputable<Consumer<ChannelPipeline>[]>(pipelineConsumers));
}
public void start(int port, int portsCount, Consumer<ChannelPipeline>... pipelineConsumers) {
start(port, portsCount, false, new Computable.PredefinedValueComputable<Consumer<ChannelPipeline>[]>(pipelineConsumers));
}
public void start(int port, Computable<Consumer<ChannelPipeline>[]> pipelineConsumers) {
start(port, 1, false, pipelineConsumers);
}
public int start(int firstPort, int portsCount, boolean tryAnyPort, Computable<Consumer<ChannelPipeline>[]> pipelineConsumers) {
if (isRunning()) {
throw new IllegalStateException("server already started");
}
ServerBootstrap bootstrap = new ServerBootstrap(channelFactory);
bootstrap.setOption("child.tcpNoDelay", true);
bootstrap.setPipelineFactory(new ChannelPipelineFactoryImpl(pipelineConsumers, new DefaultHandler(openChannels)));
return bind(firstPort, portsCount, tryAnyPort, bootstrap);
}
// IDEA-91436 idea <121 binds to 127.0.0.1, but >=121 must be available not only from localhost
// but if we bind only to any local port (0.0.0.0), instance of idea <121 can bind to our ports and any request to us will be intercepted
// so, we bind to 127.0.0.1 and 0.0.0.0
private int bind(int firstPort, int portsCount, boolean tryAnyPort, ServerBootstrap bootstrap) {
String property = System.getProperty(PROPERTY_ONLY_ANY_HOST);
boolean onlyAnyHost = property == null ? SystemInfo.isLinux : (property.isEmpty() || Boolean.valueOf(property));
for (int i = 0; i < portsCount; i++) {
int port = firstPort + i;
try {
openChannels.add(bootstrap.bind(new InetSocketAddress(port)));
if (!onlyAnyHost) {
openChannels.add(bootstrap.bind(new InetSocketAddress(InetAddress.getByName("127.0.0.1"), port)));
}
return port;
}
catch (ChannelException e) {
if (!openChannels.isEmpty()) {
openChannels.close();
openChannels.clear();
}
if (portsCount == 1) {
throw e;
}
else if (!tryAnyPort && i == (portsCount - 1)) {
LOG.error(e);
}
}
catch (UnknownHostException e) {
LOG.error(e);
}
}
if (tryAnyPort) {
try {
Channel channel = bootstrap.bind(new InetSocketAddress(0));
openChannels.add(channel);
return ((InetSocketAddress)channel.getLocalAddress()).getPort();
}
catch (ChannelException e) {
LOG.error(e);
}
}
return -1;
}
public void stop() {
try {
for (ChannelFutureListener listener : closingListeners) {
try {
listener.operationComplete(null);
}
catch (Exception e) {
LOG.error(e);
}
}
}
finally {
try {
openChannels.close().awaitUninterruptibly();
}
finally {
channelFactory.releaseExternalResources();
}
}
}
public void addClosingListener(ChannelFutureListener listener) {
closingListeners.add(listener);
}
public Runnable createShutdownTask() {
return new Runnable() {
@Override
public void run() {
if (isRunning()) {
stop();
}
}
};
}
public void addShutdownHook() {
Runtime.getRuntime().addShutdownHook(new Thread(createShutdownTask()));
}
public static void removePluggableHandlers(ChannelPipeline pipeline) {
for (String name : pipeline.getNames()) {
if (name.startsWith("pluggable_")) {
pipeline.remove(name);
}
}
}
private static class ChannelPipelineFactoryImpl implements ChannelPipelineFactory {
private final Computable<Consumer<ChannelPipeline>[]> pipelineConsumers;
private final DefaultHandler defaultHandler;
public ChannelPipelineFactoryImpl(Computable<Consumer<ChannelPipeline>[]> pipelineConsumers, DefaultHandler defaultHandler) {
this.pipelineConsumers = pipelineConsumers;
this.defaultHandler = defaultHandler;
}
@Override
public ChannelPipeline getPipeline() throws Exception {
ChannelPipeline pipeline = pipeline(new HttpRequestDecoder(), new HttpChunkAggregator(1048576), new HttpResponseEncoder());
for (Consumer<ChannelPipeline> consumer : pipelineConsumers.compute()) {
try {
consumer.consume(pipeline);
}
catch (Throwable e) {
LOG.error(e);
}
}
pipeline.addLast("defaultHandler", defaultHandler);
return pipeline;
}
}
@ChannelHandler.Sharable
private static class DefaultHandler extends SimpleChannelUpstreamHandler {
private final ChannelGroup openChannels;
public DefaultHandler(ChannelGroup openChannels) {
this.openChannels = openChannels;
}
@Override
public void channelOpen(ChannelHandlerContext context, ChannelStateEvent e) {
openChannels.add(e.getChannel());
}
@Override
public void messageReceived(ChannelHandlerContext context, MessageEvent e) throws Exception {
if (e.getMessage() instanceof HttpRequest) {
HttpResponse response = new DefaultHttpResponse(HTTP_1_1, NOT_FOUND);
context.getChannel().write(response).addListener(ChannelFutureListener.CLOSE);
}
}
}
}
| IDEA-91436 win xp
| platform/platform-impl/src/org/jetbrains/io/WebServer.java | IDEA-91436 win xp | <ide><path>latform/platform-impl/src/org/jetbrains/io/WebServer.java
<ide> // so, we bind to 127.0.0.1 and 0.0.0.0
<ide> private int bind(int firstPort, int portsCount, boolean tryAnyPort, ServerBootstrap bootstrap) {
<ide> String property = System.getProperty(PROPERTY_ONLY_ANY_HOST);
<del> boolean onlyAnyHost = property == null ? SystemInfo.isLinux : (property.isEmpty() || Boolean.valueOf(property));
<add> boolean onlyAnyHost = property == null ? SystemInfo.isLinux || SystemInfo.isWindowsXP : (property.isEmpty() || Boolean.valueOf(property));
<ide> for (int i = 0; i < portsCount; i++) {
<ide> int port = firstPort + i;
<ide> try { |
|
JavaScript | mit | 37892d7ba62f973cb448c8dd2290ad12df59f005 | 0 | 3mpire/Seattle-Real-Time-Fire-911 | // Incident object definition.
function Incident(incidentData) {
this.ID = incidentData.incident_number;
this.Address = incidentData.address;
this.Category = incidentData.type;
this.DateLogged = incidentData.datetime ;
this.Lat = incidentData.report_location.latitude;
this.Lng = incidentData.report_location.longitude;
this.Highlight = true;
};
// Incident Manager.
// Data storage.
var Storage = {
Set: function (key, value) {
localStorage.setItem(key, JSON.stringify(value));
},
Get: function (key) {
if (localStorage.getItem(key) === null) {
this.Set(key, []);
}
return JSON.parse(localStorage.getItem(key));
}
};
var log = {
Config: {
SecondsTillRefresh: 300,
BaseUri: 'https://data.seattle.gov/resource/kzjm-xkqj.json',
IncidentsKey: 'incidents'
},
RefreshData: function(newest) {
var dataSource = log.GetDataSource(newest);
var spinner = $('#spinner');
$.ajax({
type : "GET",
dataType : "JSON",
url : dataSource,
timeout: 10000,
beforeSend: function () {
spinner.text('Fetching data...');
spinner.slideDown('slow');
},
success: function(result) {
var incidents = Storage.Get(log.Config.IncidentsKey);
for (var o = 0; o < incidents.length; o++) {
// Toggle all existing incident Highlight flags to false.
incidents[o].Highlight = false;
}
// Process the result.
$.each( result, function( i, incidentData ) {
var thisIncident = new Incident(incidentData);
// Only push if there is not an object in the array with a matching IncidentID.
if (!isIncidentLogged(thisIncident))
{
incidents.push(thisIncident);
}
});
// Order array chronologically and put back into localStorage.
Storage.Set(log.Config.IncidentsKey, log.SortData(incidents));
// Reset timer if not returning historical data and new data was found.
if (newest && result.length > 0 || log.Config.SecondsTillRefresh < 1) {
log.Config.SecondsTillRefresh = 300;
}
},
error: function(xhr, status, error) {
spinner.text('Error retrieving data.');
console.log(status + ': ' + error);
}
}).complete(function(){
spinner.slideUp('slow');
log.RefreshTable();
});
},
SortData: function(data) {
// Reference: http://www.stoimen.com/blog/2010/07/09/friday-algorithms-javascript-bubble-sort/
if (data.length > 0 || data != undefined) {
var swapped;
do {
swapped = false;
for (var i = 0; i < data.length - 1; i++) {
if (data[i].DateLogged < data[i + 1].DateLogged) {
var temp = data[i];
data[i] = data[i+1];
data[i+1] = temp;
swapped = true;
}
}
} while (swapped);
}
return data;
},
SortCategories: function(categories, alphabetically) {
if (alphabetically) {
return categories.sort();
}
else {
// Reference... bro: http://davidwalsh.name/array-sort
return categories.sort(function(a, b) {
return b.count - a.count;
});
}
},
RefreshTable: function () {
var tableData = [];
//incidents = getIncidents();
incidents = Storage.Get(this.Config.IncidentsKey);
for (var i = 0; i < incidents.length; i++) {
var thisIncident = incidents[i];
var cssClass;
if (thisIncident.Highlight == true) {
cssClass = ' class="incident-row highlight"';
} else {
cssClass = ' class="incident-row"';
}
tableData.push('<tr data-toggle="modal" data-target="#incident-modal" id="' + thisIncident.ID + '""' + cssClass + '><td>' + thisIncident.ID + '</td><td>' + thisIncident.Category + '</td><td>' + thisIncident.Address + '</td><td>' + getUserFriendlyDateTime(thisIncident.DateLogged) + '</td></tr>');
}
$('#row-count').text('Incidents: ' + tableData.length);
//First remove existing rows.
$("#log").find('tr:gt(0)').remove();
//Next append new data.
$("#log").append(tableData.join(''));
log.RefreshSummary();
},
RefreshSummary: function() {
var categories = [], i;
var data = Storage.Get(this.Config.IncidentsKey);
// Display the time range represented by the current dataset.
var incidentRange = $('#incident-range');
var newest = data[0];
var oldest = data[data.length - 1];
incidentRange.text(getUserFriendlyDateTime(newest.DateLogged) + ' - ' + getUserFriendlyDateTime(oldest.DateLogged));
// Get a distinct list of categories from the current dataset.
for (i = 0; i < data.length; i++) {
var found = false;
for (var c = 0; c < categories.length; c++) {
if (categories[c].name == data[i].Category) {
found = true;
}
}
if (found == false) {
category = { name: data[i].Category, count: getIncidentCountByCategory(data[i].Category)};
categories.push(category);
}
}
if (categories.length > 0) {
// Sort the categories alphabetically.
categories = log.SortCategories(categories, false)
var htmlList = '<h1>Categories</h1><ul>';
for (i = 0; i < categories.length; i++) {
htmlList = htmlList + '<li>' + categories[i].name + '<span class=\'count\'>' + categories[i].count + '</span></li>';
}
htmlList = htmlList + '</ul>';
$('#incident-type-summary').html(htmlList);
}
},
GetIncident: function(incidentId) {
var incidents = Storage.Get(this.Config.IncidentsKey);
if (incidents.length > 0) {
for (var i = 0; i < incidents.length; i++) {
if (incidents[i].ID == incidentId) {
return incidents[i];
}
}
}
return null;
},
GetMap: function(lat, lng, incidentId) {
var incidentLatLng = new google.maps.LatLng(lat,lng);
var mapOptions = {
center: incidentLatLng,
zoom: 16
};
window.map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
// Add Marker.
var marker = new google.maps.Marker({
position: incidentLatLng,
animation: google.maps.Animation.DROP,
map: map,
title:("#" + incidentId)
});
// Add InfoWindow.
marker.info = new google.maps.InfoWindow({
content: '<b>Incident:</b> ' + incidentId
});
google.maps.event.addListener(marker, 'click', function() {
marker.info.open(map, marker);
});
// Invert colors.
// Reference: https://developers.google.com/maps/documentation/javascript/styling
var styles = [
{
"stylers": [
{ "invert_lightness": true }
]
}
];
map.setOptions({styles: styles});
},
GetDataSource: function(newest) {
var incidents = Storage.Get(this.Config.IncidentsKey);
if (incidents.length === 0) {
// Get current time in miliseconds since the epoch.
var currentTime = new Date().getTime();
// Convert to seconds.
currentTime = (currentTime / 1000);
// Subtract the number of seconds in 24 hours.
currentTime = Math.floor(currentTime - (60 * 60 * 24));
// Convert to ISO-8601 string.
var dayAgo = new Date(currentTime * 1000).toISOString();
return log.BaseUri + "?$where=datetime>'" + dayAgo + '\'';
}
else
{
var incident, dateLogged;
if (newest) {
incident = getNewestIncident();
dateLogged = new Date(incident.DateLogged * 1000).toISOString();
return log.Config.BaseUri + "?$where=datetime>'" + dateLogged + '\'';
}
else {
incident = getOldestIncident();
dateLogged = new Date(incident.DateLogged * 1000).toISOString();
return log.Config.BaseUri + "?$where=datetime<'" + dateLogged + '\'&$limit=50&$order=datetime desc';
}
}
}
};
// Checks to see if an incident already exists in the array matching on ID.
function isIncidentLogged(incident) {
var incidents = Storage.Get(log.Config.IncidentsKey);
for (var i = 0; i < incidents.length; i++)
{
if (incidents[i].ID == incident.ID)
{
// TODO: Should I compare to see if any of the properties have changed?
return true;
}
}
return false;
}
// Returns the most recently logged incident.
function getNewestIncident() {
var newest, data = Storage.Get(log.Config.IncidentsKey), i;
for (i = 0; i < data.length; i++)
{
if (newest === undefined) {
newest = data[i];
}
if (newest.DateLogged < data[i].DateLogged) {
newest = data[i];
}
}
return newest;
}
// Returns the earliest logged incident.
function getOldestIncident() {
var oldest, data = Storage.Get(log.Config.IncidentsKey), i;
for (i = 0; i < data.length; i++) {
if (oldest === undefined) {
oldest = data[i];
}
if (oldest.DateLogged > data[i].DateLogged) {
oldest = data[i];
}
}
return oldest;
}
// Returns the number of incidents in a single category.
function getIncidentCountByCategory(category) {
var count = 0, data = Storage.Get(log.Config.IncidentsKey), i;
for (i = 0; i < data.length; i++) {
if (data[i].Category == category) {
count++;
}
}
return count;
}
// Returns a user-friendly date/time string {00:00:00 XX MM/DD/YYYY}.
function getUserFriendlyDateTime(date) {
var friendlyDate = new Date(date * 1000);
return friendlyDate.toLocaleTimeString() + ' ' + friendlyDate.toLocaleDateString();
} | js/log.js | // Incident object definition.
function Incident(incidentData) {
this.ID = incidentData.incident_number;
this.Address = incidentData.address;
this.Category = incidentData.type;
this.DateLogged = incidentData.datetime ;
this.Lat = incidentData.report_location.latitude;
this.Lng = incidentData.report_location.longitude;
this.Highlight = true;
};
// Incident Manager.
// Data storage.
var Storage = {
Set: function (key, value) {
localStorage.setItem(key, JSON.stringify(value));
},
Get: function (key) {
if (localStorage.getItem(key) === null) {
this.Set(key, []);
}
return JSON.parse(localStorage.getItem(key));
}
};
var log = {
Config: {
SecondsTillRefresh: 300,
BaseUri: 'https://data.seattle.gov/resource/kzjm-xkqj.json',
IncidentsKey: 'incidents'
},
RefreshData: function(newest) {
var dataSource = log.GetDataSource(newest);
var spinner = $('#spinner');
$.ajax({
type : "GET",
dataType : "JSON",
url : dataSource,
timeout: 10000,
beforeSend: function () {
spinner.text('Fetching data...');
spinner.slideDown('slow');
},
success: function(result) {
var incidents = Storage.Get(log.Config.IncidentsKey);
for (var o = 0; o < incidents.length; o++) {
// Toggle all existing incident Highlight flags to false.
incidents[o].Highlight = false;
}
// Process the result.
$.each( result, function( i, incidentData ) {
var thisIncident = new Incident(incidentData);
// Only push if there is not an object in the array with a matching IncidentID.
if (!isIncidentLogged(thisIncident))
{
incidents.push(thisIncident);
}
});
// Order array chronologically and put back into localStorage.
Storage.Set(log.Config.IncidentsKey, log.SortData(incidents));
// Reset timer if not returning historical data and new data was found.
if (newest && result.length > 0 || log.Config.SecondsTillRefresh < 1) {
log.Config.SecondsTillRefresh = 300;
}
},
error: function(xhr, status, error) {
spinner.text('Error retrieving data.');
console.log(status + ': ' + error);
}
}).complete(function(){
spinner.slideUp('slow');
log.RefreshTable();
});
},
SortData: function(data) {
// Reference: http://www.stoimen.com/blog/2010/07/09/friday-algorithms-javascript-bubble-sort/
if (data.length > 0 || data != undefined) {
var swapped;
do {
swapped = false;
for (var i = 0; i < data.length - 1; i++) {
if (data[i].DateLogged < data[i + 1].DateLogged) {
var temp = data[i];
data[i] = data[i+1];
data[i+1] = temp;
swapped = true;
}
}
} while (swapped);
}
return data;
},
SortCategories: function(categories, alphabetically) {
if (alphabetically) {
return categories.sort();
}
else {
// Reference... bro: http://davidwalsh.name/array-sort
return categories.sort(function(a, b) {
return b.count - a.count;
});
}
},
RefreshTable: function () {
var tableData = [];
//incidents = getIncidents();
incidents = Storage.Get(this.Config.IncidentsKey);
for (var i = 0; i < incidents.length; i++) {
var thisIncident = incidents[i];
var cssClass;
// OR condition for testing purposes.
// TODO: remove for production.
if (thisIncident.Highlight == true) {
cssClass = ' class="incident-row highlight"';
} else {
cssClass = ' class="incident-row"';
}
tableData.push('<tr data-toggle="modal" data-target="#incident-modal" id="' + thisIncident.ID + '""' + cssClass + '><td>' + thisIncident.ID + '</td><td>' + thisIncident.Category + '</td><td>' + thisIncident.Address + '</td><td>' + getUserFriendlyDateTime(thisIncident.DateLogged) + '</td></tr>');
}
$('#row-count').text('Incidents: ' + tableData.length);
//First remove existing rows.
$("#log").find('tr:gt(0)').remove();
//Next append new data.
$("#log").append(tableData.join(''));
log.RefreshSummary();
},
RefreshSummary: function() {
var categories = [], i;
var data = Storage.Get(this.Config.IncidentsKey);
// Display the time range represented by the current dataset.
var incidentRange = $('#incident-range');
var newest = data[0];
var oldest = data[data.length - 1];
incidentRange.text(getUserFriendlyDateTime(newest.DateLogged) + ' - ' + getUserFriendlyDateTime(oldest.DateLogged));
// Get a distinct list of categories from the current dataset.
for (i = 0; i < data.length; i++) {
var found = false;
for (var c = 0; c < categories.length; c++) {
if (categories[c].name == data[i].Category) {
found = true;
}
}
if (found == false) {
category = { name: data[i].Category, count: getIncidentCountByCategory(data[i].Category)};
categories.push(category);
}
}
if (categories.length > 0) {
// Sort the categories alphabetically.
categories = log.SortCategories(categories, false)
var htmlList = '<h1>Categories</h1><ul>';
for (i = 0; i < categories.length; i++) {
htmlList = htmlList + '<li>' + categories[i].name + '<span class=\'count\'>' + categories[i].count + '</span></li>';
}
htmlList = htmlList + '</ul>';
$('#incident-type-summary').html(htmlList);
}
},
GetIncident: function(incidentId) {
var incidents = Storage.Get(this.Config.IncidentsKey);
if (incidents.length > 0) {
for (var i = 0; i < incidents.length; i++) {
if (incidents[i].ID == incidentId) {
return incidents[i];
}
}
}
return null;
},
GetMap: function(lat, lng, incidentId) {
var incidentLatLng = new google.maps.LatLng(lat,lng);
var mapOptions = {
center: incidentLatLng,
zoom: 16
};
window.map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
// Add Marker.
var marker = new google.maps.Marker({
position: incidentLatLng,
animation: google.maps.Animation.DROP,
map: map,
title:("#" + incidentId)
});
// Add InfoWindow.
marker.info = new google.maps.InfoWindow({
content: '<b>Incident:</b> ' + incidentId
});
google.maps.event.addListener(marker, 'click', function() {
marker.info.open(map, marker);
});
// Invert colors.
// Reference: https://developers.google.com/maps/documentation/javascript/styling
var styles = [
{
"stylers": [
{ "invert_lightness": true }
]
}
];
map.setOptions({styles: styles});
},
GetDataSource: function(newest) {
var incidents = Storage.Get(this.Config.IncidentsKey);
if (incidents.length === 0) {
// Get current time in miliseconds since the epoch.
var currentTime = new Date().getTime();
// Convert to seconds.
currentTime = (currentTime / 1000);
// Subtract the number of seconds in 24 hours.
currentTime = Math.floor(currentTime - (60 * 60 * 24));
// Convert to ISO-8601 string.
var dayAgo = new Date(currentTime * 1000).toISOString();
return log.BaseUri + "?$where=datetime>'" + dayAgo + '\'';
}
else
{
var incident, dateLogged;
if (newest) {
incident = getNewestIncident();
dateLogged = new Date(incident.DateLogged * 1000).toISOString();
return log.Config.BaseUri + "?$where=datetime>'" + dateLogged + '\'';
}
else {
incident = getOldestIncident();
dateLogged = new Date(incident.DateLogged * 1000).toISOString();
return log.Config.BaseUri + "?$where=datetime<'" + dateLogged + '\'&$limit=50&$order=datetime desc';
}
}
}
};
// Checks to see if an incident already exists in the array matching on ID.
function isIncidentLogged(incident) {
var incidents = Storage.Get(log.Config.IncidentsKey);
for (var i = 0; i < incidents.length; i++)
{
if (incidents[i].ID == incident.ID)
{
// TODO: Should I compare to see if any of the properties have changed?
return true;
}
}
return false;
}
// Returns the most recently logged incident.
function getNewestIncident() {
var newest, data = Storage.Get(log.Config.IncidentsKey), i;
for (i = 0; i < data.length; i++)
{
if (newest === undefined) {
newest = data[i];
}
if (newest.DateLogged < data[i].DateLogged) {
newest = data[i];
}
}
return newest;
}
// Returns the earliest logged incident.
function getOldestIncident() {
var oldest, data = Storage.Get(log.Config.IncidentsKey), i;
for (i = 0; i < data.length; i++) {
if (oldest === undefined) {
oldest = data[i];
}
if (oldest.DateLogged > data[i].DateLogged) {
oldest = data[i];
}
}
return oldest;
}
// Returns the number of incidents in a single category.
function getIncidentCountByCategory(category) {
var count = 0, data = Storage.Get(log.Config.IncidentsKey), i;
for (i = 0; i < data.length; i++) {
if (data[i].Category == category) {
count++;
}
}
return count;
}
// Returns a user-friendly date/time string {00:00:00 XX MM/DD/YYYY}.
function getUserFriendlyDateTime(date) {
var friendlyDate = new Date(date * 1000);
return friendlyDate.toLocaleTimeString() + ' ' + friendlyDate.toLocaleDateString();
} | Remove comments.
| js/log.js | Remove comments. | <ide><path>s/log.js
<ide> var thisIncident = incidents[i];
<ide> var cssClass;
<ide>
<del> // OR condition for testing purposes.
<del> // TODO: remove for production.
<ide> if (thisIncident.Highlight == true) {
<ide> cssClass = ' class="incident-row highlight"';
<ide> } else { |
|
Java | bsd-3-clause | 465580b3fad97638ac0d1a5330d87fbc74782be2 | 0 | NCIP/cananolab,NCIP/cananolab,NCIP/cananolab | package gov.nih.nci.calab.service.search;
import gov.nih.nci.calab.db.DataAccessProxy;
import gov.nih.nci.calab.db.IDataAccess;
import gov.nih.nci.calab.domain.nano.characterization.Characterization;
import gov.nih.nci.calab.domain.nano.particle.Nanoparticle;
import gov.nih.nci.calab.dto.characterization.CharacterizationBean;
import gov.nih.nci.calab.dto.common.UserBean;
import gov.nih.nci.calab.dto.particle.ParticleBean;
import gov.nih.nci.calab.dto.LabFileBean;
import gov.nih.nci.calab.exception.CalabException;
import gov.nih.nci.calab.service.security.UserService;
import gov.nih.nci.calab.service.util.CalabConstants;
import gov.nih.nci.calab.service.util.StringUtils;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.io.File;
import org.apache.log4j.Logger;
/**
* This class includes methods invovled in searching nanoparticles.
*
* @author pansu
*
*/
public class SearchNanoparticleService {
private static Logger logger = Logger
.getLogger(SearchNanoparticleService.class);
/**
* Search for nanoparticles based on particle source, type, function types,
* characterizationType, characterizations, keywords and filter the
* nanoparticles by user visibility.
*
* @param particleSource
* @param particleType
* @param functionTypes
* @param characterizationType
* @param characterizations
* @param keywords
* @param user
* @return
* @throws Exception
*/
public List<ParticleBean> basicSearch(String particleSource,
String particleType, String[] functionTypes,
String[] characterizations, String[] keywords, String keywordType,
UserBean user) throws Exception {
IDataAccess ida = (new DataAccessProxy())
.getInstance(IDataAccess.HIBERNATE);
String[] particleKeywords = null;
String[] assayResultKeywords = null;
if (keywordType.equals("nanoparticle")) {
particleKeywords = keywords;
} else {
assayResultKeywords = keywords;
}
List<ParticleBean> particles = new ArrayList<ParticleBean>();
try {
List<Object> paramList = new ArrayList<Object>();
List<String> whereList = new ArrayList<String>();
String where = "";
String keywordFrom = "";
String functionFrom = "";
String characterizationFrom = "";
if (particleSource != null && particleSource.length() > 0) {
where = "where ";
whereList.add("particle.source.organizationName=? ");
paramList.add(particleSource);
}
if (particleType != null && particleType.length() > 0) {
paramList.add(particleType);
where = "where ";
whereList.add("particle.type=? ");
}
if (functionTypes != null && functionTypes.length > 0) {
List<String> inList = new ArrayList<String>();
where = "where ";
for (String functionType : functionTypes) {
paramList.add(functionType);
inList.add("?");
}
functionFrom = "left join particle.functionCollection function ";
whereList.add("function.type in ("
+ StringUtils.join(inList, ", ") + ") ");
}
if (particleKeywords != null && particleKeywords.length > 0) {
List<String> inList = new ArrayList<String>();
where = "where ";
for (String keyword : particleKeywords) {
paramList.add(keyword);
inList.add("?");
}
keywordFrom = "left join particle.keywordCollection keyword ";
whereList.add("keyword.name in ("
+ StringUtils.join(inList, ", ") + ") ");
}
if (characterizations != null && characterizations.length > 0) {
List<String> inList = new ArrayList<String>();
where = "where ";
for (String characterization : characterizations) {
paramList.add(characterization);
inList.add("?");
}
characterizationFrom = "left join particle.characterizationCollection characterization ";
whereList.add("characterization.name in ("
+ StringUtils.join(inList, ", ") + ") ");
}
String whereStr = StringUtils.join(whereList, " and ");
String hqlString = "select particle from Nanoparticle particle "
+ functionFrom + keywordFrom + characterizationFrom + where
+ whereStr;
ida.open();
List<? extends Object> results = (List<? extends Object>) ida
.searchByParam(hqlString, paramList);
for (Object obj : new HashSet<Object>(results)) {
Nanoparticle particle = (Nanoparticle) obj;
ParticleBean particleBean = new ParticleBean(particle);
particles.add(particleBean);
}
} catch (Exception e) {
logger
.error("Problem finding particles with thet given search parameters ");
throw e;
} finally {
ida.close();
}
UserService userService = new UserService(CalabConstants.CSM_APP_NAME);
List<ParticleBean> filteredParticles = userService
.getFilteredParticles(user, particles);
return filteredParticles;
}
/**
* Query nanoparticle general information such as name, type, keywords and
* visibilities.
*
* @param particleName
* @param particleType
* @return
* @throws Exception
*/
public ParticleBean getGeneralInfo(String particleName, String particleType)
throws Exception {
Nanoparticle particle = null;
IDataAccess ida = (new DataAccessProxy())
.getInstance(IDataAccess.HIBERNATE);
try {
ida.open();
// get the existing particle from database created during sample
// creation
List results = ida
.search("from Nanoparticle as particle left join fetch particle.keywordCollection where particle.name='"
+ particleName
+ "' and particle.type='"
+ particleType + "'");
for (Object obj : results) {
particle = (Nanoparticle) obj;
}
if (particle == null) {
throw new CalabException("No such particle in the database");
}
} catch (Exception e) {
logger.error("Problem finding particle with name: " + particleName);
throw e;
} finally {
ida.close();
}
ParticleBean particleBean = new ParticleBean(particle);
UserService userService = new UserService(CalabConstants.CSM_APP_NAME);
List<String> accessibleGroups = userService.getAccessibleGroups(
particleName, "R");
String[] visibilityGroups = accessibleGroups.toArray(new String[0]);
particleBean.setVisibilityGroups(visibilityGroups);
return particleBean;
}
/**
* Query nanoparticle characterization information such as id, name and identification name
*
* @param particleName
* @param particleType
* @return List of CharacterizationBean
* @throws Exception
*/
public List<CharacterizationBean> getCharacterizationInfo(
String particleName, String particleType) throws Exception {
List<CharacterizationBean> charBeans = new ArrayList<CharacterizationBean>();
IDataAccess ida = (new DataAccessProxy())
.getInstance(IDataAccess.HIBERNATE);
try {
ida.open();
List results = ida
.search("select chara.id, chara.name, chara.identificationName from Nanoparticle particle join particle.characterizationCollection chara where particle.name='"
+ particleName
+ "' and particle.type='"
+ particleType + "'");
for (Object obj : results) {
String charId = ((Object[]) obj)[0].toString();
String charName = (String) (((Object[]) obj)[1]);
String viewTitle = (String) (((Object[]) obj)[2]);
CharacterizationBean charBean = new CharacterizationBean(
charId, charName, viewTitle);
charBeans.add(charBean);
}
} catch (Exception e) {
logger.error("Problem finding characterization info for particle: "
+ particleName);
throw e;
} finally {
ida.close();
}
return charBeans;
}
/**
* internal method to retrieve sample report information
*
* @param particleName
* @param particleType
* @param wCollection - which collection, reportCollection or AssociatedFileCollection
* @return List of LabFileBean
* @throws Exception
*/
private List<LabFileBean> getReport(String particleName, String particleType, String wCollection) throws Exception {
List<LabFileBean> fileBeans = new ArrayList<LabFileBean>();
IDataAccess ida = (new DataAccessProxy())
.getInstance(IDataAccess.HIBERNATE);
try {
ida.open();
List results = ida
.search("select report.id, report.filename, report.path from Nanoparticle particle join particle." + wCollection + " report where particle.name='"
+ particleName
+ "' and particle.type='"
+ particleType + "'");
for (Object obj : results) {
String reportId = ((Object[]) obj)[0].toString();
String fileName = (String) (((Object[]) obj)[1]);
String path = (String) (((Object[]) obj)[2]);
String toolTip = "";
int idx = path.lastIndexOf(File.separator);
if (idx > 0)
toolTip = path.substring(idx+1);
LabFileBean fileBean = new LabFileBean();
fileBean.setId(reportId);
fileBean.setPath(path);
fileBean.setName(fileName);
fileBean.setToolTip(toolTip);
fileBeans.add(fileBean);
}
} catch (Exception e) {
logger.error("Problem finding report info for particle: "
+ particleName);
throw e;
} finally {
ida.close();
}
return fileBeans;
}
/**
* retrieve sample report information including reportCollection and associatedFileCollection
*
* @param particleName
* @param particleType
* @return List of LabFileBean
* @throws Exception
*/
public List<LabFileBean> getReportInfo(
String particleName, String particleType) throws Exception {
List<LabFileBean> fileBeans = new ArrayList<LabFileBean>();
fileBeans.addAll(getReport(particleName, particleType, "reportCollection"));
fileBeans.addAll(getReport(particleName, particleType, "associatedFileCollection"));
return fileBeans;
}
/**
* retrieve characterization information based on id
*
* @param charId
* @return characterization
* @throws Exception
*/
public Characterization getCharacterizationBy(String charId)
throws Exception {
IDataAccess ida = (new DataAccessProxy())
.getInstance(IDataAccess.HIBERNATE);
Characterization aChar=null;
try {
ida.open();
List results = ida
.search(" from Characterization chara left join fetch chara.composingElementCollection left join fetch chara.derivedBioAssayDataCollection where chara.id="
+ charId);
for(Object obj: results) {
aChar=(Characterization)obj;
}
} catch (Exception e) {
logger.error("Problem finding characterization");
throw e;
} finally {
ida.close();
}
return aChar;
}
/**
* Query characterization, datum, condition information based on id
*
* @param charId
* @return characterization
* @throws Exception
*/
public Characterization getCharacterizationAndTableBy(String charId)
throws Exception {
IDataAccess ida = (new DataAccessProxy())
.getInstance(IDataAccess.HIBERNATE);
Characterization aChar=null;
try {
ida.open();
List results = ida
.search(" from Characterization chara left join fetch chara.derivedBioAssayDataCollection assayData" +
" left join fetch assayData.datumCollection datum left join fetch datum.conditionCollection" +
" where chara.id="
+ charId);
for(Object obj: results) {
aChar=(Characterization)obj;
}
} catch (Exception e) {
logger.error("Problem finding characterization");
throw e;
} finally {
ida.close();
}
return aChar;
}
}
| src/gov/nih/nci/calab/service/search/SearchNanoparticleService.java | package gov.nih.nci.calab.service.search;
import gov.nih.nci.calab.db.DataAccessProxy;
import gov.nih.nci.calab.db.IDataAccess;
import gov.nih.nci.calab.domain.nano.characterization.Characterization;
import gov.nih.nci.calab.domain.nano.particle.Nanoparticle;
import gov.nih.nci.calab.dto.characterization.CharacterizationBean;
import gov.nih.nci.calab.dto.common.UserBean;
import gov.nih.nci.calab.dto.particle.ParticleBean;
import gov.nih.nci.calab.exception.CalabException;
import gov.nih.nci.calab.service.security.UserService;
import gov.nih.nci.calab.service.util.CalabConstants;
import gov.nih.nci.calab.service.util.StringUtils;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import org.apache.log4j.Logger;
/**
* This class includes methods invovled in searching nanoparticles.
*
* @author pansu
*
*/
public class SearchNanoparticleService {
private static Logger logger = Logger
.getLogger(SearchNanoparticleService.class);
/**
* Search for nanoparticles based on particle source, type, function types,
* characterizationType, characterizations, keywords and filter the
* nanoparticles by user visibility.
*
* @param particleSource
* @param particleType
* @param functionTypes
* @param characterizationType
* @param characterizations
* @param keywords
* @param user
* @return
* @throws Exception
*/
public List<ParticleBean> basicSearch(String particleSource,
String particleType, String[] functionTypes,
String[] characterizations, String[] keywords, String keywordType,
UserBean user) throws Exception {
IDataAccess ida = (new DataAccessProxy())
.getInstance(IDataAccess.HIBERNATE);
String[] particleKeywords = null;
String[] assayResultKeywords = null;
if (keywordType.equals("nanoparticle")) {
particleKeywords = keywords;
} else {
assayResultKeywords = keywords;
}
List<ParticleBean> particles = new ArrayList<ParticleBean>();
try {
List<Object> paramList = new ArrayList<Object>();
List<String> whereList = new ArrayList<String>();
String where = "";
String keywordFrom = "";
String functionFrom = "";
String characterizationFrom = "";
if (particleSource != null && particleSource.length() > 0) {
where = "where ";
whereList.add("particle.source.organizationName=? ");
paramList.add(particleSource);
}
if (particleType != null && particleType.length() > 0) {
paramList.add(particleType);
where = "where ";
whereList.add("particle.type=? ");
}
if (functionTypes != null && functionTypes.length > 0) {
List<String> inList = new ArrayList<String>();
where = "where ";
for (String functionType : functionTypes) {
paramList.add(functionType);
inList.add("?");
}
functionFrom = "left join particle.functionCollection function ";
whereList.add("function.type in ("
+ StringUtils.join(inList, ", ") + ") ");
}
if (particleKeywords != null && particleKeywords.length > 0) {
List<String> inList = new ArrayList<String>();
where = "where ";
for (String keyword : particleKeywords) {
paramList.add(keyword);
inList.add("?");
}
keywordFrom = "left join particle.keywordCollection keyword ";
whereList.add("keyword.name in ("
+ StringUtils.join(inList, ", ") + ") ");
}
if (characterizations != null && characterizations.length > 0) {
List<String> inList = new ArrayList<String>();
where = "where ";
for (String characterization : characterizations) {
paramList.add(characterization);
inList.add("?");
}
characterizationFrom = "left join particle.characterizationCollection characterization ";
whereList.add("characterization.name in ("
+ StringUtils.join(inList, ", ") + ") ");
}
String whereStr = StringUtils.join(whereList, " and ");
String hqlString = "select particle from Nanoparticle particle "
+ functionFrom + keywordFrom + characterizationFrom + where
+ whereStr;
ida.open();
List<? extends Object> results = (List<? extends Object>) ida
.searchByParam(hqlString, paramList);
for (Object obj : new HashSet<Object>(results)) {
Nanoparticle particle = (Nanoparticle) obj;
ParticleBean particleBean = new ParticleBean(particle);
particles.add(particleBean);
}
} catch (Exception e) {
logger
.error("Problem finding particles with thet given search parameters ");
throw e;
} finally {
ida.close();
}
UserService userService = new UserService(CalabConstants.CSM_APP_NAME);
List<ParticleBean> filteredParticles = userService
.getFilteredParticles(user, particles);
return filteredParticles;
}
/**
* Query nanoparticle general information such as name, type, keywords and
* visibilities.
*
* @param particleName
* @param particleType
* @return
* @throws Exception
*/
public ParticleBean getGeneralInfo(String particleName, String particleType)
throws Exception {
Nanoparticle particle = null;
IDataAccess ida = (new DataAccessProxy())
.getInstance(IDataAccess.HIBERNATE);
try {
ida.open();
// get the existing particle from database created during sample
// creation
List results = ida
.search("from Nanoparticle as particle left join fetch particle.keywordCollection where particle.name='"
+ particleName
+ "' and particle.type='"
+ particleType + "'");
for (Object obj : results) {
particle = (Nanoparticle) obj;
}
if (particle == null) {
throw new CalabException("No such particle in the database");
}
} catch (Exception e) {
logger.error("Problem finding particle with name: " + particleName);
throw e;
} finally {
ida.close();
}
ParticleBean particleBean = new ParticleBean(particle);
UserService userService = new UserService(CalabConstants.CSM_APP_NAME);
List<String> accessibleGroups = userService.getAccessibleGroups(
particleName, "R");
String[] visibilityGroups = accessibleGroups.toArray(new String[0]);
particleBean.setVisibilityGroups(visibilityGroups);
return particleBean;
}
public List<CharacterizationBean> getCharacterizationInfo(
String particleName, String particleType) throws Exception {
List<CharacterizationBean> charBeans = new ArrayList<CharacterizationBean>();
IDataAccess ida = (new DataAccessProxy())
.getInstance(IDataAccess.HIBERNATE);
try {
ida.open();
List results = ida
.search("select chara.id, chara.name, chara.identificationName from Nanoparticle particle join particle.characterizationCollection chara where particle.name='"
+ particleName
+ "' and particle.type='"
+ particleType + "'");
for (Object obj : results) {
String charId = ((Object[]) obj)[0].toString();
String charName = (String) (((Object[]) obj)[1]);
String viewTitle = (String) (((Object[]) obj)[2]);
CharacterizationBean charBean = new CharacterizationBean(
charId, charName, viewTitle);
charBeans.add(charBean);
}
} catch (Exception e) {
logger.error("Problem finding characterization info for particle: "
+ particleName);
throw e;
} finally {
ida.close();
}
return charBeans;
}
public Characterization getCharacterizationBy(String charId)
throws Exception {
IDataAccess ida = (new DataAccessProxy())
.getInstance(IDataAccess.HIBERNATE);
Characterization aChar=null;
try {
ida.open();
List results = ida
.search(" from Characterization chara left join fetch chara.composingElementCollection left join fetch chara.derivedBioAssayDataCollection where chara.id="
+ charId);
for(Object obj: results) {
aChar=(Characterization)obj;
}
} catch (Exception e) {
logger.error("Problem finding characterization");
throw e;
} finally {
ida.close();
}
return aChar;
}
public Characterization getCharacterizationAndTableBy(String charId)
throws Exception {
IDataAccess ida = (new DataAccessProxy())
.getInstance(IDataAccess.HIBERNATE);
Characterization aChar=null;
try {
ida.open();
List results = ida
.search(" from Characterization chara left join fetch chara.derivedBioAssayDataCollection assayData" +
" left join fetch assayData.datumCollection datum left join fetch datum.conditionCollection" +
" where chara.id="
+ charId);
for(Object obj: results) {
aChar=(Characterization)obj;
}
} catch (Exception e) {
logger.error("Problem finding characterization");
throw e;
} finally {
ida.close();
}
return aChar;
}
}
| added getReportInfo method to retrieve report and associated file for a sample.
SVN-Revision: 2226
| src/gov/nih/nci/calab/service/search/SearchNanoparticleService.java | added getReportInfo method to retrieve report and associated file for a sample. | <ide><path>rc/gov/nih/nci/calab/service/search/SearchNanoparticleService.java
<ide> import gov.nih.nci.calab.dto.characterization.CharacterizationBean;
<ide> import gov.nih.nci.calab.dto.common.UserBean;
<ide> import gov.nih.nci.calab.dto.particle.ParticleBean;
<add>import gov.nih.nci.calab.dto.LabFileBean;
<ide> import gov.nih.nci.calab.exception.CalabException;
<ide> import gov.nih.nci.calab.service.security.UserService;
<ide> import gov.nih.nci.calab.service.util.CalabConstants;
<ide> import java.util.ArrayList;
<ide> import java.util.HashSet;
<ide> import java.util.List;
<add>import java.io.File;
<ide>
<ide> import org.apache.log4j.Logger;
<ide>
<ide> return particleBean;
<ide> }
<ide>
<add> /**
<add> * Query nanoparticle characterization information such as id, name and identification name
<add> *
<add> * @param particleName
<add> * @param particleType
<add> * @return List of CharacterizationBean
<add> * @throws Exception
<add> */
<ide> public List<CharacterizationBean> getCharacterizationInfo(
<ide> String particleName, String particleType) throws Exception {
<ide> List<CharacterizationBean> charBeans = new ArrayList<CharacterizationBean>();
<ide> }
<ide> return charBeans;
<ide> }
<del>
<add>
<add> /**
<add> * internal method to retrieve sample report information
<add> *
<add> * @param particleName
<add> * @param particleType
<add> * @param wCollection - which collection, reportCollection or AssociatedFileCollection
<add> * @return List of LabFileBean
<add> * @throws Exception
<add> */
<add> private List<LabFileBean> getReport(String particleName, String particleType, String wCollection) throws Exception {
<add> List<LabFileBean> fileBeans = new ArrayList<LabFileBean>();
<add> IDataAccess ida = (new DataAccessProxy())
<add> .getInstance(IDataAccess.HIBERNATE);
<add>
<add> try {
<add>
<add> ida.open();
<add> List results = ida
<add> .search("select report.id, report.filename, report.path from Nanoparticle particle join particle." + wCollection + " report where particle.name='"
<add> + particleName
<add> + "' and particle.type='"
<add> + particleType + "'");
<add>
<add> for (Object obj : results) {
<add> String reportId = ((Object[]) obj)[0].toString();
<add> String fileName = (String) (((Object[]) obj)[1]);
<add> String path = (String) (((Object[]) obj)[2]);
<add> String toolTip = "";
<add> int idx = path.lastIndexOf(File.separator);
<add> if (idx > 0)
<add> toolTip = path.substring(idx+1);
<add>
<add> LabFileBean fileBean = new LabFileBean();
<add> fileBean.setId(reportId);
<add> fileBean.setPath(path);
<add> fileBean.setName(fileName);
<add> fileBean.setToolTip(toolTip);
<add> fileBeans.add(fileBean);
<add> }
<add> } catch (Exception e) {
<add> logger.error("Problem finding report info for particle: "
<add> + particleName);
<add> throw e;
<add> } finally {
<add> ida.close();
<add> }
<add> return fileBeans;
<add> }
<add>
<add> /**
<add> * retrieve sample report information including reportCollection and associatedFileCollection
<add> *
<add> * @param particleName
<add> * @param particleType
<add> * @return List of LabFileBean
<add> * @throws Exception
<add> */
<add> public List<LabFileBean> getReportInfo(
<add> String particleName, String particleType) throws Exception {
<add> List<LabFileBean> fileBeans = new ArrayList<LabFileBean>();
<add>
<add> fileBeans.addAll(getReport(particleName, particleType, "reportCollection"));
<add> fileBeans.addAll(getReport(particleName, particleType, "associatedFileCollection"));
<add> return fileBeans;
<add> }
<add>
<add> /**
<add> * retrieve characterization information based on id
<add> *
<add> * @param charId
<add> * @return characterization
<add> * @throws Exception
<add> */
<ide> public Characterization getCharacterizationBy(String charId)
<ide> throws Exception {
<ide> IDataAccess ida = (new DataAccessProxy())
<ide> return aChar;
<ide> }
<ide>
<add> /**
<add> * Query characterization, datum, condition information based on id
<add> *
<add> * @param charId
<add> * @return characterization
<add> * @throws Exception
<add> */
<ide> public Characterization getCharacterizationAndTableBy(String charId)
<ide> throws Exception {
<ide> IDataAccess ida = (new DataAccessProxy()) |
|
Java | mit | 971cb189c147fd70ddf71a5e66cd5ad7560c86e8 | 0 | founderio/chaoscrystal | package founderio.chaoscrystal.rendering;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.List;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.Gui;
import net.minecraft.client.renderer.RenderHelper;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.entity.RenderItem;
import net.minecraft.client.renderer.entity.RenderManager;
import net.minecraft.entity.Entity;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.item.ItemMap;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.packet.Packet250CustomPayload;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.EnumMovingObjectType;
import net.minecraft.util.MovingObjectPosition;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.Vec3;
import net.minecraft.world.World;
import net.minecraftforge.client.event.MouseEvent;
import net.minecraftforge.client.event.RenderGameOverlayEvent;
import net.minecraftforge.client.event.RenderGameOverlayEvent.ElementType;
import net.minecraftforge.event.EventPriority;
import net.minecraftforge.event.ForgeSubscribe;
import org.lwjgl.opengl.GL11;
import cpw.mods.fml.common.network.PacketDispatcher;
import founderio.chaoscrystal.ChaosCrystalMain;
import founderio.chaoscrystal.Constants;
import founderio.chaoscrystal.aspects.Node;
import founderio.chaoscrystal.blocks.TileEntityApparatus;
import founderio.chaoscrystal.degradation.Aspects;
import founderio.chaoscrystal.degradation.IAspectStore;
import founderio.chaoscrystal.entities.EntityChaosCrystal;
import founderio.chaoscrystal.entities.EntityFocusBorder;
import founderio.chaoscrystal.entities.EntityFocusFilter;
import founderio.chaoscrystal.entities.EntityFocusTransfer;
public class OverlayAspectSelector extends Gui {
private RenderItem ri;
public OverlayAspectSelector() {
ri = new RenderItem();
ri.setRenderManager(RenderManager.instance);
}
@ForgeSubscribe(priority = EventPriority.NORMAL)
public void onMouseWheel(MouseEvent event) {
if(event.dwheel == 0) {
return;
}
if(!Minecraft.getMinecraft().thePlayer.isSneaking()) {
return;
}
ItemStack currentItem = Minecraft.getMinecraft().thePlayer.inventory.getCurrentItem();
if(currentItem == null) {
return;
}
if(currentItem.itemID == ChaosCrystalMain.itemFocus.itemID && currentItem.getItemDamage() == 2) {
event.setCanceled(true);
int aspectIndex;
NBTTagCompound tags = currentItem.getTagCompound();
if(tags != null) {
String selectedAspect = tags.getString("aspect");
aspectIndex = Aspects.getAspectIndex(selectedAspect);
if(aspectIndex == -1) {
aspectIndex = 0;
}
} else {
tags = new NBTTagCompound();
aspectIndex = 0;
}
if(event.dwheel > 0 && aspectIndex < Aspects.ASPECTS.length - 1) {
aspectIndex++;
}
if(event.dwheel < 0 && aspectIndex > 0) {
aspectIndex--;
}
tags.setString("aspect", Aspects.ASPECTS[aspectIndex]);
currentItem.setTagCompound(tags);
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream(30);
DataOutputStream dos = new DataOutputStream(bos);
dos.writeInt(2);
dos.writeInt(Minecraft.getMinecraft().thePlayer.dimension);
dos.writeUTF(Minecraft.getMinecraft().thePlayer.username);
dos.writeUTF(Aspects.ASPECTS[aspectIndex]);
Packet250CustomPayload degradationPacket = new Packet250CustomPayload();
degradationPacket.channel = Constants.CHANNEL_NAME_OTHER_VISUAL;
degradationPacket.data = bos.toByteArray();
degradationPacket.length = bos.size();
dos.close();
PacketDispatcher.sendPacketToServer(degradationPacket);
} catch (IOException e) {
e.printStackTrace();
}
} else if(currentItem.itemID == ChaosCrystalMain.itemManual.itemID) {
event.setCanceled(true);
if(event.dwheel > 0) {
RenderItemManual.page--;
} else {
RenderItemManual.page++;
}
}
}
public void renderItem(ItemStack is, int x, int y) {
RenderHelper.enableGUIStandardItemLighting();
ri.renderItemAndEffectIntoGUI(Minecraft.getMinecraft().fontRenderer, Minecraft.getMinecraft().renderEngine, is, x, y);
ri.renderItemOverlayIntoGUI(Minecraft.getMinecraft().fontRenderer, Minecraft.getMinecraft().renderEngine, is, x, y);
}
/*
* Copy & modify from Minecraft.getMinecraft().entityRenderer.getMouseOver()
*/
public static MovingObjectPosition getMouseOver(float par1)
{
Entity pointedEntity = null;
Minecraft mc = Minecraft.getMinecraft();
if (mc.renderViewEntity != null && mc.theWorld != null)
{
//mc.pointedEntityLiving = null;
double d0 = (double)mc.playerController.getBlockReachDistance();
MovingObjectPosition mop = mc.renderViewEntity.rayTrace(d0, par1);
double d1 = d0;
Vec3 vec3 = mc.renderViewEntity.getPosition(par1);
if (mc.playerController.extendedReach())
{
d0 = 6.0D;
d1 = 6.0D;
}
else
{
if (d0 > 3.0D)
{
d1 = 3.0D;
}
d0 = d1;
}
if (mop != null)
{
d1 = mop.hitVec.distanceTo(vec3);
}
Vec3 vec31 = mc.renderViewEntity.getLook(par1);
Vec3 vec32 = vec3.addVector(vec31.xCoord * d0, vec31.yCoord * d0, vec31.zCoord * d0);
pointedEntity = null;
float f1 = 1.0F;
@SuppressWarnings("rawtypes")
List list = mc.theWorld.getEntitiesWithinAABBExcludingEntity(mc.renderViewEntity, mc.renderViewEntity.boundingBox.addCoord(vec31.xCoord * d0, vec31.yCoord * d0, vec31.zCoord * d0).expand((double)f1, (double)f1, (double)f1));
double d2 = d1;
for (int i = 0; i < list.size(); ++i)
{
Entity entity = (Entity)list.get(i);
float f2 = entity.getCollisionBorderSize();
AxisAlignedBB axisalignedbb = entity.boundingBox.expand((double)f2, (double)f2, (double)f2);
MovingObjectPosition movingobjectposition = axisalignedbb.calculateIntercept(vec3, vec32);
if (axisalignedbb.isVecInside(vec3))
{
if (0.0D < d2 || d2 == 0.0D)
{
pointedEntity = entity;
d2 = 0.0D;
}
}
else if (movingobjectposition != null)
{
double d3 = vec3.distanceTo(movingobjectposition.hitVec);
if (d3 < d2 || d2 == 0.0D)
{
if (entity == mc.renderViewEntity.ridingEntity && !entity.canRiderInteract())
{
if (d2 == 0.0D)
{
pointedEntity = entity;
}
}
else
{
pointedEntity = entity;
d2 = d3;
}
}
}
}
if (pointedEntity != null && (d2 < d1 || mop == null))
{
mop = new MovingObjectPosition(pointedEntity);
}
return mop;
}
return null;
}
private void renderAspectList(int xPos, int yPos, IAspectStore store) {
int offset = 0;
int colOffset = 0;
final int colWidth = 64;
for(String aspect : Aspects.ASPECTS) {
int asp = store.getAspect(aspect);
Minecraft.getMinecraft().renderEngine.bindTexture(
new ResourceLocation(Constants.MOD_ID + ":" + "textures/hud/aspect_" + aspect + ".png"));
this.drawTexturedModalRectScaled(xPos + 5 + colOffset, yPos + offset + 5, 0, 0, 10, 10, 256, 256);
Minecraft.getMinecraft().fontRenderer.drawString(
Integer.toString(asp),
xPos + 16 + colOffset, yPos + 2 + offset + 5,
16777215);
if(offset >= 30) {
offset = 0;
colOffset += colWidth;
} else {
offset += 10;
}
}
}
private void renderAspectList(int xPos, int yPos, int[] aspectArray) {
int offset = 0;
int colOffset = 0;
final int colWidth = 64;
for(int i = 0; i < aspectArray.length; i++) {
String aspect = Aspects.ASPECTS[i];
int asp = aspectArray[i];
if(asp > 0) {
Minecraft.getMinecraft().renderEngine.bindTexture(new ResourceLocation(Constants.MOD_ID + ":" + "textures/hud/aspect_" + aspect + ".png"));
this.drawTexturedModalRectScaled(xPos + 5 + colOffset, yPos + offset + 5,
0, 0,
10, 10,
256, 256);
Minecraft.getMinecraft().fontRenderer.drawString(
Integer.toString(asp),
xPos + 16 + colOffset, yPos + 2 + offset + 5,
16777215);
if(offset >= 30) {
offset = 0;
colOffset += colWidth;
} else {
offset += 10;
}
}
}
}
@ForgeSubscribe(priority = EventPriority.NORMAL)
public void onRenderHud(RenderGameOverlayEvent event) {
if(event.type != ElementType.CROSSHAIRS) {
return;
}
ItemStack helmet = Minecraft.getMinecraft().thePlayer.inventory.armorInventory[3];
ItemStack currentItem = Minecraft.getMinecraft().thePlayer.inventory.getCurrentItem();
boolean specialSkip = (currentItem != null && currentItem.getItem() instanceof ItemMap) || ChaosCrystalMain.cfgSneakToShowAspects && !Minecraft.getMinecraft().thePlayer.isSneaking();
int centerW = event.resolution.getScaledWidth()/2;
int centerH = event.resolution.getScaledHeight()/2;
GL11.glPushMatrix();
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
GL11.glEnable(GL11.GL_BLEND);
GL11.glDisable(GL11.GL_LIGHTING);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
if(helmet != null && helmet.itemID == ChaosCrystalMain.itemCrystalGlasses.itemID && !specialSkip) {
MovingObjectPosition mop = getMouseOver(0);
if(mop != null) {
Entity lookingAt = mop.entityHit;
if(lookingAt != null) {
if(lookingAt instanceof EntityChaosCrystal) {
EntityChaosCrystal e = (EntityChaosCrystal)lookingAt;
Minecraft.getMinecraft().renderEngine.bindTexture(
new ResourceLocation(Constants.MOD_ID + ":" + "textures/items/chaoscrystal.png"));
this.drawTexturedModalRectScaled(centerW - 16 - 5, centerH + 5, 0, 0, 16, 16, 256, 256);
if(e.isInSuckMode()) {
Minecraft.getMinecraft().renderEngine.bindTexture(
new ResourceLocation(Constants.MOD_ID + ":" + "textures/hud/mode_suck.png"));
} else {
Minecraft.getMinecraft().renderEngine.bindTexture(
new ResourceLocation(Constants.MOD_ID + ":" + "textures/hud/mode_expel.png"));
}
this.drawTexturedModalRectScaled(centerW - 16 - 5, centerH - 16 - 5, 0, 0, 16, 16, 256, 256);
renderAspectList(centerW, centerH, e);
} else if(lookingAt instanceof EntityFocusFilter) {
Minecraft.getMinecraft().renderEngine.bindTexture(
new ResourceLocation(Constants.MOD_ID + ":" + "textures/items/focus_filter.png"));
this.drawTexturedModalRectScaled(centerW - 16 - 5, centerH + 5, 0, 0, 16, 16, 256, 256);
String aspect = ((EntityFocusFilter)lookingAt).getAspect();
Minecraft.getMinecraft().renderEngine.bindTexture(
new ResourceLocation(Constants.MOD_ID + ":" + "textures/hud/aspect_" + aspect + ".png"));
this.drawTexturedModalRectScaled(centerW + 5, centerH + 5, 0, 0, 16, 16, 256, 256);
} else if(lookingAt instanceof EntityFocusBorder) {
Minecraft.getMinecraft().renderEngine.bindTexture(
new ResourceLocation(Constants.MOD_ID + ":" + "textures/items/focus_border.png"));
this.drawTexturedModalRectScaled(centerW - 16 - 5, centerH + 5, 0, 0, 16, 16, 256, 256);
} else if(lookingAt instanceof EntityFocusTransfer) {
Minecraft.getMinecraft().renderEngine.bindTexture(
new ResourceLocation(Constants.MOD_ID + ":" + "textures/items/focus_transfer.png"));
this.drawTexturedModalRectScaled(centerW - 16 - 5, centerH + 5, 0, 0, 16, 16, 256, 256);
} else if(lookingAt instanceof EntityItem) {
ItemStack is = ((EntityItem)lookingAt).getEntityItem();
List<Node> degradations = ChaosCrystalMain.degradationStore.getExtractionsFrom(is);
if(degradations.size() == 0) {
} else {
Node node = degradations.get(0);
renderAspectList(centerW, centerH, node.getAspects());
ItemStack[] parents = node.getDegradedFrom(node.getDispayItemStack());
for(int s = 0; s < parents.length; s++) {
if(parents[s].itemID != 0) {
renderItem(parents[s], centerW + 5 + s*16, centerH - 16 - 5);
}
}
}
renderItem(is, centerW - 16 - 5, centerH - 16 - 5);
}
}
if(mop.typeOfHit == EnumMovingObjectType.TILE) {
World w = Minecraft.getMinecraft().thePlayer.worldObj;
int id = w.getBlockId(
mop.blockX,
mop.blockY,
mop.blockZ);
if(id != 0) {// We can't extract air...
int meta = w.getBlockMetadata(
mop.blockX,
mop.blockY,
mop.blockZ);
boolean doRenderMiniBlock = false;
List<Node> degradations = ChaosCrystalMain.degradationStore.getExtractionsFrom(new ItemStack(id, 1, meta));
if(degradations.size() != 0) {
Node node = degradations.get(0);
doRenderMiniBlock = true;
renderAspectList(centerW, centerH, node.getAspects());
ItemStack[] parents = node.getDegradedFrom(node.getDispayItemStack());
for(int s = 0; s < parents.length; s++) {
if(parents[s].itemID != 0) {
renderItem(parents[s], centerW + 5 + s*16, centerH - 16 - 5);
}
}
}
TileEntity te = w.getBlockTileEntity(mop.blockX,
mop.blockY,
mop.blockZ);
if(te instanceof TileEntityApparatus) {
TileEntityApparatus apparatus = (TileEntityApparatus)te;
doRenderMiniBlock = true;
for(int i = 0; i < apparatus.getSizeInventory(); i++) {
ItemStack its = ((TileEntityApparatus) te).getStackInSlot(i);
if(its != null && its.itemID != 0) {
renderItem(its, centerW - 16 - 5 - 16*i, centerH + 5);
}
}
}
if(doRenderMiniBlock) {
renderItem(new ItemStack(id, 1, meta), centerW - 16 - 5, centerH - 16 - 5);
}
}
}
}
}
if(currentItem != null && currentItem.itemID == ChaosCrystalMain.itemFocus.itemID && currentItem.getItemDamage() == 2) {
String selectedAspect;
int aspectIndex;
NBTTagCompound tags = currentItem.getTagCompound();
if (tags == null) {
selectedAspect = Aspects.ASPECTS[0];
aspectIndex = 0;
} else {
selectedAspect = tags.getString("aspect");
aspectIndex = Aspects.getAspectIndex(selectedAspect);
if (aspectIndex == -1) {
selectedAspect = Aspects.ASPECTS[0];
aspectIndex = 0;
}
}
int bottom = event.resolution.getScaledHeight() - 80;
Minecraft.getMinecraft().renderEngine.bindTexture(new ResourceLocation(Constants.MOD_ID + ":" + "textures/hud/aspect_" + selectedAspect + ".png"));
this.drawTexturedModalRectScaled(centerW - 8, bottom, 0, 0, 16, 16, 256, 256);
GL11.glColor4f(0.4F, 0.4F, 0.4F, 0.4F);
if(aspectIndex > 0) {
Minecraft.getMinecraft().renderEngine.bindTexture(new ResourceLocation(Constants.MOD_ID + ":" + "textures/hud/aspect_" + Aspects.ASPECTS[aspectIndex - 1] + ".png"));
this.drawTexturedModalRectScaled(centerW - 8 - 14 - 2, bottom + 2, 0, 0, 14, 14, 256, 256);
}
if(aspectIndex < Aspects.ASPECTS.length - 1) {
Minecraft.getMinecraft().renderEngine.bindTexture(new ResourceLocation(Constants.MOD_ID + ":" + "textures/hud/aspect_" + Aspects.ASPECTS[aspectIndex + 1] + ".png"));
this.drawTexturedModalRectScaled(centerW - 8 + 14 + 2, bottom + 2, 0, 0, 14, 14, 256, 256);
}
GL11.glColor4f(0.2F, 0.2F, 0.2F, 0.2F);
if(aspectIndex > 1) {
Minecraft.getMinecraft().renderEngine.bindTexture(new ResourceLocation(Constants.MOD_ID + ":" + "textures/hud/aspect_" + Aspects.ASPECTS[aspectIndex - 2] + ".png"));
this.drawTexturedModalRectScaled(centerW - 8 - 26 - 4, bottom + 6, 0, 0, 10, 10, 256, 256);
}
if(aspectIndex < Aspects.ASPECTS.length - 2) {
Minecraft.getMinecraft().renderEngine.bindTexture(new ResourceLocation(Constants.MOD_ID + ":" + "textures/hud/aspect_" + Aspects.ASPECTS[aspectIndex + 2] + ".png"));
this.drawTexturedModalRectScaled(centerW - 8 + 26 + 4, bottom + 6, 0, 0, 10, 10, 256, 256);
}
}
GL11.glPopMatrix();
Minecraft.getMinecraft().renderEngine.bindTexture(Gui.icons);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
GL11.glDisable(GL11.GL_LIGHTING);
GL11.glDisable(GL11.GL_BLEND);
}
/**
* Draws a textured rectangle at the stored z-value. Args: x, y, u, v, width, height, textureWidth, textureHeight
* This uses a separate draw size, not the texture size.
*/
public void drawTexturedModalRectScaled(int x, int y, int u, int v, int width, int height, int texWidth, int texHeight)
{
float f = 0.00390625F;
float f1 = 0.00390625F;
Tessellator tessellator = Tessellator.instance;
tessellator.startDrawingQuads();
tessellator.addVertexWithUV((double)(x + 0), (double)(y + height), (double)this.zLevel,
(double)((float)(u + 0) * f), (double)((float)(v + texHeight) * f1));
tessellator.addVertexWithUV((double)(x + width), (double)(y + height), (double)this.zLevel,
(double)((float)(u + texWidth) * f), (double)((float)(v + texHeight) * f1));
tessellator.addVertexWithUV((double)(x + width), (double)(y + 0), (double)this.zLevel,
(double)((float)(u + texWidth) * f), (double)((float)(v + 0) * f1));
tessellator.addVertexWithUV((double)(x + 0), (double)(y + 0), (double)this.zLevel,
(double)((float)(u + 0) * f), (double)((float)(v + 0) * f1));
tessellator.draw();
}
}
| common/founderio/chaoscrystal/rendering/OverlayAspectSelector.java | package founderio.chaoscrystal.rendering;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.List;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.Gui;
import net.minecraft.client.renderer.RenderHelper;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.entity.RenderItem;
import net.minecraft.client.renderer.entity.RenderManager;
import net.minecraft.entity.Entity;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.item.ItemMap;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.packet.Packet250CustomPayload;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.EnumMovingObjectType;
import net.minecraft.util.MovingObjectPosition;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.Vec3;
import net.minecraft.world.World;
import net.minecraftforge.client.event.MouseEvent;
import net.minecraftforge.client.event.RenderGameOverlayEvent;
import net.minecraftforge.client.event.RenderGameOverlayEvent.ElementType;
import net.minecraftforge.event.EventPriority;
import net.minecraftforge.event.ForgeSubscribe;
import org.lwjgl.opengl.GL11;
import cpw.mods.fml.common.network.PacketDispatcher;
import founderio.chaoscrystal.ChaosCrystalMain;
import founderio.chaoscrystal.Constants;
import founderio.chaoscrystal.aspects.Node;
import founderio.chaoscrystal.aspects.modules.ModuleVanillaWorldgen;
import founderio.chaoscrystal.blocks.TileEntityApparatus;
import founderio.chaoscrystal.degradation.Aspects;
import founderio.chaoscrystal.degradation.IAspectStore;
import founderio.chaoscrystal.entities.EntityChaosCrystal;
import founderio.chaoscrystal.entities.EntityFocusBorder;
import founderio.chaoscrystal.entities.EntityFocusFilter;
import founderio.chaoscrystal.entities.EntityFocusTransfer;
public class OverlayAspectSelector extends Gui {
private RenderItem ri;
public OverlayAspectSelector() {
ri = new RenderItem();
ri.setRenderManager(RenderManager.instance);
}
@ForgeSubscribe(priority = EventPriority.NORMAL)
public void onMouseWheel(MouseEvent event) {
if(event.dwheel == 0) {
return;
}
if(!Minecraft.getMinecraft().thePlayer.isSneaking()) {
return;
}
ItemStack currentItem = Minecraft.getMinecraft().thePlayer.inventory.getCurrentItem();
if(currentItem == null) {
return;
}
if(currentItem.itemID == ChaosCrystalMain.itemFocus.itemID && currentItem.getItemDamage() == 2) {
event.setCanceled(true);
int aspectIndex;
NBTTagCompound tags = currentItem.getTagCompound();
if(tags != null) {
String selectedAspect = tags.getString("aspect");
aspectIndex = Aspects.getAspectIndex(selectedAspect);
if(aspectIndex == -1) {
aspectIndex = 0;
}
} else {
tags = new NBTTagCompound();
aspectIndex = 0;
}
if(event.dwheel > 0 && aspectIndex < Aspects.ASPECTS.length - 1) {
aspectIndex++;
}
if(event.dwheel < 0 && aspectIndex > 0) {
aspectIndex--;
}
tags.setString("aspect", Aspects.ASPECTS[aspectIndex]);
currentItem.setTagCompound(tags);
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream(30);
DataOutputStream dos = new DataOutputStream(bos);
dos.writeInt(2);
dos.writeInt(Minecraft.getMinecraft().thePlayer.dimension);
dos.writeUTF(Minecraft.getMinecraft().thePlayer.username);
dos.writeUTF(Aspects.ASPECTS[aspectIndex]);
Packet250CustomPayload degradationPacket = new Packet250CustomPayload();
degradationPacket.channel = Constants.CHANNEL_NAME_OTHER_VISUAL;
degradationPacket.data = bos.toByteArray();
degradationPacket.length = bos.size();
dos.close();
PacketDispatcher.sendPacketToServer(degradationPacket);
} catch (IOException e) {
e.printStackTrace();
}
} else if(currentItem.itemID == ChaosCrystalMain.itemManual.itemID) {
event.setCanceled(true);
if(event.dwheel > 0) {
RenderItemManual.page--;
} else {
RenderItemManual.page++;
}
}
}
public void renderItem(ItemStack is, int x, int y) {
RenderHelper.enableGUIStandardItemLighting();
ri.renderItemAndEffectIntoGUI(Minecraft.getMinecraft().fontRenderer, Minecraft.getMinecraft().renderEngine, is, x, y);
ri.renderItemOverlayIntoGUI(Minecraft.getMinecraft().fontRenderer, Minecraft.getMinecraft().renderEngine, is, x, y);
}
/*
* Copy & modify from Minecraft.getMinecraft().entityRenderer.getMouseOver()
*/
public static MovingObjectPosition getMouseOver(float par1)
{
Entity pointedEntity = null;
Minecraft mc = Minecraft.getMinecraft();
if (mc.renderViewEntity != null)
{
if (mc.theWorld != null)
{
//mc.pointedEntityLiving = null;
double d0 = (double)mc.playerController.getBlockReachDistance();
MovingObjectPosition mop = mc.renderViewEntity.rayTrace(d0, par1);
double d1 = d0;
Vec3 vec3 = mc.renderViewEntity.getPosition(par1);
if (mc.playerController.extendedReach())
{
d0 = 6.0D;
d1 = 6.0D;
}
else
{
if (d0 > 3.0D)
{
d1 = 3.0D;
}
d0 = d1;
}
if (mop != null)
{
d1 = mop.hitVec.distanceTo(vec3);
}
Vec3 vec31 = mc.renderViewEntity.getLook(par1);
Vec3 vec32 = vec3.addVector(vec31.xCoord * d0, vec31.yCoord * d0, vec31.zCoord * d0);
pointedEntity = null;
float f1 = 1.0F;
@SuppressWarnings("rawtypes")
List list = mc.theWorld.getEntitiesWithinAABBExcludingEntity(mc.renderViewEntity, mc.renderViewEntity.boundingBox.addCoord(vec31.xCoord * d0, vec31.yCoord * d0, vec31.zCoord * d0).expand((double)f1, (double)f1, (double)f1));
double d2 = d1;
for (int i = 0; i < list.size(); ++i)
{
Entity entity = (Entity)list.get(i);
float f2 = entity.getCollisionBorderSize();
AxisAlignedBB axisalignedbb = entity.boundingBox.expand((double)f2, (double)f2, (double)f2);
MovingObjectPosition movingobjectposition = axisalignedbb.calculateIntercept(vec3, vec32);
if (axisalignedbb.isVecInside(vec3))
{
if (0.0D < d2 || d2 == 0.0D)
{
pointedEntity = entity;
d2 = 0.0D;
}
}
else if (movingobjectposition != null)
{
double d3 = vec3.distanceTo(movingobjectposition.hitVec);
if (d3 < d2 || d2 == 0.0D)
{
if (entity == mc.renderViewEntity.ridingEntity && !entity.canRiderInteract())
{
if (d2 == 0.0D)
{
pointedEntity = entity;
}
}
else
{
pointedEntity = entity;
d2 = d3;
}
}
}
}
if (pointedEntity != null && (d2 < d1 || mop == null))
{
mop = new MovingObjectPosition(pointedEntity);
}
return mop;
}
}
return null;
}
private void renderAspectList(int xPos, int yPos, IAspectStore store) {
int offset = 0;
int colOffset = 0;
final int colWidth = 64;
for(String aspect : Aspects.ASPECTS) {
int asp = store.getAspect(aspect);
Minecraft.getMinecraft().renderEngine.bindTexture(
new ResourceLocation(Constants.MOD_ID + ":" + "textures/hud/aspect_" + aspect + ".png"));
this.drawTexturedModalRectScaled(xPos + 5 + colOffset, yPos + offset + 5, 0, 0, 10, 10, 256, 256);
Minecraft.getMinecraft().fontRenderer.drawString(
Integer.toString(asp),
xPos + 16 + colOffset, yPos + 2 + offset + 5,
16777215);
if(offset >= 30) {
offset = 0;
colOffset += colWidth;
} else {
offset += 10;
}
}
}
private void renderAspectList(int xPos, int yPos, int[] aspectArray) {
int offset = 0;
int colOffset = 0;
final int colWidth = 64;
for(int i = 0; i < aspectArray.length; i++) {
String aspect = Aspects.ASPECTS[i];
int asp = aspectArray[i];
if(asp > 0) {
Minecraft.getMinecraft().renderEngine.bindTexture(new ResourceLocation(Constants.MOD_ID + ":" + "textures/hud/aspect_" + aspect + ".png"));
this.drawTexturedModalRectScaled(xPos + 5 + colOffset, yPos + offset + 5,
0, 0,
10, 10,
256, 256);
Minecraft.getMinecraft().fontRenderer.drawString(
Integer.toString(asp),
xPos + 16 + colOffset, yPos + 2 + offset + 5,
16777215);
if(offset >= 30) {
offset = 0;
colOffset += colWidth;
} else {
offset += 10;
}
}
}
}
@ForgeSubscribe(priority = EventPriority.NORMAL)
public void onRenderHud(RenderGameOverlayEvent event) {
if(event.type != ElementType.CROSSHAIRS) {
return;
}
ItemStack helmet = Minecraft.getMinecraft().thePlayer.inventory.armorInventory[3];
ItemStack currentItem = Minecraft.getMinecraft().thePlayer.inventory.getCurrentItem();
boolean specialSkip = (currentItem != null && currentItem.getItem() instanceof ItemMap) || ChaosCrystalMain.cfgSneakToShowAspects && !Minecraft.getMinecraft().thePlayer.isSneaking();
int centerW = event.resolution.getScaledWidth()/2;
int centerH = event.resolution.getScaledHeight()/2;
GL11.glPushMatrix();
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
GL11.glEnable(GL11.GL_BLEND);
GL11.glDisable(GL11.GL_LIGHTING);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
if(helmet != null && helmet.itemID == ChaosCrystalMain.itemCrystalGlasses.itemID && !specialSkip) {
MovingObjectPosition mop = getMouseOver(0);
if(mop != null) {
Entity lookingAt = mop.entityHit;
if(lookingAt != null) {
if(lookingAt instanceof EntityChaosCrystal) {
EntityChaosCrystal e = (EntityChaosCrystal)lookingAt;
Minecraft.getMinecraft().renderEngine.bindTexture(
new ResourceLocation(Constants.MOD_ID + ":" + "textures/items/chaoscrystal.png"));
this.drawTexturedModalRectScaled(centerW - 16 - 5, centerH + 5, 0, 0, 16, 16, 256, 256);
if(e.isInSuckMode()) {
Minecraft.getMinecraft().renderEngine.bindTexture(
new ResourceLocation(Constants.MOD_ID + ":" + "textures/hud/mode_suck.png"));
} else {
Minecraft.getMinecraft().renderEngine.bindTexture(
new ResourceLocation(Constants.MOD_ID + ":" + "textures/hud/mode_expel.png"));
}
this.drawTexturedModalRectScaled(centerW - 16 - 5, centerH - 16 - 5, 0, 0, 16, 16, 256, 256);
renderAspectList(centerW, centerH, e);
} else if(lookingAt instanceof EntityFocusFilter) {
Minecraft.getMinecraft().renderEngine.bindTexture(
new ResourceLocation(Constants.MOD_ID + ":" + "textures/items/focus_filter.png"));
this.drawTexturedModalRectScaled(centerW - 16 - 5, centerH + 5, 0, 0, 16, 16, 256, 256);
String aspect = ((EntityFocusFilter)lookingAt).getAspect();
Minecraft.getMinecraft().renderEngine.bindTexture(
new ResourceLocation(Constants.MOD_ID + ":" + "textures/hud/aspect_" + aspect + ".png"));
this.drawTexturedModalRectScaled(centerW + 5, centerH + 5, 0, 0, 16, 16, 256, 256);
} else if(lookingAt instanceof EntityFocusBorder) {
Minecraft.getMinecraft().renderEngine.bindTexture(
new ResourceLocation(Constants.MOD_ID + ":" + "textures/items/focus_border.png"));
this.drawTexturedModalRectScaled(centerW - 16 - 5, centerH + 5, 0, 0, 16, 16, 256, 256);
} else if(lookingAt instanceof EntityFocusTransfer) {
Minecraft.getMinecraft().renderEngine.bindTexture(
new ResourceLocation(Constants.MOD_ID + ":" + "textures/items/focus_transfer.png"));
this.drawTexturedModalRectScaled(centerW - 16 - 5, centerH + 5, 0, 0, 16, 16, 256, 256);
} else if(lookingAt instanceof EntityItem) {
ItemStack is = ((EntityItem)lookingAt).getEntityItem();
List<Node> degradations = ChaosCrystalMain.degradationStore.getExtractionsFrom(is);
if(degradations.size() == 0) {
} else {
Node node = degradations.get(0);
renderAspectList(centerW, centerH, node.getAspects());
ItemStack[] parents = node.getDegradedFrom(node.getDispayItemStack());
for(int s = 0; s < parents.length; s++) {
if(parents[s].itemID != 0) {
renderItem(parents[s], centerW + 5 + s*16, centerH - 16 - 5);
}
}
}
renderItem(is, centerW - 16 - 5, centerH - 16 - 5);
}
}
if(mop.typeOfHit == EnumMovingObjectType.TILE) {
World w = Minecraft.getMinecraft().thePlayer.worldObj;
int id = w.getBlockId(
mop.blockX,
mop.blockY,
mop.blockZ);
if(id != 0) {// We can't extract air...
int meta = w.getBlockMetadata(
mop.blockX,
mop.blockY,
mop.blockZ);
boolean doRenderMiniBlock = false;
List<Node> degradations = ChaosCrystalMain.degradationStore.getExtractionsFrom(new ItemStack(id, 1, meta));
if(degradations.size() != 0) {
Node node = degradations.get(0);
doRenderMiniBlock = true;
renderAspectList(centerW, centerH, node.getAspects());
ItemStack[] parents = node.getDegradedFrom(node.getDispayItemStack());
for(int s = 0; s < parents.length; s++) {
if(parents[s].itemID != 0) {
renderItem(parents[s], centerW + 5 + s*16, centerH - 16 - 5);
}
}
}
TileEntity te = w.getBlockTileEntity(mop.blockX,
mop.blockY,
mop.blockZ);
if(te instanceof TileEntityApparatus) {
TileEntityApparatus apparatus = (TileEntityApparatus)te;
doRenderMiniBlock = true;
for(int i = 0; i < apparatus.getSizeInventory(); i++) {
ItemStack its = ((TileEntityApparatus) te).getStackInSlot(i);
if(its != null && its.itemID != 0) {
renderItem(its, centerW - 16 - 5 - 16*i, centerH + 5);
}
}
}
if(doRenderMiniBlock) {
renderItem(new ItemStack(id, 1, meta), centerW - 16 - 5, centerH - 16 - 5);
}
}
}
}
}
if(currentItem != null && currentItem.itemID == ChaosCrystalMain.itemFocus.itemID && currentItem.getItemDamage() == 2) {
String selectedAspect;
int aspectIndex;
NBTTagCompound tags = currentItem.getTagCompound();
if (tags == null) {
selectedAspect = Aspects.ASPECTS[0];
aspectIndex = 0;
} else {
selectedAspect = tags.getString("aspect");
aspectIndex = Aspects.getAspectIndex(selectedAspect);
if (aspectIndex == -1) {
selectedAspect = Aspects.ASPECTS[0];
aspectIndex = 0;
}
}
int center = event.resolution.getScaledWidth() / 2;
int bottom = event.resolution.getScaledHeight() - 80;
Minecraft.getMinecraft().renderEngine.bindTexture(new ResourceLocation(Constants.MOD_ID + ":" + "textures/hud/aspect_" + selectedAspect + ".png"));
this.drawTexturedModalRectScaled(center - 8, bottom, 0, 0, 16, 16, 256, 256);
GL11.glColor4f(0.4F, 0.4F, 0.4F, 0.4F);
if(aspectIndex > 0) {
Minecraft.getMinecraft().renderEngine.bindTexture(new ResourceLocation(Constants.MOD_ID + ":" + "textures/hud/aspect_" + Aspects.ASPECTS[aspectIndex - 1] + ".png"));
this.drawTexturedModalRectScaled(center - 8 - 14 - 2, bottom + 2, 0, 0, 14, 14, 256, 256);
}
if(aspectIndex < Aspects.ASPECTS.length - 1) {
Minecraft.getMinecraft().renderEngine.bindTexture(new ResourceLocation(Constants.MOD_ID + ":" + "textures/hud/aspect_" + Aspects.ASPECTS[aspectIndex + 1] + ".png"));
this.drawTexturedModalRectScaled(center - 8 + 14 + 2, bottom + 2, 0, 0, 14, 14, 256, 256);
}
GL11.glColor4f(0.2F, 0.2F, 0.2F, 0.2F);
if(aspectIndex > 1) {
Minecraft.getMinecraft().renderEngine.bindTexture(new ResourceLocation(Constants.MOD_ID + ":" + "textures/hud/aspect_" + Aspects.ASPECTS[aspectIndex - 2] + ".png"));
this.drawTexturedModalRectScaled(center - 8 - 26 - 4, bottom + 6, 0, 0, 10, 10, 256, 256);
}
if(aspectIndex < Aspects.ASPECTS.length - 2) {
Minecraft.getMinecraft().renderEngine.bindTexture(new ResourceLocation(Constants.MOD_ID + ":" + "textures/hud/aspect_" + Aspects.ASPECTS[aspectIndex + 2] + ".png"));
this.drawTexturedModalRectScaled(center - 8 + 26 + 4, bottom + 6, 0, 0, 10, 10, 256, 256);
}
}
GL11.glPopMatrix();
Minecraft.getMinecraft().renderEngine.bindTexture(Gui.icons);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
GL11.glDisable(GL11.GL_LIGHTING);
GL11.glDisable(GL11.GL_BLEND);
}
/**
* Draws a textured rectangle at the stored z-value. Args: x, y, u, v, width, height, textureWidth, textureHeight
* This uses a separate draw size, not the texture size.
*/
public void drawTexturedModalRectScaled(int x, int y, int u, int v, int width, int height, int texWidth, int texHeight)
{
float f = 0.00390625F;
float f1 = 0.00390625F;
Tessellator tessellator = Tessellator.instance;
tessellator.startDrawingQuads();
tessellator.addVertexWithUV((double)(x + 0), (double)(y + height), (double)this.zLevel,
(double)((float)(u + 0) * f), (double)((float)(v + texHeight) * f1));
tessellator.addVertexWithUV((double)(x + width), (double)(y + height), (double)this.zLevel,
(double)((float)(u + texWidth) * f), (double)((float)(v + texHeight) * f1));
tessellator.addVertexWithUV((double)(x + width), (double)(y + 0), (double)this.zLevel,
(double)((float)(u + texWidth) * f), (double)((float)(v + 0) * f1));
tessellator.addVertexWithUV((double)(x + 0), (double)(y + 0), (double)this.zLevel,
(double)((float)(u + 0) * f), (double)((float)(v + 0) * f1));
tessellator.draw();
}
}
| Some cleanup & mini optimization | common/founderio/chaoscrystal/rendering/OverlayAspectSelector.java | Some cleanup & mini optimization | <ide><path>ommon/founderio/chaoscrystal/rendering/OverlayAspectSelector.java
<ide> import founderio.chaoscrystal.ChaosCrystalMain;
<ide> import founderio.chaoscrystal.Constants;
<ide> import founderio.chaoscrystal.aspects.Node;
<del>import founderio.chaoscrystal.aspects.modules.ModuleVanillaWorldgen;
<ide> import founderio.chaoscrystal.blocks.TileEntityApparatus;
<ide> import founderio.chaoscrystal.degradation.Aspects;
<ide> import founderio.chaoscrystal.degradation.IAspectStore;
<ide> if(!Minecraft.getMinecraft().thePlayer.isSneaking()) {
<ide> return;
<ide> }
<del>
<ide>
<ide> ItemStack currentItem = Minecraft.getMinecraft().thePlayer.inventory.getCurrentItem();
<ide> if(currentItem == null) {
<ide> Entity pointedEntity = null;
<ide> Minecraft mc = Minecraft.getMinecraft();
<ide>
<del> if (mc.renderViewEntity != null)
<add> if (mc.renderViewEntity != null && mc.theWorld != null)
<ide> {
<del> if (mc.theWorld != null)
<add> //mc.pointedEntityLiving = null;
<add> double d0 = (double)mc.playerController.getBlockReachDistance();
<add> MovingObjectPosition mop = mc.renderViewEntity.rayTrace(d0, par1);
<add> double d1 = d0;
<add> Vec3 vec3 = mc.renderViewEntity.getPosition(par1);
<add>
<add> if (mc.playerController.extendedReach())
<ide> {
<del> //mc.pointedEntityLiving = null;
<del> double d0 = (double)mc.playerController.getBlockReachDistance();
<del> MovingObjectPosition mop = mc.renderViewEntity.rayTrace(d0, par1);
<del> double d1 = d0;
<del> Vec3 vec3 = mc.renderViewEntity.getPosition(par1);
<del>
<del> if (mc.playerController.extendedReach())
<add> d0 = 6.0D;
<add> d1 = 6.0D;
<add> }
<add> else
<add> {
<add> if (d0 > 3.0D)
<ide> {
<del> d0 = 6.0D;
<del> d1 = 6.0D;
<del> }
<del> else
<add> d1 = 3.0D;
<add> }
<add>
<add> d0 = d1;
<add> }
<add>
<add> if (mop != null)
<add> {
<add> d1 = mop.hitVec.distanceTo(vec3);
<add> }
<add>
<add> Vec3 vec31 = mc.renderViewEntity.getLook(par1);
<add> Vec3 vec32 = vec3.addVector(vec31.xCoord * d0, vec31.yCoord * d0, vec31.zCoord * d0);
<add> pointedEntity = null;
<add> float f1 = 1.0F;
<add> @SuppressWarnings("rawtypes")
<add> List list = mc.theWorld.getEntitiesWithinAABBExcludingEntity(mc.renderViewEntity, mc.renderViewEntity.boundingBox.addCoord(vec31.xCoord * d0, vec31.yCoord * d0, vec31.zCoord * d0).expand((double)f1, (double)f1, (double)f1));
<add> double d2 = d1;
<add>
<add> for (int i = 0; i < list.size(); ++i)
<add> {
<add> Entity entity = (Entity)list.get(i);
<add>
<add> float f2 = entity.getCollisionBorderSize();
<add> AxisAlignedBB axisalignedbb = entity.boundingBox.expand((double)f2, (double)f2, (double)f2);
<add> MovingObjectPosition movingobjectposition = axisalignedbb.calculateIntercept(vec3, vec32);
<add>
<add> if (axisalignedbb.isVecInside(vec3))
<ide> {
<del> if (d0 > 3.0D)
<add> if (0.0D < d2 || d2 == 0.0D)
<ide> {
<del> d1 = 3.0D;
<add> pointedEntity = entity;
<add> d2 = 0.0D;
<ide> }
<del>
<del> d0 = d1;
<del> }
<del>
<del> if (mop != null)
<add> }
<add> else if (movingobjectposition != null)
<ide> {
<del> d1 = mop.hitVec.distanceTo(vec3);
<del> }
<del>
<del> Vec3 vec31 = mc.renderViewEntity.getLook(par1);
<del> Vec3 vec32 = vec3.addVector(vec31.xCoord * d0, vec31.yCoord * d0, vec31.zCoord * d0);
<del> pointedEntity = null;
<del> float f1 = 1.0F;
<del> @SuppressWarnings("rawtypes")
<del> List list = mc.theWorld.getEntitiesWithinAABBExcludingEntity(mc.renderViewEntity, mc.renderViewEntity.boundingBox.addCoord(vec31.xCoord * d0, vec31.yCoord * d0, vec31.zCoord * d0).expand((double)f1, (double)f1, (double)f1));
<del> double d2 = d1;
<del>
<del> for (int i = 0; i < list.size(); ++i)
<del> {
<del> Entity entity = (Entity)list.get(i);
<del>
<del> float f2 = entity.getCollisionBorderSize();
<del> AxisAlignedBB axisalignedbb = entity.boundingBox.expand((double)f2, (double)f2, (double)f2);
<del> MovingObjectPosition movingobjectposition = axisalignedbb.calculateIntercept(vec3, vec32);
<del>
<del> if (axisalignedbb.isVecInside(vec3))
<add> double d3 = vec3.distanceTo(movingobjectposition.hitVec);
<add>
<add> if (d3 < d2 || d2 == 0.0D)
<ide> {
<del> if (0.0D < d2 || d2 == 0.0D)
<add> if (entity == mc.renderViewEntity.ridingEntity && !entity.canRiderInteract())
<add> {
<add> if (d2 == 0.0D)
<add> {
<add> pointedEntity = entity;
<add> }
<add> }
<add> else
<ide> {
<ide> pointedEntity = entity;
<del> d2 = 0.0D;
<add> d2 = d3;
<ide> }
<ide> }
<del> else if (movingobjectposition != null)
<del> {
<del> double d3 = vec3.distanceTo(movingobjectposition.hitVec);
<del>
<del> if (d3 < d2 || d2 == 0.0D)
<del> {
<del> if (entity == mc.renderViewEntity.ridingEntity && !entity.canRiderInteract())
<del> {
<del> if (d2 == 0.0D)
<del> {
<del> pointedEntity = entity;
<del> }
<del> }
<del> else
<del> {
<del> pointedEntity = entity;
<del> d2 = d3;
<del> }
<del> }
<del> }
<del> }
<del>
<del> if (pointedEntity != null && (d2 < d1 || mop == null))
<del> {
<del> mop = new MovingObjectPosition(pointedEntity);
<del> }
<del> return mop;
<del> }
<add> }
<add> }
<add>
<add> if (pointedEntity != null && (d2 < d1 || mop == null))
<add> {
<add> mop = new MovingObjectPosition(pointedEntity);
<add> }
<add> return mop;
<ide> }
<ide> return null;
<ide> }
<ide> new ResourceLocation(Constants.MOD_ID + ":" + "textures/hud/mode_expel.png"));
<ide> }
<ide> this.drawTexturedModalRectScaled(centerW - 16 - 5, centerH - 16 - 5, 0, 0, 16, 16, 256, 256);
<del>
<add>
<ide> renderAspectList(centerW, centerH, e);
<ide>
<ide>
<ide> }
<ide> }
<ide>
<del> int center = event.resolution.getScaledWidth() / 2;
<ide> int bottom = event.resolution.getScaledHeight() - 80;
<ide>
<ide>
<ide> Minecraft.getMinecraft().renderEngine.bindTexture(new ResourceLocation(Constants.MOD_ID + ":" + "textures/hud/aspect_" + selectedAspect + ".png"));
<del> this.drawTexturedModalRectScaled(center - 8, bottom, 0, 0, 16, 16, 256, 256);
<add> this.drawTexturedModalRectScaled(centerW - 8, bottom, 0, 0, 16, 16, 256, 256);
<ide>
<ide> GL11.glColor4f(0.4F, 0.4F, 0.4F, 0.4F);
<ide>
<ide> if(aspectIndex > 0) {
<ide> Minecraft.getMinecraft().renderEngine.bindTexture(new ResourceLocation(Constants.MOD_ID + ":" + "textures/hud/aspect_" + Aspects.ASPECTS[aspectIndex - 1] + ".png"));
<del> this.drawTexturedModalRectScaled(center - 8 - 14 - 2, bottom + 2, 0, 0, 14, 14, 256, 256);
<add> this.drawTexturedModalRectScaled(centerW - 8 - 14 - 2, bottom + 2, 0, 0, 14, 14, 256, 256);
<ide>
<ide> }
<ide>
<ide> if(aspectIndex < Aspects.ASPECTS.length - 1) {
<ide> Minecraft.getMinecraft().renderEngine.bindTexture(new ResourceLocation(Constants.MOD_ID + ":" + "textures/hud/aspect_" + Aspects.ASPECTS[aspectIndex + 1] + ".png"));
<del> this.drawTexturedModalRectScaled(center - 8 + 14 + 2, bottom + 2, 0, 0, 14, 14, 256, 256);
<add> this.drawTexturedModalRectScaled(centerW - 8 + 14 + 2, bottom + 2, 0, 0, 14, 14, 256, 256);
<ide>
<ide> }
<ide>
<ide>
<ide> if(aspectIndex > 1) {
<ide> Minecraft.getMinecraft().renderEngine.bindTexture(new ResourceLocation(Constants.MOD_ID + ":" + "textures/hud/aspect_" + Aspects.ASPECTS[aspectIndex - 2] + ".png"));
<del> this.drawTexturedModalRectScaled(center - 8 - 26 - 4, bottom + 6, 0, 0, 10, 10, 256, 256);
<add> this.drawTexturedModalRectScaled(centerW - 8 - 26 - 4, bottom + 6, 0, 0, 10, 10, 256, 256);
<ide>
<ide> }
<ide>
<ide> if(aspectIndex < Aspects.ASPECTS.length - 2) {
<ide> Minecraft.getMinecraft().renderEngine.bindTexture(new ResourceLocation(Constants.MOD_ID + ":" + "textures/hud/aspect_" + Aspects.ASPECTS[aspectIndex + 2] + ".png"));
<del> this.drawTexturedModalRectScaled(center - 8 + 26 + 4, bottom + 6, 0, 0, 10, 10, 256, 256);
<add> this.drawTexturedModalRectScaled(centerW - 8 + 26 + 4, bottom + 6, 0, 0, 10, 10, 256, 256);
<ide>
<ide> }
<ide> |
|
JavaScript | lgpl-2.1 | 2694bcbad8bf4d886d3003e132d911b63cea2dc1 | 0 | olifre/root,olifre/root,olifre/root,olifre/root,olifre/root,olifre/root,olifre/root,root-mirror/root,root-mirror/root,root-mirror/root,root-mirror/root,root-mirror/root,root-mirror/root,olifre/root,olifre/root,root-mirror/root,root-mirror/root,root-mirror/root,root-mirror/root,olifre/root,root-mirror/root,olifre/root | sap.ui.define(['rootui5/eve7/lib/EveManager'], function(EveManager) {
"use strict";
// See also EveScene.js makeGLRepresentation(), there several members are
// set for the top-level Object3D.
//==============================================================================
// EveElemControl
//==============================================================================
function EveElemControl(o3d)
{
// JSROOT.Painter.GeoDrawingControl.call(this);
this.obj3d = o3d;
}
EveElemControl.prototype = Object.create(JSROOT.Painter.GeoDrawingControl.prototype);
EveElemControl.prototype.invokeSceneMethod = function(fname, arg)
{
if ( ! this.obj3d) return false;
var s = this.obj3d.scene;
if (s && (typeof s[fname] == "function"))
return s[fname](this.obj3d, arg, this.event);
return false;
}
EveElemControl.prototype.separateDraw = false;
EveElemControl.prototype.elementHighlighted = function(indx)
{
// default is simple selection, we ignore the indx
this.invokeSceneMethod("processElementHighlighted"); // , indx);
}
EveElemControl.prototype.elementSelected = function(indx)
{
// default is simple selection, we ignore the indx
this.invokeSceneMethod("processElementSelected"); //, indx);
}
//==============================================================================
// EveElements
//==============================================================================
var GL = { POINTS: 0, LINES: 1, LINE_LOOP: 2, LINE_STRIP: 3, TRIANGLES: 4 };
var RC;
function EveElements(rc)
{
console.log("EveElements -- RCore");
RC = rc;
}
EveElements.prototype.TestRnr = function(name, obj, rnr_data)
{
if (obj && rnr_data && rnr_data.vtxBuff) return false;
var cnt = this[name] || 0;
if (cnt++ < 5) console.log(name, obj, rnr_data);
this[name] = cnt;
return true;
}
//==============================================================================
// makeHit
//==============================================================================
EveElements.prototype.makeHit = function(hit, rnr_data)
{
if (this.TestRnr("hit", hit, rnr_data)) return null;
//let hit_size = 8 * rnr_data.fMarkerSize;
//let size = rnr_data.vtxBuff.length / 3;
let geo = new RC.Geometry();
geo.vertices = new RC.BufferAttribute( rnr_data.vtxBuff, 3 );
let col = new RC.Color(JSROOT.Painter.root_colors[hit.fMarkerColor]);
let mat = new RC.MeshBasicMaterial;
mat.color = col;
let pnts = new RC.Point(geo, mat);
// mesh.get_ctrl = function() { return new EveElemControl(this); }
// mesh.highlightScale = 2;
// mesh.material.sizeAttenuation = false;
// mesh.material.size = hit.fMarkerSize;
return pnts;
}
//==============================================================================
// makeTrack
//==============================================================================
EveElements.prototype.makeTrack = function(track, rnr_data)
{
if (this.TestRnr("track", track, rnr_data)) return null;
let N = rnr_data.vtxBuff.length/3;
let track_width = track.fLineWidth || 1;
let track_color = JSROOT.Painter.root_colors[track.fLineColor] || "rgb(255,0,255)";
if (JSROOT.browser.isWin) track_width = 1; // not supported on windows
let buf = new Float32Array((N-1) * 6), pos = 0;
for (let k=0;k<(N-1);++k) {
buf[pos] = rnr_data.vtxBuff[k*3];
buf[pos+1] = rnr_data.vtxBuff[k*3+1];
buf[pos+2] = rnr_data.vtxBuff[k*3+2];
let breakTrack = false;
if (rnr_data.idxBuff)
for (let b = 0; b < rnr_data.idxBuff.length; b++) {
if ( (k+1) == rnr_data.idxBuff[b]) {
breakTrack = true;
break;
}
}
if (breakTrack) {
buf[pos+3] = rnr_data.vtxBuff[k*3];
buf[pos+4] = rnr_data.vtxBuff[k*3+1];
buf[pos+5] = rnr_data.vtxBuff[k*3+2];
} else {
buf[pos+3] = rnr_data.vtxBuff[k*3+3];
buf[pos+4] = rnr_data.vtxBuff[k*3+4];
buf[pos+5] = rnr_data.vtxBuff[k*3+5];
}
pos+=6;
}
let style = (track.fLineStyle > 1) ? JSROOT.Painter.root_line_styles[track.fLineStyle] : "",
dash = style ? style.split(",") : [], lineMaterial;
if (dash && (dash.length > 1)) {
lineMaterial = new RC.MeshBasicMaterial({ color: track_color, linewidth: track_width, dashSize: parseInt(dash[0]), gapSize: parseInt(dash[1]) });
} else {
lineMaterial = new RC.MeshBasicMaterial({ color: track_color, linewidth: track_width });
}
let geom = new RC.Geometry();
geom.vertices = new RC.BufferAttribute( buf, 3 );
let line = new RC.Line(geom, lineMaterial);
line.renderingPrimitive = RC.LINES;
// required for the dashed material
//if (dash && (dash.length > 1))
// line.computeLineDistances();
//line.hightlightWidthScale = 2;
line.get_ctrl = function() { return new EveElemControl(this); }
return line;
}
//==============================================================================
// makeJet
//==============================================================================
EveElements.prototype.makeJet = function(jet, rnr_data)
{
if (this.TestRnr("jet", jet, rnr_data)) return null;
// console.log("make jet ", jet);
// let jet_ro = new RC.Object3D();
let pos_ba = new RC.BufferAttribute( rnr_data.vtxBuff, 3 );
let N = rnr_data.vtxBuff.length / 3;
let geo_body = new RC.Geometry();
geo_body.vertices = pos_ba;
let idcs = new Uint16Array(3 + 3 * (N - 1)); ///[0, N-1, 1];
idcs[0] = 0; idcs[1] = N-1; idcs[2] = 1;
for (let i = 1; i < N - 1; ++i) {
idcs[3*i] = 0; idcs[3*i + 1] = i; idcs[3*i + 2] = i + 1;
// idcs.push( 0, i, i + 1 );
}
geo_body.indices = new RC.BufferAttribute( idcs, 1 );
geo_body.computeVertexNormals();
let geo_rim = new RC.Geometry();
geo_rim.vertices = pos_ba;
idcs = new Uint16Array(N-1);
for (let i = 1; i < N; ++i) idcs[i-1] = i;
geo_rim.indices = new RC.BufferAttribute( idcs, 1 );
let geo_rays = new RC.Geometry();
geo_rays.vertices = pos_ba;
idcs = [];
for (let i = 1; i < N; i += 4)
idcs.push( 0, i );
geo_rays.indices = idcs;
let mcol = JSROOT.Painter.root_colors[jet.fMainColor];
let lcol = JSROOT.Painter.root_colors[jet.fLineColor];
let mesh = new RC.Mesh(geo_body, new RC.MeshPhongMaterial({ depthWrite: false, color: mcol, transparent: true, opacity: 0.5, side: RC.DoubleSide }));
let line1 = new RC.Line(geo_rim, new RC.MeshBasicMaterial({ linewidth: 2, color: lcol, transparent: true, opacity: 0.5 }));
let line2 = new RC.Line(geo_rays, new RC.MeshBasicMaterial({ linewidth: 0.5, color: lcol, transparent: true, opacity: 0.5 }));
line2.renderingPrimitive = RC.LINES;
// jet_ro.add( mesh );
mesh.add( line1 );
mesh.add( line2 );
mesh.get_ctrl = function() { return new EveElemControl(this); }
return mesh;
}
EveElements.prototype.makeJetProjected = function(jet, rnr_data)
{
// JetProjected has 3 or 4 points. 0-th is apex, others are rim.
// Fourth point is only present in RhoZ when jet hits barrel/endcap transition.
// console.log("makeJetProjected ", jet);
if (this.TestRnr("jetp", jet, rnr_data)) return null;
let pos_ba = new RC.BufferAttribute( rnr_data.vtxBuff, 3 );
let N = rnr_data.vtxBuff.length / 3;
let geo_body = new RC.Geometry();
geo_body.vertices = pos_ba;
let idcs = new Uint16Array( N > 3 ? 6 : 3);
idcs[0] = 0; idcs[1] = 2; idcs[2] = 1;
if (N > 3) { idcs[3] = 0; idcs[4] = 5; idcs[5] = 2; }
geo_body.indices = new RC.BufferAttribute( idcs, 1 );
geo_body.computeVertexNormals();
let geo_rim = new RC.Geometry();
geo_rim.vertices = pos_ba;
idcs = new Uint16Array(N-1);
for (let i = 1; i < N; ++i) idcs[i-1] = i;
geo_rim.indices = new RC.BufferAttribute( idcs, 1 );
let geo_rays = new RC.Geometry();
geo_rays.vertices = pos_ba;
idcs = new Uint16Array(4); // [ 0, 1, 0, N-1 ];
idcs[0] = 0; idcs[1] = 1; idcs[2] = 0; idcs[3] = N-1;
geo_rays.indices = new RC.BufferAttribute( idcs, 1 );;
let fcol = JSROOT.Painter.root_colors[jet.fFillColor];
let lcol = JSROOT.Painter.root_colors[jet.fLineColor];
// Process transparency !!!
// console.log("cols", fcol, lcol);
// double-side material required for correct tracing of colors - otherwise points sequence should be changed
let mesh = new RC.Mesh(geo_body, new RC.MeshBasicMaterial({ depthWrite: false, color: fcol, transparent: true, opacity: 0.5, side: RC.DoubleSide }));
let line1 = new RC.Line(geo_rim, new RC.MeshBasicMaterial({ linewidth: 2, color: lcol, transparent: true, opacity: 0.5 }));
let line2 = new RC.Line(geo_rays, new RC.MeshBasicMaterial({ linewidth: 1, color: lcol, transparent: true, opacity: 0.5 }));
line2.renderingPrimitive = RC.LINES;
// jet_ro.add( mesh );
mesh.add( line1 );
mesh.add( line2 );
mesh.get_ctrl = function() { return new EveElemControl(this); }
return mesh;
}
//==============================================================================
// makeEveGeometry / makeEveGeoShape
//==============================================================================
EveElements.prototype.makeEveGeometry = function(rnr_data, force)
{
let nVert = rnr_data.idxBuff[1]*3;
if (rnr_data.idxBuff[0] != GL.TRIANGLES) throw "Expect triangles first.";
if (2 + nVert != rnr_data.idxBuff.length) throw "Expect single list of triangles in index buffer.";
let body = new RC.Geometry();
body.vertices = new RC.BufferAttribute( rnr_data.vtxBuff, 3 );
body.indices = new RC.BufferAttribute( rnr_data.idxBuff, 1 );
body.setDrawRange(2, nVert);
body.computeVertexNormalsIdxRange(2, nVert);
// XXXX Fix this. It seems we could have flat shading with usage of simple shaders.
// XXXX Also, we could do edge detect on the server for outlines.
// XXXX a) 3d objects - angle between triangles >= 85 degrees (or something);
// XXXX b) 2d objects - segment only has one triangle.
// XXXX Somewhat orthogonal - when we do tesselation, conversion from quads to
// XXXX triangles is trivial, we could do it before invoking the big guns (if they are even needed).
// XXXX Oh, and once triangulated, we really don't need to store 3 as number of verts in a poly each time.
// XXXX Or do we? We might need it for projection stuff.
return body;
}
EveElements.prototype.makeEveGeoShape = function(egs, rnr_data)
{
let egs_ro = new RC.Group();
let geom = this.makeEveGeometry(rnr_data);
let fcol = new RC.Color(JSROOT.Painter.getColor(egs.fFillColor));
// let material = new RC.MeshPhongMaterial({// side: THREE.DoubleSide,
// depthWrite: false, color:fcol, transparent: true, opacity: 0.2 });
let material = new RC.MeshPhongMaterial;
material.color = fcol;
material.side = 2;
material.depthWrite = false;
material.transparent = true;
material.opacity = 0.2;
let mesh = new RC.Mesh(geom, material);
egs_ro.add(mesh);
return egs_ro;
}
//==============================================================================
// makePolygonSetProjected
//==============================================================================
EveElements.prototype.makePolygonSetProjected = function(psp, rnr_data)
{
let psp_ro = new RC.Group();
let pos_ba = new RC.BufferAttribute( rnr_data.vtxBuff, 3 );
let idx_ba = new RC.BufferAttribute( rnr_data.idxBuff, 1 );
let ib_len = rnr_data.idxBuff.length;
let fcol = new RC.Color(JSROOT.Painter.root_colors[psp.fMainColor]);
let material = new RC.MeshPhongMaterial;
material.color = fcol;
material.specular = new RC.Color(1, 1, 1);
material.shininess = 50;
material.side = RC.FRONT_AND_BACK_SIDE;
material.depthWrite = false;
material.transparent = true;
material.opacity = 0.4;
console.log("XXXXX", fcol, material);
// XXXXXX Should be Mesh -> Line material ???
let line_mat = new RC.MeshBasicMaterial;
line_mat.color = fcol;
for (let ib_pos = 0; ib_pos < ib_len; )
{
if (rnr_data.idxBuff[ib_pos] == GL.TRIANGLES)
{
let body = new RC.Geometry();
body.vertices = pos_ba;
body.indices = idx_ba;
body.setDrawRange(ib_pos + 2, 3 * rnr_data.idxBuff[ib_pos + 1]);
body.computeVertexNormalsIdxRange(ib_pos + 2, 3 * rnr_data.idxBuff[ib_pos + 1]);
psp_ro.add( new RC.Mesh(body, material) );
ib_pos += 2 + 3 * rnr_data.idxBuff[ib_pos + 1];
}
else if (rnr_data.idxBuff[ib_pos] == GL.LINE_LOOP)
{
let body = new RC.Geometry();
body.vertices = pos_ba;
body.indices = idx_ba;
body.setDrawRange(ib_pos + 2, rnr_data.idxBuff[ib_pos + 1]);
let ll = new RC.Line(body, line_mat);
ll.renderingPrimitive = RC.LINE_LOOP;
psp_ro.add( ll );
ib_pos += 2 + rnr_data.idxBuff[ib_pos + 1];
}
else
{
console.error("Unexpected primitive type " + rnr_data.idxBuff[ib_pos]);
break;
}
}
return psp_ro;
}
//==============================================================================
return EveElements;
});
| ui5/eve7/lib/EveElementsRCore.js | sap.ui.define(['rootui5/eve7/lib/EveManager'], function(EveManager) {
"use strict";
// See also EveScene.js makeGLRepresentation(), there several members are
// set for the top-level Object3D.
//==============================================================================
// EveElemControl
//==============================================================================
function EveElemControl(o3d)
{
// JSROOT.Painter.GeoDrawingControl.call(this);
this.obj3d = o3d;
}
EveElemControl.prototype = Object.create(JSROOT.Painter.GeoDrawingControl.prototype);
EveElemControl.prototype.invokeSceneMethod = function(fname, arg)
{
if ( ! this.obj3d) return false;
var s = this.obj3d.scene;
if (s && (typeof s[fname] == "function"))
return s[fname](this.obj3d, arg, this.event);
return false;
}
EveElemControl.prototype.separateDraw = false;
EveElemControl.prototype.elementHighlighted = function(indx)
{
// default is simple selection, we ignore the indx
this.invokeSceneMethod("processElementHighlighted"); // , indx);
}
EveElemControl.prototype.elementSelected = function(indx)
{
// default is simple selection, we ignore the indx
this.invokeSceneMethod("processElementSelected"); //, indx);
}
//==============================================================================
// EveElements
//==============================================================================
var GL = { POINTS: 0, LINES: 1, LINE_LOOP: 2, LINE_STRIP: 3, TRIANGLES: 4 };
var RC;
function EveElements(rc)
{
console.log("EveElements -- RCore");
RC = rc;
}
//==============================================================================
// makeEveGeometry / makeEveGeoShape
//==============================================================================
EveElements.prototype.makeEveGeometry = function(rnr_data, force)
{
var nVert = rnr_data.idxBuff[1]*3;
if (rnr_data.idxBuff[0] != GL.TRIANGLES) throw "Expect triangles first.";
if (2 + nVert != rnr_data.idxBuff.length) throw "Expect single list of triangles in index buffer.";
var body = new RC.Geometry();
body.vertices = new RC.BufferAttribute( rnr_data.vtxBuff, 3 );
body.indices = new RC.BufferAttribute( rnr_data.idxBuff, 1 );
body.setDrawRange(2, nVert);
body.computeVertexNormalsIdxRange(2, nVert);
// XXXX Fix this. It seems we could have flat shading with usage of simple shaders.
// XXXX Also, we could do edge detect on the server for outlines.
// XXXX a) 3d objects - angle between triangles >= 85 degrees (or something);
// XXXX b) 2d objects - segment only has one triangle.
// XXXX Somewhat orthogonal - when we do tesselation, conversion from quads to
// XXXX triangles is trivial, we could do it before invoking the big guns (if they are even needed).
// XXXX Oh, and once triangulated, we really don't need to store 3 as number of verts in a poly each time.
// XXXX Or do we? We might need it for projection stuff.
return body;
}
EveElements.prototype.makeEveGeoShape = function(egs, rnr_data)
{
var egs_ro = new RC.Group();
var geom = this.makeEveGeometry(rnr_data);
var fcol = new RC.Color(JSROOT.Painter.getColor(egs.fFillColor));
// var material = new RC.MeshPhongMaterial({// side: THREE.DoubleSide,
// depthWrite: false, color:fcol, transparent: true, opacity: 0.2 });
var material = new RC.MeshPhongMaterial;
material.color = fcol;
material.side = 2;
material.depthWrite = false;
material.transparent = true;
material.opacity = 0.2;
var mesh = new RC.Mesh(geom, material);
egs_ro.add(mesh);
return egs_ro;
}
//==============================================================================
// makePolygonSetProjected
//==============================================================================
EveElements.prototype.makePolygonSetProjected = function(psp, rnr_data)
{
var psp_ro = new RC.Group();
var pos_ba = new RC.BufferAttribute( rnr_data.vtxBuff, 3 );
var idx_ba = new RC.BufferAttribute( rnr_data.idxBuff, 1 );
var ib_len = rnr_data.idxBuff.length;
var fcol = new RC.Color(JSROOT.Painter.root_colors[psp.fMainColor]);
var material = new RC.MeshBasicMaterial;
material.color = fcol;
material.side = 2;
material.depthWrite = false;
material.transparent = true;
material.opacity = 0.4;
// XXXXXX Should be Mesh -> Line material ???
let line_mat = new RC.MeshBasicMaterial;
line_mat.color = fcol;
for (var ib_pos = 0; ib_pos < ib_len; )
{
if (rnr_data.idxBuff[ib_pos] == GL.TRIANGLES)
{
var body = new RC.Geometry();
body.vertices = pos_ba;
body.indices = idx_ba;
body.setDrawRange(ib_pos + 2, 3 * rnr_data.idxBuff[ib_pos + 1]);
body.computeVertexNormalsIdxRange(ib_pos + 2, 3 * rnr_data.idxBuff[ib_pos + 1]);
psp_ro.add( new RC.Mesh(body, material) );
ib_pos += 2 + 3 * rnr_data.idxBuff[ib_pos + 1];
}
else if (rnr_data.idxBuff[ib_pos] == GL.LINE_LOOP)
{
let body = new RC.Geometry();
body.vertices = pos_ba;
body.indices = idx_ba;
body.setDrawRange(ib_pos + 2, rnr_data.idxBuff[ib_pos + 1]);
let ll = new RC.Line(body, line_mat);
ll.renderingPrimitive = RC.LINE_LOOP;
psp_ro.add( ll );
ib_pos += 2 + rnr_data.idxBuff[ib_pos + 1];
}
else
{
console.error("Unexpected primitive type " + rnr_data.idxBuff[ib_pos]);
break;
}
}
return psp_ro;
}
//==============================================================================
return EveElements;
});
| Copy hits, tracks, jets from Three version and do first pass to work with RCore.
| ui5/eve7/lib/EveElementsRCore.js | Copy hits, tracks, jets from Three version and do first pass to work with RCore. | <ide><path>i5/eve7/lib/EveElementsRCore.js
<ide> RC = rc;
<ide> }
<ide>
<add> EveElements.prototype.TestRnr = function(name, obj, rnr_data)
<add> {
<add> if (obj && rnr_data && rnr_data.vtxBuff) return false;
<add>
<add> var cnt = this[name] || 0;
<add> if (cnt++ < 5) console.log(name, obj, rnr_data);
<add> this[name] = cnt;
<add> return true;
<add> }
<add>
<add>
<add> //==============================================================================
<add> // makeHit
<add> //==============================================================================
<add>
<add> EveElements.prototype.makeHit = function(hit, rnr_data)
<add> {
<add> if (this.TestRnr("hit", hit, rnr_data)) return null;
<add>
<add> //let hit_size = 8 * rnr_data.fMarkerSize;
<add> //let size = rnr_data.vtxBuff.length / 3;
<add>
<add> let geo = new RC.Geometry();
<add> geo.vertices = new RC.BufferAttribute( rnr_data.vtxBuff, 3 );
<add>
<add> let col = new RC.Color(JSROOT.Painter.root_colors[hit.fMarkerColor]);
<add>
<add> let mat = new RC.MeshBasicMaterial;
<add> mat.color = col;
<add>
<add> let pnts = new RC.Point(geo, mat);
<add>
<add> // mesh.get_ctrl = function() { return new EveElemControl(this); }
<add>
<add> // mesh.highlightScale = 2;
<add> // mesh.material.sizeAttenuation = false;
<add> // mesh.material.size = hit.fMarkerSize;
<add>
<add> return pnts;
<add> }
<add>
<add>
<add> //==============================================================================
<add> // makeTrack
<add> //==============================================================================
<add>
<add> EveElements.prototype.makeTrack = function(track, rnr_data)
<add> {
<add> if (this.TestRnr("track", track, rnr_data)) return null;
<add>
<add> let N = rnr_data.vtxBuff.length/3;
<add> let track_width = track.fLineWidth || 1;
<add> let track_color = JSROOT.Painter.root_colors[track.fLineColor] || "rgb(255,0,255)";
<add>
<add> if (JSROOT.browser.isWin) track_width = 1; // not supported on windows
<add>
<add> let buf = new Float32Array((N-1) * 6), pos = 0;
<add> for (let k=0;k<(N-1);++k) {
<add> buf[pos] = rnr_data.vtxBuff[k*3];
<add> buf[pos+1] = rnr_data.vtxBuff[k*3+1];
<add> buf[pos+2] = rnr_data.vtxBuff[k*3+2];
<add>
<add> let breakTrack = false;
<add> if (rnr_data.idxBuff)
<add> for (let b = 0; b < rnr_data.idxBuff.length; b++) {
<add> if ( (k+1) == rnr_data.idxBuff[b]) {
<add> breakTrack = true;
<add> break;
<add> }
<add> }
<add>
<add> if (breakTrack) {
<add> buf[pos+3] = rnr_data.vtxBuff[k*3];
<add> buf[pos+4] = rnr_data.vtxBuff[k*3+1];
<add> buf[pos+5] = rnr_data.vtxBuff[k*3+2];
<add> } else {
<add> buf[pos+3] = rnr_data.vtxBuff[k*3+3];
<add> buf[pos+4] = rnr_data.vtxBuff[k*3+4];
<add> buf[pos+5] = rnr_data.vtxBuff[k*3+5];
<add> }
<add>
<add> pos+=6;
<add> }
<add>
<add> let style = (track.fLineStyle > 1) ? JSROOT.Painter.root_line_styles[track.fLineStyle] : "",
<add> dash = style ? style.split(",") : [], lineMaterial;
<add>
<add> if (dash && (dash.length > 1)) {
<add> lineMaterial = new RC.MeshBasicMaterial({ color: track_color, linewidth: track_width, dashSize: parseInt(dash[0]), gapSize: parseInt(dash[1]) });
<add> } else {
<add> lineMaterial = new RC.MeshBasicMaterial({ color: track_color, linewidth: track_width });
<add> }
<add>
<add> let geom = new RC.Geometry();
<add> geom.vertices = new RC.BufferAttribute( buf, 3 );
<add>
<add> let line = new RC.Line(geom, lineMaterial);
<add> line.renderingPrimitive = RC.LINES;
<add>
<add> // required for the dashed material
<add> //if (dash && (dash.length > 1))
<add> // line.computeLineDistances();
<add>
<add> //line.hightlightWidthScale = 2;
<add>
<add> line.get_ctrl = function() { return new EveElemControl(this); }
<add>
<add> return line;
<add> }
<add>
<add> //==============================================================================
<add> // makeJet
<add> //==============================================================================
<add>
<add> EveElements.prototype.makeJet = function(jet, rnr_data)
<add> {
<add> if (this.TestRnr("jet", jet, rnr_data)) return null;
<add>
<add> // console.log("make jet ", jet);
<add> // let jet_ro = new RC.Object3D();
<add> let pos_ba = new RC.BufferAttribute( rnr_data.vtxBuff, 3 );
<add> let N = rnr_data.vtxBuff.length / 3;
<add>
<add> let geo_body = new RC.Geometry();
<add> geo_body.vertices = pos_ba;
<add> let idcs = new Uint16Array(3 + 3 * (N - 1)); ///[0, N-1, 1];
<add> idcs[0] = 0; idcs[1] = N-1; idcs[2] = 1;
<add> for (let i = 1; i < N - 1; ++i) {
<add> idcs[3*i] = 0; idcs[3*i + 1] = i; idcs[3*i + 2] = i + 1;
<add> // idcs.push( 0, i, i + 1 );
<add> }
<add> geo_body.indices = new RC.BufferAttribute( idcs, 1 );
<add> geo_body.computeVertexNormals();
<add>
<add> let geo_rim = new RC.Geometry();
<add> geo_rim.vertices = pos_ba;
<add> idcs = new Uint16Array(N-1);
<add> for (let i = 1; i < N; ++i) idcs[i-1] = i;
<add> geo_rim.indices = new RC.BufferAttribute( idcs, 1 );
<add>
<add> let geo_rays = new RC.Geometry();
<add> geo_rays.vertices = pos_ba;
<add> idcs = [];
<add> for (let i = 1; i < N; i += 4)
<add> idcs.push( 0, i );
<add> geo_rays.indices = idcs;
<add>
<add> let mcol = JSROOT.Painter.root_colors[jet.fMainColor];
<add> let lcol = JSROOT.Painter.root_colors[jet.fLineColor];
<add>
<add> let mesh = new RC.Mesh(geo_body, new RC.MeshPhongMaterial({ depthWrite: false, color: mcol, transparent: true, opacity: 0.5, side: RC.DoubleSide }));
<add> let line1 = new RC.Line(geo_rim, new RC.MeshBasicMaterial({ linewidth: 2, color: lcol, transparent: true, opacity: 0.5 }));
<add> let line2 = new RC.Line(geo_rays, new RC.MeshBasicMaterial({ linewidth: 0.5, color: lcol, transparent: true, opacity: 0.5 }));
<add> line2.renderingPrimitive = RC.LINES;
<add>
<add> // jet_ro.add( mesh );
<add> mesh.add( line1 );
<add> mesh.add( line2 );
<add>
<add> mesh.get_ctrl = function() { return new EveElemControl(this); }
<add>
<add> return mesh;
<add> }
<add>
<add> EveElements.prototype.makeJetProjected = function(jet, rnr_data)
<add> {
<add> // JetProjected has 3 or 4 points. 0-th is apex, others are rim.
<add> // Fourth point is only present in RhoZ when jet hits barrel/endcap transition.
<add>
<add> // console.log("makeJetProjected ", jet);
<add>
<add> if (this.TestRnr("jetp", jet, rnr_data)) return null;
<add>
<add>
<add> let pos_ba = new RC.BufferAttribute( rnr_data.vtxBuff, 3 );
<add> let N = rnr_data.vtxBuff.length / 3;
<add>
<add> let geo_body = new RC.Geometry();
<add> geo_body.vertices = pos_ba;
<add> let idcs = new Uint16Array( N > 3 ? 6 : 3);
<add> idcs[0] = 0; idcs[1] = 2; idcs[2] = 1;
<add> if (N > 3) { idcs[3] = 0; idcs[4] = 5; idcs[5] = 2; }
<add> geo_body.indices = new RC.BufferAttribute( idcs, 1 );
<add> geo_body.computeVertexNormals();
<add>
<add> let geo_rim = new RC.Geometry();
<add> geo_rim.vertices = pos_ba;
<add> idcs = new Uint16Array(N-1);
<add> for (let i = 1; i < N; ++i) idcs[i-1] = i;
<add> geo_rim.indices = new RC.BufferAttribute( idcs, 1 );
<add>
<add> let geo_rays = new RC.Geometry();
<add> geo_rays.vertices = pos_ba;
<add> idcs = new Uint16Array(4); // [ 0, 1, 0, N-1 ];
<add> idcs[0] = 0; idcs[1] = 1; idcs[2] = 0; idcs[3] = N-1;
<add> geo_rays.indices = new RC.BufferAttribute( idcs, 1 );;
<add>
<add> let fcol = JSROOT.Painter.root_colors[jet.fFillColor];
<add> let lcol = JSROOT.Painter.root_colors[jet.fLineColor];
<add> // Process transparency !!!
<add> // console.log("cols", fcol, lcol);
<add>
<add> // double-side material required for correct tracing of colors - otherwise points sequence should be changed
<add> let mesh = new RC.Mesh(geo_body, new RC.MeshBasicMaterial({ depthWrite: false, color: fcol, transparent: true, opacity: 0.5, side: RC.DoubleSide }));
<add> let line1 = new RC.Line(geo_rim, new RC.MeshBasicMaterial({ linewidth: 2, color: lcol, transparent: true, opacity: 0.5 }));
<add> let line2 = new RC.Line(geo_rays, new RC.MeshBasicMaterial({ linewidth: 1, color: lcol, transparent: true, opacity: 0.5 }));
<add> line2.renderingPrimitive = RC.LINES;
<add>
<add> // jet_ro.add( mesh );
<add> mesh.add( line1 );
<add> mesh.add( line2 );
<add>
<add> mesh.get_ctrl = function() { return new EveElemControl(this); }
<add>
<add> return mesh;
<add> }
<add>
<ide>
<ide> //==============================================================================
<ide> // makeEveGeometry / makeEveGeoShape
<ide>
<ide> EveElements.prototype.makeEveGeometry = function(rnr_data, force)
<ide> {
<del> var nVert = rnr_data.idxBuff[1]*3;
<add> let nVert = rnr_data.idxBuff[1]*3;
<ide>
<ide> if (rnr_data.idxBuff[0] != GL.TRIANGLES) throw "Expect triangles first.";
<ide> if (2 + nVert != rnr_data.idxBuff.length) throw "Expect single list of triangles in index buffer.";
<ide>
<del> var body = new RC.Geometry();
<add> let body = new RC.Geometry();
<ide> body.vertices = new RC.BufferAttribute( rnr_data.vtxBuff, 3 );
<ide> body.indices = new RC.BufferAttribute( rnr_data.idxBuff, 1 );
<ide> body.setDrawRange(2, nVert);
<ide>
<ide> EveElements.prototype.makeEveGeoShape = function(egs, rnr_data)
<ide> {
<del> var egs_ro = new RC.Group();
<del>
<del> var geom = this.makeEveGeometry(rnr_data);
<del>
<del> var fcol = new RC.Color(JSROOT.Painter.getColor(egs.fFillColor));
<del>
<del> // var material = new RC.MeshPhongMaterial({// side: THREE.DoubleSide,
<add> let egs_ro = new RC.Group();
<add>
<add> let geom = this.makeEveGeometry(rnr_data);
<add>
<add> let fcol = new RC.Color(JSROOT.Painter.getColor(egs.fFillColor));
<add>
<add> // let material = new RC.MeshPhongMaterial({// side: THREE.DoubleSide,
<ide> // depthWrite: false, color:fcol, transparent: true, opacity: 0.2 });
<del> var material = new RC.MeshPhongMaterial;
<add> let material = new RC.MeshPhongMaterial;
<ide> material.color = fcol;
<ide> material.side = 2;
<ide> material.depthWrite = false;
<ide> material.transparent = true;
<ide> material.opacity = 0.2;
<ide>
<del> var mesh = new RC.Mesh(geom, material);
<add> let mesh = new RC.Mesh(geom, material);
<ide>
<ide> egs_ro.add(mesh);
<ide>
<ide>
<ide> EveElements.prototype.makePolygonSetProjected = function(psp, rnr_data)
<ide> {
<del> var psp_ro = new RC.Group();
<del> var pos_ba = new RC.BufferAttribute( rnr_data.vtxBuff, 3 );
<del> var idx_ba = new RC.BufferAttribute( rnr_data.idxBuff, 1 );
<del>
<del> var ib_len = rnr_data.idxBuff.length;
<del>
<del> var fcol = new RC.Color(JSROOT.Painter.root_colors[psp.fMainColor]);
<del>
<del> var material = new RC.MeshBasicMaterial;
<del> material.color = fcol;
<del> material.side = 2;
<del> material.depthWrite = false;
<add> let psp_ro = new RC.Group();
<add> let pos_ba = new RC.BufferAttribute( rnr_data.vtxBuff, 3 );
<add> let idx_ba = new RC.BufferAttribute( rnr_data.idxBuff, 1 );
<add>
<add> let ib_len = rnr_data.idxBuff.length;
<add>
<add> let fcol = new RC.Color(JSROOT.Painter.root_colors[psp.fMainColor]);
<add>
<add> let material = new RC.MeshPhongMaterial;
<add> material.color = fcol;
<add> material.specular = new RC.Color(1, 1, 1);
<add> material.shininess = 50;
<add> material.side = RC.FRONT_AND_BACK_SIDE;
<add> material.depthWrite = false;
<ide> material.transparent = true;
<ide> material.opacity = 0.4;
<add>
<add> console.log("XXXXX", fcol, material);
<ide>
<ide> // XXXXXX Should be Mesh -> Line material ???
<ide> let line_mat = new RC.MeshBasicMaterial;
<ide> line_mat.color = fcol;
<ide>
<del> for (var ib_pos = 0; ib_pos < ib_len; )
<add> for (let ib_pos = 0; ib_pos < ib_len; )
<ide> {
<ide> if (rnr_data.idxBuff[ib_pos] == GL.TRIANGLES)
<ide> {
<del> var body = new RC.Geometry();
<add> let body = new RC.Geometry();
<ide> body.vertices = pos_ba;
<ide> body.indices = idx_ba;
<ide> body.setDrawRange(ib_pos + 2, 3 * rnr_data.idxBuff[ib_pos + 1]); |
|
Java | mit | 37678d80a47a1cc9824e8bd45d632dc49f2bd6f1 | 0 | OreCruncher/DynamicSurroundings,OreCruncher/DynamicSurroundings | /*
* This file is part of Dynamic Surroundings, licensed under the MIT License (MIT).
*
* Copyright (c) OreCruncher
*
* 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 org.blockartistry.DynSurround.client.handlers.scanners;
import org.blockartistry.DynSurround.api.entity.ActionState;
import org.blockartistry.DynSurround.api.entity.IEmojiData;
import org.blockartistry.DynSurround.client.handlers.EnvironStateHandler.EnvironState;
import org.blockartistry.DynSurround.entity.CapabilityEmojiData;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.boss.EntityDragon;
import net.minecraft.entity.boss.EntityWither;
import net.minecraft.entity.monster.EntityGolem;
import net.minecraft.entity.monster.EntityPolarBear;
import net.minecraft.entity.monster.IMob;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.ITickable;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
/*
* Scans the entities in the immediate vicinity to determine if
* a battle is taking place. This does not mean the player is
* being attacked - only that there are entities that are
* fighting nearby.
*/
@SideOnly(Side.CLIENT)
public class BattleScanner implements ITickable {
private static final int BOSS_RANGE = 65536; // 256 block range
private static final int MINI_BOSS_RANGE = 16384; // 128 block range
private static final int MOB_RANGE = 400; // 20 block range
private static final int BATTLE_TIMER_EXPIRY = 10;
protected int battleTimer;
protected boolean inBattle;
protected boolean isWither;
protected boolean isDragon;
protected boolean isBoss;
public void reset() {
this.inBattle = false;
this.isWither = false;
this.isDragon = false;
this.isBoss = false;
}
public boolean inBattle() {
return this.inBattle;
}
public boolean isWither() {
return this.isWither;
}
public boolean isDragon() {
return this.isDragon;
}
public boolean isBoss() {
return this.isBoss;
}
private boolean isApplicableType(final Entity e) {
if (e instanceof EntityLiving) {
if (e instanceof IMob)
return true;
if (e instanceof EntityPlayer)
return true;
if (e instanceof EntityGolem)
return true;
if (e instanceof EntityPolarBear)
return true;
}
return false;
}
@Override
public void update() {
final EntityPlayer player = EnvironState.getPlayer();
final BlockPos playerPos = EnvironState.getPlayerPosition();
final World world = EnvironState.getWorld();
boolean inBattle = false;
boolean isBoss = false;
boolean isDragon = false;
boolean isWither = false;
for (final Entity e : world.getLoadedEntityList()) {
// Invisible things do not trigger as well as the current
// player and team members.
if (e.isInvisible() || e == player || e.isOnSameTeam(player))
continue;
final double dist = e.getDistanceSq(playerPos);
if (dist > BOSS_RANGE)
continue;
if (!e.isNonBoss()) {
if (e instanceof EntityWither) {
inBattle = isWither = isBoss = true;
isDragon = false;
// Wither will override *any* other mob
// so terminate early.
break;
} else if (e instanceof EntityDragon) {
inBattle = isDragon = isBoss = true;
} else if (dist <= MINI_BOSS_RANGE) {
inBattle = isBoss = true;
}
} else if (inBattle || dist > MOB_RANGE) {
// If we are flagged to be in battle or if the normal
// mob is outside of the largest possible range it is
// not a candidate.
continue;
} else if (isApplicableType(e)) {
// Use emoji data to determine if the mob is attacking
final IEmojiData emoji = e.getCapability(CapabilityEmojiData.EMOJI, null);
if (emoji != null) {
final ActionState state = emoji.getActionState();
if (state == ActionState.ATTACKING) {
// Only in battle if the entity sees the player, or the
// player sees the entity
final EntityLiving living = (EntityLiving) e;
if (living.getEntitySenses().canSee(player) || player.canEntityBeSeen(living))
inBattle = true;
}
}
}
}
final int tickCounter = EnvironState.getTickCounter();
if (inBattle) {
this.inBattle = inBattle;
this.isBoss = isBoss;
this.isWither = isWither;
this.isDragon = isDragon;
this.battleTimer = tickCounter + BATTLE_TIMER_EXPIRY;
} else if (this.inBattle && tickCounter > this.battleTimer) {
this.reset();
}
}
}
| src/main/java/org/blockartistry/DynSurround/client/handlers/scanners/BattleScanner.java | /*
* This file is part of Dynamic Surroundings, licensed under the MIT License (MIT).
*
* Copyright (c) OreCruncher
*
* 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 org.blockartistry.DynSurround.client.handlers.scanners;
import org.blockartistry.DynSurround.api.entity.ActionState;
import org.blockartistry.DynSurround.api.entity.IEmojiData;
import org.blockartistry.DynSurround.client.handlers.EnvironStateHandler.EnvironState;
import org.blockartistry.DynSurround.entity.CapabilityEmojiData;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.boss.EntityDragon;
import net.minecraft.entity.boss.EntityWither;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.ITickable;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
/*
* Scans the entities in the immediate vicinity to determine if
* a battle is taking place. This does not mean the player is
* being attacked - only that there are entities that are
* fighting nearby.
*/
@SideOnly(Side.CLIENT)
public class BattleScanner implements ITickable {
private static final int BOSS_RANGE = 65536; // 256 block range
private static final int MINI_BOSS_RANGE = 16384; // 128 block range
private static final int MOB_RANGE = 400; // 20 block range
private static final int BATTLE_TIMER_EXPIRY = 10;
protected int battleTimer;
protected boolean inBattle;
protected boolean isWither;
protected boolean isDragon;
protected boolean isBoss;
public void reset() {
this.inBattle = false;
this.isWither = false;
this.isDragon = false;
this.isBoss = false;
}
public boolean inBattle() {
return this.inBattle;
}
public boolean isWither() {
return this.isWither;
}
public boolean isDragon() {
return this.isDragon;
}
public boolean isBoss() {
return this.isBoss;
}
@Override
public void update() {
final EntityPlayer player = EnvironState.getPlayer();
final BlockPos playerPos = EnvironState.getPlayerPosition();
final World world = EnvironState.getWorld();
boolean inBattle = false;
boolean isBoss = false;
boolean isDragon = false;
boolean isWither = false;
for (final Entity e : world.getLoadedEntityList()) {
// Invisible things do not trigger as well as the current
// player and team members.
if (e.isInvisible() || e == player || e.isOnSameTeam(player))
continue;
final double dist = e.getDistanceSq(playerPos);
if (dist > BOSS_RANGE)
continue;
if (!e.isNonBoss()) {
if (e instanceof EntityWither) {
inBattle = isWither = isBoss = true;
isDragon = false;
// Wither will override *any* other mob
// so terminate early.
break;
} else if (e instanceof EntityDragon) {
inBattle = isDragon = isBoss = true;
} else if (dist <= MINI_BOSS_RANGE) {
inBattle = isBoss = true;
}
} else if (inBattle || dist > MOB_RANGE) {
// If we are flagged to be in battle or if the normal
// mob is outside of the largest possible range it is
// not a candidate.
continue;
} else if (e instanceof EntityLiving) {
final EntityLiving living = (EntityLiving) e;
// Use emoji data to determine if the mob is attacking
final IEmojiData emoji = living.getCapability(CapabilityEmojiData.EMOJI, null);
if (emoji != null) {
final ActionState state = emoji.getActionState();
if (state == ActionState.ATTACKING) {
// Only in battle if the entity sees the player, or the
// player sees the entity
if (living.getEntitySenses().canSee(player) || player.canEntityBeSeen(living))
inBattle = true;
}
}
}
}
final int tickCounter = EnvironState.getTickCounter();
if (inBattle) {
this.inBattle = inBattle;
this.isBoss = isBoss;
this.isWither = isWither;
this.isDragon = isDragon;
this.battleTimer = tickCounter + BATTLE_TIMER_EXPIRY;
} else if (this.inBattle && tickCounter > this.battleTimer) {
this.reset();
}
}
}
| [#190] Refine entity candidates by type for battle music
| src/main/java/org/blockartistry/DynSurround/client/handlers/scanners/BattleScanner.java | [#190] Refine entity candidates by type for battle music | <ide><path>rc/main/java/org/blockartistry/DynSurround/client/handlers/scanners/BattleScanner.java
<ide> import net.minecraft.entity.EntityLiving;
<ide> import net.minecraft.entity.boss.EntityDragon;
<ide> import net.minecraft.entity.boss.EntityWither;
<add>import net.minecraft.entity.monster.EntityGolem;
<add>import net.minecraft.entity.monster.EntityPolarBear;
<add>import net.minecraft.entity.monster.IMob;
<ide> import net.minecraft.entity.player.EntityPlayer;
<ide> import net.minecraft.util.ITickable;
<ide> import net.minecraft.util.math.BlockPos;
<ide> return this.isBoss;
<ide> }
<ide>
<add> private boolean isApplicableType(final Entity e) {
<add> if (e instanceof EntityLiving) {
<add> if (e instanceof IMob)
<add> return true;
<add> if (e instanceof EntityPlayer)
<add> return true;
<add> if (e instanceof EntityGolem)
<add> return true;
<add> if (e instanceof EntityPolarBear)
<add> return true;
<add> }
<add> return false;
<add> }
<add>
<ide> @Override
<ide> public void update() {
<ide>
<ide> // mob is outside of the largest possible range it is
<ide> // not a candidate.
<ide> continue;
<del> } else if (e instanceof EntityLiving) {
<del> final EntityLiving living = (EntityLiving) e;
<add> } else if (isApplicableType(e)) {
<ide> // Use emoji data to determine if the mob is attacking
<del> final IEmojiData emoji = living.getCapability(CapabilityEmojiData.EMOJI, null);
<add> final IEmojiData emoji = e.getCapability(CapabilityEmojiData.EMOJI, null);
<ide> if (emoji != null) {
<ide> final ActionState state = emoji.getActionState();
<ide> if (state == ActionState.ATTACKING) {
<ide> // Only in battle if the entity sees the player, or the
<ide> // player sees the entity
<add> final EntityLiving living = (EntityLiving) e;
<ide> if (living.getEntitySenses().canSee(player) || player.canEntityBeSeen(living))
<ide> inBattle = true;
<ide> } |
|
JavaScript | mit | 80c754760212b8d4d9bc43ae9403fe5dfe20bce5 | 0 | makenew/tasty-brunch,rxlabs/tasty-todos,rxlabs/tasty-todos,makenew/tasty-brunch,rxlabs/tasty-todos,makenew/tasty-brunch | const fs = require('fs')
const gitRevSync = require('git-rev-sync')
const gulp = require('gulp')
const ghPages = require('gulp-gh-pages')
const htmlhint = require('gulp-htmlhint')
const htmlmin = require('gulp-htmlmin')
const plumber = require('gulp-plumber')
const sassLint = require('gulp-sass-lint')
const standard = require('gulp-standard')
const watch = require('gulp-watch')
const pkg = require('./package.json')
gulp.task('default', ['lint', 'watch'])
gulp.task('lint', ['standard', 'sass-lint'])
gulp.task('htmlhint', () => {
return gulp.src('public/**/*.html')
.pipe(htmlhint())
.pipe(htmlhint.failReporter())
})
gulp.task('standard', () => {
return gulp.src('app/**/*.js')
.pipe(standard())
.pipe(standard.reporter('default', {
breakOnError: true
}));
})
gulp.task('sass-lint', () => {
return gulp.src('app/**/*.scss')
.pipe(sassLint())
.pipe(sassLint.format())
.pipe(sassLint.failOnError());
})
gulp.task('watch', () => {
gulp.src('public/**/*.html')
.pipe(watch('public/**/*.html'))
.pipe(plumber())
.pipe(htmlhint())
.pipe(htmlhint.reporter())
gulp.src('app/**/*.js')
.pipe(watch('app/**/*.js'))
.pipe(plumber())
.pipe(standard())
.pipe(standard.reporter('default'))
return gulp.src('app/*/**/.scss')
.pipe(watch('app/**/*.scss'))
.pipe(plumber())
.pipe(sassLint())
.pipe(sassLint.format());
})
gulp.task('minify', () => {
return gulp.src('public/**/*.html')
.pipe(htmlmin({
collapseWhitespace: true,
preserveLineBreaks: true,
minifyJS: true
}))
.pipe(gulp.dest('public'))
})
gulp.task('deploy', () => {
fs.openSync('public/.nojekyll', 'w')
return gulp.src(['public/.nojekyll', 'public/**/*'])
.pipe(ghPages({
remoteUrl: `[email protected]:${pkg.repository}.git`,
message: `Deploy ${gitRevSync.short()} from v${pkg.version}`
}));
})
| gulpfile.js | const fs = require('fs')
const gitRevSync = require('git-rev-sync')
const gulp = require('gulp')
const ghPages = require('gulp-gh-pages')
const htmlhint = require('gulp-htmlhint')
const htmlmin = require('gulp-htmlmin')
const plumber = require('gulp-plumber')
const sassLint = require('gulp-sass-lint')
const standard = require('gulp-standard')
const watch = require('gulp-watch')
const pkg = require('./package.json')
gulp.task('default', ['lint', 'watch'])
gulp.task('lint', ['standard', 'sass-lint'])
gulp.task('htmlhint', () => {
return gulp.src('public/**/*.html')
.pipe(htmlhint())
.pipe(htmlhint.failReporter())
})
gulp.task('standard', () => {
return gulp.src('app/**/*.js')
.pipe(standard())
.pipe(standard.reporter('default', {
breakOnError: true
}));
})
gulp.task('sass-lint', () => {
return gulp.src('app/**/*.scss')
.pipe(sassLint())
.pipe(sassLint.format())
.pipe(sassLint.failOnError());
})
gulp.task('watch', () => {
gulp.src('public')
.pipe(watch('public/**/*.html'))
.pipe(plumber())
.pipe(htmlhint())
.pipe(htmlhint.reporter())
gulp.src('app')
.pipe(watch('app/**/*.js'))
.pipe(plumber())
.pipe(standard())
.pipe(standard.reporter('default'))
return gulp.src('app')
.pipe(watch('app/**/*.scss'))
.pipe(plumber())
.pipe(sassLint())
.pipe(sassLint.format());
})
gulp.task('minify', () => {
return gulp.src('public/**/*.html')
.pipe(htmlmin({
collapseWhitespace: true,
preserveLineBreaks: true,
minifyJS: true
}))
.pipe(gulp.dest('public'))
})
gulp.task('deploy', () => {
fs.openSync('public/.nojekyll', 'w')
return gulp.src(['public/.nojekyll', 'public/**/*'])
.pipe(ghPages({
remoteUrl: `[email protected]:${pkg.repository}.git`,
message: `Deploy ${gitRevSync.short()} from v${pkg.version}`
}));
})
| Use more specific watch globs
| gulpfile.js | Use more specific watch globs | <ide><path>ulpfile.js
<ide> })
<ide>
<ide> gulp.task('watch', () => {
<del> gulp.src('public')
<add> gulp.src('public/**/*.html')
<ide> .pipe(watch('public/**/*.html'))
<ide> .pipe(plumber())
<ide> .pipe(htmlhint())
<ide> .pipe(htmlhint.reporter())
<ide>
<del> gulp.src('app')
<add> gulp.src('app/**/*.js')
<ide> .pipe(watch('app/**/*.js'))
<ide> .pipe(plumber())
<ide> .pipe(standard())
<ide> .pipe(standard.reporter('default'))
<ide>
<del> return gulp.src('app')
<add> return gulp.src('app/*/**/.scss')
<ide> .pipe(watch('app/**/*.scss'))
<ide> .pipe(plumber())
<ide> .pipe(sassLint()) |
|
Java | apache-2.0 | 64cd4383adceab12a5467869b78059f0935610d4 | 0 | androidx/media,stari4ek/ExoPlayer,ened/ExoPlayer,amzn/exoplayer-amazon-port,stari4ek/ExoPlayer,androidx/media,amzn/exoplayer-amazon-port,google/ExoPlayer,google/ExoPlayer,ened/ExoPlayer,androidx/media,google/ExoPlayer,stari4ek/ExoPlayer,amzn/exoplayer-amazon-port,ened/ExoPlayer | /*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.exoplayer2.trackselection;
import androidx.annotation.Nullable;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.Format;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.source.TrackGroup;
import com.google.android.exoplayer2.source.chunk.MediaChunk;
import com.google.android.exoplayer2.source.chunk.MediaChunkIterator;
import com.google.android.exoplayer2.upstream.BandwidthMeter;
import com.google.android.exoplayer2.util.Assertions;
import com.google.android.exoplayer2.util.Clock;
import com.google.android.exoplayer2.util.Util;
import java.util.ArrayList;
import java.util.List;
import org.checkerframework.checker.nullness.compatqual.NullableType;
/**
* A bandwidth based adaptive {@link TrackSelection}, whose selected track is updated to be the one
* of highest quality given the current network conditions and the state of the buffer.
*/
public class AdaptiveTrackSelection extends BaseTrackSelection {
/** Factory for {@link AdaptiveTrackSelection} instances. */
public static class Factory implements TrackSelection.Factory {
@Nullable private final BandwidthMeter bandwidthMeter;
private final int minDurationForQualityIncreaseMs;
private final int maxDurationForQualityDecreaseMs;
private final int minDurationToRetainAfterDiscardMs;
private final float bandwidthFraction;
private final float bufferedFractionToLiveEdgeForQualityIncrease;
private final long minTimeBetweenBufferReevaluationMs;
private final Clock clock;
/** Creates an adaptive track selection factory with default parameters. */
public Factory() {
this(
DEFAULT_MIN_DURATION_FOR_QUALITY_INCREASE_MS,
DEFAULT_MAX_DURATION_FOR_QUALITY_DECREASE_MS,
DEFAULT_MIN_DURATION_TO_RETAIN_AFTER_DISCARD_MS,
DEFAULT_BANDWIDTH_FRACTION,
DEFAULT_BUFFERED_FRACTION_TO_LIVE_EDGE_FOR_QUALITY_INCREASE,
DEFAULT_MIN_TIME_BETWEEN_BUFFER_REEVALUTATION_MS,
Clock.DEFAULT);
}
/**
* @deprecated Use {@link #Factory()} instead. Custom bandwidth meter should be directly passed
* to the player in {@link SimpleExoPlayer.Builder}.
*/
@Deprecated
@SuppressWarnings("deprecation")
public Factory(BandwidthMeter bandwidthMeter) {
this(
bandwidthMeter,
DEFAULT_MIN_DURATION_FOR_QUALITY_INCREASE_MS,
DEFAULT_MAX_DURATION_FOR_QUALITY_DECREASE_MS,
DEFAULT_MIN_DURATION_TO_RETAIN_AFTER_DISCARD_MS,
DEFAULT_BANDWIDTH_FRACTION,
DEFAULT_BUFFERED_FRACTION_TO_LIVE_EDGE_FOR_QUALITY_INCREASE,
DEFAULT_MIN_TIME_BETWEEN_BUFFER_REEVALUTATION_MS,
Clock.DEFAULT);
}
/**
* Creates an adaptive track selection factory.
*
* @param minDurationForQualityIncreaseMs The minimum duration of buffered data required for the
* selected track to switch to one of higher quality.
* @param maxDurationForQualityDecreaseMs The maximum duration of buffered data required for the
* selected track to switch to one of lower quality.
* @param minDurationToRetainAfterDiscardMs When switching to a track of significantly higher
* quality, the selection may indicate that media already buffered at the lower quality can
* be discarded to speed up the switch. This is the minimum duration of media that must be
* retained at the lower quality.
* @param bandwidthFraction The fraction of the available bandwidth that the selection should
* consider available for use. Setting to a value less than 1 is recommended to account for
* inaccuracies in the bandwidth estimator.
*/
public Factory(
int minDurationForQualityIncreaseMs,
int maxDurationForQualityDecreaseMs,
int minDurationToRetainAfterDiscardMs,
float bandwidthFraction) {
this(
minDurationForQualityIncreaseMs,
maxDurationForQualityDecreaseMs,
minDurationToRetainAfterDiscardMs,
bandwidthFraction,
DEFAULT_BUFFERED_FRACTION_TO_LIVE_EDGE_FOR_QUALITY_INCREASE,
DEFAULT_MIN_TIME_BETWEEN_BUFFER_REEVALUTATION_MS,
Clock.DEFAULT);
}
/**
* @deprecated Use {@link #Factory(int, int, int, float)} instead. Custom bandwidth meter should
* be directly passed to the player in {@link SimpleExoPlayer.Builder}.
*/
@Deprecated
@SuppressWarnings("deprecation")
public Factory(
BandwidthMeter bandwidthMeter,
int minDurationForQualityIncreaseMs,
int maxDurationForQualityDecreaseMs,
int minDurationToRetainAfterDiscardMs,
float bandwidthFraction) {
this(
bandwidthMeter,
minDurationForQualityIncreaseMs,
maxDurationForQualityDecreaseMs,
minDurationToRetainAfterDiscardMs,
bandwidthFraction,
DEFAULT_BUFFERED_FRACTION_TO_LIVE_EDGE_FOR_QUALITY_INCREASE,
DEFAULT_MIN_TIME_BETWEEN_BUFFER_REEVALUTATION_MS,
Clock.DEFAULT);
}
/**
* Creates an adaptive track selection factory.
*
* @param minDurationForQualityIncreaseMs The minimum duration of buffered data required for the
* selected track to switch to one of higher quality.
* @param maxDurationForQualityDecreaseMs The maximum duration of buffered data required for the
* selected track to switch to one of lower quality.
* @param minDurationToRetainAfterDiscardMs When switching to a track of significantly higher
* quality, the selection may indicate that media already buffered at the lower quality can
* be discarded to speed up the switch. This is the minimum duration of media that must be
* retained at the lower quality.
* @param bandwidthFraction The fraction of the available bandwidth that the selection should
* consider available for use. Setting to a value less than 1 is recommended to account for
* inaccuracies in the bandwidth estimator.
* @param bufferedFractionToLiveEdgeForQualityIncrease For live streaming, the fraction of the
* duration from current playback position to the live edge that has to be buffered before
* the selected track can be switched to one of higher quality. This parameter is only
* applied when the playback position is closer to the live edge than {@code
* minDurationForQualityIncreaseMs}, which would otherwise prevent switching to a higher
* quality from happening.
* @param minTimeBetweenBufferReevaluationMs The track selection may periodically reevaluate its
* buffer and discard some chunks of lower quality to improve the playback quality if
* network conditions have changed. This is the minimum duration between 2 consecutive
* buffer reevaluation calls.
* @param clock A {@link Clock}.
*/
@SuppressWarnings("deprecation")
public Factory(
int minDurationForQualityIncreaseMs,
int maxDurationForQualityDecreaseMs,
int minDurationToRetainAfterDiscardMs,
float bandwidthFraction,
float bufferedFractionToLiveEdgeForQualityIncrease,
long minTimeBetweenBufferReevaluationMs,
Clock clock) {
this(
/* bandwidthMeter= */ null,
minDurationForQualityIncreaseMs,
maxDurationForQualityDecreaseMs,
minDurationToRetainAfterDiscardMs,
bandwidthFraction,
bufferedFractionToLiveEdgeForQualityIncrease,
minTimeBetweenBufferReevaluationMs,
clock);
}
/**
* @deprecated Use {@link #Factory(int, int, int, float, float, long, Clock)} instead. Custom
* bandwidth meter should be directly passed to the player in {@link
* SimpleExoPlayer.Builder}.
*/
@Deprecated
public Factory(
@Nullable BandwidthMeter bandwidthMeter,
int minDurationForQualityIncreaseMs,
int maxDurationForQualityDecreaseMs,
int minDurationToRetainAfterDiscardMs,
float bandwidthFraction,
float bufferedFractionToLiveEdgeForQualityIncrease,
long minTimeBetweenBufferReevaluationMs,
Clock clock) {
this.bandwidthMeter = bandwidthMeter;
this.minDurationForQualityIncreaseMs = minDurationForQualityIncreaseMs;
this.maxDurationForQualityDecreaseMs = maxDurationForQualityDecreaseMs;
this.minDurationToRetainAfterDiscardMs = minDurationToRetainAfterDiscardMs;
this.bandwidthFraction = bandwidthFraction;
this.bufferedFractionToLiveEdgeForQualityIncrease =
bufferedFractionToLiveEdgeForQualityIncrease;
this.minTimeBetweenBufferReevaluationMs = minTimeBetweenBufferReevaluationMs;
this.clock = clock;
}
@Override
public final @NullableType TrackSelection[] createTrackSelections(
@NullableType Definition[] definitions, BandwidthMeter bandwidthMeter) {
if (this.bandwidthMeter != null) {
bandwidthMeter = this.bandwidthMeter;
}
TrackSelection[] selections = new TrackSelection[definitions.length];
int totalFixedBandwidth = 0;
for (int i = 0; i < definitions.length; i++) {
Definition definition = definitions[i];
if (definition != null && definition.tracks.length == 1) {
// Make fixed selections first to know their total bandwidth.
selections[i] =
new FixedTrackSelection(
definition.group, definition.tracks[0], definition.reason, definition.data);
int trackBitrate = definition.group.getFormat(definition.tracks[0]).bitrate;
if (trackBitrate != Format.NO_VALUE) {
totalFixedBandwidth += trackBitrate;
}
}
}
List<AdaptiveTrackSelection> adaptiveSelections = new ArrayList<>();
for (int i = 0; i < definitions.length; i++) {
Definition definition = definitions[i];
if (definition != null && definition.tracks.length > 1) {
AdaptiveTrackSelection adaptiveSelection =
createAdaptiveTrackSelection(
definition.group, bandwidthMeter, definition.tracks, totalFixedBandwidth);
adaptiveSelections.add(adaptiveSelection);
selections[i] = adaptiveSelection;
}
}
if (adaptiveSelections.size() > 1) {
long[][] adaptiveTrackBitrates = new long[adaptiveSelections.size()][];
for (int i = 0; i < adaptiveSelections.size(); i++) {
AdaptiveTrackSelection adaptiveSelection = adaptiveSelections.get(i);
adaptiveTrackBitrates[i] = new long[adaptiveSelection.length()];
for (int j = 0; j < adaptiveSelection.length(); j++) {
adaptiveTrackBitrates[i][j] =
adaptiveSelection.getFormat(adaptiveSelection.length() - j - 1).bitrate;
}
}
long[][][] bandwidthCheckpoints = getAllocationCheckpoints(adaptiveTrackBitrates);
for (int i = 0; i < adaptiveSelections.size(); i++) {
adaptiveSelections
.get(i)
.experimental_setBandwidthAllocationCheckpoints(bandwidthCheckpoints[i]);
}
}
return selections;
}
/**
* Creates a single adaptive selection for the given group, bandwidth meter and tracks.
*
* @param group The {@link TrackGroup}.
* @param bandwidthMeter A {@link BandwidthMeter} which can be used to select tracks.
* @param tracks The indices of the selected tracks in the track group.
* @param totalFixedTrackBandwidth The total bandwidth used by all non-adaptive tracks, in bits
* per second.
* @return An {@link AdaptiveTrackSelection} for the specified tracks.
*/
protected AdaptiveTrackSelection createAdaptiveTrackSelection(
TrackGroup group,
BandwidthMeter bandwidthMeter,
int[] tracks,
int totalFixedTrackBandwidth) {
return new AdaptiveTrackSelection(
group,
tracks,
new DefaultBandwidthProvider(bandwidthMeter, bandwidthFraction, totalFixedTrackBandwidth),
minDurationForQualityIncreaseMs,
maxDurationForQualityDecreaseMs,
minDurationToRetainAfterDiscardMs,
bufferedFractionToLiveEdgeForQualityIncrease,
minTimeBetweenBufferReevaluationMs,
clock);
}
}
public static final int DEFAULT_MIN_DURATION_FOR_QUALITY_INCREASE_MS = 10000;
public static final int DEFAULT_MAX_DURATION_FOR_QUALITY_DECREASE_MS = 25000;
public static final int DEFAULT_MIN_DURATION_TO_RETAIN_AFTER_DISCARD_MS = 25000;
public static final float DEFAULT_BANDWIDTH_FRACTION = 0.7f;
public static final float DEFAULT_BUFFERED_FRACTION_TO_LIVE_EDGE_FOR_QUALITY_INCREASE = 0.75f;
public static final long DEFAULT_MIN_TIME_BETWEEN_BUFFER_REEVALUTATION_MS = 2000;
private final BandwidthProvider bandwidthProvider;
private final long minDurationForQualityIncreaseUs;
private final long maxDurationForQualityDecreaseUs;
private final long minDurationToRetainAfterDiscardUs;
private final float bufferedFractionToLiveEdgeForQualityIncrease;
private final long minTimeBetweenBufferReevaluationMs;
private final Clock clock;
private float playbackSpeed;
private int selectedIndex;
private int reason;
private long lastBufferEvaluationMs;
/**
* @param group The {@link TrackGroup}.
* @param tracks The indices of the selected tracks within the {@link TrackGroup}. Must not be
* empty. May be in any order.
* @param bandwidthMeter Provides an estimate of the currently available bandwidth.
*/
public AdaptiveTrackSelection(TrackGroup group, int[] tracks,
BandwidthMeter bandwidthMeter) {
this(
group,
tracks,
bandwidthMeter,
/* reservedBandwidth= */ 0,
DEFAULT_MIN_DURATION_FOR_QUALITY_INCREASE_MS,
DEFAULT_MAX_DURATION_FOR_QUALITY_DECREASE_MS,
DEFAULT_MIN_DURATION_TO_RETAIN_AFTER_DISCARD_MS,
DEFAULT_BANDWIDTH_FRACTION,
DEFAULT_BUFFERED_FRACTION_TO_LIVE_EDGE_FOR_QUALITY_INCREASE,
DEFAULT_MIN_TIME_BETWEEN_BUFFER_REEVALUTATION_MS,
Clock.DEFAULT);
}
/**
* @param group The {@link TrackGroup}.
* @param tracks The indices of the selected tracks within the {@link TrackGroup}. Must not be
* empty. May be in any order.
* @param bandwidthMeter Provides an estimate of the currently available bandwidth.
* @param reservedBandwidth The reserved bandwidth, which shouldn't be considered available for
* use, in bits per second.
* @param minDurationForQualityIncreaseMs The minimum duration of buffered data required for the
* selected track to switch to one of higher quality.
* @param maxDurationForQualityDecreaseMs The maximum duration of buffered data required for the
* selected track to switch to one of lower quality.
* @param minDurationToRetainAfterDiscardMs When switching to a track of significantly higher
* quality, the selection may indicate that media already buffered at the lower quality can be
* discarded to speed up the switch. This is the minimum duration of media that must be
* retained at the lower quality.
* @param bandwidthFraction The fraction of the available bandwidth that the selection should
* consider available for use. Setting to a value less than 1 is recommended to account for
* inaccuracies in the bandwidth estimator.
* @param bufferedFractionToLiveEdgeForQualityIncrease For live streaming, the fraction of the
* duration from current playback position to the live edge that has to be buffered before the
* selected track can be switched to one of higher quality. This parameter is only applied
* when the playback position is closer to the live edge than {@code
* minDurationForQualityIncreaseMs}, which would otherwise prevent switching to a higher
* quality from happening.
* @param minTimeBetweenBufferReevaluationMs The track selection may periodically reevaluate its
* buffer and discard some chunks of lower quality to improve the playback quality if network
* condition has changed. This is the minimum duration between 2 consecutive buffer
* reevaluation calls.
*/
public AdaptiveTrackSelection(
TrackGroup group,
int[] tracks,
BandwidthMeter bandwidthMeter,
long reservedBandwidth,
long minDurationForQualityIncreaseMs,
long maxDurationForQualityDecreaseMs,
long minDurationToRetainAfterDiscardMs,
float bandwidthFraction,
float bufferedFractionToLiveEdgeForQualityIncrease,
long minTimeBetweenBufferReevaluationMs,
Clock clock) {
this(
group,
tracks,
new DefaultBandwidthProvider(bandwidthMeter, bandwidthFraction, reservedBandwidth),
minDurationForQualityIncreaseMs,
maxDurationForQualityDecreaseMs,
minDurationToRetainAfterDiscardMs,
bufferedFractionToLiveEdgeForQualityIncrease,
minTimeBetweenBufferReevaluationMs,
clock);
}
private AdaptiveTrackSelection(
TrackGroup group,
int[] tracks,
BandwidthProvider bandwidthProvider,
long minDurationForQualityIncreaseMs,
long maxDurationForQualityDecreaseMs,
long minDurationToRetainAfterDiscardMs,
float bufferedFractionToLiveEdgeForQualityIncrease,
long minTimeBetweenBufferReevaluationMs,
Clock clock) {
super(group, tracks);
this.bandwidthProvider = bandwidthProvider;
this.minDurationForQualityIncreaseUs = minDurationForQualityIncreaseMs * 1000L;
this.maxDurationForQualityDecreaseUs = maxDurationForQualityDecreaseMs * 1000L;
this.minDurationToRetainAfterDiscardUs = minDurationToRetainAfterDiscardMs * 1000L;
this.bufferedFractionToLiveEdgeForQualityIncrease =
bufferedFractionToLiveEdgeForQualityIncrease;
this.minTimeBetweenBufferReevaluationMs = minTimeBetweenBufferReevaluationMs;
this.clock = clock;
playbackSpeed = 1f;
reason = C.SELECTION_REASON_UNKNOWN;
lastBufferEvaluationMs = C.TIME_UNSET;
}
/**
* Sets checkpoints to determine the allocation bandwidth based on the total bandwidth.
*
* @param allocationCheckpoints List of checkpoints. Each element must be a long[2], with [0]
* being the total bandwidth and [1] being the allocated bandwidth.
*/
public void experimental_setBandwidthAllocationCheckpoints(long[][] allocationCheckpoints) {
((DefaultBandwidthProvider) bandwidthProvider)
.experimental_setBandwidthAllocationCheckpoints(allocationCheckpoints);
}
@Override
public void enable() {
lastBufferEvaluationMs = C.TIME_UNSET;
}
@Override
public void onPlaybackSpeed(float playbackSpeed) {
this.playbackSpeed = playbackSpeed;
}
@Override
public void updateSelectedTrack(
long playbackPositionUs,
long bufferedDurationUs,
long availableDurationUs,
List<? extends MediaChunk> queue,
MediaChunkIterator[] mediaChunkIterators) {
long nowMs = clock.elapsedRealtime();
// Make initial selection
if (reason == C.SELECTION_REASON_UNKNOWN) {
reason = C.SELECTION_REASON_INITIAL;
selectedIndex = determineIdealSelectedIndex(nowMs);
return;
}
// Stash the current selection, then make a new one.
int currentSelectedIndex = selectedIndex;
selectedIndex = determineIdealSelectedIndex(nowMs);
if (selectedIndex == currentSelectedIndex) {
return;
}
if (!isBlacklisted(currentSelectedIndex, nowMs)) {
// Revert back to the current selection if conditions are not suitable for switching.
Format currentFormat = getFormat(currentSelectedIndex);
Format selectedFormat = getFormat(selectedIndex);
if (selectedFormat.bitrate > currentFormat.bitrate
&& bufferedDurationUs < minDurationForQualityIncreaseUs(availableDurationUs)) {
// The selected track is a higher quality, but we have insufficient buffer to safely switch
// up. Defer switching up for now.
selectedIndex = currentSelectedIndex;
} else if (selectedFormat.bitrate < currentFormat.bitrate
&& bufferedDurationUs >= maxDurationForQualityDecreaseUs) {
// The selected track is a lower quality, but we have sufficient buffer to defer switching
// down for now.
selectedIndex = currentSelectedIndex;
}
}
// If we adapted, update the trigger.
if (selectedIndex != currentSelectedIndex) {
reason = C.SELECTION_REASON_ADAPTIVE;
}
}
@Override
public int getSelectedIndex() {
return selectedIndex;
}
@Override
public int getSelectionReason() {
return reason;
}
@Override
@Nullable
public Object getSelectionData() {
return null;
}
@Override
public int evaluateQueueSize(long playbackPositionUs, List<? extends MediaChunk> queue) {
long nowMs = clock.elapsedRealtime();
if (!shouldEvaluateQueueSize(nowMs)) {
return queue.size();
}
lastBufferEvaluationMs = nowMs;
if (queue.isEmpty()) {
return 0;
}
int queueSize = queue.size();
MediaChunk lastChunk = queue.get(queueSize - 1);
long playoutBufferedDurationBeforeLastChunkUs =
Util.getPlayoutDurationForMediaDuration(
lastChunk.startTimeUs - playbackPositionUs, playbackSpeed);
long minDurationToRetainAfterDiscardUs = getMinDurationToRetainAfterDiscardUs();
if (playoutBufferedDurationBeforeLastChunkUs < minDurationToRetainAfterDiscardUs) {
return queueSize;
}
int idealSelectedIndex = determineIdealSelectedIndex(nowMs);
Format idealFormat = getFormat(idealSelectedIndex);
// If the chunks contain video, discard from the first SD chunk beyond
// minDurationToRetainAfterDiscardUs whose resolution and bitrate are both lower than the ideal
// track.
for (int i = 0; i < queueSize; i++) {
MediaChunk chunk = queue.get(i);
Format format = chunk.trackFormat;
long mediaDurationBeforeThisChunkUs = chunk.startTimeUs - playbackPositionUs;
long playoutDurationBeforeThisChunkUs =
Util.getPlayoutDurationForMediaDuration(mediaDurationBeforeThisChunkUs, playbackSpeed);
if (playoutDurationBeforeThisChunkUs >= minDurationToRetainAfterDiscardUs
&& format.bitrate < idealFormat.bitrate
&& format.height != Format.NO_VALUE && format.height < 720
&& format.width != Format.NO_VALUE && format.width < 1280
&& format.height < idealFormat.height) {
return i;
}
}
return queueSize;
}
/**
* Called when updating the selected track to determine whether a candidate track can be selected.
*
* @param format The {@link Format} of the candidate track.
* @param trackBitrate The estimated bitrate of the track. May differ from {@link Format#bitrate}
* if a more accurate estimate of the current track bitrate is available.
* @param playbackSpeed The current playback speed.
* @param effectiveBitrate The bitrate available to this selection.
* @return Whether this {@link Format} can be selected.
*/
@SuppressWarnings("unused")
protected boolean canSelectFormat(
Format format, int trackBitrate, float playbackSpeed, long effectiveBitrate) {
boolean isNonIframeOnly = (format.roleFlags & C.ROLE_FLAG_TRICK_PLAY) == 0;
boolean canSelect = Math.round(trackBitrate * playbackSpeed) <= effectiveBitrate;
return canSelect && isNonIframeOnly; // Default is not to use the IDR only tracks in selection
}
/**
* Called from {@link #evaluateQueueSize(long, List)} to determine whether an evaluation should be
* performed.
*
* @param nowMs The current value of {@link Clock#elapsedRealtime()}.
* @return Whether an evaluation should be performed.
*/
protected boolean shouldEvaluateQueueSize(long nowMs) {
return lastBufferEvaluationMs == C.TIME_UNSET
|| nowMs - lastBufferEvaluationMs >= minTimeBetweenBufferReevaluationMs;
}
/**
* Called from {@link #evaluateQueueSize(long, List)} to determine the minimum duration of buffer
* to retain after discarding chunks.
*
* @return The minimum duration of buffer to retain after discarding chunks, in microseconds.
*/
protected long getMinDurationToRetainAfterDiscardUs() {
return minDurationToRetainAfterDiscardUs;
}
/**
* Computes the ideal selected index ignoring buffer health.
*
* @param nowMs The current time in the timebase of {@link Clock#elapsedRealtime()}, or {@link
* Long#MIN_VALUE} to ignore blacklisting.
*/
private int determineIdealSelectedIndex(long nowMs) {
long effectiveBitrate = bandwidthProvider.getAllocatedBandwidth();
int lowestBitrateNonBlacklistedIndex = 0;
for (int i = 0; i < length; i++) {
if (nowMs == Long.MIN_VALUE || !isBlacklisted(i, nowMs)) {
Format format = getFormat(i);
if (canSelectFormat(format, format.bitrate, playbackSpeed, effectiveBitrate)) {
return i;
} else {
lowestBitrateNonBlacklistedIndex = i;
}
}
}
return lowestBitrateNonBlacklistedIndex;
}
private long minDurationForQualityIncreaseUs(long availableDurationUs) {
boolean isAvailableDurationTooShort = availableDurationUs != C.TIME_UNSET
&& availableDurationUs <= minDurationForQualityIncreaseUs;
return isAvailableDurationTooShort
? (long) (availableDurationUs * bufferedFractionToLiveEdgeForQualityIncrease)
: minDurationForQualityIncreaseUs;
}
/** Provides the allocated bandwidth. */
private interface BandwidthProvider {
/** Returns the allocated bitrate. */
long getAllocatedBandwidth();
}
private static final class DefaultBandwidthProvider implements BandwidthProvider {
private final BandwidthMeter bandwidthMeter;
private final float bandwidthFraction;
private final long reservedBandwidth;
@Nullable private long[][] allocationCheckpoints;
/* package */ DefaultBandwidthProvider(
BandwidthMeter bandwidthMeter, float bandwidthFraction, long reservedBandwidth) {
this.bandwidthMeter = bandwidthMeter;
this.bandwidthFraction = bandwidthFraction;
this.reservedBandwidth = reservedBandwidth;
}
@Override
public long getAllocatedBandwidth() {
long totalBandwidth = (long) (bandwidthMeter.getBitrateEstimate() * bandwidthFraction);
long allocatableBandwidth = Math.max(0L, totalBandwidth - reservedBandwidth);
if (allocationCheckpoints == null) {
return allocatableBandwidth;
}
int nextIndex = 1;
while (nextIndex < allocationCheckpoints.length - 1
&& allocationCheckpoints[nextIndex][0] < allocatableBandwidth) {
nextIndex++;
}
long[] previous = allocationCheckpoints[nextIndex - 1];
long[] next = allocationCheckpoints[nextIndex];
float fractionBetweenCheckpoints =
(float) (allocatableBandwidth - previous[0]) / (next[0] - previous[0]);
return previous[1] + (long) (fractionBetweenCheckpoints * (next[1] - previous[1]));
}
/* package */ void experimental_setBandwidthAllocationCheckpoints(
long[][] allocationCheckpoints) {
Assertions.checkArgument(allocationCheckpoints.length >= 2);
this.allocationCheckpoints = allocationCheckpoints;
}
}
/**
* Returns allocation checkpoints for allocating bandwidth between multiple adaptive track
* selections.
*
* @param trackBitrates Array of [selectionIndex][trackIndex] -> trackBitrate.
* @return Array of allocation checkpoints [selectionIndex][checkpointIndex][2] with [0]=total
* bandwidth at checkpoint and [1]=allocated bandwidth at checkpoint.
*/
private static long[][][] getAllocationCheckpoints(long[][] trackBitrates) {
// Algorithm:
// 1. Use log bitrates to treat all resolution update steps equally.
// 2. Distribute switch points for each selection equally in the same [0.0-1.0] range.
// 3. Switch up one format at a time in the order of the switch points.
double[][] logBitrates = getLogArrayValues(trackBitrates);
double[][] switchPoints = getSwitchPoints(logBitrates);
// There will be (count(switch point) + 3) checkpoints:
// [0] = all zero, [1] = minimum bitrates, [2-(end-1)] = up-switch points,
// [end] = extra point to set slope for additional bitrate.
int checkpointCount = countArrayElements(switchPoints) + 3;
long[][][] checkpoints = new long[logBitrates.length][checkpointCount][2];
int[] currentSelection = new int[logBitrates.length];
setCheckpointValues(checkpoints, /* checkpointIndex= */ 1, trackBitrates, currentSelection);
for (int checkpointIndex = 2; checkpointIndex < checkpointCount - 1; checkpointIndex++) {
int nextUpdateIndex = 0;
double nextUpdateSwitchPoint = Double.MAX_VALUE;
for (int i = 0; i < logBitrates.length; i++) {
if (currentSelection[i] + 1 == logBitrates[i].length) {
continue;
}
double switchPoint = switchPoints[i][currentSelection[i]];
if (switchPoint < nextUpdateSwitchPoint) {
nextUpdateSwitchPoint = switchPoint;
nextUpdateIndex = i;
}
}
currentSelection[nextUpdateIndex]++;
setCheckpointValues(checkpoints, checkpointIndex, trackBitrates, currentSelection);
}
for (long[][] points : checkpoints) {
points[checkpointCount - 1][0] = 2 * points[checkpointCount - 2][0];
points[checkpointCount - 1][1] = 2 * points[checkpointCount - 2][1];
}
return checkpoints;
}
/** Converts all input values to Math.log(value). */
private static double[][] getLogArrayValues(long[][] values) {
double[][] logValues = new double[values.length][];
for (int i = 0; i < values.length; i++) {
logValues[i] = new double[values[i].length];
for (int j = 0; j < values[i].length; j++) {
logValues[i][j] = values[i][j] == Format.NO_VALUE ? 0 : Math.log(values[i][j]);
}
}
return logValues;
}
/**
* Returns idealized switch points for each switch between consecutive track selection bitrates.
*
* @param logBitrates Log bitrates with [selectionCount][formatCount].
* @return Linearly distributed switch points in the range of [0.0-1.0].
*/
private static double[][] getSwitchPoints(double[][] logBitrates) {
double[][] switchPoints = new double[logBitrates.length][];
for (int i = 0; i < logBitrates.length; i++) {
switchPoints[i] = new double[logBitrates[i].length - 1];
if (switchPoints[i].length == 0) {
continue;
}
double totalBitrateDiff = logBitrates[i][logBitrates[i].length - 1] - logBitrates[i][0];
for (int j = 0; j < logBitrates[i].length - 1; j++) {
double switchBitrate = 0.5 * (logBitrates[i][j] + logBitrates[i][j + 1]);
switchPoints[i][j] =
totalBitrateDiff == 0.0 ? 1.0 : (switchBitrate - logBitrates[i][0]) / totalBitrateDiff;
}
}
return switchPoints;
}
/** Returns total number of elements in a 2D array. */
private static int countArrayElements(double[][] array) {
int count = 0;
for (double[] subArray : array) {
count += subArray.length;
}
return count;
}
/**
* Sets checkpoint bitrates.
*
* @param checkpoints Output checkpoints with [selectionIndex][checkpointIndex][2] where [0]=Total
* bitrate and [1]=Allocated bitrate.
* @param checkpointIndex The checkpoint index.
* @param trackBitrates The track bitrates with [selectionIndex][trackIndex].
* @param selectedTracks The indices of selected tracks for each selection for this checkpoint.
*/
private static void setCheckpointValues(
long[][][] checkpoints, int checkpointIndex, long[][] trackBitrates, int[] selectedTracks) {
long totalBitrate = 0;
for (int i = 0; i < checkpoints.length; i++) {
checkpoints[i][checkpointIndex][1] = trackBitrates[i][selectedTracks[i]];
totalBitrate += checkpoints[i][checkpointIndex][1];
}
for (long[][] points : checkpoints) {
points[checkpointIndex][0] = totalBitrate;
}
}
}
| library/core/src/main/java/com/google/android/exoplayer2/trackselection/AdaptiveTrackSelection.java | /*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.exoplayer2.trackselection;
import androidx.annotation.Nullable;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.Format;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.source.TrackGroup;
import com.google.android.exoplayer2.source.chunk.MediaChunk;
import com.google.android.exoplayer2.source.chunk.MediaChunkIterator;
import com.google.android.exoplayer2.upstream.BandwidthMeter;
import com.google.android.exoplayer2.util.Assertions;
import com.google.android.exoplayer2.util.Clock;
import com.google.android.exoplayer2.util.Util;
import java.util.ArrayList;
import java.util.List;
import org.checkerframework.checker.nullness.compatqual.NullableType;
/**
* A bandwidth based adaptive {@link TrackSelection}, whose selected track is updated to be the one
* of highest quality given the current network conditions and the state of the buffer.
*/
public class AdaptiveTrackSelection extends BaseTrackSelection {
/** Factory for {@link AdaptiveTrackSelection} instances. */
public static class Factory implements TrackSelection.Factory {
@Nullable private final BandwidthMeter bandwidthMeter;
private final int minDurationForQualityIncreaseMs;
private final int maxDurationForQualityDecreaseMs;
private final int minDurationToRetainAfterDiscardMs;
private final float bandwidthFraction;
private final float bufferedFractionToLiveEdgeForQualityIncrease;
private final long minTimeBetweenBufferReevaluationMs;
private final Clock clock;
/** Creates an adaptive track selection factory with default parameters. */
public Factory() {
this(
DEFAULT_MIN_DURATION_FOR_QUALITY_INCREASE_MS,
DEFAULT_MAX_DURATION_FOR_QUALITY_DECREASE_MS,
DEFAULT_MIN_DURATION_TO_RETAIN_AFTER_DISCARD_MS,
DEFAULT_BANDWIDTH_FRACTION,
DEFAULT_BUFFERED_FRACTION_TO_LIVE_EDGE_FOR_QUALITY_INCREASE,
DEFAULT_MIN_TIME_BETWEEN_BUFFER_REEVALUTATION_MS,
Clock.DEFAULT);
}
/**
* @deprecated Use {@link #Factory()} instead. Custom bandwidth meter should be directly passed
* to the player in {@link SimpleExoPlayer.Builder}.
*/
@Deprecated
@SuppressWarnings("deprecation")
public Factory(BandwidthMeter bandwidthMeter) {
this(
bandwidthMeter,
DEFAULT_MIN_DURATION_FOR_QUALITY_INCREASE_MS,
DEFAULT_MAX_DURATION_FOR_QUALITY_DECREASE_MS,
DEFAULT_MIN_DURATION_TO_RETAIN_AFTER_DISCARD_MS,
DEFAULT_BANDWIDTH_FRACTION,
DEFAULT_BUFFERED_FRACTION_TO_LIVE_EDGE_FOR_QUALITY_INCREASE,
DEFAULT_MIN_TIME_BETWEEN_BUFFER_REEVALUTATION_MS,
Clock.DEFAULT);
}
/**
* Creates an adaptive track selection factory.
*
* @param minDurationForQualityIncreaseMs The minimum duration of buffered data required for the
* selected track to switch to one of higher quality.
* @param maxDurationForQualityDecreaseMs The maximum duration of buffered data required for the
* selected track to switch to one of lower quality.
* @param minDurationToRetainAfterDiscardMs When switching to a track of significantly higher
* quality, the selection may indicate that media already buffered at the lower quality can
* be discarded to speed up the switch. This is the minimum duration of media that must be
* retained at the lower quality.
* @param bandwidthFraction The fraction of the available bandwidth that the selection should
* consider available for use. Setting to a value less than 1 is recommended to account for
* inaccuracies in the bandwidth estimator.
*/
public Factory(
int minDurationForQualityIncreaseMs,
int maxDurationForQualityDecreaseMs,
int minDurationToRetainAfterDiscardMs,
float bandwidthFraction) {
this(
minDurationForQualityIncreaseMs,
maxDurationForQualityDecreaseMs,
minDurationToRetainAfterDiscardMs,
bandwidthFraction,
DEFAULT_BUFFERED_FRACTION_TO_LIVE_EDGE_FOR_QUALITY_INCREASE,
DEFAULT_MIN_TIME_BETWEEN_BUFFER_REEVALUTATION_MS,
Clock.DEFAULT);
}
/**
* @deprecated Use {@link #Factory(int, int, int, float)} instead. Custom bandwidth meter should
* be directly passed to the player in {@link SimpleExoPlayer.Builder}.
*/
@Deprecated
@SuppressWarnings("deprecation")
public Factory(
BandwidthMeter bandwidthMeter,
int minDurationForQualityIncreaseMs,
int maxDurationForQualityDecreaseMs,
int minDurationToRetainAfterDiscardMs,
float bandwidthFraction) {
this(
bandwidthMeter,
minDurationForQualityIncreaseMs,
maxDurationForQualityDecreaseMs,
minDurationToRetainAfterDiscardMs,
bandwidthFraction,
DEFAULT_BUFFERED_FRACTION_TO_LIVE_EDGE_FOR_QUALITY_INCREASE,
DEFAULT_MIN_TIME_BETWEEN_BUFFER_REEVALUTATION_MS,
Clock.DEFAULT);
}
/**
* Creates an adaptive track selection factory.
*
* @param minDurationForQualityIncreaseMs The minimum duration of buffered data required for the
* selected track to switch to one of higher quality.
* @param maxDurationForQualityDecreaseMs The maximum duration of buffered data required for the
* selected track to switch to one of lower quality.
* @param minDurationToRetainAfterDiscardMs When switching to a track of significantly higher
* quality, the selection may indicate that media already buffered at the lower quality can
* be discarded to speed up the switch. This is the minimum duration of media that must be
* retained at the lower quality.
* @param bandwidthFraction The fraction of the available bandwidth that the selection should
* consider available for use. Setting to a value less than 1 is recommended to account for
* inaccuracies in the bandwidth estimator.
* @param bufferedFractionToLiveEdgeForQualityIncrease For live streaming, the fraction of the
* duration from current playback position to the live edge that has to be buffered before
* the selected track can be switched to one of higher quality. This parameter is only
* applied when the playback position is closer to the live edge than {@code
* minDurationForQualityIncreaseMs}, which would otherwise prevent switching to a higher
* quality from happening.
* @param minTimeBetweenBufferReevaluationMs The track selection may periodically reevaluate its
* buffer and discard some chunks of lower quality to improve the playback quality if
* network conditions have changed. This is the minimum duration between 2 consecutive
* buffer reevaluation calls.
* @param clock A {@link Clock}.
*/
@SuppressWarnings("deprecation")
public Factory(
int minDurationForQualityIncreaseMs,
int maxDurationForQualityDecreaseMs,
int minDurationToRetainAfterDiscardMs,
float bandwidthFraction,
float bufferedFractionToLiveEdgeForQualityIncrease,
long minTimeBetweenBufferReevaluationMs,
Clock clock) {
this(
/* bandwidthMeter= */ null,
minDurationForQualityIncreaseMs,
maxDurationForQualityDecreaseMs,
minDurationToRetainAfterDiscardMs,
bandwidthFraction,
bufferedFractionToLiveEdgeForQualityIncrease,
minTimeBetweenBufferReevaluationMs,
clock);
}
/**
* @deprecated Use {@link #Factory(int, int, int, float, float, long, Clock)} instead. Custom
* bandwidth meter should be directly passed to the player in {@link
* SimpleExoPlayer.Builder}.
*/
@Deprecated
public Factory(
@Nullable BandwidthMeter bandwidthMeter,
int minDurationForQualityIncreaseMs,
int maxDurationForQualityDecreaseMs,
int minDurationToRetainAfterDiscardMs,
float bandwidthFraction,
float bufferedFractionToLiveEdgeForQualityIncrease,
long minTimeBetweenBufferReevaluationMs,
Clock clock) {
this.bandwidthMeter = bandwidthMeter;
this.minDurationForQualityIncreaseMs = minDurationForQualityIncreaseMs;
this.maxDurationForQualityDecreaseMs = maxDurationForQualityDecreaseMs;
this.minDurationToRetainAfterDiscardMs = minDurationToRetainAfterDiscardMs;
this.bandwidthFraction = bandwidthFraction;
this.bufferedFractionToLiveEdgeForQualityIncrease =
bufferedFractionToLiveEdgeForQualityIncrease;
this.minTimeBetweenBufferReevaluationMs = minTimeBetweenBufferReevaluationMs;
this.clock = clock;
}
@Override
public final @NullableType TrackSelection[] createTrackSelections(
@NullableType Definition[] definitions, BandwidthMeter bandwidthMeter) {
if (this.bandwidthMeter != null) {
bandwidthMeter = this.bandwidthMeter;
}
TrackSelection[] selections = new TrackSelection[definitions.length];
int totalFixedBandwidth = 0;
for (int i = 0; i < definitions.length; i++) {
Definition definition = definitions[i];
if (definition != null && definition.tracks.length == 1) {
// Make fixed selections first to know their total bandwidth.
selections[i] =
new FixedTrackSelection(
definition.group, definition.tracks[0], definition.reason, definition.data);
int trackBitrate = definition.group.getFormat(definition.tracks[0]).bitrate;
if (trackBitrate != Format.NO_VALUE) {
totalFixedBandwidth += trackBitrate;
}
}
}
List<AdaptiveTrackSelection> adaptiveSelections = new ArrayList<>();
for (int i = 0; i < definitions.length; i++) {
Definition definition = definitions[i];
if (definition != null && definition.tracks.length > 1) {
AdaptiveTrackSelection adaptiveSelection =
createAdaptiveTrackSelection(
definition.group, bandwidthMeter, definition.tracks, totalFixedBandwidth);
adaptiveSelections.add(adaptiveSelection);
selections[i] = adaptiveSelection;
}
}
if (adaptiveSelections.size() > 1) {
long[][] adaptiveTrackBitrates = new long[adaptiveSelections.size()][];
for (int i = 0; i < adaptiveSelections.size(); i++) {
AdaptiveTrackSelection adaptiveSelection = adaptiveSelections.get(i);
adaptiveTrackBitrates[i] = new long[adaptiveSelection.length()];
for (int j = 0; j < adaptiveSelection.length(); j++) {
adaptiveTrackBitrates[i][j] =
adaptiveSelection.getFormat(adaptiveSelection.length() - j - 1).bitrate;
}
}
long[][][] bandwidthCheckpoints = getAllocationCheckpoints(adaptiveTrackBitrates);
for (int i = 0; i < adaptiveSelections.size(); i++) {
adaptiveSelections
.get(i)
.experimental_setBandwidthAllocationCheckpoints(bandwidthCheckpoints[i]);
}
}
return selections;
}
/**
* Creates a single adaptive selection for the given group, bandwidth meter and tracks.
*
* @param group The {@link TrackGroup}.
* @param bandwidthMeter A {@link BandwidthMeter} which can be used to select tracks.
* @param tracks The indices of the selected tracks in the track group.
* @param totalFixedTrackBandwidth The total bandwidth used by all non-adaptive tracks, in bits
* per second.
* @return An {@link AdaptiveTrackSelection} for the specified tracks.
*/
protected AdaptiveTrackSelection createAdaptiveTrackSelection(
TrackGroup group,
BandwidthMeter bandwidthMeter,
int[] tracks,
int totalFixedTrackBandwidth) {
return new AdaptiveTrackSelection(
group,
tracks,
new DefaultBandwidthProvider(bandwidthMeter, bandwidthFraction, totalFixedTrackBandwidth),
minDurationForQualityIncreaseMs,
maxDurationForQualityDecreaseMs,
minDurationToRetainAfterDiscardMs,
bufferedFractionToLiveEdgeForQualityIncrease,
minTimeBetweenBufferReevaluationMs,
clock);
}
}
public static final int DEFAULT_MIN_DURATION_FOR_QUALITY_INCREASE_MS = 10000;
public static final int DEFAULT_MAX_DURATION_FOR_QUALITY_DECREASE_MS = 25000;
public static final int DEFAULT_MIN_DURATION_TO_RETAIN_AFTER_DISCARD_MS = 25000;
public static final float DEFAULT_BANDWIDTH_FRACTION = 0.7f;
public static final float DEFAULT_BUFFERED_FRACTION_TO_LIVE_EDGE_FOR_QUALITY_INCREASE = 0.75f;
public static final long DEFAULT_MIN_TIME_BETWEEN_BUFFER_REEVALUTATION_MS = 2000;
private final BandwidthProvider bandwidthProvider;
private final long minDurationForQualityIncreaseUs;
private final long maxDurationForQualityDecreaseUs;
private final long minDurationToRetainAfterDiscardUs;
private final float bufferedFractionToLiveEdgeForQualityIncrease;
private final long minTimeBetweenBufferReevaluationMs;
private final Clock clock;
private float playbackSpeed;
private int selectedIndex;
private int reason;
private long lastBufferEvaluationMs;
/**
* @param group The {@link TrackGroup}.
* @param tracks The indices of the selected tracks within the {@link TrackGroup}. Must not be
* empty. May be in any order.
* @param bandwidthMeter Provides an estimate of the currently available bandwidth.
*/
public AdaptiveTrackSelection(TrackGroup group, int[] tracks,
BandwidthMeter bandwidthMeter) {
this(
group,
tracks,
bandwidthMeter,
/* reservedBandwidth= */ 0,
DEFAULT_MIN_DURATION_FOR_QUALITY_INCREASE_MS,
DEFAULT_MAX_DURATION_FOR_QUALITY_DECREASE_MS,
DEFAULT_MIN_DURATION_TO_RETAIN_AFTER_DISCARD_MS,
DEFAULT_BANDWIDTH_FRACTION,
DEFAULT_BUFFERED_FRACTION_TO_LIVE_EDGE_FOR_QUALITY_INCREASE,
DEFAULT_MIN_TIME_BETWEEN_BUFFER_REEVALUTATION_MS,
Clock.DEFAULT);
}
/**
* @param group The {@link TrackGroup}.
* @param tracks The indices of the selected tracks within the {@link TrackGroup}. Must not be
* empty. May be in any order.
* @param bandwidthMeter Provides an estimate of the currently available bandwidth.
* @param reservedBandwidth The reserved bandwidth, which shouldn't be considered available for
* use, in bits per second.
* @param minDurationForQualityIncreaseMs The minimum duration of buffered data required for the
* selected track to switch to one of higher quality.
* @param maxDurationForQualityDecreaseMs The maximum duration of buffered data required for the
* selected track to switch to one of lower quality.
* @param minDurationToRetainAfterDiscardMs When switching to a track of significantly higher
* quality, the selection may indicate that media already buffered at the lower quality can be
* discarded to speed up the switch. This is the minimum duration of media that must be
* retained at the lower quality.
* @param bandwidthFraction The fraction of the available bandwidth that the selection should
* consider available for use. Setting to a value less than 1 is recommended to account for
* inaccuracies in the bandwidth estimator.
* @param bufferedFractionToLiveEdgeForQualityIncrease For live streaming, the fraction of the
* duration from current playback position to the live edge that has to be buffered before the
* selected track can be switched to one of higher quality. This parameter is only applied
* when the playback position is closer to the live edge than {@code
* minDurationForQualityIncreaseMs}, which would otherwise prevent switching to a higher
* quality from happening.
* @param minTimeBetweenBufferReevaluationMs The track selection may periodically reevaluate its
* buffer and discard some chunks of lower quality to improve the playback quality if network
* condition has changed. This is the minimum duration between 2 consecutive buffer
* reevaluation calls.
*/
public AdaptiveTrackSelection(
TrackGroup group,
int[] tracks,
BandwidthMeter bandwidthMeter,
long reservedBandwidth,
long minDurationForQualityIncreaseMs,
long maxDurationForQualityDecreaseMs,
long minDurationToRetainAfterDiscardMs,
float bandwidthFraction,
float bufferedFractionToLiveEdgeForQualityIncrease,
long minTimeBetweenBufferReevaluationMs,
Clock clock) {
this(
group,
tracks,
new DefaultBandwidthProvider(bandwidthMeter, bandwidthFraction, reservedBandwidth),
minDurationForQualityIncreaseMs,
maxDurationForQualityDecreaseMs,
minDurationToRetainAfterDiscardMs,
bufferedFractionToLiveEdgeForQualityIncrease,
minTimeBetweenBufferReevaluationMs,
clock);
}
private AdaptiveTrackSelection(
TrackGroup group,
int[] tracks,
BandwidthProvider bandwidthProvider,
long minDurationForQualityIncreaseMs,
long maxDurationForQualityDecreaseMs,
long minDurationToRetainAfterDiscardMs,
float bufferedFractionToLiveEdgeForQualityIncrease,
long minTimeBetweenBufferReevaluationMs,
Clock clock) {
super(group, tracks);
this.bandwidthProvider = bandwidthProvider;
this.minDurationForQualityIncreaseUs = minDurationForQualityIncreaseMs * 1000L;
this.maxDurationForQualityDecreaseUs = maxDurationForQualityDecreaseMs * 1000L;
this.minDurationToRetainAfterDiscardUs = minDurationToRetainAfterDiscardMs * 1000L;
this.bufferedFractionToLiveEdgeForQualityIncrease =
bufferedFractionToLiveEdgeForQualityIncrease;
this.minTimeBetweenBufferReevaluationMs = minTimeBetweenBufferReevaluationMs;
this.clock = clock;
playbackSpeed = 1f;
reason = C.SELECTION_REASON_UNKNOWN;
lastBufferEvaluationMs = C.TIME_UNSET;
}
/**
* Sets checkpoints to determine the allocation bandwidth based on the total bandwidth.
*
* @param allocationCheckpoints List of checkpoints. Each element must be a long[2], with [0]
* being the total bandwidth and [1] being the allocated bandwidth.
*/
public void experimental_setBandwidthAllocationCheckpoints(long[][] allocationCheckpoints) {
((DefaultBandwidthProvider) bandwidthProvider)
.experimental_setBandwidthAllocationCheckpoints(allocationCheckpoints);
}
@Override
public void enable() {
lastBufferEvaluationMs = C.TIME_UNSET;
}
@Override
public void onPlaybackSpeed(float playbackSpeed) {
this.playbackSpeed = playbackSpeed;
}
@Override
public void updateSelectedTrack(
long playbackPositionUs,
long bufferedDurationUs,
long availableDurationUs,
List<? extends MediaChunk> queue,
MediaChunkIterator[] mediaChunkIterators) {
long nowMs = clock.elapsedRealtime();
// Make initial selection
if (reason == C.SELECTION_REASON_UNKNOWN) {
reason = C.SELECTION_REASON_INITIAL;
selectedIndex = determineIdealSelectedIndex(nowMs);
return;
}
// Stash the current selection, then make a new one.
int currentSelectedIndex = selectedIndex;
selectedIndex = determineIdealSelectedIndex(nowMs);
if (selectedIndex == currentSelectedIndex) {
return;
}
if (!isBlacklisted(currentSelectedIndex, nowMs)) {
// Revert back to the current selection if conditions are not suitable for switching.
Format currentFormat = getFormat(currentSelectedIndex);
Format selectedFormat = getFormat(selectedIndex);
if (selectedFormat.bitrate > currentFormat.bitrate
&& bufferedDurationUs < minDurationForQualityIncreaseUs(availableDurationUs)) {
// The selected track is a higher quality, but we have insufficient buffer to safely switch
// up. Defer switching up for now.
selectedIndex = currentSelectedIndex;
} else if (selectedFormat.bitrate < currentFormat.bitrate
&& bufferedDurationUs >= maxDurationForQualityDecreaseUs) {
// The selected track is a lower quality, but we have sufficient buffer to defer switching
// down for now.
selectedIndex = currentSelectedIndex;
}
}
// If we adapted, update the trigger.
if (selectedIndex != currentSelectedIndex) {
reason = C.SELECTION_REASON_ADAPTIVE;
}
}
@Override
public int getSelectedIndex() {
return selectedIndex;
}
@Override
public int getSelectionReason() {
return reason;
}
@Override
@Nullable
public Object getSelectionData() {
return null;
}
@Override
public int evaluateQueueSize(long playbackPositionUs, List<? extends MediaChunk> queue) {
long nowMs = clock.elapsedRealtime();
if (!shouldEvaluateQueueSize(nowMs)) {
return queue.size();
}
lastBufferEvaluationMs = nowMs;
if (queue.isEmpty()) {
return 0;
}
int queueSize = queue.size();
MediaChunk lastChunk = queue.get(queueSize - 1);
long playoutBufferedDurationBeforeLastChunkUs =
Util.getPlayoutDurationForMediaDuration(
lastChunk.startTimeUs - playbackPositionUs, playbackSpeed);
long minDurationToRetainAfterDiscardUs = getMinDurationToRetainAfterDiscardUs();
if (playoutBufferedDurationBeforeLastChunkUs < minDurationToRetainAfterDiscardUs) {
return queueSize;
}
int idealSelectedIndex = determineIdealSelectedIndex(nowMs);
Format idealFormat = getFormat(idealSelectedIndex);
// If the chunks contain video, discard from the first SD chunk beyond
// minDurationToRetainAfterDiscardUs whose resolution and bitrate are both lower than the ideal
// track.
for (int i = 0; i < queueSize; i++) {
MediaChunk chunk = queue.get(i);
Format format = chunk.trackFormat;
long mediaDurationBeforeThisChunkUs = chunk.startTimeUs - playbackPositionUs;
long playoutDurationBeforeThisChunkUs =
Util.getPlayoutDurationForMediaDuration(mediaDurationBeforeThisChunkUs, playbackSpeed);
if (playoutDurationBeforeThisChunkUs >= minDurationToRetainAfterDiscardUs
&& format.bitrate < idealFormat.bitrate
&& format.height != Format.NO_VALUE && format.height < 720
&& format.width != Format.NO_VALUE && format.width < 1280
&& format.height < idealFormat.height) {
return i;
}
}
return queueSize;
}
/**
* Called when updating the selected track to determine whether a candidate track can be selected.
*
* @param format The {@link Format} of the candidate track.
* @param trackBitrate The estimated bitrate of the track. May differ from {@link Format#bitrate}
* if a more accurate estimate of the current track bitrate is available.
* @param playbackSpeed The current playback speed.
* @param effectiveBitrate The bitrate available to this selection.
* @return Whether this {@link Format} can be selected.
*/
@SuppressWarnings("unused")
protected boolean canSelectFormat(
Format format, int trackBitrate, float playbackSpeed, long effectiveBitrate) {
boolean isIframeOnly = (format.roleFlags & C.ROLE_FLAG_TRICK_PLAY) != 0;
boolean canSelect = Math.round(trackBitrate * playbackSpeed) <= effectiveBitrate;
if (Math.abs(playbackSpeed) > 6.0f) {
canSelect = isIframeOnly; // TODO factor in playback speed...
} else {
canSelect = ! isIframeOnly && canSelect;
}
return canSelect;
}
/**
* Called from {@link #evaluateQueueSize(long, List)} to determine whether an evaluation should be
* performed.
*
* @param nowMs The current value of {@link Clock#elapsedRealtime()}.
* @return Whether an evaluation should be performed.
*/
protected boolean shouldEvaluateQueueSize(long nowMs) {
return lastBufferEvaluationMs == C.TIME_UNSET
|| nowMs - lastBufferEvaluationMs >= minTimeBetweenBufferReevaluationMs;
}
/**
* Called from {@link #evaluateQueueSize(long, List)} to determine the minimum duration of buffer
* to retain after discarding chunks.
*
* @return The minimum duration of buffer to retain after discarding chunks, in microseconds.
*/
protected long getMinDurationToRetainAfterDiscardUs() {
return minDurationToRetainAfterDiscardUs;
}
/**
* Computes the ideal selected index ignoring buffer health.
*
* @param nowMs The current time in the timebase of {@link Clock#elapsedRealtime()}, or {@link
* Long#MIN_VALUE} to ignore blacklisting.
*/
private int determineIdealSelectedIndex(long nowMs) {
long effectiveBitrate = bandwidthProvider.getAllocatedBandwidth();
int lowestBitrateNonBlacklistedIndex = 0;
for (int i = 0; i < length; i++) {
if (nowMs == Long.MIN_VALUE || !isBlacklisted(i, nowMs)) {
Format format = getFormat(i);
if (canSelectFormat(format, format.bitrate, playbackSpeed, effectiveBitrate)) {
return i;
} else {
lowestBitrateNonBlacklistedIndex = i;
}
}
}
return lowestBitrateNonBlacklistedIndex;
}
private long minDurationForQualityIncreaseUs(long availableDurationUs) {
boolean isAvailableDurationTooShort = availableDurationUs != C.TIME_UNSET
&& availableDurationUs <= minDurationForQualityIncreaseUs;
return isAvailableDurationTooShort
? (long) (availableDurationUs * bufferedFractionToLiveEdgeForQualityIncrease)
: minDurationForQualityIncreaseUs;
}
/** Provides the allocated bandwidth. */
private interface BandwidthProvider {
/** Returns the allocated bitrate. */
long getAllocatedBandwidth();
}
private static final class DefaultBandwidthProvider implements BandwidthProvider {
private final BandwidthMeter bandwidthMeter;
private final float bandwidthFraction;
private final long reservedBandwidth;
@Nullable private long[][] allocationCheckpoints;
/* package */ DefaultBandwidthProvider(
BandwidthMeter bandwidthMeter, float bandwidthFraction, long reservedBandwidth) {
this.bandwidthMeter = bandwidthMeter;
this.bandwidthFraction = bandwidthFraction;
this.reservedBandwidth = reservedBandwidth;
}
@Override
public long getAllocatedBandwidth() {
long totalBandwidth = (long) (bandwidthMeter.getBitrateEstimate() * bandwidthFraction);
long allocatableBandwidth = Math.max(0L, totalBandwidth - reservedBandwidth);
if (allocationCheckpoints == null) {
return allocatableBandwidth;
}
int nextIndex = 1;
while (nextIndex < allocationCheckpoints.length - 1
&& allocationCheckpoints[nextIndex][0] < allocatableBandwidth) {
nextIndex++;
}
long[] previous = allocationCheckpoints[nextIndex - 1];
long[] next = allocationCheckpoints[nextIndex];
float fractionBetweenCheckpoints =
(float) (allocatableBandwidth - previous[0]) / (next[0] - previous[0]);
return previous[1] + (long) (fractionBetweenCheckpoints * (next[1] - previous[1]));
}
/* package */ void experimental_setBandwidthAllocationCheckpoints(
long[][] allocationCheckpoints) {
Assertions.checkArgument(allocationCheckpoints.length >= 2);
this.allocationCheckpoints = allocationCheckpoints;
}
}
/**
* Returns allocation checkpoints for allocating bandwidth between multiple adaptive track
* selections.
*
* @param trackBitrates Array of [selectionIndex][trackIndex] -> trackBitrate.
* @return Array of allocation checkpoints [selectionIndex][checkpointIndex][2] with [0]=total
* bandwidth at checkpoint and [1]=allocated bandwidth at checkpoint.
*/
private static long[][][] getAllocationCheckpoints(long[][] trackBitrates) {
// Algorithm:
// 1. Use log bitrates to treat all resolution update steps equally.
// 2. Distribute switch points for each selection equally in the same [0.0-1.0] range.
// 3. Switch up one format at a time in the order of the switch points.
double[][] logBitrates = getLogArrayValues(trackBitrates);
double[][] switchPoints = getSwitchPoints(logBitrates);
// There will be (count(switch point) + 3) checkpoints:
// [0] = all zero, [1] = minimum bitrates, [2-(end-1)] = up-switch points,
// [end] = extra point to set slope for additional bitrate.
int checkpointCount = countArrayElements(switchPoints) + 3;
long[][][] checkpoints = new long[logBitrates.length][checkpointCount][2];
int[] currentSelection = new int[logBitrates.length];
setCheckpointValues(checkpoints, /* checkpointIndex= */ 1, trackBitrates, currentSelection);
for (int checkpointIndex = 2; checkpointIndex < checkpointCount - 1; checkpointIndex++) {
int nextUpdateIndex = 0;
double nextUpdateSwitchPoint = Double.MAX_VALUE;
for (int i = 0; i < logBitrates.length; i++) {
if (currentSelection[i] + 1 == logBitrates[i].length) {
continue;
}
double switchPoint = switchPoints[i][currentSelection[i]];
if (switchPoint < nextUpdateSwitchPoint) {
nextUpdateSwitchPoint = switchPoint;
nextUpdateIndex = i;
}
}
currentSelection[nextUpdateIndex]++;
setCheckpointValues(checkpoints, checkpointIndex, trackBitrates, currentSelection);
}
for (long[][] points : checkpoints) {
points[checkpointCount - 1][0] = 2 * points[checkpointCount - 2][0];
points[checkpointCount - 1][1] = 2 * points[checkpointCount - 2][1];
}
return checkpoints;
}
/** Converts all input values to Math.log(value). */
private static double[][] getLogArrayValues(long[][] values) {
double[][] logValues = new double[values.length][];
for (int i = 0; i < values.length; i++) {
logValues[i] = new double[values[i].length];
for (int j = 0; j < values[i].length; j++) {
logValues[i][j] = values[i][j] == Format.NO_VALUE ? 0 : Math.log(values[i][j]);
}
}
return logValues;
}
/**
* Returns idealized switch points for each switch between consecutive track selection bitrates.
*
* @param logBitrates Log bitrates with [selectionCount][formatCount].
* @return Linearly distributed switch points in the range of [0.0-1.0].
*/
private static double[][] getSwitchPoints(double[][] logBitrates) {
double[][] switchPoints = new double[logBitrates.length][];
for (int i = 0; i < logBitrates.length; i++) {
switchPoints[i] = new double[logBitrates[i].length - 1];
if (switchPoints[i].length == 0) {
continue;
}
double totalBitrateDiff = logBitrates[i][logBitrates[i].length - 1] - logBitrates[i][0];
for (int j = 0; j < logBitrates[i].length - 1; j++) {
double switchBitrate = 0.5 * (logBitrates[i][j] + logBitrates[i][j + 1]);
switchPoints[i][j] =
totalBitrateDiff == 0.0 ? 1.0 : (switchBitrate - logBitrates[i][0]) / totalBitrateDiff;
}
}
return switchPoints;
}
/** Returns total number of elements in a 2D array. */
private static int countArrayElements(double[][] array) {
int count = 0;
for (double[] subArray : array) {
count += subArray.length;
}
return count;
}
/**
* Sets checkpoint bitrates.
*
* @param checkpoints Output checkpoints with [selectionIndex][checkpointIndex][2] where [0]=Total
* bitrate and [1]=Allocated bitrate.
* @param checkpointIndex The checkpoint index.
* @param trackBitrates The track bitrates with [selectionIndex][trackIndex].
* @param selectedTracks The indices of selected tracks for each selection for this checkpoint.
*/
private static void setCheckpointValues(
long[][][] checkpoints, int checkpointIndex, long[][] trackBitrates, int[] selectedTracks) {
long totalBitrate = 0;
for (int i = 0; i < checkpoints.length; i++) {
checkpoints[i][checkpointIndex][1] = trackBitrates[i][selectedTracks[i]];
totalBitrate += checkpoints[i][checkpointIndex][1];
}
for (long[][] points : checkpoints) {
points[checkpointIndex][0] = totalBitrate;
}
}
}
| Default to not select iFrame oly tracks.
Pull in change to default to not use i-Frames for base AdaptiveTrackSelection.
The expectation is a subclases, that support transitioning to iFrame, will select these tracks.
| library/core/src/main/java/com/google/android/exoplayer2/trackselection/AdaptiveTrackSelection.java | Default to not select iFrame oly tracks. | <ide><path>ibrary/core/src/main/java/com/google/android/exoplayer2/trackselection/AdaptiveTrackSelection.java
<ide> protected boolean canSelectFormat(
<ide> Format format, int trackBitrate, float playbackSpeed, long effectiveBitrate) {
<ide>
<del> boolean isIframeOnly = (format.roleFlags & C.ROLE_FLAG_TRICK_PLAY) != 0;
<add> boolean isNonIframeOnly = (format.roleFlags & C.ROLE_FLAG_TRICK_PLAY) == 0;
<ide> boolean canSelect = Math.round(trackBitrate * playbackSpeed) <= effectiveBitrate;
<ide>
<del> if (Math.abs(playbackSpeed) > 6.0f) {
<del> canSelect = isIframeOnly; // TODO factor in playback speed...
<del> } else {
<del> canSelect = ! isIframeOnly && canSelect;
<del> }
<del> return canSelect;
<del>
<add> return canSelect && isNonIframeOnly; // Default is not to use the IDR only tracks in selection
<ide> }
<ide>
<ide> /** |
|
Java | apache-2.0 | a45a1189facc30952831c90c220fb3fc4c9878a7 | 0 | amckee23/drools,ChallenHB/drools,iambic69/drools,winklerm/drools,sotty/drools,ThomasLau/drools,mrietveld/drools,kedzie/drools-android,kevinpeterson/drools,TonnyFeng/drools,vinodkiran/drools,TonnyFeng/drools,prabasn/drools,pwachira/droolsexamples,mrrodriguez/drools,reynoldsm88/drools,ThomasLau/drools,Buble1981/MyDroolsFork,sotty/drools,HHzzhz/drools,manstis/drools,sutaakar/drools,reynoldsm88/drools,lanceleverich/drools,romartin/drools,HHzzhz/drools,prabasn/drools,amckee23/drools,prabasn/drools,winklerm/drools,kevinpeterson/drools,reynoldsm88/drools,prabasn/drools,ThomasLau/drools,jomarko/drools,lanceleverich/drools,mrietveld/drools,292388900/drools,mrrodriguez/drools,jomarko/drools,manstis/drools,liupugong/drools,winklerm/drools,romartin/drools,sutaakar/drools,mrrodriguez/drools,lanceleverich/drools,OnePaaS/drools,mrietveld/drools,ChallenHB/drools,jiripetrlik/drools,lanceleverich/drools,ThiagoGarciaAlves/drools,kevinpeterson/drools,manstis/drools,292388900/drools,vinodkiran/drools,amckee23/drools,manstis/drools,amckee23/drools,rajashekharmunthakewill/drools,sotty/drools,prabasn/drools,sotty/drools,Buble1981/MyDroolsFork,kedzie/drools-android,kedzie/drools-android,kedzie/drools-android,292388900/drools,rajashekharmunthakewill/drools,droolsjbpm/drools,292388900/drools,reynoldsm88/drools,winklerm/drools,liupugong/drools,292388900/drools,HHzzhz/drools,liupugong/drools,rajashekharmunthakewill/drools,TonnyFeng/drools,liupugong/drools,winklerm/drools,jiripetrlik/drools,mrrodriguez/drools,Buble1981/MyDroolsFork,ngs-mtech/drools,jomarko/drools,manstis/drools,sutaakar/drools,ngs-mtech/drools,Buble1981/MyDroolsFork,vinodkiran/drools,jiripetrlik/drools,droolsjbpm/drools,sutaakar/drools,ngs-mtech/drools,iambic69/drools,TonnyFeng/drools,jomarko/drools,OnePaaS/drools,amckee23/drools,vinodkiran/drools,rajashekharmunthakewill/drools,ThiagoGarciaAlves/drools,ThomasLau/drools,OnePaaS/drools,kevinpeterson/drools,romartin/drools,ngs-mtech/drools,sotty/drools,TonnyFeng/drools,liupugong/drools,mrietveld/drools,reynoldsm88/drools,HHzzhz/drools,OnePaaS/drools,iambic69/drools,sutaakar/drools,ngs-mtech/drools,lanceleverich/drools,HHzzhz/drools,mrrodriguez/drools,mrietveld/drools,jiripetrlik/drools,OnePaaS/drools,ThiagoGarciaAlves/drools,droolsjbpm/drools,kevinpeterson/drools,romartin/drools,ChallenHB/drools,iambic69/drools,ChallenHB/drools,jomarko/drools,vinodkiran/drools,romartin/drools,rajashekharmunthakewill/drools,ThiagoGarciaAlves/drools,jiripetrlik/drools,ThomasLau/drools,kedzie/drools-android,iambic69/drools,droolsjbpm/drools,droolsjbpm/drools,ThiagoGarciaAlves/drools,ChallenHB/drools | /*
* Copyright 2010 JBoss 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.drools.core.reteoo;
import org.drools.core.RuleBaseConfiguration;
import org.drools.core.base.ClassObjectType;
import org.drools.core.common.BetaConstraints;
import org.drools.core.common.EmptyBetaConstraints;
import org.drools.core.common.InternalFactHandle;
import org.drools.core.common.InternalRuleBase;
import org.drools.core.common.InternalWorkingMemory;
import org.drools.core.common.Memory;
import org.drools.core.common.MemoryFactory;
import org.drools.core.common.UpdateContext;
import org.drools.core.util.AbstractBaseLinkedListNode;
import org.drools.core.util.index.LeftTupleList;
import org.drools.core.marshalling.impl.PersisterHelper;
import org.drools.core.marshalling.impl.ProtobufInputMarshaller;
import org.drools.core.marshalling.impl.ProtobufInputMarshaller.TupleKey;
import org.drools.core.marshalling.impl.ProtobufMessages;
import org.drools.core.marshalling.impl.ProtobufMessages.FactHandle;
import org.drools.core.reteoo.builder.BuildContext;
import org.drools.core.rule.ContextEntry;
import org.drools.core.rule.From;
import org.drools.core.spi.AlphaNodeFieldConstraint;
import org.drools.core.spi.DataProvider;
import org.drools.core.spi.PropagationContext;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
public class FromNode extends LeftTupleSource
implements
LeftTupleSinkNode,
MemoryFactory {
private static final long serialVersionUID = 510l;
protected DataProvider dataProvider;
protected AlphaNodeFieldConstraint[] alphaConstraints;
protected BetaConstraints betaConstraints;
protected LeftTupleSinkNode previousTupleSinkNode;
protected LeftTupleSinkNode nextTupleSinkNode;
protected From from;
protected Class<?> resultClass;
protected boolean tupleMemoryEnabled;
protected transient ObjectTypeConf objectTypeConf;
public FromNode() {
}
public FromNode(final int id,
final DataProvider dataProvider,
final LeftTupleSource tupleSource,
final AlphaNodeFieldConstraint[] constraints,
final BetaConstraints binder,
final boolean tupleMemoryEnabled,
final BuildContext context,
final From from) {
super( id,
context.getPartitionId(),
context.getRuleBase().getConfiguration().isMultithreadEvaluation() );
this.dataProvider = dataProvider;
setLeftTupleSource(tupleSource);
this.alphaConstraints = constraints;
this.betaConstraints = (binder == null) ? EmptyBetaConstraints.getInstance() : binder;
this.tupleMemoryEnabled = tupleMemoryEnabled;
this.from = from;
resultClass = ((ClassObjectType)this.from.getResultPattern().getObjectType()).getClassType();
initMasks(context, tupleSource);
}
public void readExternal(ObjectInput in) throws IOException,
ClassNotFoundException {
super.readExternal( in );
dataProvider = (DataProvider) in.readObject();
alphaConstraints = (AlphaNodeFieldConstraint[]) in.readObject();
betaConstraints = (BetaConstraints) in.readObject();
tupleMemoryEnabled = in.readBoolean();
from = (From) in.readObject();
resultClass = ((ClassObjectType)this.from.getResultPattern().getObjectType()).getClassType();
}
public void writeExternal(ObjectOutput out) throws IOException {
super.writeExternal( out );
out.writeObject( dataProvider );
out.writeObject( alphaConstraints );
out.writeObject( betaConstraints );
out.writeBoolean( tupleMemoryEnabled );
out.writeObject( from );
}
public DataProvider getDataProvider() {
return dataProvider;
}
public AlphaNodeFieldConstraint[] getAlphaConstraints() {
return alphaConstraints;
}
public BetaConstraints getBetaConstraints() {
return betaConstraints;
}
public Class< ? > getResultClass() {
return resultClass;
}
public void networkUpdated(UpdateContext updateContext) {
this.leftInput.networkUpdated(updateContext);
}
@SuppressWarnings("unchecked")
public RightTuple createRightTuple( final LeftTuple leftTuple,
final PropagationContext context,
final InternalWorkingMemory workingMemory,
final Object object ) {
InternalFactHandle handle;
ProtobufMessages.FactHandle _handle = null;
if ( objectTypeConf == null ) {
// use default entry point and object class. Notice that at this point object is assignable to resultClass
objectTypeConf = new ClassObjectTypeConf( workingMemory.getEntryPoint(), resultClass, (InternalRuleBase) workingMemory.getRuleBase() );
}
if( context.getReaderContext() != null ) {
Map<ProtobufInputMarshaller.TupleKey, List<FactHandle>> map = (Map<ProtobufInputMarshaller.TupleKey, List<ProtobufMessages.FactHandle>>) context.getReaderContext().nodeMemories.get( getId() );
if( map != null ) {
TupleKey key = PersisterHelper.createTupleKey(leftTuple);
List<FactHandle> list = map.get( key );
if( list != null && ! list.isEmpty() ) {
// it is a linked list, so the operation is fairly efficient
_handle = ((java.util.LinkedList<ProtobufMessages.FactHandle>)list).removeFirst();
if( list.isEmpty() ) {
map.remove(key);
}
}
}
}
if( _handle != null ) {
// create a handle with the given id
handle = workingMemory.getFactHandleFactory().newFactHandle( _handle.getId(),
object,
_handle.getRecency(),
objectTypeConf,
workingMemory,
null );
} else {
handle = workingMemory.getFactHandleFactory().newFactHandle( object,
objectTypeConf,
workingMemory,
null );
}
RightTuple rightTuple = newRightTuple( handle, null );
return rightTuple;
}
protected RightTuple newRightTuple(InternalFactHandle handle, Object o) {
return new RightTuple( handle,
null );
}
public void addToCreatedHandlesMap(final Map<Object, RightTuple> matches,
final RightTuple rightTuple) {
if ( rightTuple.getFactHandle().isValid() ) {
Object object = rightTuple.getFactHandle().getObject();
// keeping a list of matches
RightTuple existingMatch = matches.get( object );
if ( existingMatch != null ) {
// this is for the obscene case where two or more objects returned by "from"
// have the same hash code and evaluate equals() to true, so we need to preserve
// all of them to avoid leaks
rightTuple.setNext( existingMatch );
}
matches.put( object,
rightTuple );
}
}
public Memory createMemory(final RuleBaseConfiguration config, InternalWorkingMemory wm) {
BetaMemory beta = new BetaMemory( new LeftTupleList(),
null,
this.betaConstraints.createContext(),
NodeTypeEnums.FromNode );
return new FromMemory( beta,
this.dataProvider.createContext(),
this.alphaConstraints );
}
@Override
public LeftTuple createPeer(LeftTuple original) {
FromNodeLeftTuple peer = new FromNodeLeftTuple();
peer.initPeer( (BaseLeftTuple) original, this );
original.setPeer( peer );
return peer;
}
public boolean isLeftTupleMemoryEnabled() {
return tupleMemoryEnabled;
}
public void setLeftTupleMemoryEnabled(boolean tupleMemoryEnabled) {
this.tupleMemoryEnabled = tupleMemoryEnabled;
}
/**
* Returns the next node
* @return
* The next TupleSinkNode
*/
public LeftTupleSinkNode getNextLeftTupleSinkNode() {
return this.nextTupleSinkNode;
}
/**
* Sets the next node
* @param next
* The next TupleSinkNode
*/
public void setNextLeftTupleSinkNode(final LeftTupleSinkNode next) {
this.nextTupleSinkNode = next;
}
/**
* Returns the previous node
* @return
* The previous TupleSinkNode
*/
public LeftTupleSinkNode getPreviousLeftTupleSinkNode() {
return this.previousTupleSinkNode;
}
/**
* Sets the previous node
* @param previous
* The previous TupleSinkNode
*/
public void setPreviousLeftTupleSinkNode(final LeftTupleSinkNode previous) {
this.previousTupleSinkNode = previous;
}
public short getType() {
return NodeTypeEnums.FromNode;
}
public static class FromMemory extends AbstractBaseLinkedListNode<Memory>
implements
Serializable,
Memory {
private static final long serialVersionUID = 510l;
public BetaMemory betaMemory;
public Object providerContext;
public ContextEntry[] alphaContexts;
public FromMemory(BetaMemory betaMemory,
Object providerContext,
AlphaNodeFieldConstraint[] constraints) {
this.betaMemory = betaMemory;
this.providerContext = providerContext;
this.alphaContexts = new ContextEntry[constraints.length];
for ( int i = 0; i < constraints.length; i++ ) {
this.alphaContexts[i] = constraints[i].createContextEntry();
}
}
public short getNodeType() {
return NodeTypeEnums.FromNode;
}
public SegmentMemory getSegmentMemory() {
return betaMemory.getSegmentMemory();
}
public void setSegmentMemory(SegmentMemory segmentMemory) {
betaMemory.setSegmentMemory(segmentMemory);
}
public BetaMemory getBetaMemory() {
return betaMemory;
}
public void setBetaMemory(BetaMemory betaMemory) {
this.betaMemory = betaMemory;
}
}
public LeftTuple createLeftTuple(InternalFactHandle factHandle,
LeftTupleSink sink,
boolean leftTupleMemoryEnabled) {
return new FromNodeLeftTuple(factHandle, sink, leftTupleMemoryEnabled );
}
public LeftTuple createLeftTuple(final InternalFactHandle factHandle,
final LeftTuple leftTuple,
final LeftTupleSink sink) {
return new FromNodeLeftTuple(factHandle,leftTuple, sink );
}
public LeftTuple createLeftTuple(LeftTuple leftTuple,
LeftTupleSink sink,
PropagationContext pctx, boolean leftTupleMemoryEnabled) {
return new FromNodeLeftTuple(leftTuple, sink, pctx,
leftTupleMemoryEnabled );
}
public LeftTuple createLeftTuple(LeftTuple leftTuple,
RightTuple rightTuple,
LeftTupleSink sink) {
return new FromNodeLeftTuple(leftTuple, rightTuple, sink );
}
public LeftTuple createLeftTuple(LeftTuple leftTuple,
RightTuple rightTuple,
LeftTuple currentLeftChild,
LeftTuple currentRightChild,
LeftTupleSink sink,
boolean leftTupleMemoryEnabled) {
return new FromNodeLeftTuple(leftTuple, rightTuple, currentLeftChild, currentRightChild, sink, leftTupleMemoryEnabled );
}
public LeftTupleSource getLeftTupleSource() {
return this.leftInput;
}
protected ObjectTypeNode getObjectTypeNode() {
return leftInput.getObjectTypeNode();
}
@Override
public void assertLeftTuple(LeftTuple leftTuple, PropagationContext context, InternalWorkingMemory workingMemory) {
throw new UnsupportedOperationException();
}
@Override
public void retractLeftTuple(LeftTuple leftTuple, PropagationContext context, InternalWorkingMemory workingMemory) {
throw new UnsupportedOperationException();
}
@Override
public void modifyLeftTuple(InternalFactHandle factHandle, ModifyPreviousTuples modifyPreviousTuples, PropagationContext context, InternalWorkingMemory workingMemory) {
throw new UnsupportedOperationException();
}
@Override
public void updateSink(LeftTupleSink sink, PropagationContext context, InternalWorkingMemory workingMemory) {
throw new UnsupportedOperationException();
}
@Override
public void modifyLeftTuple(LeftTuple leftTuple, PropagationContext context, InternalWorkingMemory workingMemory) {
throw new UnsupportedOperationException();
}
public void attach( BuildContext context ) {
betaConstraints.init(context, getType());
this.leftInput.addTupleSink( this, context );
}
protected void doRemove(final RuleRemovalContext context,
final ReteooBuilder builder,
final InternalWorkingMemory[] workingMemories) {
if ( !this.isInUse() ) {
getLeftTupleSource().removeTupleSink( this );
}
}
}
| drools-core/src/main/java/org/drools/core/reteoo/FromNode.java | /*
* Copyright 2010 JBoss 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.drools.core.reteoo;
import org.drools.core.RuleBaseConfiguration;
import org.drools.core.base.ClassObjectType;
import org.drools.core.common.BetaConstraints;
import org.drools.core.common.EmptyBetaConstraints;
import org.drools.core.common.InternalFactHandle;
import org.drools.core.common.InternalRuleBase;
import org.drools.core.common.InternalWorkingMemory;
import org.drools.core.common.Memory;
import org.drools.core.common.MemoryFactory;
import org.drools.core.common.UpdateContext;
import org.drools.core.util.AbstractBaseLinkedListNode;
import org.drools.core.util.index.LeftTupleList;
import org.drools.core.marshalling.impl.PersisterHelper;
import org.drools.core.marshalling.impl.ProtobufInputMarshaller;
import org.drools.core.marshalling.impl.ProtobufInputMarshaller.TupleKey;
import org.drools.core.marshalling.impl.ProtobufMessages;
import org.drools.core.marshalling.impl.ProtobufMessages.FactHandle;
import org.drools.core.reteoo.builder.BuildContext;
import org.drools.core.rule.ContextEntry;
import org.drools.core.rule.From;
import org.drools.core.spi.AlphaNodeFieldConstraint;
import org.drools.core.spi.DataProvider;
import org.drools.core.spi.PropagationContext;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
public class FromNode extends LeftTupleSource
implements
LeftTupleSinkNode,
MemoryFactory {
private static final long serialVersionUID = 510l;
protected DataProvider dataProvider;
protected AlphaNodeFieldConstraint[] alphaConstraints;
protected BetaConstraints betaConstraints;
protected LeftTupleSinkNode previousTupleSinkNode;
protected LeftTupleSinkNode nextTupleSinkNode;
protected From from;
protected Class<?> resultClass;
protected boolean tupleMemoryEnabled;
protected transient ObjectTypeConf objectTypeConf;
public FromNode() {
}
public FromNode(final int id,
final DataProvider dataProvider,
final LeftTupleSource tupleSource,
final AlphaNodeFieldConstraint[] constraints,
final BetaConstraints binder,
final boolean tupleMemoryEnabled,
final BuildContext context,
final From from) {
super( id,
context.getPartitionId(),
context.getRuleBase().getConfiguration().isMultithreadEvaluation() );
this.dataProvider = dataProvider;
setLeftTupleSource(tupleSource);
this.alphaConstraints = constraints;
this.betaConstraints = (binder == null) ? EmptyBetaConstraints.getInstance() : binder;
this.tupleMemoryEnabled = tupleMemoryEnabled;
this.from = from;
resultClass = ((ClassObjectType)this.from.getResultPattern().getObjectType()).getClassType();
initMasks(context, tupleSource);
}
public void readExternal(ObjectInput in) throws IOException,
ClassNotFoundException {
super.readExternal( in );
dataProvider = (DataProvider) in.readObject();
alphaConstraints = (AlphaNodeFieldConstraint[]) in.readObject();
betaConstraints = (BetaConstraints) in.readObject();
tupleMemoryEnabled = in.readBoolean();
from = (From) in.readObject();
resultClass = ((ClassObjectType)this.from.getResultPattern().getObjectType()).getClassType();
}
public void writeExternal(ObjectOutput out) throws IOException {
super.writeExternal( out );
out.writeObject( dataProvider );
out.writeObject( alphaConstraints );
out.writeObject( betaConstraints );
out.writeBoolean( tupleMemoryEnabled );
out.writeObject( from );
}
public DataProvider getDataProvider() {
return dataProvider;
}
public AlphaNodeFieldConstraint[] getAlphaConstraints() {
return alphaConstraints;
}
public BetaConstraints getBetaConstraints() {
return betaConstraints;
}
public Class< ? > getResultClass() {
return resultClass;
}
public void networkUpdated(UpdateContext updateContext) {
this.leftInput.networkUpdated(updateContext);
}
@SuppressWarnings("unchecked")
public RightTuple createRightTuple( final LeftTuple leftTuple,
final PropagationContext context,
final InternalWorkingMemory workingMemory,
final Object object ) {
InternalFactHandle handle;
ProtobufMessages.FactHandle _handle = null;
if ( objectTypeConf == null ) {
// use default entry point and object class. Notice that at this point object is assignable to resultClass
objectTypeConf = new ClassObjectTypeConf( workingMemory.getEntryPoint(), resultClass, (InternalRuleBase) workingMemory.getRuleBase() );
}
if( context.getReaderContext() != null ) {
Map<ProtobufInputMarshaller.TupleKey, List<FactHandle>> map = (Map<ProtobufInputMarshaller.TupleKey, List<ProtobufMessages.FactHandle>>) context.getReaderContext().nodeMemories.get( getId() );
if( map != null ) {
TupleKey key = PersisterHelper.createTupleKey(leftTuple);
List<FactHandle> list = map.get( key );
if( list == null || list.isEmpty() ) {
map.remove( key );
} else {
// it is a linked list, so the operation is fairly efficient
_handle = ((java.util.LinkedList<ProtobufMessages.FactHandle>)list).removeFirst();
}
}
}
if( _handle != null ) {
// create a handle with the given id
handle = workingMemory.getFactHandleFactory().newFactHandle( _handle.getId(),
object,
_handle.getRecency(),
objectTypeConf,
workingMemory,
null );
} else {
handle = workingMemory.getFactHandleFactory().newFactHandle( object,
objectTypeConf,
workingMemory,
null );
}
RightTuple rightTuple = newRightTuple( handle, null );
return rightTuple;
}
protected RightTuple newRightTuple(InternalFactHandle handle, Object o) {
return new RightTuple( handle,
null );
}
public void addToCreatedHandlesMap(final Map<Object, RightTuple> matches,
final RightTuple rightTuple) {
if ( rightTuple.getFactHandle().isValid() ) {
Object object = rightTuple.getFactHandle().getObject();
// keeping a list of matches
RightTuple existingMatch = matches.get( object );
if ( existingMatch != null ) {
// this is for the obscene case where two or more objects returned by "from"
// have the same hash code and evaluate equals() to true, so we need to preserve
// all of them to avoid leaks
rightTuple.setNext( existingMatch );
}
matches.put( object,
rightTuple );
}
}
public Memory createMemory(final RuleBaseConfiguration config, InternalWorkingMemory wm) {
BetaMemory beta = new BetaMemory( new LeftTupleList(),
null,
this.betaConstraints.createContext(),
NodeTypeEnums.FromNode );
return new FromMemory( beta,
this.dataProvider.createContext(),
this.alphaConstraints );
}
@Override
public LeftTuple createPeer(LeftTuple original) {
FromNodeLeftTuple peer = new FromNodeLeftTuple();
peer.initPeer( (BaseLeftTuple) original, this );
original.setPeer( peer );
return peer;
}
public boolean isLeftTupleMemoryEnabled() {
return tupleMemoryEnabled;
}
public void setLeftTupleMemoryEnabled(boolean tupleMemoryEnabled) {
this.tupleMemoryEnabled = tupleMemoryEnabled;
}
/**
* Returns the next node
* @return
* The next TupleSinkNode
*/
public LeftTupleSinkNode getNextLeftTupleSinkNode() {
return this.nextTupleSinkNode;
}
/**
* Sets the next node
* @param next
* The next TupleSinkNode
*/
public void setNextLeftTupleSinkNode(final LeftTupleSinkNode next) {
this.nextTupleSinkNode = next;
}
/**
* Returns the previous node
* @return
* The previous TupleSinkNode
*/
public LeftTupleSinkNode getPreviousLeftTupleSinkNode() {
return this.previousTupleSinkNode;
}
/**
* Sets the previous node
* @param previous
* The previous TupleSinkNode
*/
public void setPreviousLeftTupleSinkNode(final LeftTupleSinkNode previous) {
this.previousTupleSinkNode = previous;
}
public short getType() {
return NodeTypeEnums.FromNode;
}
public static class FromMemory extends AbstractBaseLinkedListNode<Memory>
implements
Serializable,
Memory {
private static final long serialVersionUID = 510l;
public BetaMemory betaMemory;
public Object providerContext;
public ContextEntry[] alphaContexts;
public FromMemory(BetaMemory betaMemory,
Object providerContext,
AlphaNodeFieldConstraint[] constraints) {
this.betaMemory = betaMemory;
this.providerContext = providerContext;
this.alphaContexts = new ContextEntry[constraints.length];
for ( int i = 0; i < constraints.length; i++ ) {
this.alphaContexts[i] = constraints[i].createContextEntry();
}
}
public short getNodeType() {
return NodeTypeEnums.FromNode;
}
public SegmentMemory getSegmentMemory() {
return betaMemory.getSegmentMemory();
}
public void setSegmentMemory(SegmentMemory segmentMemory) {
betaMemory.setSegmentMemory(segmentMemory);
}
public BetaMemory getBetaMemory() {
return betaMemory;
}
public void setBetaMemory(BetaMemory betaMemory) {
this.betaMemory = betaMemory;
}
}
public LeftTuple createLeftTuple(InternalFactHandle factHandle,
LeftTupleSink sink,
boolean leftTupleMemoryEnabled) {
return new FromNodeLeftTuple(factHandle, sink, leftTupleMemoryEnabled );
}
public LeftTuple createLeftTuple(final InternalFactHandle factHandle,
final LeftTuple leftTuple,
final LeftTupleSink sink) {
return new FromNodeLeftTuple(factHandle,leftTuple, sink );
}
public LeftTuple createLeftTuple(LeftTuple leftTuple,
LeftTupleSink sink,
PropagationContext pctx, boolean leftTupleMemoryEnabled) {
return new FromNodeLeftTuple(leftTuple, sink, pctx,
leftTupleMemoryEnabled );
}
public LeftTuple createLeftTuple(LeftTuple leftTuple,
RightTuple rightTuple,
LeftTupleSink sink) {
return new FromNodeLeftTuple(leftTuple, rightTuple, sink );
}
public LeftTuple createLeftTuple(LeftTuple leftTuple,
RightTuple rightTuple,
LeftTuple currentLeftChild,
LeftTuple currentRightChild,
LeftTupleSink sink,
boolean leftTupleMemoryEnabled) {
return new FromNodeLeftTuple(leftTuple, rightTuple, currentLeftChild, currentRightChild, sink, leftTupleMemoryEnabled );
}
public LeftTupleSource getLeftTupleSource() {
return this.leftInput;
}
protected ObjectTypeNode getObjectTypeNode() {
return leftInput.getObjectTypeNode();
}
@Override
public void assertLeftTuple(LeftTuple leftTuple, PropagationContext context, InternalWorkingMemory workingMemory) {
throw new UnsupportedOperationException();
}
@Override
public void retractLeftTuple(LeftTuple leftTuple, PropagationContext context, InternalWorkingMemory workingMemory) {
throw new UnsupportedOperationException();
}
@Override
public void modifyLeftTuple(InternalFactHandle factHandle, ModifyPreviousTuples modifyPreviousTuples, PropagationContext context, InternalWorkingMemory workingMemory) {
throw new UnsupportedOperationException();
}
@Override
public void updateSink(LeftTupleSink sink, PropagationContext context, InternalWorkingMemory workingMemory) {
throw new UnsupportedOperationException();
}
@Override
public void modifyLeftTuple(LeftTuple leftTuple, PropagationContext context, InternalWorkingMemory workingMemory) {
throw new UnsupportedOperationException();
}
public void attach( BuildContext context ) {
betaConstraints.init(context, getType());
this.leftInput.addTupleSink( this, context );
}
protected void doRemove(final RuleRemovalContext context,
final ReteooBuilder builder,
final InternalWorkingMemory[] workingMemories) {
if ( !this.isInUse() ) {
getLeftTupleSource().removeTupleSink( this );
}
}
}
| [DROOLS-376] avoid NPE on JPAKnowledgeService.loadStatefulKnowledgeSession() when Collection is modified
| drools-core/src/main/java/org/drools/core/reteoo/FromNode.java | [DROOLS-376] avoid NPE on JPAKnowledgeService.loadStatefulKnowledgeSession() when Collection is modified | <ide><path>rools-core/src/main/java/org/drools/core/reteoo/FromNode.java
<ide> if( map != null ) {
<ide> TupleKey key = PersisterHelper.createTupleKey(leftTuple);
<ide> List<FactHandle> list = map.get( key );
<del> if( list == null || list.isEmpty() ) {
<del> map.remove( key );
<del> } else {
<add> if( list != null && ! list.isEmpty() ) {
<ide> // it is a linked list, so the operation is fairly efficient
<ide> _handle = ((java.util.LinkedList<ProtobufMessages.FactHandle>)list).removeFirst();
<add> if( list.isEmpty() ) {
<add> map.remove(key);
<add> }
<ide> }
<ide> }
<ide> } |
|
Java | apache-2.0 | bdfac560268dd144f36087557693a5e048ce55ab | 0 | vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa | // Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.zookeeper;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.admin.ZooKeeperAdmin;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* @author hmusum
*/
@SuppressWarnings("unused") // Created by injection
public class VespaZooKeeperAdminImpl implements VespaZooKeeperAdmin {
private static final Logger log = java.util.logging.Logger.getLogger(VespaZooKeeperAdminImpl.class.getName());
@Override
public void reconfigure(String connectionSpec, String joiningServers, String leavingServers) throws ReconfigException {
ZooKeeperAdmin zooKeeperAdmin = null;
try {
zooKeeperAdmin = createAdmin(connectionSpec);
long fromConfig = -1;
// Using string parameters because the List variant of reconfigure fails to join empty lists (observed on 3.5.6, fixed in 3.7.0)
byte[] appliedConfig = zooKeeperAdmin.reconfigure(joiningServers, leavingServers, null, fromConfig, null);
log.log(Level.INFO, "Applied ZooKeeper config: " + new String(appliedConfig, StandardCharsets.UTF_8));
} catch (KeeperException e) {
if (retryOn(e))
throw new ReconfigException(e);
else
throw new RuntimeException(e);
} catch (IOException | InterruptedException e) {
throw new RuntimeException(e);
} finally {
if (zooKeeperAdmin != null) {
try {
zooKeeperAdmin.close();
} catch (InterruptedException e) {
}
}
}
}
private ZooKeeperAdmin createAdmin(String connectionSpec) throws IOException {
return new ZooKeeperAdmin(connectionSpec, (int) sessionTimeout().toMillis(),
(event) -> log.log(Level.INFO, event.toString()));
}
private static boolean retryOn(KeeperException e) {
return e instanceof KeeperException.ReconfigInProgress ||
e instanceof KeeperException.ConnectionLossException ||
e instanceof KeeperException.NewConfigNoQuorum;
}
}
| zookeeper-server/zookeeper-server-3.6.2/src/main/java/com/yahoo/vespa/zookeeper/VespaZooKeeperAdminImpl.java | // Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.zookeeper;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.admin.ZooKeeperAdmin;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* @author hmusum
*/
@SuppressWarnings("unused") // Created by injection
public class VespaZooKeeperAdminImpl implements VespaZooKeeperAdmin {
private static final Logger log = java.util.logging.Logger.getLogger(VespaZooKeeperAdminImpl.class.getName());
@Override
public void reconfigure(String connectionSpec, String joiningServers, String leavingServers) throws ReconfigException {
try {
ZooKeeperAdmin zooKeeperAdmin = new ZooKeeperAdmin(connectionSpec,
(int) sessionTimeout().toMillis(),
(event) -> log.log(Level.INFO, event.toString()));
long fromConfig = -1;
// Using string parameters because the List variant of reconfigure fails to join empty lists (observed on 3.5.6, fixed in 3.7.0)
byte[] appliedConfig = zooKeeperAdmin.reconfigure(joiningServers, leavingServers, null, fromConfig, null);
log.log(Level.INFO, "Applied ZooKeeper config: " + new String(appliedConfig, StandardCharsets.UTF_8));
} catch (KeeperException e) {
if (retryOn(e))
throw new ReconfigException(e);
else
throw new RuntimeException(e);
} catch (IOException | InterruptedException e) {
throw new RuntimeException(e);
}
}
private static boolean retryOn(KeeperException e) {
return e instanceof KeeperException.ReconfigInProgress ||
e instanceof KeeperException.ConnectionLossException ||
e instanceof KeeperException.NewConfigNoQuorum;
}
}
| Ensure theat we close the ZooKeeperAdmin. Unfortunately The ZooKeeper.close throw Interrupted exception which
make the compiler complain when used in try-with-resource is must be doen manually with finally clause.
| zookeeper-server/zookeeper-server-3.6.2/src/main/java/com/yahoo/vespa/zookeeper/VespaZooKeeperAdminImpl.java | Ensure theat we close the ZooKeeperAdmin. Unfortunately The ZooKeeper.close throw Interrupted exception which make the compiler complain when used in try-with-resource is must be doen manually with finally clause. | <ide><path>ookeeper-server/zookeeper-server-3.6.2/src/main/java/com/yahoo/vespa/zookeeper/VespaZooKeeperAdminImpl.java
<ide>
<ide> @Override
<ide> public void reconfigure(String connectionSpec, String joiningServers, String leavingServers) throws ReconfigException {
<add> ZooKeeperAdmin zooKeeperAdmin = null;
<ide> try {
<del> ZooKeeperAdmin zooKeeperAdmin = new ZooKeeperAdmin(connectionSpec,
<del> (int) sessionTimeout().toMillis(),
<del> (event) -> log.log(Level.INFO, event.toString()));
<add> zooKeeperAdmin = createAdmin(connectionSpec);
<ide> long fromConfig = -1;
<ide> // Using string parameters because the List variant of reconfigure fails to join empty lists (observed on 3.5.6, fixed in 3.7.0)
<ide> byte[] appliedConfig = zooKeeperAdmin.reconfigure(joiningServers, leavingServers, null, fromConfig, null);
<ide> throw new RuntimeException(e);
<ide> } catch (IOException | InterruptedException e) {
<ide> throw new RuntimeException(e);
<add> } finally {
<add> if (zooKeeperAdmin != null) {
<add> try {
<add> zooKeeperAdmin.close();
<add> } catch (InterruptedException e) {
<add> }
<add> }
<ide> }
<add> }
<add>
<add> private ZooKeeperAdmin createAdmin(String connectionSpec) throws IOException {
<add> return new ZooKeeperAdmin(connectionSpec, (int) sessionTimeout().toMillis(),
<add> (event) -> log.log(Level.INFO, event.toString()));
<ide> }
<ide>
<ide> private static boolean retryOn(KeeperException e) { |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.