repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
techblue/jasperserver-restclient | src/test/java/com/barbon/jasperclient/service/tests/RoleServiceTest.java | 2939 | /*******************************************************************************
* Copyright 2013, Barbon. All Rights Reserved.
* No part of this content may be used without Barbon's express consent.
******************************************************************************/
package com.barbon.jasperclient.service.tests;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import uk.co.techblue.jasperclient.dto.Credentials;
import uk.co.techblue.jasperclient.dto.Role;
import uk.co.techblue.jasperclient.dto.Roles;
import uk.co.techblue.jasperclient.exception.CustomException;
import uk.co.techblue.jasperclient.service.RoleService;
import uk.co.techblue.jasperclient.utility.UtilityConstants;
/**
* RoleServiceTest.java
*
* @author <a href="mailto:dishant.anand@techblue.co.uk">Dishant Anand</a>
*/
public class RoleServiceTest {
/** The role service. */
private RoleService roleService;
/**
* Before test execution.
*/
@Before
public void beforeTestExecution() {
roleService = new RoleService(UtilityConstants.JASPER_SERVER_HOST_URI, new Credentials("jasperadmin", "jasperadmin"));
}
/**
* Test search all roles.
*/
@Test
public void testSearchAllRoles() {
Roles roles = null;
try {
roles = roleService.searchAllRoles();
} catch (CustomException customException) {
customException.printStackTrace();
}
Assert.assertNotNull(roles);
}
/**
* Test search specific roles.
*/
@Test
public void testSearchSpecificRoles() {
Roles roles = null;
try {
roles = roleService.searchSpecificRoles("User");
} catch (CustomException customException) {
customException.printStackTrace();
}
Assert.assertNotNull(roles);
}
/**
* Test search role.
*/
@Test
public void testSearchRole() {
Role role = null;
try {
role = roleService.searchRole("ROLE_DEMO");
} catch (CustomException customException) {
customException.printStackTrace();
}
Assert.assertNotNull(role);
}
/**
* Test create role.
*/
@Test
public void testCreateRole() {
Role role = new Role();
role.setExternallyDefined(true);
role.setRoleType("ROLE_DEMO");
try {
roleService.createRole("ROLE_DEMO", role);
} catch (CustomException e) {
e.printStackTrace();
}
}
/**
* Test delete role.
*/
@Test
public void testDeleteRole() {
try {
roleService.deleteRole("joeUser");
} catch (CustomException customException) {
customException.printStackTrace();
}
}
}
| apache-2.0 |
LesserGiraffe/BunnyHop | src/main/java/module-info.java | 2323 | /**
* Copyright 2017 K.Koike
*
* 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.
*/
module net.seapanda.bunnyhop {
requires java.xml;
requires java.rmi;
requires java.scripting;
requires java.desktop;
requires transitive javafx.graphics;
requires transitive javafx.controls;
requires javafx.fxml;
requires transitive javafx.base;
requires rhino;
requires jsch;
requires org.apache.commons.lang3;
//requires org.scenicview.scenicview;
exports net.seapanda.bunnyhop.root;
exports net.seapanda.bunnyhop.model;
exports net.seapanda.bunnyhop.model.node;
exports net.seapanda.bunnyhop.model.node.attribute;
exports net.seapanda.bunnyhop.model.node.connective;
exports net.seapanda.bunnyhop.model.node.event;
exports net.seapanda.bunnyhop.model.node.imitation;
exports net.seapanda.bunnyhop.model.templates;
exports net.seapanda.bunnyhop.modelservice;
exports net.seapanda.bunnyhop.modelprocessor;
exports net.seapanda.bunnyhop.model.syntaxsynbol;
exports net.seapanda.bunnyhop.common;
exports net.seapanda.bunnyhop.common.tools;
exports net.seapanda.bunnyhop.common.constant;
exports net.seapanda.bunnyhop.message;
exports net.seapanda.bunnyhop.bhprogram.common; //[java -jar BhProgramExecEnv.jar] を自己完結型の Javaから呼ぶために必要
exports net.seapanda.bunnyhop.view;
exports net.seapanda.bunnyhop.view.node;
exports net.seapanda.bunnyhop.view.node.part;
opens net.seapanda.bunnyhop.view to javafx.fxml;
opens net.seapanda.bunnyhop.view.workspace to javafx.fxml;
opens net.seapanda.bunnyhop.view.nodeselection to javafx.fxml;
opens net.seapanda.bunnyhop.control to javafx.fxml;
opens net.seapanda.bunnyhop.control.workspace to javafx.fxml;
opens net.seapanda.bunnyhop.control.nodeselection to javafx.fxml;
}
| apache-2.0 |
nakamura5akihito/opensec-oval | src/main/java/io/opensec/oval/model/common/package-info.java | 234 | /**
* Defines a Java object model for
* the common types that are shared across the different schemas within OVAL.
*
* @see <a href="http://oval.mitre.org/language/">OVAL Language</a>
*/
package io.opensec.oval.model.common;
| apache-2.0 |
Roanis/atg-tdd | Core/src/main/java/com/roanis/tdd/nucleus/TddNucleusTestUtils.java | 10382 | package com.roanis.tdd.nucleus;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import atg.nucleus.Nucleus;
import atg.nucleus.NucleusTestUtils;
import atg.nucleus.NucleusTestUtils.NucleusStartupOptions;
import atg.nucleus.ServiceException;
import atg.nucleus.naming.ComponentName;
import atg.servlet.DynamoHttpServletRequest;
import atg.servlet.ServletTestUtils;
import atg.servlet.ServletTestUtils.TestingDynamoHttpServletRequest;
import atg.servlet.ServletUtil;
import com.google.common.base.Strings;
import com.google.common.collect.Maps;
/**
* Utility methods for working with Nucleus.
*
* @author rory
*
*/
public class TddNucleusTestUtils {
public static final Logger log = Logger.getLogger(TddNucleusTestUtils.class);
public static final String META_INF_DIR_NAME = "META-INF";
public static final String MANIFEST_FILE_NAME = "MANIFEST.MF";
public static final String MANIFEST_BACKUP_EXTENSION = ".BAK";
public static final String ATG_CONFIG_PATH_ATTRIBUTE_NAME = "ATG-Config-Path: ";
public static final String ATG_REQUIRED_PATH_ATTRIBUTE_NAME = "ATG-Required: ";
public static final String TDD_REQUIRED_MODULES = "TDD.Core";
public static final String TEST_CONFIG_LAYER_NAME = "testconfig";
/**
* Start Nucleus with the specified module list.
*
* @param moduleList - the list of ATG modules to start
* @param testClass - the test class or suite which is invoking this method
* @return - the running Nucleus
* @throws Throwable
*/
public static Nucleus startNucleus (List<String> moduleList, boolean isUseTestConfigLayer, Class<?> testClass) throws Throwable {
preStartNucleus(moduleList, isUseTestConfigLayer, testClass);
Nucleus nucleus = doStartNucleus(moduleList, isUseTestConfigLayer, testClass);
postStartNucleus(nucleus, moduleList, isUseTestConfigLayer, testClass);
return nucleus;
}
private static void preStartNucleus(List<String> moduleList, boolean isUseTestConfigLayer, Class<?> testClass) throws Throwable {
System.out.println("TDD by Rory Curtis: rory_curtis@roanis.com");
validateModules(moduleList);
validateATGInstall();
if(isUseTestConfigLayer){
addTestConfigPath(moduleList, testClass);
}
addTddToModules(moduleList);
}
protected static void addTddToModules(List<String> moduleList) {
moduleList.add(TDD_REQUIRED_MODULES);
}
private static Nucleus doStartNucleus(List<String> moduleList, boolean isUseTestConfigLayer, Class<?> testClass) throws Throwable {
// Fire up Nucleus - make sure DYNAMO_HOME and DUST_HOME are set.
String initialComponent = "/atg/dynamo/Configuration";
NucleusStartupOptions startupOptions = null;
// Make sure to get the testConfigDir, before adding TDD.Core to the front of the module list.
String testConfigDir=getTestConfigPath(moduleList);
if(isUseTestConfigLayer){
startupOptions = new NucleusStartupOptions(moduleList.toArray(new String[0]), testClass, testConfigDir, initialComponent);
} else {
startupOptions = new NucleusStartupOptions(moduleList.toArray(new String[0]), testClass, initialComponent);
}
Nucleus nucleus = NucleusTestUtils.startNucleusWithModules(startupOptions);
if (null == nucleus) {
throw new Exception("Unable to start Nucleus for unit tests.");
}
return nucleus;
}
private static void addTestConfigPath(List<String> moduleList, Class<?> testClass) throws Throwable {
String testConfigPath=getTestConfigPath(moduleList);
File testConfigDir=getTestConfigDirAsFile(moduleList);
updateNucleusConfigProperty(testClass, testConfigPath, testConfigDir);
return;
}
@SuppressWarnings("unchecked")
private static void updateNucleusConfigProperty(Class<?> testClass, String testConfigPath, File testConfigDir) throws NoSuchFieldException, IllegalAccessException {
Field field = NucleusTestUtils.class.getDeclaredField("sConfigDir");
field.setAccessible(true);
Map<Class<?>, Map<String, File>> value = (Map<Class<?>, Map<String, File>>) field.get(null);
Map<String, File> testConfig= Maps.newHashMap();
testConfig.put(testConfigPath, testConfigDir);
value.put(testClass, testConfig);
}
private static void postStartNucleus(Nucleus nucleus, List<String> moduleList, boolean isUseTestConfigLayer, Class<?> testClass) {
initialiseRequestResponsePair();
}
public static void validateModules(List<String> moduleList) throws Exception {
if ((null == moduleList) || (0 == moduleList.size())) {
throw new Exception("A module list must be specfied when starting Nucleus.");
}
}
public static void validateATGInstall() {
if(! isATGInstallAvailable()){
throw new RuntimeException("No ATG install could be found from DYNAMO_HOME["+dynamoHomeAsString()+"], or ATG_HOME ["+atgHomeAsString()+"]");
}
}
public static String getTestConfigPath(List<String> moduleList) throws IOException {
String atgHome = getATGHome();
String moduleName=moduleList.get(0);
String moduleDir = atgHome + moduleName.replace(".", File.separator);
String testConfigPath=moduleDir + File.separator + TEST_CONFIG_LAYER_NAME;
return testConfigPath;
}
protected static boolean testConfigLayerExists(List<String> moduleList) throws Throwable {
return null != getTestConfigDirAsFile(moduleList);
}
protected static File getTestConfigDirAsFile(List<String> moduleList) throws Throwable {
File testConfigDir = new File(getTestConfigPath(moduleList));
return testConfigDir;
}
protected static void backupManifestFile(String moduleDir) throws IOException {
String manifestBackupPath = getBackupManifestPath(moduleDir);
File manifestBackupFile = new File(manifestBackupPath);
if(manifestBackupFile.exists()){
System.out.println("WARN: A backup of the manifest file already exists in:[" +moduleDir +"]. This usually happens when a previous test run has been terminated early. It can be fixed by just doing a full test run." );
return;
}
String manifestPath = getManifestPath(moduleDir);
FileUtils.copyFile(new File(manifestPath), manifestBackupFile);
}
protected static String getManifestPath(String moduleDir){
String manifestFileLocation = getManifestFileLocation(moduleDir);
File manifestFile = new File(manifestFileLocation);
if(! manifestFile.exists()){
throw new RuntimeException("The specified Manifest file doesn't exist: " + manifestFileLocation);
}
return manifestFileLocation;
}
protected static String getManifestFileLocation(String moduleDir) {
String manifestLocation = new StringBuilder(moduleDir).append(File.separator).append(META_INF_DIR_NAME).append(File.separator).append(MANIFEST_FILE_NAME).toString();
return manifestLocation;
}
protected static String getBackupManifestPath(String moduleDir){
return getManifestFileLocation(moduleDir) + ".BAK";
}
protected static void addTddDependencies(List<String> manifestContent) {
for (int i = 0; i < manifestContent.size(); i++) {
String manifestEntry = manifestContent.get(i);
if(manifestEntry.startsWith(ATG_REQUIRED_PATH_ATTRIBUTE_NAME)){
String moduleList = manifestEntry.substring(ATG_REQUIRED_PATH_ATTRIBUTE_NAME.length());
String newDependencyList = TDD_REQUIRED_MODULES + " " + moduleList;
String newAtgRequired = ATG_REQUIRED_PATH_ATTRIBUTE_NAME + newDependencyList;
manifestContent.set(i, newAtgRequired);
return;
}
}
}
protected static String getATGHome() {
String dynamoRoot = findDynamoRootDir();
if(Strings.isNullOrEmpty(dynamoRoot)){
throw new RuntimeException("Couldn't find an ATG install. Either set a DYNAMO_HOME or ATG_HOME environment variable. Alternatively, if you don't have an ATG install, the tests can be ignored by setting the tdd.ignoreMissingATGInstall system property to true.");
}
return dynamoRoot;
}
/**
* Stop the specified running Nucleus.
*
* @param nucleus - a running Nucleus.
*/
public static void shutdownNucleus (Nucleus nucleus, List<String> moduleList, boolean isUseTestConfigLayer) {
if (nucleus != null) {
try {
NucleusTestUtils.shutdownNucleus(nucleus);
} catch (ServiceException e) {
log.error(e);
} catch (IOException e) {
log.error(e);
}
}
}
public static String findDynamoRootDir(){
String dynamoRoot = dynamoHomeAsString();
if(Strings.isNullOrEmpty(dynamoRoot)){
dynamoRoot = atgHomeAsString();
}
if(! Strings.isNullOrEmpty(dynamoRoot)){
System.setProperty("atg.dynamo.root", dynamoRoot);
}
return dynamoRoot;
}
public static String dynamoHomeAsString(){
String dynamoHome = System.getenv("DYNAMO_HOME");
if(! Strings.isNullOrEmpty(dynamoHome)){
return dynamoHome + File.separator + ".." + File.separator;
}
return null;
}
public static String atgHomeAsString(){
return System.getenv("ATG_HOME");
}
public static boolean isATGInstallAvailable() {
String dynamoRoot = findDynamoRootDir();
if(Strings.isNullOrEmpty(dynamoRoot)){
return false;
}
File file = new File(dynamoRoot);
return file.exists();
}
public static void initialiseRequestResponsePair(){
ServletTestUtils servletTestUtils = new ServletTestUtils();
TestingDynamoHttpServletRequest request = servletTestUtils.createDynamoHttpServletRequestForSession(Nucleus.getGlobalNucleus(), "1234", null);
request.setLoggingWarning(false);
request.prepareForRead();
ServletUtil.setCurrentRequest(request);
ServletUtil.setCurrentResponse(servletTestUtils.createDynamoHttpServletResponse());
}
public static Object resolveComponent(String componentPath){
ComponentName componentName = ComponentName.getComponentName(componentPath);
Object component = null;
try {
DynamoHttpServletRequest currentRequest = ServletUtil.getCurrentRequest();
if(null != currentRequest){
component = currentRequest.resolveName(componentName);
}
} catch (IllegalStateException e){
component = Nucleus.getGlobalNucleus().resolveName(componentName);
}
return component;
}
}
| apache-2.0 |
weipoint/j2objc | src/main/java/com/google/devtools/j2objc/translate/DestructorGenerator.java | 8336 | /*
* Copyright 2011 Google 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.google.devtools.j2objc.translate;
import com.google.common.collect.Lists;
import com.google.devtools.j2objc.Options;
import com.google.devtools.j2objc.types.GeneratedMethodBinding;
import com.google.devtools.j2objc.types.Types;
import com.google.devtools.j2objc.util.ErrorReportingASTVisitor;
import com.google.devtools.j2objc.util.NameTable;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTVisitor;
import org.eclipse.jdt.core.dom.Assignment;
import org.eclipse.jdt.core.dom.BodyDeclaration;
import org.eclipse.jdt.core.dom.ExpressionStatement;
import org.eclipse.jdt.core.dom.FieldDeclaration;
import org.eclipse.jdt.core.dom.IMethodBinding;
import org.eclipse.jdt.core.dom.ITypeBinding;
import org.eclipse.jdt.core.dom.IVariableBinding;
import org.eclipse.jdt.core.dom.MethodDeclaration;
import org.eclipse.jdt.core.dom.MethodInvocation;
import org.eclipse.jdt.core.dom.Modifier;
import org.eclipse.jdt.core.dom.Modifier.ModifierKeyword;
import org.eclipse.jdt.core.dom.PrimitiveType;
import org.eclipse.jdt.core.dom.SimpleName;
import org.eclipse.jdt.core.dom.Statement;
import org.eclipse.jdt.core.dom.SuperMethodInvocation;
import org.eclipse.jdt.core.dom.TryStatement;
import org.eclipse.jdt.core.dom.Type;
import org.eclipse.jdt.core.dom.TypeDeclaration;
import org.eclipse.jdt.core.dom.VariableDeclarationFragment;
import java.util.List;
/**
* Adds release methods to Java classes, in preparation for translation
* to iOS. Because Objective-C allows messages to be sent to nil, all
* fields can be released regardless of whether they currently reference
* data.
*
* @author Tom Ball
*/
public class DestructorGenerator extends ErrorReportingASTVisitor {
private final String destructorName;
public static final String FINALIZE_METHOD = "finalize";
public static final String DEALLOC_METHOD = "dealloc";
public DestructorGenerator() {
destructorName = Options.useGC() ? FINALIZE_METHOD : DEALLOC_METHOD;
}
@Override
public boolean visit(TypeDeclaration node) {
final List<IVariableBinding> releaseableFields = Lists.newArrayList();
for (final FieldDeclaration field : node.getFields()) {
if (!field.getType().isPrimitiveType() && !isStatic(field)) {
ErrorReportingASTVisitor varFinder = new ErrorReportingASTVisitor() {
@Override
public boolean visit(VariableDeclarationFragment node) {
IVariableBinding binding = Types.getVariableBinding(node);
if (!Modifier.isStatic(field.getModifiers()) && !Types.isConstantVariable(binding)) {
releaseableFields.add(binding);
}
return true;
}
};
varFinder.run(field);
}
}
if (!releaseableFields.isEmpty()) {
Types.addReleaseableFields(releaseableFields);
boolean foundDestructor = false;
// If a destructor method already exists, append release statements.
for (MethodDeclaration method : node.getMethods()) {
if (FINALIZE_METHOD.equals(method.getName().getIdentifier())) {
addReleaseStatements(method, releaseableFields);
foundDestructor = true;
}
}
// No destructor, so create a new one.
if (!foundDestructor && !Options.useARC()) {
MethodDeclaration finalizeMethod =
buildFinalizeMethod(node.getAST(), Types.getTypeBinding(node), releaseableFields);
@SuppressWarnings("unchecked")
List<BodyDeclaration> declarations = node.bodyDeclarations();
declarations.add(finalizeMethod);
}
}
// Rename method to correct destructor name. This is down outside of
// the loop above, because a class may have a finalize() method but no
// releasable fields.
for (MethodDeclaration method : node.getMethods()) {
if (needsRenaming(method.getName())) {
NameTable.rename(Types.getBinding(method), destructorName);
}
}
return super.visit(node);
}
@Override
public boolean visit(MethodInvocation node) {
if (needsRenaming(node.getName())) {
NameTable.rename(Types.getBinding(node), destructorName);
}
return true;
}
@Override
public boolean visit(SuperMethodInvocation node) {
if (needsRenaming(node.getName())) {
NameTable.rename(Types.getBinding(node), destructorName);
}
return true;
}
private boolean isStatic(FieldDeclaration f) {
return (f.getModifiers() & Modifier.STATIC) != 0;
}
private boolean needsRenaming(SimpleName methodName) {
return destructorName.equals(DEALLOC_METHOD) &&
FINALIZE_METHOD.equals(methodName.getIdentifier());
}
@SuppressWarnings("unchecked")
private void addReleaseStatements(MethodDeclaration method, List<IVariableBinding> fields) {
// Find existing super.finalize(), if any.
final boolean[] hasSuperFinalize = new boolean[1];
method.accept(new ASTVisitor() {
@Override
public void endVisit(SuperMethodInvocation node) {
if (FINALIZE_METHOD.equals(node.getName().getIdentifier())) {
hasSuperFinalize[0] = true;
}
}
});
List<Statement> statements = method.getBody().statements(); // safe by definition
if (!statements.isEmpty() && statements.get(0) instanceof TryStatement) {
TryStatement tryStatement = ((TryStatement) statements.get(0));
if (tryStatement.getBody() != null) {
statements = tryStatement.getBody().statements(); // safe by definition
}
}
AST ast = method.getAST();
int index = statements.size();
for (IVariableBinding field : fields) {
if (!field.getType().isPrimitive() && !Types.isWeakReference(field)) {
Assignment assign = ast.newAssignment();
SimpleName receiver = ast.newSimpleName(field.getName());
Types.addBinding(receiver, field);
assign.setLeftHandSide(receiver);
assign.setRightHandSide(Types.newNullLiteral());
Types.addBinding(assign, field.getDeclaringClass());
ExpressionStatement stmt = ast.newExpressionStatement(assign);
statements.add(index, stmt);
}
}
if (Options.useReferenceCounting() && !hasSuperFinalize[0]) {
SuperMethodInvocation call = ast.newSuperMethodInvocation();
IMethodBinding methodBinding = Types.getMethodBinding(method);
GeneratedMethodBinding binding = new GeneratedMethodBinding(destructorName, Modifier.PUBLIC,
Types.mapTypeName("void"), methodBinding.getDeclaringClass(), false, false, true);
Types.addBinding(call, binding);
call.setName(ast.newSimpleName(destructorName));
Types.addBinding(call.getName(), binding);
ExpressionStatement stmt = ast.newExpressionStatement(call);
statements.add(stmt);
}
}
private MethodDeclaration buildFinalizeMethod(AST ast, ITypeBinding declaringClass,
List<IVariableBinding> fields) {
ITypeBinding voidType = Types.mapTypeName("void");
GeneratedMethodBinding binding = new GeneratedMethodBinding(destructorName, Modifier.PUBLIC,
voidType, declaringClass, false, false, true);
MethodDeclaration method = ast.newMethodDeclaration();
Types.addBinding(method, binding);
method.setName(ast.newSimpleName(destructorName));
Types.addBinding(method.getName(), binding);
@SuppressWarnings("unchecked")
List<Modifier> modifiers = method.modifiers();
modifiers.add(ast.newModifier(ModifierKeyword.PUBLIC_KEYWORD));
method.setBody(ast.newBlock());
addReleaseStatements(method, fields);
Type returnType = ast.newPrimitiveType(PrimitiveType.VOID);
Types.addBinding(returnType, ast.resolveWellKnownType("void"));
method.setReturnType2(returnType);
return method;
}
}
| apache-2.0 |
yshahun/succinct-dom | src/main/java/ys/succinct/xml/dom/ElementImpl.java | 7118 | /*
* Copyright 2014 Yauheni Shahun
*
* 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 ys.succinct.xml.dom;
import org.w3c.dom.Attr;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.TypeInfo;
/**
* A succinct {@link Element} node. Internal {@code ordinalIndex} is treated as the index of the
* node in the non-text node store.
*
* @author Yauheni Shahun
*/
public class ElementImpl extends AbstractSuccinctNode implements Element {
/**
* Cached collection of the attributes of the element.
*/
private NamedNodeMap attributes;
/**
* Constructs a succinct element node.
*
* @param dom the succinct DOM
* @param index the index of the node in the balanced parentheses
* @param ordinalIndex the index of the node in the non-text node store
*/
public ElementImpl(SuccinctDom dom, int index, int ordinalIndex) {
super(dom, index, ordinalIndex);
}
/*
* Node API.
*/
@Override
public String getNodeName() {
return dom.getQName(ordinalIndex);
}
@Override
public String getNodeValue() throws DOMException {
return null;
}
@Override
public void setNodeValue(String nodeValue) throws DOMException {
// No op.
}
@Override
public short getNodeType() {
return ELEMENT_NODE;
}
@Override
public Node getParentNode() {
return dom.getParentNode(index);
}
@Override
public Node getFirstChild() {
return dom.getFirstChild(index);
}
@Override
public Node getLastChild() {
return dom.getLastChild(index);
}
@Override
public Node getPreviousSibling() {
return dom.getPreviousSibling(index);
}
@Override
public Node getNextSibling() {
return dom.getNextSibling(index);
}
@Override
public boolean hasChildNodes() {
return dom.hasChildNodes(index);
}
@Override
public NodeList getChildNodes() {
return dom.getChildNodes(index);
}
@Override
public Document getOwnerDocument() {
return dom.getDocument();
}
@Override
public String getNamespaceURI() {
return dom.getNamespaceURI(ordinalIndex);
}
@Override
public String getPrefix() {
return dom.getPrefix(ordinalIndex);
}
@Override
public String getLocalName() {
return dom.getLocalName(ordinalIndex);
}
@Override
public NamedNodeMap getAttributes() {
if (attributes == null) {
attributes = dom.getAttributes(ordinalIndex);
}
return attributes;
}
@Override
public boolean hasAttributes() {
return dom.hasAttributes(ordinalIndex);
}
@Override
public String getTextContent() throws DOMException {
return dom.getTextContent(index);
}
@Override
public void setTextContent(String textContent) throws DOMException {
throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR, "setTextContent");
}
/*
* Element API.
*/
@Override
public String getTagName() {
return dom.getQName(ordinalIndex);
}
@Override
public String getAttribute(String name) {
String value = null;
Node attribute = getAttributes().getNamedItem(name);
if (attribute != null) {
value = attribute.getNodeValue();
}
return (value == null) ? "" : value;
}
@Override
public void setAttribute(String name, String value) throws DOMException {
throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR, "setAttribute");
}
@Override
public void removeAttribute(String name) throws DOMException {
throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR, "removeAttribute");
}
@Override
public Attr getAttributeNode(String name) {
return (Attr) getAttributes().getNamedItem(name);
}
@Override
public Attr setAttributeNode(Attr newAttr) throws DOMException {
throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR, "setAttributeNode");
}
@Override
public Attr removeAttributeNode(Attr oldAttr) throws DOMException {
throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR, "removeAttributeNode");
}
@Override
public NodeList getElementsByTagName(String name) {
// TODO(yshahun): Auto-generated method stub
return null;
}
@Override
public String getAttributeNS(String namespaceURI, String localName) throws DOMException {
String value = null;
Node attribute = getAttributes().getNamedItemNS(namespaceURI, localName);
if (attribute != null) {
value = attribute.getNodeValue();
}
return (value == null) ? "" : value;
}
@Override
public void setAttributeNS(String namespaceURI, String qualifiedName, String value)
throws DOMException {
throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR, "setAttributeNS");
}
@Override
public void removeAttributeNS(String namespaceURI, String localName) throws DOMException {
throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR, "removeAttributeNS");
}
@Override
public Attr getAttributeNodeNS(String namespaceURI, String localName) throws DOMException {
return (Attr) getAttributes().getNamedItemNS(namespaceURI, localName);
}
@Override
public Attr setAttributeNodeNS(Attr newAttr) throws DOMException {
throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR, "setAttributeNodeNS");
}
@Override
public NodeList getElementsByTagNameNS(String namespaceURI, String localName)
throws DOMException {
// TODO(yshahun): Auto-generated method stub
return null;
}
@Override
public boolean hasAttribute(String name) {
return getAttributes().getNamedItem(name) != null;
}
@Override
public boolean hasAttributeNS(String namespaceURI, String localName) throws DOMException {
return getAttributes().getNamedItemNS(namespaceURI, localName) != null;
}
@Override
public TypeInfo getSchemaTypeInfo() {
throw new UnsupportedOperationException("getSchemaTypeInfo");
}
@Override
public void setIdAttribute(String name, boolean isId) throws DOMException {
throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR, "setIdAttribute");
}
@Override
public void setIdAttributeNS(String namespaceURI, String localName, boolean isId)
throws DOMException {
throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR, "setIdAttributeNS");
}
@Override
public void setIdAttributeNode(Attr idAttr, boolean isId) throws DOMException {
throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR, "setIdAttributeNode");
}
}
| apache-2.0 |
wangweifengdev/coolweather | app/src/main/java/com/qiushiweather/android/db/County.java | 833 | package com.qiushiweather.android.db;
import org.litepal.crud.DataSupport;
/**
* Created by Administrator on 2017/8/21.
*/
public class County extends DataSupport {
private int id;
private String countyName;
private String weatherId;
private int cityId;
public int getId(){
return id;
}
public void setId(int id){
this.id=id;
}
public String getCountyName(){
return countyName;
}
public void setCountyName(String countyName){
this.countyName=countyName;
}
public String getWeatherId(){
return weatherId;
}
public void setWeatherId(String weatherId){
this.weatherId=weatherId;
}
public int getCityId(){
return cityId;
}
public void setCityId(int cityId){
this.cityId=cityId;
}
}
| apache-2.0 |
drankye/haox | haox-kerb/kerb-core/src/main/java/org/apache/kerberos/kerb/spec/KrbSequenceOfType.java | 751 | package org.apache.kerberos.kerb.spec;
import org.apache.haox.asn1.type.Asn1SequenceOf;
import org.apache.haox.asn1.type.Asn1String;
import org.apache.haox.asn1.type.Asn1Type;
import java.util.ArrayList;
import java.util.List;
public class KrbSequenceOfType<T extends Asn1Type> extends Asn1SequenceOf<T> {
public List<String> getAsStrings() {
List<T> elements = getElements();
List<String> results = new ArrayList<String>();
for (T ele : elements) {
if (ele instanceof Asn1String) {
results.add(((Asn1String) ele).getValue());
} else {
throw new RuntimeException("The targeted field type isn't of string");
}
}
return results;
}
}
| apache-2.0 |
jk1/intellij-community | java/java-impl/src/com/intellij/codeInsight/completion/ConstructorInsertHandler.java | 17394 | package com.intellij.codeInsight.completion;
import com.intellij.codeInsight.ExpectedTypeInfo;
import com.intellij.codeInsight.ExpectedTypesProvider;
import com.intellij.codeInsight.generation.GenerateMembersUtil;
import com.intellij.codeInsight.generation.OverrideImplementExploreUtil;
import com.intellij.codeInsight.generation.OverrideImplementUtil;
import com.intellij.codeInsight.generation.PsiGenerationInfo;
import com.intellij.codeInsight.intention.impl.TypeExpression;
import com.intellij.codeInsight.lookup.Lookup;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.LookupElementDecorator;
import com.intellij.codeInsight.lookup.PsiTypeLookupItem;
import com.intellij.codeInsight.template.*;
import com.intellij.codeInsight.template.impl.TemplateManagerImpl;
import com.intellij.codeInsight.template.impl.TemplateState;
import com.intellij.featureStatistics.FeatureUsageTracker;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.TransactionGuard;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.command.UndoConfirmationPolicy;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.RangeMarker;
import com.intellij.openapi.editor.ScrollType;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.CodeStyleManager;
import com.intellij.psi.impl.source.PostprocessReformattingAspect;
import com.intellij.psi.infos.CandidateInfo;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiTypesUtil;
import com.intellij.psi.util.PsiUtilCore;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
/**
* @author peter
*/
public class ConstructorInsertHandler implements InsertHandler<LookupElementDecorator<LookupElement>> {
private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.completion.ConstructorInsertHandler");
public static final ConstructorInsertHandler SMART_INSTANCE = new ConstructorInsertHandler(true);
public static final ConstructorInsertHandler BASIC_INSTANCE = new ConstructorInsertHandler(false);
private final boolean mySmart;
private ConstructorInsertHandler(boolean smart) {
mySmart = smart;
}
@Override
public void handleInsert(InsertionContext context, LookupElementDecorator<LookupElement> item) {
@SuppressWarnings({"unchecked"}) final LookupElement delegate = item.getDelegate();
PsiClass psiClass = (PsiClass)item.getObject();
boolean isAbstract = psiClass.hasModifierProperty(PsiModifier.ABSTRACT);
if (Lookup.REPLACE_SELECT_CHAR == context.getCompletionChar()) {
JavaClassNameInsertHandler.overwriteTopmostReference(context);
}
context.commitDocument();
OffsetKey insideRef = context.trackOffset(context.getTailOffset(), false);
final PsiElement position = SmartCompletionDecorator.getPosition(context, delegate);
if (position == null) return;
final PsiExpression enclosing = PsiTreeUtil.getContextOfType(position, PsiExpression.class, true);
final PsiAnonymousClass anonymousClass = PsiTreeUtil.getParentOfType(position, PsiAnonymousClass.class);
final boolean inAnonymous = anonymousClass != null && anonymousClass.getParent() == enclosing;
if (delegate instanceof PsiTypeLookupItem) {
if (context.getDocument().getTextLength() > context.getTailOffset() &&
context.getDocument().getCharsSequence().charAt(context.getTailOffset()) == '<') {
PsiJavaCodeReferenceElement ref = JavaClassNameInsertHandler.findJavaReference(context.getFile(), context.getTailOffset());
if (ref != null) {
PsiReferenceParameterList parameterList = ref.getParameterList();
if (parameterList != null && context.getTailOffset() == parameterList.getTextRange().getStartOffset()) {
context.getDocument().deleteString(parameterList.getTextRange().getStartOffset(), parameterList.getTextRange().getEndOffset());
context.commitDocument();
}
}
}
delegate.handleInsert(context);
PostprocessReformattingAspect.getInstance(context.getProject()).doPostponedFormatting(context.getFile().getViewProvider());
}
if (item.getDelegate() instanceof JavaPsiClassReferenceElement) {
PsiTypeLookupItem.addImportForItem(context, psiClass);
}
insertParentheses(context, delegate, psiClass, !inAnonymous && isAbstract);
if (inAnonymous) {
return;
}
if (mySmart) {
FeatureUsageTracker.getInstance().triggerFeatureUsed(JavaCompletionFeatures.AFTER_NEW);
}
if (isAbstract) {
PostprocessReformattingAspect.getInstance(context.getProject()).doPostponedFormatting(context.getFile().getViewProvider());
final Editor editor = context.getEditor();
final Document document = editor.getDocument();
final int offset = context.getTailOffset();
document.insertString(offset, " {}");
OffsetKey insideBraces = context.trackOffset(offset + 2, true);
final PsiFile file = context.getFile();
PsiDocumentManager.getInstance(file.getProject()).commitDocument(document);
reformatEnclosingExpressionListAtOffset(file, offset);
if (promptTypeOrConstructorArgs(context, delegate, insideRef, insideBraces)) return;
editor.getCaretModel().moveToOffset(context.getOffset(insideBraces));
context.setLaterRunnable(generateAnonymousBody(editor, file));
}
else {
PsiDocumentManager.getInstance(context.getProject()).commitAllDocuments();
final PsiNewExpression newExpression =
PsiTreeUtil.findElementOfClassAtOffset(context.getFile(), context.getStartOffset(), PsiNewExpression.class, false);
if (newExpression != null) {
final PsiJavaCodeReferenceElement classReference = newExpression.getClassOrAnonymousClassReference();
if (classReference != null) {
CodeStyleManager.getInstance(context.getProject()).reformat(classReference);
}
}
if (mySmart) {
FeatureUsageTracker.getInstance().triggerFeatureUsed(JavaCompletionFeatures.AFTER_NEW);
}
promptTypeOrConstructorArgs(context, delegate, insideRef, null);
}
}
private static boolean promptTypeOrConstructorArgs(InsertionContext context, LookupElement delegate, OffsetKey refOffset, @Nullable OffsetKey insideBraces) {
if (shouldFillTypeArgs(context, delegate) && JavaCompletionUtil.promptTypeArgs(context, context.getOffset(refOffset))) {
return true;
}
PsiMethod constructor = JavaConstructorCallElement.extractCalledConstructor(delegate);
if (constructor != null && JavaMethodCallElement.startArgumentLiveTemplate(context, constructor)) {
implementMethodsWhenTemplateIsFinished(context, insideBraces);
return true;
}
return false;
}
private static void implementMethodsWhenTemplateIsFinished(InsertionContext context, @Nullable final OffsetKey insideBraces) {
TemplateState state = TemplateManagerImpl.getTemplateState(context.getEditor());
if (state != null && insideBraces != null) {
state.addTemplateStateListener(new TemplateEditingAdapter() {
@Override
public void templateFinished(Template template, boolean brokenOff) {
if (!brokenOff) {
context.getEditor().getCaretModel().moveToOffset(context.getOffset(insideBraces));
TransactionGuard.getInstance().submitTransactionAndWait(createOverrideRunnable(context.getEditor(), context.getFile(), context.getProject()));
}
}
});
}
}
private static boolean shouldFillTypeArgs(InsertionContext context, LookupElement delegate) {
if (!(delegate instanceof PsiTypeLookupItem) ||
isRawTypeExpected(context, (PsiTypeLookupItem)delegate) ||
!((PsiClass)delegate.getObject()).hasTypeParameters()) {
return false;
}
PsiElement position = SmartCompletionDecorator.getPosition(context, delegate);
return position != null &&
((PsiTypeLookupItem)delegate).calcGenerics(position, context).isEmpty() &&
context.getCompletionChar() != '(';
}
private static void reformatEnclosingExpressionListAtOffset(@NotNull PsiFile file, int offset) {
final PsiElement elementAtOffset = PsiUtilCore.getElementAtOffset(file, offset);
PsiExpressionList listToReformat = getEnclosingExpressionList(elementAtOffset.getParent());
if (listToReformat != null) {
CodeStyleManager.getInstance(file.getProject()).reformat(listToReformat);
PostprocessReformattingAspect.getInstance(file.getProject()).doPostponedFormatting();
}
}
@Nullable
private static PsiExpressionList getEnclosingExpressionList(@NotNull PsiElement element) {
if (!(element instanceof PsiAnonymousClass)) {
return null;
}
PsiElement e = element.getParent();
if (e instanceof PsiNewExpression && e.getParent() instanceof PsiExpressionList) {
return (PsiExpressionList)e.getParent();
}
return null;
}
static boolean isRawTypeExpected(InsertionContext context, PsiTypeLookupItem delegate) {
PsiNewExpression newExpr =
PsiTreeUtil.findElementOfClassAtOffset(context.getFile(), context.getStartOffset(), PsiNewExpression.class, false);
if (newExpr != null) {
for (ExpectedTypeInfo info : ExpectedTypesProvider.getExpectedTypes(newExpr, true)) {
PsiType expected = info.getDefaultType();
if (expected.isAssignableFrom(delegate.getType())) {
if (expected instanceof PsiClassType && ((PsiClassType)expected).isRaw()) {
return true;
}
}
}
}
return false;
}
public static boolean insertParentheses(InsertionContext context,
LookupElement delegate,
final PsiClass psiClass,
final boolean forAnonymous) {
if (context.getCompletionChar() == '[') {
return false;
}
PsiMethod constructor = JavaConstructorCallElement.extractCalledConstructor(delegate);
final PsiElement place = context.getFile().findElementAt(context.getStartOffset());
assert place != null;
boolean hasParams = constructor != null ? !constructor.getParameterList().isEmpty() : hasConstructorParameters(psiClass, place);
RangeMarker refEnd = context.getDocument().createRangeMarker(context.getTailOffset(), context.getTailOffset());
JavaCompletionUtil.insertParentheses(context, delegate, false, hasParams, forAnonymous);
if (constructor != null) {
PsiCallExpression call = JavaMethodCallElement.findCallAtOffset(context, refEnd.getStartOffset());
if (call != null) {
CompletionMemory.registerChosenMethod(constructor, call);
}
}
return true;
}
static boolean hasConstructorParameters(PsiClass psiClass, @NotNull PsiElement place) {
final PsiResolveHelper resolveHelper = JavaPsiFacade.getInstance(place.getProject()).getResolveHelper();
boolean hasParams = false;
for (PsiMethod constructor : psiClass.getConstructors()) {
if (!resolveHelper.isAccessible(constructor, place, null)) continue;
if (!constructor.getParameterList().isEmpty()) {
hasParams = true;
break;
}
}
return hasParams;
}
@Nullable
private static Runnable generateAnonymousBody(final Editor editor, final PsiFile file) {
final Project project = file.getProject();
PsiDocumentManager.getInstance(project).commitAllDocuments();
int offset = editor.getCaretModel().getOffset();
PsiElement element = file.findElementAt(offset);
if (element == null) return null;
PsiElement parent = element.getParent();
if (!(parent instanceof PsiAnonymousClass)) return null;
return genAnonymousBodyFor((PsiAnonymousClass)parent, editor, file, project);
}
public static Runnable genAnonymousBodyFor(PsiAnonymousClass parent,
final Editor editor,
final PsiFile file,
final Project project) {
try {
CodeStyleManager.getInstance(project).reformat(parent);
}
catch (IncorrectOperationException e) {
LOG.error(e);
}
int offset = parent.getTextRange().getEndOffset() - 1;
editor.getCaretModel().moveToOffset(offset);
editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
editor.getSelectionModel().removeSelection();
final PsiReferenceParameterList parameterList = parent.getBaseClassReference().getParameterList();
final PsiTypeElement[] parameters = parameterList != null ? parameterList.getTypeParameterElements() : null;
final PsiElement newExpr = parent.getParent();
if (newExpr != null && PsiTypesUtil.getExpectedTypeByParent(newExpr) == null && shouldStartTypeTemplate(parameters)) {
startTemplate(parent, editor, createOverrideRunnable(editor, file, project), parameters);
return null;
}
return createOverrideRunnable(editor, file, project);
}
private static Runnable createOverrideRunnable(final Editor editor, final PsiFile file, final Project project) {
return () -> {
TemplateManager.getInstance(project).finishTemplate(editor);
PsiDocumentManager.getInstance(project).commitDocument(editor.getDocument());
final PsiAnonymousClass
aClass = PsiTreeUtil.findElementOfClassAtOffset(file, editor.getCaretModel().getOffset(), PsiAnonymousClass.class, false);
if (aClass == null) return;
CommandProcessor.getInstance().executeCommand(project, () -> {
final Collection<CandidateInfo> candidatesToImplement = OverrideImplementExploreUtil.getMethodsToOverrideImplement(aClass, true);
for (Iterator<CandidateInfo> iterator = candidatesToImplement.iterator(); iterator.hasNext(); ) {
final CandidateInfo candidate = iterator.next();
final PsiElement element = candidate.getElement();
if (element instanceof PsiMethod && ((PsiMethod)element).hasModifierProperty(PsiModifier.DEFAULT)) {
iterator.remove();
}
}
boolean invokeOverride = candidatesToImplement.isEmpty();
if (invokeOverride) {
OverrideImplementUtil.chooseAndOverrideOrImplementMethods(project, editor, aClass, false);
}
else {
ApplicationManager.getApplication().runWriteAction(() -> {
try {
List<PsiMethod> methods = OverrideImplementUtil.overrideOrImplementMethodCandidates(aClass, candidatesToImplement, false);
List<PsiGenerationInfo<PsiMethod>> prototypes = OverrideImplementUtil.convert2GenerationInfos(methods);
List<PsiGenerationInfo<PsiMethod>> resultMembers =
GenerateMembersUtil.insertMembersBeforeAnchor(aClass, null, prototypes);
resultMembers.get(0).positionCaret(editor, true);
}
catch (IncorrectOperationException ioe) {
LOG.error(ioe);
}
});
}
}, getCommandName(), getCommandName(), UndoConfirmationPolicy.DEFAULT, editor.getDocument());
};
}
@Contract("null -> false")
private static boolean shouldStartTypeTemplate(PsiTypeElement[] parameters) {
if (parameters != null && parameters.length > 0) {
for (PsiTypeElement parameter : parameters) {
if (parameter.getType().equalsToText(CommonClassNames.JAVA_LANG_OBJECT)) {
return true;
}
}
}
return false;
}
private static void startTemplate(final PsiAnonymousClass aClass, final Editor editor, final Runnable runnable, @NotNull final PsiTypeElement[] parameters) {
final Project project = aClass.getProject();
WriteCommandAction.writeCommandAction(project).withName(getCommandName()).withGroupId(getCommandName()).run(() -> {
PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(editor.getDocument());
editor.getCaretModel().moveToOffset(aClass.getTextOffset());
final TemplateBuilderImpl templateBuilder = (TemplateBuilderImpl)TemplateBuilderFactory.getInstance().createTemplateBuilder(aClass);
for (int i = 0; i < parameters.length; i++) {
PsiTypeElement parameter = parameters[i];
templateBuilder.replaceElement(parameter, "param" + i, new TypeExpression(project, new PsiType[]{parameter.getType()}), true);
}
Template template = templateBuilder.buildInlineTemplate();
TemplateManager.getInstance(project).startTemplate(editor, template, false, null, new TemplateEditingAdapter() {
@Override
public void templateFinished(Template template, boolean brokenOff) {
if (!brokenOff) {
runnable.run();
}
}
});
});
}
private static String getCommandName() {
return CompletionBundle.message("completion.smart.type.generate.anonymous.body");
}
}
| apache-2.0 |
tsegall/fta | types/src/main/java/com/cobber/fta/plugins/Gender.java | 7531 | /*
* Copyright 2017-2022 Tim Segall
*
* 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.cobber.fta.plugins;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import com.cobber.fta.AnalysisConfig;
import com.cobber.fta.AnalyzerContext;
import com.cobber.fta.Facts;
import com.cobber.fta.LogicalTypeFinite;
import com.cobber.fta.PluginDefinition;
import com.cobber.fta.core.FTAPluginException;
import com.cobber.fta.core.RegExpGenerator;
import com.cobber.fta.token.TokenStreams;
/**
* Plugin to detect Gender.
*/
public class Gender extends LogicalTypeFinite {
public static final String SEMANTIC_TYPE = "GENDER.TEXT_";
private static final String BACKOUT_REGEX = "\\p{IsAlphabetic}+";
// Map from ISO language to Gender Data for the language
private static Map<String, GenderData> allGenderData = new HashMap<>();
private static Map<String, Set<String>> allMembers = new HashMap<>();
private static Map<String, Map<String, String>> allOpposites = new HashMap<>();
private Map<String, String> opposites = null;
private String happyRegex = BACKOUT_REGEX;
private String language = null;
private GenderData genderData = null;
private static class GenderData {
private final String header;
private final String feminine;
private final String masculine;
private final String feminineShort;
private final String masculineShort;
GenderData(final String header, final String feminine, final String masculine, final String feminineShort, final String masculineShort) {
this.header = header;
this.feminine = feminine;
this.masculine = masculine;
this.feminineShort = feminineShort;
this.masculineShort = masculineShort;
}
}
static {
// German
allGenderData.put("DE", new GenderData(".*(?i)(Gender|Geschlecht)", "WEIBLICH", "MÄNNLICH", "W", "M"));
// English
allGenderData.put("EN", new GenderData(".*(?i)(Gender|sex)", "FEMALE", "MALE", "F", "M"));
// Spanish
allGenderData.put("ES", new GenderData(".*(?i)(Gender|Sexo)", "FEMENINO", "MASCULINO", "F", "M"));
// French
allGenderData.put("FR", new GenderData(".*(?i)(Gender|Genre|Sexe)", "FEMME", "HOMME", "F", "H"));
// Italian
allGenderData.put("IT", new GenderData(".*(?i)(Gender|genere)", "FEMMINA", "MASCHIO", "F", "M"));
// Malaysian
allGenderData.put("MS", new GenderData(".*(?i)(Gender|jantina)", "PEREMPUAN", "LELAKI", "P", "L"));
// Dutch
allGenderData.put("NL", new GenderData(".*(?i)(Gender|Geslach|Geslacht)", "VROUWELIJK", "MANNELIJK", "V", "M"));
// Portuguese
allGenderData.put("PT", new GenderData(".*(?i)(Gender|Gênero)", "FEMININA", "MASCULINO", "F", "M"));
// Turkish
allGenderData.put("TR", new GenderData(".*(?i)(Gender)", "KADIN", "ERKEK", "K", "E"));
// Belgium covered by DE, FR, and NL
// Switzerland covered DE, FR, IT
// Austria covered by DE
}
public Gender(final PluginDefinition plugin) throws FileNotFoundException {
super(plugin);
}
@Override
public String nextRandom() {
return random.nextInt(2) != 0 ? genderData.feminine : genderData.masculine;
}
@Override
public boolean initialize(final Locale locale) throws FTAPluginException {
super.initialize(locale);
language = locale.getLanguage().toUpperCase(Locale.ROOT);
genderData = allGenderData.get(language);
opposites = allOpposites.get(language);
if (opposites == null) {
opposites = new HashMap<>();
opposites.put(genderData.feminineShort, genderData.masculineShort);
opposites.put(genderData.masculineShort, genderData.feminineShort);
opposites.put(genderData.feminine, genderData.masculine);
opposites.put(genderData.masculine, genderData.feminine);
allOpposites.put(language, opposites);
}
return true;
}
@Override
public Set<String> getMembers() {
final String setupLanguage = locale.getLanguage().toUpperCase(Locale.ROOT);
Set<String> languageMembers = allMembers.get(setupLanguage);
if (languageMembers == null) {
final GenderData setup = allGenderData.get(setupLanguage);
languageMembers = new HashSet<>();
languageMembers.add(setup.feminineShort);
languageMembers.add(setup.masculineShort);
languageMembers.add(setup.feminine);
languageMembers.add(setup.masculine);
allMembers.put(setupLanguage, languageMembers);
}
return languageMembers;
}
@Override
public String getQualifier() {
return SEMANTIC_TYPE + language;
}
@Override
public String getRegExp() {
return happyRegex;
}
@Override
public String isValidSet(final AnalyzerContext context, final long matchCount, final long realSamples, final String currentRegExp, final Facts facts, Map<String, Long> cardinality, final Map<String, Long> outliers, final TokenStreams tokenStreams, final AnalysisConfig analysisConfig) {
// Feel like this should be a little more inclusive in this day and age but not sure what set to use!!
if (outliers.size() > 1)
return BACKOUT_REGEX;
final boolean positiveStreamName = context.getStreamName().matches(genderData.header);
if (!positiveStreamName && cardinality.size() - outliers.size() <= 1)
return BACKOUT_REGEX;
String outlier;
if (!outliers.isEmpty()) {
outlier = outliers.keySet().iterator().next();
cardinality = new HashMap<>(cardinality);
cardinality.remove(outlier);
}
final int count = cardinality.size();
Iterator<String> iter = null;
String first = null;
if (count != 0) {
iter = cardinality.keySet().iterator();
first = iter.next();
}
// If we have seen no more than one outlier then we are feeling pretty good unless we are in Strict mode (e.g. 100%)
if ((threshold != 100 && outliers.size() <= 1) || (double)matchCount / realSamples >= getThreshold()/100.0) {
final RegExpGenerator re = new RegExpGenerator(5, locale);
// There is some complexity here due to the facts that 'Male' & 'Female' are good predictors of Gender.
// However a field with only 'M' and 'F' in it is not, so in this case we would like an extra hint.
if (count == 1) {
if (!positiveStreamName && (first.equals(genderData.feminineShort) || first.equals(genderData.masculineShort)))
return BACKOUT_REGEX;
re.train(first);
re.train(opposites.get(first));
} else if (count == 2) {
final String second = iter.next();
if (!positiveStreamName && (first.equals(genderData.feminineShort) || first.equals(genderData.masculineShort)) && (second.equals(genderData.feminineShort) || second.equals(genderData.masculineShort)))
return BACKOUT_REGEX;
if (opposites.get(first).equals(second)) {
re.train(first);
re.train(second);
}
else
for (final String element : getMembers())
re.train(element);
} else {
for (final String element : getMembers())
re.train(element);
}
if (!outliers.isEmpty())
re.train(outliers.keySet().iterator().next());
happyRegex = re.getResult();
return null;
}
return BACKOUT_REGEX;
}
}
| apache-2.0 |
funtl/framework | funtl-framework-tools/alipay-sdk/src/main/java/com/funtl/framework/alipay/trade/pay/protocol/downloadbill/response/AlipayDataDataserviceBillDownloadurlQueryResponse.java | 2055 | /*
* Copyright 2015-2017 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 com.funtl.framework.alipay.trade.pay.protocol.downloadbill.response;
import java.util.List;
import com.funtl.framework.alipay.trade.pay.protocol.downloadbill.api.AlipayResponse;
import com.funtl.framework.alipay.trade.pay.protocol.downloadbill.internal.mapping.ApiField;
/**
* ALIPAY API: alipay.data.dataservice.bill.downloadurl.query response.
*
* @author auto create
* @since 1.0, 2016-04-15 09:22:23
*/
public class AlipayDataDataserviceBillDownloadurlQueryResponse extends AlipayResponse {
private static final long serialVersionUID = 3294325729477111782L;
/**
* 账单下载地址链接,获取连接后30秒后未下载,链接地址失效。
*/
@ApiField("bill_download_url")
private String billDownloadUrl;
/**
* 对账单列表数据
*/
private List<String> billDataList;
/**
* 对账单汇总数据
*/
private List<String> billCountDataList;
public void setBillDownloadUrl(String billDownloadUrl) {
this.billDownloadUrl = billDownloadUrl;
}
public String getBillDownloadUrl() {
return this.billDownloadUrl;
}
public List<String> getBillCountDataList() {
return billCountDataList;
}
public void setBillCountDataList(List<String> billCountDataList) {
this.billCountDataList = billCountDataList;
}
public List<String> getBillDataList() {
return billDataList;
}
public void setBillDataList(List<String> billDataList) {
this.billDataList = billDataList;
}
} | apache-2.0 |
Pardus-Engerek/engerek | model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/script/ScriptExpressionEvaluatorFactory.java | 3351 | /*
* Copyright (c) 2010-2017 Evolveum
*
* 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.evolveum.midpoint.model.common.expression.script;
import java.util.Collection;
import javax.xml.bind.JAXBElement;
import javax.xml.namespace.QName;
import com.evolveum.midpoint.prism.ItemDefinition;
import com.evolveum.midpoint.prism.PrismValue;
import com.evolveum.midpoint.repo.common.expression.ExpressionEvaluator;
import com.evolveum.midpoint.repo.common.expression.ExpressionEvaluatorFactory;
import com.evolveum.midpoint.schema.result.OperationResult;
import com.evolveum.midpoint.security.api.SecurityEnforcer;
import com.evolveum.midpoint.task.api.Task;
import com.evolveum.midpoint.util.exception.SchemaException;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectFactory;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ScriptExpressionEvaluatorType;
/**
* @author semancik
*
*/
public class ScriptExpressionEvaluatorFactory implements ExpressionEvaluatorFactory {
private ScriptExpressionFactory scriptExpressionFactory;
private SecurityEnforcer securityEnforcer;
public ScriptExpressionEvaluatorFactory(ScriptExpressionFactory scriptExpressionFactory, SecurityEnforcer securityEnforcer) {
this.scriptExpressionFactory = scriptExpressionFactory;
this.securityEnforcer = securityEnforcer;
}
@Override
public QName getElementName() {
return new ObjectFactory().createScript(new ScriptExpressionEvaluatorType()).getName();
}
/* (non-Javadoc)
* @see com.evolveum.midpoint.common.expression.ExpressionEvaluatorFactory#createEvaluator(javax.xml.bind.JAXBElement, com.evolveum.midpoint.prism.ItemDefinition)
*/
@Override
public <V extends PrismValue,D extends ItemDefinition> ExpressionEvaluator<V,D> createEvaluator(Collection<JAXBElement<?>> evaluatorElements,
D outputDefinition, String contextDescription, Task task, OperationResult result) throws SchemaException {
if (evaluatorElements.size() > 1) {
throw new SchemaException("More than one evaluator specified in "+contextDescription);
}
JAXBElement<?> evaluatorElement = evaluatorElements.iterator().next();
Object evaluatorElementObject = evaluatorElement.getValue();
if (!(evaluatorElementObject instanceof ScriptExpressionEvaluatorType)) {
throw new IllegalArgumentException("Script expression cannot handle elements of type " + evaluatorElementObject.getClass().getName());
}
ScriptExpressionEvaluatorType scriptType = (ScriptExpressionEvaluatorType) evaluatorElementObject;
ScriptExpression scriptExpression = scriptExpressionFactory.createScriptExpression(scriptType, outputDefinition, contextDescription);
return new ScriptExpressionEvaluator<>(scriptType, scriptExpression, securityEnforcer);
}
}
| apache-2.0 |
heartup/DCF | dcf-common/src/main/java/io/reactivej/dcf/common/topology/IDAG.java | 853 | package io.reactivej.dcf.common.topology;
import java.io.Serializable;
import java.util.Map;
/**
* @See DAG
* @Description: Job拓扑结构的有向无环图描述
* @author heartup@gmail.com
* @date: 2015年8月10日 下午7:13:55
*/
public interface IDAG extends Serializable {
public static final String DEFAULT_STREAMID = "DEFAULT";
/**
* DAG中Emitter的集合,key是Emitter的id
* @return
*/
public Map<String, IComponentDescription> getEmitters();
/**
* DAG中Gear的集合,key是Gear的id
*
* @return
*/
public Map<String, IComponentDescription> getGears();
/**
* 根据id返回emitter或者gear, 用于不用区分Emitter或Gear的操作
*
* @param id
* @return
*/
public IComponentDescription getComponent(String id);
public Map<String, IComponentDescription> getComponents();
}
| apache-2.0 |
ExtaSoft/extacrm | src/main/java/ru/extas/model/common/DateTimeConverter.java | 1005 | package ru.extas.model.common;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import java.sql.Timestamp;
/**
* <p>DateTimeConverter class.</p>
*
* @author Valery_2
* @version $Id: $Id
* @since 0.3
*/
@Converter(autoApply = true)
public class DateTimeConverter implements AttributeConverter<DateTime, Timestamp> {
/** {@inheritDoc} */
@Override
public Timestamp convertToDatabaseColumn(final DateTime attribute) {
Timestamp dbVal = null;
if (attribute != null) {
dbVal = new Timestamp(attribute.withZone(DateTimeZone.UTC).getMillis());
}
return dbVal;
}
/** {@inheritDoc} */
@Override
public DateTime convertToEntityAttribute(final Timestamp dbData) {
DateTime attribute = null;
if (dbData != null)
attribute = new DateTime(dbData.getTime(), DateTimeZone.UTC);
return attribute;
}
}
| apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-macie2/src/main/java/com/amazonaws/services/macie2/model/MatchingBucket.java | 44279 | /*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.amazonaws.services.macie2.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;
/**
* <p>
* Provides statistical data and other information about an S3 bucket that Amazon Macie monitors and analyzes for your
* account. If an error occurs when Macie attempts to retrieve and process information about the bucket or the bucket's
* objects, the value for most of these properties is null. Exceptions are accountId and bucketName. To identify the
* cause of the error, refer to the errorCode and errorMessage values.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/macie2-2020-01-01/MatchingBucket" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class MatchingBucket implements Serializable, Cloneable, StructuredPojo {
/**
* <p>
* The unique identifier for the Amazon Web Services account that owns the bucket.
* </p>
*/
private String accountId;
/**
* <p>
* The name of the bucket.
* </p>
*/
private String bucketName;
/**
* <p>
* The total number of objects that Amazon Macie can analyze in the bucket. These objects use a supported storage
* class and have a file name extension for a supported file or storage format.
* </p>
*/
private Long classifiableObjectCount;
/**
* <p>
* The total storage size, in bytes, of the objects that Amazon Macie can analyze in the bucket. These objects use a
* supported storage class and have a file name extension for a supported file or storage format.
* </p>
* <p>
* If versioning is enabled for the bucket, Macie calculates this value based on the size of the latest version of
* each applicable object in the bucket. This value doesn't reflect the storage size of all versions of each
* applicable object in the bucket.
* </p>
*/
private Long classifiableSizeInBytes;
/**
* <p>
* Specifies the error code for an error that prevented Amazon Macie from retrieving and processing information
* about the bucket and the bucket's objects. If this value is ACCESS_DENIED, Macie doesn't have permission to
* retrieve the information. For example, the bucket has a restrictive bucket policy and Amazon S3 denied the
* request. If this value is null, Macie was able to retrieve and process the information.
* </p>
*/
private String errorCode;
/**
* <p>
* A brief description of the error (errorCode) that prevented Amazon Macie from retrieving and processing
* information about the bucket and the bucket's objects. This value is null if Macie was able to retrieve and
* process the information.
* </p>
*/
private String errorMessage;
/**
* <p>
* Specifies whether any one-time or recurring classification jobs are configured to analyze objects in the bucket,
* and, if so, the details of the job that ran most recently.
* </p>
*/
private JobDetails jobDetails;
/**
* <p>
* The total number of objects in the bucket.
* </p>
*/
private Long objectCount;
/**
* <p>
* The total number of objects that are in the bucket, grouped by server-side encryption type. This includes a
* grouping that reports the total number of objects that aren't encrypted or use client-side encryption.
* </p>
*/
private ObjectCountByEncryptionType objectCountByEncryptionType;
/**
* <p>
* The total storage size, in bytes, of the bucket.
* </p>
* <p>
* If versioning is enabled for the bucket, Amazon Macie calculates this value based on the size of the latest
* version of each object in the bucket. This value doesn't reflect the storage size of all versions of each object
* in the bucket.
* </p>
*/
private Long sizeInBytes;
/**
* <p>
* The total storage size, in bytes, of the objects that are compressed (.gz, .gzip, .zip) files in the bucket.
* </p>
* <p>
* If versioning is enabled for the bucket, Amazon Macie calculates this value based on the size of the latest
* version of each applicable object in the bucket. This value doesn't reflect the storage size of all versions of
* each applicable object in the bucket.
* </p>
*/
private Long sizeInBytesCompressed;
/**
* <p>
* The total number of objects that Amazon Macie can't analyze in the bucket. These objects don't use a supported
* storage class or don't have a file name extension for a supported file or storage format.
* </p>
*/
private ObjectLevelStatistics unclassifiableObjectCount;
/**
* <p>
* The total storage size, in bytes, of the objects that Amazon Macie can't analyze in the bucket. These objects
* don't use a supported storage class or don't have a file name extension for a supported file or storage format.
* </p>
*/
private ObjectLevelStatistics unclassifiableObjectSizeInBytes;
/**
* <p>
* The unique identifier for the Amazon Web Services account that owns the bucket.
* </p>
*
* @param accountId
* The unique identifier for the Amazon Web Services account that owns the bucket.
*/
public void setAccountId(String accountId) {
this.accountId = accountId;
}
/**
* <p>
* The unique identifier for the Amazon Web Services account that owns the bucket.
* </p>
*
* @return The unique identifier for the Amazon Web Services account that owns the bucket.
*/
public String getAccountId() {
return this.accountId;
}
/**
* <p>
* The unique identifier for the Amazon Web Services account that owns the bucket.
* </p>
*
* @param accountId
* The unique identifier for the Amazon Web Services account that owns the bucket.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public MatchingBucket withAccountId(String accountId) {
setAccountId(accountId);
return this;
}
/**
* <p>
* The name of the bucket.
* </p>
*
* @param bucketName
* The name of the bucket.
*/
public void setBucketName(String bucketName) {
this.bucketName = bucketName;
}
/**
* <p>
* The name of the bucket.
* </p>
*
* @return The name of the bucket.
*/
public String getBucketName() {
return this.bucketName;
}
/**
* <p>
* The name of the bucket.
* </p>
*
* @param bucketName
* The name of the bucket.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public MatchingBucket withBucketName(String bucketName) {
setBucketName(bucketName);
return this;
}
/**
* <p>
* The total number of objects that Amazon Macie can analyze in the bucket. These objects use a supported storage
* class and have a file name extension for a supported file or storage format.
* </p>
*
* @param classifiableObjectCount
* The total number of objects that Amazon Macie can analyze in the bucket. These objects use a supported
* storage class and have a file name extension for a supported file or storage format.
*/
public void setClassifiableObjectCount(Long classifiableObjectCount) {
this.classifiableObjectCount = classifiableObjectCount;
}
/**
* <p>
* The total number of objects that Amazon Macie can analyze in the bucket. These objects use a supported storage
* class and have a file name extension for a supported file or storage format.
* </p>
*
* @return The total number of objects that Amazon Macie can analyze in the bucket. These objects use a supported
* storage class and have a file name extension for a supported file or storage format.
*/
public Long getClassifiableObjectCount() {
return this.classifiableObjectCount;
}
/**
* <p>
* The total number of objects that Amazon Macie can analyze in the bucket. These objects use a supported storage
* class and have a file name extension for a supported file or storage format.
* </p>
*
* @param classifiableObjectCount
* The total number of objects that Amazon Macie can analyze in the bucket. These objects use a supported
* storage class and have a file name extension for a supported file or storage format.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public MatchingBucket withClassifiableObjectCount(Long classifiableObjectCount) {
setClassifiableObjectCount(classifiableObjectCount);
return this;
}
/**
* <p>
* The total storage size, in bytes, of the objects that Amazon Macie can analyze in the bucket. These objects use a
* supported storage class and have a file name extension for a supported file or storage format.
* </p>
* <p>
* If versioning is enabled for the bucket, Macie calculates this value based on the size of the latest version of
* each applicable object in the bucket. This value doesn't reflect the storage size of all versions of each
* applicable object in the bucket.
* </p>
*
* @param classifiableSizeInBytes
* The total storage size, in bytes, of the objects that Amazon Macie can analyze in the bucket. These
* objects use a supported storage class and have a file name extension for a supported file or storage
* format.</p>
* <p>
* If versioning is enabled for the bucket, Macie calculates this value based on the size of the latest
* version of each applicable object in the bucket. This value doesn't reflect the storage size of all
* versions of each applicable object in the bucket.
*/
public void setClassifiableSizeInBytes(Long classifiableSizeInBytes) {
this.classifiableSizeInBytes = classifiableSizeInBytes;
}
/**
* <p>
* The total storage size, in bytes, of the objects that Amazon Macie can analyze in the bucket. These objects use a
* supported storage class and have a file name extension for a supported file or storage format.
* </p>
* <p>
* If versioning is enabled for the bucket, Macie calculates this value based on the size of the latest version of
* each applicable object in the bucket. This value doesn't reflect the storage size of all versions of each
* applicable object in the bucket.
* </p>
*
* @return The total storage size, in bytes, of the objects that Amazon Macie can analyze in the bucket. These
* objects use a supported storage class and have a file name extension for a supported file or storage
* format.</p>
* <p>
* If versioning is enabled for the bucket, Macie calculates this value based on the size of the latest
* version of each applicable object in the bucket. This value doesn't reflect the storage size of all
* versions of each applicable object in the bucket.
*/
public Long getClassifiableSizeInBytes() {
return this.classifiableSizeInBytes;
}
/**
* <p>
* The total storage size, in bytes, of the objects that Amazon Macie can analyze in the bucket. These objects use a
* supported storage class and have a file name extension for a supported file or storage format.
* </p>
* <p>
* If versioning is enabled for the bucket, Macie calculates this value based on the size of the latest version of
* each applicable object in the bucket. This value doesn't reflect the storage size of all versions of each
* applicable object in the bucket.
* </p>
*
* @param classifiableSizeInBytes
* The total storage size, in bytes, of the objects that Amazon Macie can analyze in the bucket. These
* objects use a supported storage class and have a file name extension for a supported file or storage
* format.</p>
* <p>
* If versioning is enabled for the bucket, Macie calculates this value based on the size of the latest
* version of each applicable object in the bucket. This value doesn't reflect the storage size of all
* versions of each applicable object in the bucket.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public MatchingBucket withClassifiableSizeInBytes(Long classifiableSizeInBytes) {
setClassifiableSizeInBytes(classifiableSizeInBytes);
return this;
}
/**
* <p>
* Specifies the error code for an error that prevented Amazon Macie from retrieving and processing information
* about the bucket and the bucket's objects. If this value is ACCESS_DENIED, Macie doesn't have permission to
* retrieve the information. For example, the bucket has a restrictive bucket policy and Amazon S3 denied the
* request. If this value is null, Macie was able to retrieve and process the information.
* </p>
*
* @param errorCode
* Specifies the error code for an error that prevented Amazon Macie from retrieving and processing
* information about the bucket and the bucket's objects. If this value is ACCESS_DENIED, Macie doesn't have
* permission to retrieve the information. For example, the bucket has a restrictive bucket policy and Amazon
* S3 denied the request. If this value is null, Macie was able to retrieve and process the information.
* @see BucketMetadataErrorCode
*/
public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
}
/**
* <p>
* Specifies the error code for an error that prevented Amazon Macie from retrieving and processing information
* about the bucket and the bucket's objects. If this value is ACCESS_DENIED, Macie doesn't have permission to
* retrieve the information. For example, the bucket has a restrictive bucket policy and Amazon S3 denied the
* request. If this value is null, Macie was able to retrieve and process the information.
* </p>
*
* @return Specifies the error code for an error that prevented Amazon Macie from retrieving and processing
* information about the bucket and the bucket's objects. If this value is ACCESS_DENIED, Macie doesn't have
* permission to retrieve the information. For example, the bucket has a restrictive bucket policy and
* Amazon S3 denied the request. If this value is null, Macie was able to retrieve and process the
* information.
* @see BucketMetadataErrorCode
*/
public String getErrorCode() {
return this.errorCode;
}
/**
* <p>
* Specifies the error code for an error that prevented Amazon Macie from retrieving and processing information
* about the bucket and the bucket's objects. If this value is ACCESS_DENIED, Macie doesn't have permission to
* retrieve the information. For example, the bucket has a restrictive bucket policy and Amazon S3 denied the
* request. If this value is null, Macie was able to retrieve and process the information.
* </p>
*
* @param errorCode
* Specifies the error code for an error that prevented Amazon Macie from retrieving and processing
* information about the bucket and the bucket's objects. If this value is ACCESS_DENIED, Macie doesn't have
* permission to retrieve the information. For example, the bucket has a restrictive bucket policy and Amazon
* S3 denied the request. If this value is null, Macie was able to retrieve and process the information.
* @return Returns a reference to this object so that method calls can be chained together.
* @see BucketMetadataErrorCode
*/
public MatchingBucket withErrorCode(String errorCode) {
setErrorCode(errorCode);
return this;
}
/**
* <p>
* Specifies the error code for an error that prevented Amazon Macie from retrieving and processing information
* about the bucket and the bucket's objects. If this value is ACCESS_DENIED, Macie doesn't have permission to
* retrieve the information. For example, the bucket has a restrictive bucket policy and Amazon S3 denied the
* request. If this value is null, Macie was able to retrieve and process the information.
* </p>
*
* @param errorCode
* Specifies the error code for an error that prevented Amazon Macie from retrieving and processing
* information about the bucket and the bucket's objects. If this value is ACCESS_DENIED, Macie doesn't have
* permission to retrieve the information. For example, the bucket has a restrictive bucket policy and Amazon
* S3 denied the request. If this value is null, Macie was able to retrieve and process the information.
* @return Returns a reference to this object so that method calls can be chained together.
* @see BucketMetadataErrorCode
*/
public MatchingBucket withErrorCode(BucketMetadataErrorCode errorCode) {
this.errorCode = errorCode.toString();
return this;
}
/**
* <p>
* A brief description of the error (errorCode) that prevented Amazon Macie from retrieving and processing
* information about the bucket and the bucket's objects. This value is null if Macie was able to retrieve and
* process the information.
* </p>
*
* @param errorMessage
* A brief description of the error (errorCode) that prevented Amazon Macie from retrieving and processing
* information about the bucket and the bucket's objects. This value is null if Macie was able to retrieve
* and process the information.
*/
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
/**
* <p>
* A brief description of the error (errorCode) that prevented Amazon Macie from retrieving and processing
* information about the bucket and the bucket's objects. This value is null if Macie was able to retrieve and
* process the information.
* </p>
*
* @return A brief description of the error (errorCode) that prevented Amazon Macie from retrieving and processing
* information about the bucket and the bucket's objects. This value is null if Macie was able to retrieve
* and process the information.
*/
public String getErrorMessage() {
return this.errorMessage;
}
/**
* <p>
* A brief description of the error (errorCode) that prevented Amazon Macie from retrieving and processing
* information about the bucket and the bucket's objects. This value is null if Macie was able to retrieve and
* process the information.
* </p>
*
* @param errorMessage
* A brief description of the error (errorCode) that prevented Amazon Macie from retrieving and processing
* information about the bucket and the bucket's objects. This value is null if Macie was able to retrieve
* and process the information.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public MatchingBucket withErrorMessage(String errorMessage) {
setErrorMessage(errorMessage);
return this;
}
/**
* <p>
* Specifies whether any one-time or recurring classification jobs are configured to analyze objects in the bucket,
* and, if so, the details of the job that ran most recently.
* </p>
*
* @param jobDetails
* Specifies whether any one-time or recurring classification jobs are configured to analyze objects in the
* bucket, and, if so, the details of the job that ran most recently.
*/
public void setJobDetails(JobDetails jobDetails) {
this.jobDetails = jobDetails;
}
/**
* <p>
* Specifies whether any one-time or recurring classification jobs are configured to analyze objects in the bucket,
* and, if so, the details of the job that ran most recently.
* </p>
*
* @return Specifies whether any one-time or recurring classification jobs are configured to analyze objects in the
* bucket, and, if so, the details of the job that ran most recently.
*/
public JobDetails getJobDetails() {
return this.jobDetails;
}
/**
* <p>
* Specifies whether any one-time or recurring classification jobs are configured to analyze objects in the bucket,
* and, if so, the details of the job that ran most recently.
* </p>
*
* @param jobDetails
* Specifies whether any one-time or recurring classification jobs are configured to analyze objects in the
* bucket, and, if so, the details of the job that ran most recently.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public MatchingBucket withJobDetails(JobDetails jobDetails) {
setJobDetails(jobDetails);
return this;
}
/**
* <p>
* The total number of objects in the bucket.
* </p>
*
* @param objectCount
* The total number of objects in the bucket.
*/
public void setObjectCount(Long objectCount) {
this.objectCount = objectCount;
}
/**
* <p>
* The total number of objects in the bucket.
* </p>
*
* @return The total number of objects in the bucket.
*/
public Long getObjectCount() {
return this.objectCount;
}
/**
* <p>
* The total number of objects in the bucket.
* </p>
*
* @param objectCount
* The total number of objects in the bucket.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public MatchingBucket withObjectCount(Long objectCount) {
setObjectCount(objectCount);
return this;
}
/**
* <p>
* The total number of objects that are in the bucket, grouped by server-side encryption type. This includes a
* grouping that reports the total number of objects that aren't encrypted or use client-side encryption.
* </p>
*
* @param objectCountByEncryptionType
* The total number of objects that are in the bucket, grouped by server-side encryption type. This includes
* a grouping that reports the total number of objects that aren't encrypted or use client-side encryption.
*/
public void setObjectCountByEncryptionType(ObjectCountByEncryptionType objectCountByEncryptionType) {
this.objectCountByEncryptionType = objectCountByEncryptionType;
}
/**
* <p>
* The total number of objects that are in the bucket, grouped by server-side encryption type. This includes a
* grouping that reports the total number of objects that aren't encrypted or use client-side encryption.
* </p>
*
* @return The total number of objects that are in the bucket, grouped by server-side encryption type. This includes
* a grouping that reports the total number of objects that aren't encrypted or use client-side encryption.
*/
public ObjectCountByEncryptionType getObjectCountByEncryptionType() {
return this.objectCountByEncryptionType;
}
/**
* <p>
* The total number of objects that are in the bucket, grouped by server-side encryption type. This includes a
* grouping that reports the total number of objects that aren't encrypted or use client-side encryption.
* </p>
*
* @param objectCountByEncryptionType
* The total number of objects that are in the bucket, grouped by server-side encryption type. This includes
* a grouping that reports the total number of objects that aren't encrypted or use client-side encryption.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public MatchingBucket withObjectCountByEncryptionType(ObjectCountByEncryptionType objectCountByEncryptionType) {
setObjectCountByEncryptionType(objectCountByEncryptionType);
return this;
}
/**
* <p>
* The total storage size, in bytes, of the bucket.
* </p>
* <p>
* If versioning is enabled for the bucket, Amazon Macie calculates this value based on the size of the latest
* version of each object in the bucket. This value doesn't reflect the storage size of all versions of each object
* in the bucket.
* </p>
*
* @param sizeInBytes
* The total storage size, in bytes, of the bucket.</p>
* <p>
* If versioning is enabled for the bucket, Amazon Macie calculates this value based on the size of the
* latest version of each object in the bucket. This value doesn't reflect the storage size of all versions
* of each object in the bucket.
*/
public void setSizeInBytes(Long sizeInBytes) {
this.sizeInBytes = sizeInBytes;
}
/**
* <p>
* The total storage size, in bytes, of the bucket.
* </p>
* <p>
* If versioning is enabled for the bucket, Amazon Macie calculates this value based on the size of the latest
* version of each object in the bucket. This value doesn't reflect the storage size of all versions of each object
* in the bucket.
* </p>
*
* @return The total storage size, in bytes, of the bucket.</p>
* <p>
* If versioning is enabled for the bucket, Amazon Macie calculates this value based on the size of the
* latest version of each object in the bucket. This value doesn't reflect the storage size of all versions
* of each object in the bucket.
*/
public Long getSizeInBytes() {
return this.sizeInBytes;
}
/**
* <p>
* The total storage size, in bytes, of the bucket.
* </p>
* <p>
* If versioning is enabled for the bucket, Amazon Macie calculates this value based on the size of the latest
* version of each object in the bucket. This value doesn't reflect the storage size of all versions of each object
* in the bucket.
* </p>
*
* @param sizeInBytes
* The total storage size, in bytes, of the bucket.</p>
* <p>
* If versioning is enabled for the bucket, Amazon Macie calculates this value based on the size of the
* latest version of each object in the bucket. This value doesn't reflect the storage size of all versions
* of each object in the bucket.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public MatchingBucket withSizeInBytes(Long sizeInBytes) {
setSizeInBytes(sizeInBytes);
return this;
}
/**
* <p>
* The total storage size, in bytes, of the objects that are compressed (.gz, .gzip, .zip) files in the bucket.
* </p>
* <p>
* If versioning is enabled for the bucket, Amazon Macie calculates this value based on the size of the latest
* version of each applicable object in the bucket. This value doesn't reflect the storage size of all versions of
* each applicable object in the bucket.
* </p>
*
* @param sizeInBytesCompressed
* The total storage size, in bytes, of the objects that are compressed (.gz, .gzip, .zip) files in the
* bucket.</p>
* <p>
* If versioning is enabled for the bucket, Amazon Macie calculates this value based on the size of the
* latest version of each applicable object in the bucket. This value doesn't reflect the storage size of all
* versions of each applicable object in the bucket.
*/
public void setSizeInBytesCompressed(Long sizeInBytesCompressed) {
this.sizeInBytesCompressed = sizeInBytesCompressed;
}
/**
* <p>
* The total storage size, in bytes, of the objects that are compressed (.gz, .gzip, .zip) files in the bucket.
* </p>
* <p>
* If versioning is enabled for the bucket, Amazon Macie calculates this value based on the size of the latest
* version of each applicable object in the bucket. This value doesn't reflect the storage size of all versions of
* each applicable object in the bucket.
* </p>
*
* @return The total storage size, in bytes, of the objects that are compressed (.gz, .gzip, .zip) files in the
* bucket.</p>
* <p>
* If versioning is enabled for the bucket, Amazon Macie calculates this value based on the size of the
* latest version of each applicable object in the bucket. This value doesn't reflect the storage size of
* all versions of each applicable object in the bucket.
*/
public Long getSizeInBytesCompressed() {
return this.sizeInBytesCompressed;
}
/**
* <p>
* The total storage size, in bytes, of the objects that are compressed (.gz, .gzip, .zip) files in the bucket.
* </p>
* <p>
* If versioning is enabled for the bucket, Amazon Macie calculates this value based on the size of the latest
* version of each applicable object in the bucket. This value doesn't reflect the storage size of all versions of
* each applicable object in the bucket.
* </p>
*
* @param sizeInBytesCompressed
* The total storage size, in bytes, of the objects that are compressed (.gz, .gzip, .zip) files in the
* bucket.</p>
* <p>
* If versioning is enabled for the bucket, Amazon Macie calculates this value based on the size of the
* latest version of each applicable object in the bucket. This value doesn't reflect the storage size of all
* versions of each applicable object in the bucket.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public MatchingBucket withSizeInBytesCompressed(Long sizeInBytesCompressed) {
setSizeInBytesCompressed(sizeInBytesCompressed);
return this;
}
/**
* <p>
* The total number of objects that Amazon Macie can't analyze in the bucket. These objects don't use a supported
* storage class or don't have a file name extension for a supported file or storage format.
* </p>
*
* @param unclassifiableObjectCount
* The total number of objects that Amazon Macie can't analyze in the bucket. These objects don't use a
* supported storage class or don't have a file name extension for a supported file or storage format.
*/
public void setUnclassifiableObjectCount(ObjectLevelStatistics unclassifiableObjectCount) {
this.unclassifiableObjectCount = unclassifiableObjectCount;
}
/**
* <p>
* The total number of objects that Amazon Macie can't analyze in the bucket. These objects don't use a supported
* storage class or don't have a file name extension for a supported file or storage format.
* </p>
*
* @return The total number of objects that Amazon Macie can't analyze in the bucket. These objects don't use a
* supported storage class or don't have a file name extension for a supported file or storage format.
*/
public ObjectLevelStatistics getUnclassifiableObjectCount() {
return this.unclassifiableObjectCount;
}
/**
* <p>
* The total number of objects that Amazon Macie can't analyze in the bucket. These objects don't use a supported
* storage class or don't have a file name extension for a supported file or storage format.
* </p>
*
* @param unclassifiableObjectCount
* The total number of objects that Amazon Macie can't analyze in the bucket. These objects don't use a
* supported storage class or don't have a file name extension for a supported file or storage format.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public MatchingBucket withUnclassifiableObjectCount(ObjectLevelStatistics unclassifiableObjectCount) {
setUnclassifiableObjectCount(unclassifiableObjectCount);
return this;
}
/**
* <p>
* The total storage size, in bytes, of the objects that Amazon Macie can't analyze in the bucket. These objects
* don't use a supported storage class or don't have a file name extension for a supported file or storage format.
* </p>
*
* @param unclassifiableObjectSizeInBytes
* The total storage size, in bytes, of the objects that Amazon Macie can't analyze in the bucket. These
* objects don't use a supported storage class or don't have a file name extension for a supported file or
* storage format.
*/
public void setUnclassifiableObjectSizeInBytes(ObjectLevelStatistics unclassifiableObjectSizeInBytes) {
this.unclassifiableObjectSizeInBytes = unclassifiableObjectSizeInBytes;
}
/**
* <p>
* The total storage size, in bytes, of the objects that Amazon Macie can't analyze in the bucket. These objects
* don't use a supported storage class or don't have a file name extension for a supported file or storage format.
* </p>
*
* @return The total storage size, in bytes, of the objects that Amazon Macie can't analyze in the bucket. These
* objects don't use a supported storage class or don't have a file name extension for a supported file or
* storage format.
*/
public ObjectLevelStatistics getUnclassifiableObjectSizeInBytes() {
return this.unclassifiableObjectSizeInBytes;
}
/**
* <p>
* The total storage size, in bytes, of the objects that Amazon Macie can't analyze in the bucket. These objects
* don't use a supported storage class or don't have a file name extension for a supported file or storage format.
* </p>
*
* @param unclassifiableObjectSizeInBytes
* The total storage size, in bytes, of the objects that Amazon Macie can't analyze in the bucket. These
* objects don't use a supported storage class or don't have a file name extension for a supported file or
* storage format.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public MatchingBucket withUnclassifiableObjectSizeInBytes(ObjectLevelStatistics unclassifiableObjectSizeInBytes) {
setUnclassifiableObjectSizeInBytes(unclassifiableObjectSizeInBytes);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getAccountId() != null)
sb.append("AccountId: ").append(getAccountId()).append(",");
if (getBucketName() != null)
sb.append("BucketName: ").append(getBucketName()).append(",");
if (getClassifiableObjectCount() != null)
sb.append("ClassifiableObjectCount: ").append(getClassifiableObjectCount()).append(",");
if (getClassifiableSizeInBytes() != null)
sb.append("ClassifiableSizeInBytes: ").append(getClassifiableSizeInBytes()).append(",");
if (getErrorCode() != null)
sb.append("ErrorCode: ").append(getErrorCode()).append(",");
if (getErrorMessage() != null)
sb.append("ErrorMessage: ").append(getErrorMessage()).append(",");
if (getJobDetails() != null)
sb.append("JobDetails: ").append(getJobDetails()).append(",");
if (getObjectCount() != null)
sb.append("ObjectCount: ").append(getObjectCount()).append(",");
if (getObjectCountByEncryptionType() != null)
sb.append("ObjectCountByEncryptionType: ").append(getObjectCountByEncryptionType()).append(",");
if (getSizeInBytes() != null)
sb.append("SizeInBytes: ").append(getSizeInBytes()).append(",");
if (getSizeInBytesCompressed() != null)
sb.append("SizeInBytesCompressed: ").append(getSizeInBytesCompressed()).append(",");
if (getUnclassifiableObjectCount() != null)
sb.append("UnclassifiableObjectCount: ").append(getUnclassifiableObjectCount()).append(",");
if (getUnclassifiableObjectSizeInBytes() != null)
sb.append("UnclassifiableObjectSizeInBytes: ").append(getUnclassifiableObjectSizeInBytes());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof MatchingBucket == false)
return false;
MatchingBucket other = (MatchingBucket) obj;
if (other.getAccountId() == null ^ this.getAccountId() == null)
return false;
if (other.getAccountId() != null && other.getAccountId().equals(this.getAccountId()) == false)
return false;
if (other.getBucketName() == null ^ this.getBucketName() == null)
return false;
if (other.getBucketName() != null && other.getBucketName().equals(this.getBucketName()) == false)
return false;
if (other.getClassifiableObjectCount() == null ^ this.getClassifiableObjectCount() == null)
return false;
if (other.getClassifiableObjectCount() != null && other.getClassifiableObjectCount().equals(this.getClassifiableObjectCount()) == false)
return false;
if (other.getClassifiableSizeInBytes() == null ^ this.getClassifiableSizeInBytes() == null)
return false;
if (other.getClassifiableSizeInBytes() != null && other.getClassifiableSizeInBytes().equals(this.getClassifiableSizeInBytes()) == false)
return false;
if (other.getErrorCode() == null ^ this.getErrorCode() == null)
return false;
if (other.getErrorCode() != null && other.getErrorCode().equals(this.getErrorCode()) == false)
return false;
if (other.getErrorMessage() == null ^ this.getErrorMessage() == null)
return false;
if (other.getErrorMessage() != null && other.getErrorMessage().equals(this.getErrorMessage()) == false)
return false;
if (other.getJobDetails() == null ^ this.getJobDetails() == null)
return false;
if (other.getJobDetails() != null && other.getJobDetails().equals(this.getJobDetails()) == false)
return false;
if (other.getObjectCount() == null ^ this.getObjectCount() == null)
return false;
if (other.getObjectCount() != null && other.getObjectCount().equals(this.getObjectCount()) == false)
return false;
if (other.getObjectCountByEncryptionType() == null ^ this.getObjectCountByEncryptionType() == null)
return false;
if (other.getObjectCountByEncryptionType() != null && other.getObjectCountByEncryptionType().equals(this.getObjectCountByEncryptionType()) == false)
return false;
if (other.getSizeInBytes() == null ^ this.getSizeInBytes() == null)
return false;
if (other.getSizeInBytes() != null && other.getSizeInBytes().equals(this.getSizeInBytes()) == false)
return false;
if (other.getSizeInBytesCompressed() == null ^ this.getSizeInBytesCompressed() == null)
return false;
if (other.getSizeInBytesCompressed() != null && other.getSizeInBytesCompressed().equals(this.getSizeInBytesCompressed()) == false)
return false;
if (other.getUnclassifiableObjectCount() == null ^ this.getUnclassifiableObjectCount() == null)
return false;
if (other.getUnclassifiableObjectCount() != null && other.getUnclassifiableObjectCount().equals(this.getUnclassifiableObjectCount()) == false)
return false;
if (other.getUnclassifiableObjectSizeInBytes() == null ^ this.getUnclassifiableObjectSizeInBytes() == null)
return false;
if (other.getUnclassifiableObjectSizeInBytes() != null
&& other.getUnclassifiableObjectSizeInBytes().equals(this.getUnclassifiableObjectSizeInBytes()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getAccountId() == null) ? 0 : getAccountId().hashCode());
hashCode = prime * hashCode + ((getBucketName() == null) ? 0 : getBucketName().hashCode());
hashCode = prime * hashCode + ((getClassifiableObjectCount() == null) ? 0 : getClassifiableObjectCount().hashCode());
hashCode = prime * hashCode + ((getClassifiableSizeInBytes() == null) ? 0 : getClassifiableSizeInBytes().hashCode());
hashCode = prime * hashCode + ((getErrorCode() == null) ? 0 : getErrorCode().hashCode());
hashCode = prime * hashCode + ((getErrorMessage() == null) ? 0 : getErrorMessage().hashCode());
hashCode = prime * hashCode + ((getJobDetails() == null) ? 0 : getJobDetails().hashCode());
hashCode = prime * hashCode + ((getObjectCount() == null) ? 0 : getObjectCount().hashCode());
hashCode = prime * hashCode + ((getObjectCountByEncryptionType() == null) ? 0 : getObjectCountByEncryptionType().hashCode());
hashCode = prime * hashCode + ((getSizeInBytes() == null) ? 0 : getSizeInBytes().hashCode());
hashCode = prime * hashCode + ((getSizeInBytesCompressed() == null) ? 0 : getSizeInBytesCompressed().hashCode());
hashCode = prime * hashCode + ((getUnclassifiableObjectCount() == null) ? 0 : getUnclassifiableObjectCount().hashCode());
hashCode = prime * hashCode + ((getUnclassifiableObjectSizeInBytes() == null) ? 0 : getUnclassifiableObjectSizeInBytes().hashCode());
return hashCode;
}
@Override
public MatchingBucket clone() {
try {
return (MatchingBucket) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
@com.amazonaws.annotation.SdkInternalApi
@Override
public void marshall(ProtocolMarshaller protocolMarshaller) {
com.amazonaws.services.macie2.model.transform.MatchingBucketMarshaller.getInstance().marshall(this, protocolMarshaller);
}
}
| apache-2.0 |
delogic/asd | asd-core/src/test/java/br/com/delogic/asd/housekeeping/TimeHousekeepingJobTest.java | 4098 | package br.com.delogic.asd.housekeeping;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.File;
import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Test;
public class TimeHousekeepingJobTest {
private HousekeepingJob hk;
@After
public void clean() {
File tempDir = new File(getTempDir());
tempDir.delete();
}
@Test
public void deveExcluirArquivos() throws Exception {
dadoArquivosEmMBPorTempo(10, 0);
dadoHouseKeepingTempoMinutos(5.1);
quandoExecutarHousekeeping();
entaoArquivosRemanecentes(5);
entaoArquivosRemanecente("arquivo.txt5");
entaoArquivosRemanecente("arquivo.txt6");
entaoArquivosRemanecente("arquivo.txt7");
entaoArquivosRemanecente("arquivo.txt8");
entaoArquivosRemanecente("arquivo.txt9");
}
@Test
public void deveExcluirArquivosSomente1Vez() throws Exception {
dadoArquivosEmMBPorTempo(10, 0);
dadoHouseKeepingTempoMinutos(5.1);
quandoExecutarHousekeeping();
quandoExecutarHousekeeping();
quandoExecutarHousekeeping();
quandoExecutarHousekeeping();
quandoExecutarHousekeeping();
entaoArquivosRemanecentes(5);
entaoArquivosRemanecente("arquivo.txt5");
entaoArquivosRemanecente("arquivo.txt6");
entaoArquivosRemanecente("arquivo.txt7");
entaoArquivosRemanecente("arquivo.txt8");
entaoArquivosRemanecente("arquivo.txt9");
}
@Test
public void deveExcluirArquivos1Apenas() throws Exception {
dadoArquivosEmMBPorTempo(10, 0);
dadoHouseKeepingTempoMinutos(9.1);
quandoExecutarHousekeeping();
entaoArquivosRemanecentes(9);
entaoArquivosRemanecente("arquivo.txt1");
entaoArquivosRemanecente("arquivo.txt2");
entaoArquivosRemanecente("arquivo.txt3");
entaoArquivosRemanecente("arquivo.txt4");
entaoArquivosRemanecente("arquivo.txt5");
entaoArquivosRemanecente("arquivo.txt6");
entaoArquivosRemanecente("arquivo.txt7");
entaoArquivosRemanecente("arquivo.txt8");
entaoArquivosRemanecente("arquivo.txt9");
}
@Test
public void deveExcluirNenhumArquivo() throws Exception {
dadoArquivosEmMBPorTempo(10, 0);
dadoHouseKeepingTempoMinutos(10.1);
quandoExecutarHousekeeping();
entaoArquivosRemanecentes(10);
entaoArquivosRemanecente("arquivo.txt0");
entaoArquivosRemanecente("arquivo.txt1");
entaoArquivosRemanecente("arquivo.txt2");
entaoArquivosRemanecente("arquivo.txt3");
entaoArquivosRemanecente("arquivo.txt4");
entaoArquivosRemanecente("arquivo.txt5");
entaoArquivosRemanecente("arquivo.txt6");
entaoArquivosRemanecente("arquivo.txt7");
entaoArquivosRemanecente("arquivo.txt8");
entaoArquivosRemanecente("arquivo.txt9");
}
@Test
public void deveExcluirTodosArquivos() throws Exception {
dadoArquivosEmMBPorTempo(10, 1);
dadoHouseKeepingTempoMinutos(0.9999);
quandoExecutarHousekeeping();
entaoArquivosRemanecentes(0);
}
private void entaoArquivosRemanecente(String string) {
assertTrue(new File(getTempDir() + string).exists());
}
private void dadoArquivosEmMBPorTempo(int qtde, int tamanho) throws Exception {
for (int i = 0; i < qtde; i++) {
File arquivo = new File(getTempDir() + "arquivo.txt" + i);
System.out.println("gravando arquivos:" + arquivo.getAbsolutePath());
FileUtils.writeStringToFile(arquivo, getTextoEmMB(tamanho));
arquivo.setLastModified(System.currentTimeMillis() - (qtde - i) * 60 * 1000);
}
}
private String getTempDir() {
String dir = System.getProperty("java.io.tmpdir");
dir = dir.endsWith("/") ? dir : dir + File.separator;
dir += "temphousekeeping" + File.separator;
new File(dir).mkdirs();
return dir;
}
private String getTextoEmMB(int tamanho) {
StringBuilder sb = new StringBuilder();
while (sb.length() < (1024 * 1024)) {
sb.append("a");
}
return sb.toString();
}
private void dadoHouseKeepingTempoMinutos(double i) {
hk = new TimeHousekeepingJob(getTempDir(), i / 60);
}
private void quandoExecutarHousekeeping() {
hk.run();
}
private void entaoArquivosRemanecentes(int i) {
File[] arquivos = new File(getTempDir()).listFiles();
assertEquals(i, arquivos.length);
}
} | apache-2.0 |
OpenSourceConsulting/athena-chameleon | src/main/java/com/athena/chameleon/engine/entity/xml/ejbjar/jeus/v6_0/DatabaseInsertDelayType.java | 1573 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.0-b52-fcs
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2012.09.05 at 10:14:54 오후 KST
//
package com.athena.chameleon.engine.entity.xml.ejbjar.jeus.v6_0;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlEnumValue;
/**
* <p>Java class for database-insert-delayType.
*
* <p>The following schema fragment specifies the expected content contained within this class.
* <p>
* <pre>
* <simpleType name="database-insert-delayType">
* <restriction base="{http://www.w3.org/2001/XMLSchema}token">
* <enumeration value="ejbCreate"/>
* <enumeration value="ejbPostCreate"/>
* </restriction>
* </simpleType>
* </pre>
*
*/
@XmlEnum
public enum DatabaseInsertDelayType {
@XmlEnumValue("ejbCreate")
EJB_CREATE("ejbCreate"),
@XmlEnumValue("ejbPostCreate")
EJB_POST_CREATE("ejbPostCreate");
private final String value;
DatabaseInsertDelayType(String v) {
value = v;
}
public String value() {
return value;
}
public static DatabaseInsertDelayType fromValue(String v) {
for (DatabaseInsertDelayType c: DatabaseInsertDelayType.values()) {
if (c.value.equals(v)) {
return c;
}
}
throw new IllegalArgumentException(v.toString());
}
}
| apache-2.0 |
amischler/JRebirth | org.jrebirth/showcase/fxml/src/main/java/org/jrebirth/showcase/fxml/ui/embedded/EmbeddedModel.java | 432 | package org.jrebirth.showcase.fxml.ui.embedded;
import org.jrebirth.core.ui.DefaultModel;
/**
* The class <strong>StandaloneModel</strong>.
*
* @author Sébastien Bordes
*/
public class EmbeddedModel extends DefaultModel<EmbeddedModel, EmbeddedView> {
/**
* {@inheritDoc}
*/
@Override
protected void initModel() {
// Nothing to do yet
super.initModel();
}
}
| apache-2.0 |
confluentinc/examples | clients/cloud/java/src/main/java/io/confluent/examples/clients/cloud/ConsumerAvroExample.java | 3510 | /**
* Copyright 2020 Confluent 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 io.confluent.examples.clients.cloud;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.Consumer;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import io.confluent.kafka.serializers.KafkaAvroDeserializer;
import io.confluent.kafka.serializers.KafkaAvroDeserializerConfig;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Properties;
public class ConsumerAvroExample {
public static void main(final String[] args) throws Exception {
if (args.length != 2) {
System.out.println("Please provide command line arguments: configPath topic");
System.exit(1);
}
final String topic = args[1];
// Load properties from a local configuration file
// Create the configuration file (e.g. at '$HOME/.confluent/java.config') with configuration parameters
// to connect to your Kafka cluster, which can be on your local host, Confluent Cloud, or any other cluster.
// Follow these instructions to create this file: https://docs.confluent.io/platform/current/tutorials/examples/clients/docs/java.html
final Properties props = loadConfig(args[0]);
// Add additional properties.
props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer");
props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, KafkaAvroDeserializer.class);
props.put(KafkaAvroDeserializerConfig.SPECIFIC_AVRO_READER_CONFIG, true);
props.put(ConsumerConfig.GROUP_ID_CONFIG, "demo-consumer-avro-1");
props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
final Consumer<String, DataRecordAvro> consumer = new KafkaConsumer<String, DataRecordAvro>(props);
consumer.subscribe(Arrays.asList(topic));
Long total_count = 0L;
try {
while (true) {
ConsumerRecords<String, DataRecordAvro> records = consumer.poll(100);
for (ConsumerRecord<String, DataRecordAvro> record : records) {
String key = record.key();
DataRecordAvro value = record.value();
total_count += value.getCount();
System.out.printf("Consumed record with key %s and value %s, and updated total count to %d%n", key, value, total_count);
}
}
} finally {
consumer.close();
}
}
public static Properties loadConfig(String configFile) throws IOException {
if (!Files.exists(Paths.get(configFile))) {
throw new IOException(configFile + " not found.");
}
final Properties cfg = new Properties();
try (InputStream inputStream = new FileInputStream(configFile)) {
cfg.load(inputStream);
}
return cfg;
}
}
| apache-2.0 |
ruiguo11/Go-Ubiquitous | app/src/main/java/com/example/android/sunshine/app/sync/SunshineSyncService.java | 2127 | package com.example.android.sunshine.app.sync;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import com.google.android.gms.wearable.DataApi;
import com.google.android.gms.wearable.DataEvent;
import com.google.android.gms.wearable.DataEventBuffer;
public class SunshineSyncService extends Service {
private static final Object sSyncAdapterLock = new Object();
private static SunshineSyncAdapter sSunshineSyncAdapter = null;
//private static final String LOG_TAG= "SunShineSyncService";
//private static final String DATA_ITEM_RECEIVED_PATH = "/weather";
@Override
public void onCreate() {
Log.d("SunshineSyncService", "onCreate - SunshineSyncService");
synchronized (sSyncAdapterLock) {
if (sSunshineSyncAdapter == null) {
sSunshineSyncAdapter = new SunshineSyncAdapter(getApplicationContext(), true);
}
}
}
@Override
public IBinder onBind(Intent intent) {
return sSunshineSyncAdapter.getSyncAdapterBinder();
}
/*@Override
public void onDataChanged(DataEventBuffer dataEvents) {
if (Log.isLoggable(LOG_TAG, Log.DEBUG)) {
Log.d(LOG_TAG, "onDataChanged: " + dataEvents);
}
/*
final List events = FreezableUtils
.freezeIterable(dataEvents);
GoogleApiClient googleApiClient = new GoogleApiClient.Builder(this)
.addApi(Wearable.API)
.build();
ConnectionResult connectionResult =
googleApiClient.blockingConnect(30, TimeUnit.SECONDS);
if (!connectionResult.isSuccess()) {
Log.e(LOG_TAG, "Failed to connect to GoogleApiClient.");
return;
}
for (DataEvent event : dataEvents) {
if(event.getType()==DataEvent.TYPE_CHANGED){
String path = event.getDataItem().getUri().getPath();
if(path.equals(DATA_ITEM_RECEIVED_PATH ))
SunshineSyncAdapter.syncImmediately(this);
}
}
}
*/
} | apache-2.0 |
krosenvold/selenium | java/client/src/com/thoughtworks/selenium/webdriven/commands/Open.java | 1721 | // Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package com.thoughtworks.selenium.webdriven.commands;
import com.thoughtworks.selenium.SeleniumException;
import com.thoughtworks.selenium.webdriven.SeleneseCommand;
import org.openqa.selenium.WebDriver;
import java.net.MalformedURLException;
import java.net.URL;
public class Open extends SeleneseCommand<Void> {
private final URL baseUrl;
public Open(String baseUrl) {
try {
this.baseUrl = new URL(baseUrl);
} catch (MalformedURLException e) {
throw new SeleniumException(e.getMessage(), e);
}
}
@Override
protected Void handleSeleneseCommand(final WebDriver driver, String url, String ignored) {
try {
final String urlToOpen = !url.contains("://") ?
new URL(baseUrl, url).toString() :
url;
driver.get(urlToOpen);
} catch (MalformedURLException e) {
throw new SeleniumException(e.getMessage(), e);
}
return null;
}
}
| apache-2.0 |
tadayosi/camel | components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/integration/FileToFtpsImplicitSSLWithClientAuthIT.java | 2509 | /*
* 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.camel.component.file.remote.integration;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledIf;
/**
* Test the ftps component over SSL (implicit) with client authentication
*/
@EnabledIf(value = "org.apache.camel.component.file.remote.services.FtpsEmbeddedService#hasRequiredAlgorithms")
public class FileToFtpsImplicitSSLWithClientAuthIT extends FtpsServerImplicitSSLWithClientAuthTestSupport {
protected String getFtpUrl() {
return "ftps://admin@localhost:{{ftp.server.port}}"
+ "/tmp2/camel?password=admin&initialDelay=2000&disableSecureDataChannelDefaults=true"
+ "&securityProtocol=SSLv3&implicit=true&ftpClient.keyStore.file=./src/test/resources/server.jks&ftpClient.keyStore.type=JKS"
+ "&ftpClient.keyStore.algorithm=SunX509&ftpClient.keyStore.password=password&ftpClient.keyStore.keyPassword=password&delete=true";
}
@Disabled("CAMEL-16784:Disable testFromFileToFtp tests")
@Test
public void testFromFileToFtp() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedMessageCount(2);
assertMockEndpointsSatisfied();
}
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
public void configure() throws Exception {
from("file:src/main/data?noop=true").log("Got ${file:name}").to(getFtpUrl());
from(getFtpUrl()).to("mock:result");
}
};
}
}
| apache-2.0 |
nafae/developer | modules/dfp_appengine/src/main/java/com/google/api/ads/dfp/jaxws/v201306/LineItemCreativeAssociationServiceInterfacecreateLineItemCreativeAssociationResponse.java | 1766 |
package com.google.api.ads.dfp.jaxws.v201306;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for createLineItemCreativeAssociationResponse element declaration.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <element name="createLineItemCreativeAssociationResponse">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="rval" type="{https://www.google.com/apis/ads/publisher/v201306}LineItemCreativeAssociation" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"rval"
})
@XmlRootElement(name = "createLineItemCreativeAssociationResponse")
public class LineItemCreativeAssociationServiceInterfacecreateLineItemCreativeAssociationResponse {
protected LineItemCreativeAssociation rval;
/**
* Gets the value of the rval property.
*
* @return
* possible object is
* {@link LineItemCreativeAssociation }
*
*/
public LineItemCreativeAssociation getRval() {
return rval;
}
/**
* Sets the value of the rval property.
*
* @param value
* allowed object is
* {@link LineItemCreativeAssociation }
*
*/
public void setRval(LineItemCreativeAssociation value) {
this.rval = value;
}
}
| apache-2.0 |
gravitee-io/gravitee-management-rest-api | gravitee-rest-api-repository/src/main/java/io/gravitee/rest/api/repository/proxy/MonitoringRepositoryProxy.java | 1194 | /**
* Copyright (C) 2015 The Gravitee team (http://gravitee.io)
*
* 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 io.gravitee.rest.api.repository.proxy;
import io.gravitee.repository.monitoring.MonitoringRepository;
import io.gravitee.repository.monitoring.model.MonitoringResponse;
import org.springframework.stereotype.Component;
/**
* @author David BRASSELY (david.brassely at graviteesource.com)
* @author GraviteeSource Team
*/
@Component
public class MonitoringRepositoryProxy extends AbstractProxy<MonitoringRepository> implements MonitoringRepository {
@Override
public MonitoringResponse query(String s) {
return target.query(s);
}
}
| apache-2.0 |
bodawei/JPEGFile | src/main/java/com/davidjohnburrowes/format/jpeg/component/DhtHuffmanTable.java | 7107 | /*
* Copyright 2014,2017 柏大衛
*
* 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.davidjohnburrowes.format.jpeg.component;
import com.davidjohnburrowes.format.jpeg.data.Component;
import com.davidjohnburrowes.format.jpeg.support.DataBounds;
import com.davidjohnburrowes.util.Nibble;
import com.davidjohnburrowes.util.Size;
import java.io.DataInput;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* A list of Huffman values
*
* Defined on page B-12 to B-14 of the standard.
*/
public class DhtHuffmanTable extends Component {
private static final int NUM_CODE_COUNTS = 16;
private static final DataBounds tableClassBounds = new DataBounds(
"tableClass", Size.NIBBLE,
0, 1,
0, 1,
0, 1,
0, 0);
private static final DataBounds tableIdBounds = new DataBounds(
"tableId", Size.NIBBLE,
0, 1,
0, 3,
0, 3,
0, 3);
private static final DataBounds elementSizeBounds = new DataBounds(
"elementSize", Size.BYTE,
0, 255);
private static final DataBounds valueBounds = new DataBounds(
"code", Size.BYTE,
0, 255);
/**
* True if this is an AC table (otherwise is DC)
*/
protected byte tableClass;
/**
* ID of the table
*/
protected byte tableId;
/**
* The set of run length headers in this table
*/
protected List<short[]> elements;
public DhtHuffmanTable() {
tableClass = 0;
tableId = 0;
elements = new ArrayList<short[]>();
for (int index = 0; index < NUM_CODE_COUNTS; index++) {
elements.add(new short[0]);
}
}
/**
* @param newClass of the table
*/
public void setTableClass(int newClass) {
tableClassBounds.throwIfInvalid(newClass, this.getFrameMode(), this.getDataMode());
tableClass = (byte) newClass;
}
/**
* @return Class of the table (0 == DC, 1 == AC)
*/
public byte getTableClass() {
return tableClass;
}
/**
* @param newId The id for this table.
*/
public void setTableId(int newId) {
tableIdBounds.throwIfInvalid(newId, this.getFrameMode(), this.getDataMode());
this.tableId = (byte)newId;
}
/**
* @return id of this table (a value of 0-3)
*/
public int getTableId() {
return tableId;
}
/**
* Sets an element at the specified index. An element is, it self, an array
* of byte values (stored as shorts because they are unsigned values)
* @param index The index of the element to add
* @param element The element to add. Note that the items in the element array
* must be in the range 0-255
*/
public void setElement(int index, short[] element) {
if (index >= NUM_CODE_COUNTS) {
throw new IllegalArgumentException("Cant have more than 16 elements");
}
if (element == null) {
throw new IllegalArgumentException("Cant set an elements to null");
}
elementSizeBounds.throwIfInvalid(element.length, this.getFrameMode(), this.getDataMode());
for (int subIndex = 0; subIndex < element.length; subIndex++) {
if (element[subIndex] > 255 || element[subIndex] < 0) {
throw new IllegalArgumentException("Items in the element array must be in the range 0-255");
}
}
elements.set(index, element);
}
/**
*
* @param index The index of the element to retrieve
* @return The element.
*/
public short[] getElement(int index) {
if (index >= NUM_CODE_COUNTS) {
throw new IllegalArgumentException("Cant have more than 16 elements");
}
return elements.get(index);
}
/**
* {@inheritDoc}
*/
@Override
public int getSizeOnDisk() {
int elemntsSize = 0;
for (short[] element : elements) {
elemntsSize += element.length;
}
return 17 + elemntsSize;
}
/**
* {@inheritDoc}
*/
@Override
public void readParameters(DataInput source) throws IOException {
super.readParameters(source);
int flags = source.readUnsignedByte();
setTableClass((int)Nibble.getUpper(flags));
setTableId(Nibble.getLower(flags));
short[] codeCounts = new short[NUM_CODE_COUNTS];
for (int index = 0; index < NUM_CODE_COUNTS; index++) {
codeCounts[index] = (short) source.readUnsignedByte();
}
for (int index = 0; index < NUM_CODE_COUNTS; index++) {
byte[] huffmanEntries = new byte[codeCounts[index]];
source.readFully(huffmanEntries);
// convert the raw bytes to shorts
short[] actualEntries = new short[codeCounts[index]];
for (int subIndex = 0; subIndex < codeCounts[index]; subIndex ++) {
actualEntries[subIndex] = (short) (0xFF & ((short) huffmanEntries[subIndex]));
}
setElement(index, actualEntries);
}
}
/**
* {@inheritDoc}
*/
@Override
public void writeParameters(DataOutputStream output) throws IOException {
output.writeByte(Nibble.makeByte(getTableClass(), getTableId()));
for (int index = 0; index < NUM_CODE_COUNTS; index++) {
output.writeByte(getElement(index).length);
}
for (short[] element : elements) {
for (int subIndex = 0; subIndex < element.length; subIndex++) {
output.write((byte)(0xFF & element[subIndex]));
}
}
}
/**
* {@inheritDoc}
*/
@Override
public List<Exception> validate() {
List<Exception> results = super.validate();
tableClassBounds.accumulateOnViolation(getTableClass(), getFrameMode(), results);
tableIdBounds.accumulateOnViolation(getTableId(), getFrameMode(), results);
for (short[] element : elements) {
elementSizeBounds.accumulateOnViolation(element.length, this.getFrameMode(), results);
for (short value : element) {
valueBounds.accumulateOnViolation(value, getFrameMode(), results);
}
}
return results;
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(Object other) {
if ((other == null) || !(other instanceof DhtHuffmanTable)) {
return false;
} else {
DhtHuffmanTable otherTable = (DhtHuffmanTable) other;
if (getTableId() != otherTable.getTableId()) {
return false;
}
if (getTableClass() != otherTable.getTableClass()) {
return false;
}
for (int index = 0; index < NUM_CODE_COUNTS; index++) {
if ( ! Arrays.equals(getElement(index), otherTable.getElement(index))) {
return false;
}
}
}
return true;
}
@Override
public int hashCode() {
int hash = 5;
hash = 83 * hash + this.tableClass;
hash = 83 * hash + this.tableId;
hash = 83 * hash + this.elements.hashCode();
return hash;
}
/**
* {@inheritDoc}
*/
@Override
protected void checkModeChange() {
super.checkModeChange();
setTableClass(getTableClass());
setTableId(getTableId());
for (int index = 0; index < NUM_CODE_COUNTS; index++) {
setElement(index, getElement(index));
}
}
}
| apache-2.0 |
jenkinsci/kubernetes-plugin | src/test/java/org/csanchez/jenkins/plugins/kubernetes/KubernetesProvisioningLimitsTest.java | 3618 | package org.csanchez.jenkins.plugins.kubernetes;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.List;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.JenkinsRule;
import org.jvnet.hudson.test.LoggerRule;
public class KubernetesProvisioningLimitsTest {
@Rule
public JenkinsRule j = new JenkinsRule();
@Rule
public LoggerRule log = new LoggerRule().record(KubernetesProvisioningLimits.class, Level.FINEST);
@Test
public void lotsOfCloudsAndTemplates() throws InterruptedException {
ThreadLocalRandom testRandom = ThreadLocalRandom.current();
for (int i = 1; i < 4; i++) {
KubernetesCloud cloud = new KubernetesCloud("kubernetes-" + i);
cloud.setContainerCap(testRandom.nextInt(4)+1);
for (int j = 1; j < 4; j++) {
PodTemplate pt = new PodTemplate();
pt.setName(cloud.name + "-podTemplate-" + j);
pt.setInstanceCap(testRandom.nextInt(4)+1);
cloud.addTemplate(pt);
}
j.jenkins.clouds.add(cloud);
}
ExecutorService threadPool = Executors.newCachedThreadPool();
System.out.println(threadPool.getClass().getName());
CompletionService<Void> ecs = new ExecutorCompletionService<>(threadPool);
KubernetesProvisioningLimits kubernetesProvisioningLimits = KubernetesProvisioningLimits.get();
List<KubernetesCloud> clouds = j.jenkins.clouds.getAll(KubernetesCloud.class);
for (int k = 0 ; k < 1000; k++) {
ecs.submit(() -> {
ThreadLocalRandom random = ThreadLocalRandom.current();
KubernetesCloud cloud = clouds.get(random.nextInt(clouds.size()));
List<PodTemplate> templates = cloud.getTemplates();
PodTemplate podTemplate = templates.get(random.nextInt(templates.size()));
while (!kubernetesProvisioningLimits.register(cloud, podTemplate, 1)) {
try {
Thread.sleep(8);
} catch(InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
}
ecs.submit(() -> {
kubernetesProvisioningLimits.unregister(cloud, podTemplate, 1);
}, null);
}, null);
}
while (ecs.poll(20, TimeUnit.SECONDS) != null) {
try {
Thread.sleep(8);
} catch(InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
}
threadPool.shutdown();
assertTrue(threadPool.awaitTermination(60, TimeUnit.SECONDS));
assertEquals(0, threadPool.shutdownNow().size());
// Check that every count is back to 0
for (KubernetesCloud cloud : j.jenkins.clouds.getAll(KubernetesCloud.class)) {
assertEquals(0, KubernetesProvisioningLimits.get().getGlobalCount(cloud.name));
for (PodTemplate template : cloud.getTemplates()) {
assertEquals(0, KubernetesProvisioningLimits.get().getPodTemplateCount(template.getId()));
}
}
}
}
| apache-2.0 |
vjanmey/EpicMudfia | com/planet_ink/coffee_mud/Items/interfaces/ClanItem.java | 2516 | package com.planet_ink.coffee_mud.Items.interfaces;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
/*
Copyright 2000-2014 Bo Zimmerman
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.
*/
public interface ClanItem extends Item
{
public final static int CI_FLAG=0;
public final static int CI_BANNER=1;
public final static int CI_GAVEL=2;
public final static int CI_PROPAGANDA=3;
public final static int CI_GATHERITEM=4;
public final static int CI_CRAFTITEM=5;
public final static int CI_SPECIALSCALES=6;
public final static int CI_SPECIALSCAVENGER=7;
public final static int CI_SPECIALOTHER=8;
public final static int CI_SPECIALTAXER=9;
public final static int CI_DONATEJOURNAL=10;
public final static int CI_ANTIPROPAGANDA=11;
public final static int CI_SPECIALAPRON=12;
public final static int CI_LEGALBADGE=13;
public final static String[] CI_DESC={
"FLAG",
"BANNER",
"GAVEL",
"PROPAGANDA",
"GATHERITEM",
"CRAFTITEM",
"SPECIALSCALES",
"SPECIALSCAVENGER",
"SPECIALOTHER",
"SPECIALTAXER",
"DONATIONJOURNAL",
"ANTI-PROPAGANDA",
"SPECIALAPRON",
"LEGALBADGE"
};
public String clanID();
public void setClanID(String ID);
public int ciType();
public void setCIType(int type);
public Environmental rightfulOwner();
public void setRightfulOwner(Environmental E);
}
| apache-2.0 |
topie/topie-oa | src/main/java/com/topie/internal/whitelist/support/HttpWhitelistConnector.java | 2493 | package com.topie.internal.whitelist.support;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import com.topie.api.whitelist.WhitelistConnector;
import com.topie.api.whitelist.WhitelistDTO;
import com.topie.core.http.HttpHandler;
import com.topie.core.http.HttpHandlerImpl;
import com.topie.core.mapper.JsonMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
// http://localhost/rs/whitelist/get?code=CAS
public class HttpWhitelistConnector implements WhitelistConnector {
private static Logger logger = LoggerFactory
.getLogger(HttpWhitelistConnector.class);
private JsonMapper jsonMapper = new JsonMapper();
private HttpHandler httpHandler = new HttpHandlerImpl();
private String baseUrl;
public WhitelistDTO getWhitelist(String code, String tenantId) {
WhitelistDTO result = new WhitelistDTO();
List<WhitelistDTO> whitelistDtos = this.getWhitelists(code, tenantId);
for (WhitelistDTO whitelistDto : whitelistDtos) {
result.getHosts().addAll(whitelistDto.getHosts());
result.getIps().addAll(whitelistDto.getIps());
}
return result;
}
public List<WhitelistDTO> getWhitelists(String code, String tenantId) {
try {
String text = httpHandler.readText(baseUrl + "?code=" + code
+ "&tenantId=" + tenantId);
Map<String, Object> result = jsonMapper.fromJson(text, Map.class);
logger.debug("result : {}", result);
List<Map> list = (List<Map>) result.get("data");
if (list == null) {
return Collections.emptyList();
}
List<WhitelistDTO> whitelistDtos = new ArrayList<WhitelistDTO>();
for (Map map : list) {
WhitelistDTO whitelistDto = new WhitelistDTO();
whitelistDtos.add(whitelistDto);
whitelistDto.setName((String) map.get("name"));
whitelistDto.setDescription((String) map.get("description"));
whitelistDto.setHosts((List<String>) map.get("host"));
whitelistDto.setIps((List<String>) map.get("ip"));
}
return whitelistDtos;
} catch (Exception ex) {
logger.error(ex.getMessage(), ex);
return Collections.emptyList();
}
}
public void setBaseUrl(String baseUrl) {
this.baseUrl = baseUrl;
}
}
| apache-2.0 |
ridwanarip/laporan-sandikta | src/main/java/net/sandikta/smp/raportapp/entities/enums/Semester.java | 93 | package net.sandikta.smp.raportapp.entities.enums;
public enum Semester {
GANJIL,
GENAP
} | apache-2.0 |
topie/topie-oa | src/main/java/com/topie/api/user/UserCache.java | 339 | package com.topie.api.user;
public interface UserCache {
UserDTO findById(String id);
UserDTO findByUsername(String username, String userRepoRef);
UserDTO findByRef(String ref, String userRepoRef);
UserDTO findByNickName(String nickName);
void updateUser(UserDTO userDto);
void removeUser(UserDTO userDto);
}
| apache-2.0 |
sbower/kuali-rice-1 | impl/src/main/java/org/kuali/rice/krad/uif/service/impl/ViewDictionaryServiceImpl.java | 6571 | /*
* Copyright 2011 The Kuali Foundation Licensed under the Educational Community
* License, Version 1.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.opensource.org/licenses/ecl1.php 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.kuali.rice.krad.uif.service.impl;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.kuali.rice.core.api.exception.RiceRuntimeException;
import org.kuali.rice.krad.datadictionary.DataDictionary;
import org.kuali.rice.krad.datadictionary.DataDictionaryException;
import org.kuali.rice.krad.inquiry.Inquirable;
import org.kuali.rice.krad.service.DataDictionaryService;
import org.kuali.rice.krad.uif.UifConstants;
import org.kuali.rice.krad.uif.UifParameters;
import org.kuali.rice.krad.uif.util.ViewModelUtils;
import org.kuali.rice.krad.uif.view.InquiryView;
import org.kuali.rice.krad.uif.view.LookupView;
import org.kuali.rice.krad.uif.view.MaintenanceView;
import org.kuali.rice.krad.uif.view.View;
import org.kuali.rice.krad.uif.service.ViewDictionaryService;
import org.kuali.rice.krad.uif.UifConstants.ViewType;
import org.kuali.rice.krad.util.ObjectUtils;
import org.springframework.beans.PropertyValues;
/**
* Implementation of <code>ViewDictionaryService</code>
*
* <p>
* Pulls view entries from the data dictionary to implement the various query
* methods
* </p>
*
* @author Kuali Rice Team (rice.collab@kuali.org)
*/
public class ViewDictionaryServiceImpl implements ViewDictionaryService {
private DataDictionaryService dataDictionaryService;
/**
* @see org.kuali.rice.krad.uif.service.ViewDictionaryService#getInquirable(java.lang.Class,
* java.lang.String)
*/
public Inquirable getInquirable(Class<?> dataObjectClass, String viewName) {
Inquirable inquirable = null;
if (StringUtils.isBlank(viewName)) {
viewName = UifConstants.DEFAULT_VIEW_NAME;
}
Map<String, String> indexKey = new HashMap<String, String>();
indexKey.put(UifParameters.VIEW_NAME, viewName);
indexKey.put(UifParameters.DATA_OBJECT_CLASS_NAME, dataObjectClass.getName());
// get view properties
PropertyValues propertyValues = getDataDictionary().getViewPropertiesByType(ViewType.INQUIRY, indexKey);
String viewHelperServiceClassName = ViewModelUtils.getStringValFromPVs(propertyValues,
"viewHelperServiceClassName");
if (StringUtils.isNotBlank(viewHelperServiceClassName)) {
try {
inquirable = (Inquirable) ObjectUtils.newInstance(Class.forName(viewHelperServiceClassName));
} catch (ClassNotFoundException e) {
throw new RiceRuntimeException(
"Unable to find class for inquirable classname: " + viewHelperServiceClassName, e);
}
}
return inquirable;
}
/**
* @see org.kuali.rice.krad.uif.service.ViewDictionaryService#isInquirable(java.lang.Class)
*/
public boolean isInquirable(Class<?> dataObjectClass) {
Map<String, String> indexKey = new HashMap<String, String>();
indexKey.put(UifParameters.VIEW_NAME, UifConstants.DEFAULT_VIEW_NAME);
indexKey.put(UifParameters.DATA_OBJECT_CLASS_NAME, dataObjectClass.getName());
boolean isInquirable = getDataDictionary().viewByTypeExist(ViewType.INQUIRY, indexKey);
return isInquirable;
}
/**
* @see org.kuali.rice.krad.uif.service.ViewDictionaryService#isLookupable(java.lang.Class)
*/
public boolean isLookupable(Class<?> dataObjectClass) {
Map<String, String> indexKey = new HashMap<String, String>();
indexKey.put(UifParameters.VIEW_NAME, UifConstants.DEFAULT_VIEW_NAME);
indexKey.put(UifParameters.DATA_OBJECT_CLASS_NAME, dataObjectClass.getName());
boolean isLookupable = getDataDictionary().viewByTypeExist(ViewType.LOOKUP, indexKey);
return isLookupable;
}
/**
* @see org.kuali.rice.krad.uif.service.ViewDictionaryService#isMaintainable(java.lang.Class)
*/
public boolean isMaintainable(Class<?> dataObjectClass) {
Map<String, String> indexKey = new HashMap<String, String>();
indexKey.put(UifParameters.VIEW_NAME, UifConstants.DEFAULT_VIEW_NAME);
indexKey.put(UifParameters.DATA_OBJECT_CLASS_NAME, dataObjectClass.getName());
boolean isMaintainable = getDataDictionary().viewByTypeExist(ViewType.MAINTENANCE, indexKey);
return isMaintainable;
}
/**
* @see org.kuali.rice.krad.uif.service.impl.ViewDictionaryService#getResultSetLimitForLookup(java.lang.Class)
*/
@Override
public Integer getResultSetLimitForLookup(Class<?> dataObjectClass) {
LookupView lookupView = null;
List<View> lookupViews = getDataDictionary().getViewsForType(UifConstants.ViewType.LOOKUP);
for (View view : lookupViews) {
LookupView lView = (LookupView) view;
if (StringUtils.equals(lView.getDataObjectClassName().getName(), dataObjectClass.getName())) {
// if we already found a lookup view, only override if this is the default
if (lookupView != null) {
if (StringUtils.equals(lView.getViewName(), UifConstants.DEFAULT_VIEW_NAME)) {
lookupView = lView;
}
} else {
lookupView = lView;
}
}
}
if (lookupView != null) {
return lookupView.getResultSetLimit();
}
return null;
}
protected DataDictionary getDataDictionary() {
return getDataDictionaryService().getDataDictionary();
}
protected DataDictionaryService getDataDictionaryService() {
return this.dataDictionaryService;
}
public void setDataDictionaryService(DataDictionaryService dataDictionaryService) {
this.dataDictionaryService = dataDictionaryService;
}
}
| apache-2.0 |
whamu2/android-learning | AIChat/app/src/test/java/com/whamu2/android/aichat/ExampleUnitTest.java | 403 | package com.whamu2.android.aichat;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} | apache-2.0 |
enriquecs/Currexify-Server | test/es/currexify/server/dao/HistoryDAOImplTest.java | 1896 | package es.currexify.server.dao;
import static org.junit.Assert.*;
import java.util.Date;
import javax.persistence.EntityManager;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig;
import com.google.appengine.tools.development.testing.LocalServiceTestHelper;
import es.currexify.server.model.HistoryModel;
public class HistoryDAOImplTest {
private final LocalServiceTestHelper helper = new LocalServiceTestHelper(
new LocalDatastoreServiceTestConfig());
@Before
public void setUp() throws Exception {
helper.setUp();
}
@After
public void tearDown() throws Exception {
helper.tearDown();
}
@Test
public void testCreateHistory() {
EntityManager em = EMFService.get().createEntityManager();
HistoryDAOImpl hdao = HistoryDAOImpl.getInstance();
HistoryModel hm = new HistoryModel("1234", "EUR", 100, "Entrante", new Date());
HistoryModel hm2 = hdao.createHistory(em, hm);
assertEquals(hm2.getCardN(), "1234");
em.close();
}
@Test
public void testReadHistory() {
EntityManager em = EMFService.get().createEntityManager();
HistoryDAOImpl hdao = HistoryDAOImpl.getInstance();
HistoryModel hm = new HistoryModel("1234", "EUR", 100, "Entrante", new Date());
hdao.createHistory(em, hm);
assertEquals(hdao.readHistory(em).get(0).getCardN(), "1234");
em.close();
}
@Test
public void testUpdateHistory() {
EntityManager em = EMFService.get().createEntityManager();
HistoryDAOImpl hdao = HistoryDAOImpl.getInstance();
HistoryModel hm = new HistoryModel("1234", "EUR", 100, "Entrante", new Date());
hdao.createHistory(em, hm);
hm.setCardN("12345");
hdao.updateHistory(em, hm);
assertEquals(hdao.readHistory(em).get(0).getCardN(), "12345");
em.close();
}
}
| apache-2.0 |
androidx/media | libraries/session/src/main/java/androidx/media3/session/PlayerInfo.java | 34708 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.media3.session;
import static androidx.media3.common.Player.DISCONTINUITY_REASON_AUTO_TRANSITION;
import static androidx.media3.common.Player.MEDIA_ITEM_TRANSITION_REASON_REPEAT;
import static androidx.media3.common.Player.PLAYBACK_SUPPRESSION_REASON_NONE;
import static androidx.media3.common.Player.PLAY_WHEN_READY_CHANGE_REASON_USER_REQUEST;
import static androidx.media3.common.Player.STATE_IDLE;
import static java.lang.annotation.ElementType.TYPE_USE;
import android.os.Bundle;
import android.os.SystemClock;
import androidx.annotation.CheckResult;
import androidx.annotation.FloatRange;
import androidx.annotation.IntDef;
import androidx.annotation.Nullable;
import androidx.media3.common.AudioAttributes;
import androidx.media3.common.Bundleable;
import androidx.media3.common.DeviceInfo;
import androidx.media3.common.MediaItem;
import androidx.media3.common.MediaMetadata;
import androidx.media3.common.PlaybackException;
import androidx.media3.common.PlaybackParameters;
import androidx.media3.common.Player;
import androidx.media3.common.Player.PlaybackSuppressionReason;
import androidx.media3.common.Player.PositionInfo;
import androidx.media3.common.Player.State;
import androidx.media3.common.Timeline;
import androidx.media3.common.Timeline.Window;
import androidx.media3.common.TrackSelectionParameters;
import androidx.media3.common.VideoSize;
import androidx.media3.common.text.Cue;
import androidx.media3.common.util.BundleableUtil;
import com.google.common.collect.ImmutableList;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.List;
/**
* Information about the player that {@link MediaSession} uses to send its state to {@link
* MediaController}.
*/
/* package */ class PlayerInfo implements Bundleable {
public static class Builder {
@Nullable private PlaybackException playerError;
@Player.MediaItemTransitionReason private int mediaItemTransitionReason;
private SessionPositionInfo sessionPositionInfo;
private PositionInfo oldPositionInfo;
private PositionInfo newPositionInfo;
@Player.DiscontinuityReason private int discontinuityReason;
private PlaybackParameters playbackParameters;
@Player.RepeatMode private int repeatMode;
private boolean shuffleModeEnabled;
private Timeline timeline;
private VideoSize videoSize;
private MediaMetadata playlistMetadata;
private float volume;
private AudioAttributes audioAttributes;
private ImmutableList<Cue> cues;
private DeviceInfo deviceInfo;
private int deviceVolume;
private boolean deviceMuted;
private boolean playWhenReady;
@Player.PlayWhenReadyChangeReason private int playWhenReadyChangedReason;
private boolean isPlaying;
private boolean isLoading;
@PlaybackSuppressionReason private int playbackSuppressionReason;
@State private int playbackState;
private MediaMetadata mediaMetadata;
private long seekBackIncrementMs;
private long seekForwardIncrementMs;
private long maxSeekToPreviousPositionMs;
private TrackSelectionParameters trackSelectionParameters;
public Builder(PlayerInfo playerInfo) {
playerError = playerInfo.playerError;
mediaItemTransitionReason = playerInfo.mediaItemTransitionReason;
sessionPositionInfo = playerInfo.sessionPositionInfo;
oldPositionInfo = playerInfo.oldPositionInfo;
newPositionInfo = playerInfo.newPositionInfo;
discontinuityReason = playerInfo.discontinuityReason;
playbackParameters = playerInfo.playbackParameters;
repeatMode = playerInfo.repeatMode;
shuffleModeEnabled = playerInfo.shuffleModeEnabled;
timeline = playerInfo.timeline;
videoSize = playerInfo.videoSize;
playlistMetadata = playerInfo.playlistMetadata;
volume = playerInfo.volume;
audioAttributes = playerInfo.audioAttributes;
cues = ImmutableList.copyOf(playerInfo.cues);
deviceInfo = playerInfo.deviceInfo;
deviceVolume = playerInfo.deviceVolume;
deviceMuted = playerInfo.deviceMuted;
playWhenReady = playerInfo.playWhenReady;
playWhenReadyChangedReason = playerInfo.playWhenReadyChangedReason;
isPlaying = playerInfo.isPlaying;
isLoading = playerInfo.isLoading;
playbackSuppressionReason = playerInfo.playbackSuppressionReason;
playbackState = playerInfo.playbackState;
mediaMetadata = playerInfo.mediaMetadata;
seekBackIncrementMs = playerInfo.seekBackIncrementMs;
seekForwardIncrementMs = playerInfo.seekForwardIncrementMs;
maxSeekToPreviousPositionMs = playerInfo.maxSeekToPreviousPositionMs;
trackSelectionParameters = playerInfo.trackSelectionParameters;
}
public Builder setPlayerError(@Nullable PlaybackException playerError) {
this.playerError = playerError;
return this;
}
public Builder setMediaItemTransitionReason(
@Player.MediaItemTransitionReason int mediaItemTransitionReason) {
this.mediaItemTransitionReason = mediaItemTransitionReason;
return this;
}
public Builder setSessionPositionInfo(SessionPositionInfo sessionPositionInfo) {
this.sessionPositionInfo = sessionPositionInfo;
return this;
}
public Builder setOldPositionInfo(PositionInfo oldPositionInfo) {
this.oldPositionInfo = oldPositionInfo;
return this;
}
public Builder setNewPositionInfo(PositionInfo newPositionInfo) {
this.newPositionInfo = newPositionInfo;
return this;
}
public Builder setDiscontinuityReason(@Player.DiscontinuityReason int discontinuityReason) {
this.discontinuityReason = discontinuityReason;
return this;
}
public Builder setPlaybackParameters(PlaybackParameters playbackParameters) {
this.playbackParameters = playbackParameters;
return this;
}
public Builder setRepeatMode(@Player.RepeatMode int repeatMode) {
this.repeatMode = repeatMode;
return this;
}
public Builder setShuffleModeEnabled(boolean shuffleModeEnabled) {
this.shuffleModeEnabled = shuffleModeEnabled;
return this;
}
public Builder setTimeline(Timeline timeline) {
this.timeline = timeline;
return this;
}
public Builder setVideoSize(VideoSize videoSize) {
this.videoSize = videoSize;
return this;
}
public Builder setPlaylistMetadata(MediaMetadata playlistMetadata) {
this.playlistMetadata = playlistMetadata;
return this;
}
public Builder setVolume(@FloatRange(from = 0, to = 1) float volume) {
this.volume = volume;
return this;
}
public Builder setAudioAttributes(AudioAttributes audioAttributes) {
this.audioAttributes = audioAttributes;
return this;
}
public Builder setCues(List<Cue> cues) {
this.cues = ImmutableList.copyOf(cues);
return this;
}
public Builder setDeviceInfo(DeviceInfo deviceInfo) {
this.deviceInfo = deviceInfo;
return this;
}
public Builder setDeviceVolume(int deviceVolume) {
this.deviceVolume = deviceVolume;
return this;
}
public Builder setDeviceMuted(boolean deviceMuted) {
this.deviceMuted = deviceMuted;
return this;
}
public Builder setPlayWhenReady(boolean playWhenReady) {
this.playWhenReady = playWhenReady;
return this;
}
public Builder setPlayWhenReadyChangedReason(
@Player.PlayWhenReadyChangeReason int playWhenReadyChangedReason) {
this.playWhenReadyChangedReason = playWhenReadyChangedReason;
return this;
}
public Builder setIsPlaying(boolean isPlaying) {
this.isPlaying = isPlaying;
return this;
}
public Builder setIsLoading(boolean isLoading) {
this.isLoading = isLoading;
return this;
}
public Builder setPlaybackSuppressionReason(
@PlaybackSuppressionReason int playbackSuppressionReason) {
this.playbackSuppressionReason = playbackSuppressionReason;
return this;
}
public Builder setPlaybackState(@State int playbackState) {
this.playbackState = playbackState;
return this;
}
public Builder setMediaMetadata(MediaMetadata mediaMetadata) {
this.mediaMetadata = mediaMetadata;
return this;
}
public Builder setSeekBackIncrement(long seekBackIncrementMs) {
this.seekBackIncrementMs = seekBackIncrementMs;
return this;
}
public Builder setSeekForwardIncrement(long seekForwardIncrementMs) {
this.seekForwardIncrementMs = seekForwardIncrementMs;
return this;
}
public Builder setMaxSeekToPreviousPositionMs(long maxSeekToPreviousPositionMs) {
this.maxSeekToPreviousPositionMs = maxSeekToPreviousPositionMs;
return this;
}
public Builder setTrackSelectionParameters(TrackSelectionParameters parameters) {
trackSelectionParameters = parameters;
return this;
}
public PlayerInfo build() {
return new PlayerInfo(
playerError,
mediaItemTransitionReason,
sessionPositionInfo,
oldPositionInfo,
newPositionInfo,
discontinuityReason,
playbackParameters,
repeatMode,
shuffleModeEnabled,
videoSize,
timeline,
playlistMetadata,
volume,
audioAttributes,
cues,
deviceInfo,
deviceVolume,
deviceMuted,
playWhenReady,
playWhenReadyChangedReason,
playbackSuppressionReason,
playbackState,
isPlaying,
isLoading,
mediaMetadata,
seekBackIncrementMs,
seekForwardIncrementMs,
maxSeekToPreviousPositionMs,
trackSelectionParameters);
}
}
/** Default media item transition reason. */
public static final int MEDIA_ITEM_TRANSITION_REASON_DEFAULT =
MEDIA_ITEM_TRANSITION_REASON_REPEAT;
/** Default discontinuity reason. */
public static final int DISCONTINUITY_REASON_DEFAULT = DISCONTINUITY_REASON_AUTO_TRANSITION;
/** Default play when ready change reason. */
public static final int PLAY_WHEN_READY_CHANGE_REASON_DEFAULT =
PLAY_WHEN_READY_CHANGE_REASON_USER_REQUEST;
public static final PlayerInfo DEFAULT =
new PlayerInfo(
/* playerError= */ null,
MEDIA_ITEM_TRANSITION_REASON_DEFAULT,
SessionPositionInfo.DEFAULT,
/* oldPositionInfo= */ SessionPositionInfo.DEFAULT_POSITION_INFO,
/* newPositionInfo= */ SessionPositionInfo.DEFAULT_POSITION_INFO,
DISCONTINUITY_REASON_DEFAULT,
PlaybackParameters.DEFAULT,
Player.REPEAT_MODE_OFF,
/* shuffleModeEnabled= */ false,
VideoSize.UNKNOWN,
Timeline.EMPTY,
MediaMetadata.EMPTY,
/* volume= */ 1f,
AudioAttributes.DEFAULT,
/* cues = */ ImmutableList.of(),
DeviceInfo.UNKNOWN,
/* deviceVolume= */ 0,
/* deviceMuted= */ false,
/* playWhenReady = */ false,
PLAY_WHEN_READY_CHANGE_REASON_USER_REQUEST,
PLAYBACK_SUPPRESSION_REASON_NONE,
STATE_IDLE,
/* isPlaying= */ false,
/* isLoading= */ false,
MediaMetadata.EMPTY,
/* seekBackIncrementMs= */ 0,
/* seekForwardIncrementMs= */ 0,
/* maxSeekToPreviousPosition= */ 0,
TrackSelectionParameters.DEFAULT_WITHOUT_CONTEXT);
@Nullable public final PlaybackException playerError;
@Player.MediaItemTransitionReason public final int mediaItemTransitionReason;
public final SessionPositionInfo sessionPositionInfo;
public final PositionInfo oldPositionInfo;
public final PositionInfo newPositionInfo;
@Player.DiscontinuityReason public final int discontinuityReason;
public final PlaybackParameters playbackParameters;
@Player.RepeatMode public final int repeatMode;
public final boolean shuffleModeEnabled;
public final Timeline timeline;
public final VideoSize videoSize;
public final MediaMetadata playlistMetadata;
public final float volume;
public final AudioAttributes audioAttributes;
public final List<Cue> cues;
public final DeviceInfo deviceInfo;
public final int deviceVolume;
public final boolean deviceMuted;
public final boolean playWhenReady;
public final int playWhenReadyChangedReason;
public final boolean isPlaying;
public final boolean isLoading;
@Player.PlaybackSuppressionReason public final int playbackSuppressionReason;
@Player.State public final int playbackState;
public final MediaMetadata mediaMetadata;
public final long seekBackIncrementMs;
public final long seekForwardIncrementMs;
public final long maxSeekToPreviousPositionMs;
public final TrackSelectionParameters trackSelectionParameters;
@CheckResult
public PlayerInfo copyWithPlayWhenReady(
boolean playWhenReady,
@Player.PlayWhenReadyChangeReason int playWhenReadyChangedReason,
@Player.PlaybackSuppressionReason int playbackSuppressionReason) {
return new Builder(this)
.setPlayWhenReady(playWhenReady)
.setPlayWhenReadyChangedReason(playWhenReadyChangedReason)
.setPlaybackSuppressionReason(playbackSuppressionReason)
.setIsPlaying(isPlaying(playbackState, playWhenReady, playbackSuppressionReason))
.build();
}
@CheckResult
public PlayerInfo copyWithMediaItemTransitionReason(
@Player.MediaItemTransitionReason int mediaItemTransitionReason) {
return new Builder(this).setMediaItemTransitionReason(mediaItemTransitionReason).build();
}
@CheckResult
public PlayerInfo copyWithPlayerError(PlaybackException playerError) {
return new Builder(this).setPlayerError(playerError).build();
}
@CheckResult
public PlayerInfo copyWithSessionPositionInfo(SessionPositionInfo sessionPositionInfo) {
return new Builder(this).setSessionPositionInfo(sessionPositionInfo).build();
}
@CheckResult
public PlayerInfo copyWithPlaybackState(
@Player.State int playbackState, @Nullable PlaybackException playerError) {
return new Builder(this)
.setPlayerError(playerError)
.setPlaybackState(playbackState)
.setIsPlaying(isPlaying(playbackState, playWhenReady, playbackSuppressionReason))
.build();
}
@CheckResult
public PlayerInfo copyWithIsPlaying(boolean isPlaying) {
return new Builder(this).setIsPlaying(isPlaying).build();
}
@CheckResult
public PlayerInfo copyWithIsLoading(boolean isLoading) {
return new Builder(this).setIsLoading(isLoading).build();
}
@CheckResult
public PlayerInfo copyWithPositionInfos(
PositionInfo oldPositionInfo,
PositionInfo newPositionInfo,
@Player.DiscontinuityReason int discontinuityReason) {
return new Builder(this)
.setOldPositionInfo(oldPositionInfo)
.setNewPositionInfo(newPositionInfo)
.setDiscontinuityReason(discontinuityReason)
.build();
}
@CheckResult
public PlayerInfo copyWithPlaybackParameters(PlaybackParameters playbackParameters) {
return new Builder(this).setPlaybackParameters(playbackParameters).build();
}
@CheckResult
public PlayerInfo copyWithTimeline(Timeline timeline) {
return new Builder(this).setTimeline(timeline).build();
}
@CheckResult
public PlayerInfo copyWithTimeline(Timeline timeline, int windowIndex) {
return new Builder(this)
.setTimeline(timeline)
.setSessionPositionInfo(
new SessionPositionInfo(
new PositionInfo(
sessionPositionInfo.positionInfo.windowUid,
windowIndex,
sessionPositionInfo.positionInfo.mediaItem,
sessionPositionInfo.positionInfo.periodUid,
sessionPositionInfo.positionInfo.periodIndex,
sessionPositionInfo.positionInfo.positionMs,
sessionPositionInfo.positionInfo.contentPositionMs,
sessionPositionInfo.positionInfo.adGroupIndex,
sessionPositionInfo.positionInfo.adIndexInAdGroup),
sessionPositionInfo.isPlayingAd,
/* eventTimeMs= */ SystemClock.elapsedRealtime(),
sessionPositionInfo.durationMs,
sessionPositionInfo.bufferedPositionMs,
sessionPositionInfo.bufferedPercentage,
sessionPositionInfo.totalBufferedDurationMs,
sessionPositionInfo.currentLiveOffsetMs,
sessionPositionInfo.contentDurationMs,
sessionPositionInfo.contentBufferedPositionMs))
.build();
}
@CheckResult
public PlayerInfo copyWithPlaylistMetadata(MediaMetadata playlistMetadata) {
return new Builder(this).setPlaylistMetadata(playlistMetadata).build();
}
@CheckResult
public PlayerInfo copyWithRepeatMode(@Player.RepeatMode int repeatMode) {
return new Builder(this).setRepeatMode(repeatMode).build();
}
@CheckResult
public PlayerInfo copyWithShuffleModeEnabled(boolean shuffleModeEnabled) {
return new Builder(this).setShuffleModeEnabled(shuffleModeEnabled).build();
}
@CheckResult
public PlayerInfo copyWithAudioAttributes(AudioAttributes audioAttributes) {
return new Builder(this).setAudioAttributes(audioAttributes).build();
}
@CheckResult
public PlayerInfo copyWithVideoSize(VideoSize videoSize) {
return new Builder(this).setVideoSize(videoSize).build();
}
@CheckResult
public PlayerInfo copyWithVolume(@FloatRange(from = 0, to = 1) float volume) {
return new Builder(this).setVolume(volume).build();
}
@CheckResult
public PlayerInfo copyWithDeviceInfo(DeviceInfo deviceInfo) {
return new Builder(this).setDeviceInfo(deviceInfo).build();
}
@CheckResult
public PlayerInfo copyWithDeviceVolume(int deviceVolume, boolean deviceMuted) {
return new Builder(this).setDeviceVolume(deviceVolume).setDeviceMuted(deviceMuted).build();
}
@CheckResult
public PlayerInfo copyWithMediaMetadata(MediaMetadata mediaMetadata) {
return new Builder(this).setMediaMetadata(mediaMetadata).build();
}
@CheckResult
public PlayerInfo copyWithSeekBackIncrement(long seekBackIncrementMs) {
return new Builder(this).setSeekBackIncrement(seekBackIncrementMs).build();
}
@CheckResult
public PlayerInfo copyWithSeekForwardIncrement(long seekForwardIncrementMs) {
return new Builder(this).setSeekForwardIncrement(seekForwardIncrementMs).build();
}
@CheckResult
public PlayerInfo copyWithMaxSeekToPreviousPositionMs(long maxSeekToPreviousPositionMs) {
return new Builder(this).setMaxSeekToPreviousPositionMs(maxSeekToPreviousPositionMs).build();
}
@CheckResult
public PlayerInfo copyWithTrackSelectionParameters(TrackSelectionParameters parameters) {
return new Builder(this).setTrackSelectionParameters(parameters).build();
}
public PlayerInfo(
@Nullable PlaybackException playerError,
@Player.MediaItemTransitionReason int mediaItemTransitionReason,
SessionPositionInfo sessionPositionInfo,
PositionInfo oldPositionInfo,
PositionInfo newPositionInfo,
@Player.DiscontinuityReason int discontinuityReason,
PlaybackParameters playbackParameters,
@Player.RepeatMode int repeatMode,
boolean shuffleModeEnabled,
VideoSize videoSize,
Timeline timeline,
MediaMetadata playlistMetadata,
float volume,
AudioAttributes audioAttributes,
List<Cue> cues,
DeviceInfo deviceInfo,
int deviceVolume,
boolean deviceMuted,
boolean playWhenReady,
@Player.PlayWhenReadyChangeReason int playWhenReadyChangedReason,
@Player.PlaybackSuppressionReason int playbackSuppressionReason,
@Player.State int playbackState,
boolean isPlaying,
boolean isLoading,
MediaMetadata mediaMetadata,
long seekBackIncrementMs,
long seekForwardIncrementMs,
long maxSeekToPreviousPositionMs,
TrackSelectionParameters parameters) {
this.playerError = playerError;
this.mediaItemTransitionReason = mediaItemTransitionReason;
this.sessionPositionInfo = sessionPositionInfo;
this.oldPositionInfo = oldPositionInfo;
this.newPositionInfo = newPositionInfo;
this.discontinuityReason = discontinuityReason;
this.playbackParameters = playbackParameters;
this.repeatMode = repeatMode;
this.shuffleModeEnabled = shuffleModeEnabled;
this.videoSize = videoSize;
this.timeline = timeline;
this.playlistMetadata = playlistMetadata;
this.volume = volume;
this.audioAttributes = audioAttributes;
this.cues = cues;
this.deviceInfo = deviceInfo;
this.deviceVolume = deviceVolume;
this.deviceMuted = deviceMuted;
this.playWhenReady = playWhenReady;
this.playWhenReadyChangedReason = playWhenReadyChangedReason;
this.playbackSuppressionReason = playbackSuppressionReason;
this.playbackState = playbackState;
this.isPlaying = isPlaying;
this.isLoading = isLoading;
this.mediaMetadata = mediaMetadata;
this.seekBackIncrementMs = seekBackIncrementMs;
this.seekForwardIncrementMs = seekForwardIncrementMs;
this.maxSeekToPreviousPositionMs = maxSeekToPreviousPositionMs;
this.trackSelectionParameters = parameters;
}
@Nullable
public MediaItem getCurrentMediaItem() {
return timeline.isEmpty()
? null
: timeline.getWindow(sessionPositionInfo.positionInfo.mediaItemIndex, new Window())
.mediaItem;
}
private boolean isPlaying(
@State int playbackState,
boolean playWhenReady,
@PlaybackSuppressionReason int playbackSuppressionReason) {
return playbackState == Player.STATE_READY
&& playWhenReady
&& playbackSuppressionReason == PLAYBACK_SUPPRESSION_REASON_NONE;
}
// Bundleable implementation.
@Documented
@Retention(RetentionPolicy.SOURCE)
@Target(TYPE_USE)
@IntDef({
FIELD_PLAYBACK_PARAMETERS,
FIELD_REPEAT_MODE,
FIELD_SHUFFLE_MODE_ENABLED,
FIELD_TIMELINE,
FIELD_VIDEO_SIZE,
FIELD_PLAYLIST_METADATA,
FIELD_VOLUME,
FIELD_AUDIO_ATTRIBUTES,
FIELD_DEVICE_INFO,
FIELD_DEVICE_VOLUME,
FIELD_DEVICE_MUTED,
FIELD_PLAY_WHEN_READY,
FIELD_PLAY_WHEN_READY_CHANGED_REASON,
FIELD_PLAYBACK_SUPPRESSION_REASON,
FIELD_PLAYBACK_STATE,
FIELD_IS_PLAYING,
FIELD_IS_LOADING,
FIELD_PLAYBACK_ERROR,
FIELD_SESSION_POSITION_INFO,
FIELD_MEDIA_ITEM_TRANSITION_REASON,
FIELD_OLD_POSITION_INFO,
FIELD_NEW_POSITION_INFO,
FIELD_DISCONTINUITY_REASON,
FIELD_CUES,
FIELD_MEDIA_METADATA,
FIELD_SEEK_BACK_INCREMENT_MS,
FIELD_SEEK_FORWARD_INCREMENT_MS,
FIELD_MAX_SEEK_TO_PREVIOUS_POSITION_MS,
FIELD_TRACK_SELECTION_PARAMETERS,
})
private @interface FieldNumber {}
private static final int FIELD_PLAYBACK_PARAMETERS = 1;
private static final int FIELD_REPEAT_MODE = 2;
private static final int FIELD_SHUFFLE_MODE_ENABLED = 3;
private static final int FIELD_TIMELINE = 4;
private static final int FIELD_VIDEO_SIZE = 5;
private static final int FIELD_PLAYLIST_METADATA = 6;
private static final int FIELD_VOLUME = 7;
private static final int FIELD_AUDIO_ATTRIBUTES = 8;
private static final int FIELD_DEVICE_INFO = 9;
private static final int FIELD_DEVICE_VOLUME = 10;
private static final int FIELD_DEVICE_MUTED = 11;
private static final int FIELD_PLAY_WHEN_READY = 12;
private static final int FIELD_PLAY_WHEN_READY_CHANGED_REASON = 13;
private static final int FIELD_PLAYBACK_SUPPRESSION_REASON = 14;
private static final int FIELD_PLAYBACK_STATE = 15;
private static final int FIELD_IS_PLAYING = 16;
private static final int FIELD_IS_LOADING = 17;
private static final int FIELD_PLAYBACK_ERROR = 18;
private static final int FIELD_SESSION_POSITION_INFO = 19;
private static final int FIELD_MEDIA_ITEM_TRANSITION_REASON = 20;
private static final int FIELD_OLD_POSITION_INFO = 21;
private static final int FIELD_NEW_POSITION_INFO = 22;
private static final int FIELD_DISCONTINUITY_REASON = 23;
private static final int FIELD_CUES = 24;
private static final int FIELD_MEDIA_METADATA = 25;
private static final int FIELD_SEEK_BACK_INCREMENT_MS = 26;
private static final int FIELD_SEEK_FORWARD_INCREMENT_MS = 27;
private static final int FIELD_MAX_SEEK_TO_PREVIOUS_POSITION_MS = 28;
private static final int FIELD_TRACK_SELECTION_PARAMETERS = 29;
// Next field key = 30
public Bundle toBundle(
boolean excludeMediaItems,
boolean excludeMediaItemsMetadata,
boolean excludeCues,
boolean excludeTimeline) {
Bundle bundle = new Bundle();
bundle.putBundle(
keyForField(FIELD_PLAYBACK_ERROR), BundleableUtil.toNullableBundle(playerError));
bundle.putInt(keyForField(FIELD_MEDIA_ITEM_TRANSITION_REASON), mediaItemTransitionReason);
bundle.putBundle(keyForField(FIELD_SESSION_POSITION_INFO), sessionPositionInfo.toBundle());
bundle.putBundle(
keyForField(FIELD_OLD_POSITION_INFO), BundleableUtil.toNullableBundle(oldPositionInfo));
bundle.putBundle(
keyForField(FIELD_NEW_POSITION_INFO), BundleableUtil.toNullableBundle(newPositionInfo));
bundle.putInt(keyForField(FIELD_DISCONTINUITY_REASON), discontinuityReason);
bundle.putBundle(keyForField(FIELD_PLAYBACK_PARAMETERS), playbackParameters.toBundle());
bundle.putInt(keyForField(FIELD_REPEAT_MODE), repeatMode);
bundle.putBoolean(keyForField(FIELD_SHUFFLE_MODE_ENABLED), shuffleModeEnabled);
if (!excludeTimeline) {
bundle.putBundle(keyForField(FIELD_TIMELINE), timeline.toBundle(excludeMediaItems));
}
bundle.putBundle(keyForField(FIELD_VIDEO_SIZE), videoSize.toBundle());
bundle.putBundle(
keyForField(FIELD_PLAYLIST_METADATA),
excludeMediaItemsMetadata
? MediaMetadata.EMPTY.toBundle()
: BundleableUtil.toNullableBundle(playlistMetadata));
bundle.putFloat(keyForField(FIELD_VOLUME), volume);
bundle.putBundle(keyForField(FIELD_AUDIO_ATTRIBUTES), audioAttributes.toBundle());
if (!excludeCues) {
bundle.putParcelableArrayList(
keyForField(FIELD_CUES),
BundleableUtil.toBundleArrayList(MediaUtils.filterOutBitmapCues(cues)));
}
bundle.putBundle(keyForField(FIELD_DEVICE_INFO), deviceInfo.toBundle());
bundle.putInt(keyForField(FIELD_DEVICE_VOLUME), deviceVolume);
bundle.putBoolean(keyForField(FIELD_DEVICE_MUTED), deviceMuted);
bundle.putBoolean(keyForField(FIELD_PLAY_WHEN_READY), playWhenReady);
bundle.putInt(keyForField(FIELD_PLAYBACK_SUPPRESSION_REASON), playbackSuppressionReason);
bundle.putInt(keyForField(FIELD_PLAYBACK_STATE), playbackState);
bundle.putBoolean(keyForField(FIELD_IS_PLAYING), isPlaying);
bundle.putBoolean(keyForField(FIELD_IS_LOADING), isLoading);
bundle.putBundle(
keyForField(FIELD_MEDIA_METADATA),
excludeMediaItems ? MediaMetadata.EMPTY.toBundle() : mediaMetadata.toBundle());
bundle.putLong(keyForField(FIELD_SEEK_BACK_INCREMENT_MS), seekBackIncrementMs);
bundle.putLong(keyForField(FIELD_SEEK_FORWARD_INCREMENT_MS), seekForwardIncrementMs);
bundle.putLong(
keyForField(FIELD_MAX_SEEK_TO_PREVIOUS_POSITION_MS), maxSeekToPreviousPositionMs);
bundle.putBundle(
keyForField(FIELD_TRACK_SELECTION_PARAMETERS), trackSelectionParameters.toBundle());
return bundle;
}
@Override
public Bundle toBundle() {
return toBundle(
/* excludeMediaItems= */ false,
/* excludeMediaItemsMetadata= */ false,
/* excludeCues= */ false,
/* excludeTimeline= */ false);
}
/** Object that can restore {@link PlayerInfo} from a {@link Bundle}. */
public static final Creator<PlayerInfo> CREATOR = PlayerInfo::fromBundle;
private static PlayerInfo fromBundle(Bundle bundle) {
@Nullable
PlaybackException playerError =
BundleableUtil.fromNullableBundle(
PlaybackException.CREATOR, bundle.getBundle(keyForField(FIELD_PLAYBACK_ERROR)));
int mediaItemTransitionReason =
bundle.getInt(
keyForField(FIELD_MEDIA_ITEM_TRANSITION_REASON), MEDIA_ITEM_TRANSITION_REASON_REPEAT);
SessionPositionInfo sessionPositionInfo =
BundleableUtil.fromNullableBundle(
SessionPositionInfo.CREATOR,
bundle.getBundle(keyForField(FIELD_SESSION_POSITION_INFO)),
SessionPositionInfo.DEFAULT);
PositionInfo oldPositionInfo =
BundleableUtil.fromNullableBundle(
PositionInfo.CREATOR,
bundle.getBundle(keyForField(FIELD_OLD_POSITION_INFO)),
SessionPositionInfo.DEFAULT_POSITION_INFO);
PositionInfo newPositionInfo =
BundleableUtil.fromNullableBundle(
PositionInfo.CREATOR,
bundle.getBundle(keyForField(FIELD_NEW_POSITION_INFO)),
SessionPositionInfo.DEFAULT_POSITION_INFO);
int discontinuityReason =
bundle.getInt(
keyForField(FIELD_DISCONTINUITY_REASON), DISCONTINUITY_REASON_AUTO_TRANSITION);
@Nullable
Bundle playbackParametersBundle = bundle.getBundle(keyForField(FIELD_PLAYBACK_PARAMETERS));
PlaybackParameters playbackParameters =
BundleableUtil.fromNullableBundle(
PlaybackParameters.CREATOR,
playbackParametersBundle,
/* defaultValue= */ PlaybackParameters.DEFAULT);
@Player.RepeatMode
int repeatMode =
bundle.getInt(keyForField(FIELD_REPEAT_MODE), /* defaultValue= */ Player.REPEAT_MODE_OFF);
boolean shuffleModeEnabled =
bundle.getBoolean(keyForField(FIELD_SHUFFLE_MODE_ENABLED), /* defaultValue= */ false);
Timeline timeline =
BundleableUtil.fromNullableBundle(
Timeline.CREATOR, bundle.getBundle(keyForField(FIELD_TIMELINE)), Timeline.EMPTY);
VideoSize videoSize =
BundleableUtil.fromNullableBundle(
VideoSize.CREATOR, bundle.getBundle(keyForField(FIELD_VIDEO_SIZE)), VideoSize.UNKNOWN);
MediaMetadata playlistMetadata =
BundleableUtil.fromNullableBundle(
MediaMetadata.CREATOR,
bundle.getBundle(keyForField(FIELD_PLAYLIST_METADATA)),
MediaMetadata.EMPTY);
float volume = bundle.getFloat(keyForField(FIELD_VOLUME), /* defaultValue= */ 1);
AudioAttributes audioAttributes =
BundleableUtil.fromNullableBundle(
AudioAttributes.CREATOR,
bundle.getBundle(keyForField(FIELD_AUDIO_ATTRIBUTES)),
/* defaultValue= */ AudioAttributes.DEFAULT);
List<Cue> cues =
BundleableUtil.fromBundleNullableList(
Cue.CREATOR,
bundle.getParcelableArrayList(keyForField(FIELD_CUES)),
/* defaultValue= */ ImmutableList.of());
@Nullable Bundle deviceInfoBundle = bundle.getBundle(keyForField(FIELD_DEVICE_INFO));
DeviceInfo deviceInfo =
BundleableUtil.fromNullableBundle(
DeviceInfo.CREATOR, deviceInfoBundle, /* defaultValue= */ DeviceInfo.UNKNOWN);
int deviceVolume = bundle.getInt(keyForField(FIELD_DEVICE_VOLUME), /* defaultValue= */ 0);
boolean deviceMuted =
bundle.getBoolean(keyForField(FIELD_DEVICE_MUTED), /* defaultValue= */ false);
boolean playWhenReady =
bundle.getBoolean(keyForField(FIELD_PLAY_WHEN_READY), /* defaultValue= */ false);
int playWhenReadyChangedReason =
bundle.getInt(
keyForField(FIELD_PLAY_WHEN_READY_CHANGED_REASON),
/* defaultValue= */ PLAY_WHEN_READY_CHANGE_REASON_USER_REQUEST);
@Player.PlaybackSuppressionReason
int playbackSuppressionReason =
bundle.getInt(
keyForField(FIELD_PLAYBACK_SUPPRESSION_REASON),
/* defaultValue= */ PLAYBACK_SUPPRESSION_REASON_NONE);
@Player.State
int playbackState =
bundle.getInt(keyForField(FIELD_PLAYBACK_STATE), /* defaultValue= */ STATE_IDLE);
boolean isPlaying = bundle.getBoolean(keyForField(FIELD_IS_PLAYING), /* defaultValue= */ false);
boolean isLoading = bundle.getBoolean(keyForField(FIELD_IS_LOADING), /* defaultValue= */ false);
MediaMetadata mediaMetadata =
BundleableUtil.fromNullableBundle(
MediaMetadata.CREATOR,
bundle.getBundle(keyForField(FIELD_MEDIA_METADATA)),
MediaMetadata.EMPTY);
long seekBackIncrementMs =
bundle.getLong(keyForField(FIELD_SEEK_BACK_INCREMENT_MS), /* defaultValue= */ 0);
long seekForwardIncrementMs =
bundle.getLong(keyForField(FIELD_SEEK_FORWARD_INCREMENT_MS), /* defaultValue= */ 0);
long maxSeekToPreviousPosition =
bundle.getLong(keyForField(FIELD_MAX_SEEK_TO_PREVIOUS_POSITION_MS), /* defaultValue= */ 0);
TrackSelectionParameters trackSelectionParameters =
BundleableUtil.fromNullableBundle(
TrackSelectionParameters.CREATOR,
bundle.getBundle(keyForField(FIELD_TRACK_SELECTION_PARAMETERS)),
TrackSelectionParameters.DEFAULT_WITHOUT_CONTEXT);
return new PlayerInfo(
playerError,
mediaItemTransitionReason,
sessionPositionInfo,
oldPositionInfo,
newPositionInfo,
discontinuityReason,
playbackParameters,
repeatMode,
shuffleModeEnabled,
videoSize,
timeline,
playlistMetadata,
volume,
audioAttributes,
cues,
deviceInfo,
deviceVolume,
deviceMuted,
playWhenReady,
playWhenReadyChangedReason,
playbackSuppressionReason,
playbackState,
isPlaying,
isLoading,
mediaMetadata,
seekBackIncrementMs,
seekForwardIncrementMs,
maxSeekToPreviousPosition,
trackSelectionParameters);
}
private static String keyForField(@FieldNumber int field) {
return Integer.toString(field, Character.MAX_RADIX);
}
}
| apache-2.0 |
FrankHossfeld/Training | GWT-Grundlagen-Maven/module0802/src/main/java/de/gishmo/gwt/example/module0802/client/ui/navigation/INavigationView.java | 364 | package de.gishmo.gwt.example.module0802.client.ui.navigation;
import com.google.gwt.user.client.ui.IsWidget;
import de.gishmo.gwt.example.module0802.client.widgets.ReverseView;
public interface INavigationView
extends ReverseView<INavigationView.Presenter>,
IsWidget {
public interface Presenter {
void doSetCenter(String newCenter);
}
}
| apache-2.0 |
v7lin/Android_Skin_3.x | Library/LibEnvUI/src/main/java/com/v7lin/android/env/impl/NullEnvSetup.java | 628 | package com.v7lin.android.env.impl;
import android.content.Context;
import com.v7lin.android.env.EnvSetup;
/**
* @author v7lin E-mail:v7lin@qq.com
*/
public class NullEnvSetup implements EnvSetup {
private NullEnvSetup() {
super();
}
@Override
public String getSkinPath(Context context) {
return "";
}
@Override
public String getFontPath(Context context) {
return "";
}
private static class NullEnvSetupHolder {
private static final NullEnvSetup INSTANCE = new NullEnvSetup();
}
public static NullEnvSetup getInstance() {
return NullEnvSetupHolder.INSTANCE;
}
}
| apache-2.0 |
mhmdfy/autopsy | Core/src/org/sleuthkit/autopsy/modules/iOS/TextMessageAnalyzer.java | 7712 | /*
* Autopsy Forensic Browser
*
* Copyright 2014 Basis Technology Corp.
* Contact: carrier <at> sleuthkit <dot> org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sleuthkit.autopsy.modules.iOS;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.logging.Level;
import org.openide.util.NbBundle;
import org.sleuthkit.autopsy.casemodule.Case;
import org.sleuthkit.autopsy.casemodule.services.Blackboard;
import org.sleuthkit.autopsy.coreutils.Logger;
import org.sleuthkit.autopsy.coreutils.MessageNotifyUtil;
import org.sleuthkit.autopsy.datamodel.ContentUtils;
import org.sleuthkit.datamodel.AbstractFile;
import org.sleuthkit.datamodel.BlackboardArtifact;
import org.sleuthkit.datamodel.BlackboardAttribute;
import org.sleuthkit.datamodel.SleuthkitCase;
import org.sleuthkit.datamodel.TskCoreException;
class TextMessageAnalyzer {
private Connection connection = null;
private ResultSet resultSet = null;
private Statement statement = null;
private String dbPath = "";
private long fileId = 0;
private java.io.File jFile = null;
List<AbstractFile> absFiles;
private String moduleName = iOSModuleFactory.getModuleName();
private static final Logger logger = Logger.getLogger(TextMessageAnalyzer.class.getName());
private Blackboard blackboard;
void findTexts() {
blackboard = Case.getCurrentCase().getServices().getBlackboard();
try {
SleuthkitCase skCase = Case.getCurrentCase().getSleuthkitCase();
absFiles = skCase.findAllFilesWhere("name ='mmssms.db'"); //NON-NLS //get exact file name
if (absFiles.isEmpty()) {
return;
}
for (AbstractFile AF : absFiles) {
try {
jFile = new java.io.File(Case.getCurrentCase().getTempDirectory(), AF.getName().replaceAll("[<>%|\"/:*\\\\]", ""));
ContentUtils.writeToFile(AF, jFile);
dbPath = jFile.toString(); //path of file as string
fileId = AF.getId();
findTextsInDB(dbPath, fileId);
} catch (Exception e) {
logger.log(Level.SEVERE, "Error parsing text messages", e); //NON-NLS
}
}
} catch (TskCoreException e) {
logger.log(Level.SEVERE, "Error finding text messages", e); //NON-NLS
}
}
private void findTextsInDB(String DatabasePath, long fId) {
if (DatabasePath == null || DatabasePath.isEmpty()) {
return;
}
try {
Class.forName("org.sqlite.JDBC"); //NON-NLS //load JDBC driver
connection = DriverManager.getConnection("jdbc:sqlite:" + DatabasePath); //NON-NLS
statement = connection.createStatement();
} catch (ClassNotFoundException | SQLException e) {
logger.log(Level.SEVERE, "Error opening database", e); //NON-NLS
}
Case currentCase = Case.getCurrentCase();
SleuthkitCase skCase = currentCase.getSleuthkitCase();
try {
AbstractFile f = skCase.getAbstractFileById(fId);
if (f == null) {
logger.log(Level.SEVERE, "Error getting abstract file " + fId); //NON-NLS
return;
}
try {
resultSet = statement.executeQuery(
"SELECT address,date,type,subject,body FROM sms;"); //NON-NLS
BlackboardArtifact bba;
String address; // may be phone number, or other addresses
String date;//unix time
String type; // message received in inbox = 1, message sent = 2
String subject;//message subject
String body; //message body
while (resultSet.next()) {
address = resultSet.getString("address"); //NON-NLS
date = resultSet.getString("date"); //NON-NLS
type = resultSet.getString("type"); //NON-NLS
subject = resultSet.getString("subject"); //NON-NLS
body = resultSet.getString("body"); //NON-NLS
bba = f.newArtifact(BlackboardArtifact.ARTIFACT_TYPE.TSK_MESSAGE); //create Message artifact and then add attributes from result set.
// @@@ NEed to put into more specific TO or FROM
if (type.equals("1")) {
bba.addAttribute(new BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_DIRECTION.getTypeID(), moduleName, "Incoming"));
bba.addAttribute(new BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_PHONE_NUMBER_FROM.getTypeID(), moduleName, address));
} else {
bba.addAttribute(new BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_DIRECTION.getTypeID(), moduleName, "Outgoing"));
bba.addAttribute(new BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_PHONE_NUMBER_TO.getTypeID(), moduleName, address));
}
bba.addAttribute(new BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_DATETIME.getTypeID(), moduleName, date));
bba.addAttribute(new BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_DIRECTION.getTypeID(), moduleName, type));
bba.addAttribute(new BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_SUBJECT.getTypeID(), moduleName, subject));
bba.addAttribute(new BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_TEXT.getTypeID(), moduleName, body));
bba.addAttribute(new BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_MESSAGE_TYPE.getTypeID(), moduleName, "SMS Message"));
try {
// index the artifact for keyword search
blackboard.indexArtifact(bba);
} catch (Blackboard.BlackboardException ex) {
logger.log(Level.SEVERE, NbBundle.getMessage(Blackboard.class, "Blackboard.unableToIndexArtifact.error.msg", bba.getDisplayName()), ex); //NON-NLS
MessageNotifyUtil.Notify.error(
NbBundle.getMessage(Blackboard.class, "Blackboard.unableToIndexArtifact.exception.msg"), bba.getDisplayName());
}
}
} catch (Exception e) {
logger.log(Level.SEVERE, "Error parsing text messages to Blackboard", e); //NON-NLS
} finally {
try {
resultSet.close();
statement.close();
connection.close();
} catch (Exception e) {
logger.log(Level.SEVERE, "Error closing database", e); //NON-NLS
}
}
} catch (Exception e) {
logger.log(Level.SEVERE, "Error parsing text messages to Blackboard", e); //NON-NLS
}
}
}
| apache-2.0 |
quantiply-fork/copycat | core/src/main/java/net/kuujo/copycat/Query.java | 1593 | /*
* Copyright 2014 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 net.kuujo.copycat;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* State machine read-only operation annotation.<p>
*
* This annotation is used to identify read-only operations in the state machine. It is strongly recommended that
* users use this annotation for read-only state machine methods. This annotation allows Copycat to identify
* operations that do not need to be logged or replicated and thus use of this annotation can significantly
* improve read performance. Alternatively, this annotation should <em>never</em> be used on any method that
* modifies the state machine's state.
*
* @author <a href="http://github.com/kuujo">Jordan Halterman</a>
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Query {
/**
* The query name. Defaults to the method name.
*/
String name() default "";
}
| apache-2.0 |
galaran/GalaransHeroesSkills | SkillTurret/src/mccity/heroes/skills/turret/PlayersAroundChecker.java | 1832 | package mccity.heroes.skills.turret;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class PlayersAroundChecker {
private final List<Location> playersLoc = new ArrayList<Location>();
private final Map<Location, Integer> minDistanceCache = new HashMap<Location, Integer>();
public PlayersAroundChecker(Plugin plugin, int period) {
PlayersLocPoller poller = new PlayersLocPoller();
poller.run();
Bukkit.getScheduler().scheduleSyncRepeatingTask(plugin, poller, period, period);
}
/** Thread unsafe */
public boolean isAnyPlayerAround(Location loc, int radius) {
if (playersLoc.isEmpty()) return false;
Integer cachedMinDist = minDistanceCache.get(loc);
if (cachedMinDist == null) {
int minDist = Integer.MAX_VALUE;
for (Location playerLoc : playersLoc) {
if (playerLoc.getWorld().equals(loc.getWorld())) {
int curDist = (int) playerLoc.distance(loc);
if (curDist < minDist) {
minDist = curDist;
}
}
}
cachedMinDist = minDist;
minDistanceCache.put(loc, cachedMinDist);
}
return cachedMinDist <= radius;
}
private class PlayersLocPoller implements Runnable {
@Override
public void run() {
playersLoc.clear();
minDistanceCache.clear();
Player[] players = Bukkit.getServer().getOnlinePlayers();
for (Player player : players) {
playersLoc.add(player.getLocation());
}
}
}
}
| apache-2.0 |
wesleyegberto/study | Chat/src/version1/Cliente.java | 2546 | /**
* @author Wesley Egberto de Brito
* @author wesley_16738 Data: 08/08/2011
*
* Chat BSE Technology V1.0
*/
package version1;
import java.io.*;
import java.net.*;
public class Cliente {
private Socket s;
private PrintWriter bw;
private String nick = "Anonymous";
private String ip = "172.16.0.239";
private int porta = 5000;
private GUICliente guiCli;
private Thread t;
private static Cliente cli = new Cliente();
private Cliente() {
}
// GETTERS E SETTERS
public void setIp(String ip) {
if(ip.equals(""))
ip = "172.16.0.239";
this.ip = ip;
}
public String getIp() {
return this.ip;
}
public void setPorta(int porta) {
if(porta < 0)
porta = 5000;
this.porta = porta;
}
public int getPorta() {
return this.porta;
}
public void setNick(String nick) {
this.nick = nick;
}
public String getNick() {
return this.nick;
}
public void setGuiCli(GUICliente guiCli) {
this.guiCli = guiCli;
}
public GUICliente getGuiCli() {
return this.guiCli;
}
public static Cliente getCliente() {
return cli;
}
public void conectar() throws UnknownHostException, IOException {
s = new Socket(this.ip, this.porta);
bw = new PrintWriter(s.getOutputStream());
sendMessage(getNick());
t = new Thread(new SocketServerReader());
t.start();
}
@SuppressWarnings("deprecation")
public void desconectar() {
t.stop();
t.interrupt();
try {
s.close();
} catch(IOException e) {
e.printStackTrace();
}
s = null;
bw = null;
}
// Envia uma mensagem
public void sendMessage(String message) {
if(s == null) {
javax.swing.JOptionPane.showMessageDialog(null, "Sem conexão.");
return;
}
bw.println(message);
bw.flush();
}
// Classe para ficar recebendo mensagem do Servidor
class SocketServerReader implements Runnable {
java.util.Scanner sc;
String message;
public SocketServerReader() {
try {
sc = new java.util.Scanner(s.getInputStream());
} catch(IOException e) {
e.printStackTrace();
}
}
@Override
public void run() {
try {
while((message = sc.nextLine()) != null) {
guiCli.txaConversa.setText(message + "\n" + guiCli.txaConversa.getText());
}
} catch(java.util.NoSuchElementException ex) {
javax.swing.JOptionPane.showMessageDialog(null, "Conexão com Servidor perdido. Tente mais tarde.");
guiCli.trancar();
guiCli.desconectar();
}
}
}
}
| apache-2.0 |
leafclick/intellij-community | platform/indexing-impl/src/com/intellij/psi/stubs/StubIndexEx.java | 1507 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.psi.stubs;
import com.intellij.util.io.DataInputOutputUtil;
import gnu.trove.TObjectHashingStrategy;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.Map;
public abstract class StubIndexEx extends StubIndex {
static void initExtensions() {
// initialize stub index keys
for (StubIndexExtension<?, ?> extension : StubIndexExtension.EP_NAME.getExtensionList()) {
extension.getKey();
}
}
abstract <K> void serializeIndexValue(@NotNull DataOutput out, @NotNull StubIndexKey<K, ?> stubIndexKey,
@NotNull Map<K, StubIdList> map) throws IOException;
@NotNull
abstract <K> Map<K, StubIdList> deserializeIndexValue(@NotNull DataInput in, @NotNull StubIndexKey<K, ?> stubIndexKey,
@Nullable K requestedKey) throws IOException;
void skipIndexValue(@NotNull DataInput in) throws IOException {
int bufferSize = DataInputOutputUtil.readINT(in);
in.skipBytes(bufferSize);
}
@NotNull
abstract <K> TObjectHashingStrategy<K> getKeyHashingStrategy(StubIndexKey<K, ?> stubIndexKey);
@ApiStatus.Internal
abstract void ensureLoaded();
}
| apache-2.0 |
FelixXG/ZhiBan | app/src/main/java/com/felix/zhiban/viewimpl/news/NewsDetailActivity.java | 8582 | package com.felix.zhiban.viewimpl.news;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.felix.zhiban.R;
import com.felix.zhiban.base.BaseActivity;
import com.felix.zhiban.bean.zhihunews.StroyDetailEntity;
import com.felix.zhiban.presenter.news.ZhihuNewsDetailPresenter;
import com.felix.zhiban.presenterinterface.news.IZhihuNewsDetailPresenter;
import com.felix.zhiban.tool.Constants;
import com.felix.zhiban.tool.HtmlUtil;
import com.felix.zhiban.tool.ImageUtils.ImageLoaderFactory;
import com.felix.zhiban.tool.NetUtils;
import com.felix.zhiban.tool.SharePreferencesHelper;
import com.felix.zhiban.viewinterface.news.IGetNewsDetailView;
public class NewsDetailActivity extends BaseActivity implements IGetNewsDetailView {
private Toolbar mToolbar;
private ImageView mDetailBarImg;
private TextView mDetailbartitle;
private TextView mDetailBarCopyRight;
private WebView mDetailNewsContentWv;
private IZhihuNewsDetailPresenter iZhihuNewsDetailPresenter;
private StroyDetailEntity stroyDetailEntity;
private String mId;//跳转的新闻的id
//动画布局
private RelativeLayout relativeLayoutAniContainer;
//加载中
private LinearLayout mLlloading;
//加载失败
private LinearLayout mRefresh;
private ImageView imageView;
//动画
private AnimationDrawable mAnimationDrawable;
@Override
public String setActName() {
return null;
}
@Override
public void showToast(String msg) {
}
@Override
public void getNewsDetail(StroyDetailEntity stroyDetailEntity) {
this.stroyDetailEntity=stroyDetailEntity;
fillData();
}
@Override
public void showContentView() {
if(mLlloading!=null&&mLlloading.getVisibility()==View.VISIBLE){
mLlloading.setVisibility(View.GONE);
}
if(mAnimationDrawable!=null&&mAnimationDrawable.isRunning()){
mAnimationDrawable.stop();
}
if(mRefresh!=null&&mRefresh.getVisibility()==View.VISIBLE){
mRefresh.setVisibility(View.GONE);
}
if(relativeLayoutAniContainer!=null&&relativeLayoutAniContainer.getVisibility()==View.VISIBLE){
relativeLayoutAniContainer.setVisibility(View.GONE);
}
}
@Override
public void showError() {
if(relativeLayoutAniContainer!=null&&relativeLayoutAniContainer.getVisibility()==View.GONE){
relativeLayoutAniContainer.setVisibility(View.VISIBLE);
}
if (mLlloading.getVisibility() != View.GONE) {
mLlloading.setVisibility(View.GONE);
}
// 停止动画
if (mAnimationDrawable.isRunning()) {
mAnimationDrawable.stop();
}
if (mRefresh.getVisibility() != View.VISIBLE) {
mRefresh.setVisibility(View.VISIBLE);
}
}
@Override
public void showLoading() {
if(mLlloading!=null&&mLlloading.getVisibility()==View.GONE){
mLlloading.setVisibility(View.VISIBLE);
}
if(mRefresh!=null&&mRefresh!=null&&mRefresh.getVisibility()==View.VISIBLE){
mRefresh.setVisibility(View.GONE);
}
//开始动画
if(mAnimationDrawable!=null&&!mAnimationDrawable.isRunning()){
mAnimationDrawable.start();
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_newsdetail);
initView();
initEvent();
initData();
initToolBar();
initWebViewClient();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
backThActivity();
return super.onKeyDown(keyCode, event);
}
private void initView(){
mToolbar=(Toolbar)findViewById(R.id.toolbar);
mDetailBarImg=(ImageView)findViewById(R.id.img_detail);
mDetailbartitle=(TextView)findViewById(R.id.detail_bar_title);
mDetailBarCopyRight=(TextView)findViewById(R.id.detail_bar_copyright);
mDetailNewsContentWv=(WebView)findViewById(R.id.wv_detail_content);
relativeLayoutAniContainer=(RelativeLayout)findViewById(R.id.ani_container);
mLlloading=(LinearLayout)findViewById(R.id.ll_loading);
mRefresh=(LinearLayout)findViewById(R.id.ll_error_refresh);
imageView=(ImageView)findViewById(R.id.img_progress);
}
private void initEvent(){
if(imageView!=null){
//加载动画
mAnimationDrawable=(AnimationDrawable)imageView.getDrawable();
//默认进入界面开始加载动画
if(!mAnimationDrawable.isRunning()){
mAnimationDrawable.start();
}
}
if(mRefresh!=null){
mRefresh.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
showLoading();
iZhihuNewsDetailPresenter.getNewsDetailById(mId);
}
});
}
}
private void fillData(){
String imgUrl=stroyDetailEntity.getImage();
ImageLoaderFactory.getImageLoader().displaycrossFade(this,imgUrl,mDetailBarImg);
mDetailbartitle.setText(stroyDetailEntity.getTitle());
mDetailBarCopyRight.setText(stroyDetailEntity.getImage_source());
String htmlData= HtmlUtil.createHtmlData(stroyDetailEntity.getBody(),stroyDetailEntity.getCss(),stroyDetailEntity.getJs());
mDetailNewsContentWv.loadData(htmlData,HtmlUtil.MIME_TYPE,HtmlUtil.ENCODING);
}
private void initData(){
iZhihuNewsDetailPresenter=new ZhihuNewsDetailPresenter(getContext(),this);
Intent intent=getIntent();
if(intent!=null){
mId=intent.getStringExtra("EXTRA_ID");
}
if(!TextUtils.isEmpty(mId)){
iZhihuNewsDetailPresenter.getNewsDetailById(mId);
}
}
private void initToolBar() {
setSupportActionBar(mToolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
//去除默认Title显示
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeAsUpIndicator(R.drawable.icon_back);
}
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
backThActivity();
}
});
// mToolbar.setTitle("新闻详情");
}
private void initWebViewClient(){
WebSettings settings=mDetailNewsContentWv.getSettings();
if(SharePreferencesHelper.getInstance(this).getBoolean(Constants.WebViewSetting.SP_NO_IMAGE,false)){
settings.setBlockNetworkImage(true);
}
if(SharePreferencesHelper.getInstance(this).getBoolean(Constants.WebViewSetting.SP_AUTO_CACHE,true)){
//启动应用缓存
settings.setAppCacheEnabled(true);
//使用localStorage则必须打开
settings.setDomStorageEnabled(true);
settings.setDatabaseEnabled(true);
if(NetUtils.isConnected(this)){
//设置缓存模式
settings.setCacheMode(WebSettings.LOAD_DEFAULT);
}else{
settings.setCacheMode(WebSettings.LOAD_CACHE_ONLY);
}
}
//提醒WebView启用JavaScript执行.默认执行false
settings.setJavaScriptEnabled(true);
//网页内容的宽度是否可以大于WebView控件的宽度
settings.setLoadWithOverviewMode(true);
settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
settings.setSupportZoom(true);
mDetailNewsContentWv.setWebViewClient(new WebViewClient(){
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
}
}
| apache-2.0 |
bmwcarit/joynr | java/javaapi/src/test/java/io/joynr/types/StructSetterTest.java | 1687 | /*
* #%L
* %%
* Copyright (C) 2018 BMW Car IT GmbH
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package io.joynr.types;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class StructSetterTest {
@Rule
public ExpectedException expectedException = ExpectedException.none();
// joynr.types.TestTypes.TStruct is generated without extra parameters
@Test
public void setterThrowsOnNullValue() {
joynr.types.TestTypes.TStruct tStruct = new joynr.types.TestTypes.TStruct();
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("setting tString to null is not allowed");
tStruct.setTString(null);
}
// joynr.types.TestTypes2.TStruct is generated with optional parameter
// ignoreInvalidNullClassMembers true
@Test
public void setterDoesNotThrowOnNullValue() {
joynr.types.TestTypes2.TStruct tStruct = new joynr.types.TestTypes2.TStruct();
tStruct.setTString(null);
}
}
| apache-2.0 |
liulhdarks/darks-learning | src/main/java/darks/learning/neuron/AbstractNeuronNetwork.java | 7049 | /**
*
* Copyright 2014 The Darks Learning Project (Liu lihua)
*
* 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 darks.learning.neuron;
import java.util.HashMap;
import java.util.Map;
import org.jblas.DoubleMatrix;
import darks.learning.exceptions.LearningException;
import darks.learning.lossfunc.LossFunction;
import darks.learning.neuron.gradient.GradientComputer;
import darks.learning.neuron.gradient.NNGradientComputer;
import darks.learning.optimize.LearningOptimizer;
import darks.learning.optimize.LearningOptimizer.OptimizeType;
import darks.learning.optimize.LineSearchOptimizer;
import darks.learning.optimize.NoneNeuronNetworkOptimizer;
/**
* Abstract neuronm network
*
* @author Darks.Liu
*
*/
public abstract class AbstractNeuronNetwork implements ReConstructon
{
protected GradientComputer gradComputer;
protected DoubleMatrix weights;
protected DoubleMatrix vBias;
protected DoubleMatrix hBias;
protected DoubleMatrix vInput;
protected DoubleMatrix sigma;
protected DoubleMatrix hiddenSigma;
private NNConfig cfg;
protected LearningOptimizer optimizer;
protected int numIterate;
public void initialize(NNConfig cfg)
{
this.cfg = cfg;
gradComputer = new NNGradientComputer(cfg);
buildOptimizer();
}
public double getLossValue()
{
cfg.lossFunction.setWeights(weights);
cfg.lossFunction.sethBias(hBias);
cfg.lossFunction.setvBias(vBias);
cfg.lossFunction.setInput(vInput);
cfg.lossFunction.setReConstructon(this);
double val = cfg.lossFunction.getLossValue();
if (cfg.lossType == LossFunction.MSE
|| cfg.lossType == LossFunction.SQUARED_LOSS
|| cfg.lossType == LossFunction.RMSE)
{
return -val;
}
return val;
}
/**
* Get gradient through current input values
*
* @return GradientComputer
*/
public GradientComputer getGradient()
{
return getGradient(vInput);
}
/**
* Get gradient through specify input values
*
* @param input Specify input values
* @return GradientComputer
*/
public abstract GradientComputer getGradient(DoubleMatrix input);
public PropPair sampleHiddenByVisible(DoubleMatrix v)
{
return null;
}
public PropPair sampleVisibleByHidden(DoubleMatrix h)
{
return null;
}
public DoubleMatrix propForward(DoubleMatrix v)
{
return null;
}
public DoubleMatrix propBackward(DoubleMatrix h)
{
return null;
}
/**
* {@inheritDoc}
*/
@Override
public DoubleMatrix reconstruct()
{
return reconstruct(vInput);
}
/**
* {@inheritDoc}
*/
@Override
public DoubleMatrix reconstruct(DoubleMatrix input)
{
return null;
}
public void addGrad(GradientComputer grad)
{
if (weights != null && grad.getwGradient() != null)
{
weights.addi(grad.getwGradient());
}
if (hBias != null && grad.gethGradient() != null)
{
hBias.addi(grad.gethGradient());
}
if (vBias != null && grad.getvGradient() != null)
{
vBias.addi(grad.getvGradient());
}
}
public void subGrad(GradientComputer grad)
{
if (weights != null && grad.getwGradient() != null)
{
weights.subi(grad.getwGradient());
}
if (hBias != null && grad.gethGradient() != null)
{
hBias.subi(grad.gethGradient());
}
if (vBias != null && grad.getvGradient() != null)
{
vBias.subi(grad.getvGradient());
}
}
private void buildOptimizer()
{
if (cfg.optimizeType == OptimizeType.NONE)
{
optimizer = new NoneNeuronNetworkOptimizer(this);
}
else if (cfg.optimizeType == OptimizeType.LINE_SEARCH)
{
optimizer = new LineSearchOptimizer(this);
}
else
{
throw new LearningException("Cannot find optimize type " + cfg.optimizeType);
}
}
public Map<String, Object> backup()
{
Map<String, Object> result = new HashMap<String, Object>();
if (weights != null)
result.put("weights", weights.dup());
if (vBias != null)
result.put("vbias", vBias.dup());
if (hBias != null)
result.put("hbias", hBias.dup());
if (gradComputer != null)
{
result.put("wgrad", gradComputer.getwGradient() == null ? null : gradComputer.getwGradient().dup());
result.put("vgrad", gradComputer.getvGradient() == null ? null : gradComputer.getvGradient().dup());
result.put("hgrad", gradComputer.gethGradient() == null ? null : gradComputer.gethGradient().dup());
}
return result;
}
public void restore(Map<String, Object> pack)
{
Object W = pack.get("weights");
if (W != null)
{
weights = ((DoubleMatrix)W).dup();
}
Object vbias = pack.get("vbias");
if (vbias != null)
{
vBias = ((DoubleMatrix)vbias).dup();
}
Object hbias = pack.get("hbias");
if (hbias != null)
{
hBias = ((DoubleMatrix)hbias).dup();
}
if (gradComputer != null)
{
Object grad = pack.get("wgrad");
gradComputer.setwGradient(grad == null ? null : ((DoubleMatrix)grad).dup());
grad = pack.get("vgrad");
gradComputer.setvGradient(grad == null ? null : ((DoubleMatrix)grad).dup());
grad = pack.get("hgrad");
gradComputer.sethGradient(grad == null ? null : ((DoubleMatrix)grad).dup());
}
}
public NNConfig config()
{
return cfg;
}
public GradientComputer getGradComputer()
{
return gradComputer;
}
public int getNumIterate()
{
return numIterate;
}
public void setNumIterate(int numIterate)
{
this.numIterate = numIterate;
if (gradComputer != null)
{
gradComputer.setNumIterate(numIterate);
}
}
public DoubleMatrix getWeights()
{
return weights;
}
public void setWeights(DoubleMatrix weights)
{
this.weights = weights;
}
public DoubleMatrix getvBias()
{
return vBias;
}
public void setvBias(DoubleMatrix vBias)
{
this.vBias = vBias;
}
public DoubleMatrix gethBias()
{
return hBias;
}
public void sethBias(DoubleMatrix hBias)
{
this.hBias = hBias;
}
public DoubleMatrix getvInput()
{
return vInput;
}
public void setvInput(DoubleMatrix vInput)
{
this.vInput = vInput;
}
public void setLearnRate(double learnRate)
{
if (gradComputer != null)
{
gradComputer.setLearnRate(learnRate);
}
}
public double getLearnRate()
{
if (gradComputer != null)
{
return gradComputer.getLearnRate();
}
else
{
return cfg.learnRate;
}
}
}
| apache-2.0 |
xiongchenhong/MyWeather | app/src/main/java/com/xch/myweather/gson/Suggestion.java | 672 | package com.xch.myweather.gson;
import com.google.gson.annotations.SerializedName;
/**
* <p>Project: MyWeather</p>
* <p>Title: Suggestion</p>
* <p>Description: Suggestion</p>
* <p>Copyright (c) 2018 www.oppo.com Inc. All rights reserved.</p>
* <p>Company: OPPO</p>
*
* @author Chenhong.Xiong
* @since 2018-10-20
*/
public class Suggestion {
@SerializedName("comf")
public Comfort mComfort;
public Sport sport;
@SerializedName("cw")
public CarWash carWash;
public class Comfort {
public String txt;
}
public class Sport {
public String txt;
}
public class CarWash {
public String txt;
}
}
| apache-2.0 |
Jamling/AFDemo | app/src/main/java/cn/ieclipse/af/demo/sample/recycler/RefreshRecyclerSample.java | 8196 | /*
* Copyright (C) 2015-2016 QuickAF
*
* 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 cn.ieclipse.af.demo.sample.recycler;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.CompoundButton;
import android.widget.TextView;
import java.util.Calendar;
import java.util.List;
import cn.ieclipse.af.adapter.AfRecyclerAdapter;
import cn.ieclipse.af.adapter.delegate.AdapterDelegate;
import cn.ieclipse.af.demo.R;
import cn.ieclipse.af.demo.common.AppFooterLoadingDelegate;
import cn.ieclipse.af.demo.common.AppRefreshRecyclerHelper;
import cn.ieclipse.af.demo.common.ui.H5Activity;
import cn.ieclipse.af.demo.sample.SampleBaseFragment;
import cn.ieclipse.af.util.DialogUtils;
import cn.ieclipse.af.view.refresh.RefreshLayout;
import cn.ieclipse.af.view.refresh.RefreshRecyclerHelper;
import cn.ieclipse.af.volley.Controller;
import cn.ieclipse.af.volley.RestError;
/**
* Description
*
* @author Jamling
*/
public class RefreshRecyclerSample extends SampleBaseFragment implements NewsController.NewsListener,
RefreshLayout.OnRefreshListener {
RefreshLayout refreshLayout;
RefreshRecyclerHelper helper;
RecyclerView listView;
AfRecyclerAdapter<NewsController.NewsInfo> adapter;
NewsController controller = new NewsController(this);
private int loadResult;
@Override
public CharSequence getTitle() {
return "RefreshRecycler(New)";
}
@Override
protected int getContentLayout() {
return R.layout.sample_refresh_recycler;
}
@Override
protected void initContentView(View view) {
super.initContentView(view);
refreshLayout = (RefreshLayout) view.findViewById(R.id.refresh);
refreshLayout.setOnRefreshListener(this);
refreshLayout.setMode(RefreshLayout.REFRESH_MODE_BOTH);
helper = new AppRefreshRecyclerHelper(refreshLayout) {
@Override
protected boolean isEmpty() {
return getItemCount() - adapter.getHeaderCount() - adapter.getFooterCount() <= 0;
}
};
helper.setKeepLoaded(true);
listView = (RecyclerView) refreshLayout.findViewById(R.id.rv);
adapter = new AfRecyclerAdapter<>();
registerDelegate();
adapter.setOnItemClickListener(new AfRecyclerAdapter.OnItemClickListener() {
@Override
public void onItemClick(AfRecyclerAdapter adapter1, View view, int position) {
DialogUtils.showToast(refreshLayout.getContext(),
String.format("Adapter#onItemClick() layout " + "position = %d", position));
NewsController.NewsInfo info = adapter.getItem(position);
if (info != null) {
startActivity(H5Activity.create(refreshLayout.getContext(), info.url, info.title));
}
}
});
helper.setAdapter(adapter);
chk3.setChecked(refreshLayout.isAutoLoad());
chk5.setChecked(helper.isKeepLoaded());
load(true);
}
protected void registerDelegate(){
adapter.setHasStableIds(true);
adapter.registerDelegate(new NewsDelegate());
}
@Override
public void onRefresh() {
load(false);
}
@Override
public void onLoadMore() {
load(false);
}
@Override
public void onClick(View v) {
if (v == btn1) {
refreshLayout.onRefresh();
}
super.onClick(v);
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (chk1 == buttonView) {
if (isChecked) {
adapter.registerDelegate(-2, new HeaderDelegate());
}
else {
adapter.removeDelegate(-2);
}
adapter.notifyDataSetChanged();
}
else if (chk2 == buttonView) {
if (isChecked) {
adapter.registerDelegate(-3, new AppFooterLoadingDelegate<NewsController.NewsInfo>(refreshLayout));
}
else {
adapter.removeDelegate(-3);
}
adapter.notifyDataSetChanged();
}
else if (chk3 == buttonView) {
refreshLayout.setAutoLoad(isChecked);
}
else if (chk4 == buttonView) {
controller.setLazyLoad(isChecked);
}
else if (chk5 == buttonView) {
helper.setKeepLoaded(isChecked);
}
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (parent == spn1) {
loadResult = position;
}
}
long startTime;
private void load(boolean needCache) {
NewsController.NewsRequest req = new NewsController.NewsRequest();
req.page = helper.getCurrentPage();
controller.loadNews(req, needCache);
startTime = Calendar.getInstance().getTimeInMillis();
}
@Override
public void onLoadNewsFailure(RestError error) {
helper.onLoadFailure(error);
}
@Override
public void onLoadNewsSuccess(List<NewsController.NewsInfo> out, boolean fromCache) {
Controller.log("load time: " + (Calendar.getInstance().getTimeInMillis() - startTime) + " ms");
if (loadResult == 1) {
helper.onLoadFinish(null, 0, 0);
}
else if (loadResult == 2) {
throw new NullPointerException("Mock error!");
}
else {
helper.onLoadFinish(out, 50, 0);
}
}
public static class NewsDelegate extends AdapterDelegate<NewsController.NewsInfo> {
@Override
public int getLayout() {
return R.layout.sample_list_item_news;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent) {
Log.e("QuickAF", "onCreateViewHolder ");
return super.onCreateViewHolder(parent);
}
@Override
public void onUpdateView(RecyclerView.ViewHolder holder, NewsController.NewsInfo info, int position) {
Log.e("QuickAF", "onUpdateView " + position + " " + info);
NewsHolder vh = (NewsHolder) holder;
vh.setInfo(info);
}
@Override
public Class<? extends RecyclerView.ViewHolder> getViewHolderClass() {
return NewsHolder.class;
}
}
private class HeaderDelegate extends AdapterDelegate<NewsController.NewsInfo> {
@Override
public boolean isForViewType(NewsController.NewsInfo info, int position) {
return position == 0;
}
@Override
public int getLayout() {
return android.R.layout.simple_list_item_1;
}
@Override
public void onUpdateView(RecyclerView.ViewHolder holder, NewsController.NewsInfo info, int position) {
TextView tv = (TextView) holder.itemView;
tv.setText("Mock Header!");
}
}
private class StringAdapter extends AfRecyclerAdapter<NewsController.NewsInfo> {
public StringAdapter(Context context) {
super(context);
}
@Override
public int getLayout() {
return android.R.layout.simple_list_item_1;
}
@Override
public void onUpdateView(RecyclerView.ViewHolder holder, NewsController.NewsInfo data, int position) {
TextView tv = (TextView) holder.itemView;
tv.setText(String.valueOf(position) + data.title);
}
}
}
| apache-2.0 |
emreaktrk/Maktek | app/src/main/java/akturk/maktek/fragment/TiadAndMibFragment.java | 1790 | package akturk.maktek.fragment;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.View;
import com.astuetz.PagerSlidingTabStrip;
import com.github.amlcurran.showcaseview.ShowcaseView;
import akturk.maktek.R;
import akturk.maktek.adapter.PressPagerAdapter;
import akturk.maktek.adapter.TiadAndMibPagerAdapter;
import akturk.maktek.constant.SingleShotID;
public final class TiadAndMibFragment extends BaseFragment {
public static final int POSITION = 7;
private ViewPager mViewPager;
private TiadAndMibPagerAdapter mAdapter;
@Override
protected int getLayoutResourceID() {
return R.layout.fragment_tiad_and_mib;
}
@Override
protected int getShowcaseTargetResourceID() {
return ShowcaseView.NO_ID;
}
@Override
protected int getShowcaseTitleResourceID() {
return ShowcaseView.NO_ID;
}
@Override
protected int getShowcaseDetailResourceID() {
return ShowcaseView.NO_ID;
}
@Override
protected long getShowcaseSingleShotID() {
return SingleShotID.SHOWCASE_SINGLESHOT_TITLESTRIP;
}
@Override
protected int getActionBarTitle() {
return R.string.title_tiad_and_mib;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mAdapter = new TiadAndMibPagerAdapter(getChildFragmentManager(), getActivity().getBaseContext());
mViewPager = (ViewPager) view.findViewById(R.id.fragment_tiad_and_mib_viewpager);
mViewPager.setAdapter(mAdapter);
PagerSlidingTabStrip mTabStrip = (PagerSlidingTabStrip) view.findViewById(R.id.fragment_tiad_and_mib_tabstrip);
mTabStrip.setViewPager(mViewPager);
}
}
| apache-2.0 |
nafae/developer | modules/adwords_axis/src/main/java/com/google/api/ads/adwords/axis/v201409/cm/AdGroupAdLabel.java | 8316 | /**
* AdGroupAdLabel.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter.
*/
package com.google.api.ads.adwords.axis.v201409.cm;
/**
* Manages the labels associated with an AdGroupAd.
*/
public class AdGroupAdLabel implements java.io.Serializable {
/* The id of the adgroup containing the ad that the label to be
* applied to.
* <span class="constraint Required">This field is required
* and should not be {@code null} when it is contained within {@link
* Operator}s : ADD, REMOVE.</span> */
private java.lang.Long adGroupId;
/* The id of the ad that the label to be applied to.
* <span class="constraint Required">This field is required
* and should not be {@code null} when it is contained within {@link
* Operator}s : ADD, REMOVE.</span> */
private java.lang.Long adId;
/* The id of an existing label to be applied to the adgroup ad.
* <span class="constraint Required">This field is required and should
* not be {@code null} when it is contained within {@link Operator}s
* : ADD, REMOVE.</span> */
private java.lang.Long labelId;
public AdGroupAdLabel() {
}
public AdGroupAdLabel(
java.lang.Long adGroupId,
java.lang.Long adId,
java.lang.Long labelId) {
this.adGroupId = adGroupId;
this.adId = adId;
this.labelId = labelId;
}
/**
* Gets the adGroupId value for this AdGroupAdLabel.
*
* @return adGroupId * The id of the adgroup containing the ad that the label to be
* applied to.
* <span class="constraint Required">This field is required
* and should not be {@code null} when it is contained within {@link
* Operator}s : ADD, REMOVE.</span>
*/
public java.lang.Long getAdGroupId() {
return adGroupId;
}
/**
* Sets the adGroupId value for this AdGroupAdLabel.
*
* @param adGroupId * The id of the adgroup containing the ad that the label to be
* applied to.
* <span class="constraint Required">This field is required
* and should not be {@code null} when it is contained within {@link
* Operator}s : ADD, REMOVE.</span>
*/
public void setAdGroupId(java.lang.Long adGroupId) {
this.adGroupId = adGroupId;
}
/**
* Gets the adId value for this AdGroupAdLabel.
*
* @return adId * The id of the ad that the label to be applied to.
* <span class="constraint Required">This field is required
* and should not be {@code null} when it is contained within {@link
* Operator}s : ADD, REMOVE.</span>
*/
public java.lang.Long getAdId() {
return adId;
}
/**
* Sets the adId value for this AdGroupAdLabel.
*
* @param adId * The id of the ad that the label to be applied to.
* <span class="constraint Required">This field is required
* and should not be {@code null} when it is contained within {@link
* Operator}s : ADD, REMOVE.</span>
*/
public void setAdId(java.lang.Long adId) {
this.adId = adId;
}
/**
* Gets the labelId value for this AdGroupAdLabel.
*
* @return labelId * The id of an existing label to be applied to the adgroup ad.
* <span class="constraint Required">This field is required and should
* not be {@code null} when it is contained within {@link Operator}s
* : ADD, REMOVE.</span>
*/
public java.lang.Long getLabelId() {
return labelId;
}
/**
* Sets the labelId value for this AdGroupAdLabel.
*
* @param labelId * The id of an existing label to be applied to the adgroup ad.
* <span class="constraint Required">This field is required and should
* not be {@code null} when it is contained within {@link Operator}s
* : ADD, REMOVE.</span>
*/
public void setLabelId(java.lang.Long labelId) {
this.labelId = labelId;
}
private java.lang.Object __equalsCalc = null;
public synchronized boolean equals(java.lang.Object obj) {
if (!(obj instanceof AdGroupAdLabel)) return false;
AdGroupAdLabel other = (AdGroupAdLabel) obj;
if (obj == null) return false;
if (this == obj) return true;
if (__equalsCalc != null) {
return (__equalsCalc == obj);
}
__equalsCalc = obj;
boolean _equals;
_equals = true &&
((this.adGroupId==null && other.getAdGroupId()==null) ||
(this.adGroupId!=null &&
this.adGroupId.equals(other.getAdGroupId()))) &&
((this.adId==null && other.getAdId()==null) ||
(this.adId!=null &&
this.adId.equals(other.getAdId()))) &&
((this.labelId==null && other.getLabelId()==null) ||
(this.labelId!=null &&
this.labelId.equals(other.getLabelId())));
__equalsCalc = null;
return _equals;
}
private boolean __hashCodeCalc = false;
public synchronized int hashCode() {
if (__hashCodeCalc) {
return 0;
}
__hashCodeCalc = true;
int _hashCode = 1;
if (getAdGroupId() != null) {
_hashCode += getAdGroupId().hashCode();
}
if (getAdId() != null) {
_hashCode += getAdId().hashCode();
}
if (getLabelId() != null) {
_hashCode += getLabelId().hashCode();
}
__hashCodeCalc = false;
return _hashCode;
}
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(AdGroupAdLabel.class, true);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201409", "AdGroupAdLabel"));
org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("adGroupId");
elemField.setXmlName(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201409", "adGroupId"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "long"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("adId");
elemField.setXmlName(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201409", "adId"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "long"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("labelId");
elemField.setXmlName(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201409", "labelId"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "long"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
}
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
/**
* Get Custom Serializer
*/
public static org.apache.axis.encoding.Serializer getSerializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanSerializer(
_javaType, _xmlType, typeDesc);
}
/**
* Get Custom Deserializer
*/
public static org.apache.axis.encoding.Deserializer getDeserializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanDeserializer(
_javaType, _xmlType, typeDesc);
}
}
| apache-2.0 |
delzak/java_course | moysklad-web-tests/src/test/java/ru/web/moysklad/appmanager/pages/retail/RetailShiftHelper.java | 457 | package ru.web.moysklad.appmanager.pages.retail;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import ru.web.moysklad.appmanager.HelperBase;
public class RetailShiftHelper extends HelperBase {
public RetailShiftHelper(WebDriver wd) {
super(wd);
}
public String getTitleText() throws InterruptedException {
Thread.sleep(300);
return wd.findElement(By.cssSelector("div.title")).getText();
}
}
| apache-2.0 |
alim1369/sos | src/sos/base/util/DistanceSorter.java | 876 | package sos.base.util;
import java.util.Comparator;
import sos.base.entities.StandardEntity;
import sos.base.entities.StandardWorldModel;
/**
A comparator that sorts entities by distance to a reference point.
*/
public class DistanceSorter implements Comparator<StandardEntity> {
private StandardEntity reference;
private StandardWorldModel world;
/**
Create a DistanceSorter.
@param reference The reference point to measure distances from.
@param world The world model.
*/
public DistanceSorter(StandardEntity reference, StandardWorldModel world) {
this.reference = reference;
this.world = world;
}
@Override
public int compare(StandardEntity a, StandardEntity b) {
int d1 = world.getDistance(reference, a);
int d2 = world.getDistance(reference, b);
return d1 - d2;
}
}
| apache-2.0 |
covito/legend-shop | src/main/java/com/legendshop/business/service/impl/AskServiceImpl.java | 1120 | package com.legendshop.business.service.impl;
import com.legendshop.business.dao.AskDao;
import com.legendshop.core.dao.support.CriteriaQuery;
import com.legendshop.core.dao.support.PageSupport;
import com.legendshop.model.entity.Ask;
import com.legendshop.spi.service.AskService;
import com.legendshop.util.AppUtils;
import java.util.List;
public class AskServiceImpl
implements AskService
{
private AskDao askDao;
public void setAskDao(AskDao askDao)
{
this.askDao = askDao;
}
public List<Ask> getAsk(String userName) {
return this.askDao.getAsk(userName);
}
public Ask getAsk(Long id) {
return this.askDao.getAsk(id);
}
public void deleteAsk(Ask ask) {
this.askDao.deleteAsk(ask);
}
public Long saveAsk(Ask ask) {
if (!(AppUtils.isBlank(ask.getAskId()))) {
updateAsk(ask);
return ask.getAskId();
}
return ((Long)this.askDao.save(ask));
}
public void updateAsk(Ask ask) {
this.askDao.updateAsk(ask);
}
public PageSupport getAsk(CriteriaQuery cq) {
return this.askDao.find(cq);
}
} | apache-2.0 |
abluepoint/summer | summer-data-jpa/src/main/java/com/abluepoint/summer/data/jpa/JpaSummerRuntimeException.java | 901 | package com.abluepoint.summer.data.jpa;
import com.abluepoint.summer.common.exception.SummerException;
import com.abluepoint.summer.common.exception.SummerRuntimeException;
public class JpaSummerRuntimeException extends SummerRuntimeException {
public JpaSummerRuntimeException() {
}
public JpaSummerRuntimeException(String message) {
super(message);
}
public JpaSummerRuntimeException(String message, Object... args) {
super(message, args);
}
public JpaSummerRuntimeException(String message, Throwable cause) {
super(message, cause);
}
public JpaSummerRuntimeException(String message, Throwable cause, Object... args) {
super(message, cause, args);
}
public JpaSummerRuntimeException(SummerException e) {
super(e);
}
public JpaSummerRuntimeException(Throwable cause) {
super(cause);
}
}
| apache-2.0 |
trasukg/river-qa-2.2 | qa/jtreg/net/jini/config/TestAPI/TestConstructor.java | 6276 | /*
* 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.
*/
/* @test
* @summary Tests ConfigurationFile constructors
* @author Tim Blackman
* @library ../../../../unittestlib
* @build UnitTestUtilities BasicTest Test
* @run main/othervm/policy=policy TestConstructor
*/
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import net.jini.config.ConfigurationException;
import net.jini.config.ConfigurationFile;
import net.jini.config.ConfigurationNotFoundException;
public class TestConstructor extends BasicTest {
static final String src =
System.getProperty("test.src", ".") + File.separator;
static {
if (System.getProperty("java.security.policy") == null) {
System.setProperty("java.security.policy", src + "policy");
}
if (System.getProperty("java.security.properties") == null) {
System.setProperty("java.security.properties",
src + File.separator + "security.properties");
}
if (System.getSecurityManager() == null) {
System.setSecurityManager(new SecurityManager());
}
}
static Test[] tests = {
new TestConstructor(null, ConfigurationFile.class),
new TestConstructor(new String[0], ConfigurationFile.class),
new TestConstructor(sa(null), ConfigurationException.class),
new TestConstructor(sa(""), ConfigurationNotFoundException.class),
new TestConstructor(sa("-"), ConfigurationFile.class),
new TestConstructor(sa("foo"), ConfigurationNotFoundException.class),
/*
* These sources have invalid URL syntax, but ConfigurationFile assumes
* that they are files and then discovers that the files don't exist.
*/
new TestConstructor(sa("http://localhost:jdf/"),
ConfigurationNotFoundException.class),
new TestConstructor(sa("foo://"), ConfigurationNotFoundException.class),
/* No server on port */
new Object() {
Test test() {
try {
ServerSocket ss = new ServerSocket(0);
int port = ss.getLocalPort();
ss.close();
return new TestConstructor(sa("http://localhost:" + port),
ConfigurationException.class);
} catch (IOException e) {
throw unexpectedException(e);
}
}
}.test(),
new Object() {
HttpServer server = new HttpServer();
Test test() {
return new TestConstructor(
sa("http://localhost:" + server.port + "/unknown-file"),
ConfigurationNotFoundException.class)
{
public Object run() {
try {
return super.run();
} finally {
server.shutdown();
}
}
};
}
}.test(),
new TestConstructor(sa("file:" + File.separator + "unknown-file"),
ConfigurationNotFoundException.class),
new TestConstructor(sa("file:" + File.separator),
ConfigurationException.class),
new TestConstructor(sa(src + "config"), ConfigurationFile.class),
new TestConstructor(sa("file:" + src.replace(File.separatorChar, '/') +
"config"),
ConfigurationFile.class),
new TestConstructor(sa(src + "config"), null, ConfigurationFile.class),
new TestConstructor(sa(src + "config"),
new FileClassLoader(new HashMap()),
ConfigurationFile.class),
};
private final String[] options;
private boolean clSupplied;
private ClassLoader cl;
public static void main(String[] args) throws Exception {
test(tests);
}
private TestConstructor(String[] options, Class resultType) {
super(toString(options), resultType);
this.options = options;
}
private TestConstructor(String[] options,
ClassLoader cl,
Class resultType)
{
super(toString(options) + ", " + cl, resultType);
this.options = options;
this.clSupplied = true;
this.cl = cl;
}
public Object run() {
try {
if (clSupplied) {
return new ConfigurationFile(options, cl);
} else {
return new ConfigurationFile(options);
}
} catch (ConfigurationException e) {
return e;
}
}
public void check(Object result) {
if (result.getClass() != getCompareTo()) {
throw new FailedException(
"Should be of type " + getCompareTo());
}
}
static String[] sa(String s) {
return new String[] { s };
}
/**
* Defines a simple, single-threaded HTTP server, that returns 'Not Found'
* for all GET requests, and 'Bad Request' for all other requests.
*/
static class HttpServer extends Thread {
ServerSocket ss;
int port;
HttpServer() {
super("HttpServer");
try {
ss = new ServerSocket(0);
port = ss.getLocalPort();
} catch (IOException e) {
throw unexpectedException(e);
}
setDaemon(true);
start();
}
public void run() {
try {
while (true) {
Socket s = ss.accept();
try {
BufferedReader in =
new BufferedReader(
new InputStreamReader(
s.getInputStream()));
String req = in.readLine();
String line;
do {
line = in.readLine();
} while (line != null
&& line.length() > 0
&& line.charAt(0) != '\r'
&& line.charAt(0) != '\n');
DataOutputStream out =
new DataOutputStream(s.getOutputStream());
if (req.startsWith("GET")) {
out.writeBytes("HTTP/1.0 404 Not Found\r\n\r\n");
} else {
out.writeBytes("HTTP/1.0 400 Bad Request\r\n\r\n");
}
out.flush();
} finally {
try {
s.close();
} catch (IOException e) {
}
}
}
} catch (IOException e) {
debugPrint(30, e.toString());
}
}
void shutdown() {
try {
ss.close();
} catch (IOException e) {
debugPrint(30, e.toString());
}
}
}
}
| apache-2.0 |
colymore/Uned | PL2-2019/src/compiler/syntax/nonTerminal/SentAsign.java | 552 | package compiler.syntax.nonTerminal;
public class SentAsign extends NonTerminal {
private final Variables variables;
private final Expresion expresion;
public SentAsign(Variables variables, Expresion expresion) {
super();
this.variables = variables;
this.expresion = expresion;
}
public Variables getVariables() {
return variables;
}
public Expresion getExpresion() {
return expresion;
}
@Override
public String toString() {
return "SentAsign{" +
"variables=" + variables +
", expresion=" + expresion +
'}';
}
} | apache-2.0 |
nafae/developer | modules/dfa_axis/src/main/java/com/google/api/ads/dfa/axis/v1_19/SpotlightTagCodeType.java | 2573 | /**
* SpotlightTagCodeType.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter.
*/
package com.google.api.ads.dfa.axis.v1_19;
public class SpotlightTagCodeType extends com.google.api.ads.dfa.axis.v1_19.Base implements java.io.Serializable {
public SpotlightTagCodeType() {
}
public SpotlightTagCodeType(
long id,
java.lang.String name) {
super(
id,
name);
}
private java.lang.Object __equalsCalc = null;
public synchronized boolean equals(java.lang.Object obj) {
if (!(obj instanceof SpotlightTagCodeType)) return false;
SpotlightTagCodeType other = (SpotlightTagCodeType) obj;
if (obj == null) return false;
if (this == obj) return true;
if (__equalsCalc != null) {
return (__equalsCalc == obj);
}
__equalsCalc = obj;
boolean _equals;
_equals = super.equals(obj);
__equalsCalc = null;
return _equals;
}
private boolean __hashCodeCalc = false;
public synchronized int hashCode() {
if (__hashCodeCalc) {
return 0;
}
__hashCodeCalc = true;
int _hashCode = super.hashCode();
__hashCodeCalc = false;
return _hashCode;
}
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(SpotlightTagCodeType.class, true);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("http://www.doubleclick.net/dfa-api/v1.19", "SpotlightTagCodeType"));
}
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
/**
* Get Custom Serializer
*/
public static org.apache.axis.encoding.Serializer getSerializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanSerializer(
_javaType, _xmlType, typeDesc);
}
/**
* Get Custom Deserializer
*/
public static org.apache.axis.encoding.Deserializer getDeserializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanDeserializer(
_javaType, _xmlType, typeDesc);
}
}
| apache-2.0 |
lsimons/phloc-schematron-standalone | phloc-commons/src/main/java/com/phloc/commons/locale/language/ComparatorLocaleDisplayLanguage.java | 1356 | /**
* Copyright (C) 2006-2013 phloc systems
* http://www.phloc.com
* office[at]phloc[dot]com
*
* 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.phloc.commons.locale.language;
import java.util.Locale;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import com.phloc.commons.compare.AbstractCollationComparator;
/**
* {@link java.util.Comparator} that sorts {@link Locale} objects by their
* language display name in the system locale.
*
* @author Philip Helger
*/
public final class ComparatorLocaleDisplayLanguage extends AbstractCollationComparator <Locale>
{
public ComparatorLocaleDisplayLanguage (@Nullable final Locale aSortLocale)
{
super (aSortLocale);
}
@Override
protected String asString (@Nonnull final Locale aLocale)
{
return aLocale.getDisplayLanguage ();
}
}
| apache-2.0 |
MarkRunWu/buck | test/com/facebook/buck/rules/CachingBuildEngineTest.java | 67413 | /*
* Copyright 2012-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.rules;
import static com.facebook.buck.event.TestEventConfigerator.configureTestEvent;
import static com.google.common.util.concurrent.MoreExecutors.listeningDecorator;
import static org.easymock.EasyMock.anyObject;
import static org.easymock.EasyMock.capture;
import static org.easymock.EasyMock.eq;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.expectLastCall;
import static org.easymock.EasyMock.isA;
import static org.easymock.EasyMock.newCapture;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import com.facebook.buck.cli.CommandEvent;
import com.facebook.buck.event.BuckEvent;
import com.facebook.buck.event.BuckEventBus;
import com.facebook.buck.event.BuckEventBusFactory;
import com.facebook.buck.event.FakeBuckEventListener;
import com.facebook.buck.io.ProjectFilesystem;
import com.facebook.buck.java.FakeJavaPackageFinder;
import com.facebook.buck.java.JavaPackageFinder;
import com.facebook.buck.model.BuildId;
import com.facebook.buck.model.BuildTarget;
import com.facebook.buck.model.BuildTargetFactory;
import com.facebook.buck.model.Pair;
import com.facebook.buck.rules.keys.DefaultRuleKeyBuilderFactory;
import com.facebook.buck.rules.keys.SupportsInputBasedRuleKey;
import com.facebook.buck.step.AbstractExecutionStep;
import com.facebook.buck.step.DefaultStepRunner;
import com.facebook.buck.step.ExecutionContext;
import com.facebook.buck.step.Step;
import com.facebook.buck.step.StepFailedException;
import com.facebook.buck.step.StepRunner;
import com.facebook.buck.step.fs.WriteFileStep;
import com.facebook.buck.testutil.FakeFileHashCache;
import com.facebook.buck.testutil.FakeProjectFilesystem;
import com.facebook.buck.testutil.RuleMap;
import com.facebook.buck.testutil.integration.DebuggableTemporaryFolder;
import com.facebook.buck.timing.DefaultClock;
import com.facebook.buck.util.FileHashCache;
import com.facebook.buck.util.NullFileHashCache;
import com.facebook.buck.util.Verbosity;
import com.facebook.buck.util.concurrent.MoreFutures;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.Lists;
import com.google.common.hash.HashCode;
import com.google.common.hash.HashFunction;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import org.easymock.Capture;
import org.easymock.EasyMockSupport;
import org.easymock.IAnswer;
import org.hamcrest.Matchers;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.annotation.Nullable;
/**
* Ensuring that build rule caching works correctly in Buck is imperative for both its performance
* and correctness.
*/
public class CachingBuildEngineTest extends EasyMockSupport {
private static final BuildTarget buildTarget =
BuildTarget.builder("//src/com/facebook/orca", "orca").build();
private static final RuleKeyBuilderFactory NOOP_RULE_KEY_FACTORY =
new DefaultRuleKeyBuilderFactory(
new NullFileHashCache(),
new SourcePathResolver(new BuildRuleResolver()));
@Rule
public TemporaryFolder tmp = new DebuggableTemporaryFolder();
/**
* Tests what should happen when a rule is built for the first time: it should have no cached
* RuleKey, nor should it have any artifact in the ArtifactCache. The sequence of events should be
* as follows:
* <ol>
* <li>The build engine invokes the {@link CachingBuildEngine#build(BuildContext, BuildRule)}
* method on each of the transitive deps.
* <li>The rule computes its own {@link RuleKey}.
* <li>The engine compares its {@link RuleKey} to the one on disk, if present.
* <li>Because the rule has no {@link RuleKey} on disk, the engine tries to build the rule.
* <li>First, it checks the artifact cache, but there is a cache miss.
* <li>The rule generates its build steps and the build engine executes them.
* <li>Upon executing its steps successfully, the build engine should write the rule's
* {@link RuleKey} to disk.
* <li>The build engine should persist a rule's output to the ArtifactCache.
* </ol>
*/
@Test
public void testBuildRuleLocallyWithCacheMiss()
throws IOException, InterruptedException, ExecutionException, StepFailedException {
SourcePathResolver resolver = new SourcePathResolver(new BuildRuleResolver());
// Create a dep for the build rule.
BuildTarget depTarget = BuildTargetFactory.newInstance("//src/com/facebook/orca:lib");
FakeBuildRule dep = new FakeBuildRule(depTarget, resolver);
dep.setRuleKey(new RuleKey("19d2558a6bd3a34fb3f95412de9da27ed32fe208"));
// The EventBus should be updated with events indicating how the rule was built.
BuckEventBus buckEventBus = BuckEventBusFactory.newInstance();
FakeBuckEventListener listener = new FakeBuckEventListener();
buckEventBus.register(listener);
// Create an ArtifactCache whose expectations will be set later.
ArtifactCache mockArtifactCache = createMock(ArtifactCache.class);
ArtifactCache artifactCache = new LoggingArtifactCacheDecorator(buckEventBus)
.decorate(mockArtifactCache);
// Replay the mocks to instantiate the AbstractCachingBuildRule.
replayAll();
String pathToOutputFile = "buck-out/gen/src/com/facebook/orca/some_file";
List<Step> buildSteps = Lists.newArrayList();
BuildRule ruleToTest = createRule(
resolver,
ImmutableSet.<BuildRule>of(dep),
buildSteps,
/* postBuildSteps */ ImmutableList.<Step>of(),
pathToOutputFile);
verifyAll();
resetAll();
// The BuildContext that will be used by the rule's build() method.
BuildContext context = createMock(BuildContext.class);
expect(context.getProjectFilesystem()).andReturn(new FakeProjectFilesystem());
expect(context.getArtifactCache()).andReturn(artifactCache).times(2);
// Configure the OnDiskBuildInfo.
OnDiskBuildInfo onDiskBuildInfo = new FakeOnDiskBuildInfo();
expect(context.createOnDiskBuildInfoFor(buildTarget)).andReturn(onDiskBuildInfo);
// Configure the BuildInfoRecorder.
BuildInfoRecorder buildInfoRecorder = createNiceMock(BuildInfoRecorder.class);
Capture<RuleKey> ruleKeyForRecorder = newCapture();
expect(
context.createBuildInfoRecorder(
eq(buildTarget),
capture(ruleKeyForRecorder),
/* ruleKeyWithoutDepsForRecorder */ anyObject(RuleKey.class)))
.andReturn(buildInfoRecorder);
expect(
buildInfoRecorder.fetchArtifactForBuildable(
anyObject(RuleKey.class),
anyObject(File.class),
eq(artifactCache)))
.andReturn(CacheResult.miss());
expect(buildInfoRecorder.getOutputSizeAndHash(anyObject(HashFunction.class)))
.andReturn(new Pair<>(0L, HashCode.fromInt(0)))
.anyTimes();
// Set the requisite expectations to build the rule.
expect(context.getEventBus()).andReturn(buckEventBus).anyTimes();
expect(context.getStepRunner()).andReturn(createStepRunner(buckEventBus)).anyTimes();
CachingBuildEngine cachingBuildEngine =
new CachingBuildEngine(
MoreExecutors.newDirectExecutorService(),
CachingBuildEngine.BuildMode.SHALLOW,
NOOP_RULE_KEY_FACTORY);
// Add a build step so we can verify that the steps are executed.
Step buildStep = createMock(Step.class);
expect(buildStep.getDescription(anyObject(ExecutionContext.class)))
.andReturn("Some Description")
.anyTimes();
expect(buildStep.getShortName()).andReturn("Some Short Name").anyTimes();
expect(buildStep.execute(anyObject(ExecutionContext.class))).andReturn(0);
buildSteps.add(buildStep);
// These methods should be invoked after the rule is built locally.
buildInfoRecorder.recordArtifact(Paths.get(pathToOutputFile));
buildInfoRecorder.writeMetadataToDisk(/* clearExistingMetadata */ true);
buildInfoRecorder.performUploadToArtifactCache(
ImmutableSet.of(ruleToTest.getRuleKey()),
artifactCache,
buckEventBus);
// Attempting to build the rule should force a rebuild due to a cache miss.
replayAll();
cachingBuildEngine.setBuildRuleResult(
dep,
BuildRuleSuccessType.FETCHED_FROM_CACHE,
CacheResult.skip());
BuildResult result = cachingBuildEngine.build(context, ruleToTest).get();
assertEquals(BuildRuleSuccessType.BUILT_LOCALLY, result.getSuccess());
buckEventBus.post(CommandEvent.finished("build", ImmutableList.<String>of(), false, 0));
verifyAll();
// Verify the events logged to the BuckEventBus.
List<BuckEvent> events = listener.getEvents();
assertThat(events, Matchers.hasSize(11));
Iterator<BuckEvent> eventIter = events.iterator();
assertEquals(
configureTestEvent(BuildRuleEvent.started(dep), buckEventBus),
eventIter.next());
assertEquals(
configureTestEvent(BuildRuleEvent.suspended(dep), buckEventBus),
eventIter.next());
assertEquals(
configureTestEvent(BuildRuleEvent.started(ruleToTest), buckEventBus),
eventIter.next());
assertEquals(
configureTestEvent(
BuildRuleEvent.finished(
ruleToTest,
BuildRuleStatus.SUCCESS,
CacheResult.miss(),
Optional.of(BuildRuleSuccessType.BUILT_LOCALLY),
Optional.<HashCode>absent(),
Optional.<Long>absent()),
buckEventBus),
events.get(events.size() - 2));
}
/**
* Rebuild a rule where one if its dependencies has been modified such that its RuleKey has
* changed, but its ABI is the same.
*/
@Test
public void testAbiRuleCanAvoidRebuild()
throws InterruptedException, ExecutionException, IOException {
BuildRuleParams buildRuleParams = new FakeBuildRuleParamsBuilder(buildTarget).build();
TestAbstractCachingBuildRule buildRule =
new TestAbstractCachingBuildRule(
buildRuleParams,
new SourcePathResolver(new BuildRuleResolver()));
// The EventBus should be updated with events indicating how the rule was built.
BuckEventBus buckEventBus = BuckEventBusFactory.newInstance();
FakeBuckEventListener listener = new FakeBuckEventListener();
buckEventBus.register(listener);
BuildContext buildContext = createMock(BuildContext.class);
BuildInfoRecorder buildInfoRecorder = createNiceMock(BuildInfoRecorder.class);
expect(buildContext.getProjectFilesystem()).andReturn(new FakeProjectFilesystem());
expect(buildContext.createBuildInfoRecorder(
eq(buildTarget),
/* ruleKey */ anyObject(RuleKey.class),
/* ruleKeyWithoutDeps */ anyObject(RuleKey.class)))
.andReturn(buildInfoRecorder);
expect(buildInfoRecorder.getOutputSizeAndHash(anyObject(HashFunction.class)))
.andReturn(new Pair<>(0L, HashCode.fromInt(0)))
.anyTimes();
// Populate the metadata that should be read from disk.
OnDiskBuildInfo onDiskBuildInfo = new FakeOnDiskBuildInfo()
// The RuleKey on disk should be different from the current RuleKey in memory, so reverse()
// it.
.setRuleKey(reverse(buildRule.getRuleKey()))
// However, the RuleKey not including the deps in memory should be the same as the one on
// disk.
.setRuleKeyWithoutDeps(
new RuleKey(TestAbstractCachingBuildRule.RULE_KEY_WITHOUT_DEPS_HASH))
// Similarly, the ABI key for the deps in memory should be the same as the one on disk.
.putMetadata(
CachingBuildEngine.ABI_KEY_FOR_DEPS_ON_DISK_METADATA,
TestAbstractCachingBuildRule.ABI_KEY_FOR_DEPS_HASH)
.putMetadata(AbiRule.ABI_KEY_ON_DISK_METADATA,
"At some point, this method call should go away.");
// These methods should be invoked after the rule is built locally.
buildInfoRecorder.writeMetadataToDisk(/* clearExistingMetadata */ false);
expect(
buildInfoRecorder.fetchArtifactForBuildable(
anyObject(RuleKey.class),
anyObject(File.class),
anyObject(ArtifactCache.class)))
.andReturn(CacheResult.miss());
expect(buildContext.createOnDiskBuildInfoFor(buildTarget)).andReturn(onDiskBuildInfo);
expect(buildContext.getArtifactCache()).andStubReturn(new NoopArtifactCache());
expect(buildContext.getEventBus()).andReturn(buckEventBus).anyTimes();
replayAll();
CachingBuildEngine cachingBuildEngine =
new CachingBuildEngine(
MoreExecutors.newDirectExecutorService(),
CachingBuildEngine.BuildMode.SHALLOW,
NOOP_RULE_KEY_FACTORY);
ListenableFuture<BuildResult> buildResult = cachingBuildEngine.build(buildContext, buildRule);
//assertTrue(
// "We expect build() to be synchronous in this case, " +
// "so the future should already be resolved.",
// MoreFutures.isSuccess(buildResult));
buckEventBus.post(CommandEvent.finished("build", ImmutableList.<String>of(), false, 0));
BuildResult result = buildResult.get();
assertEquals(BuildRuleSuccessType.MATCHING_DEPS_ABI_AND_RULE_KEY_NO_DEPS, result.getSuccess());
assertTrue(buildRule.isAbiLoadedFromDisk());
List<BuckEvent> events = listener.getEvents();
assertThat(events, Matchers.hasSize(7));
Iterator<BuckEvent> eventIter = events.iterator();
assertEquals(
configureTestEvent(BuildRuleEvent.started(buildRule), buckEventBus),
eventIter.next());
assertEquals(
configureTestEvent(BuildRuleEvent.suspended(buildRule), buckEventBus),
eventIter.next());
assertEquals(
configureTestEvent(BuildRuleEvent.resumed(buildRule), buckEventBus),
eventIter.next());
assertEquals(
configureTestEvent(BuildRuleEvent.suspended(buildRule), buckEventBus),
eventIter.next());
assertEquals(
configureTestEvent(BuildRuleEvent.resumed(buildRule), buckEventBus),
eventIter.next());
assertEquals(
configureTestEvent(
BuildRuleEvent.finished(
buildRule,
BuildRuleStatus.SUCCESS,
CacheResult.localKeyUnchangedHit(),
Optional.of(BuildRuleSuccessType.MATCHING_DEPS_ABI_AND_RULE_KEY_NO_DEPS),
Optional.<HashCode>absent(),
Optional.<Long>absent()),
buckEventBus),
eventIter.next());
verifyAll();
}
private StepRunner createStepRunner(@Nullable BuckEventBus eventBus) {
ExecutionContext executionContext = createMock(ExecutionContext.class);
expect(executionContext.getVerbosity()).andReturn(Verbosity.SILENT).anyTimes();
if (eventBus != null) {
expect(executionContext.getBuckEventBus()).andStubReturn(eventBus);
expect(executionContext.getBuckEventBus()).andStubReturn(eventBus);
}
executionContext.postEvent(anyObject(BuckEvent.class));
expectLastCall().anyTimes();
return new DefaultStepRunner(executionContext);
}
private StepRunner createStepRunner() {
return createStepRunner(null);
}
@Test
public void testAbiKeyAutomaticallyPopulated()
throws IOException, ExecutionException, InterruptedException {
BuildRuleParams buildRuleParams = new FakeBuildRuleParamsBuilder(buildTarget).build();
TestAbstractCachingBuildRule buildRule =
new LocallyBuiltTestAbstractCachingBuildRule(
buildRuleParams,
new SourcePathResolver(new BuildRuleResolver()));
// The EventBus should be updated with events indicating how the rule was built.
BuckEventBus buckEventBus = BuckEventBusFactory.newInstance();
FakeBuckEventListener listener = new FakeBuckEventListener();
buckEventBus.register(listener);
BuildContext buildContext = createMock(BuildContext.class);
NoopArtifactCache artifactCache = new NoopArtifactCache();
expect(buildContext.getArtifactCache()).andStubReturn(artifactCache);
expect(buildContext.getStepRunner()).andStubReturn(null);
expect(buildContext.getProjectFilesystem()).andReturn(new FakeProjectFilesystem());
BuildInfoRecorder buildInfoRecorder = createNiceMock(BuildInfoRecorder.class);
expect(buildContext.createBuildInfoRecorder(
eq(buildTarget),
/* ruleKey */ anyObject(RuleKey.class),
/* ruleKeyWithoutDeps */ anyObject(RuleKey.class)))
.andReturn(buildInfoRecorder);
expect(
buildInfoRecorder.fetchArtifactForBuildable(
anyObject(RuleKey.class),
anyObject(File.class),
eq(artifactCache)))
.andReturn(CacheResult.miss());
expect(buildInfoRecorder.getOutputSizeAndHash(anyObject(HashFunction.class)))
.andReturn(new Pair<>(0L, HashCode.fromInt(0)))
.anyTimes();
// Populate the metadata that should be read from disk.
OnDiskBuildInfo onDiskBuildInfo = new FakeOnDiskBuildInfo();
// This metadata must be added to the buildInfoRecorder so that it is written as part of
// writeMetadataToDisk().
buildInfoRecorder.addMetadata(
CachingBuildEngine.ABI_KEY_FOR_DEPS_ON_DISK_METADATA,
TestAbstractCachingBuildRule.ABI_KEY_FOR_DEPS_HASH);
// These methods should be invoked after the rule is built locally.
buildInfoRecorder.writeMetadataToDisk(/* clearExistingMetadata */ true);
buildInfoRecorder.performUploadToArtifactCache(
ImmutableSet.of(buildRule.getRuleKey()),
artifactCache,
buckEventBus);
expect(buildContext.createOnDiskBuildInfoFor(buildTarget)).andReturn(onDiskBuildInfo);
expect(buildContext.getStepRunner()).andReturn(createStepRunner());
expect(buildContext.getEventBus()).andReturn(buckEventBus).anyTimes();
replayAll();
CachingBuildEngine cachingBuildEngine =
new CachingBuildEngine(
MoreExecutors.newDirectExecutorService(),
CachingBuildEngine.BuildMode.SHALLOW,
NOOP_RULE_KEY_FACTORY);
ListenableFuture<BuildResult> buildResult = cachingBuildEngine.build(buildContext, buildRule);
buckEventBus.post(CommandEvent.finished("build", ImmutableList.<String>of(), false, 0));
BuildResult result = buildResult.get();
assertEquals(BuildRuleSuccessType.BUILT_LOCALLY, result.getSuccess());
List<BuckEvent> events = listener.getEvents();
assertThat(events, Matchers.hasSize(7));
Iterator<BuckEvent> eventIter = events.iterator();
assertEquals(
configureTestEvent(BuildRuleEvent.started(buildRule), buckEventBus),
eventIter.next());
assertEquals(
configureTestEvent(BuildRuleEvent.suspended(buildRule), buckEventBus),
eventIter.next());
assertEquals(
configureTestEvent(BuildRuleEvent.resumed(buildRule), buckEventBus),
eventIter.next());
assertEquals(
configureTestEvent(BuildRuleEvent.suspended(buildRule), buckEventBus),
eventIter.next());
assertEquals(
configureTestEvent(BuildRuleEvent.resumed(buildRule), buckEventBus),
eventIter.next());
assertEquals(
configureTestEvent(
BuildRuleEvent.finished(
buildRule,
BuildRuleStatus.SUCCESS,
CacheResult.miss(),
Optional.of(BuildRuleSuccessType.BUILT_LOCALLY),
Optional.<HashCode>absent(),
Optional.<Long>absent()),
buckEventBus),
eventIter.next());
verifyAll();
}
@Test
public void testAsyncJobsAreNotLeftInExecutor()
throws IOException, ExecutionException, InterruptedException {
BuildRuleParams buildRuleParams = new FakeBuildRuleParamsBuilder(buildTarget).build();
TestAbstractCachingBuildRule buildRule =
new LocallyBuiltTestAbstractCachingBuildRule(
buildRuleParams,
new SourcePathResolver(new BuildRuleResolver()));
// The EventBus should be updated with events indicating how the rule was built.
BuckEventBus buckEventBus = BuckEventBusFactory.newInstance();
FakeBuckEventListener listener = new FakeBuckEventListener();
buckEventBus.register(listener);
BuildContext buildContext = createMock(BuildContext.class);
expect(buildContext.getProjectFilesystem()).andReturn(new FakeProjectFilesystem());
NoopArtifactCache artifactCache = new NoopArtifactCache();
expect(buildContext.getArtifactCache()).andStubReturn(artifactCache);
expect(buildContext.getStepRunner()).andStubReturn(null);
BuildInfoRecorder buildInfoRecorder = createNiceMock(BuildInfoRecorder.class);
expect(
buildContext.createBuildInfoRecorder(
eq(buildTarget),
/* ruleKey */ anyObject(RuleKey.class),
/* ruleKeyWithoutDeps */ anyObject(RuleKey.class)))
.andReturn(buildInfoRecorder);
expect(
buildInfoRecorder.fetchArtifactForBuildable(
anyObject(RuleKey.class),
anyObject(File.class),
eq(artifactCache)))
.andReturn(CacheResult.miss());
expect(buildInfoRecorder.getOutputSizeAndHash(anyObject(HashFunction.class)))
.andReturn(new Pair<>(0L, HashCode.fromInt(0)))
.anyTimes();
// Populate the metadata that should be read from disk.
OnDiskBuildInfo onDiskBuildInfo = new FakeOnDiskBuildInfo();
// This metadata must be added to the buildInfoRecorder so that it is written as part of
// writeMetadataToDisk().
buildInfoRecorder.addMetadata(
CachingBuildEngine.ABI_KEY_FOR_DEPS_ON_DISK_METADATA,
TestAbstractCachingBuildRule.ABI_KEY_FOR_DEPS_HASH);
// These methods should be invoked after the rule is built locally.
buildInfoRecorder.writeMetadataToDisk(/* clearExistingMetadata */ true);
buildInfoRecorder.performUploadToArtifactCache(
ImmutableSet.of(buildRule.getRuleKey()),
artifactCache,
buckEventBus);
expectLastCall().andAnswer(
new IAnswer<Object>() {
@Override
public Object answer() throws Throwable {
Thread.sleep(500);
return null;
}
});
ListeningExecutorService service = listeningDecorator(Executors.newFixedThreadPool(2));
expect(buildContext.createOnDiskBuildInfoFor(buildTarget)).andReturn(onDiskBuildInfo);
expect(buildContext.getStepRunner()).andReturn(createStepRunner(null));
expect(buildContext.getEventBus()).andReturn(buckEventBus).anyTimes();
replayAll();
CachingBuildEngine cachingBuildEngine =
new CachingBuildEngine(
service,
CachingBuildEngine.BuildMode.SHALLOW,
NOOP_RULE_KEY_FACTORY);
ListenableFuture<BuildResult> buildResult = cachingBuildEngine.build(buildContext, buildRule);
BuildResult result = buildResult.get();
assertEquals(BuildRuleSuccessType.BUILT_LOCALLY, result.getSuccess());
assertTrue(service.shutdownNow().isEmpty());
List<BuckEvent> events = listener.getEvents();
assertThat(events, Matchers.hasSize(6));
Iterator<BuckEvent> eventIter = events.iterator();
assertEquals(
configureTestEvent(BuildRuleEvent.started(buildRule), buckEventBus).getEventName(),
eventIter.next().getEventName());
assertEquals(
configureTestEvent(BuildRuleEvent.suspended(buildRule), buckEventBus).getEventName(),
eventIter.next().getEventName());
assertEquals(
configureTestEvent(BuildRuleEvent.resumed(buildRule), buckEventBus).getEventName(),
eventIter.next().getEventName());
assertEquals(
configureTestEvent(BuildRuleEvent.suspended(buildRule), buckEventBus).getEventName(),
eventIter.next().getEventName());
assertEquals(
configureTestEvent(BuildRuleEvent.resumed(buildRule), buckEventBus).getEventName(),
eventIter.next().getEventName());
assertEquals(
configureTestEvent(
BuildRuleEvent.finished(
buildRule,
BuildRuleStatus.SUCCESS,
CacheResult.miss(),
Optional.of(BuildRuleSuccessType.BUILT_LOCALLY),
Optional.<HashCode>absent(),
Optional.<Long>absent()),
buckEventBus)
.getEventName(),
eventIter.next().getEventName());
verifyAll();
}
@Test
public void testArtifactFetchedFromCache()
throws InterruptedException, ExecutionException, IOException {
Step step = new AbstractExecutionStep("exploding step") {
@Override
public int execute(ExecutionContext context) {
throw new UnsupportedOperationException("build step should not be executed");
}
};
BuildRule buildRule = createRule(
new SourcePathResolver(new BuildRuleResolver()),
/* deps */ ImmutableSet.<BuildRule>of(),
ImmutableList.of(step),
/* postBuildSteps */ ImmutableList.<Step>of(),
/* pathToOutputFile */ null);
StepRunner stepRunner = createStepRunner();
// Simulate successfully fetching the output file from the ArtifactCache.
ArtifactCache artifactCache = createMock(ArtifactCache.class);
Map<String, String> desiredZipEntries = ImmutableMap.of(
"buck-out/gen/src/com/facebook/orca/orca.jar",
"Imagine this is the contents of a valid JAR file.");
expect(
artifactCache.fetch(
eq(buildRule.getRuleKey()),
isA(File.class)))
.andDelegateTo(
new FakeArtifactCacheThatWritesAZipFile(desiredZipEntries));
FakeProjectFilesystem filesystem = new FakeProjectFilesystem();
BuckEventBus buckEventBus = BuckEventBusFactory.newInstance();
BuildContext buildContext = ImmutableBuildContext.builder()
.setActionGraph(RuleMap.createGraphFromSingleRule(buildRule))
.setStepRunner(stepRunner)
.setProjectFilesystem(filesystem)
.setClock(new DefaultClock())
.setBuildId(new BuildId())
.setArtifactCache(artifactCache)
.setJavaPackageFinder(createMock(JavaPackageFinder.class))
.setEventBus(buckEventBus)
.build();
// Build the rule!
replayAll();
CachingBuildEngine cachingBuildEngine =
new CachingBuildEngine(
MoreExecutors.newDirectExecutorService(),
CachingBuildEngine.BuildMode.SHALLOW,
NOOP_RULE_KEY_FACTORY);
ListenableFuture<BuildResult> buildResult = cachingBuildEngine.build(buildContext, buildRule);
buckEventBus.post(CommandEvent.finished("build", ImmutableList.<String>of(), false, 0));
verifyAll();
assertTrue(
"We expect build() to be synchronous in this case, " +
"so the future should already be resolved.",
MoreFutures.isSuccess(buildResult));
BuildResult result = buildResult.get();
assertEquals(BuildRuleSuccessType.FETCHED_FROM_CACHE, result.getSuccess());
assertTrue(
((BuildableAbstractCachingBuildRule) buildRule).isInitializedFromDisk());
assertTrue(
"The entries in the zip should be extracted as a result of building the rule.",
filesystem.exists(Paths.get("buck-out/gen/src/com/facebook/orca/orca.jar")));
}
@Test
public void testArtifactFetchedFromCacheStillRunsPostBuildSteps()
throws InterruptedException, ExecutionException, IOException {
BuckEventBus buckEventBus = BuckEventBusFactory.newInstance();
StepRunner stepRunner = createStepRunner(buckEventBus);
// Add a post build step so we can verify that it's steps are executed.
Step buildStep = createMock(Step.class);
expect(buildStep.getDescription(anyObject(ExecutionContext.class)))
.andReturn("Some Description")
.anyTimes();
expect(buildStep.getShortName()).andReturn("Some Short Name").anyTimes();
expect(buildStep.execute(anyObject(ExecutionContext.class))).andReturn(0);
BuildRule buildRule = createRule(
new SourcePathResolver(new BuildRuleResolver()),
/* deps */ ImmutableSet.<BuildRule>of(),
/* buildSteps */ ImmutableList.<Step>of(),
/* postBuildSteps */ ImmutableList.of(buildStep),
/* pathToOutputFile */ null);
// Simulate successfully fetching the output file from the ArtifactCache.
ArtifactCache artifactCache = createMock(ArtifactCache.class);
Map<String, String> desiredZipEntries = ImmutableMap.of(
"buck-out/gen/src/com/facebook/orca/orca.jar",
"Imagine this is the contents of a valid JAR file.");
expect(
artifactCache.fetch(
eq(buildRule.getRuleKey()),
isA(File.class)))
.andDelegateTo(
new FakeArtifactCacheThatWritesAZipFile(desiredZipEntries));
FakeProjectFilesystem filesystem = new FakeProjectFilesystem();
BuildContext buildContext = ImmutableBuildContext.builder()
.setActionGraph(RuleMap.createGraphFromSingleRule(buildRule))
.setStepRunner(stepRunner)
.setProjectFilesystem(filesystem)
.setClock(new DefaultClock())
.setBuildId(new BuildId())
.setArtifactCache(artifactCache)
.setJavaPackageFinder(createMock(JavaPackageFinder.class))
.setEventBus(buckEventBus)
.build();
// Build the rule!
replayAll();
CachingBuildEngine cachingBuildEngine =
new CachingBuildEngine(
MoreExecutors.newDirectExecutorService(),
CachingBuildEngine.BuildMode.SHALLOW,
NOOP_RULE_KEY_FACTORY);
ListenableFuture<BuildResult> buildResult = cachingBuildEngine.build(buildContext, buildRule);
buckEventBus.post(CommandEvent.finished("build", ImmutableList.<String>of(), false, 0));
verifyAll();
BuildResult result = buildResult.get();
assertEquals(BuildRuleSuccessType.FETCHED_FROM_CACHE, result.getSuccess());
assertTrue(
((BuildableAbstractCachingBuildRule) buildRule).isInitializedFromDisk());
assertTrue(
"The entries in the zip should be extracted as a result of building the rule.",
filesystem.exists(Paths.get("buck-out/gen/src/com/facebook/orca/orca.jar")));
}
@Test
public void testMatchingTopLevelRuleKeyAvoidsProcessingDepInShallowMode() throws Exception {
BuildRuleResolver resolver = new BuildRuleResolver();
SourcePathResolver pathResolver = new SourcePathResolver(resolver);
ArtifactCache cache = new NoopArtifactCache();
// The EventBus should be updated with events indicating how the rule was built.
BuckEventBus buckEventBus = BuckEventBusFactory.newInstance();
FakeBuckEventListener listener = new FakeBuckEventListener();
buckEventBus.register(listener);
// Create a dep for the build rule.
BuildTarget depTarget = BuildTargetFactory.newInstance("//src/com/facebook/orca:lib");
FakeBuildRule dep = new FakeBuildRule(depTarget, pathResolver);
dep.setRuleKey(new RuleKey("aaaa"));
FakeBuildRule ruleToTest = new FakeBuildRule(buildTarget, pathResolver, dep);
ruleToTest.setRuleKey(new RuleKey("bbbb"));
// The BuildContext that will be used by the rule's build() method.
BuildContext context = createMock(BuildContext.class);
expect(context.getArtifactCache()).andReturn(cache).anyTimes();
expect(context.getEventBus()).andReturn(buckEventBus).anyTimes();
expect(context.getStepRunner()).andReturn(createStepRunner(buckEventBus)).anyTimes();
expect(context.createOnDiskBuildInfoFor(buildTarget))
.andReturn(new FakeOnDiskBuildInfo().setRuleKey(ruleToTest.getRuleKey()));
BuildInfoRecorder buildInfoRecorder = createNiceMock(BuildInfoRecorder.class);
expect(buildInfoRecorder.getOutputSizeAndHash(anyObject(HashFunction.class)))
.andReturn(new Pair<>(0L, HashCode.fromInt(0)))
.anyTimes();
Capture<RuleKey> ruleKeyForRecorder = newCapture();
expect(
context.createBuildInfoRecorder(
eq(buildTarget),
capture(ruleKeyForRecorder),
/* ruleKeyWithoutDepsForRecorder */ anyObject(RuleKey.class)))
.andReturn(buildInfoRecorder);
// Create the build engine.
CachingBuildEngine cachingBuildEngine =
new CachingBuildEngine(
MoreExecutors.newDirectExecutorService(),
CachingBuildEngine.BuildMode.SHALLOW,
NOOP_RULE_KEY_FACTORY);
// Run the build.
replayAll();
BuildResult result = cachingBuildEngine.build(context, ruleToTest).get();
assertEquals(BuildRuleSuccessType.MATCHING_RULE_KEY, result.getSuccess());
verifyAll();
// Verify the events logged to the BuckEventBus.
List<BuckEvent> events = listener.getEvents();
assertThat(events, Matchers.hasSize(6));
Iterator<BuckEvent> eventIter = events.iterator();
assertEquals(
configureTestEvent(BuildRuleEvent.started(dep), buckEventBus),
eventIter.next());
assertEquals(
configureTestEvent(BuildRuleEvent.suspended(dep), buckEventBus),
eventIter.next());
assertEquals(
configureTestEvent(BuildRuleEvent.started(ruleToTest), buckEventBus),
eventIter.next());
assertEquals(
configureTestEvent(BuildRuleEvent.suspended(ruleToTest), buckEventBus),
eventIter.next());
assertEquals(
configureTestEvent(BuildRuleEvent.resumed(ruleToTest), buckEventBus),
eventIter.next());
assertEquals(
configureTestEvent(
BuildRuleEvent.finished(
ruleToTest,
BuildRuleStatus.SUCCESS,
CacheResult.localKeyUnchangedHit(),
Optional.of(BuildRuleSuccessType.MATCHING_RULE_KEY),
Optional.<HashCode>absent(),
Optional.<Long>absent()),
buckEventBus),
eventIter.next());
}
@Test
public void testMatchingTopLevelRuleKeyStillProcessesDepInDeepMode() throws Exception {
BuildRuleResolver resolver = new BuildRuleResolver();
SourcePathResolver pathResolver = new SourcePathResolver(resolver);
ArtifactCache cache = new NoopArtifactCache();
// The EventBus should be updated with events indicating how the rule was built.
BuckEventBus buckEventBus = BuckEventBusFactory.newInstance();
FakeBuckEventListener listener = new FakeBuckEventListener();
buckEventBus.register(listener);
// Create a dep for the build rule.
BuildTarget depTarget = BuildTargetFactory.newInstance("//src/com/facebook/orca:lib");
FakeBuildRule dep = new FakeBuildRule(depTarget, pathResolver);
dep.setRuleKey(new RuleKey("aaaa"));
FakeBuildRule ruleToTest = new FakeBuildRule(buildTarget, pathResolver, dep);
ruleToTest.setRuleKey(new RuleKey("bbbb"));
// The BuildContext that will be used by the rule's build() method.
BuildContext context = createMock(BuildContext.class);
expect(context.getArtifactCache()).andReturn(cache).anyTimes();
expect(context.getEventBus()).andReturn(buckEventBus).anyTimes();
expect(context.getStepRunner()).andReturn(createStepRunner(buckEventBus)).anyTimes();
expect(context.createOnDiskBuildInfoFor(buildTarget))
.andReturn(new FakeOnDiskBuildInfo().setRuleKey(ruleToTest.getRuleKey()));
expect(context.createOnDiskBuildInfoFor(dep.getBuildTarget()))
.andReturn(new FakeOnDiskBuildInfo().setRuleKey(dep.getRuleKey()));
BuildInfoRecorder buildInfoRecorder = createNiceMock(BuildInfoRecorder.class);
expect(buildInfoRecorder.getOutputSizeAndHash(anyObject(HashFunction.class)))
.andReturn(new Pair<>(0L, HashCode.fromInt(0)))
.anyTimes();
expect(
context.createBuildInfoRecorder(
anyObject(BuildTarget.class),
anyObject(RuleKey.class),
/* ruleKeyWithoutDepsForRecorder */ anyObject(RuleKey.class)))
.andReturn(buildInfoRecorder)
.anyTimes();
// Create the build engine.
CachingBuildEngine cachingBuildEngine =
new CachingBuildEngine(
MoreExecutors.newDirectExecutorService(),
CachingBuildEngine.BuildMode.DEEP,
NOOP_RULE_KEY_FACTORY);
// Run the build.
replayAll();
BuildResult result = cachingBuildEngine.build(context, ruleToTest).get();
assertEquals(BuildRuleSuccessType.MATCHING_RULE_KEY, result.getSuccess());
verifyAll();
// Verify the events logged to the BuckEventBus.
List<BuckEvent> events = listener.getEvents();
assertThat(events, Matchers.hasSize(8));
Iterator<BuckEvent> eventIter = events.iterator();
assertEquals(
configureTestEvent(BuildRuleEvent.started(dep), buckEventBus),
eventIter.next());
assertEquals(
configureTestEvent(BuildRuleEvent.suspended(dep), buckEventBus),
eventIter.next());
assertEquals(
configureTestEvent(BuildRuleEvent.started(ruleToTest), buckEventBus),
eventIter.next());
assertEquals(
configureTestEvent(BuildRuleEvent.suspended(ruleToTest), buckEventBus),
eventIter.next());
assertEquals(
configureTestEvent(BuildRuleEvent.resumed(ruleToTest), buckEventBus),
eventIter.next());
assertEquals(
configureTestEvent(BuildRuleEvent.resumed(dep), buckEventBus),
eventIter.next());
assertEquals(
configureTestEvent(
BuildRuleEvent.finished(
dep,
BuildRuleStatus.SUCCESS,
CacheResult.localKeyUnchangedHit(),
Optional.of(BuildRuleSuccessType.MATCHING_RULE_KEY),
Optional.<HashCode>absent(),
Optional.<Long>absent()),
buckEventBus),
eventIter.next());
assertEquals(
configureTestEvent(
BuildRuleEvent.finished(
ruleToTest,
BuildRuleStatus.SUCCESS,
CacheResult.localKeyUnchangedHit(),
Optional.of(BuildRuleSuccessType.MATCHING_RULE_KEY),
Optional.<HashCode>absent(),
Optional.<Long>absent()),
buckEventBus),
eventIter.next());
}
@Test
public void testMatchingTopLevelRuleKeyStillProcessesRuntimeDeps() throws Exception {
BuildRuleResolver resolver = new BuildRuleResolver();
SourcePathResolver pathResolver = new SourcePathResolver(resolver);
ArtifactCache cache = new NoopArtifactCache();
// The EventBus should be updated with events indicating how the rule was built.
BuckEventBus buckEventBus = BuckEventBusFactory.newInstance();
FakeBuckEventListener listener = new FakeBuckEventListener();
buckEventBus.register(listener);
// Setup a runtime dependency that is found transitively from the top-level rule.
FakeBuildRule transitiveRuntimeDep =
new FakeBuildRule(
BuildTargetFactory.newInstance("//:transitive_dep"),
pathResolver);
transitiveRuntimeDep.setRuleKey(new RuleKey("aaaa"));
// Setup a runtime dependency that is referenced directly by the top-level rule.
FakeBuildRule runtimeDep =
new FakeHasRuntimeDeps(
BuildTargetFactory.newInstance("//:runtime_dep"),
pathResolver,
transitiveRuntimeDep);
runtimeDep.setRuleKey(new RuleKey("bbbb"));
// Create a dep for the build rule.
FakeBuildRule ruleToTest = new FakeHasRuntimeDeps(buildTarget, pathResolver, runtimeDep);
ruleToTest.setRuleKey(new RuleKey("cccc"));
// The BuildContext that will be used by the rule's build() method.
BuildContext context = createNiceMock(BuildContext.class);
expect(context.getArtifactCache()).andReturn(cache).anyTimes();
expect(context.getEventBus()).andReturn(buckEventBus).anyTimes();
expect(context.getStepRunner()).andReturn(createStepRunner(buckEventBus)).anyTimes();
expect(context.createOnDiskBuildInfoFor(buildTarget))
.andReturn(new FakeOnDiskBuildInfo().setRuleKey(ruleToTest.getRuleKey()))
.anyTimes();
expect(context.createOnDiskBuildInfoFor(runtimeDep.getBuildTarget()))
.andReturn(new FakeOnDiskBuildInfo().setRuleKey(runtimeDep.getRuleKey()))
.anyTimes();
expect(context.createOnDiskBuildInfoFor(transitiveRuntimeDep.getBuildTarget()))
.andReturn(new FakeOnDiskBuildInfo().setRuleKey(transitiveRuntimeDep.getRuleKey()))
.anyTimes();
BuildInfoRecorder buildInfoRecorder = createNiceMock(BuildInfoRecorder.class);
expect(buildInfoRecorder.getOutputSizeAndHash(anyObject(HashFunction.class)))
.andReturn(new Pair<>(0L, HashCode.fromInt(0)))
.anyTimes();
expect(
context.createBuildInfoRecorder(
anyObject(BuildTarget.class),
anyObject(RuleKey.class),
/* ruleKeyWithoutDepsForRecorder */ anyObject(RuleKey.class)))
.andReturn(buildInfoRecorder)
.anyTimes();
// Create the build engine.
CachingBuildEngine cachingBuildEngine =
new CachingBuildEngine(
MoreExecutors.newDirectExecutorService(),
CachingBuildEngine.BuildMode.SHALLOW,
NOOP_RULE_KEY_FACTORY);
// Run the build.
replayAll();
BuildResult result = cachingBuildEngine.build(context, ruleToTest).get();
assertEquals(BuildRuleSuccessType.MATCHING_RULE_KEY, result.getSuccess());
verifyAll();
// Verify the events logged to the BuckEventBus.
List<BuckEvent> events = listener.getEvents();
assertThat(events, Matchers.hasSize(12));
Iterator<BuckEvent> eventIter = events.iterator();
assertEquals(
configureTestEvent(BuildRuleEvent.started(ruleToTest), buckEventBus),
eventIter.next());
assertEquals(
configureTestEvent(BuildRuleEvent.suspended(ruleToTest), buckEventBus),
eventIter.next());
assertEquals(
configureTestEvent(BuildRuleEvent.resumed(ruleToTest), buckEventBus),
eventIter.next());
assertEquals(
configureTestEvent(
BuildRuleEvent.finished(
ruleToTest,
BuildRuleStatus.SUCCESS,
CacheResult.localKeyUnchangedHit(),
Optional.of(BuildRuleSuccessType.MATCHING_RULE_KEY),
Optional.<HashCode>absent(),
Optional.<Long>absent()),
buckEventBus),
eventIter.next());
assertEquals(
configureTestEvent(BuildRuleEvent.started(runtimeDep), buckEventBus),
eventIter.next());
assertEquals(
configureTestEvent(BuildRuleEvent.suspended(runtimeDep), buckEventBus),
eventIter.next());
assertEquals(
configureTestEvent(BuildRuleEvent.resumed(runtimeDep), buckEventBus),
eventIter.next());
assertEquals(
configureTestEvent(
BuildRuleEvent.finished(
runtimeDep,
BuildRuleStatus.SUCCESS,
CacheResult.localKeyUnchangedHit(),
Optional.of(BuildRuleSuccessType.MATCHING_RULE_KEY),
Optional.<HashCode>absent(),
Optional.<Long>absent()),
buckEventBus),
eventIter.next());
assertEquals(
configureTestEvent(BuildRuleEvent.started(transitiveRuntimeDep), buckEventBus),
eventIter.next());
assertEquals(
configureTestEvent(BuildRuleEvent.suspended(transitiveRuntimeDep), buckEventBus),
eventIter.next());
assertEquals(
configureTestEvent(BuildRuleEvent.resumed(transitiveRuntimeDep), buckEventBus),
eventIter.next());
assertEquals(
configureTestEvent(
BuildRuleEvent.finished(
transitiveRuntimeDep,
BuildRuleStatus.SUCCESS,
CacheResult.localKeyUnchangedHit(),
Optional.of(BuildRuleSuccessType.MATCHING_RULE_KEY),
Optional.<HashCode>absent(),
Optional.<Long>absent()),
buckEventBus),
eventIter.next());
}
@Test
public void matchingRuleKeyDoesNotRunPostBuildSteps() throws Exception {
ArtifactCache cache = new NoopArtifactCache();
// The EventBus should be updated with events indicating how the rule was built.
BuckEventBus buckEventBus = BuckEventBusFactory.newInstance();
FakeBuckEventListener listener = new FakeBuckEventListener();
buckEventBus.register(listener);
// Add a post build step so we can verify that it's steps are executed.
Step failingStep =
new AbstractExecutionStep("test") {
@Override
public int execute(ExecutionContext context) throws IOException {
return 1;
}
};
BuildRule ruleToTest = createRule(
new SourcePathResolver(new BuildRuleResolver()),
/* deps */ ImmutableSet.<BuildRule>of(),
/* buildSteps */ ImmutableList.<Step>of(),
/* postBuildSteps */ ImmutableList.of(failingStep),
/* pathToOutputFile */ null);
// The BuildContext that will be used by the rule's build() method.
BuildContext context = createNiceMock(BuildContext.class);
expect(context.getArtifactCache()).andReturn(cache).anyTimes();
expect(context.getEventBus()).andReturn(buckEventBus).anyTimes();
expect(context.getStepRunner()).andReturn(createStepRunner(buckEventBus)).anyTimes();
expect(context.createOnDiskBuildInfoFor(buildTarget))
.andReturn(new FakeOnDiskBuildInfo().setRuleKey(ruleToTest.getRuleKey()))
.anyTimes();
BuildInfoRecorder buildInfoRecorder = createNiceMock(BuildInfoRecorder.class);
expect(buildInfoRecorder.getOutputSizeAndHash(anyObject(HashFunction.class)))
.andReturn(new Pair<>(0L, HashCode.fromInt(0)))
.anyTimes();
expect(
context.createBuildInfoRecorder(
anyObject(BuildTarget.class),
anyObject(RuleKey.class),
/* ruleKeyWithoutDepsForRecorder */ anyObject(RuleKey.class)))
.andReturn(buildInfoRecorder)
.anyTimes();
// Create the build engine.
CachingBuildEngine cachingBuildEngine =
new CachingBuildEngine(
MoreExecutors.newDirectExecutorService(),
CachingBuildEngine.BuildMode.SHALLOW,
NOOP_RULE_KEY_FACTORY);
// Run the build.
replayAll();
BuildResult result = cachingBuildEngine.build(context, ruleToTest).get();
assertEquals(BuildRuleSuccessType.MATCHING_RULE_KEY, result.getSuccess());
verifyAll();
}
@Test
public void testBuildRuleLocallyWithCacheError() throws Exception {
SourcePathResolver resolver = new SourcePathResolver(new BuildRuleResolver());
ProjectFilesystem filesystem = new FakeProjectFilesystem();
// Create an artifact cache that always errors out.
ArtifactCache cache =
new NoopArtifactCache() {
@Override
public CacheResult fetch(RuleKey ruleKey, File output) {
return CacheResult.error("cache", "error");
}
};
// Use the artifact cache when running a simple rule that will build locally.
BuildContext buildContext =
FakeBuildContext.newBuilder(filesystem)
.setArtifactCache(cache)
.setJavaPackageFinder(new FakeJavaPackageFinder())
.setActionGraph(new ActionGraph(ImmutableList.<BuildRule>of()))
.build();
BuildRule rule =
new NoopBuildRule(
BuildRuleParamsFactory.createTrivialBuildRuleParams(
BuildTargetFactory.newInstance("//:rule")),
resolver);
CachingBuildEngine cachingBuildEngine =
new CachingBuildEngine(
MoreExecutors.newDirectExecutorService(),
CachingBuildEngine.BuildMode.SHALLOW,
NOOP_RULE_KEY_FACTORY);
BuildResult result = cachingBuildEngine.build(buildContext, rule).get();
assertThat(result.getSuccess(), Matchers.equalTo(BuildRuleSuccessType.BUILT_LOCALLY));
assertThat(result.getCacheResult().getType(), Matchers.equalTo(CacheResult.Type.ERROR));
}
@Test
public void inputBasedRuleKeyAndArtifactAreWrittenForSupportedRules() throws Exception {
FakeProjectFilesystem filesystem = new FakeProjectFilesystem();
InMemoryArtifactCache cache = new InMemoryArtifactCache();
BuildContext buildContext =
FakeBuildContext.newBuilder(filesystem)
.setArtifactCache(cache)
.setJavaPackageFinder(new FakeJavaPackageFinder())
.setActionGraph(new ActionGraph(ImmutableList.<BuildRule>of()))
.build();
// Create a simple rule which just writes a file.
BuildTarget target = BuildTargetFactory.newInstance("//:rule");
BuildRuleParams params =
new FakeBuildRuleParamsBuilder(target)
.setProjectFilesystem(filesystem)
.build();
BuildRuleResolver resolver = new BuildRuleResolver();
SourcePathResolver pathResolver = new SourcePathResolver(resolver);
RuleKey inputRuleKey = new RuleKey("aaaa");
final Path output = Paths.get("output");
BuildRule rule =
new InputRuleKeyBuildRule(params, pathResolver) {
@Override
public ImmutableList<Step> getBuildSteps(
BuildContext context,
BuildableContext buildableContext) {
return ImmutableList.<Step>of(new WriteFileStep("", output));
}
@Override
public Path getPathToOutput() {
return output;
}
};
// Create the build engine.
CachingBuildEngine cachingBuildEngine =
new CachingBuildEngine(
MoreExecutors.newDirectExecutorService(),
CachingBuildEngine.BuildMode.SHALLOW,
new FixedRuleKeyBuilderFactory(ImmutableMap.of(rule.getBuildTarget(), inputRuleKey)));
// Run the build.
BuildResult result = cachingBuildEngine.build(buildContext, rule).get();
assertEquals(BuildRuleSuccessType.BUILT_LOCALLY, result.getSuccess());
// Verify that the artifact was indexed in the cache by the input rule key.
Optional<byte[]> artifact = cache.getArtifact(inputRuleKey);
assertTrue(artifact.isPresent());
// Verify the input rule key was written to disk.
OnDiskBuildInfo onDiskBuildInfo = buildContext.createOnDiskBuildInfoFor(target);
assertThat(
onDiskBuildInfo.getRuleKey(BuildInfo.METADATA_KEY_FOR_INPUT_BASED_RULE_KEY),
Matchers.equalTo(Optional.of(inputRuleKey)));
}
@Test
public void inputBasedRuleKeyMatchAvoidsBuildingLocally() throws Exception {
FakeProjectFilesystem filesystem = new FakeProjectFilesystem();
InMemoryArtifactCache cache = new InMemoryArtifactCache();
BuildContext buildContext =
FakeBuildContext.newBuilder(filesystem)
.setArtifactCache(cache)
.setJavaPackageFinder(new FakeJavaPackageFinder())
.setActionGraph(new ActionGraph(ImmutableList.<BuildRule>of()))
.build();
// Create a simple rule which just writes a file.
BuildTarget target = BuildTargetFactory.newInstance("//:rule");
BuildRuleParams params =
new FakeBuildRuleParamsBuilder(target)
.setProjectFilesystem(filesystem)
.build();
BuildRuleResolver resolver = new BuildRuleResolver();
SourcePathResolver pathResolver = new SourcePathResolver(resolver);
RuleKey inputRuleKey = new RuleKey("aaaa");
final Path output = Paths.get("output");
BuildRule rule =
new InputRuleKeyBuildRule(params, pathResolver) {
@Override
public ImmutableList<Step> getBuildSteps(
BuildContext context,
BuildableContext buildableContext) {
return ImmutableList.<Step>of(
new AbstractExecutionStep("false") {
@Override
public int execute(ExecutionContext context) {
return 1;
}
});
}
@Override
public Path getPathToOutput() {
return output;
}
};
// Prepopulate the input rule key on disk, so that we avoid a rebuild.
filesystem.writeContentsToPath(
inputRuleKey.toString(),
BuildInfo.getPathToMetadataDirectory(target)
.resolve(BuildInfo.METADATA_KEY_FOR_INPUT_BASED_RULE_KEY));
// Create the build engine.
CachingBuildEngine cachingBuildEngine =
new CachingBuildEngine(
MoreExecutors.newDirectExecutorService(),
CachingBuildEngine.BuildMode.SHALLOW,
new FixedRuleKeyBuilderFactory(ImmutableMap.of(rule.getBuildTarget(), inputRuleKey)));
// Run the build.
BuildResult result = cachingBuildEngine.build(buildContext, rule).get();
assertEquals(BuildRuleSuccessType.MATCHING_INPUT_BASED_RULE_KEY, result.getSuccess());
// Verify the actual rule key was updated on disk.
OnDiskBuildInfo onDiskBuildInfo = buildContext.createOnDiskBuildInfoFor(target);
assertThat(
onDiskBuildInfo.getRuleKey(BuildInfo.METADATA_KEY_FOR_RULE_KEY),
Matchers.equalTo(Optional.of(rule.getRuleKey())));
}
@Test
public void inputBasedRuleKeyCacheHitAvoidsBuildingLocally() throws Exception {
FakeProjectFilesystem filesystem = new FakeProjectFilesystem();
InMemoryArtifactCache cache = new InMemoryArtifactCache();
BuildContext buildContext =
FakeBuildContext.newBuilder(filesystem)
.setArtifactCache(cache)
.setJavaPackageFinder(new FakeJavaPackageFinder())
.setActionGraph(new ActionGraph(ImmutableList.<BuildRule>of()))
.build();
// Create a simple rule which just writes a file.
BuildTarget target = BuildTargetFactory.newInstance("//:rule");
RuleKey inputRuleKey = new RuleKey("aaaa");
BuildRuleParams params =
new FakeBuildRuleParamsBuilder(target)
.setProjectFilesystem(filesystem)
.build();
BuildRuleResolver resolver = new BuildRuleResolver();
SourcePathResolver pathResolver = new SourcePathResolver(resolver);
final Path output = Paths.get("output");
BuildRule rule =
new InputRuleKeyBuildRule(params, pathResolver) {
@Override
public ImmutableList<Step> getBuildSteps(
BuildContext context,
BuildableContext buildableContext) {
return ImmutableList.<Step>of(
new AbstractExecutionStep("false") {
@Override
public int execute(ExecutionContext context) {
return 1;
}
});
}
@Override
public Path getPathToOutput() {
return output;
}
};
// Prepopulate the cache with an artifact indexed by the input-based rule key.
File temp = File.createTempFile("artifact", ".zip");
writeEntriesToZip(
temp,
ImmutableMap.of(
BuildInfo.getPathToMetadataDirectory(target)
.resolve(BuildInfo.METADATA_KEY_FOR_RULE_KEY)
.toString(),
// Store a stale rule key, to verify it gets overwritten with the correct one.
new RuleKey("bbbb").toString(),
BuildInfo.getPathToMetadataDirectory(target)
.resolve(BuildInfo.METADATA_KEY_FOR_INPUT_BASED_RULE_KEY)
.toString(),
inputRuleKey.toString(),
output.toString(),
""));
cache.putArtifact(inputRuleKey, Files.readAllBytes(temp.toPath()));
// Create the build engine.
CachingBuildEngine cachingBuildEngine =
new CachingBuildEngine(
MoreExecutors.newDirectExecutorService(),
CachingBuildEngine.BuildMode.SHALLOW,
new FixedRuleKeyBuilderFactory(ImmutableMap.of(rule.getBuildTarget(), inputRuleKey)));
// Run the build.
BuildResult result = cachingBuildEngine.build(buildContext, rule).get();
assertEquals(BuildRuleSuccessType.FETCHED_FROM_CACHE_INPUT_BASED, result.getSuccess());
// Verify the input-based and actual rule keys were updated on disk.
OnDiskBuildInfo onDiskBuildInfo = buildContext.createOnDiskBuildInfoFor(target);
assertThat(
onDiskBuildInfo.getRuleKey(BuildInfo.METADATA_KEY_FOR_RULE_KEY),
Matchers.equalTo(Optional.of(rule.getRuleKey())));
assertThat(
onDiskBuildInfo.getRuleKey(BuildInfo.METADATA_KEY_FOR_INPUT_BASED_RULE_KEY),
Matchers.equalTo(Optional.of(inputRuleKey)));
}
// TODO(mbolin): Test that when the success files match, nothing is built and nothing is written
// back to the cache.
// TODO(mbolin): Test that when the value in the success file does not agree with the current
// value, the rule is rebuilt and the result is written back to the cache.
// TODO(mbolin): Test that a failure when executing the build steps is propagated appropriately.
// TODO(mbolin): Test what happens when the cache's methods throw an exception.
private BuildRule createRule(
SourcePathResolver resolver,
ImmutableSet<BuildRule> deps,
List<Step> buildSteps,
ImmutableList<Step> postBuildSteps,
@Nullable String pathToOutputFile) {
Comparator<BuildRule> comparator = RetainOrderComparator.createComparator(deps);
ImmutableSortedSet<BuildRule> sortedDeps = ImmutableSortedSet.copyOf(comparator, deps);
final FileHashCache fileHashCache = FakeFileHashCache.createFromStrings(ImmutableMap.of(
"/dev/null", "ae8c0f860a0ecad94ecede79b69460434eddbfbc"));
BuildRuleParams buildRuleParams = new FakeBuildRuleParamsBuilder(buildTarget)
.setDeps(sortedDeps)
.setFileHashCache(fileHashCache)
.build();
return new BuildableAbstractCachingBuildRule(
buildRuleParams,
resolver,
pathToOutputFile,
buildSteps,
postBuildSteps);
}
private static class BuildableAbstractCachingBuildRule extends AbstractBuildRule
implements HasPostBuildSteps, InitializableFromDisk<Object> {
private final Path pathToOutputFile;
private final List<Step> buildSteps;
private final ImmutableList<Step> postBuildSteps;
private final BuildOutputInitializer<Object> buildOutputInitializer;
private boolean isInitializedFromDisk = false;
private BuildableAbstractCachingBuildRule(
BuildRuleParams params,
SourcePathResolver resolver,
@Nullable String pathToOutputFile,
List<Step> buildSteps,
ImmutableList<Step> postBuildSteps) {
super(params, resolver);
this.pathToOutputFile = pathToOutputFile == null ? null : Paths.get(pathToOutputFile);
this.buildSteps = buildSteps;
this.postBuildSteps = postBuildSteps;
this.buildOutputInitializer =
new BuildOutputInitializer<>(params.getBuildTarget(), this);
}
@Override
@Nullable
public Path getPathToOutput() {
return pathToOutputFile;
}
@Override
public ImmutableList<Step> getBuildSteps(
BuildContext context,
BuildableContext buildableContext) {
if (pathToOutputFile != null) {
buildableContext.recordArtifact(pathToOutputFile);
}
return ImmutableList.copyOf(buildSteps);
}
@Override
public ImmutableList<Step> getPostBuildSteps(
BuildContext context,
BuildableContext buildableContext) {
return postBuildSteps;
}
@Override
public Object initializeFromDisk(OnDiskBuildInfo onDiskBuildInfo) {
isInitializedFromDisk = true;
return new Object();
}
@Override
public BuildOutputInitializer<Object> getBuildOutputInitializer() {
return buildOutputInitializer;
}
public boolean isInitializedFromDisk() {
return isInitializedFromDisk;
}
}
/**
* {@link AbstractBuildRule} that implements {@link AbiRule}.
*/
private static class TestAbstractCachingBuildRule extends AbstractBuildRule
implements AbiRule, BuildRule, InitializableFromDisk<Object> {
private static final String RULE_KEY_HASH = "bfcd53a794e7c732019e04e08b30b32e26e19d50";
private static final String RULE_KEY_WITHOUT_DEPS_HASH =
"efd7d450d9f1c3d9e43392dec63b1f31692305b9";
private static final String ABI_KEY_FOR_DEPS_HASH = "92d6de0a59080284055bcde5d2923f144b216a59";
private boolean isAbiLoadedFromDisk = false;
private final BuildOutputInitializer<Object> buildOutputInitializer;
TestAbstractCachingBuildRule(BuildRuleParams buildRuleParams, SourcePathResolver resolver) {
super(buildRuleParams, resolver);
this.buildOutputInitializer =
new BuildOutputInitializer<>(buildRuleParams.getBuildTarget(), this);
}
@Override
public ImmutableList<Step> getBuildSteps(
BuildContext context,
BuildableContext buildableContext) {
throw new UnsupportedOperationException("method should not be called");
}
@Nullable
@Override
public Path getPathToOutput() {
return null;
}
@Override
public RuleKey getRuleKey() {
return new RuleKey(RULE_KEY_HASH);
}
@Override
public RuleKey getRuleKeyWithoutDeps() {
return new RuleKey(RULE_KEY_WITHOUT_DEPS_HASH);
}
@Override
public Object initializeFromDisk(OnDiskBuildInfo onDiskBuildInfo) {
isAbiLoadedFromDisk = true;
return new Object();
}
@Override
public BuildOutputInitializer<Object> getBuildOutputInitializer() {
return buildOutputInitializer;
}
public boolean isAbiLoadedFromDisk() {
return isAbiLoadedFromDisk;
}
@Override
public Sha1HashCode getAbiKeyForDeps() {
return Sha1HashCode.of(ABI_KEY_FOR_DEPS_HASH);
}
}
private static class LocallyBuiltTestAbstractCachingBuildRule
extends TestAbstractCachingBuildRule {
LocallyBuiltTestAbstractCachingBuildRule(
BuildRuleParams buildRuleParams,
SourcePathResolver resolver) {
super(buildRuleParams, resolver);
}
@Override
public ImmutableList<Step> getBuildSteps(
BuildContext context,
BuildableContext buildableContext) {
return ImmutableList.of();
}
}
/**
* Implementation of {@link ArtifactCache} that, when its fetch method is called, takes the
* location of requested {@link File} and writes a zip file there with the entries specified to
* its constructor.
* <p>
* This makes it possible to react to a call to {@link ArtifactCache#store(ImmutableSet, File)}
* and ensure that there will be a zip file in place immediately after the captured method has
* been invoked.
*/
private static class FakeArtifactCacheThatWritesAZipFile implements ArtifactCache {
private final Map<String, String> desiredEntries;
public FakeArtifactCacheThatWritesAZipFile(Map<String, String> desiredEntries) {
this.desiredEntries = desiredEntries;
}
@Override
public CacheResult fetch(RuleKey ruleKey, File file) throws InterruptedException {
try {
writeEntriesToZip(file, ImmutableMap.copyOf(desiredEntries));
} catch (IOException e) {
throw new RuntimeException(e);
}
return CacheResult.hit("dir");
}
@Override
public void store(ImmutableSet<RuleKey> ruleKeys, File output) {
throw new UnsupportedOperationException();
}
@Override
public boolean isStoreSupported() {
throw new UnsupportedOperationException();
}
@Override
public void close() throws IOException {
throw new UnsupportedOperationException();
}
}
/**
* @return a RuleKey with the bits of the hash in reverse order, just to be different.
*/
private static RuleKey reverse(RuleKey ruleKey) {
String hash = ruleKey.getHashCode().toString();
String reverseHash = new StringBuilder(hash).reverse().toString();
return new RuleKey(reverseHash);
}
private static class FakeHasRuntimeDeps extends FakeBuildRule implements HasRuntimeDeps {
private final ImmutableSortedSet<BuildRule> runtimeDeps;
public FakeHasRuntimeDeps(
BuildTarget target,
SourcePathResolver resolver,
BuildRule... runtimeDeps) {
super(target, resolver);
this.runtimeDeps = ImmutableSortedSet.copyOf(runtimeDeps);
}
@Override
public ImmutableSortedSet<BuildRule> getRuntimeDeps() {
return runtimeDeps;
}
}
private static class FixedRuleKeyBuilderFactory implements RuleKeyBuilderFactory {
private final ImmutableMap<BuildTarget, RuleKey> ruleKeys;
public FixedRuleKeyBuilderFactory(ImmutableMap<BuildTarget, RuleKey> ruleKeys) {
this.ruleKeys = ruleKeys;
}
@Override
public RuleKey.Builder newInstance(final BuildRule buildRule) {
SourcePathResolver resolver = new SourcePathResolver(new BuildRuleResolver());
FileHashCache hashCache = new NullFileHashCache();
AppendableRuleKeyCache ruleKeyCache = new AppendableRuleKeyCache(resolver, hashCache);
return new RuleKey.Builder(resolver, hashCache, ruleKeyCache) {
@Override
public RuleKey.Builder setReflectively(String key, @Nullable Object val) {
return this;
}
@Override
public RuleKey build() {
return ruleKeys.get(buildRule.getBuildTarget());
}
};
}
}
private abstract static class InputRuleKeyBuildRule
extends AbstractBuildRule
implements SupportsInputBasedRuleKey {
public InputRuleKeyBuildRule(
BuildRuleParams buildRuleParams,
SourcePathResolver resolver) {
super(buildRuleParams, resolver);
}
}
private static void writeEntriesToZip(File file, ImmutableMap<String, String> entries)
throws IOException {
try (ZipOutputStream zip = new ZipOutputStream(
new BufferedOutputStream(
new FileOutputStream(file)))) {
for (Map.Entry<String, String> mapEntry : entries.entrySet()) {
ZipEntry entry = new ZipEntry(mapEntry.getKey());
zip.putNextEntry(entry);
zip.write(mapEntry.getValue().getBytes());
zip.closeEntry();
}
}
}
}
| apache-2.0 |
leafclick/intellij-community | plugins/cvs/cvs-plugin/src/com/intellij/cvsSupport2/ui/experts/importToCvs/ImportTree.java | 9928 | /*
* Copyright 2000-2014 JetBrains s.r.o.
*
* 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.intellij.cvsSupport2.ui.experts.importToCvs;
import com.intellij.CvsBundle;
import com.intellij.cvsSupport2.CvsUtil;
import com.intellij.cvsSupport2.cvsIgnore.IgnoredFilesInfo;
import com.intellij.cvsSupport2.cvsIgnore.IgnoredFilesInfoImpl;
import com.intellij.cvsSupport2.ui.experts.CvsWizard;
import com.intellij.cvsSupport2.util.CvsVfsUtil;
import com.intellij.ide.util.treeView.NodeDescriptor;
import com.intellij.ide.util.treeView.NodeRenderer;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.Presentation;
import com.intellij.openapi.fileChooser.FileElement;
import com.intellij.openapi.fileChooser.FileSystemTree;
import com.intellij.openapi.fileTypes.FileTypeManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.IconLoader;
import com.intellij.openapi.vcs.ProjectLevelVcsManager;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.ui.SimpleTextAttributes;
import com.intellij.util.IconUtil;
import com.intellij.util.PlatformIcons;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.netbeans.lib.cvsclient.file.AbstractFileObject;
import org.netbeans.lib.cvsclient.file.ICvsFileSystem;
import org.netbeans.lib.cvsclient.util.IIgnoreFileFilter;
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import java.io.File;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
/**
* @author lesya
*/
public class ImportTree extends NodeRenderer {
private final Collection<VirtualFile> myExcludedFiles = new HashSet<>();
private final Collection<VirtualFile> myIncludedFiles = new HashSet<>();
private final Project myProject;
private final FileSystemTree myFileSystemTree;
private final CvsWizard myWizard;
public ImportTree(@Nullable Project project, FileSystemTree fileSystemTree, CvsWizard wizard) {
myProject = project;
myFileSystemTree = fileSystemTree;
myWizard = wizard;
}
@Override
public void customizeCellRenderer(@NotNull JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
if (customize(tree, value, selected, expanded, leaf, row, hasFocus)) return;
super.customizeCellRenderer(tree, value, selected, expanded, leaf, row, hasFocus);
}
private boolean customize(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
if (!(value instanceof DefaultMutableTreeNode)) {
return false;
}
final DefaultMutableTreeNode node = (DefaultMutableTreeNode)value;
final Object userObject = node.getUserObject();
if (!(userObject instanceof NodeDescriptor)) {
return false;
}
final NodeDescriptor descriptor = (NodeDescriptor)userObject;
final Object element = descriptor.getElement();
if (!(element instanceof FileElement)) {
return false;
}
final FileElement fileElement = (FileElement)element;
if (!isExcluded(fileElement)) {
return false;
}
setIcon(descriptor.getIcon() == null ? null : IconLoader.getDisabledIcon(descriptor.getIcon()));
final String text = tree.convertValueToText(value, selected, expanded, leaf, row, hasFocus);
append(text, new SimpleTextAttributes(SimpleTextAttributes.STYLE_STRIKEOUT, tree.getForeground()));
return true;
}
public AnAction createExcludeAction() {
return new AnAction(CvsBundle.lazyMessage("import.wizard.exclude.from.import.action.name"), PlatformIcons.DELETE_ICON) {
@Override
public void update(@NotNull AnActionEvent e) {
final VirtualFile[] selectedFiles = myFileSystemTree.getSelectedFiles();
final Presentation presentation = e.getPresentation();
presentation.setEnabled(isAtLeastOneFileIncluded(selectedFiles));
}
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
final VirtualFile[] selectedFiles = myFileSystemTree.getSelectedFiles();
for (VirtualFile selectedFile : selectedFiles) {
exclude(selectedFile);
}
myWizard.updateStep();
myFileSystemTree.getTree().repaint();
}
};
}
private boolean isAtLeastOneFileIncluded(VirtualFile[] selectedFiles) {
if (selectedFiles == null || selectedFiles.length == 0) return false;
for (VirtualFile selectedFile : selectedFiles) {
if (!isExcluded(selectedFile)) {
return true;
}
}
return false;
}
public AnAction createIncludeAction() {
return new AnAction(CvsBundle.lazyMessage("import.wizard.include.to.import.action.name"), IconUtil.getAddIcon()) {
@Override
public void update(@NotNull AnActionEvent e) {
final VirtualFile[] selectedFiles = myFileSystemTree.getSelectedFiles();
final Presentation presentation = e.getPresentation();
presentation.setEnabled(isAtLeastOneFileExcluded(selectedFiles));
}
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
final VirtualFile[] selectedFiles = myFileSystemTree.getSelectedFiles();
for (VirtualFile selectedFile : selectedFiles) {
include(selectedFile);
}
myWizard.updateStep();
myFileSystemTree.getTree().repaint();
}
};
}
private void include(VirtualFile selectedFile) {
myExcludedFiles.remove(selectedFile);
if (myProject == null) {
return;
}
if (!isIgnoredByVcs(selectedFile)) {
return;
}
final VirtualFile parent = selectedFile.getParent();
if (parent != null && isIgnoredByVcs(parent)) {
return;
}
for (final VirtualFile excludedFile : myExcludedFiles) {
if (VfsUtil.isAncestor(excludedFile, selectedFile, true)) {
return;
}
}
myIncludedFiles.add(selectedFile);
}
private void exclude(VirtualFile selectedFile) {
myExcludedFiles.add(selectedFile);
myIncludedFiles.remove(selectedFile);
}
private boolean isAtLeastOneFileExcluded(VirtualFile[] selectedFiles) {
if (selectedFiles == null || selectedFiles.length == 0) {
return false;
}
for (VirtualFile selectedFile : selectedFiles) {
if (myExcludedFiles.contains(selectedFile)) {
return true;
}
if (myProject == null) {
continue;
}
if (!isIgnoredByVcs(selectedFile)) {
continue;
}
final VirtualFile parent = selectedFile.getParent();
if (parent == null || isIgnoredByVcs(parent) || myExcludedFiles.contains(parent)) {
continue;
}
if (!myIncludedFiles.contains(selectedFile)) {
return true;
}
}
return false;
}
private boolean isExcluded(FileElement fileElement) {
final VirtualFile file = fileElement.getFile();
if (file == null) {
return false;
}
return isExcluded(file);
}
public boolean isExcluded(VirtualFile file) {
for (final VirtualFile excludedFile : myExcludedFiles) {
if (VfsUtil.isAncestor(excludedFile, file, false)) {
return true;
}
}
if (myProject == null || !isIgnoredByVcs(file)) {
return false;
}
for (VirtualFile includedFile : myIncludedFiles) {
if (VfsUtil.isAncestor(includedFile, file, false)) {
return false;
}
}
return true;
}
public IIgnoreFileFilter getIgnoreFileFilter() {
final Collection<File> excludedFiles = new HashSet<>();
for (final VirtualFile excludedFile : myExcludedFiles) {
excludedFiles.add(CvsVfsUtil.getFileFor(excludedFile));
}
final Collection<File> includedFiles = new HashSet<>();
for (VirtualFile includedFile : myIncludedFiles) {
includedFiles.add(CvsVfsUtil.getFileFor(includedFile));
}
return new IIgnoreFileFilter() {
private final Map<File, IgnoredFilesInfo> myParentToIgnoresMap = new HashMap<>();
@Override
public boolean shouldBeIgnored(AbstractFileObject abstractFileObject, ICvsFileSystem cvsFileSystem) {
final File file = cvsFileSystem.getLocalFileSystem().getFile(abstractFileObject);
if (file.isDirectory() && file.getName().equals(CvsUtil.CVS)) return true;
if (FileTypeManager.getInstance().isFileIgnored(abstractFileObject.getName())) return true;
final VirtualFile vFile = LocalFileSystem.getInstance().findFileByIoFile(file);
if (myProject != null && !includedFiles.contains(file)) {
if (vFile != null && isIgnoredByVcs(vFile)) {
return true;
}
}
if (excludedFiles.contains(file)) return true;
final File parentFile = file.getParentFile();
if (parentFile == null) return false;
if (!myParentToIgnoresMap.containsKey(parentFile)) {
myParentToIgnoresMap.put(parentFile, IgnoredFilesInfoImpl.createForFile(new File(parentFile, CvsUtil.CVS_IGNORE_FILE)));
}
return myParentToIgnoresMap.get(parentFile).shouldBeIgnored(vFile);
}
};
}
private boolean isIgnoredByVcs(VirtualFile vFile) {
return myProject != null && ProjectLevelVcsManager.getInstance(myProject).isIgnored(vFile);
}
}
| apache-2.0 |
hyarthi/project-red | src/java/org.openntf.red.main/src/org/openntf/red/impl/Item.java | 11288 | /**
*
*/
package org.openntf.red.impl;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.util.Date;
import java.util.List;
import java.util.Vector;
import java.util.logging.Logger;
import org.openntf.red.Database;
import org.openntf.red.DateTime;
import org.openntf.red.Document;
import org.openntf.red.MIMEEntity;
import org.openntf.red.Session;
//import org.openntf.red.events.EnumEvent;
//import org.openntf.red.events.IDominoEvent;
//import org.openntf.red.events.IDominoListener;
import org.xml.sax.InputSource;
//import lotus.domino.NotesException;
import lotus.domino.XSLTResultTarget;
/**
* Entity representing a document item.
*
* @author Vladimir Kornienko
* @since 0.4.0
* @see org.openntf.red.Item
*/
public class Item extends Base<Document> implements org.openntf.red.Item {
/** Logger object. */
private static final Logger log = Logger.getLogger(Item.class.getName());
/** Back-end object that manipulates data. */
@SuppressWarnings("rawtypes")
private org.openntf.red.nsf.endpoint.Field beObject;
/**
* Default constructor.
*
* @param prnt
* Parent document
* @param _beObject
* Back-end object.
* @since 0.4.0
*/
@SuppressWarnings("rawtypes")
Item(Document prnt, org.openntf.red.nsf.endpoint.Field _beObject) {
super(prnt, Base.NOTES_ITEM);
// TODO Auto-generated constructor stub
beObject = _beObject;
}
/**
* Under consideration. Not sure if needed.
*
* @param classId
*/
Item(int classId) {
super(classId);
}
/**
* Not implemented yet.
*/
@Override
public boolean isDead() {
// TODO Auto-generated method stub
return false;
}
/**
* Returns the ancestor document.
*
* @return Ancestor document.
* @since 0.4.0
*/
@Override
public Document getAncestorDocument() {
return parent;
}
/**
* Returns the ancestor database.
*
* @return Ancestor database.
* @since 0.4.0
*/
@Override
public Database getAncestorDatabase() {
return parent.getAncestorDatabase();
}
/**
* Returns the ancestor session.
*
* @return Ancestor session.
* @since 0.4.0
*/
@Override
public Session getAncestorSession() {
return parent.getAncestorSession();
}
/**
* Not implemented yet.
*/
@Override
public void fillExceptionDetails(List<Entry> result) {
// TODO Auto-generated method stub
}
/**
* Not implemented yet.
*/
@Override
public String abstractText(int maxLen, boolean dropVowels, boolean userDict) {
// TODO Auto-generated method stub
return null;
}
/**
* Not implemented yet.
*/
@Override
public void appendToTextList(String value) {
// TODO Auto-generated method stub
}
/**
* Not implemented yet.
*/
@SuppressWarnings("rawtypes")
@Override
public void appendToTextList(Vector values) {
// TODO Auto-generated method stub
}
/**
* Not implemented yet.
*/
@Override
public boolean containsValue(Object value) {
// TODO Auto-generated method stub
return false;
}
/**
* Not implemented yet.
*/
@Override
public org.openntf.red.Item copyItemToDocument(lotus.domino.Document doc) {
// TODO Auto-generated method stub
return null;
}
/**
* Not implemented yet.
*/
@Override
public org.openntf.red.Item copyItemToDocument(lotus.domino.Document doc, String newName) {
// TODO Auto-generated method stub
return null;
}
/**
* Not implemented yet.
*/
@Override
public DateTime getDateTimeValue() {
// TODO Auto-generated method stub
return null;
}
/**
* Not implemented yet.
*/
@Override
public InputSource getInputSource() {
// TODO Auto-generated method stub
return null;
}
/**
* Not implemented yet.
*/
@Override
public InputStream getInputStream() {
// TODO Auto-generated method stub
return null;
}
/**
* Not implemented yet.
*/
@Override
public DateTime getLastModified() {
// TODO Auto-generated method stub
return null;
}
/**
* Not implemented yet.
*/
@Override
public MIMEEntity getMIMEEntity() {
// TODO Auto-generated method stub
return null;
}
/**
* Not implemented yet.
*/
@Override
public String getName() {
return beObject.getName();
}
/**
* Returns parent document.<br>
* Similar to <code>getAncestorDocument()</code> in this case.
*
* @return Parent document
* @since 0.4.0
*/
@Override
public Document getParent() {
// TODO Auto-generated method stub
return parent;
}
/**
* Not implemented yet.
*/
@Override
public Reader getReader() {
// TODO Auto-generated method stub
return null;
}
/**
* Not implemented yet.
*/
@Override
public String getText() {
// TODO Auto-generated method stub
return null;
}
/**
* Not implemented yet.
*/
@Override
public String getText(int maxLen) {
// TODO Auto-generated method stub
return null;
}
/**
* Returns the item Notes type code (e.g. TEXT - 1280).
*
* @return Item type code.
* @since 0.4.0
*/
@Override
public int getType() {
return beObject.getType();
}
/**
* Not implemented yet.
*/
@Override
public Object getValueCustomData() throws IOException, ClassNotFoundException {
// TODO Auto-generated method stub
return null;
}
/**
* Not implemented yet.
*/
@Override
public Object getValueCustomData(String dataTypeName) throws IOException, ClassNotFoundException {
// TODO Auto-generated method stub
return null;
}
/**
* Not implemented yet.
*/
@Override
public byte[] getValueCustomDataBytes(String dataTypeName) throws IOException {
// TODO Auto-generated method stub
return null;
}
/**
* Not implemented yet.
*/
@Override
public Vector<DateTime> getValueDateTimeArray() {
// TODO Auto-generated method stub
return null;
}
/**
* Not implemented yet.
*/
@Override
public double getValueDouble() {
// TODO Auto-generated method stub
return 0;
}
/**
* Not implemented yet.
*/
@Override
public int getValueInteger() {
// TODO Auto-generated method stub
return 0;
}
/**
* Not implemented yet.
*/
@Override
public int getValueLength() {
// TODO Auto-generated method stub
return 0;
}
/**
* Not implemented yet.
*/
@Override
public Vector<Object> getValues() {
// TODO Auto-generated method stub
return null;
}
/**
* Gets a {@link List} of item values.<br>
* Should be more effective than {@link Vector}.
*
* @return A {@link List} of item values.
* @since 0.4.0
*/
@SuppressWarnings("unchecked")
@Override
public List<Object> getValuesEx() {
return beObject.getValue();
}
/**
* Not implemented yet.
*/
@Override
public String getValueString() {
// TODO Auto-generated method stub
return null;
}
/**
* Not implemented yet.
*/
@Override
public boolean isAuthors() {
// TODO Auto-generated method stub
return false;
}
/**
* Not implemented yet.
*/
@Override
public boolean isEncrypted() {
// TODO Auto-generated method stub
return false;
}
/**
* Not implemented yet.
*/
@Override
public boolean isNames() {
// TODO Auto-generated method stub
return false;
}
/**
* Not implemented yet.
*/
@Override
public boolean isProtected() {
// TODO Auto-generated method stub
return false;
}
/**
* Not implemented yet.
*/
@Override
public boolean isReaders() {
// TODO Auto-generated method stub
return false;
}
/**
* Not implemented yet.
*/
@Override
public boolean isSaveToDisk() {
// TODO Auto-generated method stub
return false;
}
/**
* Not implemented yet.
*/
@Override
public boolean isSigned() {
// TODO Auto-generated method stub
return false;
}
/**
* Not implemented yet.
*/
@Override
public boolean isSummary() {
// TODO Auto-generated method stub
return false;
}
/**
* Not implemented yet.
*/
@Override
public org.w3c.dom.Document parseXML(boolean validate) throws IOException {
// TODO Auto-generated method stub
return null;
}
/**
* Not implemented yet.
*/
@Override
public void remove() {
// TODO Auto-generated method stub
}
/**
* Not implemented yet.
*/
@Override
public void setAuthors(boolean flag) {
// TODO Auto-generated method stub
}
/**
* Not implemented yet.
*/
@Override
public void setDateTimeValue(lotus.domino.DateTime dateTime) {
// TODO Auto-generated method stub
}
/**
* Not implemented yet.
*/
@Override
public void setEncrypted(boolean flag) {
// TODO Auto-generated method stub
}
/**
* Not implemented yet.
*/
@Override
public void setNames(boolean flag) {
// TODO Auto-generated method stub
}
/**
* Not implemented yet.
*/
@Override
public void setProtected(boolean flag) {
// TODO Auto-generated method stub
}
/**
* Not implemented yet.
*/
@Override
public void setReaders(boolean flag) {
// TODO Auto-generated method stub
}
/**
* Not implemented yet.
*/
@Override
public void setSaveToDisk(boolean flag) {
// TODO Auto-generated method stub
}
/**
* Not implemented yet.
*/
@Override
public void setSigned(boolean flag) {
// TODO Auto-generated method stub
}
/**
* Not implemented yet.
*/
@Override
public void setSummary(boolean flag) {
// TODO Auto-generated method stub
}
/**
* Not implemented yet.
*/
@Override
public void setValueCustomData(Object userObj) throws IOException {
// TODO Auto-generated method stub
}
/**
* Not implemented yet.
*/
@Override
public void setValueCustomData(String dataTypeName, Object userObj) throws IOException {
// TODO Auto-generated method stub
}
/**
* Not implemented yet.
*/
@Override
public void setValueCustomDataBytes(String dataTypeName, byte[] byteArray) throws IOException {
// TODO Auto-generated method stub
}
/**
* Not implemented yet.
*/
@Override
public void setValueDouble(double value) {
// TODO Auto-generated method stub
}
/**
* Not implemented yet.
*/
@Override
public void setValueInteger(int value) {
// TODO Auto-generated method stub
}
/**
* Not implemented yet.
*/
@SuppressWarnings("rawtypes")
@Override
public void setValues(Vector values) {
// TODO Auto-generated method stub
}
/**
* Not implemented yet.
*/
@Override
public void setValueString(String value) {
// TODO Auto-generated method stub
}
/**
* Not implemented yet.
*/
@Override
public void transformXML(Object style, XSLTResultTarget result) {
// TODO Auto-generated method stub
}
/**
* Not implemented yet.
*/
@Override
public <T> T getValues(Class<T> type) {
// TODO Auto-generated method stub
return null;
}
/**
* Not implemented yet.
*/
@Override
public Date getLastModifiedDate() {
// TODO Auto-generated method stub
return null;
}
/**
* Not implemented yet.
*/
@Override
public boolean hasFlag(Flags flag) {
// TODO Auto-generated method stub
return false;
}
/**
* Not implemented yet.
*/
@Override
public boolean isReadersNamesAuthors() {
// TODO Auto-generated method stub
return false;
}
/**
* Not implemented yet.
*/
@Override
public void markDirty() {
// TODO Auto-generated method stub
}
/**
* Not implemented yet.
*/
@Override
public Type getTypeEx() {
// TODO Auto-generated method stub
return null;
}
}
| apache-2.0 |
tramchamploo/buffer-slayer | boundedqueue/src/main/java/io/github/tramchamploo/bufferslayer/ConcurrentSizeBoundedQueueFactory.java | 660 | package io.github.tramchamploo.bufferslayer;
import io.github.tramchamploo.bufferslayer.Message.MessageKey;
import io.github.tramchamploo.bufferslayer.OverflowStrategy.Strategy;
/**
* Factory for {@link ConcurrentSizeBoundedQueue}
*/
public final class ConcurrentSizeBoundedQueueFactory extends SizeBoundedQueueFactory {
@Override
protected boolean isAvailable() {
return true;
}
@Override
protected int priority() {
return 10;
}
@Override
protected AbstractSizeBoundedQueue newQueue(int maxSize, Strategy overflowStrategy,
MessageKey key) {
return new ConcurrentSizeBoundedQueue(maxSize, overflowStrategy, key);
}
}
| apache-2.0 |
DenverM80/ds3_java_sdk | ds3-sdk/src/main/java/com/spectralogic/ds3client/Ds3ClientBuilder.java | 8912 | /*
* ******************************************************************************
* Copyright 2014-2017 Spectra Logic Corporation. 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. A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file.
* This file 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.spectralogic.ds3client;
import com.spectralogic.ds3client.models.common.Credentials;
import com.spectralogic.ds3client.networking.NetworkClient;
import com.spectralogic.ds3client.networking.NetworkClientImpl;
import com.spectralogic.ds3client.utils.Builder;
import com.spectralogic.ds3client.utils.Guard;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.URI;
import java.net.URISyntaxException;
/**
* A Builder class used to create a Ds3Client instance. This allows you to customize the behavior of a {@link Ds3Client}.
* For instance, the number of times that the Ds3Client instance will perform a 307 redirect before throwing an error
* can be customized with the {@link Ds3ClientBuilder#withRedirectRetries(int)} as well as
* setting a proxy with {@link Ds3ClientBuilder#withProxy(String)}.
*/
public class Ds3ClientBuilder implements Builder<Ds3Client> {
static final private Logger LOG = LoggerFactory.getLogger(Ds3ClientBuilder.class);
static final private String ENDPOINT = "DS3_ENDPOINT";
static final private String ACCESS_KEY = "DS3_ACCESS_KEY";
static final private String SECRET_KEY = "DS3_SECRET_KEY";
final private String endpoint;
final private Credentials credentials;
private boolean https = true;
private boolean certificateVerification = true;
private URI proxy = null;
private int retries = 5;
private int connectionTimeoutInMillis = 5 * 1000;
private int bufferSizeInBytes = 1024 * 1024;
private int socketTimeoutInMillis = 1000 * 60 * 60;
private String userAgent;
private Ds3ClientBuilder(final String endpoint, final Credentials credentials) throws IllegalArgumentException {
if (Guard.isStringNullOrEmpty(endpoint)) {
throw new IllegalArgumentException("Endpoint must be non empty");
}
if(credentials == null || !credentials.isValid()) {
throw new IllegalArgumentException("Credentials must be filled out.");
}
this.endpoint = endpoint.trim();
this.credentials = credentials;
}
/**
* Returns a Builder which is used to customize the behavior of the Ds3Client library.
* @param endpoint The DS3 endpoint the library should connect to.
* @param creds The {@link Credentials} used for connecting to a DS3 endpoint.
* @return The Builder for the {@link Ds3ClientImpl} object.
*/
public static Ds3ClientBuilder create(final String endpoint, final Credentials creds) {
return new Ds3ClientBuilder(endpoint, creds);
}
/**
* Returns a Build which already has the endpoint and credentials populated from environment variables.
* DS3_ENDPOINT, DS3_ACCESS_KEY, and DS3_SECRET_KEY are all used when creating the builder. This will
* also detect if http_proxy is set, and if it is will us it when creating the client and set the proxy
* variable accordingly.
* @return
* @throws IllegalArgumentException
*/
public static Ds3ClientBuilder fromEnv() throws IllegalArgumentException {
final String endpoint = System.getenv(ENDPOINT);
if (Guard.isStringNullOrEmpty(endpoint)) {
throw new IllegalArgumentException("Missing " + ENDPOINT + " environment variable");
}
final String accessKey = System.getenv(ACCESS_KEY);
if (Guard.isStringNullOrEmpty(accessKey)) {
throw new IllegalArgumentException("Missing " + ACCESS_KEY + " environment variable");
}
final String secretKey = System.getenv(SECRET_KEY);
if (Guard.isStringNullOrEmpty(secretKey)) {
throw new IllegalArgumentException("Missing " + SECRET_KEY + " environment variable");
}
final Ds3ClientBuilder builder = create(endpoint, new Credentials(accessKey, secretKey));
final String httpProxy = System.getenv("http_proxy");
if (httpProxy != null) {
builder.withProxy(httpProxy);
}
return builder;
}
/**
* Specifies if the library should use HTTP or HTTPS. The default is HTTP.
* @param secure True will use HTTPS, false will use HTTP.
* @return The current builder.
*/
public Ds3ClientBuilder withHttps(final boolean secure) {
this.https = secure;
return this;
}
/**
* @param bufferSizeInBytes The size of the buffer to be used when writing content out to DS3.
* @return The current builder.
*/
public Ds3ClientBuilder withBufferSize(final int bufferSizeInBytes) {
this.bufferSizeInBytes = bufferSizeInBytes;
return this;
}
/**
* Specifies if the library should perform SSL certificate validation.
*/
public Ds3ClientBuilder withCertificateVerification(final boolean certificateVerification) {
this.certificateVerification = certificateVerification;
return this;
}
/**
* Sets a HTTP proxy.
* @param proxy The endpoint of the HTTP proxy.
* @return The current builder.
* @throws IllegalArgumentException This will be thrown if the proxy endpoint is not a valid URI.
*/
public Ds3ClientBuilder withProxy(final String proxy) throws IllegalArgumentException {
if (proxy == null) {
LOG.info("Proxy was null");
return this;
}
try {
final URI proxyUri;
if(!proxy.startsWith("http")) {
throw new IllegalArgumentException("Invalid proxy format. The web address must start with either http or https.");
}
proxyUri = new URI(proxy);
this.proxy = proxyUri;
} catch (final URISyntaxException e) {
throw new IllegalArgumentException("Invalid proxy format. Must be a web address.");
}
return this;
}
/**
* Sets the number of retries the library will attempt to perform when it receives 307 redirects from a
* DS3 appliance. The default is 5.
* @param retries The number of times the library should perform retries on 307.
* @return The current builder.
*/
public Ds3ClientBuilder withRedirectRetries(final int retries) {
this.retries = retries;
return this;
}
/**
* Sets the number of milliseconds to wait for a connection to be established before timing out.
*
* Default: 5 minutes
*/
public Ds3ClientBuilder withConnectionTimeout(final int timeoutInMillis) {
this.connectionTimeoutInMillis = timeoutInMillis;
return this;
}
/**
* Sets the number of milliseconds to wait between data packets before timing out a request.
*
* Default: 60 minutes
*/
public Ds3ClientBuilder withSocketTimeout(final int timeoutInMillis) {
this.socketTimeoutInMillis = timeoutInMillis;
return this;
}
/**
* The value to send in the http User-Agent header field.
* @param userAgent If null or empty, the User-Agent header field will contain a default value.
*/
public Ds3ClientBuilder withUserAgent(final String userAgent) {
this.userAgent = userAgent;
return this;
}
/**
* Returns a new Ds3Client instance.
*/
@Override
public Ds3Client build() {
LOG.info("Making connection details for endpoint [{}] using this authorization id [{}]",
this.endpoint, this.credentials.getClientId());
final ConnectionDetailsImpl.Builder connBuilder = ConnectionDetailsImpl
.builder(this.endpoint, this.credentials)
.withProxy(this.proxy)
.withHttps(this.https)
.withCertificateVerification(this.certificateVerification)
.withRedirectRetries(this.retries)
.withBufferSize(this.bufferSizeInBytes)
.withConnectionTimeout(this.connectionTimeoutInMillis)
.withSocketTimeout(this.socketTimeoutInMillis)
.withUserAgent(this.userAgent);
final NetworkClient netClient = new NetworkClientImpl(connBuilder.build());
return new Ds3ClientImpl(netClient);
}
}
| apache-2.0 |
leafclick/intellij-community | platform/core-impl/src/com/intellij/psi/impl/source/resolve/FileContextUtil.java | 1223 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.psi.impl.source.resolve;
import com.intellij.openapi.util.Key;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.SmartPsiElementPointer;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class FileContextUtil {
public static final Key<SmartPsiElementPointer> INJECTED_IN_ELEMENT = Key.create("injectedIn");
public static final Key<PsiFile> CONTAINING_FILE_KEY = Key.create("CONTAINING_FILE_KEY");
private FileContextUtil() { }
@Nullable
public static PsiElement getFileContext(@NotNull PsiFile file) {
SmartPsiElementPointer pointer = file.getUserData(INJECTED_IN_ELEMENT);
return pointer == null ? null : pointer.getElement();
}
@Nullable
public static PsiFile getContextFile(@NotNull PsiElement element) {
PsiFile file = element.getContainingFile();
if (file == null) return null;
PsiElement context = file.getContext();
if (context == null) {
return file;
}
else {
return getContextFile(context);
}
}
} | apache-2.0 |
nafae/developer | modules/adwords_axis/src/main/java/com/google/api/ads/adwords/axis/v201402/video/ContentCategoryLabel.java | 2703 | /**
* ContentCategoryLabel.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter.
*/
package com.google.api.ads.adwords.axis.v201402.video;
/**
* Represents a content label criterion
*/
public class ContentCategoryLabel extends com.google.api.ads.adwords.axis.v201402.video.BaseCriterion implements java.io.Serializable {
public ContentCategoryLabel() {
}
public ContentCategoryLabel(
java.lang.Long id,
java.lang.String baseCriterionType) {
super(
id,
baseCriterionType);
}
private java.lang.Object __equalsCalc = null;
public synchronized boolean equals(java.lang.Object obj) {
if (!(obj instanceof ContentCategoryLabel)) return false;
ContentCategoryLabel other = (ContentCategoryLabel) obj;
if (obj == null) return false;
if (this == obj) return true;
if (__equalsCalc != null) {
return (__equalsCalc == obj);
}
__equalsCalc = obj;
boolean _equals;
_equals = super.equals(obj);
__equalsCalc = null;
return _equals;
}
private boolean __hashCodeCalc = false;
public synchronized int hashCode() {
if (__hashCodeCalc) {
return 0;
}
__hashCodeCalc = true;
int _hashCode = super.hashCode();
__hashCodeCalc = false;
return _hashCode;
}
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(ContentCategoryLabel.class, true);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/video/v201402", "ContentCategoryLabel"));
}
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
/**
* Get Custom Serializer
*/
public static org.apache.axis.encoding.Serializer getSerializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanSerializer(
_javaType, _xmlType, typeDesc);
}
/**
* Get Custom Deserializer
*/
public static org.apache.axis.encoding.Deserializer getDeserializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanDeserializer(
_javaType, _xmlType, typeDesc);
}
}
| apache-2.0 |
wychytu/easyweb | src/com/easyweb/utils/SysUtil.java | 3700 | package com.easyweb.utils;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.easyweb.common.Var;
public class SysUtil {
private static long currentId = 0;
private static char serverId;
private static Object idLock = new Object();
public static String getId() {
long id;
synchronized (idLock) {
if (currentId == 0) {
currentId = (new Date()).getTime() * 10000;
try {
serverId = Var.get("server.serverId").charAt(0);
} catch (Throwable e) {
serverId = '2';
}
}
id = currentId++;
}
return numToString(id);
}
private static char intToChar(int val) {
if (val < 10)
return (char) (val + 48);
else
return (char) (val + 55);
}
private static String numToString(long num) {
char[] buf = new char[12];
int charPos = 12;
long val;
buf[0] = serverId;
while ((val = num / 36) > 0) {
buf[--charPos] = intToChar((int) (num % 36));
num = val;
}
buf[--charPos] = intToChar((int) (num % 36));
return new String(buf);
}
public static String getShortError(Throwable e) {
Throwable cause = e, c = e;
while (c != null) {
cause = c;
c = c.getCause();
}
String message = cause.getMessage();
if (StringUtil.isEmpty(message))
message = cause.toString();
return StringUtil.toLine(message);
}
public static void executeMethod(String classMethodName,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
int pos = classMethodName.lastIndexOf('.');
String className, methodName;
if (pos == -1) {
className = "";
methodName = classMethodName;
} else {
className = classMethodName.substring(0, pos);
methodName = classMethodName.substring(pos + 1);
}
Class<?> cls = Class.forName(className);
cls.getMethod(methodName, HttpServletRequest.class,
HttpServletResponse.class).invoke(cls, request, response);
}
public static void executeMethod(String classMethodName) throws Exception {
if (StringUtil.isEmpty(classMethodName))
return;
int pos = classMethodName.lastIndexOf('.');
String className, methodName;
if (pos == -1) {
className = "";
methodName = classMethodName;
} else {
className = classMethodName.substring(0, pos);
methodName = classMethodName.substring(pos + 1);
}
Class<?> cls = Class.forName(className);
cls.getMethod(methodName).invoke(cls);
}
public static int isToOs(InputStream is, OutputStream os) throws Exception {
byte buf[] = new byte[8192];
int len, size = 0;
while ((len = is.read(buf)) > 0) {
os.write(buf, 0, len);
size += len;
}
return size;
}
public static ByteArrayInputStream getBIS(InputStream is) throws Exception {
if (is == null)
return null;
if (is instanceof ByteArrayInputStream)
return (ByteArrayInputStream) is;
ByteArrayOutputStream bos;
try {
bos = new ByteArrayOutputStream();
SysUtil.isToOs(is, bos);
} finally {
is.close();
}
return new ByteArrayInputStream(bos.toByteArray());
}
public static String readString(Reader reader) throws Exception {
char buf[] = new char[8192];
StringBuilder sb = new StringBuilder();
int len;
while ((len = reader.read(buf)) > 0) {
sb.append(buf, 0, len);
}
return sb.toString();
}
public static void closeInputStream(InputStream inputStream) {
if (inputStream != null) {
try {
inputStream.close();
} catch (Throwable e) {
}
}
}
public static void error(String msg) throws Exception {
throw new Exception(msg);
}
}
| artistic-2.0 |
NguyenAnhDuc/fptqa | src/main/java/vn/com/fpt/fti/api/helper/ResponseHelper.java | 942 | package vn.com.fpt.fti.api.helper;
import vn.com.fpt.fti.api.model.FailResponseJson;
import vn.com.fpt.fti.api.model.SuccessResponseJson;
public class ResponseHelper {
public static SuccessResponseJson buildSuccessJsonReponse(String result){
SuccessResponseJson json = new SuccessResponseJson();
json.status = "success";
json.result = result;
return json;
}
public static FailResponseJson buildFailJsonResponse(int errorCode) {
FailResponseJson json = new FailResponseJson();
json.status = "fail";
json.errorCode = errorCode;
json.errorMessage = getErrorMessage(errorCode);
return json;
}
public static String getErrorMessage(int errorCode){
String errorMessage = "";
switch (errorCode){
case 404: errorMessage = "Not Found";
break;
case 411: errorMessage = "Invalid Paramaters";
break;
case 500: errorMessage = "Internal Error Server";
break;
}
return errorMessage;
}
}
| artistic-2.0 |
stalk-io/stalk-server | src/main/java/io/stalk/common/oauth/provider/AuthProvider.java | 877 | package io.stalk.common.oauth.provider;
import io.stalk.common.oauth.Profile;
import io.stalk.common.oauth.strategy.RequestToken;
import io.stalk.common.oauth.utils.AccessGrant;
import java.util.Map;
public interface AuthProvider {
String EXT_NAMESPACE = "http://specs.openid.net/extensions/oauth/1.0";
String EMAIL = "email";
String COUNTRY = "country";
String LANGUAGE = "language";
String FULL_NAME = "fullname";
String NICK_NAME = "nickname";
String DOB = "dob";
String GENDER = "gender";
String POSTCODE = "postcode";
String FIRST_NAME = "firstname";
String LAST_NAME = "lastname";
public RequestToken getLoginRedirectURL() throws Exception;
public Profile connect(AccessGrant requestToken, Map<String, String> requestParams) throws Exception;
public String getProviderId();
}
| artistic-2.0 |
PhantomThief/jedis-helper | src/main/java/com/github/phantomthief/jedis/OpInterceptor.java | 1411 | package com.github.phantomthief.jedis;
import java.io.Closeable;
import java.lang.reflect.Method;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/**
* @author w.vela
* Created on 2017-08-11.
*/
public interface OpInterceptor<J extends Closeable, P> {
/**
* @return {@code null} if didn't want to change any behavior.
*/
@Nullable
JedisOpCall<J> interceptCall(P pool, Method method, J jedis, Object[] args);
class JedisOpCall<J extends Closeable> {
private final Method method;
private final J jedis;
private final Object[] args;
private Object finalObject;
private boolean hasFinalObject;
public JedisOpCall(@Nonnull Method method, @Nonnull J jedis, @Nonnull Object[] args) {
this.method = method;
this.jedis = jedis;
this.args = args;
}
boolean hasFinalObject() {
return hasFinalObject;
}
Object getFinalObject() {
return finalObject;
}
public JedisOpCall<J> setFinalObject(Object obj) {
this.finalObject = obj;
hasFinalObject = true;
return this;
}
Method getMethod() {
return method;
}
J getJedis() {
return jedis;
}
Object[] getArgs() {
return args;
}
}
}
| artistic-2.0 |
douhao4648/Test | src/concurrency/chapter8_test/recipe7_debug/task/Task1.java | 910 | package concurrency.chapter8_test.recipe7_debug.task;
import java.util.concurrent.locks.Lock;
/**
* This class implements the first task of the example
*/
public class Task1 implements Runnable {
/**
* Two locks that will be used by the example
*/
private Lock lock1, lock2;
/**
* Constructor of the class. Initialize its attributes
*
* @param lock1 A lock used by the class
* @param lock2 A lock used by the class
*/
public Task1(Lock lock1, Lock lock2) {
this.lock1 = lock1;
this.lock2 = lock2;
}
/**
* Main method of the task
*/
@Override
public void run() {
lock1.lock();
System.out.printf("Task 1: Lock 1 locked\n");
lock2.lock();
System.out.printf("Task 1: Lock 2 locked\n");
lock2.unlock();
lock1.unlock();
}
}
| artistic-2.0 |
ginere/ginere-jdbc-mysql | src/main/java/eu/ginere/jdbc/mysql/MySQLDatabaseUtils.java | 4525 | package eu.ginere.jdbc.mysql;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Properties;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import org.apache.log4j.Logger;
import com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource;
import eu.ginere.base.util.dao.DaoManagerException;
import eu.ginere.base.util.properties.GlobalFileProperties;
/**
* Clase madre para todos los managers JDBC. Esta clase contiene las datasource
* utilizadas por los managers.
*
* CREATE SCHEMA `cgps` DEFAULT CHARACTER SET utf8 ;
*
* @see #setDataSource(DataSource)
* @author avmendo
*
*/
public abstract class MySQLDatabaseUtils {
static Logger log = Logger.getLogger(MySQLDatabaseUtils.class);
// protected static DataSource dataSource = null;
// /**
// * Instala la datasource que sera utilizada por todos los managers JDBC
// *
// * @param newDataSource
// */
// public static void setDataSource(DataSource newDataSource) {
// if (newDataSource == null) {
// log.error("Inicializanfdo la DataSource con un valor NULO.");
// } else {
// log
// .info("Inicializanfdo la DataSource con '" + newDataSource
// + "'");
// dataSource = newDataSource;
// }
// }
/**
* Obtiene una datasource JNI.
*
* @see #setDataSource(DataSource)
*
* @param jniDatasourceName
* @return
* @throws NamingException
*/
public static DataSource getJniDataSource(String jniDatasourceName)throws NamingException {
// Context initContext = new InitialContext();
// Context envContext = (Context) initContext.lookup("java:/comp/env");
// DataSource dataSource = (DataSource)
// envContext.lookup(jniDatasourceName);
// javax.naming.InitialContext ic = new javax.naming.InitialContext();
// javax.sql.DataSource dataSource = (javax.sql.DataSource) ic
// .lookup(jniDatasourceName);
log.info("Accedeiendo a la Datasource jni:'" + jniDatasourceName + "'");
Context initContext = new InitialContext();
Context envContext = (Context) initContext.lookup("java:/comp/env");
DataSource ds = (DataSource) envContext.lookup(jniDatasourceName);
if (ds == null) {
log
.warn("la busqueda en java:/comp/env dio un resultado nulo buscando directamente el nombre");
ds = (DataSource) initContext.lookup(jniDatasourceName);
if (ds == null) {
log.warn("No se encontro una datasource jni de nombre:'"
+ jniDatasourceName + "'");
}
} else {
log.info("Se obtubo la datasource:'" + ds + "' de nombre:'"
+ jniDatasourceName + "'");
}
return ds;
}
/**
* @param driverClassName
* @param url
* jdbc:oracle:thin:@172.24.0.22:1521:ESTRADA1
* @param user
* USER
* @param password
* SECRET
* @return
* @throws SQLException
*/
public static DataSource createMySQLDataSource(String url,
String username,
String password) throws SQLException {
/*
* De Oracle
*/
MysqlConnectionPoolDataSource datasource=new MysqlConnectionPoolDataSource();
datasource.setUser(username);
datasource.setPassword(password);
datasource.setURL(url);
return datasource;
}
/**
* @param filePath
* @return
* @throws NamingException
* @throws FileNotFoundException
* @throws IOException
*/
public static DataSource createMySQLDataSourceFromPropertiesFile(String filePath) throws SQLException,
FileNotFoundException,IOException {
filePath=GlobalFileProperties.getPropertiesFilePath(filePath);
Properties prop = new Properties();
prop.load(new FileInputStream(filePath));
String url = prop.getProperty("jdbc.url");
String username = prop.getProperty("jdbc.username");
String password = prop.getProperty("jdbc.password");
DataSource ret=createMySQLDataSource(url, username, password);
return ret;
}
public static void initDatasource(String filePropertiesName) throws DaoManagerException {
try {
DataSource dataSource = MySQLDatabaseUtils.createMySQLDataSourceFromPropertiesFile(filePropertiesName);
MySQLDataBase.initDatasource(filePropertiesName,dataSource);
}catch(Exception e){
throw new DaoManagerException("While init datasource from file:"+filePropertiesName, e);
}
}
}
| artistic-2.0 |
cattaka/MathDrawer | src/main/java/net/cattaka/mathdrawer/util/DocumentUtil.java | 2859 | /*
* Copyright (c) 2009, Takao Sumitomo
* All rights reserved.
*
* Redistribution and use in source and binary forms,
* with or without modification, are permitted provided
* that the following conditions are met:
*
* * Redistributions of source code must retain the
* above copyright notice, this list of conditions
* and the following disclaimer.
* * Redistributions in binary form must reproduce
* the above copyright notice, this list of
* conditions and the following disclaimer in the
* documentation and/or other materials provided
* with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software
* and documentation are those of the authors and should
* not be interpreted as representing official policies,
* either expressed or implied.
*/
/*
* $Id: DocumentUtil.java 232 2009-08-01 07:06:41Z cattaka $
*/
package net.cattaka.mathdrawer.util;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import net.cattaka.util.ExceptionHandler;
public class DocumentUtil {
private static ArrayList<int[]> cache = new ArrayList<int[]>();
public static int[][] getWordIndexs(Document document, int offset, int length, int margin) {
cache.clear();
int start = offset - margin;
int end = offset+length + margin;
if (start < 0) {
start = 0;
}
if (end >= document.getLength()) {
end = document.getLength();
}
try {
String tmpStr = document.getText(start, end-start);
Pattern pattern = Pattern.compile("[^\\s]+");
Matcher mr = pattern.matcher(tmpStr);
while(mr.find()) {
int[] t = new int[]{start + mr.start(),start + mr.end()};
cache.add(t);
}
if (start > 0) {
cache.remove(0);
}
if (end < document.getLength()) {
cache.remove(cache.size()-1);
}
} catch (BadLocationException e) {
ExceptionHandler.error(e);
}
return cache.toArray(new int[cache.size()][]);
}
}
| bsd-2-clause |
highsource/jaxb2-basics | runtime/src/test/java/org/jvnet/jaxb2_commons/xml/bind/model/util/tests/gamma/A4.java | 169 | package org.jvnet.jaxb2_commons.xml.bind.model.util.tests.gamma;
import jakarta.xml.bind.annotation.XmlType;
@XmlType(name="AFour", namespace="")
public class A4 {
}
| bsd-2-clause |
j123b567/stack-usage | src/cz/jaybee/stackusage/callgraph/FunctionCall.java | 617 | package cz.jaybee.stackusage.callgraph;
/**
*
* @author Jan Breuer
*/
public class FunctionCall {
FunctionVertex caller;
FunctionVertex callee;
CallType type;
public FunctionCall(FunctionVertex caller, FunctionVertex callee, CallType type) {
this.caller = caller;
this.callee = callee;
this.type = type;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(caller);
sb.append(";");
sb.append(callee);
sb.append(";");
sb.append(type);
return sb.toString();
}
}
| bsd-2-clause |
licehammer/perun | perun-base/src/main/java/cz/metacentrum/perun/core/api/User.java | 8749 | package cz.metacentrum.perun.core.api;
/**
* Represents user of some source.
*
* @author Michal Prochazka
* @author Slavek Licehammer
* @author Martin Kuba
*/
public class User extends Auditable implements Comparable<PerunBean> {
protected String firstName;
protected String lastName;
protected String middleName;
protected String titleBefore;
protected String titleAfter;
private boolean serviceUser = false;
private boolean sponsoredUser = false;
public User() {
super();
}
public User(int id, String firstName, String lastName, String middleName, String titleBefore, String titleAfter) {
super(id);
this.firstName = firstName;
this.lastName = lastName;
this.middleName = middleName;
this.titleBefore = titleBefore;
this.titleAfter = titleAfter;
}
public User(int id, String firstName, String lastName, String middleName, String titleBefore, String titleAfter, boolean serviceUser, boolean sponsoredUser) {
this(id, firstName, lastName, middleName, titleBefore, titleAfter);
this.serviceUser = serviceUser;
this.sponsoredUser = sponsoredUser;
}
public User(int id, String firstName, String lastName, String middleName, String titleBefore, String titleAfter,
String createdAt, String createdBy, String modifiedAt, String modifiedBy, Integer createdByUid, Integer modifiedByUid) {
super(id, createdAt, createdBy, modifiedAt, modifiedBy, createdByUid, modifiedByUid);
this.firstName = firstName;
this.lastName = lastName;
this.middleName = middleName;
this.titleAfter = titleAfter;
this.titleBefore = titleBefore;
}
public User(int id, String firstName, String lastName, String middleName, String titleBefore, String titleAfter,
String createdAt, String createdBy, String modifiedAt, String modifiedBy, boolean serviceUser, boolean sponsoredUser, Integer createdByUid, Integer modifiedByUid) {
this(id, firstName, lastName, middleName, titleBefore, titleAfter, createdAt, createdBy, modifiedAt, modifiedBy, createdByUid, modifiedByUid);
this.serviceUser = serviceUser;
this.sponsoredUser = sponsoredUser;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getMiddleName() {
return middleName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
public String getTitleBefore() {
return titleBefore;
}
public void setTitleBefore(String titleBefore) {
this.titleBefore = titleBefore;
}
public String getTitleAfter() {
return titleAfter;
}
public String getCommonName() {
String name = "";
if (firstName != null) name = firstName;
if (middleName != null) {
if (name.length() != 0) name += " ";
name += middleName;
}
if (lastName != null) {
if (name.length() != 0) name += " ";
name += lastName;
}
return name;
}
public String getDisplayName() {
String name = "";
if (titleBefore != null) name = titleBefore;
if (firstName != null) {
if (name.length() != 0) name += " ";
name += firstName;
}
if (middleName != null) {
if (name.length() != 0) name += " ";
name += middleName;
}
if (lastName != null) {
if (name.length() != 0) name += " ";
name += lastName;
}
if (titleAfter != null) {
if (name.length() != 0) name += " ";
name += titleAfter;
}
return name;
}
public void setTitleAfter(String titleAfter) {
this.titleAfter = titleAfter;
}
public boolean isServiceUser() {
return serviceUser;
}
public void setServiceUser(boolean serviceUser) {
this.serviceUser = serviceUser;
}
public boolean isSponsoredUser() {
return sponsoredUser;
}
public void setSponsoredUser(boolean sponsoredUser) {
this.sponsoredUser = sponsoredUser;
}
public boolean isSpecificUser() {
return isServiceUser() || isSponsoredUser();
}
public SpecificUserType getMajorSpecificType() {
if (isServiceUser()) return SpecificUserType.SERVICE;
else if (isSponsoredUser()) return SpecificUserType.SPONSORED;
else return SpecificUserType.NORMAL;
}
/**
* Compare this object with another perunBean.
* <p>
* If the perunBean is User object, compare them by LastName, then FirstName and then Id
*
* @param perunBean some perunBean object or User
* @return a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object
* @see Comparable#compareTo(Object)
*/
@Override
public int compareTo(PerunBean perunBean) {
if (perunBean == null) throw new NullPointerException("PerunBean to compare with is null.");
if (perunBean instanceof User) {
User user = (User) perunBean;
int compare;
//Compare on last Name
if (this.getLastName() == null && user.getLastName() != null) compare = -1;
else if (user.getLastName() == null && this.getLastName() != null) compare = 1;
else if (this.getLastName() == null && user.getLastName() == null) compare = 0;
else compare = this.getLastName().compareToIgnoreCase(user.getLastName());
if (compare != 0) return compare;
//Compare on first Name if not
if (this.getFirstName() == null && user.getFirstName() != null) compare = -1;
else if (user.getFirstName() == null && this.getFirstName() != null) compare = 1;
else if (this.getFirstName() == null && user.getFirstName() == null) compare = 0;
else compare = this.getFirstName().compareToIgnoreCase(user.getFirstName());
if (compare != 0) return compare;
//Compare to id if not
return (this.getId() - perunBean.getId());
} else {
return (this.getId() - perunBean.getId());
}
}
@Override
public String serializeToString() {
return this.getClass().getSimpleName() + ":[" +
"id=<" + getId() + ">" +
", titleBefore=<" + (getTitleBefore() == null ? "\\0" : BeansUtils.createEscaping(getTitleBefore())) + ">" +
", firstName=<" + (getFirstName() == null ? "\\0" : BeansUtils.createEscaping(getFirstName())) + ">" +
", lastName=<" + (getLastName() == null ? "\\0" : BeansUtils.createEscaping(getLastName())) + ">" +
", middleName=<" + (getMiddleName() == null ? "\\0" : BeansUtils.createEscaping(getMiddleName())) + ">" +
", titleAfter=<" + (getTitleAfter() == null ? "\\0" : BeansUtils.createEscaping(getTitleAfter())) + ">" +
", serviceAccount=<" + isServiceUser() + ">" +
", sponsoredAccount=<" + isSponsoredUser() + ">" +
']';
}
@Override
public String toString() {
return getClass().getSimpleName() +
":[id='" +
getId() +
"', titleBefore='" +
titleBefore +
"', firstName='" +
firstName +
"', lastName='" +
lastName +
"', middleName='" +
middleName +
"', titleAfter='" +
titleAfter +
"', serviceAccount='" +
serviceUser +
"', sponsoredAccount='" +
sponsoredUser +
"']";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((firstName == null) ? 0 : firstName.hashCode());
result = prime * result + getId();
result = prime * result
+ ((lastName == null) ? 0 : lastName.hashCode());
result = prime * result
+ ((middleName == null) ? 0 : middleName.hashCode());
result = prime * result
+ ((titleAfter == null) ? 0 : titleAfter.hashCode());
result = prime * result
+ ((titleBefore == null) ? 0 : titleBefore.hashCode());
result = prime * result
+ ((serviceUser ? 1 : 2));
result = prime * result
+ ((sponsoredUser ? 1 : 2));
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
User other = (User) obj;
if (firstName == null) {
if (other.firstName != null)
return false;
} else if (!firstName.equals(other.firstName))
return false;
if (getId() != other.getId())
return false;
if (lastName == null) {
if (other.lastName != null)
return false;
} else if (!lastName.equals(other.lastName))
return false;
if (middleName == null) {
if (other.middleName != null)
return false;
} else if (!middleName.equals(other.middleName))
return false;
if (titleAfter == null) {
if (other.titleAfter != null)
return false;
} else if (!titleAfter.equals(other.titleAfter))
return false;
if (titleBefore == null) {
if (other.titleBefore != null)
return false;
} else if (!titleBefore.equals(other.titleBefore))
return false;
else if (serviceUser != other.serviceUser)
return false;
else if (sponsoredUser != other.sponsoredUser)
return false;
return true;
}
}
| bsd-2-clause |
jcodec/jcodec | src/main/java/org/jcodec/common/io/BitReader.java | 6106 | package org.jcodec.common.io;
import java.lang.IllegalArgumentException;
import java.nio.ByteBuffer;
/**
* This class is part of JCodec ( www.jcodec.org ) This software is distributed
* under FreeBSD License
*
* @author The JCodec project
*
*/
public class BitReader {
public static BitReader createBitReader(ByteBuffer bb) {
BitReader r = new BitReader(bb);
r.curInt = r.readInt();
r.deficit = 0;
return r;
}
private int deficit = -1;
private int curInt = -1;
private ByteBuffer bb;
private int initPos;
private BitReader(ByteBuffer bb) {
this.bb = bb;
this.initPos = bb.position();
}
public BitReader fork() {
BitReader fork = new BitReader(this.bb.duplicate());
fork.initPos = 0;
fork.curInt = this.curInt;
fork.deficit = this.deficit;
return fork;
}
public final int readInt() {
if (((java.nio.Buffer)bb).remaining() >= 4) {
deficit -= 32;
return ((bb.get() & 0xff) << 24) | ((bb.get() & 0xff) << 16) | ((bb.get() & 0xff) << 8) | (bb.get() & 0xff);
} else
return readIntSafe();
}
private int readIntSafe() {
deficit -= (((java.nio.Buffer)bb).remaining() << 3);
int res = 0;
if (bb.hasRemaining())
res |= bb.get() & 0xff;
res <<= 8;
if (bb.hasRemaining())
res |= bb.get() & 0xff;
res <<= 8;
if (bb.hasRemaining())
res |= bb.get() & 0xff;
res <<= 8;
if (bb.hasRemaining())
res |= bb.get() & 0xff;
return res;
}
public int read1Bit() {
int ret = curInt >>> 31;
curInt <<= 1;
++deficit;
if (deficit == 32) {
curInt = readInt();
}
// System.out.println(ret);
return ret;
}
public int readNBitSigned(int n) {
int v = readNBit(n);
return read1Bit() == 0 ? v : -v;
}
public int readNBit(int n) {
if (n > 32)
throw new IllegalArgumentException("Can not read more then 32 bit");
int ret = 0;
if (n + deficit > 31) {
ret |= (curInt >>> deficit);
n -= 32 - deficit;
ret <<= n;
deficit = 32;
curInt = readInt();
}
if (n != 0) {
ret |= curInt >>> (32 - n);
curInt <<= n;
deficit += n;
}
return ret;
}
public boolean moreData() {
int remaining = ((java.nio.Buffer)bb).remaining() + 4 - ((deficit + 7) >> 3);
return remaining > 1 || (remaining == 1 && curInt != 0);
}
public int remaining() {
return (((java.nio.Buffer)bb).remaining() << 3) + 32 - deficit;
}
public final boolean isByteAligned() {
return (deficit & 0x7) == 0;
}
public int skip(int bits) {
int left = bits;
if (left + deficit > 31) {
left -= 32 - deficit;
deficit = 32;
if (left > 31) {
int skip = Math.min(left >> 3, ((java.nio.Buffer)bb).remaining());
((java.nio.Buffer)bb).position(((java.nio.Buffer)bb).position() + skip);
left -= skip << 3;
}
curInt = readInt();
}
deficit += left;
curInt <<= left;
return bits;
}
public int skipFast(int bits) {
deficit += bits;
curInt <<= bits;
return bits;
}
public int bitsToAlign() {
return (deficit & 0x7) > 0 ? 8 - (deficit & 0x7) : 0;
}
public int align() {
return (deficit & 0x7) > 0 ? skip(8 - (deficit & 0x7)) : 0;
}
public int check24Bits() {
if (deficit > 16) {
deficit -= 16;
curInt |= nextIgnore16() << deficit;
}
if (deficit > 8) {
deficit -= 8;
curInt |= nextIgnore() << deficit;
}
return curInt >>> 8;
}
public int check16Bits() {
if (deficit > 16) {
deficit -= 16;
curInt |= nextIgnore16() << deficit;
}
return curInt >>> 16;
}
public int readFast16(int n) {
if (n == 0)
return 0;
if (deficit > 16) {
deficit -= 16;
curInt |= nextIgnore16() << deficit;
}
int ret = curInt >>> (32 - n);
deficit += n;
curInt <<= n;
return ret;
}
public int checkNBit(int n) {
if (n > 24) {
throw new IllegalArgumentException("Can not check more then 24 bit");
}
return checkNBitDontCare(n);
}
public int checkNBitDontCare(int n) {
while (deficit + n > 32) {
deficit -= 8;
curInt |= nextIgnore() << deficit;
}
int res = curInt >>> (32 - n);
return res;
}
private int nextIgnore16() {
return ((java.nio.Buffer)bb).remaining() > 1 ? bb.getShort() & 0xffff : (((java.nio.Buffer)bb).hasRemaining() ? ((bb.get() & 0xff) << 8) : 0);
}
private int nextIgnore() {
return ((java.nio.Buffer)bb).hasRemaining() ? bb.get() & 0xff : 0;
}
public int curBit() {
return deficit & 0x7;
}
public boolean lastByte() {
return ((java.nio.Buffer)bb).remaining() + 4 - (deficit >> 3) <= 1;
}
public void terminate() {
int putBack = (32 - deficit) >> 3;
((java.nio.Buffer)bb).position(((java.nio.Buffer)bb).position() - putBack);
}
public int position() {
return ((((java.nio.Buffer)bb).position() - initPos - 4) << 3) + deficit;
}
/**
* Stops this bit reader. Returns underlying ByteBuffer pointer to the next
* byte unread byte
*/
public void stop() {
((java.nio.Buffer)bb).position(((java.nio.Buffer)bb).position() - ((32 - deficit) >> 3));
}
public int checkAllBits() {
return curInt;
}
public boolean readBool() {
return read1Bit() == 1;
}
} | bsd-2-clause |
kofnego-jw/spring4uli | projects/t04jpa/src/main/java/at/ac/uibk/fiba/wang/spring4uli/jpa/repository/ProjectRepo.java | 681 | package at.ac.uibk.fiba.wang.spring4uli.jpa.repository;
import at.ac.uibk.fiba.wang.spring4uli.jpa.ontology.Person;
import at.ac.uibk.fiba.wang.spring4uli.jpa.ontology.Project;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface ProjectRepo extends JpaRepository<Project, Long> {
List<Project> findAllByLeader(Person leader);
@Query("SELECT p FROM Project p WHERE ?1 MEMBER OF p.laborators")
List<Project> findAllByLaboratorsHavingPerson(Person laborator);
Project findByName(String name);
}
| bsd-2-clause |
mapfish/mapfish-print | core/src/main/java/org/mapfish/print/URIUtils.java | 10287 | package org.mapfish.print;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
import org.apache.commons.io.IOUtils;
import org.mapfish.print.http.MfClientHttpRequestFactory;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.ClientHttpResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
/**
* Utility methods for editing and analyzing uris.
*/
public final class URIUtils {
private URIUtils() {
// intentionally empty
}
/**
* Parse the URI and get all the parameters in map form. Query name -> List of Query values.
*
* @param uri uri to analyze
*/
public static Multimap<String, String> getParameters(final URI uri) {
return getParameters(uri.getRawQuery());
}
/**
* Parse the URI and get all the parameters in map form. Query name -> List of Query values.
*
* @param rawQuery query portion of the uri to analyze.
*/
public static Multimap<String, String> getParameters(final String rawQuery) {
Multimap<String, String> result = HashMultimap.create();
if (rawQuery == null) {
return result;
}
StringTokenizer tokens = new StringTokenizer(rawQuery, "&");
while (tokens.hasMoreTokens()) {
String pair = tokens.nextToken();
int pos = pair.indexOf('=');
String key;
String value;
if (pos == -1) {
key = pair;
value = "";
} else {
try {
key = URLDecoder.decode(pair.substring(0, pos), "UTF-8");
value = URLDecoder.decode(pair.substring(pos + 1), "UTF-8");
} catch (UnsupportedEncodingException e) {
throw ExceptionUtils.getRuntimeException(e);
}
}
result.put(key, value);
}
return result;
}
/**
* Add the given params to the query.
*
* @param url The query
* @param params The params to add
* @param overrideParams A set of parameter names that must be overridden and not added
* @return The new query
* @throws URISyntaxException
*/
public static String addParams(
final String url, final Multimap<String, String> params, final Set<String> overrideParams)
throws URISyntaxException {
return addParams(new URI(url), params, overrideParams).toString();
}
/**
* Add the given params to the query.
*
* @param uri The query
* @param params The params to add
* @param overrideParams A set of parameter names that must be overridden and not added
* @return The new query
*/
public static URI addParams(
final URI uri, final Multimap<String, String> params, final Set<String> overrideParams) {
if (params == null || params.isEmpty()) {
return uri;
}
final String origTxt = uri.toString();
int queryStart = origTxt.indexOf('?');
final StringBuilder result = new StringBuilder();
if (queryStart < 0) {
int fragmentStart = origTxt.indexOf('#');
if (fragmentStart < 0) {
result.append(origTxt);
} else {
result.append(origTxt, 0, fragmentStart);
}
} else {
result.append(origTxt, 0, queryStart);
}
Map<String, Collection<String>> origParams = getParameters(uri).asMap();
boolean first = true;
for (Map.Entry<String, Collection<String>> param: params.asMap().entrySet()) {
final String key = param.getKey();
Collection<String> origList = origParams.remove(key);
if (origList != null && (overrideParams == null || !overrideParams.contains(key))) {
first = addParams(result, first, key, origList);
}
Collection<String> list = param.getValue();
first = addParams(result, first, key, list);
}
for (Map.Entry<String, Collection<String>> param: origParams.entrySet()) {
final String key = param.getKey();
Collection<String> list = param.getValue();
first = addParams(result, first, key, list);
}
if (uri.getFragment() != null) {
result.append('#').append(uri.getRawFragment());
}
try {
return new URI(result.toString());
} catch (URISyntaxException e) {
throw ExceptionUtils.getRuntimeException(e);
}
}
private static boolean addParams(
final StringBuilder result, final boolean isFirstParam, final String key,
final Collection<String> list) {
boolean first = isFirstParam;
for (String val: list) {
if (first) {
result.append('?');
first = false;
} else {
result.append('&');
}
try {
result.append(URLEncoder.encode(key, Constants.DEFAULT_ENCODING));
result.append("=");
result.append(URLEncoder.encode(val, Constants.DEFAULT_ENCODING));
} catch (UnsupportedEncodingException e) {
throw ExceptionUtils.getRuntimeException(e);
}
}
return first;
}
/**
* Add a parameter to the query params (the params map) replacing any parameter that might be there.
*
* @param params the query parameters
* @param key the key/param name
* @param value the value to insert
*/
public static void addParamOverride(
final Multimap<String, String> params, final String key, final String value) {
params.removeAll(key);
params.put(key, value);
}
/**
* Add a parameter to the query params (the params map) if there is not existing value for that key.
*
* @param params the query parameters
* @param key the key/param name
* @param value the value to insert
*/
public static void setParamDefault(
final Multimap<String, String> params, final String key, final String value) {
if (!params.containsKey(key)) {
params.put(key, value);
}
}
/**
* Construct a new uri by replacing query parameters in initialUri with the query parameters provided.
*
* @param initialUri the initial/template URI
* @param queryParams the new query parameters.
*/
public static URI setQueryParams(final URI initialUri, final Multimap<String, String> queryParams) {
StringBuilder queryString = new StringBuilder();
for (Map.Entry<String, String> entry: queryParams.entries()) {
if (queryString.length() > 0) {
queryString.append("&");
}
queryString.append(entry.getKey()).append("=").append(entry.getValue());
}
try {
if (initialUri.getHost() == null && initialUri.getAuthority() != null) {
return new URI(initialUri.getScheme(), initialUri.getAuthority(), initialUri.getPath(),
queryString.toString(),
initialUri.getFragment());
} else {
return new URI(initialUri.getScheme(), initialUri.getUserInfo(), initialUri.getHost(),
initialUri.getPort(),
initialUri.getPath(),
queryString.toString(), initialUri.getFragment());
}
} catch (URISyntaxException e) {
throw ExceptionUtils.getRuntimeException(e);
}
}
/**
* Read all the data from the provided URI and return the data as a string.
*
* @param requestFactory Request factory for making the request.
* @param uri the uri to load data from.
* @return the data in string form.
*/
public static String toString(final MfClientHttpRequestFactory requestFactory, final URI uri)
throws IOException {
try (ClientHttpResponse response = requestFactory.createRequest(uri, HttpMethod.GET).execute()) {
return IOUtils.toString(response.getBody(), Constants.DEFAULT_ENCODING);
}
}
/**
* Read all the data from the provided URI and return the data as a string.
*
* @param requestFactory Request factory for making the request.
* @param url the uri to load data from.
* @return the data in string form.
*/
public static String toString(final MfClientHttpRequestFactory requestFactory, final URL url)
throws IOException {
try {
return toString(requestFactory, url.toURI());
} catch (URISyntaxException e) {
throw ExceptionUtils.getRuntimeException(e);
}
}
/**
* Set the replace of the uri and return the new URI.
*
* @param initialUri the starting URI, the URI to update
* @param path the path to set on the baeURI
*/
public static URI setPath(final URI initialUri, final String path) {
String finalPath = path;
if (!finalPath.startsWith("/")) {
finalPath = '/' + path;
}
try {
if (initialUri.getHost() == null && initialUri.getAuthority() != null) {
return new URI(initialUri.getScheme(), initialUri.getAuthority(), finalPath,
initialUri.getQuery(),
initialUri.getFragment());
} else {
return new URI(initialUri.getScheme(), initialUri.getUserInfo(), initialUri.getHost(),
initialUri.getPort(),
finalPath, initialUri.getQuery(), initialUri.getFragment());
}
} catch (URISyntaxException e) {
throw ExceptionUtils.getRuntimeException(e);
}
}
}
| bsd-2-clause |
Rezar/Ubiqlog | app/src/main/java/com/ubiqlog/vis/ui/extras/bluetooth/BluetoothLogDevicesView.java | 7544 | package com.ubiqlog.vis.ui.extras.bluetooth;
import java.util.ArrayList;
import com.ubiqlog.vis.extras.bluetooth.BluetoothDetection;
import com.ubiqlog.vis.extras.bluetooth.BluetoothDetectionContainer;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.Path;
import android.graphics.PointF;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.PathShape;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
public class BluetoothLogDevicesView extends View
{
private String[] devicesNames;
private String[] devicesAddresses;
private ArrayList<Integer> indexesVisibleDevices;
private LayerDrawable layerDrawable;
private Drawable[] drawableLayers;
private ShapeDrawable shapeDrawableAxis;
private ShapeDrawable shapeDrawableTicks;
private Paint paintText;
private Path pathTicks;
private Path pathAxis;
private int numDevices;
private int spaceInBetweenTicks = 100;
private int spaceInBetweenTicksOneThird = spaceInBetweenTicks / 3;
private int choosenIndex = -1;
private boolean bDataLoaded;
private PointF[] tickTextPositions;
private Float[] tickPositions;
private Toast viewToast;
private BluetoothLogDataView bluetoothLogDataView;
private int iPaddingTop, iPaddingBottom;
public BluetoothLogDevicesView(Context context, BluetoothLogDataView bluetoothLogDataView)
{
super(context);
this.bluetoothLogDataView = bluetoothLogDataView;
bDataLoaded = false;
drawableLayers = new Drawable[2];
shapeDrawableAxis = new ShapeDrawable();
shapeDrawableAxis.getPaint().setColor(Color.WHITE);
shapeDrawableAxis.getPaint().setStrokeCap(Paint.Cap.SQUARE);
shapeDrawableAxis.getPaint().setStyle(Paint.Style.STROKE);
shapeDrawableAxis.getPaint().setStrokeWidth(3);
shapeDrawableTicks = new ShapeDrawable();
shapeDrawableTicks.getPaint().setColor(Color.WHITE);
shapeDrawableTicks.getPaint().setStrokeCap(Paint.Cap.SQUARE);
shapeDrawableTicks.getPaint().setStyle(Paint.Style.STROKE);
shapeDrawableTicks.getPaint().setStrokeWidth(2);
drawableLayers[0] = shapeDrawableAxis;
drawableLayers[1] = shapeDrawableTicks;
layerDrawable = new LayerDrawable(drawableLayers);
paintText = new Paint();
paintText.setTextSize(18);
paintText.setColor(Color.WHITE);
paintText.setTextAlign(Align.RIGHT);
pathTicks = new Path();
pathAxis = new Path();
indexesVisibleDevices = new ArrayList<Integer>();
}
public void setData(BluetoothDetectionContainer bluetoothContainer)
{
bDataLoaded = false;
numDevices = bluetoothContainer.getNumberOfDevices();
devicesNames = new String[numDevices];
devicesAddresses = new String[numDevices];
ArrayList<BluetoothDetection> bluetoothDetections = bluetoothContainer.getAllDevicesDetections();
int index = 0;
for (BluetoothDetection bluetoothDetection : bluetoothDetections)
{
devicesNames[index] = bluetoothDetection.getDeviceName();
devicesAddresses[index] = bluetoothDetection.getDeviceAddress();
++index;
}
tickTextPositions = new PointF[numDevices];
tickPositions = new Float[numDevices];
iPaddingTop = this.getPaddingTop();
iPaddingBottom = this.getPaddingBottom();
bDataLoaded = true;
ViewGroup.LayoutParams params = getLayoutParams();
params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
setLayoutParams(params);
invalidate();
}
public void DoScroll(int top)
{
UpdateDeviceData(top);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
int width = View.MeasureSpec.getSize(widthMeasureSpec);
int height = 0;
if (bDataLoaded)
{
height = spaceInBetweenTicks * (numDevices+1);
RefreshTicksPath(0.9f*width, width, spaceInBetweenTicks);
shapeDrawableTicks.setShape(new PathShape(pathTicks, width, height));
shapeDrawableTicks.setBounds(0, 0, width, height);
pathAxis.rewind();
pathAxis.moveTo(0.95f*width, 0.01f*height);
pathAxis.lineTo(0.95f*width, 0.99f*height);
shapeDrawableAxis.setShape(new PathShape(pathAxis, width, height));
shapeDrawableAxis.setBounds(0, 0, width, height);
RefreshTickTextPositions(0.8f*width, spaceInBetweenTicks);
}
setMeasuredDimension(width, height);
}
@Override
public void onLayout (boolean changed, int left, int top, int right, int bottom)
{
UpdateDeviceData(0);
}
@Override
protected void onDraw(Canvas canvas)
{
layerDrawable.draw(canvas);
if (bDataLoaded)
{
for (int indexText = 0, indexPos = 0; indexPos < tickTextPositions.length && indexText < devicesNames.length; indexPos++, indexText++)
{
canvas.drawText(devicesNames[indexText], tickTextPositions[indexPos].x, tickTextPositions[indexPos].y, paintText);
}
}
}
@Override
public boolean onTouchEvent(MotionEvent event)
{
if (bDataLoaded)
{
switch (event.getAction())
{
case MotionEvent.ACTION_DOWN:
int y = (int)event.getY();
for (int index = 0; index < tickPositions.length; ++ index)
{
if ((tickPositions[index] >= (y - spaceInBetweenTicksOneThird)) && (tickPositions[index] <= (y + spaceInBetweenTicksOneThird)))
{
choosenIndex = index;
break;
}
}
return true;
case MotionEvent.ACTION_UP:
String strintToShow = new String("Device name: " + devicesNames[choosenIndex] + "\nDevice address: " + devicesAddresses[choosenIndex]);
viewToast = Toast.makeText(BluetoothLogDevicesView.this.getContext(), strintToShow, Toast.LENGTH_SHORT);
viewToast.show();
break;
}
}
return false;
}
private void RefreshTickTextPositions(float right, float top)
{
float fCurrentY = top;
for (int index = 0; index < numDevices; index++)
{
tickTextPositions[index] = new PointF(right, fCurrentY);
fCurrentY += spaceInBetweenTicks;
}
}
private void RefreshTicksPath(float left, float right, float top)
{
pathTicks.rewind();
float fCurrentY = top;
for (int index = 0; index < numDevices; index++)
{
tickPositions[index] = new Float(fCurrentY);
pathTicks.moveTo(left, fCurrentY);
pathTicks.lineTo(right, fCurrentY);
fCurrentY += spaceInBetweenTicks;
}
}
private void UpdateDeviceData(int top)
{
Rect rect = new Rect();
getLocalVisibleRect(rect);
indexesVisibleDevices.clear();
for (int index = 0; index < numDevices; ++index)
{
if ((rect.top + iPaddingTop + spaceInBetweenTicks) <= tickPositions[index].intValue() && tickPositions[index].intValue() <= (rect.bottom - iPaddingBottom - spaceInBetweenTicks))
{
indexesVisibleDevices.add(index);
}
}
int numIndexes = indexesVisibleDevices.size();
String[] stringVisibleDeviceAddresses = new String[numIndexes];
float[] floatVisibleDevicesPositions = new float[numIndexes];
int index = 0;
for (int visibleIndex : indexesVisibleDevices)
{
stringVisibleDeviceAddresses[index] = devicesAddresses[visibleIndex];
floatVisibleDevicesPositions[index] = tickPositions[visibleIndex] - (top - iPaddingTop - spaceInBetweenTicks);
index++;
}
bluetoothLogDataView.updateDeviceData(stringVisibleDeviceAddresses, floatVisibleDevicesPositions);
}
}
| bsd-2-clause |
RBMHTechnology/ttt | ttt-ttx/src/main/java/com/skynav/ttx/transformer/isd/ISD.java | 80554 | /*
* Copyright 2013-15 Skynav, Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 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 SKYNAV, INC. AND ITS 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 SKYNAV, INC. OR ITS CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.skynav.ttx.transformer.isd;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import java.text.MessageFormat;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.namespace.QName;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Attr;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.Text;
import com.skynav.ttv.app.InvalidOptionUsageException;
import com.skynav.ttv.app.MissingOptionArgumentException;
import com.skynav.ttv.app.OptionSpecification;
import com.skynav.ttv.app.UnknownOptionException;
import com.skynav.ttv.model.Model;
import com.skynav.ttv.model.value.TimeParameters;
import com.skynav.ttv.util.Annotations;
import com.skynav.ttv.util.ComparableQName;
import com.skynav.ttv.util.IOUtil;
import com.skynav.ttv.util.Namespaces;
import com.skynav.ttv.util.PostVisitor;
import com.skynav.ttv.util.PreVisitor;
import com.skynav.ttv.util.Reporter;
import com.skynav.ttv.util.StyleSet;
import com.skynav.ttv.util.StyleSpecification;
import com.skynav.ttv.util.Traverse;
import com.skynav.ttv.util.Visitor;
import com.skynav.ttv.verifier.ttml.timing.TimingVerificationParameters;
import com.skynav.ttx.transformer.AbstractTransformer;
import com.skynav.ttx.transformer.TransformerContext;
import com.skynav.ttx.transformer.TransformerException;
import com.skynav.ttx.util.DirectedGraph;
import com.skynav.ttx.util.TimeCoordinate;
import com.skynav.ttx.util.TimeInterval;
import com.skynav.ttx.util.TopologicalSort;
import com.skynav.xml.helpers.XML;
public class ISD {
public static final String TRANSFORMER_NAME = "isd";
private static final String DEFAULT_OUTPUT_ENCODING = AbstractTransformer.DEFAULT_OUTPUT_ENCODING;
private static final Charset defaultOutputEncoding;
private static final String defaultOutputFileNamePattern = "isdi{0,number,000000}.xml";
static {
Charset de;
try {
de = Charset.forName(DEFAULT_OUTPUT_ENCODING);
} catch (RuntimeException e) {
de = Charset.defaultCharset();
}
defaultOutputEncoding = de;
}
// option and usage info
private static final String[][] longOptionSpecifications = new String[][] {
{ "isd-output-clean", "", "clean (remove) all files in output directory prior to writing ISD output" },
{ "isd-output-directory", "DIRECTORY","specify path to directory where ISD output is to be written" },
{ "isd-output-encoding", "ENCODING", "specify character encoding of ISD output (default: " + defaultOutputEncoding.name() + ")" },
{ "isd-output-indent", "", "indent ISD output (default: no indent)" },
{ "isd-output-pattern", "PATTERN", "specify ISD output file name pattern (default: 'isd00000')" },
};
private static final Collection<OptionSpecification> longOptions;
static {
Set<OptionSpecification> s = new java.util.TreeSet<OptionSpecification>();
for (String[] spec : longOptionSpecifications) {
s.add(new OptionSpecification(spec[0], spec[1], spec[2]));
}
longOptions = Collections.unmodifiableSet(s);
}
public static TTMLHelper getHelper(TransformerContext context) {
return (TTMLHelper) context.getResourceState(ResourceState.isdHelper.name());
}
@SuppressWarnings("unchecked")
public static Map<Object,Object> getParents(TransformerContext context) {
return (Map<Object,Object>) context.getResourceState(ResourceState.isdParents.name());
}
@SuppressWarnings("unchecked")
public static Map<Object,TimingState> getTimingStates(TransformerContext context) {
return (Map<Object,TimingState>) context.getResourceState(ResourceState.isdTimingStates.name());
}
public static class ISDTransformer extends AbstractTransformer {
// options state
private boolean outputDirectoryClean;
private String outputDirectoryPath;
private String outputEncodingName;
private boolean outputIndent;
private String outputPattern;
// derived option state
private File outputDirectory;
private Charset outputEncoding;
public ISDTransformer() {
}
public String getName() {
return TRANSFORMER_NAME;
}
@Override
public Collection<OptionSpecification> getShortOptionSpecs() {
return null;
}
@Override
public Collection<OptionSpecification> getLongOptionSpecs() {
return longOptions;
}
@Override
public int parseLongOption(List<String> args, int index) {
String arg = args.get(index);
int numArgs = args.size();
String option = arg;
assert option.length() > 2;
option = option.substring(2);
if (option.equals("isd-output-clean")) {
outputDirectoryClean = true;
} else if (option.equals("isd-output-directory")) {
if (index + 1 > numArgs)
throw new MissingOptionArgumentException("--" + option);
outputDirectoryPath = args.get(++index);
} else if (option.equals("isd-output-encoding")) {
if (index + 1 > numArgs)
throw new MissingOptionArgumentException("--" + option);
outputEncodingName = args.get(++index);
} else if (option.equals("isd-output-indent")) {
outputIndent = true;
} else if (option.equals("isd-output-pattern")) {
if (index + 1 > numArgs)
throw new MissingOptionArgumentException("--" + option);
outputPattern = args.get(++index);
} else
index = index - 1;
return index + 1;
}
@Override
public int parseShortOption(List<String> args, int index) {
String arg = args.get(index);
String option = arg;
assert option.length() == 2;
option = option.substring(1);
throw new UnknownOptionException("-" + option);
}
@Override
public void processDerivedOptions() {
// output directory
File outputDirectory;
if (outputDirectoryPath != null) {
outputDirectory = new File(outputDirectoryPath);
if (!outputDirectory.exists())
throw new InvalidOptionUsageException("isd-output-directory", "directory does not exist: " + outputDirectoryPath);
else if (!outputDirectory.isDirectory())
throw new InvalidOptionUsageException("isd-output-directory", "not a directory: " + outputDirectoryPath);
} else
outputDirectory = new File(".");
this.outputDirectory = outputDirectory;
// output encoding
Charset outputEncoding;
if (outputEncodingName != null) {
try {
outputEncoding = Charset.forName(outputEncodingName);
} catch (Exception e) {
outputEncoding = null;
}
if (outputEncoding == null)
throw new InvalidOptionUsageException("isd-output-encoding", "unknown encoding: " + outputEncodingName);
} else
outputEncoding = null;
if (outputEncoding == null)
outputEncoding = defaultOutputEncoding;
this.outputEncoding = outputEncoding;
// output pattern
String outputPattern = this.outputPattern;
if (outputPattern == null)
outputPattern = defaultOutputFileNamePattern;
this.outputPattern = outputPattern;
}
@Override
public void transform(List<String> args, Object root, TransformerContext context, OutputStream out) {
assert root != null;
assert context != null;
populateContext(context);
Reporter reporter = context.getReporter();
reporter.logInfo(reporter.message("*KEY*", "Transforming result using ''{0}'' transformer...", getName()));
// extract significant time intervals
Set<TimeInterval> intervals = extractISDIntervals(root, context);
if (reporter.getDebugLevel() > 0) {
StringBuffer sb = new StringBuffer();
for (TimeInterval interval : intervals) {
if (sb.length() > 0)
sb.append(',');
sb.append(interval);
}
reporter.logDebug(reporter.message("*KEY*", "Resolved active intervals: {0}.", "{" + sb + "}"));
}
writeISDSequence(root, context, intervals, out);
}
private void populateContext(TransformerContext context) {
context.setResourceState(ResourceState.isdHelper.name(), TTMLHelper.makeInstance(context.getModel().getTTMLVersion()));
context.setResourceState(ResourceState.isdParents.name(), new java.util.HashMap<Object, Object>());
context.setResourceState(ResourceState.isdTimingStates.name(), new java.util.HashMap<Object, TimingState>());
context.setResourceState(ResourceState.isdGenerationIndices.name(), new int[GenerationIndex.values().length]);
}
private Set<TimeInterval> extractISDIntervals(Object root, TransformerContext context) {
Reporter reporter = context.getReporter();
getHelper(context).generateAnonymousSpans(root, context);
recordParents(root, context);
resolveTiming(root, context);
Set<TimeCoordinate> coordinates = new java.util.TreeSet<TimeCoordinate>();
for (TimeInterval interval : extractActiveIntervals(root, context)) {
coordinates.add(interval.getBegin());
coordinates.add(interval.getEnd());
}
if (reporter.getDebugLevel() > 0) {
StringBuffer sb = new StringBuffer();
for (TimeCoordinate coordinate : coordinates) {
if (sb.length() > 0)
sb.append(',');
sb.append(coordinate);
}
reporter.logDebug(reporter.message("*KEY*", "Resolved active coordinates: {0}.", "{" + sb + "}"));
}
Set<TimeInterval> intervals = new java.util.TreeSet<TimeInterval>();
TimeCoordinate lastCoordinate = null;
for (TimeCoordinate coordinate : coordinates) {
if (lastCoordinate != null)
intervals.add(new TimeInterval(lastCoordinate, coordinate));
lastCoordinate = coordinate;
}
return intervals;
}
private void recordParents(Object root, final TransformerContext context) {
try {
getHelper(context).traverse(root, new PreVisitor() {
public boolean visit(Object content, Object parent, Visitor.Order order) {
Map<Object,Object> parents = getParents(context);
if (!parents.containsKey(content))
parents.put(content, parent);
return true;
}
});
} catch (Exception e) {
context.getReporter().logError(e);
}
}
private void resolveTiming(Object root, TransformerContext context) {
resolveExplicit(root, context);
resolveImplicit(root, context);
resolveActive(root, context);
}
private void resolveExplicit(Object root, final TransformerContext context) {
try {
final TimeParameters timeParameters = TimingVerificationParameters.makeInstance(root, context.getExternalParameters()).getTimeParameters();
getHelper(context).traverse(root, new PreVisitor() {
public boolean visit(Object content, Object parent, Visitor.Order order) {
if (getHelper(context).isTimed(content)) {
TimingState ts = getTimingState(content, context, timeParameters);
ts.resolveExplicit();
}
return true;
}
});
} catch (Exception e) {
context.getReporter().logError(e);
}
}
private void resolveImplicit(Object root, final TransformerContext context) {
try {
final TimeParameters timeParameters = TimingVerificationParameters.makeInstance(root, context.getExternalParameters()).getTimeParameters();
getHelper(context).traverse(root, new PostVisitor() {
public boolean visit(Object content, Object parent, Visitor.Order order) {
if (getHelper(context).isTimed(content)) {
TimingState ts = getTimingState(content, context, timeParameters);
ts.resolveImplicit();
}
return true;
}
});
} catch (Exception e) {
context.getReporter().logError(e);
}
}
private void resolveActive(Object root, final TransformerContext context) {
try {
final TimeParameters timeParameters = TimingVerificationParameters.makeInstance(root, context.getExternalParameters()).getTimeParameters();
getHelper(context).traverse(root, new PreVisitor() {
public boolean visit(Object content, Object parent, Visitor.Order order) {
if (getHelper(context).isTimed(content)) {
TimingState ts = getTimingState(content, context, timeParameters);
ts.resolveActive();
}
return true;
}
});
} catch (Exception e) {
context.getReporter().logError(e);
}
}
private java.util.Set<TimeInterval> extractActiveIntervals(Object root, final TransformerContext context) {
final TimeParameters timeParameters = TimingVerificationParameters.makeInstance(root, context.getExternalParameters()).getTimeParameters();
final java.util.Set<TimeInterval> intervals = new java.util.TreeSet<TimeInterval>();
try {
getHelper(context).traverse(root, new PreVisitor() {
public boolean visit(Object content, Object parent, Visitor.Order order) {
if (getHelper(context).isTimed(content)) {
TimingState ts = getTimingState(content,context, timeParameters);
ts.extractActiveInterval(intervals);
}
return true;
}
});
} catch (Exception e) {
context.getReporter().logError(e);
}
return intervals;
}
private TimingState getTimingState(Object content, TransformerContext context, TimeParameters timeParameters) {
if (content == null)
return null;
Map<Object,TimingState> timingStates = getTimingStates(context);
if (!timingStates.containsKey(content))
timingStates.put(content, new TimingState(context, content, timeParameters));
return getTimingStates(context).get(content);
}
private void writeISDSequence(Object root, TransformerContext context, Set<TimeInterval> intervals, OutputStream out) {
Reporter reporter = context.getReporter();
boolean suppressOutput = (Boolean) context.getResourceState(TransformerContext.ResourceState.ttxSuppressOutputSerialization.name());
if (!suppressOutput && outputDirectoryClean)
cleanOutputDirectory(outputDirectory, context);
try {
Model model = context.getModel();
JAXBContext jc = JAXBContext.newInstance(model.getJAXBContextPath());
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.newDocument();
Marshaller m = jc.createMarshaller();
m.marshal(context.getBindingElement(context.getXMLNode(root)), doc);
List<Object> isdSequence = new java.util.ArrayList<Object>();
for (TimeInterval interval : intervals) {
Document docCopy = copyDocument(doc, db);
markIdAttributes(docCopy, context);
pruneIntervals(docCopy, context, interval);
pruneRegions(docCopy, context);
pruneTimingAndRegionAttributes(docCopy, context);
generateISDWrapper(docCopy, interval, context);
pruneISDExclusions(docCopy, context);
Namespaces.normalize(docCopy, model.getNormalizedPrefixes());
if (hasUsableContent(docCopy, context)) {
Object isd = writeISD(docCopy, isdSequence.size() + 1, suppressOutput, context);
if (isd != null)
isdSequence.add(isd);
}
}
if (suppressOutput) {
reporter.logInfo(reporter.message("*KEY*", "Suppressing ''{0}'' transformer output serialization.", getName()));
context.setResourceState(TransformerContext.ResourceState.ttxOutput.name(), isdSequence);
}
} catch (JAXBException e) {
reporter.logError(e);
} catch (ParserConfigurationException e) {
reporter.logError(e);
}
}
private static Document copyDocument(Document doc, DocumentBuilder db) {
Document docCopy = db.newDocument();
Node rootCopy = doc.getDocumentElement().cloneNode(true);
docCopy.appendChild(docCopy.adoptNode(rootCopy));
return docCopy;
}
private static void markIdAttributes(Document doc, TransformerContext context) {
try {
Traverse.traverseElements(doc, new PreVisitor() {
public boolean visit(Object content, Object parent, Visitor.Order order) {
assert content instanceof Element;
Element elt = (Element) content;
if (elt.hasAttributeNS(XML.xmlNamespace, "id"))
elt.setIdAttributeNS(XML.xmlNamespace, "id", true);
return true;
}
});
} catch (Exception e) {
context.getReporter().logError(e);
}
}
private static void pruneIntervals(Document doc, TransformerContext context, final TimeInterval interval) {
try {
Traverse.traverseElements(doc, new PreVisitor() {
public boolean visit(Object content, Object parent, Visitor.Order order) {
assert content instanceof Element;
Element elt = (Element) content;
if (isTimedElement(elt)) {
TimeInterval eltInterval = getActiveInterval(elt);
if (eltInterval.isEmpty() || !eltInterval.intersects(interval)) {
assert parent instanceof Element;
Element eltParent = (Element) parent;
pruneElement(elt, eltParent);
}
}
return true;
}
});
} catch (Exception e) {
context.getReporter().logError(e);
}
}
private static boolean isTimedElement(Element elt) {
String nsUri = elt.getNamespaceURI();
if ((nsUri == null) || !nsUri.equals(TTMLHelper.NAMESPACE_TT))
return false;
else {
String localName = elt.getLocalName();
if (localName.equals("animate"))
return true;
else if (localName.equals("body"))
return true;
else if (localName.equals("div"))
return true;
else if (localName.equals("p"))
return true;
else if (localName.equals("span"))
return true;
else if (localName.equals("br"))
return true;
else if (localName.equals("region"))
return true;
else if (localName.equals("set"))
return true;
else
return false;
}
}
private static TimeInterval getActiveInterval(Element elt) {
String begin;
if (elt.hasAttributeNS(TTMLHelper.NAMESPACE_ISD, "begin"))
begin = elt.getAttributeNS(TTMLHelper.NAMESPACE_ISD, "begin");
else
begin = null;
String end;
if (elt.hasAttributeNS(TTMLHelper.NAMESPACE_ISD, "end"))
end = elt.getAttributeNS(TTMLHelper.NAMESPACE_ISD, "end");
else
end = null;
return new TimeInterval(begin, end);
}
private static void pruneElement(Element elt, Element parent) {
assert elt != null;
if (parent != null) {
assert elt.getParentNode() == parent;
parent.removeChild(elt);
}
}
private static void pruneRegions(Document doc, TransformerContext context) {
List<Element> regions = getRegionElements(doc, context);
regions = maybeImplyDefaultRegion(doc, context, regions);
for (Element region : regions) {
try {
Element body = copyBodyElement(doc, context);
if (body != null) {
pruneUnselectedContent(body, context, region);
if (hasUsableContent(body, context))
region.appendChild(body);
}
} catch (DOMException e) {
context.getReporter().logError(e);
}
}
removeBodyElement(doc, context);
}
private static boolean hasUsableContent(Element elt, TransformerContext context) {
final boolean returnUsable[] = new boolean[1];
try {
Traverse.traverseElements(elt, null, new PreVisitor() {
public boolean visit(Object content, Object parent, Visitor.Order order) {
assert content instanceof Element;
Element elt = (Element) content;
if (isParagraphElement(elt)) {
if (hasUsableContentInParagraph(elt)) {
returnUsable[0] = true;
return false;
} else
return true;
} else
return true;
}
});
} catch (Exception e) {
context.getReporter().logError(e);
}
return returnUsable[0];
}
private static boolean hasUsableContentInParagraph(Element elt) {
String content = elt.getTextContent();
for (int i = 0, n = content.length(); i < n; ++i) {
if (!Character.isWhitespace(content.charAt(i)))
return true;
}
return false;
}
private static void pruneUnselectedContent(final Element body, TransformerContext context, final Element region) {
try {
Traverse.traverseElements(body, null, new PostVisitor() {
public boolean visit(Object content, Object parent, Visitor.Order order) {
assert content instanceof Element;
Element elt = (Element) content;
if (!isSelectedContent(elt, region)) {
if (parent != null) {
assert parent instanceof Element;
Element eltParent = (Element) parent;
pruneElement(elt, eltParent);
} else if (elt != body) {
assert false;
}
}
return true;
}
});
} catch (Exception e) {
context.getReporter().logError(e);
}
}
private static boolean isSelectedContent(Element elt, Element region) {
String id = getAssociatedRegionIdentifier(elt);
if (id != null) {
String idRegion = getXmlIdentifier(region);
if (idRegion != null)
return id.equals(idRegion);
else
return false;
} else
return isAnonymousRegionElement(region);
}
private static String getAssociatedRegionIdentifier(Element elt) {
String id;
id = getRegionIdentifier(elt);
if (id != null)
return id;
// use descendant before ancestor since we are doing post-traversal visit
id = getNearestDescendantRegionIdentifier(elt);
if (id != null)
return id;
// use ancestor after descendant since we are doing post-traversal visit
id = getNearestAncestorRegionIdentifier(elt);
if (id != null)
return id;
return null;
}
private static String getNearestAncestorRegionIdentifier(Element elt) {
for (Node a = elt.getParentNode(); a != null; a = a.getParentNode()) {
if (a instanceof Element) {
String id = getRegionIdentifier((Element) a);
if (id != null)
return id;
} else
break;
}
return null;
}
private static String getNearestDescendantRegionIdentifier(Element elt) {
Queue<Element> descendants = new java.util.LinkedList<Element>();
descendants.add(elt);
while (!descendants.isEmpty()) {
Element e = descendants.remove();
for (Node n = e.getFirstChild(); n != null; n = n.getNextSibling()) {
if (n instanceof Element) {
Element c = (Element) n;
String id = getRegionIdentifier(c);
if (id != null)
return id;
descendants.add(c);
}
}
}
return null;
}
private static String getRegionIdentifier(Element elt) {
if (elt.hasAttributeNS(null, "region"))
return elt.getAttributeNS(null, "region");
else
return null;
}
private static String getXmlIdentifier(Element elt) {
if (elt.hasAttributeNS(XML.xmlNamespace, "id"))
return elt.getAttributeNS(XML.xmlNamespace, "id");
else
return null;
}
private static List<Element> getRegionElements(Document doc, TransformerContext context) {
final List<Element> regions = new java.util.ArrayList<Element>();
try {
Traverse.traverseElements(doc, new PreVisitor() {
public boolean visit(Object content, Object parent, Visitor.Order order) {
assert content instanceof Element;
Element elt = (Element) content;
if (isOutOfLineRegionElement(elt))
regions.add(elt);
return true;
}
});
} catch (Exception e) {
context.getReporter().logError(e);
}
return regions;
}
private static boolean isOutOfLineRegionElement(Element elt) {
return isRegionElement(elt) && isLayoutElement((Element) elt.getParentNode());
}
private static Element maybeImplyHeadElement(Document document, TransformerContext context) {
Element head = getHeadElement(document, context);
if (head == null) {
Element defaultHead = document.createElementNS(TTMLHelper.NAMESPACE_TT, "head");
Element body = getBodyElement(document, context);
try {
Element root = document.getDocumentElement();
if (body != null)
root.insertBefore(defaultHead, body);
else
root.appendChild(defaultHead);
head = defaultHead;
} catch (DOMException e) {
context.getReporter().logError(e);
}
}
return head;
}
private static Element maybeImplyLayoutElement(Document document, TransformerContext context) {
Element layout = getLayoutElement(document, context);
if (layout == null) {
Element defaultLayout = document.createElementNS(TTMLHelper.NAMESPACE_TT, "layout");
Element head = maybeImplyHeadElement(document, context);
assert head != null;
try {
head.appendChild(defaultLayout);
layout = defaultLayout;
} catch (DOMException e) {
context.getReporter().logError(e);
}
}
return layout;
}
private static List<Element> maybeImplyDefaultRegion(Document document, TransformerContext context, List<Element> regions) {
if (regions.isEmpty()) {
try {
Element defaultRegion = document.createElementNS(TTMLHelper.NAMESPACE_TT, "region");
defaultRegion.setAttributeNS(XML.xmlNamespace, "id", getHelper(context).generateAnonymousRegionId(context));
Element layout = maybeImplyLayoutElement(document, context);
assert layout != null;
layout.appendChild(defaultRegion);
regions.add(defaultRegion);
} catch (DOMException e) {
context.getReporter().logError(e);
}
}
return regions;
}
private static Element copyBodyElement(Document document, TransformerContext context) {
Element body = getBodyElement(document, context);
if (body != null)
return (Element) body.cloneNode(true);
else
return null;
}
private static Element removeBodyElement(Document document, TransformerContext context) {
try {
Element body = getBodyElement(document, context);
if (body != null)
return (Element) body.getParentNode().removeChild(body);
} catch (DOMException e) {
context.getReporter().logError(e);
}
return null;
}
private static boolean isTimedTextElement(Element elt, String localName) {
if (elt != null) {
String nsUri = elt.getNamespaceURI();
if ((nsUri != null) && nsUri.equals(TTMLHelper.NAMESPACE_TT) && elt.getLocalName().equals(localName))
return true;
}
return false;
}
private static boolean isRootElement(Element elt) {
return isTimedTextElement(elt, "tt");
}
private static Element getHeadElement(Document document, TransformerContext context) {
final Element[] retHead = new Element[1];
try {
Traverse.traverseElements(document, new PreVisitor() {
public boolean visit(Object content, Object parent, Visitor.Order order) {
assert content instanceof Element;
Element elt = (Element) content;
if (isHeadElement(elt)) {
retHead[0] = elt;
return false;
} else
return true;
}
});
} catch (Exception e) {
context.getReporter().logError(e);
}
return retHead[0];
}
private static boolean isHeadElement(Element elt) {
return isTimedTextElement(elt, "head");
}
private static Element getBodyElement(Document document, TransformerContext context) {
final Element[] retBody = new Element[1];
try {
Traverse.traverseElements(document, new PreVisitor() {
public boolean visit(Object content, Object parent, Visitor.Order order) {
assert content instanceof Element;
Element elt = (Element) content;
Element eltParent = (Element) parent;
if (isBodyElement(elt) && isRootElement(eltParent)) {
retBody[0] = elt;
return false;
} else
return true;
}
});
} catch (Exception e) {
context.getReporter().logError(e);
}
return retBody[0];
}
private static boolean isBodyElement(Element elt) {
return isTimedTextElement(elt, "body");
}
private static Element getLayoutElement(Document document, TransformerContext context) {
final Element[] retLayout = new Element[1];
try {
Traverse.traverseElements(document, new PreVisitor() {
public boolean visit(Object content, Object parent, Visitor.Order order) {
assert content instanceof Element;
Element elt = (Element) content;
if (isLayoutElement(elt)) {
retLayout[0] = elt;
return false;
} else
return true;
}
});
} catch (Exception e) {
context.getReporter().logError(e);
}
return retLayout[0];
}
private static boolean isLayoutElement(Element elt) {
return isTimedTextElement(elt, "layout");
}
private static boolean isRegionElement(Element elt) {
return isTimedTextElement(elt, "region");
}
private static boolean isAnonymousRegionElement(Element elt) {
if (!isRegionElement(elt))
return false;
else {
String id = getXmlIdentifier(elt);
return (id != null) && (id.indexOf("isdRegion") == 0);
}
}
private static boolean isParagraphElement(Element elt) {
return isTimedTextElement(elt, "p");
}
private static boolean isSpanElement(Element elt) {
return isTimedTextElement(elt, "span");
}
private static boolean isAnonymousSpanElement(Element elt) {
if (!isSpanElement(elt))
return false;
else {
String id = getXmlIdentifier(elt);
return (id != null) && (id.indexOf("isdSpan") == 0);
}
}
private static boolean isStyleElement(Element elt) {
return isTimedTextElement(elt, "style");
}
private static boolean isAnimationElement(Element elt) {
return isTimedTextElement(elt, "set");
}
private static boolean isContentElement(Element elt) {
String nsUri = elt.getNamespaceURI();
if ((nsUri == null) || !nsUri.equals(TTMLHelper.NAMESPACE_TT))
return false;
else {
String localName = elt.getLocalName();
if (localName.equals("body"))
return true;
else if (localName.equals("div"))
return true;
else if (localName.equals("p"))
return true;
else if (localName.equals("span"))
return true;
else if (localName.equals("br"))
return true;
else
return false;
}
}
private static boolean isRegionOrContentElement(Element elt) {
return isRegionElement(elt) || isContentElement(elt);
}
private static void pruneTimingAndRegionAttributes(Document document, TransformerContext context) {
try {
Traverse.traverseElements(document, new PreVisitor() {
public boolean visit(Object content, Object parent, Visitor.Order order) {
assert content instanceof Element;
Element elt = (Element) content;
if (isTimedElement(elt)) {
pruneTimingAttributes(elt);
pruneRegionAttributes(elt);
}
return true;
}
});
} catch (Exception e) {
context.getReporter().logError(e);
}
}
private static void pruneTimingAttributes(Element elt) {
elt.removeAttributeNS(null, "begin");
elt.removeAttributeNS(null, "end");
elt.removeAttributeNS(null, "dur");
elt.removeAttributeNS(null, "timeContainer");
}
private static void pruneRegionAttributes(Element elt) {
elt.removeAttributeNS(null, "region");
}
private static void generateISDWrapper(Document document, TimeInterval interval, TransformerContext context) {
Element root = document.getDocumentElement();
Element isd = document.createElementNS(TTMLHelper.NAMESPACE_ISD, "isd");
isd.setAttributeNS(null, "begin", interval.getBegin().toString());
isd.setAttributeNS(null, "end", interval.getEnd().toString());
copyWrapperAttributes(isd, root);
generateISDComputedStyleSets(isd, root, context);
generateISDRegions(isd, root, context);
unwrapRedundantAnonymousSpans(isd, root, context);
document.removeChild(root);
document.appendChild(isd);
}
private static void copyWrapperAttributes(Element isd, Element root) {
NamedNodeMap attrs = root.getAttributes();
for (int i = 0, n = attrs.getLength(); i < n; ++i) {
Node node = attrs.item(i);
if (node instanceof Attr) {
Attr a = (Attr) node;
String nsUri = a.getNamespaceURI();
if (nsUri == null) {
continue;
} else if (nsUri.equals(TTMLHelper.NAMESPACE_TT_PARAMETER)) {
if (inISDParameterAttributeSet(a) && !isDefaultParameterValue(a)) {
isd.setAttributeNS(nsUri, a.getLocalName(), a.getValue());
}
} else if (nsUri.equals(XML.xmlNamespace)) {
String ln = a.getLocalName();
if (ln.equals("lang") || ln.equals("space"))
isd.setAttributeNS(nsUri, ln, a.getValue());
}
}
}
}
private static boolean inISDParameterAttributeSet(Attr attr) {
String localName = attr.getLocalName();
String value = attr.getValue();
if ((value == null) || value.isEmpty())
return false;
else if (localName.equals("cellResolution"))
return true;
else if (localName.equals("frameRate"))
return true;
else if (localName.equals("frameRateMultiplier"))
return true;
else if (localName.equals("pixelAspectRatio"))
return true;
else if (localName.equals("subFrameRate"))
return true;
else if (localName.equals("tickRate"))
return true;
else
return false;
}
private static void generateISDComputedStyleSets(final Element isd, Element root, TransformerContext context) {
try {
final Map<Element, StyleSet> computedStyleSets = resolveComputedStyles(root, context);
final Set<String> styleIds = new java.util.HashSet<String>();
final Document document = isd.getOwnerDocument();
Traverse.traverseElements(root, null, new PreVisitor() {
public boolean visit(Object content, Object parent, Visitor.Order order) {
assert content instanceof Element;
Element elt = (Element) content;
if (computedStyleSets.containsKey(elt)) {
StyleSet css = computedStyleSets.get(elt);
String id = css.getId();
if (!id.isEmpty()) {
elt.setAttributeNS(TTMLHelper.NAMESPACE_ISD, "css", id);
if (!styleIds.contains(id)) {
Element isdStyle = document.createElementNS(TTMLHelper.NAMESPACE_ISD, "css");
generateAttributes(css, isdStyle);
isd.appendChild(isdStyle);
styleIds.add(id);
}
}
}
return true;
}
});
} catch (Exception e) {
context.getReporter().logError(e);
}
}
private static void generateAttributes(StyleSet ss, Element elt) {
String id = ss.getId();
if ((id != null) && !id.isEmpty()) {
for (StyleSpecification s : ss.getStyles().values()) {
ComparableQName n = s.getName();
elt.setAttributeNS(n.getNamespaceURI(), n.getLocalPart(), s.getValue());
}
elt.setAttributeNS(XML.xmlNamespace, "id", id);
}
}
private static Map<Element, StyleSet> resolveComputedStyles(Element root, TransformerContext context) {
// compute initial value overrides
StyleSet overrides = computeInitialStyleOverrides(root.getOwnerDocument(), context);
// resolve specified style sets
Map<Element, StyleSet> specifiedStyleSets = resolveSpecifiedStyles(root, context, overrides);
// derive {CSS(E)} from {SSS(E)}
Map<Element, StyleSet> computedStyleSets = new java.util.HashMap<Element, StyleSet>();
for (Map.Entry<Element, StyleSet> e : specifiedStyleSets.entrySet()) {
Element elt = e.getKey();
if (isRegionElement(elt)) {
if (findChildElement(elt, TTMLHelper.NAMESPACE_TT, "body") != null)
computedStyleSets.put(elt, applicableStyles(e.getValue(), elt, context));
} else if (isContentElement(elt)) {
computedStyleSets.put(elt, applicableStyles(e.getValue(), elt, context));
}
}
// maybe elide initial values
if (!(Boolean) context.getResourceState(TransformerContext.ResourceState.ttxDontElideInitials.name())) {
for (Map.Entry<Element, StyleSet> e : computedStyleSets.entrySet())
elideInitialValues(e.getValue(), e.getKey(), context);
}
// compute set of unique CSSs
Set<StyleSet> uniqueComputedStyleSets = new java.util.TreeSet<StyleSet>(StyleSet.getValuesComparator());
for (StyleSet css : computedStyleSets.values()) {
if (!css.isEmpty())
uniqueComputedStyleSets.add(css);
}
// obtain ordered list of unique CSSs
List<StyleSet> uniqueStyles = new java.util.ArrayList<StyleSet>(uniqueComputedStyleSets);
// assign identifiers to unique CSSs
int uniqueStyleIndex = 0;
for (StyleSet css : uniqueStyles)
css.setId("s" + uniqueStyleIndex++);
// remap CSS map entries to unique CSSs
for (Map.Entry<Element,StyleSet> e : computedStyleSets.entrySet()) {
StyleSet css = e.getValue();
int index = uniqueStyles.indexOf(css);
if (index >= 0) {
StyleSet cssUnique = uniqueStyles.get(index);
if (css != cssUnique) // N.B. must not use equals() here
e.setValue(cssUnique);
}
}
return computedStyleSets;
}
private static StyleSet computeInitialStyleOverrides(Document doc, TransformerContext context) {
StyleSet overrides = new StyleSet();
for (Element initial : getInitialElements(doc, context)) {
overrides.merge(getInlineStyles(initial));
}
return overrides;
}
private static List<Element> getInitialElements(Document doc, TransformerContext context) {
final List<Element> initials = new java.util.ArrayList<Element>();
try {
Traverse.traverseElements(doc, new PreVisitor() {
public boolean visit(Object content, Object parent, Visitor.Order order) {
assert content instanceof Element;
Element elt = (Element) content;
if (isInitialElement(elt))
initials.add(elt);
return true;
}
});
} catch (Exception e) {
context.getReporter().logError(e);
}
return initials;
}
private static boolean isInitialElement(Element elt) {
return isTimedTextElement(elt, "initial");
}
private static Map<Element, StyleSet> resolveSpecifiedStyles(Element root, TransformerContext context, StyleSet overrides) {
Map<Element, StyleSet> specifiedStyleSets = new java.util.HashMap<Element, StyleSet>();
specifiedStyleSets = resolveSpecifiedStyles(getStyleElements(root, context), specifiedStyleSets, context, overrides);
specifiedStyleSets = resolveSpecifiedStyles(getAnimationElements(root, context), specifiedStyleSets, context, overrides);
specifiedStyleSets = resolveSpecifiedStyles(getRegionOrContentElements(root, context), specifiedStyleSets, context, overrides);
return specifiedStyleSets;
}
private static Collection<Element> getStyleElements(Element root, TransformerContext context) {
final Collection<Element> elts = new java.util.ArrayList<Element>();
try {
Traverse.traverseElements(root, null, new PreVisitor() {
public boolean visit(Object content, Object parent, Visitor.Order order) {
assert content instanceof Element;
Element elt = (Element) content;
if (isStyleElement(elt)) {
elts.add(elt);
}
return true;
}
});
} catch (Exception e) {
context.getReporter().logError(e);
}
return topoSortByStyleReferences(elts, context);
}
private static Collection<Element> topoSortByStyleReferences(Collection<Element> elts, TransformerContext context) {
DirectedGraph<Element> graph = new DirectedGraph<Element>();
for (Element elt : elts)
graph.addNode(elt);
for (Element elt : elts) {
for (Element refStyle : getReferencedStyleElements(elt)) {
graph.addEdge(elt, refStyle);
}
}
try {
List<Element> eltsSorted = TopologicalSort.sort(graph);
// topo sort ensures all forward refs, but we want all reverse refs, so reverse sorted results
Collections.reverse(eltsSorted);
return eltsSorted;
} catch (IllegalArgumentException e) {
Reporter reporter = context.getReporter();
reporter.logError(reporter.message("*KEY*", "Cycle in style chain, unable to resolve styles."));
return new java.util.ArrayList<Element>();
}
}
private static Collection<Element> getAnimationElements(Element root, TransformerContext context) {
final Collection<Element> elts = new java.util.ArrayList<Element>();
try {
Traverse.traverseElements(root, null, new PreVisitor() {
public boolean visit(Object content, Object parent, Visitor.Order order) {
assert content instanceof Element;
Element elt = (Element) content;
if (isAnimationElement(elt)) {
elts.add(elt);
}
return true;
}
});
} catch (Exception e) {
context.getReporter().logError(e);
}
return elts;
}
private static Collection<Element> getRegionOrContentElements(Element root, TransformerContext context) {
final Collection<Element> elts = new java.util.ArrayList<Element>();
try {
Traverse.traverseElements(root, null, new PreVisitor() {
public boolean visit(Object content, Object parent, Visitor.Order order) {
assert content instanceof Element;
Element elt = (Element) content;
if (isRegionOrContentElement(elt))
elts.add(elt);
return true;
}
});
} catch (Exception e) {
context.getReporter().logError(e);
}
return elts;
}
private static Map<Element, StyleSet> resolveSpecifiedStyles(Collection<Element> elts, Map<Element, StyleSet> specifiedStyleSets, TransformerContext context, StyleSet overrides) {
for (Element elt : elts) {
assert !specifiedStyleSets.containsKey(elt);
specifiedStyleSets.put(elt, computeSpecifiedStyleSet(elt, specifiedStyleSets, context, overrides));
}
return specifiedStyleSets;
}
private static StyleSet applicableStyles(StyleSet ss, Element elt, TransformerContext context) {
boolean containsInapplicableStyle = false;
QName eltName = new QName(elt.getNamespaceURI(), elt.getLocalName());
for (StyleSpecification s : ss.getStyles().values()) {
if (!doesStyleApply(eltName, s.getName(), context)) {
containsInapplicableStyle = true;
break;
}
}
if (!containsInapplicableStyle)
return ss;
else {
StyleSet ssNew = new StyleSet(ss.getGeneration());
for (StyleSpecification s : ss.getStyles().values()) {
if (doesStyleApply(eltName, s.getName(), context)) {
ssNew.merge(s);
}
}
return ssNew;
}
}
private static boolean doesStyleApply(Element elt, QName styleName, TransformerContext context) {
QName eltName = new QName(elt.getNamespaceURI(), elt.getLocalName());
return doesStyleApply(eltName, styleName, context);
}
private static boolean doesStyleApply(QName eltName, QName styleName, TransformerContext context) {
return context.getModel().doesStyleApply(eltName, styleName);
}
private static void elideInitialValues(StyleSet ss, Element elt, TransformerContext context) {
QName eltName = new QName(elt.getNamespaceURI(), elt.getLocalName());
List<StyleSpecification> elisions = new java.util.ArrayList<StyleSpecification>();
for (StyleSpecification s : ss.getStyles().values()) {
StyleSpecification initial = getInitialStyle(eltName, s.getName(), context, null);
if (initial != null) {
String value = initial.getValue();
if ((value != null) && value.equals(s.getValue()))
elisions.add(s);
}
}
for (StyleSpecification s : elisions) {
ss.remove(s.getName());
}
}
private static StyleSpecification getInitialStyle(Element elt, QName styleName, TransformerContext context, StyleSet overrides) {
QName eltName = new QName(elt.getNamespaceURI(), elt.getLocalName());
return getInitialStyle(eltName, styleName, context, overrides);
}
private static StyleSpecification getInitialStyle(QName eltName, QName styleName, TransformerContext context, StyleSet overrides) {
String value = context.getModel().getInitialStyleValue(eltName, styleName);
if (value != null) {
if (overrides != null) {
StyleSpecification override = overrides.get(styleName);
if (override != null)
value = override.getValue();
}
return new StyleSpecification(new ComparableQName(styleName), value);
} else
return null;
}
private static StyleSet computeSpecifiedStyleSet(Element elt, Map<Element, StyleSet> specifiedStyleSets, TransformerContext context, StyleSet overrides) {
// See TTML2, Section 8.4.4.2
// 1. initialization
StyleSet sss = new StyleSet(getHelper(context).generateStyleSetIndex(context));
// 2. referential and chained referential styling
for (StyleSet ss : getSpecifiedStyleSets(getReferencedStyleElements(elt), specifiedStyleSets))
sss.merge(ss);
// 3. nested styling
for (StyleSet ss : getSpecifiedStyleSets(getChildStyleElements(elt), specifiedStyleSets))
sss.merge(ss);
// 4. inline styling
sss.merge(getInlineStyles(elt));
// 5. animation styling
if (!isAnimationElement(elt)) {
for (StyleSet ss : getSpecifiedStyleSets(getChildAnimationElements(elt), specifiedStyleSets))
sss.merge(ss);
}
// 6. implicit inheritance and initial value fallback
if (!isAnimationElement(elt) && !isStyleElement(elt)) {
for (QName name : getDefinedStyleNames(context)) {
if (!sss.containsKey(name)) {
StyleSpecification s;
if (!isInheritableStyle(elt, name, context) || isRootStylingElement(elt))
s = getInitialStyle(elt, name, context, overrides);
else if (specialStyleInheritance(elt, name, sss, context))
s = getSpecialInheritedStyle(elt, name, sss, specifiedStyleSets, context);
else
s = getNearestAncestorStyle(elt, name, specifiedStyleSets);
if ((s != null) && (doesStyleApply(elt, name, context) || isRootStylingElement(elt)))
sss.merge(s);
}
}
}
return sss;
}
private static Collection<Element> getReferencedStyleElements(Element elt) {
Collection<Element> elts = new java.util.ArrayList<Element>();
if (elt.hasAttribute("style")) {
String style = elt.getAttribute("style");
if (!style.isEmpty()) {
Document document = elt.getOwnerDocument();
String[] idrefs = style.split("\\s+");
for (String idref : idrefs) {
Element refStyle = document.getElementById(idref);
if (refStyle != null)
elts.add(refStyle);
}
}
}
return elts;
}
private static Collection<Element> getChildStyleElements(Element elt) {
Collection<Element> elts = new java.util.ArrayList<Element>();
for (Node n = elt.getFirstChild(); n != null; n = n.getNextSibling()) {
if (n instanceof Element) {
Element c = (Element) n;
if (isStyleElement(c))
elts.add(c);
}
}
return elts;
}
private static Collection<Element> getChildAnimationElements(Element elt) {
Collection<Element> elts = new java.util.ArrayList<Element>();
for (Node n = elt.getFirstChild(); n != null; n = n.getNextSibling()) {
if (n instanceof Element) {
Element c = (Element) n;
if (isAnimationElement(c))
elts.add(c);
}
}
return elts;
}
private static Collection<StyleSet> getSpecifiedStyleSets(Collection<Element> elts, Map<Element, StyleSet> specifiedStyleSets) {
Collection<StyleSet> styleSets = new java.util.ArrayList<StyleSet>();
for (Element elt : elts) {
if (specifiedStyleSets.containsKey(elt))
styleSets.add(specifiedStyleSets.get(elt));
}
return styleSets;
}
private static StyleSet getInlineStyles(Element elt) {
StyleSet styles = new StyleSet();
NamedNodeMap attrs = elt.getAttributes();
for (int i = 0, n = attrs.getLength(); i < n; ++i) {
Node node = attrs.item(i);
if (node instanceof Attr) {
Attr a = (Attr) node;
String nsUri = a.getNamespaceURI();
if ((nsUri != null) && nsUri.equals(TTMLHelper.NAMESPACE_TT_STYLE)) {
styles.merge(new StyleSpecification(new ComparableQName(a.getNamespaceURI(), a.getLocalName()), a.getValue()));
}
}
}
return styles;
}
private static Collection<QName> getDefinedStyleNames(TransformerContext context) {
return context.getModel().getDefinedStyleNames();
}
private static boolean isInheritableStyle(Element elt, QName styleName, TransformerContext context) {
return isInheritableStyle(new QName(elt.getNamespaceURI(), elt.getLocalName()), styleName, context);
}
private static boolean isInheritableStyle(QName eltName, QName styleName, TransformerContext context) {
return context.getModel().isInheritableStyle(eltName, styleName);
}
private static boolean isRootStylingElement(Element elt) {
/* TBD - MIGRATE TO ROOT in TTML2
int version = getHelper(context).getVersion();
if (version == 1)
return isRegionElement(elt);
else
return isRootElement(elt);
*/
return isRegionElement(elt);
}
private static boolean specialStyleInheritance(Element elt, QName styleName, StyleSet sss, TransformerContext context) {
return getHelper(context).specialStyleInheritance(elt, styleName, sss, context);
}
private static StyleSpecification getSpecialInheritedStyle(Element elt, QName styleName, StyleSet sss, Map<Element, StyleSet> specifiedStyleSets, TransformerContext context) {
return getHelper(context).getSpecialInheritedStyle(elt, styleName, sss, specifiedStyleSets, context);
}
private static StyleSpecification getNearestAncestorStyle(Element elt, QName styleName, Map<Element, StyleSet> specifiedStyleSets) {
for (Node a = elt.getParentNode(); a != null; a = a.getParentNode()) {
if (a instanceof Element) {
Element p = (Element) a;
StyleSet ss = specifiedStyleSets.get(p);
if (ss != null) {
if (ss.containsKey(styleName))
return ss.get(styleName);
}
}
}
return null;
}
private static void generateISDRegions(final Element isd, Element root, final TransformerContext context) {
try {
Traverse.traverseElements(root, null, new PreVisitor() {
public boolean visit(Object content, Object parent, Visitor.Order order) {
assert content instanceof Element;
Element elt = (Element) content;
if (isRegionElement(elt)) {
generateISDRegion(isd, elt, context);
}
return true;
}
});
} catch (Exception e) {
context.getReporter().logError(e);
}
}
private static void generateISDRegion(Element isd, Element region, TransformerContext context) {
Element body = detachBody(region);
if (body != null) {
Document document = isd.getOwnerDocument();
Element isdRegion = document.createElementNS(TTMLHelper.NAMESPACE_ISD, "region");
copyRegionAttributes(isdRegion, region, context);
isdRegion.appendChild(body);
isd.appendChild(isdRegion);
}
}
private static void copyRegionAttributes(Element isdRegion, Element region, TransformerContext context) {
boolean retainLocations = (Boolean) context.getResourceState(TransformerContext.ResourceState.ttxRetainLocations.name());
NamedNodeMap attrs = region.getAttributes();
List<Attr> attrsNew = new java.util.ArrayList<Attr>();
for (int i = 0, n = attrs.getLength(); i < n; ++i) {
Node node = attrs.item(i);
Attr aNew = null;
if (node instanceof Attr) {
Attr a = (Attr) node;
String nsUri = a.getNamespaceURI();
String localName = a.getLocalName();
if (nsUri != null) {
if (nsUri.equals(XML.xmlNamespace)) {
if (localName.equals("id"))
aNew = a;
} else if (nsUri.equals(TTMLHelper.NAMESPACE_ISD)) {
if (localName.equals("css"))
aNew = a;
} else if (nsUri.equals(Annotations.getNamespace())) {
if (retainLocations) {
if (localName.equals("loc"))
aNew = a;
}
}
}
}
if (aNew != null)
attrsNew.add(aNew);
}
for (Attr a : attrsNew)
isdRegion.setAttributeNS(a.getNamespaceURI(), a.getLocalName(), a.getValue());
}
private static Element detachBody(Element region) {
Element body = findChildElement(region, TTMLHelper.NAMESPACE_TT, "body");
if (body != null) {
assert body.getParentNode() == region;
region.removeChild(body);
return body;
} else
return null;
}
private static void unwrapRedundantAnonymousSpans(final Element isd, Element root, TransformerContext context) {
try {
Traverse.traverseElements(isd, null, new PostVisitor() {
public boolean visit(Object content, Object parent, Visitor.Order order) {
assert content instanceof Element;
Element elt = (Element) content;
if (isAnonymousSpanElement(elt)) {
if (parent instanceof Element) {
if (hasSameComputedStyleSet(elt, (Element) parent))
unwrapAnonymousSpan(elt, (Element) parent);
}
}
return true;
}
});
} catch (Exception e) {
context.getReporter().logError(e);
}
}
private static boolean hasSameComputedStyleSet(Element e1, Element e2) {
if (!e1.hasAttributeNS(TTMLHelper.NAMESPACE_ISD, "css"))
return false;
else if (!e2.hasAttributeNS(TTMLHelper.NAMESPACE_ISD, "css"))
return false;
else {
String s1 = e1.getAttributeNS(TTMLHelper.NAMESPACE_ISD, "css");
String s2 = e2.getAttributeNS(TTMLHelper.NAMESPACE_ISD, "css");
return s1.equals(s2);
}
}
private static void unwrapAnonymousSpan(Element elt, Element parent) {
Node fc = elt.getFirstChild();
assert fc != null;
Node lc = elt.getLastChild();
assert lc == fc;
if (fc instanceof Text) {
Text text = (Text) elt.removeChild(fc);
assert text != null;
parent.replaceChild(text, elt);
}
}
private static Element findChildElement(Element elt, String namespace, String name) {
for (Node n = elt.getFirstChild(); n != null; n = n.getNextSibling()) {
if (n instanceof Element) {
Element c = (Element) n;
String nsUri = c.getNamespaceURI();
String localName = c.getLocalName();
if ((namespace == null) ^ (nsUri == null))
continue;
else if (!localName.equals(name))
continue;
else
return c;
}
}
return null;
}
private void pruneISDExclusions(Document document, final TransformerContext context) {
try {
Traverse.traverseElements(document, new PreVisitor() {
public boolean visit(Object content, Object parent, Visitor.Order order) {
assert content instanceof Element;
Element elt = (Element) content;
if (!maybeExcludeElement(elt, context))
maybeExcludeAttributes(elt, context);
return true;
}
});
} catch (Exception e) {
context.getReporter().logError(e);
}
}
private static boolean maybeExcludeElement(Element elt, TransformerContext context) {
boolean retainMetadata = (Boolean) context.getResourceState(TransformerContext.ResourceState.ttxRetainMetadata.name());
String nsUri = elt.getNamespaceURI();
boolean exclude = false;
if (nsUri.equals(TTMLHelper.NAMESPACE_TT_METADATA)) {
if (!retainMetadata)
exclude = true;
}
if (exclude) {
excludeElement(elt);
return true;
} else
return false;
}
private static void excludeElement(Element elt) {
Node parent = elt.getParentNode();
if (parent != null) {
parent.removeChild(elt);
}
}
private static boolean maybeExcludeAttributes(Element elt, TransformerContext context) {
boolean retainLocations = (Boolean) context.getResourceState(TransformerContext.ResourceState.ttxRetainLocations.name());
String nsUriElt = elt.getNamespaceURI();
NamedNodeMap attrs = elt.getAttributes();
List<Attr> exclusions = new java.util.ArrayList<Attr>();
for (int i = 0, n = attrs.getLength(); i < n; ++i) {
Node node = attrs.item(i);
if (node instanceof Attr) {
Attr a = (Attr) node;
String nsUri = a.getNamespaceURI();
String localName = a.getLocalName();
String value = a.getValue();
if (nsUri == null) {
if (localName.equals("style") && value.isEmpty())
exclusions.add(a);
else
continue;
} else if (nsUri.equals(TTMLHelper.NAMESPACE_TT_METADATA)) {
exclusions.add(a);
} else if (nsUri.equals(TTMLHelper.NAMESPACE_TT_PARAMETER)) {
if (isDefaultParameterValue(a))
exclusions.add(a);
} else if (nsUri.equals(TTMLHelper.NAMESPACE_TT_STYLE)) {
if ((nsUriElt == null) || !nsUriElt.equals(TTMLHelper.NAMESPACE_ISD))
exclusions.add(a);
} else if (nsUri.equals(TTMLHelper.NAMESPACE_ISD)) {
if (!localName.equals("css"))
exclusions.add(a);
} else if (nsUri.equals(Annotations.getNamespace())) {
if (!retainLocations)
exclusions.add(a);
} else if (nsUri.equals(XML.xmlnsNamespace)) {
if (value != null) {
if (value.equals(TTMLHelper.NAMESPACE_ISD)) {
if ((nsUriElt != null) && nsUriElt.equals(TTMLHelper.NAMESPACE_TT))
exclusions.add(a);
} else if (value.equals(TTMLHelper.NAMESPACE_TT))
exclusions.add(a);
else if (value.equals(TTMLHelper.NAMESPACE_TT_METADATA))
exclusions.add(a);
else if (value.equals(Annotations.getNamespace()))
exclusions.add(a);
}
}
}
}
for (Attr a : exclusions)
elt.removeAttributeNode(a);
return exclusions.size() > 0;
}
// TBD - use defaulting data from TTML1ParameterVerifier.parameterAccessorMap
private static boolean isDefaultParameterValue(Attr attr) {
String localName = attr.getLocalName();
String value = attr.getValue();
if ((value == null) || value.isEmpty())
return false;
else if (localName.equals("cellResolution"))
return value.equals("32 15");
else if (localName.equals("clockMode"))
return value.equals("utc");
else if (localName.equals("dropMode"))
return value.equals("nonDrop");
else if (localName.equals("frameRateMultiplier"))
return value.equals("1 1");
else if (localName.equals("markerMode"))
return value.equals("discontinuous");
else if (localName.equals("pixelAspectRatio"))
return value.equals("1 1");
else if (localName.equals("subFrameRate"))
return value.equals("1");
else if (localName.equals("tickRate"))
return value.equals("1");
else if (localName.equals("timeBase"))
return value.equals("media");
else
return false;
}
private static boolean hasUsableContent(Document document, TransformerContext context) {
Element root = document.getDocumentElement();
return (root != null) && hasUsableContent(root, context);
}
private static void cleanOutputDirectory(File directory, TransformerContext context) {
Reporter reporter = context.getReporter();
reporter.logInfo(reporter.message("*KEY*", "Cleaning ISD artifacts from output directory ''{0}''...", directory.getPath()));
File[] files = directory.listFiles();
if (files != null) {
for (File f : files) {
String name = f.getName();
if (name.indexOf("isd") != 0)
continue;
else if (name.indexOf(".xml") != (name.length() - 4))
continue;
else if (!f.delete())
throw new TransformerException("unable to clean output directory: can't delete: '" + name + "'");
}
}
}
private Object writeISD(Document document, int sequenceIndex, boolean suppressOutput, TransformerContext context) {
if (suppressOutput)
return writeISDAsByteArray(document, sequenceIndex, context);
else
return writeISDAsFile(document, sequenceIndex, context);
}
private Object writeISDAsFile(Document document, int sequenceIndex, TransformerContext context) {
Reporter reporter = context.getReporter();
FileOutputStream fos = null;
BufferedOutputStream bos = null;
try {
String outputFileName = MessageFormat.format(outputPattern, sequenceIndex);
File outputFile = new File(outputDirectory, outputFileName);
fos = new FileOutputStream(outputFile);
bos = new BufferedOutputStream(fos);
writeISD(document, bos, context);
reporter.logInfo(reporter.message("*KEY*", "Wrote ISD ''{0}''.", outputFile.getAbsolutePath()));
return outputFile;
} catch (FileNotFoundException e) {
reporter.logError(e);
return null;
} finally {
IOUtil.closeSafely(bos);
IOUtil.closeSafely(fos);
}
}
private Object writeISDAsByteArray(Document document, int sequenceIndex, TransformerContext context) {
Reporter reporter = context.getReporter();
ByteArrayOutputStream bas = null;
BufferedOutputStream bos = null;
try {
bas = new ByteArrayOutputStream();
bos = new BufferedOutputStream(bas);
writeISD(document, bos, context);
return bas.toByteArray();
} catch (Exception e) {
reporter.logError(e);
return null;
} finally {
IOUtil.closeSafely(bos);
IOUtil.closeSafely(bas);
}
}
private void writeISD(Document document, OutputStream os, TransformerContext context) throws TransformerException {
BufferedWriter bw = null;
try {
TransformerFactory tf = TransformerFactory.newInstance();
DOMSource source = new DOMSource(document);
bw = new BufferedWriter(new OutputStreamWriter(os, outputEncoding));
StreamResult result = new StreamResult(bw);
javax.xml.transform.Transformer t = tf.newTransformer();
t.setOutputProperty(OutputKeys.INDENT, outputIndent ? "yes" : "no");
t.transform(source, result);
} catch (TransformerConfigurationException e) {
throw new RuntimeException(e);
} catch (javax.xml.transform.TransformerException e) {
throw new RuntimeException(e);
} finally {
if (bw != null) {
try { bw.close(); } catch (IOException e) {}
}
}
}
}
}
| bsd-2-clause |
jupsal/schmies-jTEM | libUnzipped/de/jtem/mfc/set/MultiIndexedDoubleSet.java | 5530 | /**
This file is part of a jTEM project.
All jTEM projects are licensed under the FreeBSD license
or 2-clause BSD license (see http://www.opensource.org/licenses/bsd-license.php).
Copyright (c) 2002-2009, Technische Universität Berlin, jTEM
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
OF SUCH DAMAGE.
**/
package de.jtem.mfc.set;
public class MultiIndexedDoubleSet extends MultiIndexedSet {
public static final long serialVersionUID = 1L;
final double [] set;
public MultiIndexedDoubleSet( int [] max ) {
this( new int[ max.length ], max );
}
public MultiIndexedDoubleSet( MultiIndexedSet multiIndexedSet ) {
this( multiIndexedSet.min, multiIndexedSet.max );
}
public MultiIndexedDoubleSet( MultiIndexedDoubleSet multiIndexedDoubleSet ) {
super( multiIndexedDoubleSet.min, multiIndexedDoubleSet.max );
set = (double [])multiIndexedDoubleSet.set.clone();
}
public MultiIndexedDoubleSet( int [] min, int [] max ) {
super( min, max );
set = new double[ numOfVertices ];
}
public double getValue( int [] index ) {
return getValue( index, true );
}
public double getValue( int [] index, boolean checkBounds ) {
return set[ getLinearIndexOf( index, checkBounds ) ];
}
public double getValue( int linearIndex ) {
return set[ linearIndex ];
}
public void setValue( int [] index, double value ) {
setValue( index, value, true );
}
public void setValue( int [] index, double value, boolean checkBounds ) {
set[ getLinearIndexOf( index, checkBounds ) ] = value;
}
public void setValue( int linearIndex, double value ) {
set[ linearIndex ] = value;
}
public Object toArray() {
return toArray( (Object)null );
}
public Object toArray( Object array ) {
switch( dim ) {
case 1:
return toArray( (double [])array );
case 2:
return toArray( (double [][])array );
case 3:
return toArray( (double [][][])array );
case 4:
return toArray( (double [][][][])array );
default:
throw new UnsupportedOperationException("dimension bigger then 4 are not supported");
}
}
public double [] toArray( double [] array ) {
if( dim != 1 )
throw new IllegalArgumentException( "array has wrong dimension" );
if( array == null || array.length != max[0] - min[0] + 1 )
array = new double [ max[0] - min[0] + 1 ];
System.arraycopy( set, 0, array, 0, array.length );
return array;
}
public double [][] toArray( double [][] array ) {
if( dim != 2 )
throw new IllegalArgumentException( "array has wrong dimension" );
final int xSize = max[0] - min[0] + 1;
final int ySize = max[1] - min[1] + 1;
if( array == null ||
array .length != xSize ||
array[0].length != ySize )
array = new double [ xSize ][ ySize ];
for( int i=0, j=0; i<xSize; i++, j+=ySize )
System.arraycopy( set, j, array[i], 0, ySize );
return array;
}
public double [][][] toArray( double [][][] array ) {
if( dim != 3 )
throw new IllegalArgumentException( "array has wrong dimension" );
final int xSize = max[0] - min[0] + 1;
final int ySize = max[1] - min[1] + 1;
final int vSize = max[2] - min[2] + 1;
if( array == null ||
array .length != xSize ||
array[0] .length != ySize ||
array[0][0].length != vSize )
array = new double [ xSize ][ ySize ][ vSize ];
for( int i=0, k=0; i<xSize; i++ )
for( int j=0; j<ySize; j++, k+=vSize )
System.arraycopy( set, k, array[i][j], 0, vSize );
return array;
}
public double [][][][] toArray( double [][][][] array ) {
if( dim != 4 )
throw new IllegalArgumentException( "array has wrong dimension" );
final int xSize = max[0] - min[0] + 1;
final int ySize = max[1] - min[1] + 1;
final int vSize = max[2] - min[2] + 1;
final int wSize = max[3] - min[3] + 1;
if( array == null ||
array .length != xSize ||
array[0] .length != ySize ||
array[0][0] .length != vSize ||
array[0][0][0].length != wSize )
array = new double [ xSize ][ ySize ][ vSize ][ wSize ];
for( int i=0, l=0; i<xSize; i++ )
for( int j=0; j<ySize; j++ )
for( int k=0; k<vSize; k++, l+=wSize )
System.arraycopy( set, l, array[i][j][k], 0, wSize );
return array;
}
}
| bsd-2-clause |
tfennelly/stapler | core/src/main/java/org/kohsuke/stapler/StaplerResponse.java | 9409 | /*
* Copyright (c) 2004-2010, Kohsuke Kawaguchi
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided
* that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
* THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.kohsuke.stapler;
import net.sf.json.JsonConfig;
import org.kohsuke.stapler.export.Flavor;
import javax.annotation.Nonnull;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Writer;
import java.net.URL;
import java.net.URLConnection;
import org.kohsuke.stapler.export.Model;
import org.kohsuke.stapler.export.NamedPathPruner;
/**
* Defines additional operations made available by Stapler.
*
* @see Stapler#getCurrentResponse()
* @author Kohsuke Kawaguchi
*/
public interface StaplerResponse extends HttpServletResponse {
/**
* Evaluates the url against the given object and
* forwards the request to the result.
*
* <p>
* This can be used for example inside an action method
* to forward a request to a JSP.
*
* @param it
* the URL is evaluated against this object. Must not be null.
* @param url
* the relative URL (e.g., "foo" or "foo/bar") to resolve
* against the "it" object.
* @param request
* Request to be forwarded.
*/
void forward(Object it, String url, StaplerRequest request) throws ServletException, IOException;
/**
* Redirects the browser to where it came from (the referer.)
*/
void forwardToPreviousPage(StaplerRequest request) throws ServletException, IOException;
/**
* Works like {@link #sendRedirect(String)} except that this method
* escapes the URL.
*/
void sendRedirect2(@Nonnull String url) throws IOException;
/**
* Works like {@link #sendRedirect2(String)} but allows the caller to specify the HTTP status code.
*/
void sendRedirect(int statusCore, @Nonnull String url) throws IOException;
/**
* Serves a static resource.
*
* <p>
* This method sets content type, HTTP status code, sends the complete data
* and closes the response. This method also handles cache-control HTTP headers
* like "If-Modified-Since" and others.
*/
void serveFile(StaplerRequest request, URL res) throws ServletException, IOException;
void serveFile(StaplerRequest request, URL res, long expiration) throws ServletException, IOException;
/**
* Works like {@link #serveFile(StaplerRequest, URL)} but chooses the locale specific
* version of the resource if it's available. The convention of "locale specific version"
* is the same as that of property files.
* So Japanese resource for <tt>foo.html</tt> would be named <tt>foo_ja.html</tt>.
*/
void serveLocalizedFile(StaplerRequest request, URL res) throws ServletException, IOException;
/**
* Works like {@link #serveFile(StaplerRequest, URL, long)} but chooses the locale
* specific version of the resource if it's available.
*
* See {@link #serveLocalizedFile(StaplerRequest, URL)} for more details.
*/
void serveLocalizedFile(StaplerRequest request, URL res, long expiration) throws ServletException, IOException;
/**
* Serves a static resource.
*
* <p>
* This method works like {@link #serveFile(StaplerRequest, URL)} but this version
* allows the caller to fetch data from anywhere.
*
* @param data
* {@link InputStream} that contains the data of the static resource.
* @param lastModified
* The timestamp when the resource was last modified. See {@link URLConnection#getLastModified()}
* for the meaning of the value. 0 if unknown, in which case "If-Modified-Since" handling
* will not be performed.
* @param expiration
* The number of milliseconds until the resource will "expire".
* Until it expires the browser will be allowed to cache it
* and serve it without checking back with the server.
* After it expires, the client will send conditional GET to
* check if the resource is actually modified or not.
* If 0, it will immediately expire.
* @param contentLength
* if the length of the input stream is known in advance, specify that value
* so that HTTP keep-alive works. Otherwise specify -1 to indicate that the length is unknown.
* @param fileName
* file name of this resource. Used to determine the MIME type.
* Since the only important portion is the file extension, this could be just a file name,
* or a full path name, or even a pseudo file name that doesn't actually exist.
* It supports both '/' and '\\' as the path separator.
*
* If this string starts with "mime-type:", like "mime-type:foo/bar", then "foo/bar" will
* be used as a MIME type without consulting the servlet container.
*/
void serveFile(StaplerRequest req, InputStream data, long lastModified, long expiration, long contentLength, String fileName) throws ServletException, IOException;
/**
* @Deprecated use form with long contentLength
*/
void serveFile(StaplerRequest req, InputStream data, long lastModified, long expiration, int contentLength, String fileName) throws ServletException, IOException;
/**
* Serves a static resource.
*
* Expiration date is set to the value that forces browser to do conditional GET
* for all resources.
*
* @see #serveFile(StaplerRequest, InputStream, long, long, int, String)
*/
void serveFile(StaplerRequest req, InputStream data, long lastModified, long contentLength, String fileName) throws ServletException, IOException;
/**
* @Deprecated use form with long contentLength
*/
void serveFile(StaplerRequest req, InputStream data, long lastModified, int contentLength, String fileName) throws ServletException, IOException;
/**
* Serves the exposed bean in the specified flavor.
*
* <p>
* This method performs the complete output from the header to the response body.
* If the flavor is JSON, this method also supports JSONP via the {@code jsonp} query parameter.
*
* <p>The {@code depth} parameter may be used to specify a recursion depth
* as in {@link Model#writeTo(Object,int,DataWriter)}.
*
* <p>As of 1.146, the {@code tree} parameter may be used to control the output
* in detail; see {@link NamedPathPruner#NamedPathPruner(String)} for details.
*/
void serveExposedBean(StaplerRequest req, Object exposedBean, Flavor flavor) throws ServletException,IOException;
/**
* Works like {@link #getOutputStream()} but tries to send the response
* with gzip compression if the client supports it.
*
* <p>
* This method is useful for sending out a large text content.
*
* @param req
* Used to determine whether the client supports compression
*/
OutputStream getCompressedOutputStream(HttpServletRequest req) throws IOException;
/**
* Works like {@link #getCompressedOutputStream(HttpServletRequest)} but this
* method is for {@link #getWriter()}.
*/
Writer getCompressedWriter(HttpServletRequest req) throws IOException;
/**
* Performs the reverse proxy to the given URL.
*
* @return
* The status code of the response.
*/
int reverseProxyTo(URL url, StaplerRequest req) throws IOException;
/**
* The JsonConfig to be used when serializing java beans from js bound methods to JSON.
* Setting this to null will make the default config to be used.
*
* @param config the config
*/
void setJsonConfig(JsonConfig config);
/**
* The JsonConfig to be used when serializing java beans to JSON previously set by {@link #setJsonConfig(JsonConfig)}.
* Will return the default config if nothing has previously been set.
*
* @return the config
*/
JsonConfig getJsonConfig();
}
| bsd-2-clause |
oGZo/zjgsu-abroadStu-web | backend/zjgsu-abroadStu/abroadStu-model/src/main/java/com/zjgsu/abroadStu/model/http/ResponseCodeList.java | 446 | package com.zjgsu.abroadStu.model.http;
/**
* Created by JIADONG on 16/3/16.
*/
public class ResponseCodeList {
// 请求成功码
public static final int Success = 0;
//失败码
public static final int Fail = 1000;
//token过期
public static final int EXPIRED_TOKEN= 99;
// 服务端错误
public static final int SERVER_ERROR = 5001;
// api过期
public static final int API_EXPIRED = 5002;
}
| bsd-2-clause |
twistedtiger/tt08 | CardsAgainstHumanity/src/cardsagainsthumanity/CardsAgainstHumans.java | 563 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package cardsagainsthumanity;
import java.io.IOException;
/**
*
* @author thoma_000
*/
public class CardsAgainstHumans {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException {
// TODO code application logic here
GameGUI game = new GameGUI();
game.init();
}
}
| bsd-2-clause |
Pushjet/Pushjet-Android | gradle/wrapper/dists/gradle-1.12-all/4ff8jj5a73a7zgj5nnzv1ubq0/gradle-1.12/src/core-impl/org/gradle/api/internal/artifacts/ivyservice/resolveengine/DefaultDependencyResolver.java | 8322 | /*
* Copyright 2011 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.gradle.api.internal.artifacts.ivyservice.resolveengine;
import org.apache.ivy.Ivy;
import org.gradle.api.Action;
import org.gradle.api.artifacts.ResolveException;
import org.gradle.api.artifacts.result.ResolvedComponentResult;
import org.gradle.api.internal.artifacts.ArtifactDependencyResolver;
import org.gradle.api.internal.artifacts.ModuleMetadataProcessor;
import org.gradle.api.internal.artifacts.ResolverResults;
import org.gradle.api.internal.artifacts.configurations.ConfigurationInternal;
import org.gradle.api.internal.artifacts.ivyservice.*;
import org.gradle.api.internal.artifacts.ivyservice.clientmodule.ClientModuleResolver;
import org.gradle.api.internal.artifacts.ivyservice.ivyresolve.ErrorHandlingArtifactResolver;
import org.gradle.api.internal.artifacts.ivyservice.ivyresolve.LazyDependencyToModuleResolver;
import org.gradle.api.internal.artifacts.ivyservice.ivyresolve.RepositoryChain;
import org.gradle.api.internal.artifacts.ivyservice.ivyresolve.ResolveIvyFactory;
import org.gradle.api.internal.artifacts.ivyservice.ivyresolve.strategy.LatestStrategy;
import org.gradle.api.internal.artifacts.ivyservice.ivyresolve.strategy.VersionMatcher;
import org.gradle.api.internal.artifacts.ivyservice.projectmodule.ProjectArtifactResolver;
import org.gradle.api.internal.artifacts.ivyservice.projectmodule.ProjectComponentRegistry;
import org.gradle.api.internal.artifacts.ivyservice.projectmodule.ProjectDependencyResolver;
import org.gradle.api.internal.artifacts.ivyservice.resolutionstrategy.StrictConflictResolution;
import org.gradle.api.internal.artifacts.ivyservice.resolveengine.oldresult.DefaultResolvedConfigurationBuilder;
import org.gradle.api.internal.artifacts.ivyservice.resolveengine.oldresult.TransientConfigurationResults;
import org.gradle.api.internal.artifacts.ivyservice.resolveengine.oldresult.TransientConfigurationResultsBuilder;
import org.gradle.api.internal.artifacts.ivyservice.resolveengine.result.ResolutionResultBuilder;
import org.gradle.api.internal.artifacts.ivyservice.resolveengine.result.StreamingResolutionResultBuilder;
import org.gradle.api.internal.artifacts.ivyservice.resolveengine.store.ResolutionResultsStoreFactory;
import org.gradle.api.internal.artifacts.ivyservice.resolveengine.store.StoreSet;
import org.gradle.api.internal.artifacts.repositories.ResolutionAwareRepository;
import org.gradle.api.internal.cache.BinaryStore;
import org.gradle.api.internal.cache.Store;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
public class DefaultDependencyResolver implements ArtifactDependencyResolver {
private static final Logger LOGGER = LoggerFactory.getLogger(DefaultDependencyResolver.class);
private final LocalComponentFactory localComponentFactory;
private final ResolveIvyFactory ivyFactory;
private final ProjectComponentRegistry projectComponentRegistry;
private final CacheLockingManager cacheLockingManager;
private final IvyContextManager ivyContextManager;
private final ResolutionResultsStoreFactory storeFactory;
private final VersionMatcher versionMatcher;
private final LatestStrategy latestStrategy;
public DefaultDependencyResolver(ResolveIvyFactory ivyFactory, LocalComponentFactory localComponentFactory,
ProjectComponentRegistry projectComponentRegistry, CacheLockingManager cacheLockingManager, IvyContextManager ivyContextManager,
ResolutionResultsStoreFactory storeFactory, VersionMatcher versionMatcher, LatestStrategy latestStrategy) {
this.ivyFactory = ivyFactory;
this.localComponentFactory = localComponentFactory;
this.projectComponentRegistry = projectComponentRegistry;
this.cacheLockingManager = cacheLockingManager;
this.ivyContextManager = ivyContextManager;
this.storeFactory = storeFactory;
this.versionMatcher = versionMatcher;
this.latestStrategy = latestStrategy;
}
public void resolve(final ConfigurationInternal configuration,
final List<? extends ResolutionAwareRepository> repositories,
final ModuleMetadataProcessor metadataProcessor,
final ResolverResults results) throws ResolveException {
LOGGER.debug("Resolving {}", configuration);
ivyContextManager.withIvy(new Action<Ivy>() {
public void execute(Ivy ivy) {
RepositoryChain repositoryChain = ivyFactory.create(configuration, repositories, metadataProcessor);
DependencyToModuleVersionResolver dependencyResolver = repositoryChain.getDependencyResolver();
dependencyResolver = new ClientModuleResolver(dependencyResolver);
ProjectDependencyResolver projectDependencyResolver = new ProjectDependencyResolver(projectComponentRegistry, localComponentFactory, dependencyResolver);
dependencyResolver = projectDependencyResolver;
DependencyToModuleVersionIdResolver idResolver = new LazyDependencyToModuleResolver(dependencyResolver, versionMatcher);
idResolver = new VersionForcingDependencyToModuleResolver(idResolver, configuration.getResolutionStrategy().getDependencyResolveRule());
ArtifactResolver artifactResolver = createArtifactResolver(repositoryChain);
ModuleConflictResolver conflictResolver;
if (configuration.getResolutionStrategy().getConflictResolution() instanceof StrictConflictResolution) {
conflictResolver = new StrictConflictResolver();
} else {
conflictResolver = new LatestModuleConflictResolver(latestStrategy);
}
conflictResolver = new VersionSelectionReasonResolver(conflictResolver);
DependencyGraphBuilder builder = new DependencyGraphBuilder(idResolver, projectDependencyResolver, artifactResolver, conflictResolver, new DefaultDependencyToConfigurationResolver());
StoreSet stores = storeFactory.createStoreSet();
BinaryStore newModelStore = stores.nextBinaryStore();
Store<ResolvedComponentResult> newModelCache = stores.oldModelStore();
ResolutionResultBuilder newModelBuilder = new StreamingResolutionResultBuilder(newModelStore, newModelCache);
BinaryStore oldModelStore = stores.nextBinaryStore();
Store<TransientConfigurationResults> oldModelCache = stores.newModelStore();
TransientConfigurationResultsBuilder oldTransientModelBuilder = new TransientConfigurationResultsBuilder(oldModelStore, oldModelCache);
DefaultResolvedConfigurationBuilder oldModelBuilder = new DefaultResolvedConfigurationBuilder(oldTransientModelBuilder);
builder.resolve(configuration, newModelBuilder, oldModelBuilder);
DefaultLenientConfiguration result = new DefaultLenientConfiguration(configuration, oldModelBuilder, cacheLockingManager);
results.resolved(new DefaultResolvedConfiguration(result), newModelBuilder.complete());
}
});
}
private ArtifactResolver createArtifactResolver(RepositoryChain repositoryChain) {
ArtifactResolver artifactResolver = repositoryChain.getArtifactResolver();
artifactResolver = new ProjectArtifactResolver(artifactResolver);
artifactResolver = new ContextualArtifactResolver(cacheLockingManager, ivyContextManager, artifactResolver);
artifactResolver = new ErrorHandlingArtifactResolver(artifactResolver);
return artifactResolver;
}
}
| bsd-2-clause |
javafunk/funk | funk-core/src/test/java/org/javafunk/funk/LazilyRestTest.java | 2024 | /*
* Copyright (C) 2011-Present Funk committers.
* All rights reserved.
*
* The software in this package is published under the terms of the BSD
* style license a copy of which has been included with this distribution in
* the LICENSE.txt file.
*/
package org.javafunk.funk;
import org.junit.Test;
import static org.javafunk.funk.Iterables.materialize;
import static org.javafunk.funk.Literals.iterableWith;
import static org.javafunk.matchbox.Matchers.hasOnlyItemsInOrder;
import static org.junit.Assert.assertThat;
public class LazilyRestTest {
@Test
public void shouldReturnTheRestOfTheIterable(){
// Given
Iterable<String> iterable = iterableWith("a", "b", "c", "d");
Iterable<String> expectedRest = iterableWith("b", "c", "d");
// When
Iterable<String> rest = Lazily.rest(iterable);
// Then
assertThat(materialize(rest), hasOnlyItemsInOrder(expectedRest));
}
@Test
public void shouldReturnEmptyIterableForAnIterableWithOneElement(){
// Given
Iterable<String> iterable = iterableWith("a");
Iterable<String> expectedRest = Iterables.empty();
// When
Iterable<String> rest = Lazily.rest(iterable);
// Then
assertThat(materialize(rest), hasOnlyItemsInOrder(expectedRest));
}
@Test
public void shouldReturnEmptyIterableForAnEmptyIterable(){
// Given
Iterable<String> iterable = Iterables.empty();
Iterable<String> expectedRest = Iterables.empty();
// When
Iterable<String> rest = Lazily.rest(iterable);
// Then
assertThat(materialize(rest), hasOnlyItemsInOrder(expectedRest));
}
@Test(expected = NullPointerException.class)
public void shouldThrowNullPointerExceptionIfAnEmptyIterableIsPassedToRest() throws Exception {
// Given
Iterable<String> iterable = null;
// When
Lazily.rest(iterable);
// Then a NullPointerException is thrown
}
}
| bsd-2-clause |
nvdb-vegdata/sosi-reader | impl/src/main/java/no/vegvesen/nvdb/sosi/encoding/SosiCharsetProvider.java | 2614 | /*
* Copyright (c) 2015-2016, Statens vegvesen
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
package no.vegvesen.nvdb.sosi.encoding;
import no.vegvesen.nvdb.sosi.encoding.charset.DECN7;
import no.vegvesen.nvdb.sosi.encoding.charset.DOSN8;
import no.vegvesen.nvdb.sosi.encoding.charset.ISO8859_10;
import no.vegvesen.nvdb.sosi.encoding.charset.ND7;
import java.nio.charset.Charset;
import java.nio.charset.spi.CharsetProvider;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
/**
* Charset provider for custom SOSI character sets.
*
* @author Tore Eide Andersen (Kantega AS)
*/
public class SosiCharsetProvider extends CharsetProvider {
private final List<Charset> charsets;
private static final Charset ISO8859_10 = new ISO8859_10();
private static final Charset DOSN8 = new DOSN8();
private static final Charset ND7 = new ND7();
private static final Charset DECN7 = new DECN7();
public SosiCharsetProvider() {
this.charsets = Arrays.asList(ISO8859_10, DOSN8, ND7, DECN7);
}
@Override
public Iterator<Charset> charsets() {
return charsets.iterator();
}
@Override
public Charset charsetForName(String charsetName) {
return charsets.stream().filter(cs -> cs.name().equals(charsetName)).findFirst().orElse(null);
}
}
| bsd-2-clause |
md-k-sarker/ROWL | src/main/java/edu/wright/dase/model/ruletoaxiom/RollUp.java | 9260 | package edu.wright.dase.model.ruletoaxiom;
import java.util.HashSet;
import java.util.Set;
import org.semanticweb.owlapi.model.OWLClassExpression;
import org.semanticweb.owlapi.model.OWLDataRange;
import org.semanticweb.owlapi.model.OWLIndividual;
import org.semanticweb.owlapi.model.OWLLiteral;
import org.semanticweb.owlapi.model.OWLObjectPropertyExpression;
import org.semanticweb.owlapi.model.SWRLArgument;
import org.semanticweb.owlapi.model.SWRLAtom;
import org.semanticweb.owlapi.model.SWRLClassAtom;
import org.semanticweb.owlapi.model.SWRLDataPropertyAtom;
import org.semanticweb.owlapi.model.SWRLDataRangeAtom;
import org.semanticweb.owlapi.model.SWRLIArgument;
import org.semanticweb.owlapi.model.SWRLIndividualArgument;
import org.semanticweb.owlapi.model.SWRLLiteralArgument;
import org.semanticweb.owlapi.model.SWRLObjectPropertyAtom;
import org.semanticweb.owlapi.model.SWRLVariable;
import uk.ac.manchester.cs.owl.owlapi.SWRLClassAtomImpl;
public class RollUp {
// Public Methods
public static void rollUpLiterals(SWRLIArgument root, Set<SWRLAtom> atoms) {
Set<SWRLArgument> roots = new HashSet<SWRLArgument>();
roots.add(root);
rollUpLiterals(roots, atoms);
}
public static void rollUpLiterals(SWRLVariable root1, SWRLVariable root2, Set<SWRLAtom> atoms) {
Set<SWRLArgument> roots = new HashSet<SWRLArgument>();
roots.add(root1);
roots.add(root2);
rollUpLiterals(roots, atoms);
}
public static void rollUpIndsAndVars(SWRLVariable root, Set<SWRLAtom> atoms) {
Set<SWRLArgument> roots = new HashSet<SWRLArgument>();
roots.add(root);
rollUpIndsAndVars(roots, atoms);
}
public static void rollUpIndsAndVars(SWRLIArgument root1, SWRLVariable root2, Set<SWRLAtom> atoms) {
Set<SWRLArgument> roots = new HashSet<SWRLArgument>();
roots.add(root1);
roots.add(root2);
rollUpIndsAndVars(roots, atoms);
}
public static void rollUpIndsAndVars(SWRLVariable root1, SWRLVariable root2, SWRLVariable root3, Set<SWRLAtom> atoms) {
Set<SWRLArgument> roots = new HashSet<SWRLArgument>();
roots.add(root1);
roots.add(root2);
roots.add(root3);
rollUpIndsAndVars(roots, atoms);
}
// Private Methods
private static void rollUpLiterals(Set<SWRLArgument> roots, Set<SWRLAtom> atoms) {
Set<SWRLLiteralArgument> lits = Srd.getLitsToSet(atoms);
for (SWRLLiteralArgument lit : lits)
rollUpDataArg(lit, atoms);
}
private static void rollUpIndsAndVars(Set<SWRLArgument> roots, Set<SWRLAtom> atoms) {
SWRLArgument rollUpArg = selectArgToRollUp(roots, atoms);
while (rollUpArg != null) {
rollUpArg(rollUpArg, atoms);
rollUpArg = selectArgToRollUp(roots, atoms);
}
}
private static SWRLArgument selectArgToRollUp(Set<SWRLArgument> roots, Set<SWRLAtom> atoms) {
for (SWRLVariable var : Srd.getVarsToSet(atoms))
if (!roots.contains(var)) {
int counter = 0;
Set<SWRLDataPropertyAtom> dataPropAtoms = Srd.getDataPropAtomsWithArg(atoms, var);
for (SWRLDataPropertyAtom dataPropAtom : dataPropAtoms)
if (dataPropAtom.getFirstArgument().equals(var))
counter = 2;
else
counter++;
Set<SWRLObjectPropertyAtom> objPropAtoms = Srd.getObjPropAtomsWithArg(atoms, var);
for (SWRLObjectPropertyAtom objPropAtom : objPropAtoms)
if (Srd.isObjPropAtomWith2DiffVars(objPropAtom))
counter++;
if (counter == 1)
return var;
}
Set<SWRLIndividualArgument> inds = Srd.getIndsToSet(atoms);
for (SWRLIndividualArgument ind : inds)
if (Srd.getDataPropAtomsWithArg(atoms, ind).isEmpty())
if (Connector.isConnected(Srd.getAtomsWithoutArg(atoms, ind)))
return ind;
if (!inds.isEmpty())
return inds.iterator().next();
return null;
}
private static void rollUpArg(SWRLArgument rollUpArg, Set<SWRLAtom> atoms) {
if (rollUpArg instanceof SWRLVariable) {
if (Srd.isObjVar((SWRLVariable) rollUpArg, atoms))
rollUpObjVar((SWRLVariable) rollUpArg, atoms);
else
rollUpDataArg(rollUpArg, atoms);
} else if (rollUpArg instanceof SWRLLiteralArgument)
rollUpDataArg(rollUpArg, atoms);
else if (rollUpArg instanceof SWRLIndividualArgument)
rollUpInd((SWRLIndividualArgument) rollUpArg, atoms);
}
private static void rollUpObjVar(SWRLVariable rollUpObjVar, Set<SWRLAtom> atoms) {
Set<SWRLClassAtom> classAtomsWithRollUpObjVar = Srd.getClassAtomsWithArg(atoms, rollUpObjVar);
atoms.removeAll(classAtomsWithRollUpObjVar);
Set<SWRLObjectPropertyAtom> objPropAtomsWithRollUpObjVar = Srd.getObjPropAtomsWithArg(atoms, rollUpObjVar);
atoms.removeAll(objPropAtomsWithRollUpObjVar);
Set<OWLClassExpression> fillerConjuncts = new HashSet<OWLClassExpression>();
for (SWRLClassAtom classAtomWithRollUpObjVar : classAtomsWithRollUpObjVar)
fillerConjuncts.add(classAtomWithRollUpObjVar.getPredicate());
for (SWRLObjectPropertyAtom objPropAtomWithRollUpObjVar : objPropAtomsWithRollUpObjVar)
if (objPropAtomWithRollUpObjVar.getFirstArgument().equals(objPropAtomWithRollUpObjVar.getSecondArgument()))
fillerConjuncts.add(Srd.factory.getOWLObjectHasSelf(objPropAtomWithRollUpObjVar.getPredicate()));
OWLObjectPropertyExpression objProp = null;
SWRLArgument hookArg = null;
for (SWRLObjectPropertyAtom objPropAtomWithRollUpObjVar : objPropAtomsWithRollUpObjVar)
if (!objPropAtomWithRollUpObjVar.getFirstArgument().equals(objPropAtomWithRollUpObjVar.getSecondArgument()))
if (objPropAtomWithRollUpObjVar.getSecondArgument().equals(rollUpObjVar)) {
objProp = objPropAtomWithRollUpObjVar.getPredicate();
hookArg = objPropAtomWithRollUpObjVar.getFirstArgument();
} else {
objProp = Srd.invert(objPropAtomWithRollUpObjVar.getPredicate());
hookArg = objPropAtomWithRollUpObjVar.getSecondArgument();
}
atoms.add(new SWRLClassAtomImpl(Srd.factory.getOWLObjectSomeValuesFrom(objProp, Srd.buildClassExpressionIntersection(fillerConjuncts)), (SWRLIArgument) hookArg));
}
private static void rollUpInd(SWRLIndividualArgument rollUpInd, Set<SWRLAtom> atoms) {
Set<SWRLClassAtom> classAtomsWithRollUpInd = Srd.getClassAtomsWithArg(atoms, rollUpInd);
atoms.removeAll(classAtomsWithRollUpInd);
Set<SWRLObjectPropertyAtom> objPropAtomsWithRollUpInd = Srd.getObjPropAtomsWithArg(atoms, rollUpInd);
atoms.removeAll(objPropAtomsWithRollUpInd);
Set<OWLClassExpression> fillerConjuncts = new HashSet<OWLClassExpression>();
Set<OWLIndividual> individualSet = new HashSet<OWLIndividual>();
individualSet.add(rollUpInd.getIndividual());
OWLClassExpression nominal = Srd.factory.getOWLObjectOneOf(individualSet);
fillerConjuncts.add(nominal);
for (SWRLClassAtom classAtomWithRollUpInd : classAtomsWithRollUpInd)
fillerConjuncts.add(classAtomWithRollUpInd.getPredicate());
for (SWRLObjectPropertyAtom objPropAtom : objPropAtomsWithRollUpInd)
if (objPropAtom.getFirstArgument().equals(objPropAtom.getSecondArgument()))
fillerConjuncts.add(Srd.factory.getOWLObjectHasSelf(objPropAtom.getPredicate()));
OWLClassExpression fillerWithConjuncts = Srd.buildClassExpressionIntersection(fillerConjuncts);
boolean addedFillerWithConjuncts = false;
for (SWRLObjectPropertyAtom objPropAtomWithRollUpInd : objPropAtomsWithRollUpInd)
if (!objPropAtomWithRollUpInd.getFirstArgument().equals(objPropAtomWithRollUpInd.getSecondArgument())) {
OWLObjectPropertyExpression objProp = null;
SWRLIArgument hookArg = null;
if (objPropAtomWithRollUpInd.getSecondArgument().equals(rollUpInd)) {
objProp = objPropAtomWithRollUpInd.getPredicate();
hookArg = (SWRLIArgument) objPropAtomWithRollUpInd.getFirstArgument();
} else {
objProp = Srd.invert(objPropAtomWithRollUpInd.getPredicate());
hookArg = (SWRLIArgument) objPropAtomWithRollUpInd.getSecondArgument();
}
if (!addedFillerWithConjuncts) {
atoms.add(new SWRLClassAtomImpl(Srd.factory.getOWLObjectSomeValuesFrom(objProp, fillerWithConjuncts), hookArg));
addedFillerWithConjuncts = true;
} else
atoms.add(new SWRLClassAtomImpl(Srd.factory.getOWLObjectSomeValuesFrom(objProp, nominal), hookArg));
}
}
private static void rollUpDataArg(SWRLArgument rollUpDataArg, Set<SWRLAtom> atoms) {
Set<SWRLDataPropertyAtom> dataPropAtomsWithRollUpDataVar = Srd.getDataPropAtomsWithArg(atoms, rollUpDataArg);
atoms.removeAll(dataPropAtomsWithRollUpDataVar);
Set<SWRLDataRangeAtom> dataRangeAtomsWithRollUpDataVar = Srd.getDataRangeAtomsWithArg(atoms, rollUpDataArg);
atoms.removeAll(dataRangeAtomsWithRollUpDataVar);
Set<OWLDataRange> dataRangeConjuncts = new HashSet<OWLDataRange>();
for (SWRLDataRangeAtom dataRangeAtomWithRollUpDataVar : dataRangeAtomsWithRollUpDataVar)
dataRangeConjuncts.add(dataRangeAtomWithRollUpDataVar.getPredicate());
if (rollUpDataArg instanceof SWRLLiteralArgument) {
SWRLLiteralArgument literalDataArg = (SWRLLiteralArgument) rollUpDataArg;
Set<OWLLiteral> nomLiteral = new HashSet<OWLLiteral>();
nomLiteral.add(literalDataArg.getLiteral());
dataRangeConjuncts.add(Srd.factory.getOWLDataOneOf(nomLiteral));
}
for (SWRLDataPropertyAtom dataPropAtom : dataPropAtomsWithRollUpDataVar)
atoms.add(new SWRLClassAtomImpl(Srd.factory.getOWLDataSomeValuesFrom(dataPropAtom.getPredicate(), Srd.buildDataRangeIntersection(dataRangeConjuncts)),
dataPropAtom.getFirstArgument()));
}
}
| bsd-2-clause |
deepinniagafalls/part2 | part2/src/code/Game_047.java | 11436 | package code;
import java.io.Console;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import code.base.Board_024;
import code.base.Inventory_024;
import code.base.Player_024_047;
import code.base.Scrabble_024_047;
import code.base.Tile_024;
import code.util.ReaderTool_047;
import java.util.Scanner.*;
/**
* @author tylerdie (Tyler Dietrich)
* @author ceelman (Chris Elman)
* @author jaeheunk (Jason(Jaeheun) Kim)
* @author mjszymko (Michael Szymkowski)
* @date 2015-APRIL-10
* Game class is responsible for instantiating all of the elements for the graphic user interface (GUI).
*/
public class Game_047 {
/**
* @author tylerdie (Tyler Dietrich)
* @author ceelman (Chris Elman)
* @author jaeheunk (Jason(Jaeheun) Kim)
* @author mjszymko (Michael Szymkowski)
* @date 2015-APRIL-10
* Instance variable that holds reference to the Tile class
*/
Tile_024 _t;
/**
* @author tylerdie (Tyler Dietrich)
* @author ceelman (Chris Elman)
* @author jaeheunk (Jason(Jaeheun) Kim)
* @author mjszymko (Michael Szymkowski)
* @date 2015-APRIL-10
* Instance variable that holds reference to the number of players
*/
private static int _numberOfPlayers;
/**
* @author tylerdie (Tyler Dietrich)
* @author ceelman (Chris Elman)
* @author jaeheunk (Jason(Jaeheun) Kim)
* @author mjszymko (Michael Szymkowski)
* @date 2015-APRIL-10
* Instance variable that holds reference to the Scrabble class
*/
private static ArrayList<Player_024_047> _playerList;
/**
* @author tylerdie (Tyler Dietrich)
* @author ceelman (Chris Elman)
* @author jaeheunk (Jason(Jaeheun) Kim)
* @author mjszymko (Michael Szymkowski)
* @date 2015-APRIL-10
* Instance variable that holds reference to the players in the game
*/
private static ArrayList<PlayerFrame_047> _playerFrameList;
/**
* @author tylerdie (Tyler Dietrich)
* @author ceelman (Chris Elman)
* @author jaeheunk (Jason(Jaeheun) Kim)
* @author mjszymko (Michael Szymkowski)
* @date 2015-APRIL-10
* Instance variable that holds reference to the PlayerFrame class
*/
private static int _currentTurn = 0;
/**
* @author tylerdie (Tyler Dietrich)
* @author ceelman (Chris Elman)
* @author jaeheunk (Jason(Jaeheun) Kim)
* @author mjszymko (Michael Szymkowski)
* @date 2015-APRIL-10
* Instance variable that holds reference to the current turn
*/
private static Game_047 _currentGame;
/**
* @author tylerdie (Tyler Dietrich)
* @author ceelman (Chris Elman)
* @author jaeheunk (Jason(Jaeheun) Kim)
* @author mjszymko (Michael Szymkowski)
* @date 2015-APRIL-10
* Constructor for the Game class
* @param String for the player names
* @throws IOEception
*/
private ArrayList<String> _names = new ArrayList<>();
public Game_047(String s, boolean mode) throws IOException{
try {
UIManager.setLookAndFeel(new javax.swing.plaf.metal.MetalLookAndFeel());
} catch(Exception e) {
e.printStackTrace();
}
String e1 = "";
String e2 = "";
String e3 = "";
String e4 = "";
String p = "";
String path = "";
// ArrayList<String> names = new ArrayList<>();
_currentGame = this;
if(mode){
if(s == "CUI"){
System.out.print("Please type in the path of the dictionary file. Press Enter instead to use the dictionary that is already provided with the code: ");
Scanner ps = new Scanner(System.in);
path = ps.nextLine();
Integer pl = path.length();
if(pl == 0){
path = "Documents/words.txt";
}
System.out.print("How many players do you want? ");
Scanner scanIn = new Scanner(System.in);
p = scanIn.nextLine();
if(p != null){_numberOfPlayers = Integer.parseInt(p);}
else{JOptionPane.showMessageDialog(null, "Error! you choose to cancel","ERROR",JOptionPane.ERROR_MESSAGE);System.exit(0);}
if(_numberOfPlayers > 4){
JOptionPane.showMessageDialog(null, "Error! The maximum number of players is 4","ERROR",JOptionPane.ERROR_MESSAGE);System.exit(0);}
if(_numberOfPlayers < 2){
JOptionPane.showMessageDialog(null, "Error! The minimum number of players is 2","ERROR",JOptionPane.ERROR_MESSAGE);
System.exit(0);}
if(_numberOfPlayers == 2){
System.out.print("Please enter player 1's name in: ");
Scanner scanIn2 = new Scanner(System.in);
e1 = scanIn2.nextLine();
System.out.print("Please enter player 2's name in: ");
Scanner scanIn3 = new Scanner(System.in);
e2 = scanIn3.nextLine();
_names.add(e1);
_names.add(e2);
}
else if(_numberOfPlayers == 3){
//String e1 = JOptionPane.showInputDialog(null, "Please enter player 1's name in","Number",JOptionPane.QUESTION_MESSAGE);;
//String e2 = JOptionPane.showInputDialog(null, "Please enter player 2's name in","Number",JOptionPane.QUESTION_MESSAGE);;
//String e3 = JOptionPane.showInputDialog(null, "Please enter player 3's name in","Number",JOptionPane.QUESTION_MESSAGE);;
System.out.print("Please enter player 1's name in: ");
Scanner scanIn2 = new Scanner(System.in);
e1 = scanIn2.nextLine();
System.out.print("Please enter player 2's name in: ");
Scanner scanIn3 = new Scanner(System.in);
e2 = scanIn3.nextLine();
System.out.print("Please enter player 3's name in: ");
Scanner scanIn4 = new Scanner(System.in);
e3 = scanIn4.nextLine();
_names.add(e1);
_names.add(e2);
_names.add(e3);
}
else if(_numberOfPlayers == 4){
System.out.print("Please enter player 1's name in: ");
Scanner scanIn2 = new Scanner(System.in);
e1 = scanIn2.nextLine();
System.out.print("Please enter player 2's name in: ");
Scanner scanIn3 = new Scanner(System.in);
e2 = scanIn3.nextLine();
System.out.print("Please enter player 3's name in: ");
Scanner scanIn4 = new Scanner(System.in);
e3 = scanIn4.nextLine();
System.out.print("Please enter player 4's name in: ");
Scanner scanIn5 = new Scanner(System.in);
e4 = scanIn5.nextLine();
_names.add(e1);
_names.add(e2);
_names.add(e3);
_names.add(e4);
}
}
else if(s != "CUI"){
path = JOptionPane.showInputDialog(null, "Please type in the path of the dictionary file. Type default instead to use the dictionary that is already provided with the code","PATH",JOptionPane.QUESTION_MESSAGE);
Integer pl = path.length();
if(pl == 0){
path = "Documents/words.txt";
}
p = JOptionPane.showInputDialog(null, "How many players do you want?","Number of Players",JOptionPane.QUESTION_MESSAGE);
if(p != null){_numberOfPlayers = Integer.parseInt(p);}
else{JOptionPane.showMessageDialog(null, "Error! you choose to cancel","ERROR",JOptionPane.ERROR_MESSAGE);System.exit(0);}
if(_numberOfPlayers > 4){
JOptionPane.showMessageDialog(null, "Error! The maximum number of players is 4","ERROR",JOptionPane.ERROR_MESSAGE);System.exit(0);}
if(_numberOfPlayers < 2){
JOptionPane.showMessageDialog(null, "Error! The minimum number of players is 2","ERROR",JOptionPane.ERROR_MESSAGE);
System.exit(0);}
if(_numberOfPlayers == 2){
e1 = JOptionPane.showInputDialog(null, "Please enter player 1's name in","Number",JOptionPane.QUESTION_MESSAGE);;
e2 = JOptionPane.showInputDialog(null, "Please enter player 2's name in","Number",JOptionPane.QUESTION_MESSAGE);;
_names.add(e1);
_names.add(e2);
}
else if(_numberOfPlayers == 3){
e1 = JOptionPane.showInputDialog(null, "Please enter player 1's name in","Number",JOptionPane.QUESTION_MESSAGE);;
e2 = JOptionPane.showInputDialog(null, "Please enter player 2's name in","Number",JOptionPane.QUESTION_MESSAGE);;
e3 = JOptionPane.showInputDialog(null, "Please enter player 3's name in","Number",JOptionPane.QUESTION_MESSAGE);;
_names.add(e1);
_names.add(e2);
_names.add(e3);
}
else if(_numberOfPlayers == 4){
e1 = JOptionPane.showInputDialog(null, "Please enter player 1's name in","Number",JOptionPane.QUESTION_MESSAGE);;
e2 = JOptionPane.showInputDialog(null, "Please enter player 2's name in","Number",JOptionPane.QUESTION_MESSAGE);;
e3 = JOptionPane.showInputDialog(null, "Please enter player 3's name in","Number",JOptionPane.QUESTION_MESSAGE);;
e4 = JOptionPane.showInputDialog(null, "Please enter player 4's name in","Number",JOptionPane.QUESTION_MESSAGE);;
_names.add(e1);
_names.add(e2);
_names.add(e3);
_names.add(e4);
}
}
}
else{
_numberOfPlayers = 2;
_names.add("Frigg");
_names.add("Freya");
}
Scrabble_024_047 scrabble = new Scrabble_024_047(_numberOfPlayers, this);
Inventory_024 invent = scrabble.getInv();
Board_024 board = scrabble.getBoard();
_playerList = scrabble.getPlayers();
_playerFrameList = new ArrayList<PlayerFrame_047>();
for(int i = 0; i < _numberOfPlayers; i++){
_playerFrameList.add(new PlayerFrame_047(scrabble, scrabble.returnPlayer(i).getTileRack(), i, _currentGame, _names));
}
BoardFrame_047 boardframe = new BoardFrame_047(scrabble, board , invent,_playerFrameList, _currentGame, scrabble, path);
Extravaganza_047 fc = new Extravaganza_047(scrabble, boardframe, this, _names, _playerFrameList, path);
}
/**
* @author tylerdie (Tyler Dietrich)
* @author ceelman (Chris Elman)
* @author jaeheunk (Jason(Jaeheun) Kim)
* @author mjszymko (Michael Szymkowski)
* @date 2015-APRIL-10
* Method that controls the turns for the game
* @return returns the current turn in the game
*/
public int incrementTurn(){
if(_currentTurn == _numberOfPlayers-1){
_currentTurn = 0;
return _currentTurn;
}
else{
_currentTurn = _currentTurn + 1;
return _currentTurn;
}
}
/**
* @author tylerdie (Tyler Dietrich)
* @author ceelman (Chris Elman)
* @author jaeheunk (Jason(Jaeheun) Kim)
* @author mjszymko (Michael Szymkowski)
* @date 2015-APRIL-10
* Method that obtains the contents of the Game class
* @return Returns the current game
*/
public Game_047 getGame(){
return _currentGame;
}
/**
* @author tylerdie (Tyler Dietrich)
* @author ceelman (Chris Elman)
* @author jaeheunk (Jason(Jaeheun) Kim)
* @author mjszymko (Michael Szymkowski)
* @date 2015-APRIL-10
* Method that obtains the current turn
* @return Returns the current turn
*/
public int getCurrentTurn(){
return _currentTurn;
}
public int getNumOfPlayers(){
return _numberOfPlayers;
}
public String getName(int index){
return _names.get(index);
}
public Player_024_047 getPlayer(int index){
return _playerList.get(index);
}
public ArrayList<Player_024_047> getPlayerList(){
return _playerList;
}
public void printOutWinner(){
String winner = _playerList.get(0).getName();
int highest = _playerList.get(0).getScore();
for(int i=0; i<_numberOfPlayers; i++){
if(_playerList.get(i).getScore()<highest){
winner = _playerList.get(i).getName();
highest = _playerList.get(i).getScore();
}
}
System.out.println("The game is over, " + winner + " is the winner!");
}
}
| bsd-2-clause |
RBMHTechnology/ttt | ttt-ttpe/src/main/java/com/skynav/ttpe/render/xml/XMLRenderProcessor.java | 14782 | /*
* Copyright 2014-15 Skynav, Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 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 SKYNAV, INC. AND ITS 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 SKYNAV, INC. OR ITS CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.skynav.ttpe.render.xml;
import java.text.MessageFormat;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import com.skynav.ttpe.area.AnnotationArea;
import com.skynav.ttpe.area.Area;
import com.skynav.ttpe.area.AreaNode;
import com.skynav.ttpe.area.BlockArea;
import com.skynav.ttpe.area.BlockFillerArea;
import com.skynav.ttpe.area.CanvasArea;
import com.skynav.ttpe.area.GlyphArea;
import com.skynav.ttpe.area.InlineFillerArea;
import com.skynav.ttpe.area.LineArea;
import com.skynav.ttpe.area.ReferenceArea;
import com.skynav.ttpe.area.SpaceArea;
import com.skynav.ttpe.area.ViewportArea;
import com.skynav.ttpe.geometry.Extent;
import com.skynav.ttpe.geometry.Point;
import com.skynav.ttpe.geometry.Rectangle;
import com.skynav.ttpe.geometry.TransformMatrix;
import com.skynav.ttpe.geometry.WritingMode;
import com.skynav.ttpe.render.Frame;
import com.skynav.ttpe.render.RenderProcessor;
import com.skynav.ttpe.style.InlineAlignment;
import com.skynav.ttpe.util.Characters;
import com.skynav.ttv.app.MissingOptionArgumentException;
import com.skynav.ttv.app.OptionSpecification;
import com.skynav.ttv.util.Namespaces;
import com.skynav.ttv.util.Reporter;
import com.skynav.ttx.transformer.TransformerContext;
import com.skynav.xml.helpers.Documents;
public class XMLRenderProcessor extends RenderProcessor {
public static final String NAME = "xml";
// static defaults
private static final String defaultOutputFileNamePattern = "ttpx{0,number,000000}.xml";
// option and usage info
private static final String[][] longOptionSpecifications = new String[][] {
{ "xml-include-generator", "", "include ISD generator information in output, i.e., information about source ISD instance" },
};
private static final Map<String,OptionSpecification> longOptions;
static {
longOptions = new java.util.TreeMap<String,OptionSpecification>();
for (String[] spec : longOptionSpecifications) {
longOptions.put(spec[0], new OptionSpecification(spec[0], spec[1], spec[2]));
}
}
// miscellaneous statics
public static final MessageFormat doubleFormatter = new MessageFormat("{0,number,#.####}");
// options state
private boolean includeGenerator;
private String outputPattern;
// render state
private List<Rectangle> regions;
public XMLRenderProcessor(TransformerContext context) {
super(context);
}
@Override
public String getName() {
return NAME;
}
@Override
public String getOutputPattern() {
return outputPattern;
}
@Override
public Collection<OptionSpecification> getLongOptionSpecs() {
return longOptions.values();
}
@Override
public int parseLongOption(List<String> args, int index) {
String arg = args.get(index);
int numArgs = args.size();
String option = arg;
assert option.length() > 2;
option = option.substring(2);
if (option.equals("output-pattern")) {
if (index + 1 > numArgs)
throw new MissingOptionArgumentException("--" + option);
outputPattern = args.get(++index);
} else if (option.equals("xml-include-generator")) {
includeGenerator = true;
} else {
return super.parseLongOption(args, index);
}
return index + 1;
}
@Override
public void processDerivedOptions() {
super.processDerivedOptions();
// output pattern
String outputPattern = this.outputPattern;
if (outputPattern == null)
outputPattern = defaultOutputFileNamePattern;
this.outputPattern = outputPattern;
}
@Override
public List<Frame> render(List<Area> areas) {
List<Frame> frames = new java.util.ArrayList<Frame>();
for (Area a : areas) {
if (a instanceof CanvasArea) {
Frame f = renderCanvas((CanvasArea) a);
if (f != null)
frames.add(f);
}
}
return frames;
}
@Override
public void clear(boolean all) {
regions = null;
}
private Frame renderCanvas(CanvasArea a) {
Reporter reporter = context.getReporter();
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();
Document d = db.newDocument();
d.appendChild(renderCanvas(a, d));
Namespaces.normalize(d, XMLDocumentFrame.prefixes);
return new XMLDocumentFrame(a.getBegin(), a.getEnd(), a.getExtent(), d, regions);
} catch (ParserConfigurationException e) {
reporter.logError(e);
}
return null;
}
private Element renderCanvas(CanvasArea a, Document d) {
Element e = Documents.createElement(d, XMLDocumentFrame.ttpeCanvasEltName);
for (Area c : a.getChildren()) {
e.appendChild(renderArea(c, d));
}
return e;
}
private Element renderViewport(ViewportArea a, Document d) {
Element e = Documents.createElement(d, XMLDocumentFrame.ttpeViewportEltName);
renderCommonAreaAttributes(a, e, false, false);
Extent extent = a.getExtent();
if (extent != null)
Documents.setAttribute(e, XMLDocumentFrame.extentAttrName, extent.toString());
if (a.getClip())
Documents.setAttribute(e, XMLDocumentFrame.clipAttrName, Boolean.valueOf(a.getClip()).toString().toLowerCase());
for (Area c : a.getChildren()) {
e.appendChild(renderArea(c, d));
}
return e;
}
private Element renderReference(ReferenceArea a, Document d) {
Element e = Documents.createElement(d, XMLDocumentFrame.ttpeReferenceEltName);
renderCommonAreaAttributes(a, e, false, false);
Extent extent = a.getExtent();
if (extent != null)
Documents.setAttribute(e, XMLDocumentFrame.extentAttrName, extent.toString());
TransformMatrix ctm = a.getCTM();
if (ctm != null)
Documents.setAttribute(e, XMLDocumentFrame.ctmAttrName, ctm.toString());
if (!isRootReference(a)) {
Point origin = a.getOrigin();
if (origin != null) {
Documents.setAttribute(e, XMLDocumentFrame.originAttrName, origin.toString());
if (extent != null)
addRegion(origin, extent);
}
WritingMode wm = a.getWritingMode();
if (wm != null)
Documents.setAttribute(e, XMLDocumentFrame.wmAttrName, wm.toString().toLowerCase());
}
for (Area c : a.getChildren()) {
e.appendChild(renderArea(c, d));
}
return e;
}
private boolean isRootReference(AreaNode a) {
for (AreaNode p = a.getParent(); p != null; p = p.getParent()) {
if (p instanceof ReferenceArea)
return false;
}
return true;
}
private void addRegion(Point origin, Extent extent) {
if (regions == null)
regions = new java.util.ArrayList<Rectangle>();
regions.add(new Rectangle(origin, extent));
}
private Element renderBlock(BlockArea a, Document d) {
Element e = Documents.createElement(d, XMLDocumentFrame.ttpeBlockEltName);
renderCommonBlockAreaAttributes(a, e);
for (Area c : a.getChildren()) {
e.appendChild(renderArea(c, d));
}
return e;
}
private Element renderFiller(BlockFillerArea a, Document d) {
Element e = Documents.createElement(d, XMLDocumentFrame.ttpeFillEltName);
renderCommonBlockAreaAttributes(a, e);
return e;
}
private Element renderLine(LineArea a, Document d) {
Element e = Documents.createElement(d, XMLDocumentFrame.ttpeLineEltName);
renderCommonBlockAreaAttributes(a, e);
if (isOverflowed(a)) {
InlineAlignment alignment = a.getAlignment();
String align;
if (alignment == InlineAlignment.START)
align = null;
else if (alignment == InlineAlignment.END)
align = "end";
else
align = "center";
if (align != null)
Documents.setAttribute(e, XMLDocumentFrame.inlineAlignAttrName, align);
Documents.setAttribute(e, XMLDocumentFrame.overflowAttrName, doubleFormatter.format(new Object[] {a.getOverflow()}));
}
for (Area c : a.getChildren()) {
e.appendChild(renderArea(c, d));
}
return e;
}
private boolean isOverflowed(LineArea a) {
return a.getOverflow() > 0;
}
private Element renderAnnotation(AnnotationArea a, Document d) {
Element e = Documents.createElement(d, XMLDocumentFrame.ttpeAnnotationEltName);
renderCommonInlineAreaAttributes(a, e, true);
for (Area c : a.getChildren()) {
e.appendChild(renderArea(c, d));
}
return e;
}
private Element renderGlyph(GlyphArea a, Document d) {
Element e = Documents.createElement(d, XMLDocumentFrame.ttpeGlyphsEltName);
renderCommonInlineAreaAttributes(a, e, false);
Documents.setAttribute(e, XMLDocumentFrame.textAttrName, a.getText());
return e;
}
private Element renderSpace(SpaceArea a, Document d) {
Element e = Documents.createElement(d, XMLDocumentFrame.ttpeSpaceEltName);
renderCommonInlineAreaAttributes(a, e, false);
Documents.setAttribute(e, XMLDocumentFrame.textAttrName, escapeWhitespace(a.getText()));
return e;
}
private Element renderFiller(InlineFillerArea a, Document d) {
Element e = Documents.createElement(d, XMLDocumentFrame.ttpeFillEltName);
renderCommonInlineAreaAttributes(a, e, false);
return e;
}
private Element renderArea(Area a, Document d) {
if (a instanceof GlyphArea)
return renderGlyph((GlyphArea) a, d);
else if (a instanceof SpaceArea)
return renderSpace((SpaceArea) a, d);
else if (a instanceof InlineFillerArea)
return renderFiller((InlineFillerArea) a, d);
else if (a instanceof AnnotationArea)
return renderAnnotation((AnnotationArea) a, d);
else if (a instanceof LineArea)
return renderLine((LineArea) a, d);
else if (a instanceof ReferenceArea)
return renderReference((ReferenceArea) a, d);
else if (a instanceof ViewportArea)
return renderViewport((ViewportArea) a, d);
else if (a instanceof BlockFillerArea)
return renderFiller((BlockFillerArea) a, d);
else if (a instanceof BlockArea)
return renderBlock((BlockArea) a, d);
else
throw new IllegalArgumentException();
}
private Element renderCommonInlineAreaAttributes(Area a, Element e, boolean bpdInclude) {
renderCommonAreaAttributes(a, e, bpdInclude, true);
return e;
}
private Element renderCommonBlockAreaAttributes(Area a, Element e) {
renderCommonAreaAttributes(a, e, true, true);
return e;
}
private Element renderCommonAreaAttributes(Area a, Element e, boolean bpdInclude, boolean ipdInclude) {
if (bpdInclude)
Documents.setAttribute(e, XMLDocumentFrame.bpdAttrName, doubleFormatter.format(new Object[] {a.getBPD()}));
if (ipdInclude)
Documents.setAttribute(e, XMLDocumentFrame.ipdAttrName, doubleFormatter.format(new Object[] {a.getIPD()}));
if (includeGenerator) {
String ln = (a.getElement() != null) ? a.getElement().getLocalName() : null;
if (ln != null)
Documents.setAttribute(e, XMLDocumentFrame.fromAttrName, ln);
}
return e;
}
public static String escapeWhitespace(String s) {
if (s == null)
return null;
else {
StringBuffer sb = new StringBuffer(s.length());
for (int i = 0, n = s.length(); i < n; ++i) {
int c = s.codePointAt(i);
if (Characters.isWhitespace(c))
appendNumericCharReference(sb, c);
else
sb.append((char) c);
}
return sb.toString();
}
}
private static void appendNumericCharReference(StringBuffer sb, int codepoint) {
sb.append("\\u");
sb.append(pad(codepoint, 16, (codepoint > 65535) ? 6 : 4, '0'));
}
private static String digits = "0123456789ABCDEF";
private static String pad(int value, int radix, int width, char padding) {
assert value >= 0;
StringBuffer sb = new StringBuffer(width);
while (value > 0) {
sb.append(digits.charAt(value % radix));
value /= radix;
}
while (sb.length() < width) {
sb.append(padding);
}
return sb.reverse().toString();
}
}
| bsd-2-clause |
decarbonization/android-fonz | app/src/main/java/com/kevinmacwhinnie/fonz/state/Board.java | 5185 | /*
* Copyright (c) 2015, Peter 'Kevin' MacWhinnie
* 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 may not be sold, nor may they be used in a commercial
* product or activity.
* 2. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 3. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.kevinmacwhinnie.fonz.state;
import android.os.Bundle;
import android.support.annotation.NonNull;
import com.kevinmacwhinnie.fonz.data.GamePersistence;
import com.kevinmacwhinnie.fonz.data.PowerUp;
import com.kevinmacwhinnie.fonz.events.BaseValueEvent;
import com.squareup.otto.Bus;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.Iterator;
public class Board implements GamePersistence {
static final String SAVED_PIES = Board.class.getName() + ".SAVED_PIES";
static final String SAVED_POWER_UPS = Board.class.getName() + ".SAVED_POWER_UPS";
public static final int NUMBER_PIES = 6;
public final Bus bus;
private final Pie[] pies;
private final EnumSet<PowerUp> powerUps = EnumSet.noneOf(PowerUp.class);
public Board(@NonNull Bus bus) {
this.bus = bus;
this.pies = new Pie[NUMBER_PIES];
for (int slot = 0; slot < NUMBER_PIES; slot++) {
this.pies[slot] = new Pie(bus);
}
}
@Override
public void restoreState(@NonNull Bundle inState) {
final ArrayList<Bundle> savedPieStates = inState.getParcelableArrayList(SAVED_PIES);
assert savedPieStates != null;
for (int i = 0, length = savedPieStates.size(); i < length; i++) {
final Bundle savedPieState = savedPieStates.get(i);
pies[i].restoreState(savedPieState);
}
@SuppressWarnings("unchecked")
final EnumSet<PowerUp> savedPowerUps =
(EnumSet<PowerUp>) inState.getSerializable(SAVED_POWER_UPS);
assert savedPowerUps != null;
powerUps.clear();
powerUps.addAll(savedPowerUps);
}
@Override
public void saveState(@NonNull Bundle outState) {
final ArrayList<Bundle> savedPies = new ArrayList<>(pies.length);
for (final Pie pie : pies) {
final Bundle outPieState = new Bundle();
pie.saveState(outPieState);
savedPies.add(outPieState);
}
outState.putParcelableArrayList(SAVED_PIES, savedPies);
outState.putSerializable(SAVED_POWER_UPS, powerUps);
}
public int getSlot(@NonNull Pie pie) {
for (int i = 0, length = pies.length; i < length; i++) {
if (pies[i].equals(pie)) {
return i;
}
}
return -1;
}
public Pie getPie(int slot) {
return pies[slot];
}
public boolean pieHasPowerUp(int slot) {
return (slot < PowerUp.values().length);
}
public boolean addPowerUp(@NonNull PowerUp powerUp) {
if (powerUps.add(powerUp)) {
bus.post(new PowerUpChanged(powerUp));
return true;
} else {
return false;
}
}
public boolean usePowerUp(@NonNull PowerUp powerUp) {
if (powerUps.remove(powerUp)) {
bus.post(new PowerUpChanged(powerUp));
return true;
} else {
return false;
}
}
public boolean hasPowerUp(@NonNull PowerUp powerUp) {
return powerUps.contains(powerUp);
}
public int getPowerUpCount() {
return powerUps.size();
}
public void reset() {
for (int i = 0; i < NUMBER_PIES; i++) {
pies[i].reset();
}
final Iterator<PowerUp> iterator = powerUps.iterator();
while (iterator.hasNext()) {
final PowerUp powerUp = iterator.next();
iterator.remove();
bus.post(new PowerUpChanged(powerUp));
}
}
public static class PowerUpChanged extends BaseValueEvent<PowerUp> {
public PowerUpChanged(@NonNull PowerUp value) {
super(value);
}
}
}
| bsd-2-clause |
le1nux/DST-Framework | TestingFramework/src/com/lue/client/ScheduleRunnerIF.java | 604 | package com.lue.client;
import java.rmi.RemoteException;
import com.lue.common.Schedule;
import com.lue.common.SupportedTests;
import com.lue.common.UnitTestException;
public interface ScheduleRunnerIF extends NameIF {
public SupportedTests getSupportedTests() throws RemoteException;
public void pushSchedule(Schedule schedule) throws RemoteException, UnitTestException;
public void resetSchedule() throws RemoteException;
public void runSchedule() throws RemoteException;
public boolean isAlive() throws RemoteException;
public int getId() throws RemoteException;
}
| bsd-2-clause |
col726/game-engine-CMZ | AndroidProject/gen/com/drexel/CS680/CMZ/gameEngine/BuildConfig.java | 173 | /** Automatically generated file. DO NOT MODIFY */
package com.drexel.CS680.CMZ.gameEngine;
public final class BuildConfig {
public final static boolean DEBUG = true;
} | bsd-2-clause |
radai-rosenblatt/li-apache-kafka-clients | li-apache-kafka-clients/src/main/java/com/linkedin/kafka/clients/producer/LiKafkaProducer.java | 1107 | /*
* Copyright 2017 LinkedIn Corp. Licensed under the BSD 2-Clause License (the "License").
See License in the project root for license information.
*/
package com.linkedin.kafka.clients.producer;
import com.linkedin.kafka.clients.annotations.InterfaceOrigin;
import java.util.concurrent.TimeUnit;
import org.apache.kafka.clients.producer.Producer;
/**
* The general producer interface that allows allows pluggable serializers and deserializers.
* LiKafkaProducer has the same interface as open source {@link Producer}. We define the interface separately to allow
* future extensions.
* @see LiKafkaProducerImpl
*/
public interface LiKafkaProducer<K, V> extends Producer<K, V> {
/**
* Flush any accumulated records from the producer. If the close does not complete within the timeout, throws exception.
* If the underlying producer does not support bounded flush, this method defaults to {@link #flush()}
* TODO: This API is added as a HOTFIX until the API change is available in apache/kafka
*/
@InterfaceOrigin.LiKafkaClients
void flush(long timeout, TimeUnit timeUnit);
}
| bsd-2-clause |
xranby/nifty-gui | nifty-controls/src/main/java/de/lessvoid/nifty/controls/radiobutton/builder/RadioButtonBuilder.java | 382 | package de.lessvoid.nifty.controls.radiobutton.builder;
import de.lessvoid.nifty.builder.ControlBuilder;
public class RadioButtonBuilder extends ControlBuilder {
public RadioButtonBuilder() {
super("radioButton");
}
public RadioButtonBuilder(final String id) {
super(id, "radioButton");
}
public void group(final String group) {
set("group", group);
}
}
| bsd-2-clause |
fokus-llc/lenzenslijper | src/main/java/us/fok/lenzenslijper/models/jooq/routines/Droprasterconstraints4.java | 10909 | /**
* This class is generated by jOOQ
*/
package us.fok.lenzenslijper.models.jooq.routines;
/**
* This class is generated by jOOQ.
*/
@javax.annotation.Generated(value = { "http://www.jooq.org", "3.3.0" },
comments = "This class is generated by jOOQ")
@java.lang.SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class Droprasterconstraints4 extends org.jooq.impl.AbstractRoutine<java.lang.Boolean> {
private static final long serialVersionUID = 922832356;
/**
* The parameter <code>public.droprasterconstraints.RETURN_VALUE</code>.
*/
public static final org.jooq.Parameter<java.lang.Boolean> RETURN_VALUE = createParameter("RETURN_VALUE", org.jooq.impl.SQLDataType.BOOLEAN);
/**
* The parameter <code>public.droprasterconstraints.rasttable</code>.
*/
public static final org.jooq.Parameter<java.lang.String> RASTTABLE = createParameter("rasttable", org.jooq.impl.SQLDataType.VARCHAR);
/**
* The parameter <code>public.droprasterconstraints.rastcolumn</code>.
*/
public static final org.jooq.Parameter<java.lang.String> RASTCOLUMN = createParameter("rastcolumn", org.jooq.impl.SQLDataType.VARCHAR);
/**
* The parameter <code>public.droprasterconstraints.srid</code>.
*/
public static final org.jooq.Parameter<java.lang.Boolean> SRID = createParameter("srid", org.jooq.impl.SQLDataType.BOOLEAN);
/**
* The parameter <code>public.droprasterconstraints.scale_x</code>.
*/
public static final org.jooq.Parameter<java.lang.Boolean> SCALE_X = createParameter("scale_x", org.jooq.impl.SQLDataType.BOOLEAN);
/**
* The parameter <code>public.droprasterconstraints.scale_y</code>.
*/
public static final org.jooq.Parameter<java.lang.Boolean> SCALE_Y = createParameter("scale_y", org.jooq.impl.SQLDataType.BOOLEAN);
/**
* The parameter <code>public.droprasterconstraints.blocksize_x</code>.
*/
public static final org.jooq.Parameter<java.lang.Boolean> BLOCKSIZE_X = createParameter("blocksize_x", org.jooq.impl.SQLDataType.BOOLEAN);
/**
* The parameter <code>public.droprasterconstraints.blocksize_y</code>.
*/
public static final org.jooq.Parameter<java.lang.Boolean> BLOCKSIZE_Y = createParameter("blocksize_y", org.jooq.impl.SQLDataType.BOOLEAN);
/**
* The parameter <code>public.droprasterconstraints.same_alignment</code>.
*/
public static final org.jooq.Parameter<java.lang.Boolean> SAME_ALIGNMENT = createParameter("same_alignment", org.jooq.impl.SQLDataType.BOOLEAN);
/**
* The parameter <code>public.droprasterconstraints.regular_blocking</code>.
*/
public static final org.jooq.Parameter<java.lang.Boolean> REGULAR_BLOCKING = createParameter("regular_blocking", org.jooq.impl.SQLDataType.BOOLEAN);
/**
* The parameter <code>public.droprasterconstraints.num_bands</code>.
*/
public static final org.jooq.Parameter<java.lang.Boolean> NUM_BANDS = createParameter("num_bands", org.jooq.impl.SQLDataType.BOOLEAN);
/**
* The parameter <code>public.droprasterconstraints.pixel_types</code>.
*/
public static final org.jooq.Parameter<java.lang.Boolean> PIXEL_TYPES = createParameter("pixel_types", org.jooq.impl.SQLDataType.BOOLEAN);
/**
* The parameter <code>public.droprasterconstraints.nodata_values</code>.
*/
public static final org.jooq.Parameter<java.lang.Boolean> NODATA_VALUES = createParameter("nodata_values", org.jooq.impl.SQLDataType.BOOLEAN);
/**
* The parameter <code>public.droprasterconstraints.out_db</code>.
*/
public static final org.jooq.Parameter<java.lang.Boolean> OUT_DB = createParameter("out_db", org.jooq.impl.SQLDataType.BOOLEAN);
/**
* The parameter <code>public.droprasterconstraints.extent</code>.
*/
public static final org.jooq.Parameter<java.lang.Boolean> EXTENT = createParameter("extent", org.jooq.impl.SQLDataType.BOOLEAN);
/**
* Create a new routine call instance
*/
public Droprasterconstraints4() {
super("droprasterconstraints", us.fok.lenzenslijper.models.jooq.Public.PUBLIC, org.jooq.impl.SQLDataType.BOOLEAN);
setReturnParameter(RETURN_VALUE);
addInParameter(RASTTABLE);
addInParameter(RASTCOLUMN);
addInParameter(SRID);
addInParameter(SCALE_X);
addInParameter(SCALE_Y);
addInParameter(BLOCKSIZE_X);
addInParameter(BLOCKSIZE_Y);
addInParameter(SAME_ALIGNMENT);
addInParameter(REGULAR_BLOCKING);
addInParameter(NUM_BANDS);
addInParameter(PIXEL_TYPES);
addInParameter(NODATA_VALUES);
addInParameter(OUT_DB);
addInParameter(EXTENT);
setOverloaded(true);
}
/**
* Set the <code>rasttable</code> parameter IN value to the routine
*/
public void setRasttable(java.lang.String value) {
setValue(us.fok.lenzenslijper.models.jooq.routines.Droprasterconstraints4.RASTTABLE, value);
}
/**
* Set the <code>rasttable</code> parameter to the function to be used with a {@link org.jooq.Select} statement
*/
public void setRasttable(org.jooq.Field<java.lang.String> field) {
setField(RASTTABLE, field);
}
/**
* Set the <code>rastcolumn</code> parameter IN value to the routine
*/
public void setRastcolumn(java.lang.String value) {
setValue(us.fok.lenzenslijper.models.jooq.routines.Droprasterconstraints4.RASTCOLUMN, value);
}
/**
* Set the <code>rastcolumn</code> parameter to the function to be used with a {@link org.jooq.Select} statement
*/
public void setRastcolumn(org.jooq.Field<java.lang.String> field) {
setField(RASTCOLUMN, field);
}
/**
* Set the <code>srid</code> parameter IN value to the routine
*/
public void setSrid(java.lang.Boolean value) {
setValue(us.fok.lenzenslijper.models.jooq.routines.Droprasterconstraints4.SRID, value);
}
/**
* Set the <code>srid</code> parameter to the function to be used with a {@link org.jooq.Select} statement
*/
public void setSrid(org.jooq.Field<java.lang.Boolean> field) {
setField(SRID, field);
}
/**
* Set the <code>scale_x</code> parameter IN value to the routine
*/
public void setScaleX(java.lang.Boolean value) {
setValue(us.fok.lenzenslijper.models.jooq.routines.Droprasterconstraints4.SCALE_X, value);
}
/**
* Set the <code>scale_x</code> parameter to the function to be used with a {@link org.jooq.Select} statement
*/
public void setScaleX(org.jooq.Field<java.lang.Boolean> field) {
setField(SCALE_X, field);
}
/**
* Set the <code>scale_y</code> parameter IN value to the routine
*/
public void setScaleY(java.lang.Boolean value) {
setValue(us.fok.lenzenslijper.models.jooq.routines.Droprasterconstraints4.SCALE_Y, value);
}
/**
* Set the <code>scale_y</code> parameter to the function to be used with a {@link org.jooq.Select} statement
*/
public void setScaleY(org.jooq.Field<java.lang.Boolean> field) {
setField(SCALE_Y, field);
}
/**
* Set the <code>blocksize_x</code> parameter IN value to the routine
*/
public void setBlocksizeX(java.lang.Boolean value) {
setValue(us.fok.lenzenslijper.models.jooq.routines.Droprasterconstraints4.BLOCKSIZE_X, value);
}
/**
* Set the <code>blocksize_x</code> parameter to the function to be used with a {@link org.jooq.Select} statement
*/
public void setBlocksizeX(org.jooq.Field<java.lang.Boolean> field) {
setField(BLOCKSIZE_X, field);
}
/**
* Set the <code>blocksize_y</code> parameter IN value to the routine
*/
public void setBlocksizeY(java.lang.Boolean value) {
setValue(us.fok.lenzenslijper.models.jooq.routines.Droprasterconstraints4.BLOCKSIZE_Y, value);
}
/**
* Set the <code>blocksize_y</code> parameter to the function to be used with a {@link org.jooq.Select} statement
*/
public void setBlocksizeY(org.jooq.Field<java.lang.Boolean> field) {
setField(BLOCKSIZE_Y, field);
}
/**
* Set the <code>same_alignment</code> parameter IN value to the routine
*/
public void setSameAlignment(java.lang.Boolean value) {
setValue(us.fok.lenzenslijper.models.jooq.routines.Droprasterconstraints4.SAME_ALIGNMENT, value);
}
/**
* Set the <code>same_alignment</code> parameter to the function to be used with a {@link org.jooq.Select} statement
*/
public void setSameAlignment(org.jooq.Field<java.lang.Boolean> field) {
setField(SAME_ALIGNMENT, field);
}
/**
* Set the <code>regular_blocking</code> parameter IN value to the routine
*/
public void setRegularBlocking(java.lang.Boolean value) {
setValue(us.fok.lenzenslijper.models.jooq.routines.Droprasterconstraints4.REGULAR_BLOCKING, value);
}
/**
* Set the <code>regular_blocking</code> parameter to the function to be used with a {@link org.jooq.Select} statement
*/
public void setRegularBlocking(org.jooq.Field<java.lang.Boolean> field) {
setField(REGULAR_BLOCKING, field);
}
/**
* Set the <code>num_bands</code> parameter IN value to the routine
*/
public void setNumBands(java.lang.Boolean value) {
setValue(us.fok.lenzenslijper.models.jooq.routines.Droprasterconstraints4.NUM_BANDS, value);
}
/**
* Set the <code>num_bands</code> parameter to the function to be used with a {@link org.jooq.Select} statement
*/
public void setNumBands(org.jooq.Field<java.lang.Boolean> field) {
setField(NUM_BANDS, field);
}
/**
* Set the <code>pixel_types</code> parameter IN value to the routine
*/
public void setPixelTypes(java.lang.Boolean value) {
setValue(us.fok.lenzenslijper.models.jooq.routines.Droprasterconstraints4.PIXEL_TYPES, value);
}
/**
* Set the <code>pixel_types</code> parameter to the function to be used with a {@link org.jooq.Select} statement
*/
public void setPixelTypes(org.jooq.Field<java.lang.Boolean> field) {
setField(PIXEL_TYPES, field);
}
/**
* Set the <code>nodata_values</code> parameter IN value to the routine
*/
public void setNodataValues(java.lang.Boolean value) {
setValue(us.fok.lenzenslijper.models.jooq.routines.Droprasterconstraints4.NODATA_VALUES, value);
}
/**
* Set the <code>nodata_values</code> parameter to the function to be used with a {@link org.jooq.Select} statement
*/
public void setNodataValues(org.jooq.Field<java.lang.Boolean> field) {
setField(NODATA_VALUES, field);
}
/**
* Set the <code>out_db</code> parameter IN value to the routine
*/
public void setOutDb(java.lang.Boolean value) {
setValue(us.fok.lenzenslijper.models.jooq.routines.Droprasterconstraints4.OUT_DB, value);
}
/**
* Set the <code>out_db</code> parameter to the function to be used with a {@link org.jooq.Select} statement
*/
public void setOutDb(org.jooq.Field<java.lang.Boolean> field) {
setField(OUT_DB, field);
}
/**
* Set the <code>extent</code> parameter IN value to the routine
*/
public void setExtent(java.lang.Boolean value) {
setValue(us.fok.lenzenslijper.models.jooq.routines.Droprasterconstraints4.EXTENT, value);
}
/**
* Set the <code>extent</code> parameter to the function to be used with a {@link org.jooq.Select} statement
*/
public void setExtent(org.jooq.Field<java.lang.Boolean> field) {
setField(EXTENT, field);
}
}
| bsd-2-clause |
DragonHawkMedia/KyperJGE | src/dragonhawk/kyperj/core/load/GameResourceLoader.java | 2155 | package dragonhawk.kyperj.core.load;
import java.util.List;
import dragonhawk.kyperj.core.graphics.GameImage;
import dragonhawk.kyperj.core.graphics.GameSheet;
import dragonhawk.kyperj.core.graphics.font.GameFont;
import dragonhawk.kyperj.core.sound.GameSound;
import dragonhawk.kyperj.core.sound.GameSound.SoundType;
import dragonhawk.kyperj.core.state.GameState;
public interface GameResourceLoader {
/**
* load an image into the game with a different method
* depending on the environment chosen
* @param file - the name of the file
* @param inpath - whether or not the file is inside the project
* @return - the GameImage to be used for rendering onto the screen
*/
public GameImage loadGameImage(String file, boolean inproject);
/**
* load a sound into the game with a different method
* depending on the environment chosen
* @param file - the name of the file
* @param inpath - whether or not the file is inside the project
* @return - the GameSound to be used
*/
public GameSound loadGameSound(String file, boolean inproject, SoundType type);
/**
* load a game sheet(tilesheet) with
* @param file
* @param inproject
* @param segment_size
* @return
*/
public GameSheet loadGameSheet(String file, boolean inproject, int segment_size);
public GameFont loadGameFont(String file,boolean inproject, int width,int height);
/**
* reload all assets
*/
public void reload();
/**
* load all assets
*/
public void load();
public void load(String state);
/**
* if assets are done loading
* @return if assets are loading
*/
public boolean isDoneLoading();
/**
* get all the resources to be loaded
* @return an arraylist containing all resources to be loaded
*/
public List<GameResource> getResources();
/**
* set the resources to be loaded via an arraylist
* @param resources
*/
public void setResources(List<GameResource> resources);
/**
* get the loading percentage
* @return files that have been loaded %
*/
public double getPercentageDone(String state);
public void loadBegin(GameState state);
public void loadEnd(GameState state);
}
| bsd-2-clause |
OxBRCInformatics/metadata-catalogue | MetadataCatalogue/src/test/java/ox/softeng/metadatacatalogue/test/restapi/service/PrimitiveTypeServiceIT.java | 806 | package ox.softeng.metadatacatalogue.test.restapi.service;
import ox.softeng.metadatacatalogue.api.DataSetApi;
import ox.softeng.metadatacatalogue.domain.core.DataSet;
import ox.softeng.metadatacatalogue.domain.core.PrimitiveType;
public class PrimitiveTypeServiceIT extends DataTypeServiceIT<PrimitiveType> {
@Override
protected PrimitiveType getInstance() throws Exception
{
DataSet ds = DataSetApi.createDataSet(apiCtx, "My test DataSet", "DataSet description", "Test Author", "Test Organization");
PrimitiveType pt = DataSetApi.newPrimitiveType(apiCtx, ds, "String", "String type", "");
return pt;
}
@Override
protected String getServicePath()
{
return "/primitivetype";
}
@Override
protected Class<? extends PrimitiveType> getClazz()
{
return PrimitiveType.class;
}
}
| bsd-3-clause |
znerd/xins | src/java/org/xins/client/XINSCallResultData.java | 1550 | /*
* $Id: XINSCallResultData.java,v 1.11 2007/02/28 15:47:20 agoubard Exp $
*
* Copyright 2003-2007 Orange Nederland Breedband B.V.
* See the COPYRIGHT file for redistribution and use restrictions.
*/
package org.xins.client;
import org.xins.common.collections.PropertyReader;
import org.xins.common.xml.Element;
/**
* Data part of a XINS call result.
*
* @version $Revision: 1.11 $ $Date: 2007/02/28 15:47:20 $
* @author <a href="mailto:ernst@ernstdehaan.com">Ernst de Haan</a>
*
* @since XINS 1.0.0
*/
public interface XINSCallResultData {
/**
* Returns the error code. If <code>null</code> is returned the call was
* successful and thus no error code was returned. Otherwise the call was
* unsuccessful.
*
* <p>This method will never return an empty string, so if the result is
* not <code>null</code>, then it is safe to assume the length of the
* string is at least 1 character.
*
* @return
* the returned error code, or <code>null</code> if the call was
* successful.
*/
String getErrorCode();
/**
* Retrieves all result parameters.
*
* @return
* a {@link PropertyReader} with all output parameters,
* or <code>null</code> if there are none.
*/
PropertyReader getParameters();
/**
* Returns the optional extra data. The data is an XML {@link Element},
* or <code>null</code>.
*
* @return
* the extra data as an XML {@link Element}, can be
* <code>null</code>;
*/
Element getDataElement();
}
| bsd-3-clause |
FRC1735/Steamworks2017 | src/org/usfirst/frc1735/Steamworks2017/subsystems/GearPresence.java | 2626 | // RobotBuilder Version: 2.0
//
// This file was generated by RobotBuilder. It contains sections of
// code that are automatically generated and assigned by robotbuilder.
// These sections will be updated in the future when you export to
// Java from RobotBuilder. Do not put any code or make any change in
// the blocks indicating autogenerated code or it will be lost on an
// update. Deleting the comments indicating the section will prevent
// it from being updated in the future.
package org.usfirst.frc1735.Steamworks2017.subsystems;
import org.usfirst.frc1735.Steamworks2017.RobotMap;
import org.usfirst.frc1735.Steamworks2017.commands.*;
import edu.wpi.first.wpilibj.DigitalInput;
import edu.wpi.first.wpilibj.Solenoid;
import edu.wpi.first.wpilibj.command.Subsystem;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
/**
*
*/
public class GearPresence extends Subsystem {
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTANTS
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTANTS
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS
private final DigitalInput bannerSensor = RobotMap.gearPresenceBannerSensor;
private final Solenoid gearPresenceRelay = RobotMap.gearPresenceGearPresenceRelay;
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS
// Put methods for controlling this subsystem
// here. Call these from Commands.
public void initDefaultCommand() {
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DEFAULT_COMMAND
setDefaultCommand(new MonitorGearPresence());
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DEFAULT_COMMAND
// Set the default command for a subsystem here.
// setDefaultCommand(new MySpecialCommand());
}
public void gearPresenceLightOn(boolean onState) {
// If onState is true, turn the camera light relay on.
// Otherwise, turn it off.
gearPresenceRelay.set(onState);
// Print the new state of the light to the SmartDashboard
//SmartDashboard.putBoolean("Gear Presence Light On", onState);
}
public boolean isGearPresent() {
// Get the current state of the banner sensor.
// if it is TRUE, then the beam is broken and the gear is present.
// if it is FALSE, then the beam is unbroken (reflected back and received) and the gear is NOT present.
// This implementation is done so that if the banner sensor fails or gets disconnected, the pullup resistor on the RoboRio will make it look like the beam is still there (no gear, no light)
return (bannerSensor.get());
}
}
| bsd-3-clause |
picocontainer/NanoContainer-remoting | remoting/src/java/org/nanocontainer/remoting/jmx/DynamicMBeanComponentProvider.java | 3140 | /*****************************************************************************
* Copyright (C) NanoContainer Organization. All rights reserved. *
* ------------------------------------------------------------------------- *
* The software in this package is published under the terms of the BSD *
* style license a copy of which has been included with this distribution in *
* the LICENSE.txt file. *
* *
* Original code by Joerg Schaible *
*****************************************************************************/
package org.nanocontainer.remoting.jmx;
import javax.management.DynamicMBean;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import org.picocontainer.ComponentAdapter;
import org.picocontainer.PicoContainer;
/**
* DynamicMBeanProvider, that will provide a component directly if it is already a {@link DynamicMBean}.
* @author Jörg Schaible
* @since 1.0
*/
public class DynamicMBeanComponentProvider implements DynamicMBeanProvider {
private final ObjectNameFactory objectNameFactory;
/**
* Construct a DynamicMBeanComponentProvider. This instance will use a {@link TypedObjectNameFactory} and register
* all MBeans in the default domain of the {@link javax.management.MBeanServer}.
*/
public DynamicMBeanComponentProvider() {
this(new TypedObjectNameFactory());
}
/**
* Construct a DynamicMBeanComponentProvider with a specified ObjectNameFactory.
* @param factory The {@link ObjectNameFactory}.
*/
public DynamicMBeanComponentProvider(final ObjectNameFactory factory) {
if (factory == null) {
throw new NullPointerException("ObjectFactoryName is null");
}
objectNameFactory = factory;
}
/**
* Provide the component itself as {@link DynamicMBean} if it is one and if an {@link ObjectName} can be created.
* @see org.nanocontainer.remoting.jmx.DynamicMBeanProvider#provide(org.picocontainer.PicoContainer,
* org.picocontainer.ComponentAdapter)
*/
public JMXRegistrationInfo provide(final PicoContainer picoContainer, final ComponentAdapter componentAdapter) {
if (DynamicMBean.class.isAssignableFrom(componentAdapter.getComponentImplementation())) {
final DynamicMBean mBean = (DynamicMBean)componentAdapter.getComponentInstance(picoContainer);
try {
final ObjectName objectName = objectNameFactory.create(componentAdapter.getComponentKey(), mBean);
if (objectName != null) {
return new JMXRegistrationInfo(objectName, mBean);
}
} catch (final MalformedObjectNameException e) {
throw new JMXRegistrationException("Cannot create ObjectName for component '"
+ componentAdapter.getComponentKey()
+ "'", e);
}
}
return null;
}
}
| bsd-3-clause |
kakada/dhis2 | dhis-web/dhis-web-commons/src/main/java/org/hisp/dhis/paging/ActionPagingSupport.java | 4525 | package org.hisp.dhis.paging;
/*
* Copyright (c) 2004-2015, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project 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.
*/
import java.util.Enumeration;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import org.hisp.dhis.system.paging.Paging;
import org.hisp.dhis.util.ContextUtils;
import com.opensymphony.xwork2.Action;
/**
* @author Quang Nguyen
*/
public abstract class ActionPagingSupport<T>
implements Action
{
protected Integer currentPage;
public Integer getCurrentPage()
{
return currentPage;
}
public void setCurrentPage( Integer currentPage )
{
this.currentPage = currentPage;
}
protected Integer pageSize;
public void setPageSize( Integer pageSize )
{
this.pageSize = pageSize;
}
protected Paging paging;
public Paging getPaging()
{
return paging;
}
protected boolean usePaging = false;
public boolean isUsePaging()
{
return usePaging;
}
public void setUsePaging( boolean usePaging )
{
this.usePaging = usePaging;
}
protected Integer getDefaultPageSize()
{
String sessionPageSize = ContextUtils.getCookieValue( ServletActionContext.getRequest(), "pageSize" );
if ( sessionPageSize != null )
{
return Integer.valueOf( sessionPageSize );
}
return Paging.DEFAULT_PAGE_SIZE;
}
@SuppressWarnings( "unchecked" )
private String getCurrentLink()
{
HttpServletRequest request = ServletActionContext.getRequest();
String baseLink = request.getRequestURI() + "?";
Enumeration<String> paramNames = request.getParameterNames();
while ( paramNames.hasMoreElements() )
{
String paramName = paramNames.nextElement();
if ( !paramName.equalsIgnoreCase( "pageSize" ) && !paramName.equalsIgnoreCase( "currentPage" ) )
{
String[] values = request.getParameterValues( paramName );
for ( String value : values )
{
baseLink += paramName + "=" + value + "&";
}
}
}
return baseLink.substring( 0, baseLink.length() - 1 );
}
protected Paging createPaging( Integer totalRecord )
{
Paging resultPaging = new Paging( getCurrentLink(), pageSize == null ? getDefaultPageSize() : pageSize );
resultPaging.setCurrentPage( currentPage == null ? 0 : currentPage );
resultPaging.setTotal( totalRecord );
return resultPaging;
}
protected List<T> getBlockElement( List<T> elementList, int startPos, int pageSize )
{
List<T> returnList;
int endPos = paging.getEndPos();
returnList = elementList.subList( startPos, endPos );
return returnList;
}
}
| bsd-3-clause |