repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
PaulLuchyn/libreplan | libreplan-business/src/main/java/org/libreplan/business/resources/entities/Machine.java | 3681 | /*
* This file is part of LibrePlan
*
* Copyright (C) 2009-2010 Fundación para o Fomento da Calidade Industrial e
* Desenvolvemento Tecnolóxico de Galicia
* Copyright (C) 2010-2011 Igalia, S.L.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.libreplan.business.resources.entities;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.validator.constraints.NotEmpty;
import javax.validation.Valid;
/**
* Represents entity. It is another type of work resource.
*
* @author Javier Moran Rua <jmoran@igalia.com>
* @author Fernando Bellas Permuy <fbellas@udc.es>
*/
public class Machine extends Resource {
private final static ResourceEnum type = ResourceEnum.MACHINE;
private String name;
private String description;
private Set<MachineWorkersConfigurationUnit> configurationUnits = new HashSet<>();
@Valid
public Set<MachineWorkersConfigurationUnit> getConfigurationUnits() {
return Collections.unmodifiableSet(configurationUnits);
}
public void addMachineWorkersConfigurationUnit(MachineWorkersConfigurationUnit unit) {
configurationUnits.add(unit);
}
public void removeMachineWorkersConfigurationUnit(MachineWorkersConfigurationUnit unit) {
configurationUnits.remove(unit);
}
public static Machine createUnvalidated(String code, String name, String description) {
Machine machine = create(new Machine(), code);
machine.name = name;
machine.description = description;
return machine;
}
public void updateUnvalidated(String name, String description) {
if (!StringUtils.isBlank(name)) {
this.name = name;
}
if (!StringUtils.isBlank(description)) {
this.description = description;
}
}
/**
* Used by Hibernate. Do not use!
*/
protected Machine() {}
public static Machine create() {
return create(new Machine());
}
public static Machine create(String code) {
return create(new Machine(), code);
}
@NotEmpty(message = "machine name not specified")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public String getShortDescription() {
return name + " (" + getCode() + ")";
}
public void setDescription(String description) {
this.description = description;
}
@Override
protected boolean isCriterionSatisfactionOfCorrectType(CriterionSatisfaction c) {
return c.getResourceType().equals(ResourceEnum.MACHINE);
}
@Override
public ResourceEnum getType() {
return type;
}
@Override
public String toString() {
return String.format("MACHINE: %s", name);
}
@Override
public String getHumanId() {
return name;
}
}
| agpl-3.0 |
aglne/mycollab | mycollab-web/src/main/java/com/mycollab/vaadin/web/ui/CheckBoxDecor.java | 1104 | /**
* Copyright © MyCollab
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.mycollab.vaadin.web.ui;
import com.vaadin.ui.CheckBox;
import com.vaadin.ui.themes.ValoTheme;
/**
* @author MyCollab Ltd.
* @since 3.0
*/
public class CheckBoxDecor extends CheckBox {
private static final long serialVersionUID = 1L;
public CheckBoxDecor(String title, boolean value) {
super(title, value);
this.addStyleName(ValoTheme.CHECKBOX_SMALL);
}
}
| agpl-3.0 |
aihua/opennms | features/poller/remote/src/test/java/org/opennms/netmgt/poller/remote/metadata/EmailValidatorTest.java | 2394 | /*******************************************************************************
* This file is part of OpenNMS(R).
*
* Copyright (C) 2016-2016 The OpenNMS Group, Inc.
* OpenNMS(R) is Copyright (C) 1999-2016 The OpenNMS Group, Inc.
*
* OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
*
* OpenNMS(R) is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* OpenNMS(R) is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with OpenNMS(R). If not, see:
* http://www.gnu.org/licenses/
*
* For more information contact:
* OpenNMS(R) Licensing <license@opennms.org>
* http://www.opennms.org/
* http://www.opennms.com/
*******************************************************************************/
package org.opennms.netmgt.poller.remote.metadata;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.Test;
import org.opennms.netmgt.poller.remote.metadata.MetadataField.Validator;
public class EmailValidatorTest {
private Validator m_validator;
@Before
public void setUp() {
m_validator = new EmailValidator();
}
@Test
public void testValid() {
assertTrue(m_validator.isValid("ranger@opennms.org"));
assertTrue(m_validator.isValid("ranger@monkey.esophagus"));
assertTrue(m_validator.isValid("ranger@giant.list.of.sub.domains.com"));
}
@Test
public void testInvalid() {
assertFalse(m_validator.isValid("ranger@opennms"));
assertFalse(m_validator.isValid("ranger.monkey.esophagus"));
assertFalse(m_validator.isValid("ranger@"));
assertFalse(m_validator.isValid("@foo.com"));
assertFalse(m_validator.isValid("@foo.com."));
assertFalse(m_validator.isValid("@foo.com"));
assertFalse(m_validator.isValid(".@foo.com"));
assertFalse(m_validator.isValid(".e@foo.com"));
}
}
| agpl-3.0 |
paraita/programming | programming-core/src/main/java/org/objectweb/proactive/core/jmx/mbean/JMXClassLoaderMBean.java | 1413 | /*
* ProActive Parallel Suite(TM):
* The Open Source library for parallel and distributed
* Workflows & Scheduling, Orchestration, Cloud Automation
* and Big Data Analysis on Enterprise Grids & Clouds.
*
* Copyright (c) 2007 - 2017 ActiveEon
* Contact: contact@activeeon.com
*
* This library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation: version 3 of
* the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* If needed, contact us to obtain a release under GPL Version 2 or 3
* or a different license than the AGPL.
*/
package org.objectweb.proactive.core.jmx.mbean;
import java.io.Serializable;
/**
* This interface is used to add a class loader to the MBean Server repository.
* See JMX Specification, version 1.4 ; Chap 8.4.1 : 'A class loader is added to the repository if it is registered as an MBean'.
* @author The ProActive Team
*/
public interface JMXClassLoaderMBean extends Serializable {
}
| agpl-3.0 |
kuali/kc | coeus-impl/src/main/java/org/kuali/coeus/propdev/impl/action/ProposalDevelopmentRejectionRule.java | 1586 | /*
* Kuali Coeus, a comprehensive research administration system for higher education.
*
* Copyright 2005-2016 Kuali, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kuali.coeus.propdev.impl.action;
import org.apache.commons.lang3.StringUtils;
import org.kuali.coeus.sys.framework.rule.KcTransactionalDocumentRuleBase;
import org.kuali.rice.core.api.util.RiceKeyConstants;
public class ProposalDevelopmentRejectionRule extends KcTransactionalDocumentRuleBase {
private static final String ACTION_REASON = "proposalDevelopmentRejectionBean.actionReason";
public boolean proccessProposalDevelopmentRejection(ProposalDevelopmentActionBean bean) {
boolean valid = true;
if (StringUtils.isEmpty(bean.getActionReason())) {
valid = false;
String errorParams = "";
reportError(ACTION_REASON, RiceKeyConstants.ERROR_REQUIRED, errorParams);
}
return valid;
}
}
| agpl-3.0 |
ggiudetti/opencms-core | src/org/opencms/gwt/shared/sort/CmsComparatorType.java | 1889 | /*
* This library is part of OpenCms -
* the Open Source Content Management System
*
* Copyright (c) Alkacon Software GmbH & Co. KG (http://www.alkacon.com)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* For further information about Alkacon Software, please see the
* company website: http://www.alkacon.com
*
* For further information about OpenCms, please see the
* project website: http://www.opencms.org
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.opencms.gwt.shared.sort;
import java.util.Comparator;
/**
* Comparator for objects with a type property.<p>
*
* @see I_CmsHasType
*
* @since 8.0.0
*/
public class CmsComparatorType implements Comparator<I_CmsHasType> {
/** Sort order flag. */
private boolean m_ascending;
/**
* Constructor.<p>
*
* @param ascending if <code>true</code> order is ascending
*/
public CmsComparatorType(boolean ascending) {
m_ascending = ascending;
}
/**
* @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
*/
public int compare(I_CmsHasType o1, I_CmsHasType o2) {
int result = o1.getType().compareTo(o2.getType());
return m_ascending ? result : -result;
}
}
| lgpl-2.1 |
modius/railo | railo-java/railo-core/src/railo/runtime/search/lucene2/query/Concator.java | 516 | package railo.runtime.search.lucene2.query;
import railo.commons.lang.StringUtil;
public final class Concator implements Op {
private Op left;
private Op right;
public Concator(Op left,Op right) {
this.left=left;
this.right=right;
}
@Override
public String toString() {
if(left instanceof Literal && right instanceof Literal) {
String str=((Literal)left).literal+" "+((Literal)right).literal;
return "\""+StringUtil.replace(str, "\"", "\"\"", false)+"\"";
}
return left+" "+right;
}
}
| lgpl-2.1 |
britt/hivedb | src/main/java/org/hivedb/hibernate/RecordNodeOpenSessionEvent.java | 834 | package org.hivedb.hibernate;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.shards.session.OpenSessionEvent;
import java.sql.SQLException;
public class RecordNodeOpenSessionEvent implements OpenSessionEvent {
public static ThreadLocal<String> node = new ThreadLocal<String>();
public static String getNode() {
return node.get();
}
public static void setNode(Session session) {
node.set(getNode(session));
}
public void onOpenSession(Session session) {
setNode(session);
}
@SuppressWarnings("deprecation")
private static String getNode(Session session) {
String node = "";
if (session != null) {
try {
node = session.connection().getMetaData().getURL();
} catch (SQLException ex) {
} catch (HibernateException ex) {
}
}
return node;
}
}
| lgpl-2.1 |
JordanReiter/railo | railo-java/railo-core/src/railo/runtime/functions/dateTime/NowServer.java | 870 | package railo.runtime.functions.dateTime;
import java.util.TimeZone;
import railo.runtime.PageContext;
import railo.runtime.exp.ExpressionException;
import railo.runtime.ext.function.Function;
import railo.runtime.tag.util.DeprecatedUtil;
import railo.runtime.type.dt.DateTime;
import railo.runtime.type.dt.DateTimeImpl;
/**
* Implements the CFML Function now
* @deprecated removed with no replacement
*/
public final class NowServer implements Function {
/**
* @param pc
* @return server time
* @throws ExpressionException
*/
public static DateTime call(PageContext pc ) throws ExpressionException {
DeprecatedUtil.function(pc,"nowServer");
long now = System.currentTimeMillis();
int railo = pc.getTimeZone().getOffset(now);
int server = TimeZone.getDefault().getOffset(now);
return new DateTimeImpl(pc,now-(railo-server),false);
}
} | lgpl-2.1 |
aruanruan/hivedb | src/main/java/org/hivedb/hibernate/simplified/PostDeleteEventListenerImpl.java | 2748 | package org.hivedb.hibernate.simplified;
import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.action.Executable;
import org.hibernate.event.PostDeleteEvent;
import org.hibernate.event.PostDeleteEventListener;
import org.hivedb.Hive;
import org.hivedb.HiveLockableException;
import org.hivedb.configuration.EntityConfig;
import org.hivedb.configuration.EntityHiveConfig;
import org.hivedb.hibernate.HiveIndexer;
import org.hivedb.util.classgen.ReflectionTools;
import org.hivedb.util.functional.Transform;
import org.hivedb.util.functional.Unary;
import java.io.Serializable;
/**
* This is an alternative way of deleting the hive indexes after successful
* transaction completion (instead of using a custom Interceptor) and up
* for discussion. Hooked up via org.hibernate.cfg.Configuration.
* getEventListeners().setPostDeleteEventListeners
*
* @author mellwanger
*/
public class PostDeleteEventListenerImpl implements PostDeleteEventListener {
private static final Logger log = Logger.getLogger(PostInsertEventListenerImpl.class);
private final EntityHiveConfig hiveConfig;
private final HiveIndexer indexer;
public PostDeleteEventListenerImpl(EntityHiveConfig hiveConfig, Hive hive) {
this.hiveConfig = hiveConfig;
indexer = new HiveIndexer(hive);
}
public void onPostDelete(final PostDeleteEvent event) {
event.getSession().getActionQueue().execute(new Executable() {
public void afterTransactionCompletion(boolean success) {
if (success) {
deleteIndexes(event.getEntity());
}
}
public void beforeExecutions() throws HibernateException {
// TODO Auto-generated method stub
}
public void execute() throws HibernateException {
// TODO Auto-generated method stub
}
public Serializable[] getPropertySpaces() {
// TODO Auto-generated method stub
return null;
}
public boolean hasAfterTransactionCompletion() {
return true;
}
});
}
@SuppressWarnings("unchecked")
private Class resolveEntityClass(Class clazz) {
return ReflectionTools.whichIsImplemented(
clazz,
Transform.map(new Unary<EntityConfig, Class>() {
public Class f(EntityConfig entityConfig) {
return entityConfig.getRepresentedInterface();
}
},
hiveConfig.getEntityConfigs()));
}
private void deleteIndexes(Object entity) {
try {
final Class<?> resolvedEntityClass = resolveEntityClass(entity.getClass());
if (resolvedEntityClass != null)
indexer.delete(hiveConfig.getEntityConfig(entity.getClass()), entity);
} catch (HiveLockableException e) {
log.warn(e);
}
}
}
| lgpl-2.1 |
xtiankisutsa/MARA_Framework | tools/decompilers/Krakatau/tests/disassembler/source/LineNumbersTest.java | 857 | import java.util.*;
public class LineNumbersTest extends LinkedList<Object>{
public LineNumbersTest(int x) {
super((x & 0) == 1 ?
new LinkedList<Object>((x & 1) == x++ ? new ArrayList<Object>() : new HashSet<Object>())
:new HashSet<Object>());
super.add(x = getLineNo());
this.add(x = getLineNo());
}
static int getLineNo() {
return new Throwable().fillInStackTrace().getStackTrace()[1].getLineNumber();
}
public static void main(String[] args) {
System.out.println(getLineNo());
System.out.println(new Throwable().fillInStackTrace().getStackTrace()[0].getFileName());
System.out.println(getLineNo());
System.out.println(new LineNumbersTest(2));
List<Object> foo = new ArrayList<>();
System.out.println(foo.addAll(foo));
}
}
| lgpl-3.0 |
dana-i2cat/opennaas | utils/rest-client/src/test/java/org/opennaas/client/rest/GRETunnelTest.java | 3036 | package org.opennaas.client.rest;
import java.io.FileNotFoundException;
import java.util.List;
import javax.ws.rs.core.MediaType;
import javax.xml.bind.JAXBException;
import org.apache.log4j.Logger;
import org.opennaas.extensions.router.model.EnabledLogicalElement.EnabledState;
import org.opennaas.extensions.router.model.GRETunnelConfiguration;
import org.opennaas.extensions.router.model.GRETunnelService;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.GenericType;
import com.sun.jersey.api.client.WebResource;
public class GRETunnelTest {
private static final Logger LOGGER = Logger.getLogger(GRETunnelTest.class);
public static void main(String[] args) throws FileNotFoundException, JAXBException {
createGRETunnel();
deleteGRETunnel();
showGRETunnelConfiguration();
}
/**
*
*/
private static void createGRETunnel() {
ClientResponse response = null;
String url = "http://localhost:8888/opennaas/router/lolaM20/gretunnel/createGRETunnel";
try {
Client client = Client.create();
WebResource webResource = client.resource(url);
response = webResource.type(MediaType.APPLICATION_XML).post(ClientResponse.class, getGRETunnelService());
LOGGER.info("Response code: " + response.getStatus());
} catch (Exception e) {
LOGGER.error(e.getMessage());
}
}
/**
*
*/
private static void deleteGRETunnel() {
ClientResponse response = null;
String url = "http://localhost:8888/opennaas/router/lolaM20/gretunnel/deleteGRETunnel";
try {
Client client = Client.create();
WebResource webResource = client.resource(url);
response = webResource.type(MediaType.APPLICATION_XML).post(ClientResponse.class, getGRETunnelService());
LOGGER.info("Response code: " + response.getStatus());
} catch (Exception e) {
LOGGER.error(e.getMessage());
}
}
/**
*
*/
private static void showGRETunnelConfiguration() {
List<GRETunnelService> response = null;
String url = "http://localhost:8888/opennaas/router/lolaM20/gretunnel/showGRETunnelConfiguration";
GenericType<List<GRETunnelService>> genericType =
new GenericType<List<GRETunnelService>>() {
};
try {
Client client = Client.create();
WebResource webResource = client.resource(url);
response = webResource.accept(MediaType.APPLICATION_XML).post(genericType);
LOGGER.info("Number of GRETunnels: " + response.size());
} catch (Exception e) {
LOGGER.error(e.getMessage());
}
}
/**
* @return
*/
private static GRETunnelService getGRETunnelService() {
GRETunnelService greTunnelService = new GRETunnelService();
greTunnelService.setName("MyTunnelService");
greTunnelService.setEnabledState(EnabledState.OTHER);
GRETunnelConfiguration greTunnelConfiguration = new GRETunnelConfiguration();
greTunnelConfiguration.setCaption("MyCaption");
greTunnelConfiguration.setInstanceID("MyInstanceId");
greTunnelService.setGRETunnelConfiguration(greTunnelConfiguration);
return greTunnelService;
}
} | lgpl-3.0 |
jaggr2/ch.bfh.fbi.mobiComp.17herz | com.tinkerforge/src/examples/Bricklet/Moisture/ExampleSimple.java | 1020 | package examples.Bricklet.Moisture;
import com.tinkerforge.BrickletMoisture;
import com.tinkerforge.IPConnection;
public class ExampleSimple {
private static final String host = "localhost";
private static final int port = 4223;
private static final String UID = "XYZ"; // Change to your UID
// Note: To make the examples code cleaner we do not handle exceptions. Exceptions you
// might normally want to catch are described in the documentation
public static void main(String args[]) throws Exception {
IPConnection ipcon = new IPConnection(); // Create IP connection
BrickletMoisture al = new BrickletMoisture(UID, ipcon); // Create device object
ipcon.connect(host, port); // Connect to brickd
// Don't use device before ipcon is connected
// Get current moisture value
int moisture = al.getMoistureValue(); // Can throw com.tinkerforge.TimeoutException
System.out.println("Moisture Value: " + moisture);
System.console().readLine("Press key to exit\n");
ipcon.disconnect();
}
}
| apache-2.0 |
alyiwang/WhereHows | wherehows-ingestion/src/test/java/wherehows/ingestion/converters/KafkaLogCompactionConverterTest.java | 2728 | /**
* Copyright 2015 LinkedIn Corp. 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.
*/
package wherehows.ingestion.converters;
import com.linkedin.events.metadata.DatasetIdentifier;
import com.linkedin.events.metadata.DeploymentDetail;
import com.linkedin.events.metadata.MetadataChangeEvent;
import java.util.Collections;
import org.testng.annotations.Test;
import static org.testng.Assert.*;
public class KafkaLogCompactionConverterTest {
@Test
public void testConvert() {
MetadataChangeEvent event = new MetadataChangeEvent();
event.datasetIdentifier = new DatasetIdentifier();
event.datasetIdentifier.dataPlatformUrn = "urn:li:dataPlatform:kafka";
DeploymentDetail deployment = new DeploymentDetail();
deployment.additionalDeploymentInfo = Collections.singletonMap("EI", "compact");
event.deploymentInfo = Collections.singletonList(deployment);
MetadataChangeEvent newEvent = new KafkaLogCompactionConverter().convert(event);
assertEquals(newEvent.datasetIdentifier.dataPlatformUrn, "urn:li:dataPlatform:kafka-lc");
}
@Test
public void testNotConvert() {
KafkaLogCompactionConverter converter = new KafkaLogCompactionConverter();
MetadataChangeEvent event = new MetadataChangeEvent();
event.datasetIdentifier = new DatasetIdentifier();
event.datasetIdentifier.dataPlatformUrn = "foo";
DeploymentDetail deployment = new DeploymentDetail();
deployment.additionalDeploymentInfo = Collections.singletonMap("EI", "compact");
event.deploymentInfo = Collections.singletonList(deployment);
MetadataChangeEvent newEvent = converter.convert(event);
assertEquals(newEvent.datasetIdentifier.dataPlatformUrn, "foo");
event.datasetIdentifier.dataPlatformUrn = "urn:li:dataPlatform:kafka";
event.deploymentInfo = null;
newEvent = converter.convert(event);
assertEquals(newEvent.datasetIdentifier.dataPlatformUrn, "urn:li:dataPlatform:kafka");
event.datasetIdentifier.dataPlatformUrn = "urn:li:dataPlatform:kafka";
deployment.additionalDeploymentInfo = Collections.singletonMap("EI", "delete");
event.deploymentInfo = Collections.singletonList(deployment);
newEvent = converter.convert(event);
assertEquals(newEvent.datasetIdentifier.dataPlatformUrn, "urn:li:dataPlatform:kafka");
}
}
| apache-2.0 |
engagepoint/camel | camel-core/src/test/java/org/apache/camel/util/DumpModelAsXmlChoiceFilterRouteTest.java | 2322 | /**
* 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.util;
import org.apache.camel.ContextTestSupport;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.model.ModelHelper;
/**
*
*/
public class DumpModelAsXmlChoiceFilterRouteTest extends ContextTestSupport {
public void testDumpModelAsXml() throws Exception {
String xml = ModelHelper.dumpModelAsXml(context.getRouteDefinition("myRoute"));
assertNotNull(xml);
log.info(xml);
assertTrue(xml.contains("<header>gold</header>"));
assertTrue(xml.contains("<header>extra-gold</header>"));
assertTrue(xml.contains("<simple>${body} contains Camel</simple>"));
}
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
from("direct:start").routeId("myRoute")
.to("log:input")
.choice()
.when().header("gold")
.to("mock:gold")
.filter().header("extra-gold")
.to("mock:extra-gold")
.endChoice()
.when().simple("${body} contains Camel")
.to("mock:camel")
.otherwise()
.to("mock:other")
.end()
.to("mock:result");
}
};
}
}
| apache-2.0 |
RanjithKumar5550/RanMifos | fineract-provider/src/main/java/org/apache/fineract/template/api/TemplatesApiResource.java | 9902 | /**
* 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.fineract.template.api;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.UriInfo;
import org.apache.fineract.commands.domain.CommandWrapper;
import org.apache.fineract.commands.service.CommandWrapperBuilder;
import org.apache.fineract.commands.service.PortfolioCommandSourceWritePlatformService;
import org.apache.fineract.infrastructure.core.api.ApiRequestParameterHelper;
import org.apache.fineract.infrastructure.core.data.CommandProcessingResult;
import org.apache.fineract.infrastructure.core.serialization.ApiRequestJsonSerializationSettings;
import org.apache.fineract.infrastructure.core.serialization.DefaultToApiJsonSerializer;
import org.apache.fineract.infrastructure.security.service.PlatformSecurityContext;
import org.apache.fineract.template.data.TemplateData;
import org.apache.fineract.template.domain.Template;
import org.apache.fineract.template.domain.TemplateEntity;
import org.apache.fineract.template.domain.TemplateType;
import org.apache.fineract.template.service.TemplateDomainService;
import org.apache.fineract.template.service.TemplateMergeService;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
@Path("/templates")
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
@Component
@Scope("singleton")
public class TemplatesApiResource {
private final Set<String> RESPONSE_TEMPLATES_DATA_PARAMETERS = new HashSet<>(Arrays.asList("id"));
private final Set<String> RESPONSE_TEMPLATE_DATA_PARAMETERS = new HashSet<>(Arrays.asList("id", "entities", "types", "template"));
private final String RESOURCE_NAME_FOR_PERMISSION = "template";
private final PlatformSecurityContext context;
private final DefaultToApiJsonSerializer<Template> toApiJsonSerializer;
private final DefaultToApiJsonSerializer<TemplateData> templateDataApiJsonSerializer;
private final ApiRequestParameterHelper apiRequestParameterHelper;
private final TemplateDomainService templateService;
private final TemplateMergeService templateMergeService;
private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService;
@Autowired
public TemplatesApiResource(final PlatformSecurityContext context, final DefaultToApiJsonSerializer<Template> toApiJsonSerializer,
final DefaultToApiJsonSerializer<TemplateData> templateDataApiJsonSerializer,
final ApiRequestParameterHelper apiRequestParameterHelper, final TemplateDomainService templateService,
final TemplateMergeService templateMergeService,
final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService) {
this.context = context;
this.toApiJsonSerializer = toApiJsonSerializer;
this.templateDataApiJsonSerializer = templateDataApiJsonSerializer;
this.apiRequestParameterHelper = apiRequestParameterHelper;
this.templateService = templateService;
this.templateMergeService = templateMergeService;
this.commandsSourceWritePlatformService = commandsSourceWritePlatformService;
}
@GET
public String retrieveAll(@DefaultValue("-1") @QueryParam("typeId") final int typeId,
@DefaultValue("-1") @QueryParam("entityId") final int entityId, @Context final UriInfo uriInfo) {
this.context.authenticatedUser().validateHasReadPermission(this.RESOURCE_NAME_FOR_PERMISSION);
// FIXME - we dont use the ORM when doing fetches - we write SQL and
// fetch through JDBC returning data to be serialized to JSON
List<Template> templates = new ArrayList<>();
if (typeId != -1 && entityId != -1) {
templates = this.templateService.getAllByEntityAndType(TemplateEntity.values()[entityId], TemplateType.values()[typeId]);
} else {
templates = this.templateService.getAll();
}
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
return this.toApiJsonSerializer.serialize(settings, templates, this.RESPONSE_TEMPLATES_DATA_PARAMETERS);
}
@GET
@Path("template")
public String template(@Context final UriInfo uriInfo) {
this.context.authenticatedUser().validateHasReadPermission(this.RESOURCE_NAME_FOR_PERMISSION);
final TemplateData templateData = TemplateData.template();
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
return this.templateDataApiJsonSerializer.serialize(settings, templateData, this.RESPONSE_TEMPLATES_DATA_PARAMETERS);
}
@POST
public String createTemplate(final String apiRequestBodyAsJson) {
final CommandWrapper commandRequest = new CommandWrapperBuilder().createTemplate().withJson(apiRequestBodyAsJson).build();
final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest);
return this.toApiJsonSerializer.serialize(result);
}
@GET
@Path("{templateId}")
public String retrieveOne(@PathParam("templateId") final Long templateId, @Context final UriInfo uriInfo) {
this.context.authenticatedUser().validateHasReadPermission(this.RESOURCE_NAME_FOR_PERMISSION);
final Template template = this.templateService.findOneById(templateId);
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
return this.toApiJsonSerializer.serialize(settings, template, this.RESPONSE_TEMPLATES_DATA_PARAMETERS);
}
@GET
@Path("{templateId}/template")
public String getTemplateByTemplate(@PathParam("templateId") final Long templateId, @Context final UriInfo uriInfo) {
this.context.authenticatedUser().validateHasReadPermission(this.RESOURCE_NAME_FOR_PERMISSION);
final TemplateData template = TemplateData.template(this.templateService.findOneById(templateId));
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
return this.templateDataApiJsonSerializer.serialize(settings, template, this.RESPONSE_TEMPLATE_DATA_PARAMETERS);
}
@PUT
@Path("{templateId}")
public String saveTemplate(@PathParam("templateId") final Long templateId, final String apiRequestBodyAsJson) {
final CommandWrapper commandRequest = new CommandWrapperBuilder().updateTemplate(templateId).withJson(apiRequestBodyAsJson).build();
final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest);
return this.toApiJsonSerializer.serialize(result);
}
@DELETE
@Path("{templateId}")
public String deleteTemplate(@PathParam("templateId") final Long templateId) {
final CommandWrapper commandRequest = new CommandWrapperBuilder().deleteTemplate(templateId).build();
final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest);
return this.toApiJsonSerializer.serialize(result);
}
@POST
@Path("{templateId}")
@Produces({ MediaType.TEXT_HTML })
public String mergeTemplate(@PathParam("templateId") final Long templateId, @Context final UriInfo uriInfo,
final String apiRequestBodyAsJson) throws MalformedURLException, IOException {
final Template template = this.templateService.findOneById(templateId);
@SuppressWarnings("unchecked")
final HashMap<String, Object> result = new ObjectMapper().readValue(apiRequestBodyAsJson, HashMap.class);
final MultivaluedMap<String, String> parameters = uriInfo.getQueryParameters();
final Map<String, Object> parametersMap = new HashMap<>();
for (final Map.Entry<String, List<String>> entry : parameters.entrySet()) {
if (entry.getValue().size() == 1) {
parametersMap.put(entry.getKey(), entry.getValue().get(0));
} else {
parametersMap.put(entry.getKey(), entry.getValue());
}
}
parametersMap.put("BASE_URI", uriInfo.getBaseUri());
parametersMap.putAll(result);
return this.templateMergeService.compile(template, parametersMap);
}
} | apache-2.0 |
amdtelecom/jsmpp | jsmpp/src/main/java/org/jsmpp/bean/SimpleDataCoding.java | 3967 | /*
* 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.jsmpp.bean;
/**
* This is simple DataCoding. Only contains Alphabet (DEFAULT and 8-bit) and
* Message Class.
*
* @author uudashr
*
*/
public class SimpleDataCoding implements DataCoding {
private final Alphabet alphabet;
private final MessageClass messageClass;
/**
* Construct Data Coding using default Alphabet and
* {@link MessageClass#CLASS1} Message Class.
*/
public SimpleDataCoding() {
this(Alphabet.ALPHA_DEFAULT, MessageClass.CLASS1);
}
/**
* Construct Data Coding using specified Alphabet and Message Class.
*
* @param alphabet is the alphabet. Only support
* {@link Alphabet#ALPHA_DEFAULT} and {@link Alphabet#ALPHA_8_BIT}.
* @param messageClass
* @throws IllegalArgumentException if alphabet is <tt>null</tt> or using
* non {@link Alphabet#ALPHA_DEFAULT} and
* {@link Alphabet#ALPHA_8_BIT} alphabet or
* <code>messageClass</code> is null.
*/
public SimpleDataCoding(Alphabet alphabet, MessageClass messageClass) throws IllegalArgumentException {
if (alphabet == null) {
throw new IllegalArgumentException(
"Alphabet is mandatory, can't be null");
}
if (alphabet.equals(Alphabet.ALPHA_UCS2)
|| alphabet.isReserved()) {
throw new IllegalArgumentException(
"Supported alphabet for SimpleDataCoding does not include "
+ Alphabet.ALPHA_UCS2 + " or "
+ "reserved alphabet codes. Current alphabet is " + alphabet);
}
if (messageClass == null) {
throw new IllegalArgumentException(
"MessageClass is mandatory, can't be null");
}
this.alphabet = alphabet;
this.messageClass = messageClass;
}
public Alphabet getAlphabet() {
return alphabet;
}
public MessageClass getMessageClass() {
return messageClass;
}
public byte toByte() {
// base byte is 11110xxx or 0xf0, others injected
byte value = (byte)0xf0;
value |= alphabet.value();
value |= messageClass.value();
return value;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((alphabet == null) ? 0 : alphabet.hashCode());
result = prime * result
+ ((messageClass == null) ? 0 : messageClass.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
SimpleDataCoding other = (SimpleDataCoding)obj;
if (alphabet == null) {
if (other.alphabet != null)
return false;
} else if (!alphabet.equals(other.alphabet))
return false;
if (messageClass == null) {
if (other.messageClass != null)
return false;
} else if (!messageClass.equals(other.messageClass))
return false;
return true;
}
@Override
public String toString() {
return "DataCoding:" + (0xff & toByte());
}
}
| apache-2.0 |
wprice/boon | boon/src/main/java/org/boon/validation/annotations/Email.java | 2011 | /*
* Copyright 2013-2014 Richard M. Hightower
* 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.
*
* __________ _____ __ .__
* \______ \ ____ ____ ____ /\ / \ _____ | | _|__| ____ ____
* | | _// _ \ / _ \ / \ \/ / \ / \\__ \ | |/ / |/ \ / ___\
* | | ( <_> | <_> ) | \ /\ / Y \/ __ \| <| | | \/ /_/ >
* |______ /\____/ \____/|___| / \/ \____|__ (____ /__|_ \__|___| /\___ /
* \/ \/ \/ \/ \/ \//_____/
* ____. ___________ _____ ______________.___.
* | |____ ___ _______ \_ _____/ / _ \ / _____/\__ | |
* | \__ \\ \/ /\__ \ | __)_ / /_\ \ \_____ \ / | |
* /\__| |/ __ \\ / / __ \_ | \/ | \/ \ \____ |
* \________(____ /\_/ (____ / /_______ /\____|__ /_______ / / ______|
* \/ \/ \/ \/ \/ \/
*/
package org.boon.validation.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention ( RetentionPolicy.RUNTIME )
@Target ( { ElementType.METHOD, ElementType.TYPE, ElementType.FIELD } )
public @interface Email {
String detailMessage() default "";
String summaryMessage() default "";
}
| apache-2.0 |
signed/intellij-community | platform/usageView/src/com/intellij/usages/impl/rules/NonCodeUsageGroupingRule.java | 4612 | /*
* Copyright 2000-2015 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.usages.impl.rules;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.GeneratedSourcesFilter;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.usageView.UsageInfo;
import com.intellij.usageView.UsageViewBundle;
import com.intellij.usages.*;
import com.intellij.usages.rules.PsiElementUsage;
import com.intellij.usages.rules.SingleParentUsageGroupingRule;
import com.intellij.usages.rules.UsageInFile;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* @author max
*/
public class NonCodeUsageGroupingRule extends SingleParentUsageGroupingRule {
private final Project myProject;
public NonCodeUsageGroupingRule(Project project) {
myProject = project;
}
private static class CodeUsageGroup extends UsageGroupBase {
private static final UsageGroup INSTANCE = new CodeUsageGroup();
private CodeUsageGroup() {
super(0);
}
@Override
@NotNull
public String getText(UsageView view) {
return view == null ? UsageViewBundle.message("node.group.code.usages") : view.getPresentation().getCodeUsagesString();
}
public String toString() {
//noinspection HardCodedStringLiteral
return "CodeUsages";
}
}
private static class UsageInGeneratedCodeGroup extends UsageGroupBase {
public static final UsageGroup INSTANCE = new UsageInGeneratedCodeGroup();
private UsageInGeneratedCodeGroup() {
super(3);
}
@Override
@NotNull
public String getText(UsageView view) {
return view == null ? UsageViewBundle.message("node.usages.in.generated.code") : view.getPresentation().getUsagesInGeneratedCodeString();
}
public String toString() {
return "UsagesInGeneratedCode";
}
}
private static class NonCodeUsageGroup extends UsageGroupBase {
public static final UsageGroup INSTANCE = new NonCodeUsageGroup();
private NonCodeUsageGroup() {
super(2);
}
@Override
@NotNull
public String getText(UsageView view) {
return view == null ? UsageViewBundle.message("node.non.code.usages") : view.getPresentation().getNonCodeUsagesString();
}
@Override
public void update() {
}
public String toString() {
//noinspection HardCodedStringLiteral
return "NonCodeUsages";
}
}
private static class DynamicUsageGroup extends UsageGroupBase {
public static final UsageGroup INSTANCE = new DynamicUsageGroup();
@NonNls private static final String DYNAMIC_CAPTION = "Dynamic usages";
public DynamicUsageGroup() {
super(1);
}
@Override
@NotNull
public String getText(UsageView view) {
if (view == null) {
return DYNAMIC_CAPTION;
}
else {
final String dynamicCodeUsagesString = view.getPresentation().getDynamicCodeUsagesString();
return dynamicCodeUsagesString == null ? DYNAMIC_CAPTION : dynamicCodeUsagesString;
}
}
public String toString() {
//noinspection HardCodedStringLiteral
return "DynamicUsages";
}
}
@Nullable
@Override
protected UsageGroup getParentGroupFor(@NotNull Usage usage, @NotNull UsageTarget[] targets) {
if (usage instanceof UsageInFile) {
VirtualFile file = ((UsageInFile)usage).getFile();
if (file != null && GeneratedSourcesFilter.isGeneratedSourceByAnyFilter(file, myProject)) {
return UsageInGeneratedCodeGroup.INSTANCE;
}
}
if (usage instanceof PsiElementUsage) {
if (usage instanceof UsageInfo2UsageAdapter) {
final UsageInfo usageInfo = ((UsageInfo2UsageAdapter)usage).getUsageInfo();
if (usageInfo.isDynamicUsage()) {
return DynamicUsageGroup.INSTANCE;
}
}
if (((PsiElementUsage)usage).isNonCodeUsage()) {
return NonCodeUsageGroup.INSTANCE;
}
else {
return CodeUsageGroup.INSTANCE;
}
}
return null;
}
}
| apache-2.0 |
flofreud/aws-sdk-java | aws-java-sdk-gamelift/src/main/java/com/amazonaws/services/gamelift/model/transform/CreateAliasResultJsonUnmarshaller.java | 2842 | /*
* Copyright 2010-2016 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.gamelift.model.transform;
import java.util.Map;
import java.util.Map.Entry;
import java.math.*;
import java.nio.ByteBuffer;
import com.amazonaws.services.gamelift.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* CreateAliasResult JSON Unmarshaller
*/
public class CreateAliasResultJsonUnmarshaller implements
Unmarshaller<CreateAliasResult, JsonUnmarshallerContext> {
public CreateAliasResult unmarshall(JsonUnmarshallerContext context)
throws Exception {
CreateAliasResult createAliasResult = new CreateAliasResult();
int originalDepth = context.getCurrentDepth();
String currentParentElement = context.getCurrentParentElement();
int targetDepth = originalDepth + 1;
JsonToken token = context.getCurrentToken();
if (token == null)
token = context.nextToken();
if (token == VALUE_NULL)
return null;
while (true) {
if (token == null)
break;
if (token == FIELD_NAME || token == START_OBJECT) {
if (context.testExpression("Alias", targetDepth)) {
context.nextToken();
createAliasResult.setAlias(AliasJsonUnmarshaller
.getInstance().unmarshall(context));
}
} else if (token == END_ARRAY || token == END_OBJECT) {
if (context.getLastParsedParentElement() == null
|| context.getLastParsedParentElement().equals(
currentParentElement)) {
if (context.getCurrentDepth() <= originalDepth)
break;
}
}
token = context.nextToken();
}
return createAliasResult;
}
private static CreateAliasResultJsonUnmarshaller instance;
public static CreateAliasResultJsonUnmarshaller getInstance() {
if (instance == null)
instance = new CreateAliasResultJsonUnmarshaller();
return instance;
}
}
| apache-2.0 |
dropbox/bazel | src/tools/android/java/com/google/devtools/build/android/desugar/io/ZipOutputFileProvider.java | 2761 | // Copyright 2017 The Bazel Authors. 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.build.android.desugar.io;
import static com.google.common.base.Preconditions.checkArgument;
import com.google.common.io.ByteStreams;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/** Output provider is a zip file. */
class ZipOutputFileProvider implements OutputFileProvider {
private final ZipOutputStream out;
public ZipOutputFileProvider(Path root) throws IOException {
out = new ZipOutputStream(new BufferedOutputStream(Files.newOutputStream(root)));
}
@Override
public void copyFrom(String filename, InputFileProvider inputFileProvider) throws IOException {
// TODO(bazel-team): Avoid de- and re-compressing resource files
out.putNextEntry(inputFileProvider.getZipEntry(filename));
try (InputStream is = inputFileProvider.getInputStream(filename)) {
ByteStreams.copy(is, out);
}
out.closeEntry();
}
@Override
public void write(String filename, byte[] content) throws IOException {
checkArgument(filename.equals(DESUGAR_DEPS_FILENAME) || filename.endsWith(".class"),
"Expect file to be copied: %s", filename);
writeStoredEntry(out, filename, content);
}
@Override
public void close() throws IOException {
out.close();
}
private static void writeStoredEntry(ZipOutputStream out, String filename, byte[] content)
throws IOException {
// Need to pre-compute checksum for STORED (uncompressed) entries)
CRC32 checksum = new CRC32();
checksum.update(content);
ZipEntry result = new ZipEntry(filename);
result.setTime(0L); // Use stable timestamp Jan 1 1980
result.setCrc(checksum.getValue());
result.setSize(content.length);
result.setCompressedSize(content.length);
// Write uncompressed, since this is just an intermediary artifact that
// we will convert to .dex
result.setMethod(ZipEntry.STORED);
out.putNextEntry(result);
out.write(content);
out.closeEntry();
}
}
| apache-2.0 |
project-ncl/pnc | build-coordinator/src/test/java/org/jboss/pnc/coordinator/test/OutsideGroupDependentConfigsTest.java | 3646 | /**
* JBoss, Home of Professional Open Source.
* Copyright 2014-2022 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.pnc.coordinator.test;
import org.jboss.pnc.common.json.ConfigurationParseException;
import org.jboss.pnc.mock.repository.BuildConfigurationRepositoryMock;
import org.jboss.pnc.model.BuildConfiguration;
import org.jboss.pnc.model.BuildConfigurationSet;
import org.jboss.pnc.enums.RebuildMode;
import org.jboss.pnc.spi.datastore.DatastoreException;
import org.jboss.pnc.spi.exception.CoreException;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeoutException;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
/**
* Group consists of configA,config B and configC. <br/>
* configC is independent, configB depends on configA. <br/>
*
*
* config1 is an "outside" dependency of configA
*
* <p>
* Author: Michal Szynkiewicz, michal.l.szynkiewicz@gmail.com Date: 9/14/16 Time: 12:09 PM
* </p>
*/
public class OutsideGroupDependentConfigsTest extends AbstractDependentBuildTest {
private BuildConfiguration config1;
private BuildConfiguration configA;
private BuildConfiguration configB;
private BuildConfigurationSet configSet;
@Before
public void initialize() throws DatastoreException, ConfigurationParseException {
config1 = buildConfig("1");
configA = buildConfig("A", config1);
configB = buildConfig("B", configA);
BuildConfiguration configC = buildConfig("C");
configSet = configSet(configA, configB, configC);
buildConfigurationRepository = spy(new BuildConfigurationRepositoryMock());
when(buildConfigurationRepository.queryWithPredicates(any()))
.thenReturn(new ArrayList<>(configSet.getBuildConfigurations()));
super.initialize();
saveConfig(config1);
configSet.getBuildConfigurations().forEach(this::saveConfig);
insertNewBuildRecords(config1, configA, configB, configC);
makeResult(configA).dependOn(config1);
}
@Test
public void shouldNotRebuildIfDependencyIsNotRebuilt()
throws CoreException, TimeoutException, InterruptedException {
build(configSet, RebuildMode.IMPLICIT_DEPENDENCY_CHECK);
waitForEmptyBuildQueue();
List<BuildConfiguration> configsWithTasks = getBuiltConfigs();
assertThat(configsWithTasks).isEmpty();
}
@Test
public void shouldRebuildOnlyDependent() throws CoreException, TimeoutException, InterruptedException {
insertNewBuildRecords(config1);
build(configSet, RebuildMode.IMPLICIT_DEPENDENCY_CHECK);
waitForEmptyBuildQueue();
List<BuildConfiguration> configsWithTasks = getBuiltConfigs();
assertThat(configsWithTasks).hasSameElementsAs(Arrays.asList(configA, configB));
}
} | apache-2.0 |
Herve-M/sablecc | src/org/sablecc/sablecc/semantics/Context.java | 794 | /* This file is part of SableCC ( http://sablecc.org ).
*
* See the NOTICE file distributed with this work for copyright information.
*
* 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.sablecc.sablecc.semantics;
public class Context {
private Grammar grammar;
}
| apache-2.0 |
marsorp/blog | presto166/presto-main/src/main/java/com/facebook/presto/operator/OperatorStats.java | 15302 | /*
* 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.presto.operator;
import com.facebook.presto.sql.planner.plan.PlanNodeId;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.collect.ImmutableList;
import io.airlift.units.DataSize;
import io.airlift.units.Duration;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
import java.util.Optional;
import static com.google.common.base.Preconditions.checkArgument;
import static io.airlift.units.DataSize.succinctBytes;
import static java.util.Objects.requireNonNull;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
@Immutable
public class OperatorStats
{
private final int operatorId;
private final PlanNodeId planNodeId;
private final String operatorType;
private final long totalDrivers;
private final long addInputCalls;
private final Duration addInputWall;
private final Duration addInputCpu;
private final Duration addInputUser;
private final DataSize inputDataSize;
private final long inputPositions;
private final double sumSquaredInputPositions;
private final long getOutputCalls;
private final Duration getOutputWall;
private final Duration getOutputCpu;
private final Duration getOutputUser;
private final DataSize outputDataSize;
private final long outputPositions;
private final Duration blockedWall;
private final long finishCalls;
private final Duration finishWall;
private final Duration finishCpu;
private final Duration finishUser;
private final DataSize memoryReservation;
private final DataSize systemMemoryReservation;
private final Optional<BlockedReason> blockedReason;
private final OperatorInfo info;
@JsonCreator
public OperatorStats(
@JsonProperty("operatorId") int operatorId,
@JsonProperty("planNodeId") PlanNodeId planNodeId,
@JsonProperty("operatorType") String operatorType,
@JsonProperty("totalDrivers") long totalDrivers,
@JsonProperty("addInputCalls") long addInputCalls,
@JsonProperty("addInputWall") Duration addInputWall,
@JsonProperty("addInputCpu") Duration addInputCpu,
@JsonProperty("addInputUser") Duration addInputUser,
@JsonProperty("inputDataSize") DataSize inputDataSize,
@JsonProperty("inputPositions") long inputPositions,
@JsonProperty("sumSquaredInputPositions") double sumSquaredInputPositions,
@JsonProperty("getOutputCalls") long getOutputCalls,
@JsonProperty("getOutputWall") Duration getOutputWall,
@JsonProperty("getOutputCpu") Duration getOutputCpu,
@JsonProperty("getOutputUser") Duration getOutputUser,
@JsonProperty("outputDataSize") DataSize outputDataSize,
@JsonProperty("outputPositions") long outputPositions,
@JsonProperty("blockedWall") Duration blockedWall,
@JsonProperty("finishCalls") long finishCalls,
@JsonProperty("finishWall") Duration finishWall,
@JsonProperty("finishCpu") Duration finishCpu,
@JsonProperty("finishUser") Duration finishUser,
@JsonProperty("memoryReservation") DataSize memoryReservation,
@JsonProperty("systemMemoryReservation") DataSize systemMemoryReservation,
@JsonProperty("blockedReason") Optional<BlockedReason> blockedReason,
@JsonProperty("info") OperatorInfo info)
{
checkArgument(operatorId >= 0, "operatorId is negative");
this.operatorId = operatorId;
this.planNodeId = requireNonNull(planNodeId, "planNodeId is null");
this.operatorType = requireNonNull(operatorType, "operatorType is null");
this.totalDrivers = totalDrivers;
this.addInputCalls = addInputCalls;
this.addInputWall = requireNonNull(addInputWall, "addInputWall is null");
this.addInputCpu = requireNonNull(addInputCpu, "addInputCpu is null");
this.addInputUser = requireNonNull(addInputUser, "addInputUser is null");
this.inputDataSize = requireNonNull(inputDataSize, "inputDataSize is null");
checkArgument(inputPositions >= 0, "inputPositions is negative");
this.inputPositions = inputPositions;
this.sumSquaredInputPositions = sumSquaredInputPositions;
this.getOutputCalls = getOutputCalls;
this.getOutputWall = requireNonNull(getOutputWall, "getOutputWall is null");
this.getOutputCpu = requireNonNull(getOutputCpu, "getOutputCpu is null");
this.getOutputUser = requireNonNull(getOutputUser, "getOutputUser is null");
this.outputDataSize = requireNonNull(outputDataSize, "outputDataSize is null");
checkArgument(outputPositions >= 0, "outputPositions is negative");
this.outputPositions = outputPositions;
this.blockedWall = requireNonNull(blockedWall, "blockedWall is null");
this.finishCalls = finishCalls;
this.finishWall = requireNonNull(finishWall, "finishWall is null");
this.finishCpu = requireNonNull(finishCpu, "finishCpu is null");
this.finishUser = requireNonNull(finishUser, "finishUser is null");
this.memoryReservation = requireNonNull(memoryReservation, "memoryReservation is null");
this.systemMemoryReservation = requireNonNull(systemMemoryReservation, "systemMemoryReservation is null");
this.blockedReason = blockedReason;
this.info = info;
}
@JsonProperty
public int getOperatorId()
{
return operatorId;
}
@JsonProperty
public PlanNodeId getPlanNodeId()
{
return planNodeId;
}
@JsonProperty
public String getOperatorType()
{
return operatorType;
}
@JsonProperty
public long getTotalDrivers()
{
return totalDrivers;
}
@JsonProperty
public long getAddInputCalls()
{
return addInputCalls;
}
@JsonProperty
public Duration getAddInputWall()
{
return addInputWall;
}
@JsonProperty
public Duration getAddInputCpu()
{
return addInputCpu;
}
@JsonProperty
public Duration getAddInputUser()
{
return addInputUser;
}
@JsonProperty
public DataSize getInputDataSize()
{
return inputDataSize;
}
@JsonProperty
public long getInputPositions()
{
return inputPositions;
}
@JsonProperty
public double getSumSquaredInputPositions()
{
return sumSquaredInputPositions;
}
@JsonProperty
public long getGetOutputCalls()
{
return getOutputCalls;
}
@JsonProperty
public Duration getGetOutputWall()
{
return getOutputWall;
}
@JsonProperty
public Duration getGetOutputCpu()
{
return getOutputCpu;
}
@JsonProperty
public Duration getGetOutputUser()
{
return getOutputUser;
}
@JsonProperty
public DataSize getOutputDataSize()
{
return outputDataSize;
}
@JsonProperty
public long getOutputPositions()
{
return outputPositions;
}
@JsonProperty
public Duration getBlockedWall()
{
return blockedWall;
}
@JsonProperty
public long getFinishCalls()
{
return finishCalls;
}
@JsonProperty
public Duration getFinishWall()
{
return finishWall;
}
@JsonProperty
public Duration getFinishCpu()
{
return finishCpu;
}
@JsonProperty
public Duration getFinishUser()
{
return finishUser;
}
@JsonProperty
public DataSize getMemoryReservation()
{
return memoryReservation;
}
@JsonProperty
public DataSize getSystemMemoryReservation()
{
return systemMemoryReservation;
}
@JsonProperty
public Optional<BlockedReason> getBlockedReason()
{
return blockedReason;
}
@Nullable
@JsonProperty
public OperatorInfo getInfo()
{
return info;
}
public OperatorStats add(OperatorStats... operators)
{
return add(ImmutableList.copyOf(operators));
}
public OperatorStats add(Iterable<OperatorStats> operators)
{
long totalDrivers = this.totalDrivers;
long addInputCalls = this.addInputCalls;
long addInputWall = this.addInputWall.roundTo(NANOSECONDS);
long addInputCpu = this.addInputCpu.roundTo(NANOSECONDS);
long addInputUser = this.addInputUser.roundTo(NANOSECONDS);
long inputDataSize = this.inputDataSize.toBytes();
long inputPositions = this.inputPositions;
double sumSquaredInputPositions = this.sumSquaredInputPositions;
long getOutputCalls = this.getOutputCalls;
long getOutputWall = this.getOutputWall.roundTo(NANOSECONDS);
long getOutputCpu = this.getOutputCpu.roundTo(NANOSECONDS);
long getOutputUser = this.getOutputUser.roundTo(NANOSECONDS);
long outputDataSize = this.outputDataSize.toBytes();
long outputPositions = this.outputPositions;
long blockedWall = this.blockedWall.roundTo(NANOSECONDS);
long finishCalls = this.finishCalls;
long finishWall = this.finishWall.roundTo(NANOSECONDS);
long finishCpu = this.finishCpu.roundTo(NANOSECONDS);
long finishUser = this.finishUser.roundTo(NANOSECONDS);
long memoryReservation = this.memoryReservation.toBytes();
long systemMemoryReservation = this.systemMemoryReservation.toBytes();
Optional<BlockedReason> blockedReason = this.blockedReason;
Mergeable<OperatorInfo> base = getMergeableInfoOrNull(info);
for (OperatorStats operator : operators) {
checkArgument(operator.getOperatorId() == operatorId, "Expected operatorId to be %s but was %s", operatorId, operator.getOperatorId());
totalDrivers += operator.totalDrivers;
addInputCalls += operator.getAddInputCalls();
addInputWall += operator.getAddInputWall().roundTo(NANOSECONDS);
addInputCpu += operator.getAddInputCpu().roundTo(NANOSECONDS);
addInputUser += operator.getAddInputUser().roundTo(NANOSECONDS);
inputDataSize += operator.getInputDataSize().toBytes();
inputPositions += operator.getInputPositions();
sumSquaredInputPositions += operator.getSumSquaredInputPositions();
getOutputCalls += operator.getGetOutputCalls();
getOutputWall += operator.getGetOutputWall().roundTo(NANOSECONDS);
getOutputCpu += operator.getGetOutputCpu().roundTo(NANOSECONDS);
getOutputUser += operator.getGetOutputUser().roundTo(NANOSECONDS);
outputDataSize += operator.getOutputDataSize().toBytes();
outputPositions += operator.getOutputPositions();
finishCalls += operator.getFinishCalls();
finishWall += operator.getFinishWall().roundTo(NANOSECONDS);
finishCpu += operator.getFinishCpu().roundTo(NANOSECONDS);
finishUser += operator.getFinishUser().roundTo(NANOSECONDS);
blockedWall += operator.getBlockedWall().roundTo(NANOSECONDS);
memoryReservation += operator.getMemoryReservation().toBytes();
systemMemoryReservation += operator.getSystemMemoryReservation().toBytes();
if (operator.getBlockedReason().isPresent()) {
blockedReason = operator.getBlockedReason();
}
OperatorInfo info = operator.getInfo();
if (base != null && info != null && base.getClass() == info.getClass()) {
base = mergeInfo(base, info);
}
}
return new OperatorStats(
operatorId,
planNodeId,
operatorType,
totalDrivers,
addInputCalls,
new Duration(addInputWall, NANOSECONDS).convertToMostSuccinctTimeUnit(),
new Duration(addInputCpu, NANOSECONDS).convertToMostSuccinctTimeUnit(),
new Duration(addInputUser, NANOSECONDS).convertToMostSuccinctTimeUnit(),
succinctBytes(inputDataSize),
inputPositions,
sumSquaredInputPositions,
getOutputCalls,
new Duration(getOutputWall, NANOSECONDS).convertToMostSuccinctTimeUnit(),
new Duration(getOutputCpu, NANOSECONDS).convertToMostSuccinctTimeUnit(),
new Duration(getOutputUser, NANOSECONDS).convertToMostSuccinctTimeUnit(),
succinctBytes(outputDataSize),
outputPositions,
new Duration(blockedWall, NANOSECONDS).convertToMostSuccinctTimeUnit(),
finishCalls,
new Duration(finishWall, NANOSECONDS).convertToMostSuccinctTimeUnit(),
new Duration(finishCpu, NANOSECONDS).convertToMostSuccinctTimeUnit(),
new Duration(finishUser, NANOSECONDS).convertToMostSuccinctTimeUnit(),
succinctBytes(memoryReservation),
succinctBytes(systemMemoryReservation),
blockedReason,
(OperatorInfo) base);
}
@SuppressWarnings("unchecked")
private static Mergeable<OperatorInfo> getMergeableInfoOrNull(OperatorInfo info)
{
Mergeable<OperatorInfo> base = null;
if (info instanceof Mergeable) {
base = (Mergeable<OperatorInfo>) info;
}
return base;
}
@SuppressWarnings("unchecked")
private static <T> Mergeable<T> mergeInfo(Mergeable<T> base, T other)
{
return (Mergeable<T>) base.mergeWith(other);
}
public OperatorStats summarize()
{
return new OperatorStats(
operatorId,
planNodeId,
operatorType,
totalDrivers,
addInputCalls,
addInputWall,
addInputCpu,
addInputUser,
inputDataSize,
inputPositions,
sumSquaredInputPositions,
getOutputCalls,
getOutputWall,
getOutputCpu,
getOutputUser,
outputDataSize,
outputPositions,
blockedWall,
finishCalls,
finishWall,
finishCpu,
finishUser,
memoryReservation,
systemMemoryReservation,
blockedReason,
(info != null && info.isFinal()) ? info : null);
}
}
| apache-2.0 |
nezirus/elasticsearch | core/src/test/java/org/elasticsearch/client/AbstractClientHeadersTestCase.java | 9899 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.client;
import org.elasticsearch.ExceptionsHelper;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.GenericAction;
import org.elasticsearch.action.admin.cluster.reroute.ClusterRerouteAction;
import org.elasticsearch.action.admin.cluster.snapshots.create.CreateSnapshotAction;
import org.elasticsearch.action.admin.cluster.stats.ClusterStatsAction;
import org.elasticsearch.action.admin.cluster.storedscripts.DeleteStoredScriptAction;
import org.elasticsearch.action.admin.indices.cache.clear.ClearIndicesCacheAction;
import org.elasticsearch.action.admin.indices.create.CreateIndexAction;
import org.elasticsearch.action.admin.indices.flush.FlushAction;
import org.elasticsearch.action.admin.indices.stats.IndicesStatsAction;
import org.elasticsearch.action.delete.DeleteAction;
import org.elasticsearch.action.get.GetAction;
import org.elasticsearch.action.index.IndexAction;
import org.elasticsearch.action.search.SearchAction;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.util.concurrent.ThreadContext;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.env.Environment;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.threadpool.ThreadPool;
import java.util.HashMap;
import java.util.Map;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.notNullValue;
public abstract class AbstractClientHeadersTestCase extends ESTestCase {
protected static final Settings HEADER_SETTINGS = Settings.builder()
.put(ThreadContext.PREFIX + ".key1", "val1")
.put(ThreadContext.PREFIX + ".key2", "val 2")
.build();
private static final GenericAction[] ACTIONS = new GenericAction[] {
// client actions
GetAction.INSTANCE, SearchAction.INSTANCE, DeleteAction.INSTANCE, DeleteStoredScriptAction.INSTANCE,
IndexAction.INSTANCE,
// cluster admin actions
ClusterStatsAction.INSTANCE, CreateSnapshotAction.INSTANCE, ClusterRerouteAction.INSTANCE,
// indices admin actions
CreateIndexAction.INSTANCE, IndicesStatsAction.INSTANCE, ClearIndicesCacheAction.INSTANCE, FlushAction.INSTANCE
};
protected ThreadPool threadPool;
private Client client;
@Override
public void setUp() throws Exception {
super.setUp();
Settings settings = Settings.builder()
.put(HEADER_SETTINGS)
.put("path.home", createTempDir().toString())
.put("node.name", "test-" + getTestName())
.put(Environment.PATH_HOME_SETTING.getKey(), createTempDir().toString())
.build();
threadPool = new ThreadPool(settings);
client = buildClient(settings, ACTIONS);
}
@Override
public void tearDown() throws Exception {
super.tearDown();
client.close();
terminate(threadPool);
}
protected abstract Client buildClient(Settings headersSettings, GenericAction[] testedActions);
public void testActions() {
// TODO this is a really shitty way to test it, we need to figure out a way to test all the client methods
// without specifying each one (reflection doesn't as each action needs its own special settings, without
// them, request validation will fail before the test is executed. (one option is to enable disabling the
// validation in the settings??? - ugly and conceptually wrong)
// choosing arbitrary top level actions to test
client.prepareGet("idx", "type", "id").execute(new AssertingActionListener<>(GetAction.NAME, client.threadPool()));
client.prepareSearch().execute(new AssertingActionListener<>(SearchAction.NAME, client.threadPool()));
client.prepareDelete("idx", "type", "id").execute(new AssertingActionListener<>(DeleteAction.NAME, client.threadPool()));
client.admin().cluster().prepareDeleteStoredScript("lang", "id").execute(new AssertingActionListener<>(DeleteStoredScriptAction.NAME, client.threadPool()));
client.prepareIndex("idx", "type", "id").setSource("source", XContentType.JSON).execute(new AssertingActionListener<>(IndexAction.NAME, client.threadPool()));
// choosing arbitrary cluster admin actions to test
client.admin().cluster().prepareClusterStats().execute(new AssertingActionListener<>(ClusterStatsAction.NAME, client.threadPool()));
client.admin().cluster().prepareCreateSnapshot("repo", "bck").execute(new AssertingActionListener<>(CreateSnapshotAction.NAME, client.threadPool()));
client.admin().cluster().prepareReroute().execute(new AssertingActionListener<>(ClusterRerouteAction.NAME, client.threadPool()));
// choosing arbitrary indices admin actions to test
client.admin().indices().prepareCreate("idx").execute(new AssertingActionListener<>(CreateIndexAction.NAME, client.threadPool()));
client.admin().indices().prepareStats().execute(new AssertingActionListener<>(IndicesStatsAction.NAME, client.threadPool()));
client.admin().indices().prepareClearCache("idx1", "idx2").execute(new AssertingActionListener<>(ClearIndicesCacheAction.NAME, client.threadPool()));
client.admin().indices().prepareFlush().execute(new AssertingActionListener<>(FlushAction.NAME, client.threadPool()));
}
public void testOverrideHeader() throws Exception {
String key1Val = randomAlphaOfLength(5);
Map<String, String> expected = new HashMap<>();
expected.put("key1", key1Val);
expected.put("key2", "val 2");
client.threadPool().getThreadContext().putHeader("key1", key1Val);
client.prepareGet("idx", "type", "id")
.execute(new AssertingActionListener<>(GetAction.NAME, expected, client.threadPool()));
client.admin().cluster().prepareClusterStats()
.execute(new AssertingActionListener<>(ClusterStatsAction.NAME, expected, client.threadPool()));
client.admin().indices().prepareCreate("idx")
.execute(new AssertingActionListener<>(CreateIndexAction.NAME, expected, client.threadPool()));
}
protected static void assertHeaders(Map<String, String> headers, Map<String, String> expected) {
assertNotNull(headers);
assertEquals(expected.size(), headers.size());
for (Map.Entry<String, String> expectedEntry : expected.entrySet()) {
assertEquals(headers.get(expectedEntry.getKey()), expectedEntry.getValue());
}
}
protected static void assertHeaders(ThreadPool pool) {
assertHeaders(pool.getThreadContext().getHeaders(), (Map)HEADER_SETTINGS.getAsSettings(ThreadContext.PREFIX).getAsStructuredMap());
}
public static class InternalException extends Exception {
private final String action;
public InternalException(String action) {
this.action = action;
}
}
protected static class AssertingActionListener<T> implements ActionListener<T> {
private final String action;
private final Map<String, String> expectedHeaders;
private final ThreadPool pool;
public AssertingActionListener(String action, ThreadPool pool) {
this(action, (Map)HEADER_SETTINGS.getAsSettings(ThreadContext.PREFIX).getAsStructuredMap(), pool);
}
public AssertingActionListener(String action, Map<String, String> expectedHeaders, ThreadPool pool) {
this.action = action;
this.expectedHeaders = expectedHeaders;
this.pool = pool;
}
@Override
public void onResponse(T t) {
fail("an internal exception was expected for action [" + action + "]");
}
@Override
public void onFailure(Exception t) {
Throwable e = unwrap(t, InternalException.class);
assertThat("expected action [" + action + "] to throw an internal exception", e, notNullValue());
assertThat(action, equalTo(((InternalException) e).action));
Map<String, String> headers = pool.getThreadContext().getHeaders();
assertHeaders(headers, expectedHeaders);
}
public Throwable unwrap(Throwable t, Class<? extends Throwable> exceptionType) {
int counter = 0;
Throwable result = t;
while (!exceptionType.isInstance(result)) {
if (result.getCause() == null) {
return null;
}
if (result.getCause() == result) {
return null;
}
if (counter++ > 10) {
// dear god, if we got more than 10 levels down, WTF? just bail
fail("Exception cause unwrapping ran for 10 levels: " + ExceptionsHelper.stackTrace(t));
return null;
}
result = result.getCause();
}
return result;
}
}
}
| apache-2.0 |
ilinum/intellij-scala | test/org/jetbrains/plugins/scala/lang/formatter/AbstractScalaFormatterTestBase.java | 7072 | package org.jetbrains.plugins.scala.lang.formatter;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.EditorFactory;
import com.intellij.openapi.editor.impl.DocumentImpl;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiFile;
import com.intellij.psi.codeStyle.CodeStyleManager;
import com.intellij.psi.codeStyle.CodeStyleSettings;
import com.intellij.psi.codeStyle.CodeStyleSettingsManager;
import com.intellij.psi.codeStyle.CommonCodeStyleSettings;
import com.intellij.testFramework.LightIdeaTestCase;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.plugins.scala.ScalaLanguage;
import org.jetbrains.plugins.scala.lang.formatting.settings.ScalaCodeStyleSettings;
import org.jetbrains.plugins.scala.util.TestUtils;
import java.io.File;
import java.util.EnumMap;
import java.util.Map;
/**
* Base class for java formatter tests that holds utility methods.
*
* @author Denis Zhdanov
* @since Apr 27, 2010 6:26:29 PM
*/
//todo: almost duplicate from Java
public abstract class AbstractScalaFormatterTestBase extends LightIdeaTestCase {
protected enum Action {REFORMAT, INDENT}
private interface TestFormatAction {
void run(PsiFile psiFile, int startOffset, int endOffset);
}
private static final Map<Action, TestFormatAction> ACTIONS = new EnumMap<Action, TestFormatAction>(Action.class);
static {
ACTIONS.put(Action.REFORMAT, new TestFormatAction() {
public void run(PsiFile psiFile, int startOffset, int endOffset) {
CodeStyleManager.getInstance(getProject()).reformatText(psiFile, startOffset, endOffset);
}
});
ACTIONS.put(Action.INDENT, new TestFormatAction() {
public void run(PsiFile psiFile, int startOffset, int endOffset) {
CodeStyleManager.getInstance(getProject()).adjustLineIndent(psiFile, startOffset);
}
});
}
private static final String BASE_PATH = TestUtils.getTestDataPath() + "/psi/formatter";
public TextRange myTextRange;
public TextRange myLineRange;
public CommonCodeStyleSettings getCommonSettings() {
return getSettings().getCommonSettings(ScalaLanguage.INSTANCE);
}
public ScalaCodeStyleSettings getScalaSettings() {
return getSettings().getCustomSettings(ScalaCodeStyleSettings.class);
}
public CodeStyleSettings getSettings() {
return CodeStyleSettingsManager.getSettings(getProject());
}
public CommonCodeStyleSettings.IndentOptions getIndentOptions() {
return getCommonSettings().getIndentOptions();
}
public void doTest() throws Exception {
doTest(getTestName(false) + ".scala", getTestName(false) + "_after.scala");
}
public void doTest(String fileNameBefore, String fileNameAfter) throws Exception {
doTextTest(Action.REFORMAT, loadFile(fileNameBefore), loadFile(fileNameAfter));
}
public void doTextTest(final String text, String textAfter) throws IncorrectOperationException {
doTextTest(Action.REFORMAT, StringUtil.convertLineSeparators(text), StringUtil.convertLineSeparators(textAfter));
}
public void doTextTest(final Action action, final String text, String textAfter) throws IncorrectOperationException {
final PsiFile file = createFile("A.scala", text);
if (myLineRange != null) {
final DocumentImpl document = new DocumentImpl(text);
myTextRange =
new TextRange(document.getLineStartOffset(myLineRange.getStartOffset()), document.getLineEndOffset(myLineRange.getEndOffset()));
}
/*
CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() {
public void run() {
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
performFormatting(file);
}
});
}
}, null, null);
assertEquals(prepareText(textAfter), prepareText(file.getText()));
*/
final PsiDocumentManager manager = PsiDocumentManager.getInstance(getProject());
final Document document = manager.getDocument(file);
CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() {
public void run() {
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
document.replaceString(0, document.getTextLength(), text);
manager.commitDocument(document);
try {
TextRange rangeToUse = myTextRange;
if (rangeToUse == null) {
rangeToUse = file.getTextRange();
}
ACTIONS.get(action).run(file, rangeToUse.getStartOffset(), rangeToUse.getEndOffset());
}
catch (IncorrectOperationException e) {
assertTrue(e.getLocalizedMessage(), false);
}
}
});
}
}, "", "");
if (document == null) {
fail("Don't expect the document to be null");
return;
}
assertEquals(prepareText(textAfter), prepareText(document.getText()));
manager.commitDocument(document);
assertEquals(prepareText(textAfter), prepareText(file.getText()));
}
//todo: was unused, should be deleted (??)
/* public void doMethodTest(final String before, final String after) throws Exception {
doTextTest(
Action.REFORMAT,
"class Foo{\n" + " void foo() {\n" + before + '\n' + " }\n" + "}",
"class Foo {\n" + " void foo() {\n" + shiftIndentInside(after, 8, false) + '\n' + " }\n" + "}"
);
}
public void doClassTest(final String before, final String after) throws Exception {
doTextTest(
Action.REFORMAT,
"class Foo{\n" + before + '\n' + "}",
"class Foo {\n" + shiftIndentInside(after, 4, false) + '\n' + "}"
);
}*/
private static String prepareText(String actual) {
if (actual.startsWith("\n")) {
actual = actual.substring(1);
}
if (actual.startsWith("\n")) {
actual = actual.substring(1);
}
// Strip trailing spaces
final Document doc = EditorFactory.getInstance().createDocument(actual);
CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() {
public void run() {
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
((DocumentImpl)doc).stripTrailingSpaces(getProject());
}
});
}
}, "formatting", null);
return doc.getText().trim();
}
private static String loadFile(String name) throws Exception {
String fullName = BASE_PATH + File.separatorChar + name;
String text = new String(FileUtil.loadFileText(new File(fullName)));
text = StringUtil.convertLineSeparators(text);
return text;
}
@Override
protected void setUp() throws Exception {
super.setUp();
TestUtils.disableTimerThread();
}
}
| apache-2.0 |
liveqmock/platform-tools-idea | platform/indexing-impl/src/com/intellij/openapi/module/impl/scopes/LibraryRuntimeClasspathScope.java | 6421 | /*
* Copyright 2000-2009 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.openapi.module.impl.scopes;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.roots.*;
import com.intellij.openapi.roots.libraries.Library;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.util.containers.ContainerUtil;
import gnu.trove.THashSet;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
import java.util.*;
/**
* @author max
*/
public class LibraryRuntimeClasspathScope extends GlobalSearchScope {
private final ProjectFileIndex myIndex;
private final LinkedHashSet<VirtualFile> myEntries = new LinkedHashSet<VirtualFile>();
private int myCachedHashCode = 0;
public LibraryRuntimeClasspathScope(final Project project, final List<Module> modules) {
super(project);
myIndex = ProjectRootManager.getInstance(project).getFileIndex();
final Set<Sdk> processedSdk = new THashSet<Sdk>();
final Set<Library> processedLibraries = new THashSet<Library>();
final Set<Module> processedModules = new THashSet<Module>();
final Condition<OrderEntry> condition = new Condition<OrderEntry>() {
@Override
public boolean value(OrderEntry orderEntry) {
if (orderEntry instanceof ModuleOrderEntry) {
final Module module = ((ModuleOrderEntry)orderEntry).getModule();
return module != null && !processedModules.contains(module);
}
return true;
}
};
for (Module module : modules) {
buildEntries(module, processedModules, processedLibraries, processedSdk, condition);
}
}
public LibraryRuntimeClasspathScope(Project project, LibraryOrderEntry entry) {
super(project);
myIndex = ProjectRootManager.getInstance(project).getFileIndex();
Collections.addAll(myEntries, entry.getRootFiles(OrderRootType.CLASSES));
}
public int hashCode() {
if (myCachedHashCode == 0) {
myCachedHashCode = myEntries.hashCode();
}
return myCachedHashCode;
}
public boolean equals(Object object) {
if (object == this) return true;
if (object == null || object.getClass() != LibraryRuntimeClasspathScope.class) return false;
final LibraryRuntimeClasspathScope that = (LibraryRuntimeClasspathScope)object;
return that.myEntries.equals(myEntries);
}
private void buildEntries(@NotNull final Module module,
@NotNull final Set<Module> processedModules,
@NotNull final Set<Library> processedLibraries,
@NotNull final Set<Sdk> processedSdk,
Condition<OrderEntry> condition) {
if (!processedModules.add(module)) return;
ModuleRootManager.getInstance(module).orderEntries().recursively().satisfying(condition).process(new RootPolicy<LinkedHashSet<VirtualFile>>() {
public LinkedHashSet<VirtualFile> visitLibraryOrderEntry(final LibraryOrderEntry libraryOrderEntry,
final LinkedHashSet<VirtualFile> value) {
final Library library = libraryOrderEntry.getLibrary();
if (library != null && processedLibraries.add(library)) {
ContainerUtil.addAll(value, libraryOrderEntry.getRootFiles(OrderRootType.CLASSES));
}
return value;
}
public LinkedHashSet<VirtualFile> visitModuleSourceOrderEntry(final ModuleSourceOrderEntry moduleSourceOrderEntry,
final LinkedHashSet<VirtualFile> value) {
processedModules.add(moduleSourceOrderEntry.getOwnerModule());
ContainerUtil.addAll(value, moduleSourceOrderEntry.getRootModel().getSourceRoots());
return value;
}
@Override
public LinkedHashSet<VirtualFile> visitModuleOrderEntry(ModuleOrderEntry moduleOrderEntry, LinkedHashSet<VirtualFile> value) {
final Module depModule = moduleOrderEntry.getModule();
if (depModule != null) {
ContainerUtil.addAll(value, ModuleRootManager.getInstance(depModule).getSourceRoots());
}
return value;
}
public LinkedHashSet<VirtualFile> visitJdkOrderEntry(final JdkOrderEntry jdkOrderEntry, final LinkedHashSet<VirtualFile> value) {
final Sdk jdk = jdkOrderEntry.getJdk();
if (jdk != null && processedSdk.add(jdk)) {
ContainerUtil.addAll(value, jdkOrderEntry.getRootFiles(OrderRootType.CLASSES));
}
return value;
}
}, myEntries);
}
public boolean contains(VirtualFile file) {
return myEntries.contains(getFileRoot(file));
}
@Nullable
private VirtualFile getFileRoot(VirtualFile file) {
if (myIndex.isLibraryClassFile(file)) {
return myIndex.getClassRootForFile(file);
}
if (myIndex.isInContent(file)) {
return myIndex.getSourceRootForFile(file);
}
if (myIndex.isInLibraryClasses(file)) {
return myIndex.getClassRootForFile(file);
}
return null;
}
public int compare(VirtualFile file1, VirtualFile file2) {
final VirtualFile r1 = getFileRoot(file1);
final VirtualFile r2 = getFileRoot(file2);
for (VirtualFile root : myEntries) {
if (Comparing.equal(r1, root)) return 1;
if (Comparing.equal(r2, root)) return -1;
}
return 0;
}
@TestOnly
public List<VirtualFile> getRoots() {
return new ArrayList<VirtualFile>(myEntries);
}
public boolean isSearchInModuleContent(@NotNull Module aModule) {
return false;
}
public boolean isSearchInLibraries() {
return true;
}
}
| apache-2.0 |
cf0566/CarMarket | src/com/easemob/chatuidemo/widget/photoview/ScrollerProxy.java | 3945 | /**
* Copyright (C) 2013-2014 EaseMob Technologies. 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.
*/
/*******************************************************************************
* Copyright 2011, 2012 Chris Banes.
*
* 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.easemob.chatuidemo.widget.photoview;
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.widget.OverScroller;
import android.widget.Scroller;
public abstract class ScrollerProxy {
public static ScrollerProxy getScroller(Context context) {
if (VERSION.SDK_INT < VERSION_CODES.GINGERBREAD) {
return new PreGingerScroller(context);
} else {
return new GingerScroller(context);
}
}
public abstract boolean computeScrollOffset();
public abstract void fling(int startX, int startY, int velocityX, int velocityY, int minX, int maxX, int minY,
int maxY, int overX, int overY);
public abstract void forceFinished(boolean finished);
public abstract int getCurrX();
public abstract int getCurrY();
@TargetApi(9)
private static class GingerScroller extends ScrollerProxy {
private OverScroller mScroller;
public GingerScroller(Context context) {
mScroller = new OverScroller(context);
}
@Override
public boolean computeScrollOffset() {
return mScroller.computeScrollOffset();
}
@Override
public void fling(int startX, int startY, int velocityX, int velocityY, int minX, int maxX, int minY, int maxY,
int overX, int overY) {
mScroller.fling(startX, startY, velocityX, velocityY, minX, maxX, minY, maxY, overX, overY);
}
@Override
public void forceFinished(boolean finished) {
mScroller.forceFinished(finished);
}
@Override
public int getCurrX() {
return mScroller.getCurrX();
}
@Override
public int getCurrY() {
return mScroller.getCurrY();
}
}
private static class PreGingerScroller extends ScrollerProxy {
private Scroller mScroller;
public PreGingerScroller(Context context) {
mScroller = new Scroller(context);
}
@Override
public boolean computeScrollOffset() {
return mScroller.computeScrollOffset();
}
@Override
public void fling(int startX, int startY, int velocityX, int velocityY, int minX, int maxX, int minY, int maxY,
int overX, int overY) {
mScroller.fling(startX, startY, velocityX, velocityY, minX, maxX, minY, maxY);
}
@Override
public void forceFinished(boolean finished) {
mScroller.forceFinished(finished);
}
@Override
public int getCurrX() {
return mScroller.getCurrX();
}
@Override
public int getCurrY() {
return mScroller.getCurrY();
}
}
}
| apache-2.0 |
implydata/druid | sql/src/main/java/org/apache/druid/sql/calcite/expression/builtin/LikeOperatorConversion.java | 3331 | /*
* 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.druid.sql.calcite.expression.builtin;
import org.apache.calcite.rex.RexCall;
import org.apache.calcite.rex.RexLiteral;
import org.apache.calcite.rex.RexNode;
import org.apache.calcite.sql.SqlOperator;
import org.apache.calcite.sql.fun.SqlStdOperatorTable;
import org.apache.druid.query.filter.DimFilter;
import org.apache.druid.query.filter.LikeDimFilter;
import org.apache.druid.segment.VirtualColumn;
import org.apache.druid.segment.column.RowSignature;
import org.apache.druid.sql.calcite.expression.DirectOperatorConversion;
import org.apache.druid.sql.calcite.expression.DruidExpression;
import org.apache.druid.sql.calcite.expression.Expressions;
import org.apache.druid.sql.calcite.planner.PlannerContext;
import org.apache.druid.sql.calcite.rel.VirtualColumnRegistry;
import javax.annotation.Nullable;
import java.util.List;
public class LikeOperatorConversion extends DirectOperatorConversion
{
private static final SqlOperator SQL_FUNCTION = SqlStdOperatorTable.LIKE;
public LikeOperatorConversion()
{
super(SQL_FUNCTION, "like");
}
@Override
public SqlOperator calciteOperator()
{
return SQL_FUNCTION;
}
@Nullable
@Override
public DimFilter toDruidFilter(
PlannerContext plannerContext,
RowSignature rowSignature,
@Nullable VirtualColumnRegistry virtualColumnRegistry,
RexNode rexNode
)
{
final List<RexNode> operands = ((RexCall) rexNode).getOperands();
final DruidExpression druidExpression = Expressions.toDruidExpression(
plannerContext,
rowSignature,
operands.get(0)
);
if (druidExpression == null) {
return null;
}
if (druidExpression.isSimpleExtraction()) {
return new LikeDimFilter(
druidExpression.getSimpleExtraction().getColumn(),
RexLiteral.stringValue(operands.get(1)),
operands.size() > 2 ? RexLiteral.stringValue(operands.get(2)) : null,
druidExpression.getSimpleExtraction().getExtractionFn()
);
} else if (virtualColumnRegistry != null) {
VirtualColumn v = virtualColumnRegistry.getOrCreateVirtualColumnForExpression(
plannerContext,
druidExpression,
operands.get(0).getType().getSqlTypeName()
);
return new LikeDimFilter(
v.getOutputName(),
RexLiteral.stringValue(operands.get(1)),
operands.size() > 2 ? RexLiteral.stringValue(operands.get(2)) : null,
null
);
} else {
return null;
}
}
}
| apache-2.0 |
DavesMan/guava | guava-testlib/src/com/google/common/collect/testing/ConcurrentNavigableMapTestSuiteBuilder.java | 1706 | /*
* Copyright (C) 2015 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect.testing;
import com.google.common.annotations.GwtIncompatible;
import java.util.List;
/**
* Creates, based on your criteria, a JUnit test suite that exhaustively tests
* a ConcurrentNavigableMap implementation.
*
* @author Louis Wasserman
*/
@GwtIncompatible
public class ConcurrentNavigableMapTestSuiteBuilder<K, V>
extends NavigableMapTestSuiteBuilder<K, V> {
public static <K, V> ConcurrentNavigableMapTestSuiteBuilder<K, V> using(
TestSortedMapGenerator<K, V> generator) {
ConcurrentNavigableMapTestSuiteBuilder<K, V> result =
new ConcurrentNavigableMapTestSuiteBuilder<K, V>();
result.usingGenerator(generator);
return result;
}
@Override
protected List<Class<? extends AbstractTester>> getTesters() {
List<Class<? extends AbstractTester>> testers = Helpers.copyToList(super.getTesters());
testers.addAll(ConcurrentMapTestSuiteBuilder.TESTERS);
return testers;
}
@Override
NavigableMapTestSuiteBuilder<K, V> subSuiteUsing(TestSortedMapGenerator<K, V> generator) {
return using(generator);
}
}
| apache-2.0 |
ankitsinghal/phoenix | phoenix-pherf/src/main/java/org/apache/phoenix/pherf/rules/SequentialIntegerDataGenerator.java | 2431 | /*
* 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.phoenix.pherf.rules;
import org.apache.phoenix.thirdparty.com.google.common.base.Preconditions;
import org.apache.phoenix.pherf.configuration.Column;
import org.apache.phoenix.pherf.configuration.DataSequence;
import org.apache.phoenix.pherf.configuration.DataTypeMapping;
import java.util.concurrent.atomic.AtomicLong;
public class SequentialIntegerDataGenerator implements RuleBasedDataGenerator {
private final Column columnRule;
private final AtomicLong counter;
private final long minValue;
private final long maxValue;
public SequentialIntegerDataGenerator(Column columnRule) {
Preconditions.checkArgument(columnRule.getDataSequence() == DataSequence.SEQUENTIAL);
Preconditions.checkArgument(isIntegerType(columnRule.getType()));
this.columnRule = columnRule;
minValue = columnRule.getMinValue();
maxValue = columnRule.getMaxValue();
counter = new AtomicLong(0);
}
/**
* Note that this method rolls over for attempts to get larger than maxValue
* @return new DataValue
*/
@Override
public DataValue getDataValue() {
return new DataValue(columnRule.getType(), String.valueOf((counter.getAndIncrement() % (maxValue - minValue + 1)) + minValue));
}
// Probably could go into a util class in the future
boolean isIntegerType(DataTypeMapping mapping) {
switch (mapping) {
case BIGINT:
case INTEGER:
case TINYINT:
case UNSIGNED_LONG:
return true;
default:
return false;
}
}
}
| apache-2.0 |
Dhandapani/gluster-ovirt | backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/ConfigCommandBase.java | 288 | package org.ovirt.engine.core.bll;
import org.ovirt.engine.core.common.action.VdcActionParametersBase;
public abstract class ConfigCommandBase<T extends VdcActionParametersBase> extends CommandBase<T> {
protected ConfigCommandBase(T parameters) {
super(parameters);
}
}
| apache-2.0 |
christophd/camel | components/camel-infinispan/camel-infinispan/src/test/java/org/apache/camel/component/infinispan/remote/InfinispanRemoteConfigurationIT.java | 4826 | /*
* 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.infinispan.remote;
import org.apache.camel.test.infra.infinispan.services.InfinispanService;
import org.apache.camel.test.infra.infinispan.services.InfinispanServiceFactory;
import org.infinispan.client.hotrod.RemoteCache;
import org.infinispan.commons.api.BasicCache;
import org.infinispan.configuration.cache.CacheMode;
import org.jgroups.util.UUID;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.testcontainers.shaded.org.apache.commons.lang.SystemUtils;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class InfinispanRemoteConfigurationIT {
@RegisterExtension
static InfinispanService service = InfinispanServiceFactory.createService();
@Test
public void remoteCacheWithoutProperties() throws Exception {
InfinispanRemoteConfiguration configuration = new InfinispanRemoteConfiguration();
configuration.setHosts(service.host() + ":" + service.port());
configuration.setSecure(true);
configuration.setUsername(service.username());
configuration.setPassword(service.password());
configuration.setSecurityServerName("infinispan");
configuration.setSaslMechanism("DIGEST-MD5");
configuration.setSecurityRealm("default");
if (SystemUtils.IS_OS_MAC) {
configuration.addConfigurationProperty(
"infinispan.client.hotrod.client_intelligence", "BASIC");
}
try (InfinispanRemoteManager manager = new InfinispanRemoteManager(configuration)) {
manager.start();
manager.getCacheContainer().administration()
.getOrCreateCache(
"misc_cache",
new org.infinispan.configuration.cache.ConfigurationBuilder()
.clustering()
.cacheMode(CacheMode.DIST_SYNC).build());
BasicCache<Object, Object> cache = manager.getCache("misc_cache");
assertNotNull(cache);
assertTrue(cache instanceof RemoteCache);
String key = UUID.randomUUID().toString();
assertNull(cache.put(key, "val1"));
assertNull(cache.put(key, "val2"));
}
}
@Test
public void remoteCacheWithProperties() throws Exception {
InfinispanRemoteConfiguration configuration = new InfinispanRemoteConfiguration();
configuration.setHosts(service.host() + ":" + service.port());
configuration.setSecure(true);
configuration.setUsername(service.username());
configuration.setPassword(service.password());
configuration.setSecurityServerName("infinispan");
configuration.setSaslMechanism("DIGEST-MD5");
configuration.setSecurityRealm("default");
if (SystemUtils.IS_OS_MAC) {
configuration.setConfigurationUri("infinispan/client-mac.properties");
} else {
configuration.setConfigurationUri("infinispan/client.properties");
}
try (InfinispanRemoteManager manager = new InfinispanRemoteManager(configuration)) {
manager.start();
manager.getCacheContainer().administration()
.getOrCreateCache(
"misc_cache",
new org.infinispan.configuration.cache.ConfigurationBuilder()
.clustering()
.cacheMode(CacheMode.DIST_SYNC).build());
BasicCache<Object, Object> cache = manager.getCache("misc_cache");
assertNotNull(cache);
assertTrue(cache instanceof RemoteCache);
String key = UUID.randomUUID().toString();
assertNull(cache.put(key, "val1"));
assertNotNull(cache.put(key, "val2"));
}
}
}
| apache-2.0 |
damienmg/bazel | src/test/java/com/google/devtools/build/lib/profiler/ProfilerTest.java | 19092 | // Copyright 2015 The Bazel Authors. 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.build.lib.profiler;
import static com.google.common.truth.Truth.assertThat;
import static java.nio.charset.StandardCharsets.ISO_8859_1;
import static org.junit.Assert.fail;
import com.google.devtools.build.lib.clock.BlazeClock;
import com.google.devtools.build.lib.clock.Clock;
import com.google.devtools.build.lib.profiler.Profiler.ProfiledTaskKinds;
import com.google.devtools.build.lib.profiler.analysis.ProfileInfo;
import com.google.devtools.build.lib.testutil.FoundationTestCase;
import com.google.devtools.build.lib.testutil.ManualClock;
import com.google.devtools.build.lib.testutil.Suite;
import com.google.devtools.build.lib.testutil.TestSpec;
import com.google.devtools.build.lib.vfs.FileSystemUtils;
import com.google.devtools.build.lib.vfs.Path;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.zip.Deflater;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* Unit tests for the profiler.
*/
@TestSpec(size = Suite.MEDIUM_TESTS) // testConcurrentProfiling takes ~700ms, testProfiler 100ms.
@RunWith(JUnit4.class)
public class ProfilerTest extends FoundationTestCase {
private Path cacheDir;
private Profiler profiler = Profiler.instance();
private ManualClock clock;
@Before
public final void createCacheDirectory() throws Exception {
cacheDir = scratch.dir("/tmp");
}
@Before
public final void setManualClock() {
clock = new ManualClock();
BlazeClock.setClock(clock);
}
@Test
public void testProfilerActivation() throws Exception {
Path cacheFile = cacheDir.getRelative("profile1.dat");
assertThat(profiler.isActive()).isFalse();
profiler.start(ProfiledTaskKinds.ALL, cacheFile.getOutputStream(), "basic test", false,
BlazeClock.instance(), BlazeClock.instance().nanoTime());
assertThat(profiler.isActive()).isTrue();
profiler.stop();
assertThat(profiler.isActive()).isFalse();
}
@Test
public void testTaskDetails() throws Exception {
Path cacheFile = cacheDir.getRelative("profile1.dat");
profiler.start(ProfiledTaskKinds.ALL, cacheFile.getOutputStream(), "basic test", false,
BlazeClock.instance(), BlazeClock.instance().nanoTime());
profiler.startTask(ProfilerTask.ACTION, "action task");
profiler.logEvent(ProfilerTask.TEST, "event");
profiler.completeTask(ProfilerTask.ACTION);
profiler.stop();
ProfileInfo info = ProfileInfo.loadProfile(cacheFile);
info.calculateStats();
ProfileInfo.Task task = info.allTasksById.get(0);
assertThat(task.id).isEqualTo(1);
assertThat(task.type).isEqualTo(ProfilerTask.ACTION);
assertThat(task.getDescription()).isEqualTo("action task");
task = info.allTasksById.get(1);
assertThat(task.id).isEqualTo(2);
assertThat(task.type).isEqualTo(ProfilerTask.TEST);
assertThat(task.getDescription()).isEqualTo("event");
}
@Test
public void testProfiler() throws Exception {
Path cacheFile = cacheDir.getRelative("profile1.dat");
profiler.start(ProfiledTaskKinds.ALL, cacheFile.getOutputStream(), "basic test", false,
BlazeClock.instance(), BlazeClock.instance().nanoTime());
profiler.logSimpleTask(BlazeClock.instance().nanoTime(),
ProfilerTask.PHASE, "profiler start");
profiler.startTask(ProfilerTask.ACTION, "complex task");
profiler.logEvent(ProfilerTask.PHASE, "event1");
profiler.startTask(ProfilerTask.ACTION_CHECK, "complex subtask");
// next task takes less than 10 ms and should be only aggregated
profiler.logSimpleTask(BlazeClock.instance().nanoTime(),
ProfilerTask.VFS_STAT, "stat1");
long startTime = BlazeClock.instance().nanoTime();
clock.advanceMillis(20);
// this one will take at least 20 ms and should be present
profiler.logSimpleTask(startTime, ProfilerTask.VFS_STAT, "stat2");
profiler.completeTask(ProfilerTask.ACTION_CHECK);
profiler.completeTask(ProfilerTask.ACTION);
profiler.stop();
// all other calls to profiler should be ignored
profiler.logEvent(ProfilerTask.PHASE, "should be ignored");
// normally this would cause an exception but it is ignored since profiler
// is disabled
profiler.completeTask(ProfilerTask.ACTION_EXECUTE);
ProfileInfo info = ProfileInfo.loadProfile(cacheFile);
info.calculateStats();
assertThat(info.allTasksById).hasSize(6); // only 5 tasks + finalization should be recorded
ProfileInfo.Task task = info.allTasksById.get(0);
assertThat(task.stats.isEmpty()).isTrue();
task = info.allTasksById.get(1);
int count = 0;
for (ProfileInfo.AggregateAttr attr : task.getStatAttrArray()) {
if (attr != null) {
count++;
}
}
assertThat(count).isEqualTo(2); // only children are GENERIC and ACTION_CHECK
assertThat(ProfilerTask.TASK_COUNT).isEqualTo(task.aggregatedStats.toArray().length);
assertThat(task.aggregatedStats.getAttr(ProfilerTask.VFS_STAT).count).isEqualTo(2);
task = info.allTasksById.get(2);
assertThat(task.durationNanos).isEqualTo(0);
task = info.allTasksById.get(3);
assertThat(task.stats.getAttr(ProfilerTask.VFS_STAT).count).isEqualTo(2);
assertThat(task.subtasks).hasLength(1);
assertThat(task.subtasks[0].getDescription()).isEqualTo("stat2");
// assert that startTime grows with id
long time = -1;
for (ProfileInfo.Task t : info.allTasksById) {
assertThat(t.startTime).isAtLeast(time);
time = t.startTime;
}
}
@Test
public void testProfilerRecordingAllEvents() throws Exception {
Path cacheFile = cacheDir.getRelative("profile1.dat");
profiler.start(ProfiledTaskKinds.ALL, cacheFile.getOutputStream(), "basic test", true,
BlazeClock.instance(), BlazeClock.instance().nanoTime());
profiler.startTask(ProfilerTask.ACTION, "action task");
// Next task takes less than 10 ms but should be recorded anyway.
clock.advanceMillis(1);
profiler.logSimpleTask(BlazeClock.instance().nanoTime(), ProfilerTask.VFS_STAT, "stat1");
profiler.completeTask(ProfilerTask.ACTION);
profiler.stop();
ProfileInfo info = ProfileInfo.loadProfile(cacheFile);
info.calculateStats();
assertThat(info.allTasksById).hasSize(3); // 2 tasks + finalization should be recorded
ProfileInfo.Task task = info.allTasksById.get(1);
assertThat(task.type).isEqualTo(ProfilerTask.VFS_STAT);
// Check that task would have been dropped if profiler was not configured to record everything.
assertThat(task.durationNanos).isLessThan(ProfilerTask.VFS_STAT.minDuration);
}
@Test
public void testProfilerRecordingOnlySlowestEvents() throws Exception {
Path profileData = cacheDir.getRelative("foo");
profiler.start(ProfiledTaskKinds.SLOWEST, profileData.getOutputStream(), "test", true,
BlazeClock.instance(), BlazeClock.instance().nanoTime());
profiler.logSimpleTask(10000, 20000, ProfilerTask.VFS_STAT, "stat");
profiler.logSimpleTask(20000, 30000, ProfilerTask.REMOTE_EXECUTION, "remote execution");
assertThat(profiler.isProfiling(ProfilerTask.VFS_STAT)).isTrue();
assertThat(profiler.isProfiling(ProfilerTask.REMOTE_EXECUTION)).isFalse();
profiler.stop();
ProfileInfo info = ProfileInfo.loadProfile(profileData);
info.calculateStats();
assertThat(info.allTasksById).hasSize(1); // only VFS_STAT task should be recorded
ProfileInfo.Task task = info.allTasksById.get(0);
assertThat(task.type).isEqualTo(ProfilerTask.VFS_STAT);
}
@Test
public void testProfilerRecordsNothing() throws Exception {
Path profileData = cacheDir.getRelative("foo");
profiler.start(ProfiledTaskKinds.NONE, profileData.getOutputStream(), "test", true,
BlazeClock.instance(), BlazeClock.instance().nanoTime());
profiler.logSimpleTask(10000, 20000, ProfilerTask.VFS_STAT, "stat");
assertThat(ProfilerTask.VFS_STAT.collectsSlowestInstances()).isTrue();
assertThat(profiler.isProfiling(ProfilerTask.VFS_STAT)).isFalse();
profiler.stop();
ProfileInfo info = ProfileInfo.loadProfile(profileData);
info.calculateStats();
assertThat(info.allTasksById).isEmpty();
}
@Test
public void testInconsistentCompleteTask() throws Exception {
Path cacheFile = cacheDir.getRelative("profile2.dat");
profiler.start(ProfiledTaskKinds.ALL, cacheFile.getOutputStream(),
"task stack inconsistency test", false,
BlazeClock.instance(), BlazeClock.instance().nanoTime());
profiler.startTask(ProfilerTask.PHASE, "some task");
try {
profiler.completeTask(ProfilerTask.ACTION);
fail();
} catch (IllegalStateException e) {
// this is expected
}
profiler.stop();
}
@Test
public void testConcurrentProfiling() throws Exception {
Path cacheFile = cacheDir.getRelative("profile3.dat");
profiler.start(ProfiledTaskKinds.ALL, cacheFile.getOutputStream(), "concurrent test", false,
BlazeClock.instance(), BlazeClock.instance().nanoTime());
long id = Thread.currentThread().getId();
Thread thread1 = new Thread() {
@Override public void run() {
for (int i = 0; i < 10000; i++) {
Profiler.instance().logEvent(ProfilerTask.TEST, "thread1");
}
}
};
long id1 = thread1.getId();
Thread thread2 = new Thread() {
@Override public void run() {
for (int i = 0; i < 10000; i++) {
Profiler.instance().logEvent(ProfilerTask.TEST, "thread2");
}
}
};
long id2 = thread2.getId();
profiler.startTask(ProfilerTask.PHASE, "main task");
profiler.logEvent(ProfilerTask.TEST, "starting threads");
thread1.start();
thread2.start();
thread2.join();
thread1.join();
profiler.logEvent(ProfilerTask.TEST, "joined");
profiler.completeTask(ProfilerTask.PHASE);
profiler.stop();
ProfileInfo info = ProfileInfo.loadProfile(cacheFile);
info.calculateStats();
info.analyzeRelationships();
assertThat(info.allTasksById).hasSize(4 + 10000 + 10000); // total number of tasks
assertThat(info.tasksByThread).hasSize(3); // total number of threads
// while main thread had 3 tasks, 2 of them were nested, so tasksByThread
// would contain only one "main task" task
assertThat(info.tasksByThread.get(id)).hasLength(2);
ProfileInfo.Task mainTask = info.tasksByThread.get(id)[0];
assertThat(mainTask.getDescription()).isEqualTo("main task");
assertThat(mainTask.subtasks).hasLength(2);
// other threads had 10000 independent recorded tasks each
assertThat(info.tasksByThread.get(id1)).hasLength(10000);
assertThat(info.tasksByThread.get(id2)).hasLength(10000);
int startId = mainTask.subtasks[0].id; // id of "starting threads"
int endId = mainTask.subtasks[1].id; // id of "joining"
assertThat(startId).isLessThan(info.tasksByThread.get(id1)[0].id);
assertThat(startId).isLessThan(info.tasksByThread.get(id2)[0].id);
assertThat(endId).isGreaterThan(info.tasksByThread.get(id1)[9999].id);
assertThat(endId).isGreaterThan(info.tasksByThread.get(id2)[9999].id);
}
@Test
public void testPhaseTasks() throws Exception {
Path cacheFile = cacheDir.getRelative("profile4.dat");
profiler.start(ProfiledTaskKinds.ALL, cacheFile.getOutputStream(), "phase test", false,
BlazeClock.instance(), BlazeClock.instance().nanoTime());
Thread thread1 = new Thread() {
@Override public void run() {
for (int i = 0; i < 100; i++) {
Profiler.instance().logEvent(ProfilerTask.TEST, "thread1");
}
}
};
profiler.markPhase(ProfilePhase.INIT); // Empty phase.
profiler.markPhase(ProfilePhase.LOAD);
thread1.start();
thread1.join();
clock.advanceMillis(1);
profiler.markPhase(ProfilePhase.ANALYZE);
Thread thread2 = new Thread() {
@Override public void run() {
profiler.startTask(ProfilerTask.TEST, "complex task");
for (int i = 0; i < 100; i++) {
Profiler.instance().logEvent(ProfilerTask.TEST, "thread2a");
}
profiler.completeTask(ProfilerTask.TEST);
profiler.markPhase(ProfilePhase.EXECUTE);
for (int i = 0; i < 100; i++) {
Profiler.instance().logEvent(ProfilerTask.TEST, "thread2b");
}
}
};
thread2.start();
thread2.join();
profiler.logEvent(ProfilerTask.TEST, "last task");
clock.advanceMillis(1);
profiler.stop();
ProfileInfo info = ProfileInfo.loadProfile(cacheFile);
info.calculateStats();
info.analyzeRelationships();
// number of tasks: INIT(1) + LOAD(1) + Thread1.TEST(100) + ANALYZE(1)
// + Thread2a.TEST(100) + TEST(1) + EXECUTE(1) + Thread2b.TEST(100) + TEST(1) + INFO(1)
assertThat(info.allTasksById).hasSize(1 + 1 + 100 + 1 + 100 + 1 + 1 + 100 + 1 + 1);
assertThat(info.tasksByThread).hasSize(3); // total number of threads
// Phase0 contains only itself
ProfileInfo.Task p0 = info.getPhaseTask(ProfilePhase.INIT);
assertThat(info.getTasksForPhase(p0)).hasSize(1);
// Phase1 contains itself and 100 TEST "thread1" tasks
ProfileInfo.Task p1 = info.getPhaseTask(ProfilePhase.LOAD);
assertThat(info.getTasksForPhase(p1)).hasSize(101);
// Phase2 contains itself and 1 "complex task"
ProfileInfo.Task p2 = info.getPhaseTask(ProfilePhase.ANALYZE);
assertThat(info.getTasksForPhase(p2)).hasSize(2);
// Phase3 contains itself, 100 TEST "thread2b" tasks and "last task"
ProfileInfo.Task p3 = info.getPhaseTask(ProfilePhase.EXECUTE);
assertThat(info.getTasksForPhase(p3)).hasSize(103);
}
@Test
public void testCorruptedFile() throws Exception {
Path cacheFile = cacheDir.getRelative("profile5.dat");
profiler.start(ProfiledTaskKinds.ALL, cacheFile.getOutputStream(), "phase test", false,
BlazeClock.instance(), BlazeClock.instance().nanoTime());
for (int i = 0; i < 100; i++) {
profiler.startTask(ProfilerTask.TEST, "outer task " + i);
clock.advanceMillis(1);
profiler.logEvent(ProfilerTask.TEST, "inner task " + i);
profiler.completeTask(ProfilerTask.TEST);
}
profiler.stop();
ProfileInfo info = ProfileInfo.loadProfile(cacheFile);
info.calculateStats();
assertThat(info.isCorruptedOrIncomplete()).isFalse();
Path corruptedFile = cacheDir.getRelative("profile5bad.dat");
FileSystemUtils.writeContent(
corruptedFile, Arrays.copyOf(FileSystemUtils.readContent(cacheFile), 2000));
info = ProfileInfo.loadProfile(corruptedFile);
info.calculateStats();
assertThat(info.isCorruptedOrIncomplete()).isTrue();
// Since root tasks will appear after nested tasks in the profile file and
// we have exactly one nested task for each root task, the following will always
// be true for our corrupted file:
// 0 <= number_of_all_tasks - 2*number_of_root_tasks <= 1
assertThat(info.allTasksById.size() / 2).isEqualTo(info.rootTasksById.size());
}
@Test
public void testUnsupportedProfilerRecord() throws Exception {
Path dataFile = cacheDir.getRelative("profile5.dat");
profiler.start(ProfiledTaskKinds.ALL, dataFile.getOutputStream(), "phase test", false,
BlazeClock.instance(), BlazeClock.instance().nanoTime());
profiler.startTask(ProfilerTask.TEST, "outer task");
profiler.logEvent(ProfilerTask.EXCEPTION, "inner task");
profiler.completeTask(ProfilerTask.TEST);
profiler.startTask(ProfilerTask.SCANNER, "outer task 2");
profiler.logSimpleTask(Profiler.nanoTimeMaybe(), ProfilerTask.TEST, "inner task 2");
profiler.completeTask(ProfilerTask.SCANNER);
profiler.stop();
// Validate our test profile.
ProfileInfo info = ProfileInfo.loadProfile(dataFile);
info.calculateStats();
assertThat(info.isCorruptedOrIncomplete()).isFalse();
assertThat(info.getStatsForType(ProfilerTask.TEST, info.rootTasksById).count).isEqualTo(2);
assertThat(info.getStatsForType(ProfilerTask.UNKNOWN, info.rootTasksById).count).isEqualTo(0);
// Now replace "TEST" type with something unsupported - e.g. "XXXX".
InputStream in = new InflaterInputStream(dataFile.getInputStream(), new Inflater(false), 65536);
byte[] buffer = new byte[60000];
int len = in.read(buffer);
in.close();
assertThat(len).isLessThan(buffer.length); // Validate that file was completely decoded.
String content = new String(buffer, ISO_8859_1);
int infoIndex = content.indexOf("TEST");
assertThat(infoIndex).isGreaterThan(0);
content = content.substring(0, infoIndex) + "XXXX" + content.substring(infoIndex + 4);
OutputStream out = new DeflaterOutputStream(dataFile.getOutputStream(),
new Deflater(Deflater.BEST_SPEED, false), 65536);
out.write(content.getBytes(ISO_8859_1));
out.close();
// Validate that XXXX records were classified as UNKNOWN.
info = ProfileInfo.loadProfile(dataFile);
info.calculateStats();
assertThat(info.isCorruptedOrIncomplete()).isFalse();
assertThat(info.getStatsForType(ProfilerTask.TEST, info.rootTasksById).count).isEqualTo(0);
assertThat(info.getStatsForType(ProfilerTask.SCANNER, info.rootTasksById).count).isEqualTo(1);
assertThat(info.getStatsForType(ProfilerTask.EXCEPTION, info.rootTasksById).count).isEqualTo(1);
assertThat(info.getStatsForType(ProfilerTask.UNKNOWN, info.rootTasksById).count).isEqualTo(2);
}
@Test
public void testResilenceToNonDecreasingNanoTimes() throws Exception {
final long initialNanoTime = BlazeClock.instance().nanoTime();
final AtomicInteger numNanoTimeCalls = new AtomicInteger(0);
Clock badClock = new Clock() {
@Override
public long currentTimeMillis() {
return BlazeClock.instance().currentTimeMillis();
}
@Override
public long nanoTime() {
return initialNanoTime - numNanoTimeCalls.addAndGet(1);
}
};
Path cacheFile = cacheDir.getRelative("profile1.dat");
profiler.start(ProfiledTaskKinds.ALL, cacheFile.getOutputStream(),
"testResilenceToNonDecreasingNanoTimes", false, badClock, initialNanoTime);
profiler.logSimpleTask(badClock.nanoTime(), ProfilerTask.TEST, "some task");
profiler.stop();
}
}
| apache-2.0 |
nknize/elasticsearch | x-pack/plugin/runtime-fields/src/main/java/org/elasticsearch/xpack/runtimefields/query/StringScriptFieldRangeQuery.java | 3629 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
package org.elasticsearch.xpack.runtimefields.query;
import org.apache.lucene.search.QueryVisitor;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.automaton.Automata;
import org.apache.lucene.util.automaton.ByteRunAutomaton;
import org.elasticsearch.script.Script;
import org.elasticsearch.xpack.runtimefields.mapper.StringFieldScript;
import java.util.List;
import java.util.Objects;
public class StringScriptFieldRangeQuery extends AbstractStringScriptFieldQuery {
private final String lowerValue;
private final String upperValue;
private final boolean includeLower;
private final boolean includeUpper;
public StringScriptFieldRangeQuery(
Script script,
StringFieldScript.LeafFactory leafFactory,
String fieldName,
String lowerValue,
String upperValue,
boolean includeLower,
boolean includeUpper
) {
super(script, leafFactory, fieldName);
this.lowerValue = Objects.requireNonNull(lowerValue);
this.upperValue = Objects.requireNonNull(upperValue);
this.includeLower = includeLower;
this.includeUpper = includeUpper;
assert lowerValue.compareTo(upperValue) <= 0;
}
@Override
protected boolean matches(List<String> values) {
for (String value : values) {
int lct = lowerValue.compareTo(value);
boolean lowerOk = includeLower ? lct <= 0 : lct < 0;
if (lowerOk) {
int uct = upperValue.compareTo(value);
boolean upperOk = includeUpper ? uct >= 0 : uct > 0;
if (upperOk) {
return true;
}
}
}
return false;
}
@Override
public void visit(QueryVisitor visitor) {
if (visitor.acceptField(fieldName())) {
visitor.consumeTermsMatching(
this,
fieldName(),
() -> new ByteRunAutomaton(
Automata.makeBinaryInterval(new BytesRef(lowerValue), includeLower, new BytesRef(upperValue), includeUpper)
)
);
}
}
@Override
public final String toString(String field) {
StringBuilder b = new StringBuilder();
if (false == fieldName().contentEquals(field)) {
b.append(fieldName()).append(':');
}
b.append(includeLower ? '[' : '{');
b.append(lowerValue).append(" TO ").append(upperValue);
b.append(includeUpper ? ']' : '}');
return b.toString();
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), lowerValue, upperValue, includeLower, includeUpper);
}
@Override
public boolean equals(Object obj) {
if (false == super.equals(obj)) {
return false;
}
StringScriptFieldRangeQuery other = (StringScriptFieldRangeQuery) obj;
return lowerValue.equals(other.lowerValue)
&& upperValue.equals(other.upperValue)
&& includeLower == other.includeLower
&& includeUpper == other.includeUpper;
}
String lowerValue() {
return lowerValue;
}
String upperValue() {
return upperValue;
}
boolean includeLower() {
return includeLower;
}
boolean includeUpper() {
return includeUpper;
}
}
| apache-2.0 |
xasx/camunda-bpm-platform | distro/wildfly8/subsystem/src/main/java/org/camunda/bpm/container/impl/jboss/deployment/marker/ProcessApplicationAttachments.java | 5340 | /*
* Copyright © 2013-2018 camunda services GmbH and various authors (info@camunda.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 org.camunda.bpm.container.impl.jboss.deployment.marker;
import java.util.List;
import org.camunda.bpm.application.AbstractProcessApplication;
import org.camunda.bpm.application.impl.metadata.spi.ProcessesXml;
import org.camunda.bpm.container.impl.jboss.util.ProcessesXmlWrapper;
import org.jboss.as.ee.component.ComponentDescription;
import org.jboss.as.server.deployment.AttachmentKey;
import org.jboss.as.server.deployment.AttachmentList;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.jandex.AnnotationInstance;
/**
*
* @author Daniel Meyer
*
*/
public class ProcessApplicationAttachments {
private static final AttachmentKey<Boolean> MARKER = AttachmentKey.create(Boolean.class);
private static final AttachmentKey<Boolean> PART_OF_MARKER = AttachmentKey.create(Boolean.class);
private static final AttachmentKey<AttachmentList<ProcessesXmlWrapper>> PROCESSES_XML_LIST = AttachmentKey.createList(ProcessesXmlWrapper.class);
private static final AttachmentKey<ComponentDescription> PA_COMPONENT = AttachmentKey.create(ComponentDescription.class);
private static final AttachmentKey<AnnotationInstance> POST_DEPLOY_METHOD = AttachmentKey.create(AnnotationInstance.class);
private static final AttachmentKey<AnnotationInstance> PRE_UNDEPLOY_METHOD = AttachmentKey.create(AnnotationInstance.class);
/**
* Attach the parsed ProcessesXml file to a deployment unit.
*
*/
public static void addProcessesXml(DeploymentUnit unit, ProcessesXmlWrapper processesXmlWrapper) {
unit.addToAttachmentList(PROCESSES_XML_LIST, processesXmlWrapper);
}
/**
* Returns the attached {@link ProcessesXml} marker or null;
*
*/
public static List<ProcessesXmlWrapper> getProcessesXmls(DeploymentUnit deploymentUnit) {
return deploymentUnit.getAttachmentList(PROCESSES_XML_LIST);
}
/**
* marks a a {@link DeploymentUnit} as a process application
*/
public static void mark(DeploymentUnit unit) {
unit.putAttachment(MARKER, Boolean.TRUE);
}
/**
* marks a a {@link DeploymentUnit} as part of a process application
*/
public static void markPartOfProcessApplication(DeploymentUnit unit) {
if(unit.getParent() != null && unit.getParent() != unit) {
unit.getParent().putAttachment(PART_OF_MARKER, Boolean.TRUE);
}
}
/**
* return true if the deployment unit is either itself a process
* application or part of a process application.
*/
public static boolean isPartOfProcessApplication(DeploymentUnit unit) {
if(isProcessApplication(unit)) {
return true;
}
if(unit.getParent() != null && unit.getParent() != unit) {
return unit.getParent().hasAttachment(PART_OF_MARKER);
}
return false;
}
/**
* Returns true if the {@link DeploymentUnit} itself is a process application (carries a processes.xml)
*
*/
public static boolean isProcessApplication(DeploymentUnit deploymentUnit) {
return deploymentUnit.hasAttachment(MARKER);
}
/**
* Returns the {@link ComponentDescription} for the {@link AbstractProcessApplication} component
*/
public static ComponentDescription getProcessApplicationComponent(DeploymentUnit deploymentUnit) {
return deploymentUnit.getAttachment(PA_COMPONENT);
}
/**
* Attach the {@link ComponentDescription} for the {@link AbstractProcessApplication} component
*/
public static void attachProcessApplicationComponent(DeploymentUnit deploymentUnit, ComponentDescription componentDescription){
deploymentUnit.putAttachment(PA_COMPONENT, componentDescription);
}
/**
* Attach the {@link AnnotationInstance}s for the PostDeploy methods
*/
public static void attachPostDeployDescription(DeploymentUnit deploymentUnit, AnnotationInstance annotation){
deploymentUnit.putAttachment(POST_DEPLOY_METHOD, annotation);
}
/**
* Attach the {@link AnnotationInstance}s for the PreUndeploy methods
*/
public static void attachPreUndeployDescription(DeploymentUnit deploymentUnit, AnnotationInstance annotation){
deploymentUnit.putAttachment(PRE_UNDEPLOY_METHOD, annotation);
}
/**
* @return the description of the PostDeploy method
*/
public static AnnotationInstance getPostDeployDescription(DeploymentUnit deploymentUnit) {
return deploymentUnit.getAttachment(POST_DEPLOY_METHOD);
}
/**
* @return the description of the PreUndeploy method
*/
public static AnnotationInstance getPreUndeployDescription(DeploymentUnit deploymentUnit) {
return deploymentUnit.getAttachment(PRE_UNDEPLOY_METHOD);
}
private ProcessApplicationAttachments() {
}
}
| apache-2.0 |
steveturner/datadistrib4j | srcJava/org/omg/dds/type/typeobject/UnionType.java | 1765 | /* Copyright 2010, Object Management Group, Inc.
* Copyright 2010, PrismTech, Inc.
* Copyright 2010, Real-Time Innovations, 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 org.omg.dds.type.typeobject;
import java.util.List;
import org.omg.dds.type.Extensibility;
import org.omg.dds.type.ID;
import org.omg.dds.type.Nested;
@Extensibility(Extensibility.Kind.MUTABLE_EXTENSIBILITY)
@Nested
public interface UnionType extends Type
{
// -----------------------------------------------------------------------
// Properties
// -----------------------------------------------------------------------
@ID(MemberId.MEMBER_UNIONTYPE_MEMBER_ID)
public List<UnionMember> getMember();
// -----------------------------------------------------------------------
// Types
// -----------------------------------------------------------------------
public static final class MemberId
{
// --- Constants: ----------------------------------------------------
public static final int MEMBER_UNIONTYPE_MEMBER_ID = 100;
// --- Constructor: --------------------------------------------------
private MemberId() {
// empty
}
}
}
| apache-2.0 |
alien4cloud/alien4cloud | alien4cloud-tosca/src/main/java/alien4cloud/tosca/parser/postprocess/NodeTypePostProcessor.java | 784 | package alien4cloud.tosca.parser.postprocess;
import static alien4cloud.utils.AlienUtils.safe;
import javax.annotation.Resource;
import org.alien4cloud.tosca.model.types.NodeType;
import org.springframework.stereotype.Component;
/**
* Post process a node type.
*/
@Component
public class NodeTypePostProcessor implements IPostProcessor<NodeType> {
@Resource
private CapabilityDefinitionPostProcessor capabilityDefinitionPostProcessor;
@Resource
private RequirementDefinitionPostProcessor requirementDefinitionPostProcessor;
@Override
public void process(NodeType instance) {
safe(instance.getCapabilities()).forEach(capabilityDefinitionPostProcessor);
safe(instance.getRequirements()).forEach(requirementDefinitionPostProcessor);
}
} | apache-2.0 |
emeroad/pinpoint | profiler/src/main/java/com/navercorp/pinpoint/profiler/plugin/config/DefaultPluginLoadingConfig.java | 2527 | /*
* Copyright 2021 NAVER Corp.
*
* 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.navercorp.pinpoint.profiler.plugin.config;
import com.navercorp.pinpoint.bootstrap.config.DefaultProfilerConfig;
import com.navercorp.pinpoint.bootstrap.config.Value;
import com.navercorp.pinpoint.common.util.StringUtils;
import java.util.Collections;
import java.util.List;
public class DefaultPluginLoadingConfig implements PluginLoadingConfig {
// ArtifactIdUtils.ARTIFACT_SEPARATOR
private static final String ARTIFACT_SEPARATOR = ";";
private List<String> pluginLoadOrder = Collections.emptyList();
private List<String> disabledPlugins = Collections.emptyList();
private List<String> importPluginIds = Collections.emptyList();
public DefaultPluginLoadingConfig() {
}
@Override
public List<String> getPluginLoadOrder() {
return pluginLoadOrder;
}
@Value("${profiler.plugin.load.order}")
public void setPluginLoadOrder(String pluginLoadOrder) {
this.pluginLoadOrder = StringUtils.tokenizeToStringList(pluginLoadOrder, ",");
}
@Override
public List<String> getDisabledPlugins() {
return disabledPlugins;
}
@Value("${profiler.plugin.disable}")
public void setDisabledPlugins(String disabledPlugins) {
this.disabledPlugins = StringUtils.tokenizeToStringList(disabledPlugins, ",");
}
@Override
public List<String> getImportPluginIds() {
return importPluginIds;
}
@Value("${" + DefaultProfilerConfig.IMPORT_PLUGIN + "}")
public void setImportPluginIds(String importPluginIds) {
this.importPluginIds = StringUtils.tokenizeToStringList(importPluginIds, ARTIFACT_SEPARATOR);
}
@Override
public String toString() {
return "DefaultPluginLoadingConfig{" +
"pluginLoadOrder=" + pluginLoadOrder +
", disabledPlugins=" + disabledPlugins +
", importPluginIds=" + importPluginIds +
'}';
}
}
| apache-2.0 |
dubenju/javay | src/java/org/jaudiotagger/audio/mp4/Mp4AudioHeader.java | 1542 | package org.jaudiotagger.audio.mp4;
import org.jaudiotagger.audio.generic.GenericAudioHeader;
import org.jaudiotagger.audio.mp4.atom.Mp4EsdsBox;
/**
* Store some additional attributes not available for all audio types
*/
public class Mp4AudioHeader extends GenericAudioHeader {
/**
* The key for the kind field<br>
*
* @see #content
*/
public final static String FIELD_KIND = "KIND";
/**
* The key for the profile<br>
*
* @see #content
*/
public final static String FIELD_PROFILE = "PROFILE";
/**
* The key for the ftyp brand<br>
*
* @see #content
*/
public final static String FIELD_BRAND = "BRAND";
public void setKind(Mp4EsdsBox.Kind kind) {
content.put(FIELD_KIND, kind);
}
/**
* @return kind
*/
public Mp4EsdsBox.Kind getKind() {
return (Mp4EsdsBox.Kind) content.get(FIELD_KIND);
}
/**
* The key for the profile
*
* @param profile
*/
public void setProfile(Mp4EsdsBox.AudioProfile profile) {
content.put(FIELD_PROFILE, profile);
}
/**
* @return audio profile
*/
public Mp4EsdsBox.AudioProfile getProfile() {
return (Mp4EsdsBox.AudioProfile) content.get(FIELD_PROFILE);
}
/**
* @param brand
*/
public void setBrand(String brand) {
content.put(FIELD_BRAND, brand);
}
/**
* @return brand
*/
public String getBrand() {
return (String) content.get(FIELD_BRAND);
}
}
| apache-2.0 |
VibyJocke/gocd | common/src/com/thoughtworks/go/serverhealth/HealthStateScope.java | 9950 | /*
* Copyright 2016 ThoughtWorks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.thoughtworks.go.serverhealth;
import com.thoughtworks.go.config.CaseInsensitiveString;
import com.thoughtworks.go.config.CruiseConfig;
import com.thoughtworks.go.config.PipelineConfig;
import com.thoughtworks.go.config.remote.ConfigRepoConfig;
import com.thoughtworks.go.domain.materials.Material;
import com.thoughtworks.go.domain.materials.MaterialConfig;
import org.apache.commons.lang.StringUtils;
import java.util.HashSet;
import java.util.Set;
public class HealthStateScope implements Comparable<HealthStateScope> {
public static final HealthStateScope GLOBAL = new HealthStateScope(ScopeType.GLOBAL, "GLOBAL");
private final ScopeType type;
private final String scope;
private HealthStateScope(ScopeType type, String scope) {
this.type = type;
this.scope = scope;
}
public static HealthStateScope forGroup(String groupName) {
return new HealthStateScope(ScopeType.GROUP, groupName);
}
public static HealthStateScope forPipeline(String pipelineName) {
return new HealthStateScope(ScopeType.PIPELINE, pipelineName);
}
public static HealthStateScope forFanin(String pipelineName) {
return new HealthStateScope(ScopeType.FANIN, pipelineName);
}
public static HealthStateScope forStage(String pipelineName, String stageName) {
return new HealthStateScope(ScopeType.STAGE, pipelineName + "/" + stageName);
}
public static HealthStateScope forJob(String pipelineName, String stageName, String jobName) {
return new HealthStateScope(ScopeType.JOB, pipelineName + "/" + stageName + "/" + jobName);
}
public static HealthStateScope forMaterial(Material material) {
return new HealthStateScope(ScopeType.MATERIAL, material.getSqlCriteria().toString());
}
public static HealthStateScope forMaterialUpdate(Material material) {
return new HealthStateScope(ScopeType.MATERIAL_UPDATE, material.getFingerprint());
}
public static HealthStateScope forMaterialConfig(MaterialConfig materialConfig) {
return new HealthStateScope(ScopeType.MATERIAL, materialConfig.getSqlCriteria().toString());
}
public static HealthStateScope forMaterialConfigUpdate(MaterialConfig materialConfig) {
return new HealthStateScope(ScopeType.MATERIAL_UPDATE, materialConfig.getFingerprint());
}
public static HealthStateScope forConfigRepo(String operation) {
return new HealthStateScope(ScopeType.CONFIG_REPO, operation);
}
public static HealthStateScope forPartialConfigRepo(ConfigRepoConfig repoConfig) {
return new HealthStateScope(ScopeType.CONFIG_PARTIAL, repoConfig.getMaterialConfig().getFingerprint());
}
public static HealthStateScope forPartialConfigRepo(String fingerprint) {
return new HealthStateScope(ScopeType.CONFIG_PARTIAL, fingerprint);
}
public boolean isSame(String scope) {
return StringUtils.endsWithIgnoreCase(this.scope, scope);
}
public boolean isForPipeline() {
return type == ScopeType.PIPELINE;
}
public boolean isForGroup() {
return type == ScopeType.GROUP;
}
public boolean isForMaterial() {
return type == ScopeType.MATERIAL;
}
ScopeType getType() {
return type;
}
public String getScope() {
return scope;
}
public String toString() {
return String.format("LogScope[%s, scope=%s]", type, scope);
}
public boolean equals(Object that) {
if (this == that) { return true; }
if (that == null) { return false; }
if (getClass() != that.getClass()) { return false; }
return equals((HealthStateScope) that);
}
private boolean equals(HealthStateScope that) {
if (type != that.type) { return false; }
if (!scope.equals(that.scope)) { return false; }
return true;
}
public int hashCode() {
int result = type.hashCode();
result = 31 * result + (scope != null ? scope.hashCode() : 0);
return result;
}
public boolean isRemovedFromConfig(CruiseConfig cruiseConfig) {
return type.isRemovedFromConfig(cruiseConfig, scope);
}
public static HealthStateScope forAgent(String cookie) {
return new HealthStateScope(ScopeType.GLOBAL, cookie);
}
public static HealthStateScope forInvalidConfig() {
return new HealthStateScope(ScopeType.GLOBAL, "global");
}
public int compareTo(HealthStateScope o) {
int comparison;
comparison = type.compareTo(o.type);
if (comparison != 0) {
return comparison;
}
comparison = scope.compareTo(o.scope);
if (comparison != 0) {
return comparison;
}
return 0;
}
public static HealthStateScope forPlugin(String symbolicName) {
return new HealthStateScope(ScopeType.PLUGIN, symbolicName);
}
public Set<String> getPipelineNames(CruiseConfig config) {
HashSet<String> pipelineNames = new HashSet<>();
switch (type) {
case PIPELINE:
case FANIN:
pipelineNames.add(scope);
break;
case STAGE:
case JOB:
pipelineNames.add(scope.split("/")[0]);
break;
case MATERIAL:
for (PipelineConfig pc : config.getAllPipelineConfigs()) {
for (MaterialConfig mc : pc.materialConfigs()) {
String scope = HealthStateScope.forMaterialConfig(mc).getScope();
if (scope.equals(this.scope)) {
pipelineNames.add(pc.name().toString());
}
}
}
break;
case MATERIAL_UPDATE:
for (PipelineConfig pc : config.getAllPipelineConfigs()) {
for (MaterialConfig mc : pc.materialConfigs()) {
String scope = HealthStateScope.forMaterialConfigUpdate(mc).getScope();
if (scope.equals(this.scope)) {
pipelineNames.add(pc.name().toString());
}
}
}
break;
}
return pipelineNames;
}
public boolean isForConfigPartial() {
return type == ScopeType.CONFIG_PARTIAL;
}
enum ScopeType {
GLOBAL,
CONFIG_REPO,
GROUP {
public boolean isRemovedFromConfig(CruiseConfig cruiseConfig, String group) {
return !cruiseConfig.hasPipelineGroup(group);
}
},
MATERIAL {
public boolean isRemovedFromConfig(CruiseConfig cruiseConfig, String materialScope) {
for (MaterialConfig materialConfig : cruiseConfig.getAllUniqueMaterials()) {
if (HealthStateScope.forMaterialConfig(materialConfig).getScope().equals(materialScope)) {
return false;
}
}
return true;
}
},
MATERIAL_UPDATE {
public boolean isRemovedFromConfig(CruiseConfig cruiseConfig, String materialScope) {
for (MaterialConfig materialConfig : cruiseConfig.getAllUniqueMaterials()) {
if (HealthStateScope.forMaterialConfigUpdate(materialConfig).getScope().equals(materialScope)) {
return false;
}
}
return true;
}
},
CONFIG_PARTIAL {
public boolean isRemovedFromConfig(CruiseConfig cruiseConfig, String materialScope) {
for (ConfigRepoConfig configRepoConfig : cruiseConfig.getConfigRepos()) {
if (HealthStateScope.forPartialConfigRepo(configRepoConfig).getScope().equals(materialScope)) {
return false;
}
}
return true;
}
},
PIPELINE {
public boolean isRemovedFromConfig(CruiseConfig cruiseConfig, String pipeline) {
return !cruiseConfig.hasPipelineNamed(new CaseInsensitiveString(pipeline));
}
},
FANIN {
public boolean isRemovedFromConfig(CruiseConfig cruiseConfig, String pipeline) {
return !cruiseConfig.hasPipelineNamed(new CaseInsensitiveString(pipeline));
}
},
STAGE {
public boolean isRemovedFromConfig(CruiseConfig cruiseConfig, String pipelineStage) {
String[] parts = pipelineStage.split("/");
return !cruiseConfig.hasStageConfigNamed(new CaseInsensitiveString(parts[0]), new CaseInsensitiveString(parts[1]), true);
}
},
JOB {
public boolean isRemovedFromConfig(CruiseConfig cruiseConfig, String pipelineStageJob) {
String[] parts = pipelineStageJob.split("/");
return !cruiseConfig.hasBuildPlan(new CaseInsensitiveString(parts[0]), new CaseInsensitiveString(parts[1]), parts[2], true);
}
}, PLUGIN;
protected boolean isRemovedFromConfig(CruiseConfig cruiseConfig, String scope) {
return false;
};
}
}
| apache-2.0 |
porcelli-forks/kie-wb-common | kie-wb-common-stunner/kie-wb-common-stunner-sets/kie-wb-common-stunner-bpmn/kie-wb-common-stunner-bpmn-marshalling/src/test/java/org/kie/workbench/common/stunner/bpmn/client/marshall/converters/customproperties/AssociationListTest.java | 1713 | /*
* Copyright 2019 Red Hat, Inc. and/or its affiliates.
*
* 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.kie.workbench.common.stunner.bpmn.client.marshall.converters.customproperties;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class AssociationListTest {
private AssociationList tested;
public static final String VALUE = "[din]var1->input1,[din]var2->input2,[dout]var3->output1," +
"[dout]var5->output2";
public static final String VALUE_WITH_COMMA = "[din]var1->input1,[din]var2->input2,input22,input33," +
"[dout]var3->output1,[dout]var5->output2,output22,ouput23";
@Before
public void setUp() {
tested = new AssociationList();
}
@Test
public void fromString() {
AssociationList list = tested.fromString(VALUE);
assertEquals(2, list.getInputs().size());
assertEquals(2, list.getOutputs().size());
}
@Test
public void fromStringWithComma() {
AssociationList list = tested.fromString(VALUE_WITH_COMMA);
assertEquals(2, list.getInputs().size());
assertEquals(2, list.getOutputs().size());
}
} | apache-2.0 |
HB-SI/voldemort | src/java/voldemort/cluster/Cluster.java | 13745 | /*
* Copyright 2008-2013 LinkedIn, 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 voldemort.cluster;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import voldemort.VoldemortException;
import voldemort.annotations.concurrency.Threadsafe;
import voldemort.annotations.jmx.JmxGetter;
import voldemort.annotations.jmx.JmxManaged;
import voldemort.utils.Utils;
import com.google.common.collect.Sets;
/**
* A representation of the voldemort cluster
*
*
*/
@Threadsafe
@JmxManaged(description = "Metadata about the physical servers on which the Voldemort cluster runs")
public class Cluster implements Serializable {
private static final long serialVersionUID = 1;
private final String name;
private final int numberOfPartitionIds;
private final Map<Integer, Node> nodesById;
private final Map<Integer, Zone> zonesById;
private final Map<Zone, List<Integer>> nodesPerZone;
private final Map<Zone, List<Integer>> partitionsPerZone;
// Since partitionId space must be dense, arrays could be used instead of
// maps. To do so, the partition ID range would have to be determined. This
// could be done by summing up the lengths of each node's .getPartitionIds()
// returned list. This could be faster to construct and lookup by some
// constant and memory footprint could be better.
private final Map<Integer, Zone> partitionIdToZone;
private final Node[] partitionIdToNodeArray;
private final Map<Integer, Node> partitionIdToNode;
private final Map<Integer, Integer> partitionIdToNodeId;
public Cluster(String name, List<Node> nodes) {
this(name, nodes, new ArrayList<Zone>());
}
public Cluster(String name, List<Node> nodes, List<Zone> zones) {
this.name = Utils.notNull(name);
this.partitionsPerZone = new LinkedHashMap<Zone, List<Integer>>();
this.nodesPerZone = new LinkedHashMap<Zone, List<Integer>>();
this.partitionIdToZone = new HashMap<Integer, Zone>();
Map<Integer, Node> partitionIdToNodeMap = new HashMap<Integer, Node>();
this.partitionIdToNode = new HashMap<Integer, Node>();
this.partitionIdToNodeId = new HashMap<Integer, Integer>();
if(zones.size() != 0) {
zonesById = new LinkedHashMap<Integer, Zone>(zones.size());
for(Zone zone: zones) {
if(zonesById.containsKey(zone.getId()))
throw new IllegalArgumentException("Zone id " + zone.getId()
+ " appears twice in the zone list.");
zonesById.put(zone.getId(), zone);
nodesPerZone.put(zone, new ArrayList<Integer>());
partitionsPerZone.put(zone, new ArrayList<Integer>());
}
} else {
// Add default zone
zonesById = new LinkedHashMap<Integer, Zone>(1);
Zone defaultZone = new Zone();
zonesById.put(defaultZone.getId(), defaultZone);
nodesPerZone.put(defaultZone, new ArrayList<Integer>());
partitionsPerZone.put(defaultZone, new ArrayList<Integer>());
}
this.nodesById = new LinkedHashMap<Integer, Node>(nodes.size());
for(Node node: nodes) {
if(nodesById.containsKey(node.getId()))
throw new IllegalArgumentException("Node id " + node.getId()
+ " appears twice in the node list.");
nodesById.put(node.getId(), node);
Zone nodesZone = zonesById.get(node.getZoneId());
if(nodesZone == null) {
throw new IllegalArgumentException("No zone associated with this node exists.");
}
nodesPerZone.get(nodesZone).add(node.getId());
partitionsPerZone.get(nodesZone).addAll(node.getPartitionIds());
for(Integer partitionId: node.getPartitionIds()) {
if(this.partitionIdToNodeId.containsKey(partitionId)) {
throw new IllegalArgumentException("Partition id " + partitionId
+ " found on two nodes : " + node.getId()
+ " and "
+ this.partitionIdToNodeId.get(partitionId));
}
this.partitionIdToZone.put(partitionId, nodesZone);
partitionIdToNodeMap.put(partitionId, node);
this.partitionIdToNode.put(partitionId, node);
this.partitionIdToNodeId.put(partitionId, node.getId());
}
}
this.numberOfPartitionIds = getNumberOfTags(nodes);
this.partitionIdToNodeArray = new Node[this.numberOfPartitionIds];
for(int partitionId = 0; partitionId < this.numberOfPartitionIds; partitionId++) {
this.partitionIdToNodeArray[partitionId] = partitionIdToNodeMap.get(partitionId);
}
}
private int getNumberOfTags(List<Node> nodes) {
List<Integer> tags = new ArrayList<Integer>();
for(Node node: nodes) {
tags.addAll(node.getPartitionIds());
}
Collections.sort(tags);
for(int i = 0; i < numberOfPartitionIds; i++) {
if(tags.get(i).intValue() != i)
throw new IllegalArgumentException("Invalid tag assignment.");
}
return tags.size();
}
@JmxGetter(name = "name", description = "The name of the cluster")
public String getName() {
return name;
}
public Collection<Node> getNodes() {
return nodesById.values();
}
/**
* @return Sorted set of node Ids
*/
public Set<Integer> getNodeIds() {
Set<Integer> nodeIds = nodesById.keySet();
return new TreeSet<Integer>(nodeIds);
}
/**
*
* @return Sorted set of Zone Ids
*/
public Set<Integer> getZoneIds() {
Set<Integer> zoneIds = zonesById.keySet();
return new TreeSet<Integer>(zoneIds);
}
public Collection<Zone> getZones() {
return zonesById.values();
}
public Zone getZoneById(int id) {
Zone zone = zonesById.get(id);
if(zone == null) {
throw new VoldemortException("No such zone in cluster: " + id
+ " Available zones : " + displayZones());
}
return zone;
}
private String displayZones() {
String zoneIDS = "{";
for(Zone z: this.getZones()) {
if(zoneIDS.length() != 1)
zoneIDS += ",";
zoneIDS += z.getId();
}
zoneIDS += "}";
return zoneIDS;
}
public int getNumberOfZones() {
return zonesById.size();
}
public int getNumberOfPartitionsInZone(Integer zoneId) {
return partitionsPerZone.get(getZoneById(zoneId)).size();
}
public int getNumberOfNodesInZone(Integer zoneId) {
return nodesPerZone.get(getZoneById(zoneId)).size();
}
/**
* @return Sorted set of node Ids for given zone
*/
public Set<Integer> getNodeIdsInZone(Integer zoneId) {
return new TreeSet<Integer>(nodesPerZone.get(getZoneById(zoneId)));
}
/**
* @return Sorted set of partition Ids for given zone
*/
public Set<Integer> getPartitionIdsInZone(Integer zoneId) {
return new TreeSet<Integer>(partitionsPerZone.get(getZoneById(zoneId)));
}
public Zone getZoneForPartitionId(int partitionId) {
return partitionIdToZone.get(partitionId);
}
public Node getNodeForPartitionId(int partitionId) {
return this.partitionIdToNodeArray[partitionId];
}
public Node[] getPartitionIdToNodeArray() {
return this.partitionIdToNodeArray;
}
/**
*
* @return Map of partition id to node id.
*/
public Map<Integer, Integer> getPartitionIdToNodeIdMap() {
return new HashMap<Integer, Integer>(partitionIdToNodeId);
}
public Node getNodeById(int id) {
Node node = nodesById.get(id);
if(node == null)
throw new VoldemortException("No such node in cluster: " + id);
return node;
}
/**
* Given a cluster and a node id checks if the node exists
*
* @param nodeId The node id to search for
* @return True if cluster contains the node id, else false
*/
public boolean hasNodeWithId(int nodeId) {
Node node = nodesById.get(nodeId);
if(node == null) {
return false;
}
return true;
}
@JmxGetter(name = "numberOfNodes", description = "The number of nodes in the cluster.")
public int getNumberOfNodes() {
return nodesById.size();
}
public int getNumberOfPartitions() {
return numberOfPartitionIds;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Cluster('");
builder.append(getName());
builder.append("', [");
for(Node n: getNodes()) {
builder.append(n.toString());
builder.append('\n');
}
builder.append("])");
return builder.toString();
}
/**
* Return a detailed string representation of the current cluster
*
* @param isDetailed
* @return descripton of cluster
*/
public String toString(boolean isDetailed) {
if(!isDetailed) {
return toString();
}
StringBuilder builder = new StringBuilder("Cluster [" + getName() + "] Nodes ["
+ getNumberOfNodes() + "] Zones ["
+ getNumberOfZones() + "] Partitions ["
+ getNumberOfPartitions() + "]");
builder.append(" Zone Info [" + getZones() + "]");
builder.append(" Node Info [" + getNodes() + "]");
return builder.toString();
}
/**
* Clones the cluster by constructing a new one with same name, partition
* layout, and nodes.
*
* @param cluster
* @return clone of Cluster cluster.
*/
public static Cluster cloneCluster(Cluster cluster) {
// Could add a better .clone() implementation that clones the derived
// data structures. The constructor invoked by this clone implementation
// can be slow for large numbers of partitions. Probably faster to copy
// all the maps and stuff.
return new Cluster(cluster.getName(),
new ArrayList<Node>(cluster.getNodes()),
new ArrayList<Zone>(cluster.getZones()));
/*-
* Historic "clone" code being kept in case this, for some reason, was the "right" way to be doing this.
ClusterMapper mapper = new ClusterMapper();
return mapper.readCluster(new StringReader(mapper.writeCluster(cluster)));
*/
}
@Override
public boolean equals(Object second) {
if(this == second)
return true;
if(second == null || second.getClass() != getClass())
return false;
Cluster secondCluster = (Cluster) second;
if(this.getZones().size() != secondCluster.getZones().size()) {
return false;
}
if(this.getNodes().size() != secondCluster.getNodes().size()) {
return false;
}
for(Zone zoneA: this.getZones()) {
Zone zoneB;
try {
zoneB = secondCluster.getZoneById(zoneA.getId());
} catch(VoldemortException e) {
return false;
}
if(zoneB == null || zoneB.getProximityList().size() != zoneA.getProximityList().size()) {
return false;
}
for(int index = 0; index < zoneA.getProximityList().size(); index++) {
if(zoneA.getProximityList().get(index) != zoneB.getProximityList().get(index)) {
return false;
}
}
}
for(Node nodeA: this.getNodes()) {
Node nodeB;
try {
nodeB = secondCluster.getNodeById(nodeA.getId());
} catch(VoldemortException e) {
return false;
}
if(nodeA.getNumberOfPartitions() != nodeB.getNumberOfPartitions()) {
return false;
}
if(nodeA.getZoneId() != nodeB.getZoneId()) {
return false;
}
if(!Sets.newHashSet(nodeA.getPartitionIds())
.equals(Sets.newHashSet(nodeB.getPartitionIds())))
return false;
}
return true;
}
@Override
public int hashCode() {
int hc = getNodes().size();
for(Node node: getNodes()) {
hc ^= node.getHost().hashCode();
}
return hc;
}
}
| apache-2.0 |
Deepnekroz/kaa | server/common/nosql/cassandra-dao/src/test/java/org/kaaproject/kaa/server/common/nosql/cassandra/dao/model/CassandraEndpointUserTest.java | 999 | /**
* Copyright 2014-2016 CyberVision, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kaaproject.kaa.server.common.nosql.cassandra.dao.model;
import nl.jqno.equalsverifier.EqualsVerifier;
import nl.jqno.equalsverifier.Warning;
import org.junit.Test;
public class CassandraEndpointUserTest {
@Test
public void hashCodeEqualsTest(){
EqualsVerifier.forClass(CassandraEndpointUser.class).suppress(Warning.NONFINAL_FIELDS).verify();
}
} | apache-2.0 |
qwerty4030/elasticsearch | server/src/main/java/org/elasticsearch/search/aggregations/bucket/composite/CompositeValuesComparator.java | 5333 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.search.aggregations.bucket.composite;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.LeafReaderContext;
import org.elasticsearch.search.aggregations.LeafBucketCollector;
import java.io.IOException;
import static org.elasticsearch.search.aggregations.support.ValuesSource.Numeric;
import static org.elasticsearch.search.aggregations.support.ValuesSource.Bytes;
import static org.elasticsearch.search.aggregations.support.ValuesSource.Bytes.WithOrdinals;
final class CompositeValuesComparator {
private final int size;
private final CompositeValuesSource<?, ?>[] arrays;
private boolean topValueSet = false;
/**
*
* @param sources The list of {@link CompositeValuesSourceConfig} to build the composite buckets.
* @param size The number of composite buckets to keep.
*/
CompositeValuesComparator(IndexReader reader, CompositeValuesSourceConfig[] sources, int size) {
this.size = size;
this.arrays = new CompositeValuesSource<?, ?>[sources.length];
for (int i = 0; i < sources.length; i++) {
final int reverseMul = sources[i].reverseMul();
if (sources[i].valuesSource() instanceof WithOrdinals && reader instanceof DirectoryReader) {
WithOrdinals vs = (WithOrdinals) sources[i].valuesSource();
arrays[i] = CompositeValuesSource.wrapGlobalOrdinals(vs, size, reverseMul);
} else if (sources[i].valuesSource() instanceof Bytes) {
Bytes vs = (Bytes) sources[i].valuesSource();
arrays[i] = CompositeValuesSource.wrapBinary(vs, size, reverseMul);
} else if (sources[i].valuesSource() instanceof Numeric) {
final Numeric vs = (Numeric) sources[i].valuesSource();
if (vs.isFloatingPoint()) {
arrays[i] = CompositeValuesSource.wrapDouble(vs, size, reverseMul);
} else {
arrays[i] = CompositeValuesSource.wrapLong(vs, sources[i].format(), size, reverseMul);
}
}
}
}
/**
* Moves the values in <code>slot1</code> to <code>slot2</code>.
*/
void move(int slot1, int slot2) {
assert slot1 < size && slot2 < size;
for (int i = 0; i < arrays.length; i++) {
arrays[i].move(slot1, slot2);
}
}
/**
* Compares the values in <code>slot1</code> with <code>slot2</code>.
*/
int compare(int slot1, int slot2) {
assert slot1 < size && slot2 < size;
for (int i = 0; i < arrays.length; i++) {
int cmp = arrays[i].compare(slot1, slot2);
if (cmp != 0) {
return cmp;
}
}
return 0;
}
/**
* Returns true if a top value has been set for this comparator.
*/
boolean hasTop() {
return topValueSet;
}
/**
* Sets the top values for this comparator.
*/
void setTop(Comparable<?>[] values) {
assert values.length == arrays.length;
topValueSet = true;
for (int i = 0; i < arrays.length; i++) {
arrays[i].setTop(values[i]);
}
}
/**
* Compares the top values with the values in <code>slot</code>.
*/
int compareTop(int slot) {
assert slot < size;
for (int i = 0; i < arrays.length; i++) {
int cmp = arrays[i].compareTop(slot);
if (cmp != 0) {
return cmp;
}
}
return 0;
}
/**
* Builds the {@link CompositeKey} for <code>slot</code>.
*/
CompositeKey toCompositeKey(int slot) throws IOException {
assert slot < size;
Comparable<?>[] values = new Comparable<?>[arrays.length];
for (int i = 0; i < values.length; i++) {
values[i] = arrays[i].toComparable(slot);
}
return new CompositeKey(values);
}
/**
* Gets the {@link LeafBucketCollector} that will record the composite buckets of the visited documents.
*/
CompositeValuesSource.Collector getLeafCollector(LeafReaderContext context, CompositeValuesSource.Collector in) throws IOException {
int last = arrays.length - 1;
CompositeValuesSource.Collector next = arrays[last].getLeafCollector(context, in);
for (int i = last - 1; i >= 0; i--) {
next = arrays[i].getLeafCollector(context, next);
}
return next;
}
}
| apache-2.0 |
syzer/incubator-tamaya | modules/events/src/test/java/org/apache/tamaya/events/TestConfigView.java | 4643 | /*
* 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.tamaya.events;
import org.apache.tamaya.ConfigException;
import org.apache.tamaya.ConfigOperator;
import org.apache.tamaya.ConfigQuery;
import org.apache.tamaya.Configuration;
import org.apache.tamaya.ConfigurationProvider;
import org.apache.tamaya.TypeLiteral;
import org.apache.tamaya.spi.PropertyConverter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
/**
* Created by Anatole on 24.03.2015.
*/
public class TestConfigView implements ConfigOperator{
private static final TestConfigView INSTANCE = new TestConfigView();
private TestConfigView(){}
public static ConfigOperator of(){
return INSTANCE;
}
@Override
public Configuration operate(final Configuration config) {
return new Configuration() {
@Override
public Map<String, String> getProperties() {
Map<String, String> result = new HashMap<>();
for (Map.Entry<String, String> en : config.getProperties().entrySet()) {
if (en.getKey().startsWith("test")) {
result.put(en.getKey(), en.getValue());
}
}
return result;
// return config.getProperties().entrySet().stream().filter(e -> e.getKey().startsWith("test")).collect(
// Collectors.toMap(en -> en.getKey(), en -> en.getValue()));
}
@Override
public Configuration with(ConfigOperator operator) {
return null;
}
@Override
public <T> T query(ConfigQuery<T> query) {
return null;
}
@Override
public String get(String key) {
return getProperties().get(key);
}
@Override
public <T> T get(String key, Class<T> type) {
return (T) get(key, TypeLiteral.of(type));
}
/**
* Accesses the current String value for the given key and tries to convert it
* using the {@link org.apache.tamaya.spi.PropertyConverter} instances provided by the current
* {@link org.apache.tamaya.spi.ConfigurationContext}.
*
* @param key the property's absolute, or relative path, e.g. @code
* a/b/c/d.myProperty}.
* @param type The target type required, not null.
* @param <T> the value type
* @return the converted value, never null.
*/
@Override
public <T> T get(String key, TypeLiteral<T> type) {
String value = get(key);
if (value != null) {
List<PropertyConverter<T>> converters = ConfigurationProvider.getConfigurationContext()
.getPropertyConverters(type);
for (PropertyConverter<T> converter : converters) {
try {
T t = converter.convert(value);
if (t != null) {
return t;
}
} catch (Exception e) {
Logger.getLogger(getClass().getName())
.log(Level.FINEST, "PropertyConverter: " + converter + " failed to convert value: "
+ value, e);
}
}
throw new ConfigException("Unparseable config value for type: " + type.getRawType().getName() + ": " + key);
}
return null;
}
};
}
}
| apache-2.0 |
StephanEwen/incubator-flink | flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/functions/aggfunctions/AvgAggFunction.java | 7723 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.table.planner.functions.aggfunctions;
import org.apache.flink.table.api.DataTypes;
import org.apache.flink.table.expressions.Expression;
import org.apache.flink.table.expressions.UnresolvedCallExpression;
import org.apache.flink.table.expressions.UnresolvedReferenceExpression;
import org.apache.flink.table.types.DataType;
import org.apache.flink.table.types.logical.DecimalType;
import org.apache.flink.table.types.logical.utils.LogicalTypeMerging;
import java.math.BigDecimal;
import static org.apache.flink.table.expressions.ApiExpressionUtils.unresolvedRef;
import static org.apache.flink.table.planner.expressions.ExpressionBuilder.cast;
import static org.apache.flink.table.planner.expressions.ExpressionBuilder.div;
import static org.apache.flink.table.planner.expressions.ExpressionBuilder.equalTo;
import static org.apache.flink.table.planner.expressions.ExpressionBuilder.ifThenElse;
import static org.apache.flink.table.planner.expressions.ExpressionBuilder.isNull;
import static org.apache.flink.table.planner.expressions.ExpressionBuilder.literal;
import static org.apache.flink.table.planner.expressions.ExpressionBuilder.minus;
import static org.apache.flink.table.planner.expressions.ExpressionBuilder.nullOf;
import static org.apache.flink.table.planner.expressions.ExpressionBuilder.plus;
import static org.apache.flink.table.planner.expressions.ExpressionBuilder.typeLiteral;
/** built-in avg aggregate function. */
public abstract class AvgAggFunction extends DeclarativeAggregateFunction {
private UnresolvedReferenceExpression sum = unresolvedRef("sum");
private UnresolvedReferenceExpression count = unresolvedRef("count");
public abstract DataType getSumType();
@Override
public int operandCount() {
return 1;
}
@Override
public UnresolvedReferenceExpression[] aggBufferAttributes() {
return new UnresolvedReferenceExpression[] {sum, count};
}
@Override
public DataType[] getAggBufferTypes() {
return new DataType[] {getSumType(), DataTypes.BIGINT()};
}
@Override
public Expression[] initialValuesExpressions() {
return new Expression[] {
/* sum = */ literal(0L, getSumType().notNull()), /* count = */ literal(0L)
};
}
@Override
public Expression[] accumulateExpressions() {
return new Expression[] {
/* sum = */ adjustSumType(ifThenElse(isNull(operand(0)), sum, plus(sum, operand(0)))),
/* count = */ ifThenElse(isNull(operand(0)), count, plus(count, literal(1L))),
};
}
@Override
public Expression[] retractExpressions() {
return new Expression[] {
/* sum = */ adjustSumType(ifThenElse(isNull(operand(0)), sum, minus(sum, operand(0)))),
/* count = */ ifThenElse(isNull(operand(0)), count, minus(count, literal(1L))),
};
}
@Override
public Expression[] mergeExpressions() {
return new Expression[] {
/* sum = */ adjustSumType(plus(sum, mergeOperand(sum))),
/* count = */ plus(count, mergeOperand(count))
};
}
private UnresolvedCallExpression adjustSumType(UnresolvedCallExpression sumExpr) {
return cast(sumExpr, typeLiteral(getSumType()));
}
/** If all input are nulls, count will be 0 and we will get null after the division. */
@Override
public Expression getValueExpression() {
Expression ifTrue = nullOf(getResultType());
Expression ifFalse = cast(div(sum, count), typeLiteral(getResultType()));
return ifThenElse(equalTo(count, literal(0L)), ifTrue, ifFalse);
}
/** Built-in Byte Avg aggregate function. */
public static class ByteAvgAggFunction extends AvgAggFunction {
@Override
public DataType getResultType() {
return DataTypes.TINYINT();
}
@Override
public DataType getSumType() {
return DataTypes.BIGINT();
}
}
/** Built-in Short Avg aggregate function. */
public static class ShortAvgAggFunction extends AvgAggFunction {
@Override
public DataType getResultType() {
return DataTypes.SMALLINT();
}
@Override
public DataType getSumType() {
return DataTypes.BIGINT();
}
}
/** Built-in Integer Avg aggregate function. */
public static class IntAvgAggFunction extends AvgAggFunction {
@Override
public DataType getResultType() {
return DataTypes.INT();
}
@Override
public DataType getSumType() {
return DataTypes.BIGINT();
}
}
/** Built-in Long Avg aggregate function. */
public static class LongAvgAggFunction extends AvgAggFunction {
@Override
public DataType getResultType() {
return DataTypes.BIGINT();
}
@Override
public DataType getSumType() {
return DataTypes.BIGINT();
}
}
/** Built-in Float Avg aggregate function. */
public static class FloatAvgAggFunction extends AvgAggFunction {
@Override
public DataType getResultType() {
return DataTypes.FLOAT();
}
@Override
public DataType getSumType() {
return DataTypes.DOUBLE();
}
@Override
public Expression[] initialValuesExpressions() {
return new Expression[] {literal(0D), literal(0L)};
}
}
/** Built-in Double Avg aggregate function. */
public static class DoubleAvgAggFunction extends AvgAggFunction {
@Override
public DataType getResultType() {
return DataTypes.DOUBLE();
}
@Override
public DataType getSumType() {
return DataTypes.DOUBLE();
}
@Override
public Expression[] initialValuesExpressions() {
return new Expression[] {literal(0D), literal(0L)};
}
}
/** Built-in Decimal Avg aggregate function. */
public static class DecimalAvgAggFunction extends AvgAggFunction {
private final DecimalType type;
public DecimalAvgAggFunction(DecimalType type) {
this.type = type;
}
@Override
public DataType getResultType() {
DecimalType t = (DecimalType) LogicalTypeMerging.findAvgAggType(type);
return DataTypes.DECIMAL(t.getPrecision(), t.getScale());
}
@Override
public DataType getSumType() {
DecimalType t = (DecimalType) LogicalTypeMerging.findSumAggType(type);
return DataTypes.DECIMAL(t.getPrecision(), t.getScale());
}
@Override
public Expression[] initialValuesExpressions() {
return new Expression[] {literal(BigDecimal.ZERO, getSumType().notNull()), literal(0L)};
}
}
}
| apache-2.0 |
mehant/incubator-calcite | core/src/main/java/org/apache/calcite/rel/convert/package-info.java | 964 | /*
* 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.
*/
/**
* Defines relational expressions and rules for converting between calling
* conventions.
*/
package org.apache.calcite.rel.convert;
// End package-info.java
| apache-2.0 |
longerian/RC4A | src/org/rubychina/android/GlobalResource.java | 1797 | /*Copyright (C) 2012 Longerian (http://www.longerian.me)
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.rubychina.android;
import java.util.ArrayList;
import java.util.List;
import org.rubychina.android.type.Node;
import org.rubychina.android.type.SiteGroup;
import org.rubychina.android.type.Topic;
import org.rubychina.android.type.User;
public enum GlobalResource {
INSTANCE;
private List<Topic> curTopics = new ArrayList<Topic>();
private List<Node> nodes = new ArrayList<Node>();
private List<User> users = new ArrayList<User>();
private List<SiteGroup> sites = new ArrayList<SiteGroup>();
public synchronized List<Topic> getCurTopics() {
return curTopics;
}
public synchronized void setCurTopics(List<Topic> curTopics) {
this.curTopics = curTopics;
}
public synchronized List<Node> getNodes() {
return nodes;
}
public synchronized void setNodes(List<Node> nodes) {
this.nodes = nodes;
}
public synchronized List<User> getUsers() {
return users;
}
public synchronized void setUsers(List<User> users) {
this.users = users;
}
public synchronized List<SiteGroup> getSites() {
return sites;
}
public synchronized void setSites(List<SiteGroup> sites) {
this.sites = sites;
}
}
| apache-2.0 |
psiroky/kie-wb-common | kie-wb-common-widgets/kie-wb-common-ui/src/main/java/org/kie/workbench/common/widgets/client/widget/PercentageCalculator.java | 979 | /*
* Copyright 2011 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kie.workbench.common.widgets.client.widget;
public class PercentageCalculator {
public static int calculatePercent(int numerator,
int denominator) {
int percent = 0;
if (denominator != 0) {
percent = (int) ((((float) denominator - (float) numerator) / (float) denominator) * 100);
}
return percent;
}
}
| apache-2.0 |
ruebot/fcrepo4 | fcrepo-http-api/src/main/java/org/fcrepo/http/api/FedoraHttpConfiguration.java | 1125 | /*
* Copyright 2015 DuraSpace, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.fcrepo.http.api;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* @author cabeer
* @since 10/17/14
*/
@Component
public class FedoraHttpConfiguration {
@Value("${fcrepo.http.ldp.putRequiresIfMatch:false}")
private boolean putRequiresIfMatch;
/**
* Should PUT requests require an If-Match header?
* @return put request if match
*/
public boolean putRequiresIfMatch() {
return putRequiresIfMatch;
}
}
| apache-2.0 |
paplorinc/intellij-community | xml/dom-openapi/src/com/intellij/util/xml/highlighting/DomElementAnnotationHolder.java | 2866 | /*
* Copyright 2000-2009 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.util.xml.highlighting;
import com.intellij.codeInspection.LocalQuickFix;
import com.intellij.codeInspection.ProblemHighlightType;
import com.intellij.lang.annotation.Annotation;
import com.intellij.lang.annotation.HighlightSeverity;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiReference;
import com.intellij.util.xml.DomElement;
import com.intellij.util.xml.DomFileElement;
import com.intellij.util.xml.GenericDomValue;
import com.intellij.util.xml.reflect.DomCollectionChildDescription;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public interface DomElementAnnotationHolder extends Iterable<DomElementProblemDescriptor>{
boolean isOnTheFly();
@NotNull
DomFileElement<?> getFileElement();
@NotNull
DomElementProblemDescriptor createProblem(@NotNull DomElement domElement, @Nullable String message, LocalQuickFix... fixes);
@NotNull
DomElementProblemDescriptor createProblem(@NotNull DomElement domElement, DomCollectionChildDescription childDescription, @Nullable String message);
@NotNull
DomElementProblemDescriptor createProblem(@NotNull DomElement domElement, HighlightSeverity highlightType, String message);
DomElementProblemDescriptor createProblem(@NotNull DomElement domElement, HighlightSeverity highlightType, String message, LocalQuickFix... fixes);
DomElementProblemDescriptor createProblem(@NotNull DomElement domElement, HighlightSeverity highlightType, String message, TextRange textRange, LocalQuickFix... fixes);
DomElementProblemDescriptor createProblem(@NotNull DomElement domElement, ProblemHighlightType highlightType, String message, @Nullable TextRange textRange, LocalQuickFix... fixes);
@NotNull
DomElementResolveProblemDescriptor createResolveProblem(@NotNull GenericDomValue element, @NotNull PsiReference reference);
/**
* Is useful only if called from {@link com.intellij.util.xml.highlighting.DomElementsAnnotator} instance
* @param element element
* @param severity highlight severity
* @param message description
* @return annotation
*/
@NotNull
Annotation createAnnotation(@NotNull DomElement element, HighlightSeverity severity, @Nullable String message);
int getSize();
}
| apache-2.0 |
matsprea/omim | android/src/com/mapswithme/maps/purchase/BookmarkPaymentFragment.java | 13042 | package com.mapswithme.maps.purchase;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.android.billingclient.api.SkuDetails;
import com.bumptech.glide.Glide;
import com.mapswithme.maps.Framework;
import com.mapswithme.maps.PrivateVariables;
import com.mapswithme.maps.PurchaseOperationObservable;
import com.mapswithme.maps.R;
import com.mapswithme.maps.base.BaseMwmFragment;
import com.mapswithme.maps.bookmarks.data.PaymentData;
import com.mapswithme.maps.dialog.AlertDialogCallback;
import com.mapswithme.util.Utils;
import com.mapswithme.util.log.Logger;
import com.mapswithme.util.log.LoggerFactory;
import com.mapswithme.util.statistics.Statistics;
import java.util.Collections;
import java.util.List;
public class BookmarkPaymentFragment extends BaseMwmFragment
implements AlertDialogCallback, PurchaseStateActivator<BookmarkPaymentState>
{
static final String ARG_PAYMENT_DATA = "arg_payment_data";
private static final Logger LOGGER = LoggerFactory.INSTANCE.getLogger(LoggerFactory.Type.BILLING);
private static final String TAG = BookmarkPaymentFragment.class.getSimpleName();
private static final String EXTRA_CURRENT_STATE = "extra_current_state";
private static final String EXTRA_PRODUCT_DETAILS = "extra_product_details";
private static final String EXTRA_SUBS_PRODUCT_DETAILS = "extra_subs_product_details";
private static final String EXTRA_VALIDATION_RESULT = "extra_validation_result";
@SuppressWarnings("NullableProblems")
@NonNull
private PurchaseController<PurchaseCallback> mPurchaseController;
@SuppressWarnings("NullableProblems")
@NonNull
private BookmarkPurchaseCallback mPurchaseCallback;
@SuppressWarnings("NullableProblems")
@NonNull
private PaymentData mPaymentData;
@Nullable
private ProductDetails mProductDetails;
@Nullable
private ProductDetails mSubsProductDetails;
private boolean mValidationResult;
@NonNull
private BookmarkPaymentState mState = BookmarkPaymentState.NONE;
@SuppressWarnings("NullableProblems")
@NonNull
private BillingManager<PlayStoreBillingCallback> mSubsProductDetailsLoadingManager;
@NonNull
private final SubsProductDetailsCallback mSubsProductDetailsCallback
= new SubsProductDetailsCallback();
@Override
public void onCreate(@Nullable Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Bundle args = getArguments();
if (args == null)
throw new IllegalStateException("Args must be provided for payment fragment!");
PaymentData paymentData = args.getParcelable(ARG_PAYMENT_DATA);
if (paymentData == null)
throw new IllegalStateException("Payment data must be provided for payment fragment!");
mPaymentData = paymentData;
mPurchaseCallback = new BookmarkPurchaseCallback(mPaymentData.getServerId());
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable
Bundle savedInstanceState)
{
mPurchaseController = PurchaseFactory.createBookmarkPurchaseController(requireContext(),
mPaymentData.getProductId(),
mPaymentData.getServerId());
if (savedInstanceState != null)
mPurchaseController.onRestore(savedInstanceState);
mPurchaseController.initialize(requireActivity());
mSubsProductDetailsLoadingManager = PurchaseFactory.createSubscriptionBillingManager();
mSubsProductDetailsLoadingManager.initialize(requireActivity());
mSubsProductDetailsLoadingManager.addCallback(mSubsProductDetailsCallback);
mSubsProductDetailsCallback.attach(this);
View root = inflater.inflate(R.layout.fragment_bookmark_payment, container, false);
View subscriptionButton = root.findViewById(R.id.buy_subs_btn);
subscriptionButton.setOnClickListener(v -> onBuySubscriptionClicked());
TextView buyInappBtn = root.findViewById(R.id.buy_inapp_btn);
buyInappBtn.setOnClickListener(v -> onBuyInappClicked());
return root;
}
private void onBuySubscriptionClicked()
{
SubscriptionType type = SubscriptionType.getTypeByBookmarksGroup(mPaymentData.getGroup());
if (type.equals(SubscriptionType.BOOKMARKS_SIGHTS))
{
BookmarksSightsSubscriptionActivity.startForResult
(this, PurchaseUtils.REQ_CODE_PAY_SUBSCRIPTION, Statistics.ParamValue.CARD);
return;
}
BookmarksAllSubscriptionActivity.startForResult
(this, PurchaseUtils.REQ_CODE_PAY_SUBSCRIPTION, Statistics.ParamValue.CARD);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != Activity.RESULT_OK)
return;
if (requestCode == PurchaseUtils.REQ_CODE_PAY_SUBSCRIPTION)
{
Intent intent = new Intent();
intent.putExtra(PurchaseUtils.EXTRA_IS_SUBSCRIPTION, true);
requireActivity().setResult(Activity.RESULT_OK, intent);
requireActivity().finish();
}
}
private void onBuyInappClicked()
{
Statistics.INSTANCE.trackPurchasePreviewSelect(mPaymentData.getServerId(),
mPaymentData.getProductId());
Statistics.INSTANCE.trackPurchaseEvent(Statistics.EventName.INAPP_PURCHASE_PREVIEW_PAY,
mPaymentData.getServerId(),
Statistics.STATISTICS_CHANNEL_REALTIME);
startPurchaseTransaction();
}
@Override
public boolean onBackPressed()
{
if (mState == BookmarkPaymentState.VALIDATION)
{
Toast.makeText(requireContext(), R.string.purchase_please_wait_toast, Toast.LENGTH_SHORT)
.show();
return true;
}
Statistics.INSTANCE.trackPurchaseEvent(Statistics.EventName.INAPP_PURCHASE_PREVIEW_CANCEL,
mPaymentData.getServerId());
return super.onBackPressed();
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState)
{
super.onViewCreated(view, savedInstanceState);
if (savedInstanceState == null)
Statistics.INSTANCE.trackPurchasePreviewShow(mPaymentData.getServerId(),
PrivateVariables.bookmarksVendor(),
mPaymentData.getProductId());
LOGGER.d(TAG, "onViewCreated savedInstanceState = " + savedInstanceState);
setInitialPaymentData();
loadImage();
if (savedInstanceState != null)
{
mProductDetails = savedInstanceState.getParcelable(EXTRA_PRODUCT_DETAILS);
if (mProductDetails != null)
updateProductDetails();
mSubsProductDetails = savedInstanceState.getParcelable(EXTRA_SUBS_PRODUCT_DETAILS);
if (mSubsProductDetails != null)
updateSubsProductDetails();
mValidationResult = savedInstanceState.getBoolean(EXTRA_VALIDATION_RESULT);
BookmarkPaymentState savedState
= BookmarkPaymentState.values()[savedInstanceState.getInt(EXTRA_CURRENT_STATE)];
activateState(savedState);
return;
}
activateState(BookmarkPaymentState.PRODUCT_DETAILS_LOADING);
mPurchaseController.queryProductDetails();
SubscriptionType type = SubscriptionType.getTypeByBookmarksGroup(mPaymentData.getGroup());
List<String> subsProductIds =
Collections.singletonList(type.getMonthlyProductId());
mSubsProductDetailsLoadingManager.queryProductDetails(subsProductIds);
}
@Override
public void onDestroyView()
{
super.onDestroyView();
mPurchaseController.destroy();
mSubsProductDetailsLoadingManager.removeCallback(mSubsProductDetailsCallback);
mSubsProductDetailsCallback.detach();
mSubsProductDetailsLoadingManager.destroy();
}
private void startPurchaseTransaction()
{
activateState(BookmarkPaymentState.TRANSACTION_STARTING);
Framework.nativeStartPurchaseTransaction(mPaymentData.getServerId(),
PrivateVariables.bookmarksVendor());
}
void launchBillingFlow()
{
mPurchaseController.launchPurchaseFlow(mPaymentData.getProductId());
activateState(BookmarkPaymentState.PAYMENT_IN_PROGRESS);
}
@Override
public void onStart()
{
super.onStart();
PurchaseOperationObservable observable = PurchaseOperationObservable.from(requireContext());
observable.addTransactionObserver(mPurchaseCallback);
mPurchaseController.addCallback(mPurchaseCallback);
mPurchaseCallback.attach(this);
}
@Override
public void onStop()
{
super.onStop();
PurchaseOperationObservable observable = PurchaseOperationObservable.from(requireContext());
observable.removeTransactionObserver(mPurchaseCallback);
mPurchaseController.removeCallback();
mPurchaseCallback.detach();
}
@Override
public void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
LOGGER.d(TAG, "onSaveInstanceState");
outState.putInt(EXTRA_CURRENT_STATE, mState.ordinal());
outState.putParcelable(EXTRA_PRODUCT_DETAILS, mProductDetails);
outState.putParcelable(EXTRA_SUBS_PRODUCT_DETAILS, mSubsProductDetails);
mPurchaseController.onSave(outState);
}
@Override
public void activateState(@NonNull BookmarkPaymentState state)
{
if (state == mState)
return;
LOGGER.i(TAG, "Activate state: " + state);
mState = state;
mState.activate(this);
}
private void loadImage()
{
if (TextUtils.isEmpty(mPaymentData.getImgUrl()))
return;
ImageView imageView = getViewOrThrow().findViewById(R.id.image);
Glide.with(imageView.getContext())
.load(mPaymentData.getImgUrl())
.centerCrop()
.into(imageView);
}
private void setInitialPaymentData()
{
TextView name = getViewOrThrow().findViewById(R.id.product_catalog_name);
name.setText(mPaymentData.getName());
TextView author = getViewOrThrow().findViewById(R.id.author_name);
author.setText(mPaymentData.getAuthorName());
}
void handleProductDetails(@NonNull List<SkuDetails> details)
{
if (details.isEmpty())
return;
SkuDetails skuDetails = details.get(0);
mProductDetails = PurchaseUtils.toProductDetails(skuDetails);
}
void handleSubsProductDetails(@NonNull List<SkuDetails> details)
{
if (details.isEmpty())
return;
SkuDetails skuDetails = details.get(0);
mSubsProductDetails = PurchaseUtils.toProductDetails(skuDetails);
}
void handleValidationResult(boolean validationResult)
{
mValidationResult = validationResult;
}
@Override
public void onAlertDialogPositiveClick(int requestCode, int which)
{
handleErrorDialogEvent(requestCode);
}
@Override
public void onAlertDialogNegativeClick(int requestCode, int which)
{
// Do nothing by default.
}
@Override
public void onAlertDialogCancel(int requestCode)
{
handleErrorDialogEvent(requestCode);
}
private void handleErrorDialogEvent(int requestCode)
{
switch (requestCode)
{
case PurchaseUtils.REQ_CODE_PRODUCT_DETAILS_FAILURE:
requireActivity().finish();
break;
case PurchaseUtils.REQ_CODE_START_TRANSACTION_FAILURE:
case PurchaseUtils.REQ_CODE_PAYMENT_FAILURE:
activateState(BookmarkPaymentState.PRODUCT_DETAILS_LOADED);
break;
}
}
void updateProductDetails()
{
if (mProductDetails == null)
throw new AssertionError("Product details must be obtained at this moment!");
TextView buyButton = getViewOrThrow().findViewById(R.id.buy_inapp_btn);
String price = Utils.formatCurrencyString(mProductDetails.getPrice(),
mProductDetails.getCurrencyCode());
buyButton.setText(getString(R.string.buy_btn, price));
TextView storeName = getViewOrThrow().findViewById(R.id.product_store_name);
storeName.setText(mProductDetails.getTitle());
}
void updateSubsProductDetails()
{
if (mSubsProductDetails == null)
throw new AssertionError("Subs product details must be obtained at this moment!");
String formattedPrice = Utils.formatCurrencyString(mSubsProductDetails.getPrice(),
mSubsProductDetails.getCurrencyCode());
TextView subsButton = getViewOrThrow().findViewById(R.id.buy_subs_btn);
subsButton.setText(getString(R.string.buy_btn_for_subscription_version_2, formattedPrice));
}
void finishValidation()
{
if (mValidationResult)
requireActivity().setResult(Activity.RESULT_OK);
requireActivity().finish();
}
}
| apache-2.0 |
networknt/light-4j | metrics/src/test/java/io/dropwizard/metrics/SlidingWindowReservoirTest.java | 1479 | /*
* Copyright 2010-2013 Coda Hale and Yammer, Inc., 2014-2017 Dropwizard Team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.dropwizard.metrics;
import org.junit.Test;
import io.dropwizard.metrics.SlidingWindowReservoir;
import static org.assertj.core.api.Assertions.assertThat;
public class SlidingWindowReservoirTest {
private final SlidingWindowReservoir reservoir = new SlidingWindowReservoir(3);
@Test
public void handlesSmallDataStreams() throws Exception {
reservoir.update(1);
reservoir.update(2);
assertThat(reservoir.getSnapshot().getValues())
.containsOnly(1, 2);
}
@Test
public void onlyKeepsTheMostRecentFromBigDataStreams() throws Exception {
reservoir.update(1);
reservoir.update(2);
reservoir.update(3);
reservoir.update(4);
assertThat(reservoir.getSnapshot().getValues())
.containsOnly(2, 3, 4);
}
}
| apache-2.0 |
juanavelez/hazelcast | hazelcast/src/test/java/com/hazelcast/concurrent/atomicreference/AtomicReferenceInstanceSharingTest.java | 2990 | /*
* Copyright (c) 2008-2017, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.concurrent.atomicreference;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.IAtomicReference;
import com.hazelcast.test.HazelcastParallelClassRunner;
import com.hazelcast.test.HazelcastTestSupport;
import com.hazelcast.test.annotation.ParallelTest;
import com.hazelcast.test.annotation.QuickTest;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import java.io.Serializable;
import java.util.concurrent.ExecutionException;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
@RunWith(HazelcastParallelClassRunner.class)
@Category({QuickTest.class, ParallelTest.class})
public class AtomicReferenceInstanceSharingTest extends HazelcastTestSupport {
private HazelcastInstance[] instances;
private HazelcastInstance local;
private HazelcastInstance remote;
@Before
public void setUp() {
instances = createHazelcastInstanceFactory(2).newInstances();
warmUpPartitions(instances);
local = instances[0];
remote = instances[1];
}
@Test
public void invocationToLocalMember() throws ExecutionException, InterruptedException {
String localKey = generateKeyOwnedBy(local);
IAtomicReference<DummyObject> ref = local.getAtomicReference(localKey);
DummyObject inserted = new DummyObject();
ref.set(inserted);
DummyObject get1 = ref.get();
DummyObject get2 = ref.get();
assertNotNull(get1);
assertNotNull(get2);
assertNotSame(get1, get2);
assertNotSame(get1, inserted);
assertNotSame(get2, inserted);
}
public static class DummyObject implements Serializable {
}
@Test
public void invocationToRemoteMember() throws ExecutionException, InterruptedException {
String localKey = generateKeyOwnedBy(remote);
IAtomicReference<DummyObject> ref = local.getAtomicReference(localKey);
DummyObject inserted = new DummyObject();
ref.set(inserted);
DummyObject get1 = ref.get();
DummyObject get2 = ref.get();
assertNotNull(get1);
assertNotNull(get2);
assertNotSame(get1, get2);
assertNotSame(get1, inserted);
assertNotSame(get2, inserted);
}
}
| apache-2.0 |
flofreud/aws-sdk-java | aws-java-sdk-directory/src/main/java/com/amazonaws/services/directory/model/transform/CreateConditionalForwarderResultJsonUnmarshaller.java | 1808 | /*
* Copyright 2010-2016 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.directory.model.transform;
import java.util.Map;
import java.util.Map.Entry;
import java.math.*;
import java.nio.ByteBuffer;
import com.amazonaws.services.directory.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* CreateConditionalForwarderResult JSON Unmarshaller
*/
public class CreateConditionalForwarderResultJsonUnmarshaller implements
Unmarshaller<CreateConditionalForwarderResult, JsonUnmarshallerContext> {
public CreateConditionalForwarderResult unmarshall(
JsonUnmarshallerContext context) throws Exception {
CreateConditionalForwarderResult createConditionalForwarderResult = new CreateConditionalForwarderResult();
return createConditionalForwarderResult;
}
private static CreateConditionalForwarderResultJsonUnmarshaller instance;
public static CreateConditionalForwarderResultJsonUnmarshaller getInstance() {
if (instance == null)
instance = new CreateConditionalForwarderResultJsonUnmarshaller();
return instance;
}
}
| apache-2.0 |
ketan/gocd | server/src/main/java/com/thoughtworks/go/server/controller/actions/JsonAction.java | 4901 | /*
* Copyright 2020 ThoughtWorks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.thoughtworks.go.server.controller.actions;
import com.thoughtworks.go.config.validation.GoConfigValidity;
import com.thoughtworks.go.server.web.JsonView;
import com.thoughtworks.go.server.web.SimpleJsonView;
import com.thoughtworks.go.serverhealth.ServerHealthState;
import com.thoughtworks.go.util.GoConstants;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletResponse;
import java.util.LinkedHashMap;
import java.util.Map;
import static com.thoughtworks.go.util.GoConstants.ERROR_FOR_JSON;
import static com.thoughtworks.go.util.GoConstants.RESPONSE_CHARSET_JSON;
import static javax.servlet.http.HttpServletResponse.*;
public class JsonAction implements RestfulAction {
private final int status;
private final Object json;
public static JsonAction from(ServerHealthState serverHealthState) {
if (serverHealthState.isSuccess()) {
return jsonCreated(new LinkedHashMap());
}
Map<String, Object> jsonLog = new LinkedHashMap<>();
jsonLog.put(ERROR_FOR_JSON, serverHealthState.getDescription());
return new JsonAction(serverHealthState.getType().getHttpCode(), jsonLog);
}
public static JsonAction jsonCreated(Object json) {
return new JsonAction(SC_CREATED, json);
}
public static JsonAction jsonFound(Object json) {
return new JsonAction(SC_OK, json);
}
public static JsonAction jsonOK() {
return jsonOK(new LinkedHashMap());
}
public static JsonAction jsonNotAcceptable(Object json) {
return new JsonAction(SC_NOT_ACCEPTABLE, json);
}
public static JsonAction jsonForbidden() {
return new JsonAction(SC_FORBIDDEN, new LinkedHashMap());
}
public static JsonAction jsonForbidden(String message) {
Map<String, Object> map = new LinkedHashMap<>();
map.put(ERROR_FOR_JSON, message);
return new JsonAction(SC_FORBIDDEN, map);
}
public static JsonAction jsonForbidden(Exception e) {
return jsonForbidden(e.getMessage());
}
public static JsonAction jsonBadRequest(Object json) {
return new JsonAction(SC_BAD_REQUEST, json);
}
public static JsonAction jsonNotFound(Object json) {
return new JsonAction(SC_NOT_FOUND, json);
}
public static JsonAction jsonConflict(Object json) {
return new JsonAction(SC_CONFLICT, json);
}
public static JsonAction jsonByValidity(Object json, GoConfigValidity.InvalidGoConfig configValidity) {
return (configValidity.isType(GoConfigValidity.VT_CONFLICT) ||
configValidity.isType(GoConfigValidity.VT_MERGE_OPERATION_ERROR) ||
configValidity.isType(GoConfigValidity.VT_MERGE_POST_VALIDATION_ERROR) ||
configValidity.isType(GoConfigValidity.VT_MERGE_PRE_VALIDATION_ERROR)) ? jsonConflict(json) : jsonNotFound(json);
}
/**
* @deprecated replace with createView
*/
@Override
public ModelAndView respond(HttpServletResponse response) {
return new JsonModelAndView(response, json, status);
}
private JsonAction(int status, Object json) {
this.status = status;
this.json = json;
}
public ModelAndView createView() {
SimpleJsonView view = new SimpleJsonView(status, json);
return new ModelAndView(view, JsonView.asMap(json));
}
public static JsonAction jsonOK(Map jsonMap) {
return new JsonAction(SC_OK, jsonMap);
}
private class JsonModelAndView extends ModelAndView {
@Override
public String getViewName() {
return "jsonView";
}
public JsonModelAndView(HttpServletResponse response, Object json, int status) {
super(new JsonView(), JsonView.asMap(json));
// In IE, there's a problem with caching. We want to cache if we can.
// This will force the browser to clear the cache only for this page.
// If any other pages need to clear the cache, we might want to move this
// logic to an intercepter.
response.addHeader("Cache-Control", GoConstants.CACHE_CONTROL);
response.setStatus(status);
response.setContentType(RESPONSE_CHARSET_JSON);
}
}
}
| apache-2.0 |
ThiagoGarciaAlves/intellij-community | xml/dom-impl/src/com/intellij/util/xml/impl/DomManagerImpl.java | 17979 | /*
* Copyright 2000-2017 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.util.xml.impl;
import com.intellij.ide.highlighter.DomSupportEnabled;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.fileTypes.StdFileTypes;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ProjectFileIndex;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.Factory;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.vfs.*;
import com.intellij.openapi.vfs.newvfs.NewVirtualFile;
import com.intellij.pom.PomManager;
import com.intellij.pom.PomModel;
import com.intellij.pom.PomModelAspect;
import com.intellij.pom.event.PomModelEvent;
import com.intellij.pom.event.PomModelListener;
import com.intellij.pom.xml.XmlAspect;
import com.intellij.pom.xml.XmlChangeSet;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiFileFactory;
import com.intellij.psi.PsiManager;
import com.intellij.psi.impl.PsiManagerEx;
import com.intellij.psi.xml.XmlAttribute;
import com.intellij.psi.xml.XmlElement;
import com.intellij.psi.xml.XmlFile;
import com.intellij.psi.xml.XmlTag;
import com.intellij.reference.SoftReference;
import com.intellij.semantic.SemKey;
import com.intellij.semantic.SemService;
import com.intellij.util.EventDispatcher;
import com.intellij.util.SmartList;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.xml.*;
import com.intellij.util.xml.events.DomEvent;
import com.intellij.util.xml.reflect.AbstractDomChildrenDescription;
import com.intellij.util.xml.reflect.DomGenericInfo;
import net.sf.cglib.proxy.AdvancedProxy;
import net.sf.cglib.proxy.InvocationHandler;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.lang.ref.WeakReference;
import java.lang.reflect.Type;
import java.util.*;
/**
* @author peter
*/
public final class DomManagerImpl extends DomManager {
private static final Key<Object> MOCK = Key.create("MockElement");
static final Key<WeakReference<DomFileElementImpl>> CACHED_FILE_ELEMENT = Key.create("CACHED_FILE_ELEMENT");
static final Key<DomFileDescription> MOCK_DESCRIPTION = Key.create("MockDescription");
static final SemKey<FileDescriptionCachedValueProvider> FILE_DESCRIPTION_KEY = SemKey.createKey("FILE_DESCRIPTION_KEY");
static final SemKey<DomInvocationHandler> DOM_HANDLER_KEY = SemKey.createKey("DOM_HANDLER_KEY");
static final SemKey<IndexedElementInvocationHandler> DOM_INDEXED_HANDLER_KEY = DOM_HANDLER_KEY.subKey("DOM_INDEXED_HANDLER_KEY");
static final SemKey<CollectionElementInvocationHandler> DOM_COLLECTION_HANDLER_KEY = DOM_HANDLER_KEY.subKey("DOM_COLLECTION_HANDLER_KEY");
static final SemKey<CollectionElementInvocationHandler> DOM_CUSTOM_HANDLER_KEY = DOM_HANDLER_KEY.subKey("DOM_CUSTOM_HANDLER_KEY");
static final SemKey<AttributeChildInvocationHandler> DOM_ATTRIBUTE_HANDLER_KEY = DOM_HANDLER_KEY.subKey("DOM_ATTRIBUTE_HANDLER_KEY");
private final EventDispatcher<DomEventListener> myListeners = EventDispatcher.create(DomEventListener.class);
private final Project myProject;
private final SemService mySemService;
private final DomApplicationComponent myApplicationComponent;
private boolean myChanging;
public DomManagerImpl(Project project) {
super(project);
myProject = project;
mySemService = SemService.getSemService(project);
myApplicationComponent = DomApplicationComponent.getInstance();
final PomModel pomModel = PomManager.getModel(project);
pomModel.addModelListener(new PomModelListener() {
@Override
public void modelChanged(PomModelEvent event) {
if (myChanging) return;
final XmlChangeSet changeSet = (XmlChangeSet)event.getChangeSet(pomModel.getModelAspect(XmlAspect.class));
if (changeSet != null) {
for (XmlFile file : changeSet.getChangedFiles()) {
DomFileElementImpl<DomElement> element = getCachedFileElement(file);
if (element != null) {
fireEvent(new DomEvent(element, false));
}
}
}
}
@Override
public boolean isAspectChangeInteresting(PomModelAspect aspect) {
return aspect instanceof XmlAspect;
}
}, project);
VirtualFileManager.getInstance().addVirtualFileListener(new VirtualFileListener() {
private final List<DomEvent> myDeletionEvents = new SmartList<>();
@Override
public void contentsChanged(@NotNull VirtualFileEvent event) {
if (!event.isFromSave()) {
fireEvents(calcDomChangeEvents(event.getFile()));
}
}
@Override
public void fileMoved(@NotNull VirtualFileMoveEvent event) {
fireEvents(calcDomChangeEvents(event.getFile()));
}
@Override
public void beforeFileDeletion(@NotNull final VirtualFileEvent event) {
myDeletionEvents.addAll(calcDomChangeEvents(event.getFile()));
}
@Override
public void fileDeleted(@NotNull VirtualFileEvent event) {
if (!myDeletionEvents.isEmpty()) {
fireEvents(myDeletionEvents);
myDeletionEvents.clear();
}
}
@Override
public void propertyChanged(@NotNull VirtualFilePropertyEvent event) {
final VirtualFile file = event.getFile();
if (!file.isDirectory() && VirtualFile.PROP_NAME.equals(event.getPropertyName())) {
fireEvents(calcDomChangeEvents(file));
}
}
}, myProject);
}
public long getPsiModificationCount() {
return PsiManager.getInstance(getProject()).getModificationTracker().getModificationCount();
}
public <T extends DomInvocationHandler> void cacheHandler(SemKey<T> key, XmlElement element, T handler) {
mySemService.setCachedSemElement(key, element, handler);
}
private PsiFile getCachedPsiFile(VirtualFile file) {
return PsiManagerEx.getInstanceEx(myProject).getFileManager().getCachedPsiFile(file);
}
private List<DomEvent> calcDomChangeEvents(final VirtualFile file) {
if (!(file instanceof NewVirtualFile) || myProject.isDisposed()) {
return Collections.emptyList();
}
final List<DomEvent> events = ContainerUtil.newArrayList();
VfsUtilCore.visitChildrenRecursively(file, new VirtualFileVisitor() {
@Override
public boolean visitFile(@NotNull VirtualFile file) {
if (myProject.isDisposed() || !ProjectFileIndex.SERVICE.getInstance(myProject).isInContent(file)) {
return false;
}
if (!file.isDirectory() && StdFileTypes.XML == file.getFileType()) {
final PsiFile psiFile = getCachedPsiFile(file);
if (psiFile != null && StdFileTypes.XML.equals(psiFile.getFileType()) && psiFile instanceof XmlFile) {
final DomFileElementImpl domElement = getCachedFileElement((XmlFile)psiFile);
if (domElement != null) {
events.add(new DomEvent(domElement, false));
}
}
}
return true;
}
@Nullable
@Override
public Iterable<VirtualFile> getChildrenIterable(@NotNull VirtualFile file) {
return ((NewVirtualFile)file).getCachedChildren();
}
});
return events;
}
@SuppressWarnings({"MethodOverridesStaticMethodOfSuperclass"})
public static DomManagerImpl getDomManager(Project project) {
return (DomManagerImpl)DomManager.getDomManager(project);
}
@Override
public void addDomEventListener(DomEventListener listener, Disposable parentDisposable) {
myListeners.addListener(listener, parentDisposable);
}
@Override
public final ConverterManager getConverterManager() {
return ServiceManager.getService(ConverterManager.class);
}
@Override
public final ModelMerger createModelMerger() {
return new ModelMergerImpl();
}
final void fireEvent(DomEvent event) {
if (mySemService.isInsideAtomicChange()) return;
incModificationCount();
myListeners.getMulticaster().eventOccured(event);
}
private void fireEvents(Collection<DomEvent> events) {
for (DomEvent event : events) {
fireEvent(event);
}
}
@Override
public final DomGenericInfo getGenericInfo(final Type type) {
return myApplicationComponent.getStaticGenericInfo(type);
}
@Nullable
public static DomInvocationHandler getDomInvocationHandler(DomElement proxy) {
if (proxy instanceof DomFileElement) {
return null;
}
if (proxy instanceof DomInvocationHandler) {
return (DomInvocationHandler)proxy;
}
final InvocationHandler handler = AdvancedProxy.getInvocationHandler(proxy);
if (handler instanceof StableInvocationHandler) {
//noinspection unchecked
final DomElement element = ((StableInvocationHandler<DomElement>)handler).getWrappedElement();
return element == null ? null : getDomInvocationHandler(element);
}
if (handler instanceof DomInvocationHandler) {
return (DomInvocationHandler)handler;
}
return null;
}
@NotNull
public static DomInvocationHandler getNotNullHandler(DomElement proxy) {
DomInvocationHandler handler = getDomInvocationHandler(proxy);
if (handler == null) {
throw new AssertionError("null handler for " + proxy);
}
return handler;
}
public static StableInvocationHandler getStableInvocationHandler(Object proxy) {
return (StableInvocationHandler)AdvancedProxy.getInvocationHandler(proxy);
}
public DomApplicationComponent getApplicationComponent() {
return myApplicationComponent;
}
@Override
public final Project getProject() {
return myProject;
}
@Override
@NotNull
public final <T extends DomElement> DomFileElementImpl<T> getFileElement(final XmlFile file, final Class<T> aClass, String rootTagName) {
//noinspection unchecked
if (file.getUserData(MOCK_DESCRIPTION) == null) {
file.putUserData(MOCK_DESCRIPTION, new MockDomFileDescription<>(aClass, rootTagName, file.getViewProvider().getVirtualFile()));
mySemService.clearCache();
}
final DomFileElementImpl<T> fileElement = getFileElement(file);
assert fileElement != null;
return fileElement;
}
@SuppressWarnings({"unchecked"})
@NotNull
final <T extends DomElement> FileDescriptionCachedValueProvider<T> getOrCreateCachedValueProvider(final XmlFile xmlFile) {
//noinspection ConstantConditions
return mySemService.getSemElement(FILE_DESCRIPTION_KEY, xmlFile);
}
public final Set<DomFileDescription> getFileDescriptions(String rootTagName) {
return myApplicationComponent.getFileDescriptions(rootTagName);
}
public final Set<DomFileDescription> getAcceptingOtherRootTagNameDescriptions() {
return myApplicationComponent.getAcceptingOtherRootTagNameDescriptions();
}
@NotNull
@NonNls
public final String getComponentName() {
return getClass().getName();
}
final void runChange(Runnable change) {
final boolean b = setChanging(true);
try {
change.run();
}
finally {
setChanging(b);
}
}
final boolean setChanging(final boolean changing) {
boolean oldChanging = myChanging;
if (changing) {
assert !oldChanging;
}
myChanging = changing;
return oldChanging;
}
@Override
@Nullable
public final <T extends DomElement> DomFileElementImpl<T> getFileElement(XmlFile file) {
if (file == null) return null;
if (!(file.getFileType() instanceof DomSupportEnabled)) return null;
final VirtualFile virtualFile = file.getVirtualFile();
if (virtualFile != null && virtualFile.isDirectory()) return null;
return this.<T>getOrCreateCachedValueProvider(file).getFileElement();
}
@Nullable
static <T extends DomElement> DomFileElementImpl<T> getCachedFileElement(@NotNull XmlFile file) {
//noinspection unchecked
return SoftReference.dereference(file.getUserData(CACHED_FILE_ELEMENT));
}
@Override
@Nullable
public final <T extends DomElement> DomFileElementImpl<T> getFileElement(XmlFile file, Class<T> domClass) {
final DomFileDescription description = getDomFileDescription(file);
if (description != null && myApplicationComponent.assignabilityCache.isAssignable(domClass, description.getRootElementClass())) {
return getFileElement(file);
}
return null;
}
@Override
@Nullable
public final DomElement getDomElement(final XmlTag element) {
if (myChanging) return null;
final DomInvocationHandler handler = getDomHandler(element);
return handler != null ? handler.getProxy() : null;
}
@Override
@Nullable
public GenericAttributeValue getDomElement(final XmlAttribute attribute) {
if (myChanging) return null;
final AttributeChildInvocationHandler handler = mySemService.getSemElement(DOM_ATTRIBUTE_HANDLER_KEY, attribute);
return handler == null ? null : (GenericAttributeValue)handler.getProxy();
}
@Nullable
public DomInvocationHandler getDomHandler(final XmlElement tag) {
if (tag == null) return null;
List<DomInvocationHandler> cached = mySemService.getCachedSemElements(DOM_HANDLER_KEY, tag);
if (cached != null && !cached.isEmpty()) {
return cached.get(0);
}
return mySemService.getSemElement(DOM_HANDLER_KEY, tag);
}
@Override
@Nullable
public AbstractDomChildrenDescription findChildrenDescription(@NotNull final XmlTag tag, @NotNull final DomElement parent) {
return findChildrenDescription(tag, getDomInvocationHandler(parent));
}
static AbstractDomChildrenDescription findChildrenDescription(final XmlTag tag, final DomInvocationHandler parent) {
final DomGenericInfoEx info = parent.getGenericInfo();
return info.findChildrenDescription(parent, tag.getLocalName(), tag.getNamespace(), false, tag.getName());
}
public final boolean isDomFile(@Nullable PsiFile file) {
return file instanceof XmlFile && getFileElement((XmlFile)file) != null;
}
@Nullable
public final DomFileDescription<?> getDomFileDescription(PsiElement element) {
if (element instanceof XmlElement) {
final PsiFile psiFile = element.getContainingFile();
if (psiFile instanceof XmlFile) {
return getDomFileDescription((XmlFile)psiFile);
}
}
return null;
}
@Override
public final <T extends DomElement> T createMockElement(final Class<T> aClass, final Module module, final boolean physical) {
final XmlFile file = (XmlFile)PsiFileFactory.getInstance(myProject).createFileFromText("a.xml", StdFileTypes.XML, "", (long)0, physical);
file.putUserData(MOCK_ELEMENT_MODULE, module);
file.putUserData(MOCK, new Object());
return getFileElement(file, aClass, "I_sincerely_hope_that_nobody_will_have_such_a_root_tag_name").getRootElement();
}
@Override
public final boolean isMockElement(DomElement element) {
return DomUtil.getFile(element).getUserData(MOCK) != null;
}
@Override
public final <T extends DomElement> T createStableValue(final Factory<T> provider) {
return createStableValue(provider, t -> t.isValid());
}
@Override
public final <T> T createStableValue(final Factory<T> provider, final Condition<T> validator) {
final T initial = provider.create();
assert initial != null;
final StableInvocationHandler handler = new StableInvocationHandler<>(initial, provider, validator);
final Set<Class> intf = new HashSet<>();
ContainerUtil.addAll(intf, initial.getClass().getInterfaces());
intf.add(StableElement.class);
//noinspection unchecked
return (T)AdvancedProxy.createProxy(initial.getClass().getSuperclass(), intf.toArray(new Class[intf.size()]),
handler);
}
public final <T extends DomElement> void registerFileDescription(final DomFileDescription<T> description, Disposable parentDisposable) {
registerFileDescription(description);
Disposer.register(parentDisposable, new Disposable() {
@Override
public void dispose() {
getFileDescriptions(description.getRootTagName()).remove(description);
getAcceptingOtherRootTagNameDescriptions().remove(description);
}
});
}
@Override
public final void registerFileDescription(final DomFileDescription description) {
mySemService.clearCache();
myApplicationComponent.registerFileDescription(description);
}
@Override
@NotNull
public final DomElement getResolvingScope(GenericDomValue element) {
final DomFileDescription<?> description = DomUtil.getFileElement(element).getFileDescription();
return description.getResolveScope(element);
}
@Override
@Nullable
public final DomElement getIdentityScope(DomElement element) {
final DomFileDescription description = DomUtil.getFileElement(element).getFileDescription();
return description.getIdentityScope(element);
}
@Override
public TypeChooserManager getTypeChooserManager() {
return myApplicationComponent.getTypeChooserManager();
}
public void performAtomicChange(@NotNull Runnable change) {
mySemService.performAtomicChange(change);
if (!mySemService.isInsideAtomicChange()) {
incModificationCount();
}
}
public SemService getSemService() {
return mySemService;
}
}
| apache-2.0 |
stianst/keycloak | quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/storage/database/liquibase/QuarkusLiquibaseConnectionProvider.java | 5267 | /*
* Copyright 2021 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* 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.keycloak.quarkus.runtime.storage.database.liquibase;
import java.lang.reflect.Method;
import java.sql.Connection;
import javax.xml.parsers.SAXParserFactory;
import org.jboss.logging.Logger;
import org.keycloak.Config;
import org.keycloak.connections.jpa.updater.liquibase.conn.LiquibaseConnectionProvider;
import org.keycloak.connections.jpa.updater.liquibase.conn.LiquibaseConnectionProviderFactory;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.KeycloakSessionFactory;
import liquibase.Liquibase;
import liquibase.database.Database;
import liquibase.database.DatabaseFactory;
import liquibase.database.jvm.JdbcConnection;
import liquibase.exception.LiquibaseException;
import liquibase.parser.ChangeLogParser;
import liquibase.parser.ChangeLogParserFactory;
import liquibase.parser.core.xml.XMLChangeLogSAXParser;
import liquibase.resource.ClassLoaderResourceAccessor;
import liquibase.resource.ResourceAccessor;
public class QuarkusLiquibaseConnectionProvider implements LiquibaseConnectionProviderFactory, LiquibaseConnectionProvider {
private static final Logger logger = Logger.getLogger(QuarkusLiquibaseConnectionProvider.class);
private volatile boolean initialized = false;
private ClassLoaderResourceAccessor resourceAccessor;
@Override
public LiquibaseConnectionProvider create(KeycloakSession session) {
if (!initialized) {
synchronized (this) {
if (!initialized) {
baseLiquibaseInitialization(session);
initialized = true;
}
}
}
return this;
}
protected void baseLiquibaseInitialization(KeycloakSession session) {
resourceAccessor = new ClassLoaderResourceAccessor(getClass().getClassLoader());
// disables XML validation
for (ChangeLogParser parser : ChangeLogParserFactory.getInstance().getParsers()) {
if (parser instanceof XMLChangeLogSAXParser) {
Method getSaxParserFactory = null;
try {
getSaxParserFactory = XMLChangeLogSAXParser.class.getDeclaredMethod("getSaxParserFactory");
getSaxParserFactory.setAccessible(true);
SAXParserFactory saxParserFactory = (SAXParserFactory) getSaxParserFactory.invoke(parser);
saxParserFactory.setValidating(false);
saxParserFactory.setSchema(null);
} catch (Exception e) {
logger.warnf("Failed to disable liquibase XML validations");
} finally {
if (getSaxParserFactory != null) {
getSaxParserFactory.setAccessible(false);
}
}
}
}
}
@Override
public void init(Config.Scope config) {
}
@Override
public void postInit(KeycloakSessionFactory factory) {
}
@Override
public void close() {
}
@Override
public String getId() {
return "quarkus";
}
@Override
public Liquibase getLiquibase(Connection connection, String defaultSchema) throws LiquibaseException {
Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new JdbcConnection(connection));
if (defaultSchema != null) {
database.setDefaultSchemaName(defaultSchema);
}
String changelog = QuarkusJpaUpdaterProvider.CHANGELOG;
logger.debugf("Using changelog file %s and changelogTableName %s", changelog, database.getDatabaseChangeLogTableName());
return new Liquibase(changelog, resourceAccessor, database);
}
@Override
public Liquibase getLiquibaseForCustomUpdate(Connection connection, String defaultSchema, String changelogLocation, ClassLoader classloader, String changelogTableName) throws LiquibaseException {
Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new JdbcConnection(connection));
if (defaultSchema != null) {
database.setDefaultSchemaName(defaultSchema);
}
ResourceAccessor resourceAccessor = new ClassLoaderResourceAccessor(classloader);
database.setDatabaseChangeLogTableName(changelogTableName);
logger.debugf("Using changelog file %s and changelogTableName %s", changelogLocation, database.getDatabaseChangeLogTableName());
return new Liquibase(changelogLocation, resourceAccessor, database);
}
@Override
public int order() {
return 100;
}
}
| apache-2.0 |
robertoschwald/cas | core/cas-server-core-webflow/src/test/java/org/apereo/cas/web/flow/actions/RedirectToServiceActionTests.java | 2947 | package org.apereo.cas.web.flow.actions;
import org.apereo.cas.authentication.CoreAuthenticationTestUtils;
import org.apereo.cas.authentication.principal.ResponseBuilderLocator;
import org.apereo.cas.authentication.principal.WebApplicationService;
import org.apereo.cas.authentication.principal.WebApplicationServiceResponseBuilder;
import org.apereo.cas.config.CasCoreServicesConfiguration;
import org.apereo.cas.config.CasCoreUtilConfiguration;
import org.apereo.cas.services.ServicesManager;
import org.apereo.cas.web.flow.CasWebflowConstants;
import org.apereo.cas.web.support.WebUtils;
import lombok.val;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.autoconfigure.RefreshAutoConfiguration;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockServletContext;
import org.springframework.test.context.junit4.rules.SpringClassRule;
import org.springframework.test.context.junit4.rules.SpringMethodRule;
import org.springframework.webflow.context.servlet.ServletExternalContext;
import org.springframework.webflow.test.MockRequestContext;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
/**
* This is {@link RedirectToServiceActionTests}.
*
* @author Misagh Moayyed
* @since 5.3.0
*/
@SpringBootTest(classes = {
RefreshAutoConfiguration.class,
CasCoreServicesConfiguration.class,
CasCoreUtilConfiguration.class
})
public class RedirectToServiceActionTests {
@ClassRule
public static final SpringClassRule SPRING_CLASS_RULE = new SpringClassRule();
@Rule
public final SpringMethodRule springMethodRule = new SpringMethodRule();
@Autowired
@Qualifier("servicesManager")
private ServicesManager servicesManager;
@Test
public void verifyAction() throws Exception {
val context = new MockRequestContext();
val request = new MockHttpServletRequest();
context.setExternalContext(new ServletExternalContext(new MockServletContext(), request, new MockHttpServletResponse()));
WebUtils.putAuthentication(CoreAuthenticationTestUtils.getAuthentication(), context);
WebUtils.putService(context, CoreAuthenticationTestUtils.getWebApplicationService());
val locator = mock(ResponseBuilderLocator.class);
when(locator.locate(any(WebApplicationService.class))).thenReturn(new WebApplicationServiceResponseBuilder(this.servicesManager));
val redirectToServiceAction = new RedirectToServiceAction(locator);
val event = redirectToServiceAction.execute(context);
assertEquals(CasWebflowConstants.TRANSITION_ID_REDIRECT, event.getId());
}
}
| apache-2.0 |
tkaefer/camunda-bpm-platform | engine-rest/src/test/java/org/camunda/bpm/engine/rest/wink/MessageRestServiceTest.java | 629 | package org.camunda.bpm.engine.rest.wink;
import org.camunda.bpm.engine.rest.AbstractMessageRestServiceTest;
import org.camunda.bpm.engine.rest.util.WinkTomcatServerBootstrap;
import org.junit.AfterClass;
import org.junit.BeforeClass;
public class MessageRestServiceTest extends AbstractMessageRestServiceTest {
protected static WinkTomcatServerBootstrap serverBootstrap;
@BeforeClass
public static void setUpEmbeddedRuntime() {
serverBootstrap = new WinkTomcatServerBootstrap();
serverBootstrap.start();
}
@AfterClass
public static void tearDownEmbeddedRuntime() {
serverBootstrap.stop();
}
}
| apache-2.0 |
jboss-developer/jboss-wfk-quickstarts | deltaspike-partialbean-basic/src/main/java/org/jboss/as/quickstart/deltaspike/partialbean/ExamplePartialBeanImplementation.java | 1876 | /*
* JBoss, Home of Professional Open Source
* Copyright 2014, Red Hat, Inc. and/or its affiliates, and individual
* contributors by the @authors tag. See the copyright.txt in the
* distribution for a full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.as.quickstart.deltaspike.partialbean;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import javax.enterprise.context.ApplicationScoped;
/**
* This class implements a dynamic DeltaSpike Partial Bean. It is bound to
* one or more abstract classes or interfaces via the Binding Annotation
* (@ExamplePartialBeanBinding below).
*
* All abstract, unimplemented methods from those beans will be implemented
* via the invoke method.
*
*/
@ExamplePartialBeanBinding
@ApplicationScoped
public class ExamplePartialBeanImplementation implements InvocationHandler {
/**
* In our example, this method will be invoked when the "sayHello" method is called.
*
* @param proxy The object upon which the method is being invoked.
* @param method The method being invoked (sayHello in this QuickStart)
* @param args The arguments being passed in to the invoked method
*/
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
return "Hello " + args[0];
}
}
| apache-2.0 |
jmartisk/hibernate-validator | engine/src/main/java/org/hibernate/validator/cfg/defs/EmailDef.java | 1337 | /*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat, Inc. and/or its affiliates, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hibernate.validator.cfg.defs;
import javax.validation.constraints.Pattern;
import org.hibernate.validator.cfg.ConstraintDef;
import org.hibernate.validator.constraints.Email;
/**
* @author Hardy Ferentschik
*/
public class EmailDef extends ConstraintDef<EmailDef, Email> {
public EmailDef() {
super( Email.class );
}
public EmailDef regexp(String regexp) {
addParameter( "regexp", regexp );
return this;
}
public EmailDef flags(Pattern.Flag... flags) {
addParameter( "flags", flags );
return this;
}
}
| apache-2.0 |
UAK-35/wro4j | wro4j-core/src/test/java/ro/isdc/wro/model/resource/processor/TestConformColorsCssProcessor.java | 1512 | /*
* Copyright (c) 2010. All rights reserved.
*/
package ro.isdc.wro.model.resource.processor;
import static org.junit.Assert.assertEquals;
import java.io.File;
import java.net.URL;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import ro.isdc.wro.config.Context;
import ro.isdc.wro.model.resource.ResourceType;
import ro.isdc.wro.model.resource.processor.impl.css.ConformColorsCssProcessor;
import ro.isdc.wro.util.WroTestUtils;
/**
* TestConformColorsCssProcessor.
*
* @author Alex Objelean
* @created Created on Aug 15, 2010
*/
public class TestConformColorsCssProcessor {
private ResourcePreProcessor processor;
@BeforeClass
public static void onBeforeClass() {
assertEquals(0, Context.countActive());
}
@AfterClass
public static void onAfterClass() {
assertEquals(0, Context.countActive());
}
@Before
public void setUp() {
processor = new ConformColorsCssProcessor();
}
@Test
public void testFromFolder()
throws Exception {
final URL url = getClass().getResource("conformColors");
final File testFolder = new File(url.getFile(), "test");
final File expectedFolder = new File(url.getFile(), "expected");
WroTestUtils.compareFromDifferentFoldersByExtension(testFolder, expectedFolder, "css", processor);
}
@Test
public void shouldSupportCorrectResourceTypes() {
WroTestUtils.assertProcessorSupportResourceTypes(processor, ResourceType.CSS);
}
}
| apache-2.0 |
dakshika/product-mss | samples/petstore/frontend-util/src/main/java/org/wso2/carbon/mss/examples/petstore/util/fe/view/NavigationBean.java | 1401 | /*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.wso2.carbon.mss.examples.petstore.util.fe.view;
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
/**
* Bean classes used for JSF model.
*/
@ManagedBean
@SessionScoped
public class NavigationBean implements Serializable {
private static final long serialVersionUID = -8628674465932953415L;
public String redirectToStoreWelcome() {
return "pet/list.xhtml?faces-redirect=true";
}
public String redirectToAdminWelcome() {
return "pet/index.xhtml?faces-redirect=true";
}
public String toLogin() {
return "/login.xhtml";
}
public String backtoList() {
return "list";
}
}
| apache-2.0 |
darshanasbg/identity-inbound-auth-oauth | components/org.wso2.carbon.identity.oauth/src/test/java/org/wso2/carbon/identity/oauth2/validators/OAuth2TokenValidationMessageContextTest.java | 2398 | /*
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.wso2.carbon.identity.oauth2.validators;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import org.wso2.carbon.identity.oauth2.dto.OAuth2TokenValidationRequestDTO;
import org.wso2.carbon.identity.oauth2.dto.OAuth2TokenValidationResponseDTO;
import static org.testng.Assert.assertEquals;
public class OAuth2TokenValidationMessageContextTest {
private OAuth2TokenValidationMessageContext oAuth2TokenValidationMessageContext;
private OAuth2TokenValidationRequestDTO requestDTO;
private OAuth2TokenValidationResponseDTO responseDTO;
@BeforeMethod
public void setUp() throws Exception {
requestDTO = new OAuth2TokenValidationRequestDTO();
responseDTO = new OAuth2TokenValidationResponseDTO();
oAuth2TokenValidationMessageContext = new OAuth2TokenValidationMessageContext(requestDTO, responseDTO);
}
@Test
public void testGetRequestDTO() throws Exception {
assertEquals(oAuth2TokenValidationMessageContext.getRequestDTO(), requestDTO);
}
@Test
public void testGetResponseDTO() throws Exception {
assertEquals(oAuth2TokenValidationMessageContext.getResponseDTO(), responseDTO);
}
@Test
public void testAddProperty() throws Exception {
oAuth2TokenValidationMessageContext.addProperty("testProperty", "testValue");
assertEquals(oAuth2TokenValidationMessageContext.getProperty("testProperty"), "testValue");
}
@Test
public void testGetProperty() throws Exception {
oAuth2TokenValidationMessageContext.addProperty("testProperty", "testValue");
assertEquals(oAuth2TokenValidationMessageContext.getProperty("testProperty"), "testValue");
}
}
| apache-2.0 |
chubbymaggie/binnavi | src/main/java/com/google/security/zynamics/binnavi/disassembly/INaviEdgeListener.java | 1248 | /*
Copyright 2011-2016 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.security.zynamics.binnavi.disassembly;
import com.google.security.zynamics.zylib.gui.zygraph.edges.IViewEdgeListener;
/**
* Interface for objects that want to be notified about changes in edges.
*/
public interface INaviEdgeListener extends IViewEdgeListener {
/**
* Invoked after the global comment of an edge changed.
*
* @param naviEdge The edge whose global comment changed.
*/
void changedGlobalComment(CNaviViewEdge naviEdge);
/**
* Invoked after the local comment of an edge changed.
*
* @param naviEdge The edge whose local comment changed.
*/
void changedLocalComment(CNaviViewEdge naviEdge);
}
| apache-2.0 |
billkalter/emodb | common/dropwizard/src/main/java/com/bazaarvoice/emodb/common/dropwizard/leader/LeaderServiceTask.java | 5047 | package com.bazaarvoice.emodb.common.dropwizard.leader;
import com.bazaarvoice.curator.recipes.leader.LeaderService;
import com.bazaarvoice.emodb.common.dropwizard.task.TaskRegistry;
import com.bazaarvoice.emodb.common.zookeeper.leader.PartitionedLeaderService;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.Maps;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.common.util.concurrent.Service;
import com.google.inject.Inject;
import io.dropwizard.servlets.tasks.Task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.PrintWriter;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentMap;
/**
* Shows the current status of leadership processes managed by {@link LeaderService}. Allows terminating
* individual leadership processes, but such that they can be restarted only by restarting the entire server.
*/
public class LeaderServiceTask extends Task {
private static final Logger _log = LoggerFactory.getLogger(LeaderServiceTask.class);
private final ConcurrentMap<String, LeaderService> _selectorMap = Maps.newConcurrentMap();
@Inject
public LeaderServiceTask(TaskRegistry tasks) {
super("leader");
tasks.addTask(this);
}
public void register(final String name, final LeaderService leaderService) {
_selectorMap.put(name, leaderService);
// Unregister automatically to avoid memory leaks.
leaderService.addListener(new AbstractServiceListener() {
@Override
public void terminated(Service.State from) {
unregister(name, leaderService);
}
@Override
public void failed(Service.State from, Throwable failure) {
unregister(name, leaderService);
}
}, MoreExecutors.sameThreadExecutor());
}
public void register(final String name, final PartitionedLeaderService partitionedLeaderService) {
int partition = 0;
for (LeaderService leaderService : partitionedLeaderService.getPartitionLeaderServices()) {
register(String.format("%s-%d", name, partition++), leaderService);
}
}
public void unregister(String name, LeaderService leaderService) {
_selectorMap.remove(name, leaderService);
}
@Override
public void execute(ImmutableMultimap<String, String> parameters, PrintWriter out) throws Exception {
// The 'release' argument tells a server to give up leadership and let a new leader be elected, possibly
// re-electing the current server. This is useful for rebalancing leader-controlled activities.
for (String name : parameters.get("release")) {
LeaderService leaderService = _selectorMap.get(name);
if (leaderService == null) {
out.printf("Unknown leader process: %s%n", name);
continue;
}
Service actualService = leaderService.getCurrentDelegateService().orNull();
if (actualService == null || !actualService.isRunning()) {
out.printf("Process is not currently elected leader: %s%n", name);
continue;
}
_log.warn("Temporarily releasing leadership for process: {}", name);
out.printf("Temporarily releasing leadership for process: %s, cluster will elect a new leader.%n", name);
actualService.stopAndWait();
}
// The 'terminate' argument tells a server to give up leadership permanently (or until the server restarts).
for (String name : parameters.get("terminate")) {
LeaderService leaderService = _selectorMap.get(name);
if (leaderService == null) {
out.printf("Unknown leader process: %s%n", name);
continue;
}
_log.warn("Terminating leader process for: {}", name);
out.printf("Terminating leader process for: %s. Restart the server to restart the leader process.%n", name);
leaderService.stopAndWait();
}
// Print current status.
for (Map.Entry<String, LeaderService> entry : new TreeMap<>(_selectorMap).entrySet()) {
String name = entry.getKey();
LeaderService leaderService = entry.getValue();
out.printf("%s: %s (leader=%s)%n", name,
describeState(leaderService.state(), leaderService.hasLeadership()),
getLeaderId(leaderService));
}
}
private String describeState(Service.State state, boolean hasLeadership) {
if (state == Service.State.RUNNING && !hasLeadership) {
return "waiting to win leadership election";
} else {
return state.name();
}
}
private String getLeaderId(LeaderService leaderService) {
try {
return leaderService.getLeader().getId();
} catch (Exception e) {
return "<unknown>";
}
}
}
| apache-2.0 |
bazaarvoice/es-client-java | es-rest-client-1.3/core/src/main/java/org/elasticsearch/action/get/GetRest.java | 2328 | package org.elasticsearch.action.get;
import com.bazaarvoice.elasticsearch.client.core.spi.RestExecutor;
import com.bazaarvoice.elasticsearch.client.core.spi.RestResponse;
import com.bazaarvoice.elasticsearch.client.core.util.UrlBuilder;
import org.elasticsearch.action.AbstractRestClientAction;
import org.elasticsearch.common.base.Function;
import org.elasticsearch.common.util.concurrent.Futures;
import org.elasticsearch.common.util.concurrent.ListenableFuture;
import static com.bazaarvoice.elasticsearch.client.core.util.StringFunctions.booleanToString;
import static com.bazaarvoice.elasticsearch.client.core.util.StringFunctions.commaDelimitedToString;
import static com.bazaarvoice.elasticsearch.client.core.util.UrlBuilder.urlEncode;
import static com.bazaarvoice.elasticsearch.client.core.util.Validation.notNull;
import static org.elasticsearch.common.base.Optional.fromNullable;
/**
* The inverse of {@link org.elasticsearch.rest.action.get.RestGetAction}
*
* @param <ResponseType>
*/
public class GetRest<ResponseType> extends AbstractRestClientAction<GetRequest, ResponseType> {
public GetRest(final String protocol, final String host, final int port, final RestExecutor executor, final Function<RestResponse, ResponseType> responseTransform) {
super(protocol, host, port, executor, responseTransform);
}
@Override public ListenableFuture<ResponseType> act(GetRequest request) {
UrlBuilder url = UrlBuilder.create()
.protocol(protocol).host(host).port(port)
.path(urlEncode(notNull(request.index())))
.seg(urlEncode(notNull(request.type())))
.seg(urlEncode(notNull(request.id())))
.paramIfPresent("refresh", fromNullable(request.refresh()).transform(booleanToString))
.paramIfPresent("routing", fromNullable(request.routing()))
// note parent(string) seems just to set the routing, so we don't need to provide it here
.paramIfPresent("preference", fromNullable(request.preference()))
.paramIfPresent("realtime", fromNullable(request.realtime()).transform(booleanToString))
.paramIfPresent("fields", fromNullable(request.fields()).transform(commaDelimitedToString));
return Futures.transform(executor.get(url.url()), responseTransform);
}
}
| apache-2.0 |
benmccann/pdfbox | tools/src/main/java/org/apache/pdfbox/tools/TextToPDF.java | 11926 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.pdfbox.tools;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.HashMap;
import java.util.Map;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDType0Font;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
/**
* This will take a text file and ouput a pdf with that text.
*
* @author Ben Litchfield
*/
public class TextToPDF
{
/**
* The scaling factor for font units to PDF units
*/
private static final int FONTSCALE = 1000;
/**
* The default font
*/
private static final PDType1Font DEFAULT_FONT = PDType1Font.HELVETICA;
/**
* The default font size
*/
private static final int DEFAULT_FONT_SIZE = 10;
/**
* The line height as a factor of the font size
*/
private static final float LINE_HEIGHT_FACTOR = 1.05f;
private int fontSize = DEFAULT_FONT_SIZE;
private PDFont font = DEFAULT_FONT;
private static final Map<String, PDType1Font> STANDARD_14 = new HashMap<String, PDType1Font>();
static
{
STANDARD_14.put(PDType1Font.TIMES_ROMAN.getBaseFont(), PDType1Font.TIMES_ROMAN);
STANDARD_14.put(PDType1Font.TIMES_BOLD.getBaseFont(), PDType1Font.TIMES_BOLD);
STANDARD_14.put(PDType1Font.TIMES_ITALIC.getBaseFont(), PDType1Font.TIMES_ITALIC);
STANDARD_14.put(PDType1Font.TIMES_BOLD_ITALIC.getBaseFont(), PDType1Font.TIMES_BOLD_ITALIC);
STANDARD_14.put(PDType1Font.HELVETICA.getBaseFont(), PDType1Font.HELVETICA);
STANDARD_14.put(PDType1Font.HELVETICA_BOLD.getBaseFont(), PDType1Font.HELVETICA_BOLD);
STANDARD_14.put(PDType1Font.HELVETICA_OBLIQUE.getBaseFont(), PDType1Font.HELVETICA_OBLIQUE);
STANDARD_14.put(PDType1Font.HELVETICA_BOLD_OBLIQUE.getBaseFont(), PDType1Font.HELVETICA_BOLD_OBLIQUE);
STANDARD_14.put(PDType1Font.COURIER.getBaseFont(), PDType1Font.COURIER);
STANDARD_14.put(PDType1Font.COURIER_BOLD.getBaseFont(), PDType1Font.COURIER_BOLD);
STANDARD_14.put(PDType1Font.COURIER_OBLIQUE.getBaseFont(), PDType1Font.COURIER_OBLIQUE);
STANDARD_14.put(PDType1Font.COURIER_BOLD_OBLIQUE.getBaseFont(), PDType1Font.COURIER_BOLD_OBLIQUE);
STANDARD_14.put(PDType1Font.SYMBOL.getBaseFont(), PDType1Font.SYMBOL);
STANDARD_14.put(PDType1Font.ZAPF_DINGBATS.getBaseFont(), PDType1Font.ZAPF_DINGBATS);
}
/**
* Create a PDF document with some text.
*
* @param text The stream of text data.
*
* @return The document with the text in it.
*
* @throws IOException If there is an error writing the data.
*/
public PDDocument createPDFFromText( Reader text ) throws IOException
{
PDDocument doc = new PDDocument();
createPDFFromText(doc, text);
return doc;
}
/**
* Create a PDF document with some text.
*
* @param text The stream of text data.
*
* @throws IOException If there is an error writing the data.
*/
public void createPDFFromText( PDDocument doc, Reader text ) throws IOException
{
try
{
final int margin = 40;
float height = font.getBoundingBox().getHeight() / FONTSCALE;
//calculate font height and increase by a factor.
height = height*fontSize*LINE_HEIGHT_FACTOR;
BufferedReader data = new BufferedReader( text );
String nextLine = null;
PDPage page = new PDPage();
PDPageContentStream contentStream = null;
float y = -1;
float maxStringLength = page.getMediaBox().getWidth() - 2*margin;
// There is a special case of creating a PDF document from an empty string.
boolean textIsEmpty = true;
while( (nextLine = data.readLine()) != null )
{
// The input text is nonEmpty. New pages will be created and added
// to the PDF document as they are needed, depending on the length of
// the text.
textIsEmpty = false;
String[] lineWords = nextLine.trim().split( " " );
int lineIndex = 0;
while( lineIndex < lineWords.length )
{
StringBuilder nextLineToDraw = new StringBuilder();
float lengthIfUsingNextWord = 0;
do
{
nextLineToDraw.append( lineWords[lineIndex] );
nextLineToDraw.append( " " );
lineIndex++;
if( lineIndex < lineWords.length )
{
String lineWithNextWord = nextLineToDraw.toString() + lineWords[lineIndex];
lengthIfUsingNextWord =
(font.getStringWidth( lineWithNextWord )/FONTSCALE) * fontSize;
}
}
while( lineIndex < lineWords.length &&
lengthIfUsingNextWord < maxStringLength );
if( y < margin )
{
// We have crossed the end-of-page boundary and need to extend the
// document by another page.
page = new PDPage();
doc.addPage( page );
if( contentStream != null )
{
contentStream.endText();
contentStream.close();
}
contentStream = new PDPageContentStream(doc, page);
contentStream.setFont( font, fontSize );
contentStream.beginText();
y = page.getMediaBox().getHeight() - margin + height;
contentStream.newLineAtOffset(
margin, y);
}
if( contentStream == null )
{
throw new IOException( "Error:Expected non-null content stream." );
}
contentStream.newLineAtOffset(0, -height);
y -= height;
contentStream.showText(nextLineToDraw.toString());
}
}
// If the input text was the empty string, then the above while loop will have short-circuited
// and we will not have added any PDPages to the document.
// So in order to make the resultant PDF document readable by Adobe Reader etc, we'll add an empty page.
if (textIsEmpty)
{
doc.addPage(page);
}
if( contentStream != null )
{
contentStream.endText();
contentStream.close();
}
}
catch( IOException io )
{
if( doc != null )
{
doc.close();
}
throw io;
}
}
/**
* This will create a PDF document with some text in it.
* <br />
* see usage() for commandline
*
* @param args Command line arguments.
*
* @throws IOException If there is an error with the PDF.
*/
public static void main(String[] args) throws IOException
{
// suppress the Dock icon on OS X
System.setProperty("apple.awt.UIElement", "true");
TextToPDF app = new TextToPDF();
PDDocument doc = new PDDocument();
try
{
if( args.length < 2 )
{
app.usage();
}
else
{
for( int i=0; i<args.length-2; i++ )
{
if( args[i].equals( "-standardFont" ))
{
i++;
app.setFont( getStandardFont( args[i] ));
}
else if( args[i].equals( "-ttf" ))
{
i++;
PDFont font = PDType0Font.load( doc, new File( args[i]) );
app.setFont( font );
}
else if( args[i].equals( "-fontSize" ))
{
i++;
app.setFontSize( Integer.parseInt( args[i] ) );
}
else
{
throw new IOException( "Unknown argument:" + args[i] );
}
}
app.createPDFFromText( doc, new FileReader( args[args.length-1] ) );
doc.save( args[args.length-2] );
}
}
finally
{
doc.close();
}
}
/**
* This will print out a message telling how to use this example.
*/
private void usage()
{
String[] std14 = getStandard14Names();
StringBuilder message = new StringBuilder();
message.append("Usage: jar -jar pdfbox-app-x.y.z.jar TextToPDF [options] <outputfile> <textfile>\n");
message.append("\nOptions:\n");
message.append(" -standardFont <name> : " + DEFAULT_FONT.getBaseFont() + " (default)\n");
for (String std14String : std14)
{
message.append(" " + std14String + "\n");
}
message.append(" -ttf <ttf file> : The TTF font to use.\n");
message.append(" -fontSize <fontSize> : default: " + DEFAULT_FONT_SIZE );
System.err.println(message.toString());
System.exit(1);
}
/**
* A convenience method to get one of the standard 14 font from name.
*
* @param name The name of the font to get.
*
* @return The font that matches the name or null if it does not exist.
*/
private static PDType1Font getStandardFont(String name)
{
return STANDARD_14.get(name);
}
/**
* This will get the names of the standard 14 fonts.
*
* @return An array of the names of the standard 14 fonts.
*/
private static String[] getStandard14Names()
{
return STANDARD_14.keySet().toArray(new String[14]);
}
/**
* @return Returns the font.
*/
public PDFont getFont()
{
return font;
}
/**
* @param aFont The font to set.
*/
public void setFont(PDFont aFont)
{
this.font = aFont;
}
/**
* @return Returns the fontSize.
*/
public int getFontSize()
{
return fontSize;
}
/**
* @param aFontSize The fontSize to set.
*/
public void setFontSize(int aFontSize)
{
this.fontSize = aFontSize;
}
}
| apache-2.0 |
sidgoyal/standards.jsr352.jbatch | javax.batch/src/main/java/javax/batch/api/chunk/listener/AbstractItemWriteListener.java | 2264 | /*
* Copyright 2012 International Business Machines Corp.
*
* See the NOTICE file distributed with this work for additional information
* regarding copyright ownership. 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 javax.batch.api.chunk.listener;
import java.util.List;
/**
* The AbstractItemWriteListener provides default
* implementations of less commonly implemented methods.
*/
public abstract class AbstractItemWriteListener implements
ItemWriteListener {
/**
* Override this method if the ItemWriteListener
* will do something before the items are written.
* The default implementation does nothing.
*
* @param items specifies the items about to be
* written.
* @throws Exception (or subclass) if an error occurs.
*/
@Override
public void beforeWrite(List<Object> items) throws Exception {}
/**
* Override this method if the ItemWriteListener
* will do something after the items are written.
* The default implementation does nothing.
*
* @param items specifies the items about to be
* written.
* @throws Exception (or subclass) if an error occurs.
*/
@Override
public void afterWrite(List<Object> items) throws Exception {}
/**
* Override this method if the ItemWriteListener
* will do something when the ItemWriter writeItems
* method throws an exception.
* The default implementation does nothing.
*
* @param items specifies the items about to be
* written.
* @param ex specifies the exception thrown by the item
* writer.
* @throws Exception (or subclass) if an error occurs.
*/
@Override
public void onWriteError(List<Object> items, Exception ex) throws Exception {}
}
| apache-2.0 |
akdasari/SparkIntegration | src/test/java/org/sparkcommerce/core/payment/service/NullPaymentGatewayConfigurationImpl.java | 3194 | /*
* #%L
* SparkCommerce Framework Web
* %%
* Copyright (C) 2009 - 2013 Spark Commerce
* %%
* 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 org.sparkcommerce.core.payment.service;
import org.sparkcommerce.common.payment.PaymentGatewayType;
import org.springframework.stereotype.Service;
/**
* In order to use load this demo service, you will need to component scan
* the package "com.mycompany.sample".
*
* This should NOT be used in production, and is meant solely for demonstration
* purposes only.
*
* @author Elbert Bautista (elbertbautista)
*/
@Service("blNullPaymentGatewayConfiguration")
public class NullPaymentGatewayConfigurationImpl implements NullPaymentGatewayConfiguration {
protected int failureReportingThreshold = 1;
protected boolean performAuthorizeAndCapture = true;
@Override
public String getTransparentRedirectUrl() {
return "/null-checkout/process";
}
@Override
public String getTransparentRedirectReturnUrl() {
return "/null-checkout/return";
}
@Override
public boolean isPerformAuthorizeAndCapture() {
return true;
}
@Override
public void setPerformAuthorizeAndCapture(boolean performAuthorizeAndCapture) {
this.performAuthorizeAndCapture = performAuthorizeAndCapture;
}
@Override
public int getFailureReportingThreshold() {
return failureReportingThreshold;
}
@Override
public void setFailureReportingThreshold(int failureReportingThreshold) {
this.failureReportingThreshold = failureReportingThreshold;
}
@Override
public boolean handlesAuthorize() {
return true;
}
@Override
public boolean handlesCapture() {
return false;
}
@Override
public boolean handlesAuthorizeAndCapture() {
return true;
}
@Override
public boolean handlesReverseAuthorize() {
return false;
}
@Override
public boolean handlesVoid() {
return false;
}
@Override
public boolean handlesRefund() {
return false;
}
@Override
public boolean handlesPartialCapture() {
return false;
}
@Override
public boolean handlesMultipleShipment() {
return false;
}
@Override
public boolean handlesRecurringPayment() {
return false;
}
@Override
public boolean handlesSavedCustomerPayment() {
return false;
}
@Override
public boolean handlesMultiplePayments() {
return false;
}
@Override
public PaymentGatewayType getGatewayType() {
return NullPaymentGatewayType.NULL_GATEWAY;
}
}
| apache-2.0 |
zstackorg/zstack | sdk/src/main/java/org/zstack/sdk/zwatch/thirdparty/api/QueryThirdpartyAlertResult.java | 513 | package org.zstack.sdk.zwatch.thirdparty.api;
public class QueryThirdpartyAlertResult {
public java.util.List inventories;
public void setInventories(java.util.List inventories) {
this.inventories = inventories;
}
public java.util.List getInventories() {
return this.inventories;
}
public java.lang.Long total;
public void setTotal(java.lang.Long total) {
this.total = total;
}
public java.lang.Long getTotal() {
return this.total;
}
}
| apache-2.0 |
dpursehouse/elasticsearch | core/src/test/java/org/elasticsearch/discovery/zen/publish/PublishClusterStateActionTests.java | 44836 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.discovery.zen.publish;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.Version;
import org.elasticsearch.cluster.ClusterChangedEvent;
import org.elasticsearch.cluster.ClusterName;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.ClusterStateListener;
import org.elasticsearch.cluster.Diff;
import org.elasticsearch.cluster.block.ClusterBlocks;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.cluster.metadata.MetaData;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.Randomness;
import org.elasticsearch.common.collect.ImmutableOpenMap;
import org.elasticsearch.common.collect.Tuple;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.logging.ESLogger;
import org.elasticsearch.common.settings.ClusterSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.discovery.Discovery;
import org.elasticsearch.discovery.DiscoverySettings;
import org.elasticsearch.discovery.zen.DiscoveryNodesProvider;
import org.elasticsearch.env.NodeEnvironment;
import org.elasticsearch.node.Node;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.test.junit.annotations.TestLogging;
import org.elasticsearch.test.transport.MockTransportService;
import org.elasticsearch.threadpool.TestThreadPool;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.transport.BytesTransportRequest;
import org.elasticsearch.transport.TransportChannel;
import org.elasticsearch.transport.TransportConnectionListener;
import org.elasticsearch.transport.TransportResponse;
import org.elasticsearch.transport.TransportResponseOptions;
import org.elasticsearch.transport.TransportService;
import org.junit.After;
import org.junit.Before;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Supplier;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.emptyIterable;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasToString;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
@TestLogging("discovery.zen.publish:TRACE")
public class PublishClusterStateActionTests extends ESTestCase {
private static final ClusterName CLUSTER_NAME = ClusterName.CLUSTER_NAME_SETTING.getDefault(Settings.EMPTY);
protected ThreadPool threadPool;
protected Map<String, MockNode> nodes = new HashMap<>();
public static class MockNode implements PublishClusterStateAction.NewPendingClusterStateListener, DiscoveryNodesProvider {
public final DiscoveryNode discoveryNode;
public final MockTransportService service;
public MockPublishAction action;
public final ClusterStateListener listener;
public volatile ClusterState clusterState;
private final ESLogger logger;
public MockNode(DiscoveryNode discoveryNode, MockTransportService service, @Nullable ClusterStateListener listener, ESLogger logger) {
this.discoveryNode = discoveryNode;
this.service = service;
this.listener = listener;
this.logger = logger;
this.clusterState = ClusterState.builder(CLUSTER_NAME).nodes(DiscoveryNodes.builder().put(discoveryNode).localNodeId(discoveryNode.getId()).build()).build();
}
public MockNode setAsMaster() {
this.clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder(clusterState.nodes()).masterNodeId(discoveryNode.getId())).build();
return this;
}
public MockNode resetMasterId() {
this.clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder(clusterState.nodes()).masterNodeId(null)).build();
return this;
}
public void connectTo(DiscoveryNode node) {
service.connectToNode(node);
}
@Override
public void onNewClusterState(String reason) {
ClusterState newClusterState = action.pendingStatesQueue().getNextClusterStateToProcess();
logger.debug("[{}] received version [{}], uuid [{}]", discoveryNode.getName(), newClusterState.version(), newClusterState.stateUUID());
if (listener != null) {
ClusterChangedEvent event = new ClusterChangedEvent("", newClusterState, clusterState);
listener.clusterChanged(event);
}
if (clusterState.nodes().getMasterNode() == null || newClusterState.supersedes(clusterState)) {
clusterState = newClusterState;
}
action.pendingStatesQueue().markAsProcessed(newClusterState);
}
@Override
public DiscoveryNodes nodes() {
return clusterState.nodes();
}
}
public MockNode createMockNode(final String name) throws Exception {
return createMockNode(name, Settings.EMPTY);
}
public MockNode createMockNode(String name, Settings settings) throws Exception {
return createMockNode(name, settings, null);
}
public MockNode createMockNode(String name, final Settings basSettings, @Nullable ClusterStateListener listener) throws Exception {
final Settings settings = Settings.builder()
.put("name", name)
.put(TransportService.TRACE_LOG_INCLUDE_SETTING.getKey(), "", TransportService.TRACE_LOG_EXCLUDE_SETTING.getKey(), "NOTHING")
.put(basSettings)
.build();
MockTransportService service = buildTransportService(settings);
DiscoveryNode discoveryNode = DiscoveryNode.createLocal(settings, service.boundAddress().publishAddress(),
NodeEnvironment.generateNodeId(settings));
MockNode node = new MockNode(discoveryNode, service, listener, logger);
node.action = buildPublishClusterStateAction(settings, service, () -> node.clusterState, node);
final CountDownLatch latch = new CountDownLatch(nodes.size() * 2 + 1);
TransportConnectionListener waitForConnection = new TransportConnectionListener() {
@Override
public void onNodeConnected(DiscoveryNode node) {
latch.countDown();
}
@Override
public void onNodeDisconnected(DiscoveryNode node) {
fail("disconnect should not be called " + node);
}
};
node.service.addConnectionListener(waitForConnection);
for (MockNode curNode : nodes.values()) {
curNode.service.addConnectionListener(waitForConnection);
curNode.connectTo(node.discoveryNode);
node.connectTo(curNode.discoveryNode);
}
node.connectTo(node.discoveryNode);
assertThat("failed to wait for all nodes to connect", latch.await(5, TimeUnit.SECONDS), equalTo(true));
for (MockNode curNode : nodes.values()) {
curNode.service.removeConnectionListener(waitForConnection);
}
node.service.removeConnectionListener(waitForConnection);
if (nodes.put(name, node) != null) {
fail("Node with the name " + name + " already exist");
}
return node;
}
public MockTransportService service(String name) {
MockNode node = nodes.get(name);
if (node != null) {
return node.service;
}
return null;
}
public PublishClusterStateAction action(String name) {
MockNode node = nodes.get(name);
if (node != null) {
return node.action;
}
return null;
}
@Override
@Before
public void setUp() throws Exception {
super.setUp();
threadPool = new TestThreadPool(getClass().getName());
}
@Override
@After
public void tearDown() throws Exception {
super.tearDown();
for (MockNode curNode : nodes.values()) {
curNode.action.close();
curNode.service.close();
}
terminate(threadPool);
}
protected MockTransportService buildTransportService(Settings settings) {
MockTransportService transportService = MockTransportService.local(Settings.EMPTY, Version.CURRENT, threadPool);
transportService.start();
transportService.acceptIncomingRequests();
return transportService;
}
protected MockPublishAction buildPublishClusterStateAction(
Settings settings,
MockTransportService transportService,
Supplier<ClusterState> clusterStateSupplier,
PublishClusterStateAction.NewPendingClusterStateListener listener
) {
DiscoverySettings discoverySettings =
new DiscoverySettings(settings, new ClusterSettings(settings, ClusterSettings.BUILT_IN_CLUSTER_SETTINGS));
return new MockPublishAction(
settings,
transportService,
clusterStateSupplier,
listener,
discoverySettings,
CLUSTER_NAME);
}
public void testSimpleClusterStatePublishing() throws Exception {
MockNode nodeA = createMockNode("nodeA", Settings.EMPTY).setAsMaster();
MockNode nodeB = createMockNode("nodeB", Settings.EMPTY);
// Initial cluster state
ClusterState clusterState = nodeA.clusterState;
// cluster state update - add nodeB
DiscoveryNodes discoveryNodes = DiscoveryNodes.builder(clusterState.nodes()).put(nodeB.discoveryNode).build();
ClusterState previousClusterState = clusterState;
clusterState = ClusterState.builder(clusterState).nodes(discoveryNodes).incrementVersion().build();
publishStateAndWait(nodeA.action, clusterState, previousClusterState);
assertSameStateFromFull(nodeB.clusterState, clusterState);
// cluster state update - add block
previousClusterState = clusterState;
clusterState = ClusterState.builder(clusterState).blocks(ClusterBlocks.builder().addGlobalBlock(MetaData.CLUSTER_READ_ONLY_BLOCK)).incrementVersion().build();
publishStateAndWait(nodeA.action, clusterState, previousClusterState);
assertSameStateFromDiff(nodeB.clusterState, clusterState);
assertThat(nodeB.clusterState.blocks().global().size(), equalTo(1));
// cluster state update - remove block
previousClusterState = clusterState;
clusterState = ClusterState.builder(clusterState).blocks(ClusterBlocks.EMPTY_CLUSTER_BLOCK).incrementVersion().build();
publishStateAndWait(nodeA.action, clusterState, previousClusterState);
assertSameStateFromDiff(nodeB.clusterState, clusterState);
assertTrue(nodeB.clusterState.wasReadFromDiff());
// Adding new node - this node should get full cluster state while nodeB should still be getting diffs
MockNode nodeC = createMockNode("nodeC", Settings.EMPTY);
// cluster state update 3 - register node C
previousClusterState = clusterState;
discoveryNodes = DiscoveryNodes.builder(discoveryNodes).put(nodeC.discoveryNode).build();
clusterState = ClusterState.builder(clusterState).nodes(discoveryNodes).incrementVersion().build();
publishStateAndWait(nodeA.action, clusterState, previousClusterState);
assertSameStateFromDiff(nodeB.clusterState, clusterState);
// First state
assertSameStateFromFull(nodeC.clusterState, clusterState);
// cluster state update 4 - update settings
previousClusterState = clusterState;
MetaData metaData = MetaData.builder(clusterState.metaData()).transientSettings(Settings.builder().put("foo", "bar").build()).build();
clusterState = ClusterState.builder(clusterState).metaData(metaData).incrementVersion().build();
publishStateAndWait(nodeA.action, clusterState, previousClusterState);
assertSameStateFromDiff(nodeB.clusterState, clusterState);
assertThat(nodeB.clusterState.blocks().global().size(), equalTo(0));
assertSameStateFromDiff(nodeC.clusterState, clusterState);
assertThat(nodeC.clusterState.blocks().global().size(), equalTo(0));
// cluster state update - skipping one version change - should request full cluster state
previousClusterState = ClusterState.builder(clusterState).incrementVersion().build();
clusterState = ClusterState.builder(clusterState).incrementVersion().build();
publishStateAndWait(nodeA.action, clusterState, previousClusterState);
assertSameStateFromFull(nodeB.clusterState, clusterState);
assertSameStateFromFull(nodeC.clusterState, clusterState);
assertFalse(nodeC.clusterState.wasReadFromDiff());
// node A steps down from being master
nodeA.resetMasterId();
nodeB.resetMasterId();
nodeC.resetMasterId();
// node B becomes the master and sends a version of the cluster state that goes back
discoveryNodes = DiscoveryNodes.builder(discoveryNodes)
.put(nodeA.discoveryNode)
.put(nodeB.discoveryNode)
.put(nodeC.discoveryNode)
.masterNodeId(nodeB.discoveryNode.getId())
.localNodeId(nodeB.discoveryNode.getId())
.build();
previousClusterState = ClusterState.builder(new ClusterName("test")).nodes(discoveryNodes).build();
clusterState = ClusterState.builder(clusterState).nodes(discoveryNodes).incrementVersion().build();
publishStateAndWait(nodeB.action, clusterState, previousClusterState);
assertSameStateFromFull(nodeA.clusterState, clusterState);
assertSameStateFromFull(nodeC.clusterState, clusterState);
}
public void testUnexpectedDiffPublishing() throws Exception {
MockNode nodeA = createMockNode("nodeA", Settings.EMPTY, event -> {
fail("Shouldn't send cluster state to myself");
}).setAsMaster();
MockNode nodeB = createMockNode("nodeB", Settings.EMPTY);
// Initial cluster state with both states - the second node still shouldn't get diff even though it's present in the previous cluster state
DiscoveryNodes discoveryNodes = DiscoveryNodes.builder(nodeA.nodes()).put(nodeB.discoveryNode).build();
ClusterState previousClusterState = ClusterState.builder(CLUSTER_NAME).nodes(discoveryNodes).build();
ClusterState clusterState = ClusterState.builder(previousClusterState).incrementVersion().build();
publishStateAndWait(nodeA.action, clusterState, previousClusterState);
assertSameStateFromFull(nodeB.clusterState, clusterState);
// cluster state update - add block
previousClusterState = clusterState;
clusterState = ClusterState.builder(clusterState).blocks(ClusterBlocks.builder().addGlobalBlock(MetaData.CLUSTER_READ_ONLY_BLOCK)).incrementVersion().build();
publishStateAndWait(nodeA.action, clusterState, previousClusterState);
assertSameStateFromDiff(nodeB.clusterState, clusterState);
}
public void testDisablingDiffPublishing() throws Exception {
Settings noDiffPublishingSettings = Settings.builder().put(DiscoverySettings.PUBLISH_DIFF_ENABLE_SETTING.getKey(), false).build();
MockNode nodeA = createMockNode("nodeA", noDiffPublishingSettings, new ClusterStateListener() {
@Override
public void clusterChanged(ClusterChangedEvent event) {
fail("Shouldn't send cluster state to myself");
}
});
MockNode nodeB = createMockNode("nodeB", noDiffPublishingSettings, new ClusterStateListener() {
@Override
public void clusterChanged(ClusterChangedEvent event) {
assertFalse(event.state().wasReadFromDiff());
}
});
// Initial cluster state
DiscoveryNodes discoveryNodes = DiscoveryNodes.builder().put(nodeA.discoveryNode).localNodeId(nodeA.discoveryNode.getId()).masterNodeId(nodeA.discoveryNode.getId()).build();
ClusterState clusterState = ClusterState.builder(CLUSTER_NAME).nodes(discoveryNodes).build();
// cluster state update - add nodeB
discoveryNodes = DiscoveryNodes.builder(discoveryNodes).put(nodeB.discoveryNode).build();
ClusterState previousClusterState = clusterState;
clusterState = ClusterState.builder(clusterState).nodes(discoveryNodes).incrementVersion().build();
publishStateAndWait(nodeA.action, clusterState, previousClusterState);
// cluster state update - add block
previousClusterState = clusterState;
clusterState = ClusterState.builder(clusterState).blocks(ClusterBlocks.builder().addGlobalBlock(MetaData.CLUSTER_READ_ONLY_BLOCK)).incrementVersion().build();
publishStateAndWait(nodeA.action, clusterState, previousClusterState);
}
/**
* Test not waiting on publishing works correctly (i.e., publishing times out)
*/
public void testSimultaneousClusterStatePublishing() throws Exception {
int numberOfNodes = randomIntBetween(2, 10);
int numberOfIterations = scaledRandomIntBetween(5, 50);
Settings settings = Settings.builder().put(DiscoverySettings.PUBLISH_DIFF_ENABLE_SETTING.getKey(), randomBoolean()).build();
MockNode master = createMockNode("node0", settings, new ClusterStateListener() {
@Override
public void clusterChanged(ClusterChangedEvent event) {
assertProperMetaDataForVersion(event.state().metaData(), event.state().version());
}
}).setAsMaster();
DiscoveryNodes.Builder discoveryNodesBuilder = DiscoveryNodes.builder(master.nodes());
for (int i = 1; i < numberOfNodes; i++) {
final String name = "node" + i;
final MockNode node = createMockNode(name, settings, new ClusterStateListener() {
@Override
public void clusterChanged(ClusterChangedEvent event) {
assertProperMetaDataForVersion(event.state().metaData(), event.state().version());
}
});
discoveryNodesBuilder.put(node.discoveryNode);
}
AssertingAckListener[] listeners = new AssertingAckListener[numberOfIterations];
DiscoveryNodes discoveryNodes = discoveryNodesBuilder.build();
MetaData metaData = MetaData.EMPTY_META_DATA;
ClusterState clusterState = ClusterState.builder(CLUSTER_NAME).metaData(metaData).build();
ClusterState previousState;
for (int i = 0; i < numberOfIterations; i++) {
previousState = clusterState;
metaData = buildMetaDataForVersion(metaData, i + 1);
clusterState = ClusterState.builder(clusterState).incrementVersion().metaData(metaData).nodes(discoveryNodes).build();
listeners[i] = publishState(master.action, clusterState, previousState);
}
for (int i = 0; i < numberOfIterations; i++) {
listeners[i].await(1, TimeUnit.SECONDS);
}
// set the master cs
master.clusterState = clusterState;
for (MockNode node : nodes.values()) {
assertSameState(node.clusterState, clusterState);
assertThat(node.clusterState.nodes().getLocalNode(), equalTo(node.discoveryNode));
}
}
public void testSerializationFailureDuringDiffPublishing() throws Exception {
MockNode nodeA = createMockNode("nodeA", Settings.EMPTY, new ClusterStateListener() {
@Override
public void clusterChanged(ClusterChangedEvent event) {
fail("Shouldn't send cluster state to myself");
}
}).setAsMaster();
MockNode nodeB = createMockNode("nodeB", Settings.EMPTY);
// Initial cluster state with both states - the second node still shouldn't get diff even though it's present in the previous cluster state
DiscoveryNodes discoveryNodes = DiscoveryNodes.builder(nodeA.nodes()).put(nodeB.discoveryNode).build();
ClusterState previousClusterState = ClusterState.builder(CLUSTER_NAME).nodes(discoveryNodes).build();
ClusterState clusterState = ClusterState.builder(previousClusterState).incrementVersion().build();
publishStateAndWait(nodeA.action, clusterState, previousClusterState);
assertSameStateFromFull(nodeB.clusterState, clusterState);
// cluster state update - add block
previousClusterState = clusterState;
clusterState = ClusterState.builder(clusterState).blocks(ClusterBlocks.builder().addGlobalBlock(MetaData.CLUSTER_READ_ONLY_BLOCK)).incrementVersion().build();
ClusterState unserializableClusterState = new ClusterState(clusterState.version(), clusterState.stateUUID(), clusterState) {
@Override
public Diff<ClusterState> diff(ClusterState previousState) {
return new Diff<ClusterState>() {
@Override
public ClusterState apply(ClusterState part) {
fail("this diff shouldn't be applied");
return part;
}
@Override
public void writeTo(StreamOutput out) throws IOException {
throw new IOException("Simulated failure of diff serialization");
}
};
}
};
try {
publishStateAndWait(nodeA.action, unserializableClusterState, previousClusterState);
fail("cluster state published despite of diff errors");
} catch (Discovery.FailedToCommitClusterStateException e) {
assertThat(e.getCause(), notNullValue());
assertThat(e.getCause().getMessage(), containsString("failed to serialize"));
}
}
public void testFailToPublishWithLessThanMinMasterNodes() throws Exception {
final int masterNodes = randomIntBetween(1, 10);
MockNode master = createMockNode("master");
DiscoveryNodes.Builder discoveryNodesBuilder = DiscoveryNodes.builder().put(master.discoveryNode);
for (int i = 1; i < masterNodes; i++) {
discoveryNodesBuilder.put(createMockNode("node" + i).discoveryNode);
}
final int dataNodes = randomIntBetween(0, 5);
final Settings dataSettings = Settings.builder().put(Node.NODE_MASTER_SETTING.getKey(), false).build();
for (int i = 0; i < dataNodes; i++) {
discoveryNodesBuilder.put(createMockNode("data_" + i, dataSettings).discoveryNode);
}
discoveryNodesBuilder.localNodeId(master.discoveryNode.getId()).masterNodeId(master.discoveryNode.getId());
DiscoveryNodes discoveryNodes = discoveryNodesBuilder.build();
MetaData metaData = MetaData.EMPTY_META_DATA;
ClusterState clusterState = ClusterState.builder(CLUSTER_NAME).metaData(metaData).nodes(discoveryNodes).build();
ClusterState previousState = master.clusterState;
try {
publishState(master.action, clusterState, previousState, masterNodes + randomIntBetween(1, 5));
fail("cluster state publishing didn't fail despite of not having enough nodes");
} catch (Discovery.FailedToCommitClusterStateException expected) {
logger.debug("failed to publish as expected", expected);
}
}
public void testPublishingWithSendingErrors() throws Exception {
int goodNodes = randomIntBetween(2, 5);
int errorNodes = randomIntBetween(1, 5);
int timeOutNodes = randomBoolean() ? 0 : randomIntBetween(1, 5); // adding timeout nodes will force timeout errors
final int numberOfMasterNodes = goodNodes + errorNodes + timeOutNodes + 1; // master
final boolean expectingToCommit = randomBoolean();
Settings.Builder settings = Settings.builder();
// make sure we have a reasonable timeout if we expect to timeout, o.w. one that will make the test "hang"
settings.put(DiscoverySettings.COMMIT_TIMEOUT_SETTING.getKey(), expectingToCommit == false && timeOutNodes > 0 ? "100ms" : "1h")
.put(DiscoverySettings.PUBLISH_TIMEOUT_SETTING.getKey(), "5ms"); // test is about committing
MockNode master = createMockNode("master", settings.build());
// randomize things a bit
int[] nodeTypes = new int[goodNodes + errorNodes + timeOutNodes];
for (int i = 0; i < goodNodes; i++) {
nodeTypes[i] = 0;
}
for (int i = goodNodes; i < goodNodes + errorNodes; i++) {
nodeTypes[i] = 1;
}
for (int i = goodNodes + errorNodes; i < nodeTypes.length; i++) {
nodeTypes[i] = 2;
}
Collections.shuffle(Arrays.asList(nodeTypes), random());
DiscoveryNodes.Builder discoveryNodesBuilder = DiscoveryNodes.builder().put(master.discoveryNode);
for (int i = 0; i < nodeTypes.length; i++) {
final MockNode mockNode = createMockNode("node" + i);
discoveryNodesBuilder.put(mockNode.discoveryNode);
switch (nodeTypes[i]) {
case 1:
mockNode.action.errorOnSend.set(true);
break;
case 2:
mockNode.action.timeoutOnSend.set(true);
break;
}
}
final int dataNodes = randomIntBetween(0, 3); // data nodes don't matter
for (int i = 0; i < dataNodes; i++) {
final MockNode mockNode = createMockNode("data_" + i, Settings.builder().put(Node.NODE_MASTER_SETTING.getKey(), false).build());
discoveryNodesBuilder.put(mockNode.discoveryNode);
if (randomBoolean()) {
// we really don't care - just chaos monkey
mockNode.action.errorOnCommit.set(randomBoolean());
mockNode.action.errorOnSend.set(randomBoolean());
mockNode.action.timeoutOnCommit.set(randomBoolean());
mockNode.action.timeoutOnSend.set(randomBoolean());
}
}
final int minMasterNodes;
final String expectedBehavior;
if (expectingToCommit) {
minMasterNodes = randomIntBetween(0, goodNodes + 1); // count master
expectedBehavior = "succeed";
} else {
minMasterNodes = randomIntBetween(goodNodes + 2, numberOfMasterNodes); // +2 because of master
expectedBehavior = timeOutNodes > 0 ? "timeout" : "fail";
}
logger.info("--> expecting commit to {}. good nodes [{}], errors [{}], timeouts [{}]. min_master_nodes [{}]",
expectedBehavior, goodNodes + 1, errorNodes, timeOutNodes, minMasterNodes);
discoveryNodesBuilder.localNodeId(master.discoveryNode.getId()).masterNodeId(master.discoveryNode.getId());
DiscoveryNodes discoveryNodes = discoveryNodesBuilder.build();
MetaData metaData = MetaData.EMPTY_META_DATA;
ClusterState clusterState = ClusterState.builder(CLUSTER_NAME).metaData(metaData).nodes(discoveryNodes).build();
ClusterState previousState = master.clusterState;
try {
publishState(master.action, clusterState, previousState, minMasterNodes);
if (expectingToCommit == false) {
fail("cluster state publishing didn't fail despite of not have enough nodes");
}
} catch (Discovery.FailedToCommitClusterStateException exception) {
logger.debug("failed to publish as expected", exception);
if (expectingToCommit) {
throw exception;
}
assertThat(exception.getMessage(), containsString(timeOutNodes > 0 ? "timed out" : "failed"));
}
}
public void testIncomingClusterStateValidation() throws Exception {
MockNode node = createMockNode("node");
logger.info("--> testing acceptances of any master when having no master");
ClusterState state = ClusterState.builder(node.clusterState)
.nodes(DiscoveryNodes.builder(node.nodes()).masterNodeId(randomAsciiOfLength(10))).incrementVersion().build();
node.action.validateIncomingState(state, null);
// now set a master node
node.clusterState = ClusterState.builder(node.clusterState).nodes(DiscoveryNodes.builder(node.nodes()).masterNodeId("master")).build();
logger.info("--> testing rejection of another master");
try {
node.action.validateIncomingState(state, node.clusterState);
fail("node accepted state from another master");
} catch (IllegalStateException OK) {
assertThat(OK.toString(), containsString("cluster state from a different master than the current one, rejecting"));
}
logger.info("--> test state from the current master is accepted");
node.action.validateIncomingState(ClusterState.builder(node.clusterState)
.nodes(DiscoveryNodes.builder(node.nodes()).masterNodeId("master")).incrementVersion().build(), node.clusterState);
logger.info("--> testing rejection of another cluster name");
try {
node.action.validateIncomingState(ClusterState.builder(new ClusterName(randomAsciiOfLength(10))).nodes(node.nodes()).build(), node.clusterState);
fail("node accepted state with another cluster name");
} catch (IllegalStateException OK) {
assertThat(OK.toString(), containsString("received state from a node that is not part of the cluster"));
}
logger.info("--> testing rejection of a cluster state with wrong local node");
try {
state = ClusterState.builder(node.clusterState)
.nodes(DiscoveryNodes.builder(node.nodes()).localNodeId("_non_existing_").build())
.incrementVersion().build();
node.action.validateIncomingState(state, node.clusterState);
fail("node accepted state with non-existence local node");
} catch (IllegalStateException OK) {
assertThat(OK.toString(), containsString("received state with a local node that does not match the current local node"));
}
try {
MockNode otherNode = createMockNode("otherNode");
state = ClusterState.builder(node.clusterState).nodes(
DiscoveryNodes.builder(node.nodes()).put(otherNode.discoveryNode).localNodeId(otherNode.discoveryNode.getId()).build()
).incrementVersion().build();
node.action.validateIncomingState(state, node.clusterState);
fail("node accepted state with existent but wrong local node");
} catch (IllegalStateException OK) {
assertThat(OK.toString(), containsString("received state with a local node that does not match the current local node"));
}
logger.info("--> testing acceptance of an old cluster state");
final ClusterState incomingState = node.clusterState;
node.clusterState = ClusterState.builder(node.clusterState).incrementVersion().build();
final IllegalStateException e =
expectThrows(IllegalStateException.class, () -> node.action.validateIncomingState(incomingState, node.clusterState));
final String message = String.format(
Locale.ROOT,
"rejecting cluster state version [%d] uuid [%s] received from [%s]",
incomingState.version(),
incomingState.stateUUID(),
incomingState.nodes().getMasterNodeId()
);
assertThat(e, hasToString("java.lang.IllegalStateException: " + message));
// an older version from a *new* master is also OK!
ClusterState previousState = ClusterState.builder(node.clusterState).incrementVersion().build();
state = ClusterState.builder(node.clusterState)
.nodes(DiscoveryNodes.builder(node.clusterState.nodes()).masterNodeId("_new_master_").build())
.build();
// remove the master of the node (but still have a previous cluster state with it)!
node.resetMasterId();
node.action.validateIncomingState(state, previousState);
}
public void testOutOfOrderCommitMessages() throws Throwable {
MockNode node = createMockNode("node").setAsMaster();
final CapturingTransportChannel channel = new CapturingTransportChannel();
List<ClusterState> states = new ArrayList<>();
final int numOfStates = scaledRandomIntBetween(3, 25);
for (int i = 1; i <= numOfStates; i++) {
states.add(ClusterState.builder(node.clusterState).version(i).stateUUID(ClusterState.UNKNOWN_UUID).build());
}
final ClusterState finalState = states.get(numOfStates - 1);
logger.info("--> publishing states");
for (ClusterState state : states) {
node.action.handleIncomingClusterStateRequest(
new BytesTransportRequest(PublishClusterStateAction.serializeFullClusterState(state, Version.CURRENT), Version.CURRENT),
channel);
assertThat(channel.response.get(), equalTo((TransportResponse) TransportResponse.Empty.INSTANCE));
assertThat(channel.error.get(), nullValue());
channel.clear();
}
logger.info("--> committing states");
long largestVersionSeen = Long.MIN_VALUE;
Randomness.shuffle(states);
for (ClusterState state : states) {
node.action.handleCommitRequest(new PublishClusterStateAction.CommitClusterStateRequest(state.stateUUID()), channel);
if (largestVersionSeen < state.getVersion()) {
assertThat(channel.response.get(), equalTo((TransportResponse) TransportResponse.Empty.INSTANCE));
if (channel.error.get() != null) {
throw channel.error.get();
}
largestVersionSeen = state.getVersion();
} else {
// older cluster states will be rejected
assertNotNull(channel.error.get());
assertThat(channel.error.get(), instanceOf(IllegalStateException.class));
}
channel.clear();
}
//now check the last state held
assertSameState(node.clusterState, finalState);
}
/**
* Tests that cluster is committed or times out. It should never be the case that we fail
* an update due to a commit timeout, but it ends up being committed anyway
*/
public void testTimeoutOrCommit() throws Exception {
Settings settings = Settings.builder()
.put(DiscoverySettings.COMMIT_TIMEOUT_SETTING.getKey(), "1ms").build(); // short but so we will sometime commit sometime timeout
MockNode master = createMockNode("master", settings);
MockNode node = createMockNode("node", settings);
ClusterState state = ClusterState.builder(master.clusterState)
.nodes(DiscoveryNodes.builder(master.clusterState.nodes()).put(node.discoveryNode).masterNodeId(master.discoveryNode.getId())).build();
for (int i = 0; i < 10; i++) {
state = ClusterState.builder(state).incrementVersion().build();
logger.debug("--> publishing version [{}], UUID [{}]", state.version(), state.stateUUID());
boolean success;
try {
publishState(master.action, state, master.clusterState, 2).await(1, TimeUnit.HOURS);
success = true;
} catch (Discovery.FailedToCommitClusterStateException OK) {
success = false;
}
logger.debug("--> publishing [{}], verifying...", success ? "succeeded" : "failed");
if (success) {
assertSameState(node.clusterState, state);
} else {
assertThat(node.clusterState.stateUUID(), not(equalTo(state.stateUUID())));
}
}
}
private MetaData buildMetaDataForVersion(MetaData metaData, long version) {
ImmutableOpenMap.Builder<String, IndexMetaData> indices = ImmutableOpenMap.builder(metaData.indices());
indices.put("test" + version, IndexMetaData.builder("test" + version).settings(Settings.builder().put(IndexMetaData.SETTING_VERSION_CREATED, Version.CURRENT))
.numberOfShards((int) version).numberOfReplicas(0).build());
return MetaData.builder(metaData)
.transientSettings(Settings.builder().put("test", version).build())
.indices(indices.build())
.build();
}
private void assertProperMetaDataForVersion(MetaData metaData, long version) {
for (long i = 1; i <= version; i++) {
assertThat(metaData.index("test" + i), notNullValue());
assertThat(metaData.index("test" + i).getNumberOfShards(), equalTo((int) i));
}
assertThat(metaData.index("test" + (version + 1)), nullValue());
assertThat(metaData.transientSettings().get("test"), equalTo(Long.toString(version)));
}
public void publishStateAndWait(PublishClusterStateAction action, ClusterState state, ClusterState previousState) throws InterruptedException {
publishState(action, state, previousState).await(1, TimeUnit.SECONDS);
}
public AssertingAckListener publishState(PublishClusterStateAction action, ClusterState state, ClusterState previousState) throws InterruptedException {
final int minimumMasterNodes = randomIntBetween(-1, state.nodes().getMasterNodes().size());
return publishState(action, state, previousState, minimumMasterNodes);
}
public AssertingAckListener publishState(PublishClusterStateAction action, ClusterState state, ClusterState previousState, int minMasterNodes) throws InterruptedException {
AssertingAckListener assertingAckListener = new AssertingAckListener(state.nodes().getSize() - 1);
ClusterChangedEvent changedEvent = new ClusterChangedEvent("test update", state, previousState);
action.publish(changedEvent, minMasterNodes, assertingAckListener);
return assertingAckListener;
}
public static class AssertingAckListener implements Discovery.AckListener {
private final List<Tuple<DiscoveryNode, Throwable>> errors = new CopyOnWriteArrayList<>();
private final AtomicBoolean timeoutOccurred = new AtomicBoolean();
private final CountDownLatch countDown;
public AssertingAckListener(int nodeCount) {
countDown = new CountDownLatch(nodeCount);
}
@Override
public void onNodeAck(DiscoveryNode node, @Nullable Exception e) {
if (e != null) {
errors.add(new Tuple<>(node, e));
}
countDown.countDown();
}
@Override
public void onTimeout() {
timeoutOccurred.set(true);
// Fast forward the counter - no reason to wait here
long currentCount = countDown.getCount();
for (long i = 0; i < currentCount; i++) {
countDown.countDown();
}
}
public void await(long timeout, TimeUnit unit) throws InterruptedException {
assertThat(awaitErrors(timeout, unit), emptyIterable());
}
public List<Tuple<DiscoveryNode, Throwable>> awaitErrors(long timeout, TimeUnit unit) throws InterruptedException {
countDown.await(timeout, unit);
assertFalse(timeoutOccurred.get());
return errors;
}
}
void assertSameState(ClusterState actual, ClusterState expected) {
assertThat(actual, notNullValue());
final String reason = "\n--> actual ClusterState: " + actual.prettyPrint() + "\n--> expected ClusterState:" + expected.prettyPrint();
assertThat("unequal UUIDs" + reason, actual.stateUUID(), equalTo(expected.stateUUID()));
assertThat("unequal versions" + reason, actual.version(), equalTo(expected.version()));
}
void assertSameStateFromDiff(ClusterState actual, ClusterState expected) {
assertSameState(actual, expected);
assertTrue(actual.wasReadFromDiff());
}
void assertSameStateFromFull(ClusterState actual, ClusterState expected) {
assertSameState(actual, expected);
assertFalse(actual.wasReadFromDiff());
}
static class MockPublishAction extends PublishClusterStateAction {
AtomicBoolean timeoutOnSend = new AtomicBoolean();
AtomicBoolean errorOnSend = new AtomicBoolean();
AtomicBoolean timeoutOnCommit = new AtomicBoolean();
AtomicBoolean errorOnCommit = new AtomicBoolean();
public MockPublishAction(Settings settings, TransportService transportService, Supplier<ClusterState> clusterStateSupplier, NewPendingClusterStateListener listener, DiscoverySettings discoverySettings, ClusterName clusterName) {
super(settings, transportService, clusterStateSupplier, listener, discoverySettings, clusterName);
}
@Override
protected void handleIncomingClusterStateRequest(BytesTransportRequest request, TransportChannel channel) throws IOException {
if (errorOnSend.get()) {
throw new ElasticsearchException("forced error on incoming cluster state");
}
if (timeoutOnSend.get()) {
return;
}
super.handleIncomingClusterStateRequest(request, channel);
}
@Override
protected void handleCommitRequest(PublishClusterStateAction.CommitClusterStateRequest request, TransportChannel channel) {
if (errorOnCommit.get()) {
throw new ElasticsearchException("forced error on incoming commit");
}
if (timeoutOnCommit.get()) {
return;
}
super.handleCommitRequest(request, channel);
}
}
static class CapturingTransportChannel implements TransportChannel {
AtomicReference<TransportResponse> response = new AtomicReference<>();
AtomicReference<Throwable> error = new AtomicReference<>();
public void clear() {
response.set(null);
error.set(null);
}
@Override
public String action() {
return "_noop_";
}
@Override
public String getProfileName() {
return "_noop_";
}
@Override
public void sendResponse(TransportResponse response) throws IOException {
this.response.set(response);
assertThat(error.get(), nullValue());
}
@Override
public void sendResponse(TransportResponse response, TransportResponseOptions options) throws IOException {
this.response.set(response);
assertThat(error.get(), nullValue());
}
@Override
public void sendResponse(Exception exception) throws IOException {
this.error.set(exception);
assertThat(response.get(), nullValue());
}
@Override
public long getRequestId() {
return 0;
}
@Override
public String getChannelType() {
return "capturing";
}
}
}
| apache-2.0 |
nengxu/OrientDB | core/src/test/java/com/orientechnologies/orient/core/index/OSimpleKeyIndexDefinitionTest.java | 4965 | package com.orientechnologies.orient.core.index;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import com.orientechnologies.common.collection.OCompositeKey;
import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
import com.orientechnologies.orient.core.metadata.schema.OType;
import com.orientechnologies.orient.core.record.impl.ODocument;
@Test
@SuppressWarnings("unchecked")
public class OSimpleKeyIndexDefinitionTest {
private OSimpleKeyIndexDefinition simpleKeyIndexDefinition;
@BeforeMethod
public void beforeMethod() {
simpleKeyIndexDefinition = new OSimpleKeyIndexDefinition(OType.INTEGER, OType.STRING);
}
@Test
public void testGetFields() {
Assert.assertTrue(simpleKeyIndexDefinition.getFields().isEmpty());
}
@Test
public void testGetClassName() {
Assert.assertNull(simpleKeyIndexDefinition.getClassName());
}
@Test
public void testCreateValueSimpleKey() {
final OSimpleKeyIndexDefinition keyIndexDefinition = new OSimpleKeyIndexDefinition(OType.INTEGER);
final Object result = keyIndexDefinition.createValue("2");
Assert.assertEquals(result, 2);
}
@Test
public void testCreateValueCompositeKeyListParam() {
final Object result = simpleKeyIndexDefinition.createValue(Arrays.asList("2", "3"));
final OCompositeKey compositeKey = new OCompositeKey(Arrays.asList(2, "3"));
Assert.assertEquals(result, compositeKey);
}
@Test
public void testCreateValueCompositeKeyNullListParam() {
final Object result = simpleKeyIndexDefinition.createValue(Arrays.asList((Object) null));
Assert.assertNull(result);
}
@Test
public void testNullParamListItem() {
final Object result = simpleKeyIndexDefinition.createValue(Arrays.asList("2", null));
Assert.assertNull(result);
}
@Test
public void testWrongParamTypeListItem() {
final Object result = simpleKeyIndexDefinition.createValue(Arrays.asList("a", "3"));
Assert.assertNull(result);
}
@Test
public void testCreateValueCompositeKey() {
final Object result = simpleKeyIndexDefinition.createValue("2", "3");
final OCompositeKey compositeKey = new OCompositeKey(Arrays.asList(2, "3"));
Assert.assertEquals(result, compositeKey);
}
@Test
public void testCreateValueCompositeKeyNullParamList() {
final Object result = simpleKeyIndexDefinition.createValue((List<?>) null);
Assert.assertNull(result);
}
@Test
public void testCreateValueCompositeKeyNullParam() {
final Object result = simpleKeyIndexDefinition.createValue((Object) null);
Assert.assertNull(result);
}
@Test
public void testCreateValueCompositeKeyEmptyList() {
final Object result = simpleKeyIndexDefinition.createValue(Collections.<Object> emptyList());
Assert.assertNull(result);
}
@Test
public void testNullParamItem() {
final Object result = simpleKeyIndexDefinition.createValue("2", null);
Assert.assertNull(result);
}
@Test
public void testWrongParamType() {
final Object result = simpleKeyIndexDefinition.createValue("a", "3");
Assert.assertNull(result);
}
@Test
public void testParamCount() {
Assert.assertEquals(simpleKeyIndexDefinition.getParamCount(), 2);
}
@Test
public void testParamCountOneItem() {
final OSimpleKeyIndexDefinition keyIndexDefinition = new OSimpleKeyIndexDefinition(OType.INTEGER);
Assert.assertEquals(keyIndexDefinition.getParamCount(), 1);
}
@Test
public void testGetKeyTypes() {
Assert.assertEquals(simpleKeyIndexDefinition.getTypes(), new OType[] { OType.INTEGER, OType.STRING });
}
@Test
public void testGetKeyTypesOneType() {
final OSimpleKeyIndexDefinition keyIndexDefinition = new OSimpleKeyIndexDefinition(OType.BOOLEAN);
Assert.assertEquals(keyIndexDefinition.getTypes(), new OType[] { OType.BOOLEAN });
}
@Test
public void testReload() {
final ODatabaseDocumentTx databaseDocumentTx = new ODatabaseDocumentTx("memory:osimplekeyindexdefinitiontest");
databaseDocumentTx.create();
final ODocument storeDocument = simpleKeyIndexDefinition.toStream();
storeDocument.save();
final ODocument loadDocument = databaseDocumentTx.load(storeDocument.getIdentity());
final OSimpleKeyIndexDefinition loadedKeyIndexDefinition = new OSimpleKeyIndexDefinition();
loadedKeyIndexDefinition.fromStream(loadDocument);
databaseDocumentTx.drop();
Assert.assertEquals(loadedKeyIndexDefinition, simpleKeyIndexDefinition);
}
@Test(expectedExceptions = OIndexException.class)
public void testGetDocumentValueToIndex() {
simpleKeyIndexDefinition.getDocumentValueToIndex(new ODocument());
}
}
| apache-2.0 |
IllusionRom-deprecated/android_platform_tools_idea | plugins/ant/src/com/intellij/lang/ant/refactoring/AntRenameHandler.java | 3289 | /*
* Copyright 2000-2010 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.lang.ant.refactoring;
import com.intellij.codeInsight.TargetElementUtilBase;
import com.intellij.lang.ant.dom.AntDomFileDescription;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.actionSystem.LangDataKeys;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.IndexNotReadyException;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiReference;
import com.intellij.psi.xml.XmlFile;
import com.intellij.refactoring.rename.PsiElementRenameHandler;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Collection;
/**
* @author Eugene Zhuravlev
* Date: Mar 19, 2007
*/
public final class AntRenameHandler extends PsiElementRenameHandler {
public boolean isAvailableOnDataContext(final DataContext dataContext) {
final PsiElement[] elements = getElements(dataContext);
return elements != null && elements.length > 1;
}
public void invoke(@NotNull final Project project, final Editor editor, final PsiFile file, final DataContext dataContext) {
final PsiElement[] elements = getElements(dataContext);
if (elements != null && elements.length > 0) {
invoke(project, new PsiElement[]{elements[0]}, dataContext);
}
}
public void invoke(@NotNull final Project project, @NotNull final PsiElement[] elements, final DataContext dataContext) {
super.invoke(project, elements, dataContext);
}
@Nullable
private static PsiElement[] getElements(DataContext dataContext) {
final PsiFile psiFile = CommonDataKeys.PSI_FILE.getData(dataContext);
if (!(psiFile instanceof XmlFile && AntDomFileDescription.isAntFile((XmlFile)psiFile))) {
return null;
}
final Editor editor = LangDataKeys.EDITOR.getData(dataContext);
if (editor == null) {
return null;
}
return getPsiElementsIn(editor, psiFile);
}
@Nullable
private static PsiElement[] getPsiElementsIn(final Editor editor, final PsiFile psiFile) {
try {
final PsiReference reference = TargetElementUtilBase.findReference(editor, editor.getCaretModel().getOffset());
if (reference == null) {
return null;
}
final Collection<PsiElement> candidates = TargetElementUtilBase.getInstance().getTargetCandidates(reference);
return ContainerUtil.toArray(candidates, new PsiElement[candidates.size()]);
}
catch (IndexNotReadyException e) {
return null;
}
}
}
| apache-2.0 |
JadiraOrg/jadira | bindings/src/main/java/org/jadira/bindings/core/binder/RegisterableBinder.java | 8392 | /*
* Copyright 2011 Christopher Pheby
*
* 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.jadira.bindings.core.binder;
import java.lang.annotation.Annotation;
import java.net.URL;
import org.jadira.bindings.core.api.Binding;
import org.jadira.bindings.core.api.Converter;
import org.jadira.bindings.core.api.FromUnmarshaller;
import org.jadira.bindings.core.api.ToMarshaller;
public interface RegisterableBinder {
/**
* Register the configuration file (bindings.xml) at the given URL
* @param nextLocation The URL to register
*/
void registerConfiguration(URL nextLocation);
/**
* Register a Binding with the given source and target class.
* A binding unifies a marshaller and an unmarshaller and both must be available to resolve a binding.
*
* The source class is considered the owning class of the binding. The source can be marshalled
* into the target class. Similarly, the target can be unmarshalled to produce an instance of the source type.
* @param key The converter key
* @param converter The binding to be registered
* @param <S> Source type
* @param <T> Target type
*/
<S, T> void registerBinding(ConverterKey<S,T> key, Binding<S, T> converter);
/**
* Register an UnMarshaller with the given source and target class.
* The unmarshaller is used as follows: Instances of the source can be marshalled into the target class.
* @param key The converter key
* @param converter The FromUnmarshaller to be registered
* @param <S> Source type
* @param <T> Target type
*/
<S, T> void registerUnmarshaller(ConverterKey<S,T> key, FromUnmarshaller<S, T> converter);
/**
* Register a Marshaller with the given source and target class.
* The marshaller is used as follows: Instances of the source can be marshalled into the target class.
* @param key The converter key
* @param converter The ToMarshaller to be registered
* @param <S> Source type
* @param <T> Target type
*/
<S, T> void registerMarshaller(ConverterKey<S,T> key, ToMarshaller<S, T> converter);
/**
* Register a Converter with the given input and output classes. Instances of the input class can be converted into
* instances of the output class
* @param key The converter key
* @param converter The Converter to be registered
* @param <S> Source type
* @param <T> Target type
*/
<S, T> void registerConverter(ConverterKey<S,T> key, Converter<S, T> converter);
/**
* Register a Binding with the given source and target class.
* A binding unifies a marshaller and an unmarshaller and both must be available to resolve a binding.
*
* The source class is considered the owning class of the binding. The source can be marshalled
* into the target class. Similarly, the target can be unmarshalled to produce an instance of the source type.
* @param sourceClass The source (owning) class
* @param targetClass The target (foreign) class
* @param converter The binding to be registered
* @param <S> Source type
* @param <T> Target type
*/
<S, T> void registerBinding(final Class<S> sourceClass, Class<T> targetClass, Binding<S, T> converter);
/**
* Register an UnMarshaller with the given source and target class.
* The unmarshaller is used as follows: Instances of the source can be marshalled into the target class.
* @param sourceClass The source (input) class
* @param targetClass The target (output) class
* @param converter The FromUnmarshaller to be registered
* @param <S> Source type
* @param <T> Target type
*/
<S, T> void registerUnmarshaller(Class<S> sourceClass, Class<T> targetClass, FromUnmarshaller<S, T> converter);
/**
* Register a Marshaller with the given source and target class.
* The marshaller is used as follows: Instances of the source can be marshalled into the target class.
* @param sourceClass The source (input) class
* @param targetClass The target (output) class
* @param converter The ToMarshaller to be registered
* @param <S> Source type
* @param <T> Target type
*/
<S, T> void registerMarshaller(Class<S> sourceClass, Class<T> targetClass, ToMarshaller<S, T> converter);
/**
* Register a Converter with the given input and output classes. Instances of the input class can be converted into
* instances of the output class
* @param sourceClass The source (input) class
* @param targetClass The target (output) class
* @param converter The Converter to be registered
* @param <S> Source type
* @param <T> Target type
*/
<S, T> void registerConverter(final Class<S> sourceClass, Class<T> targetClass, Converter<S, T> converter);
/**
* Register a Binding with the given source and target class.
* A binding unifies a marshaller and an unmarshaller and both must be available to resolve a binding.
*
* The source class is considered the owning class of the binding. The source can be marshalled
* into the target class. Similarly, the target can be unmarshalled to produce an instance of the source type.
* @param sourceClass The source (owning) class
* @param targetClass The target (foreign) class
* @param converter The binding to be registered
* @param qualifier The qualifier for which the binding must be registered
* @param <S> Source type
* @param <T> Target type
*/
<S, T> void registerBinding(final Class<S> sourceClass, Class<T> targetClass, Binding<S, T> converter, Class<? extends Annotation> qualifier);
/**
* Register an UnMarshaller with the given source and target class.
* The unmarshaller is used as follows: Instances of the source can be marshalled into the target class.
* @param sourceClass The source (input) class
* @param targetClass The target (output) class
* @param converter The FromUnmarshaller to be registered
* @param qualifier The qualifier for which the unmarshaller must be registered
* @param <S> Source type
* @param <T> Target type
*/
<S, T> void registerUnmarshaller(Class<S> sourceClass, Class<T> targetClass, FromUnmarshaller<S, T> converter, Class<? extends Annotation> qualifier);
/**
* Register a Marshaller with the given source and target class.
* The marshaller is used as follows: Instances of the source can be marshalled into the target class.
* @param sourceClass The source (input) class
* @param targetClass The target (output) class
* @param converter The ToMarshaller to be registered
* @param qualifier The qualifier for which the marshaller must be registered
* @param <S> Source type
* @param <T> Target type
*/
<S, T> void registerMarshaller(Class<S> sourceClass, Class<T> targetClass, ToMarshaller<S, T> converter, Class<? extends Annotation> qualifier);
/**
* Register a Converter with the given input and output classes. Instances of the input class can be converted into
* instances of the output class
* @param sourceClass The source (input) class
* @param targetClass The target (output) class
* @param converter The Converter to be registered
* @param qualifier The qualifier for which the converter must be registered
* @param <S> Source type
* @param <T> Target type
*/
<S, T> void registerConverter(final Class<S> sourceClass, Class<T> targetClass, Converter<S, T> converter, Class<? extends Annotation> qualifier);
/**
* Inspect each of the supplied classes, processing any of the annotated methods found
* @param classesToInspect
*/
void registerAnnotatedClasses(Class<?>... classesToInspect);
/**
* Return an iterable collection of ConverterKeys, one for each currently registered conversion
*/
Iterable<ConverterKey<?, ?>> getConverterEntries();
}
| apache-2.0 |
pdalbora/gosu-lang | idea-gosu-plugin/src/main/java/gw/plugin/ij/intentions/WhileToForFix.java | 4712 | /*
* Copyright 2014 Guidewire Software, Inc.
*/
package gw.plugin.ij.intentions;
import com.intellij.codeInsight.CodeInsightUtilBase;
import com.intellij.codeInspection.LocalQuickFixAndIntentionActionOnPsiElement;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiWhiteSpace;
import com.intellij.psi.util.PsiMatcherImpl;
import gw.internal.gosu.parser.Expression;
import gw.internal.gosu.parser.expressions.NumericLiteral;
import gw.lang.parser.IStatement;
import gw.lang.parser.statements.IAssignmentStatement;
import gw.lang.parser.statements.IStatementList;
import gw.lang.parser.statements.IWhileStatement;
import gw.plugin.ij.lang.psi.api.statements.IGosuVariable;
import gw.plugin.ij.lang.psi.impl.statements.GosuForEachStatementImpl;
import gw.plugin.ij.lang.psi.impl.statements.GosuWhileStatementImpl;
import gw.plugin.ij.lang.psi.util.GosuPsiParseUtil;
import gw.plugin.ij.util.GosuBundle;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import static com.intellij.psi.util.PsiMatchers.hasClass;
public class WhileToForFix extends LocalQuickFixAndIntentionActionOnPsiElement {
String ident;
Expression rhs;
private IGosuVariable declarationEqualToZero;
private IAssignmentStatement increment;
public WhileToForFix(PsiElement whileStmt, String ident, Expression rhs, IGosuVariable declarationEqualToZero, IAssignmentStatement increment) {
super(whileStmt);
this.ident = ident;
this.rhs = rhs;
this.declarationEqualToZero = declarationEqualToZero;
this.increment = increment;
}
@Override
public void invoke(@NotNull Project project, @NotNull PsiFile file, @Nullable("is null when called from inspection") Editor editor, @NotNull PsiElement startElement, @NotNull PsiElement endElement) {
if (!CodeInsightUtilBase.prepareFileForWrite(startElement.getContainingFile())) {
return;
}
IWhileStatement parsedElement = ((GosuWhileStatementImpl) startElement).getParsedElement();
if (parsedElement == null) {
return;
}
IStatement statement = parsedElement.getStatement();
IStatement[] statements = ((IStatementList) statement).getStatements();
StringBuilder forStmt = new StringBuilder();
forStmt.append("for (");
forStmt.append(ident);
forStmt.append(" in 0..");
if(rhs instanceof NumericLiteral) {
Object res = rhs.evaluate();
if(res instanceof Integer) {
forStmt.append(((Integer)res)-1);
}
} else {
forStmt.append("|" + rhs);
}
forStmt.append(") {\n");
String indent = getIndet(parsedElement, statements);
for (IStatement statement1 : statements) {
if (statement1 != increment) {
forStmt.append(indent);
forStmt.append(statement1.getLocation().getTextFromTokens());
forStmt.append("\n");
}
}
forStmt.append("}");
PsiElement stub = GosuPsiParseUtil.parseProgramm(forStmt.toString(), startElement, file.getManager(), null);
PsiElement newForStmt = new PsiMatcherImpl(stub)
.descendant(hasClass(GosuForEachStatementImpl.class))
.getElement();
if (newForStmt != null) {
declarationEqualToZero.delete();
startElement.replace(newForStmt);
}
}
private String getIndet(IWhileStatement parsedElement, IStatement[] statements) {
int whileColum = parsedElement.getLocation().getColumn();
int column = statements[1].getLocation().getColumn() - whileColum;
if(column < 0) {
return " ";
}
StringBuilder out = new StringBuilder();
for(int i = 0; i <= column; i++) {
out.append(" ");
}
return out.toString();
}
private void removeVarDecl(PsiElement whileStmt, String ident) {
PsiElement prev = whileStmt.getPrevSibling();
while (prev instanceof PsiWhiteSpace) {
prev = prev.getPrevSibling();
}
if (prev instanceof IGosuVariable && ((IGosuVariable) prev).getName().equals(ident)) {
prev.delete();
}
}
@Override
public boolean isAvailable(@NotNull Project project,
@NotNull PsiFile file,
@NotNull PsiElement startElement,
@NotNull PsiElement endElement) {
return startElement instanceof GosuWhileStatementImpl;
}
@NotNull
@Override
public String getText() {
return GosuBundle.message("inspection.while.to.for");
}
@NotNull
@Override
public String getFamilyName() {
return GosuBundle.message("inspection.group.name.statement.issues");
}
}
| apache-2.0 |
jgrivolla/uima-addons | RegularExpressionAnnotator/src/main/java/org/apache/uima/annotator/regex/RegexVariables.java | 1870 | /*
* 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.uima.annotator.regex;
import java.util.regex.Pattern;
/**
* RegexVariables interface.
*/
public interface RegexVariables {
public static final String VARIABLE_START = "\\v";
public static final String VARIABLE_REGEX_BEGIN = "\\\\v\\{";
public static final String VARIABLE_REGEX_END = "\\}";
public static final Pattern VARIABLE_REGEX_PATTERN = Pattern
.compile(VARIABLE_REGEX_BEGIN + "(\\w+)" + VARIABLE_REGEX_END);
/**
* Adds a variable to the Variables object.
*
* @param varName
* variable name
*
* @param varValue
* variable value
*/
public void addVariable(String varName, String varValue);
/**
* returns the value of the specified variable or <code>null</code> if the
* variable does not exist
*
* @param varName
* variable name
*
* @return returns the variable value of <code>null</code> if the variable
* does not exist
*
*/
public String getVariableValue(String varName);
} | apache-2.0 |
wwjiang007/alluxio | core/client/fs/src/main/java/alluxio/client/block/stream/DefaultBlockWorkerClient.java | 9174 | /*
* The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
* (the "License"). You may not use this work except in compliance with the License, which is
* available at www.apache.org/licenses/LICENSE-2.0
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied, as more fully set forth in the License.
*
* See the NOTICE file distributed with this work for information regarding copyright ownership.
*/
package alluxio.client.block.stream;
import alluxio.conf.AlluxioConfiguration;
import alluxio.conf.PropertyKey;
import alluxio.exception.status.AlluxioStatusException;
import alluxio.exception.status.UnauthenticatedException;
import alluxio.grpc.BlockWorkerGrpc;
import alluxio.grpc.CacheRequest;
import alluxio.grpc.ClearMetricsRequest;
import alluxio.grpc.ClearMetricsResponse;
import alluxio.grpc.CreateLocalBlockRequest;
import alluxio.grpc.CreateLocalBlockResponse;
import alluxio.grpc.DataMessageMarshaller;
import alluxio.grpc.DataMessageMarshallerProvider;
import alluxio.grpc.GrpcChannel;
import alluxio.grpc.GrpcChannelBuilder;
import alluxio.grpc.GrpcNetworkGroup;
import alluxio.grpc.GrpcSerializationUtils;
import alluxio.grpc.GrpcServerAddress;
import alluxio.grpc.MoveBlockRequest;
import alluxio.grpc.MoveBlockResponse;
import alluxio.grpc.OpenLocalBlockRequest;
import alluxio.grpc.OpenLocalBlockResponse;
import alluxio.grpc.ReadRequest;
import alluxio.grpc.ReadResponse;
import alluxio.grpc.RemoveBlockRequest;
import alluxio.grpc.RemoveBlockResponse;
import alluxio.grpc.WriteRequest;
import alluxio.grpc.WriteResponse;
import alluxio.resource.AlluxioResourceLeakDetectorFactory;
import alluxio.retry.RetryPolicy;
import alluxio.retry.RetryUtils;
import alluxio.security.user.UserState;
import com.google.common.base.Preconditions;
import com.google.common.io.Closer;
import io.grpc.StatusRuntimeException;
import io.grpc.stub.StreamObserver;
import io.netty.util.ResourceLeakDetector;
import io.netty.util.ResourceLeakTracker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nullable;
/**
* Default implementation of {@link BlockWorkerClient}.
*/
public class DefaultBlockWorkerClient implements BlockWorkerClient {
private static final Logger LOG =
LoggerFactory.getLogger(DefaultBlockWorkerClient.class.getName());
private static final ResourceLeakDetector<DefaultBlockWorkerClient> DETECTOR =
AlluxioResourceLeakDetectorFactory.instance()
.newResourceLeakDetector(DefaultBlockWorkerClient.class);
private GrpcChannel mStreamingChannel;
private GrpcChannel mRpcChannel;
private GrpcServerAddress mAddress;
private final long mRpcTimeoutMs;
private BlockWorkerGrpc.BlockWorkerStub mStreamingAsyncStub;
private BlockWorkerGrpc.BlockWorkerBlockingStub mRpcBlockingStub;
private BlockWorkerGrpc.BlockWorkerStub mRpcAsyncStub;
@Nullable
private final ResourceLeakTracker<DefaultBlockWorkerClient> mTracker;
/**
* Creates a client instance for communicating with block worker.
*
* @param userState the user state
* @param address the address of the worker
* @param alluxioConf Alluxio configuration
*/
public DefaultBlockWorkerClient(UserState userState, GrpcServerAddress address,
AlluxioConfiguration alluxioConf) throws IOException {
RetryPolicy retryPolicy = RetryUtils.defaultClientRetry(
alluxioConf.getDuration(PropertyKey.USER_RPC_RETRY_MAX_DURATION),
alluxioConf.getDuration(PropertyKey.USER_RPC_RETRY_BASE_SLEEP_MS),
alluxioConf.getDuration(PropertyKey.USER_RPC_RETRY_MAX_SLEEP_MS));
UnauthenticatedException lastException = null;
// TODO(feng): unify worker client with AbstractClient
while (retryPolicy.attempt()) {
try {
// Disables channel pooling for data streaming to achieve better throughput.
// Channel is still reused due to client pooling.
mStreamingChannel = GrpcChannelBuilder.newBuilder(address, alluxioConf)
.setSubject(userState.getSubject())
.setNetworkGroup(GrpcNetworkGroup.STREAMING)
.setClientType("DefaultBlockWorkerClient-Stream")
.build();
mStreamingChannel.intercept(new StreamSerializationClientInterceptor());
// Uses default pooling strategy for RPC calls for better scalability.
mRpcChannel = GrpcChannelBuilder.newBuilder(address, alluxioConf)
.setSubject(userState.getSubject())
.setNetworkGroup(GrpcNetworkGroup.RPC)
.setClientType("DefaultBlockWorkerClient-Rpc")
.build();
lastException = null;
break;
} catch (StatusRuntimeException e) {
close();
throw AlluxioStatusException.fromStatusRuntimeException(e);
} catch (UnauthenticatedException e) {
close();
userState.relogin();
lastException = e;
}
}
if (lastException != null) {
throw lastException;
}
mStreamingAsyncStub = BlockWorkerGrpc.newStub(mStreamingChannel);
mRpcBlockingStub = BlockWorkerGrpc.newBlockingStub(mRpcChannel);
mRpcAsyncStub = BlockWorkerGrpc.newStub(mRpcChannel);
mAddress = address;
mRpcTimeoutMs = alluxioConf.getMs(PropertyKey.USER_RPC_RETRY_MAX_DURATION);
mTracker = DETECTOR.track(this);
}
@Override
public boolean isShutdown() {
return mStreamingChannel.isShutdown() || mRpcChannel.isShutdown();
}
@Override
public boolean isHealthy() {
return !isShutdown() && mStreamingChannel.isHealthy() && mRpcChannel.isHealthy();
}
@Override
public void close() throws IOException {
try (Closer closer = Closer.create()) {
closer.register(() -> {
if (mStreamingChannel != null) {
mStreamingChannel.shutdown();
}
});
closer.register(() -> {
if (mRpcChannel != null) {
mRpcChannel.shutdown();
}
});
closer.register(() -> {
if (mTracker != null) {
mTracker.close(this);
}
});
}
}
@Override
public StreamObserver<WriteRequest> writeBlock(StreamObserver<WriteResponse> responseObserver) {
if (responseObserver instanceof DataMessageMarshallerProvider) {
DataMessageMarshaller<WriteRequest> marshaller =
((DataMessageMarshallerProvider<WriteRequest, WriteResponse>) responseObserver)
.getRequestMarshaller();
Preconditions.checkNotNull(marshaller, "marshaller");
return mStreamingAsyncStub
.withOption(GrpcSerializationUtils.OVERRIDDEN_METHOD_DESCRIPTOR,
BlockWorkerGrpc.getWriteBlockMethod().toBuilder()
.setRequestMarshaller(marshaller)
.build())
.writeBlock(responseObserver);
} else {
return mStreamingAsyncStub.writeBlock(responseObserver);
}
}
@Override
public StreamObserver<ReadRequest> readBlock(StreamObserver<ReadResponse> responseObserver) {
if (responseObserver instanceof DataMessageMarshallerProvider) {
DataMessageMarshaller<ReadResponse> marshaller =
((DataMessageMarshallerProvider<ReadRequest, ReadResponse>) responseObserver)
.getResponseMarshaller();
Preconditions.checkNotNull(marshaller);
return mStreamingAsyncStub
.withOption(GrpcSerializationUtils.OVERRIDDEN_METHOD_DESCRIPTOR,
BlockWorkerGrpc.getReadBlockMethod().toBuilder()
.setResponseMarshaller(marshaller)
.build())
.readBlock(responseObserver);
} else {
return mStreamingAsyncStub.readBlock(responseObserver);
}
}
@Override
public StreamObserver<CreateLocalBlockRequest> createLocalBlock(
StreamObserver<CreateLocalBlockResponse> responseObserver) {
return mStreamingAsyncStub.createLocalBlock(responseObserver);
}
@Override
public StreamObserver<OpenLocalBlockRequest> openLocalBlock(
StreamObserver<OpenLocalBlockResponse> responseObserver) {
return mStreamingAsyncStub.openLocalBlock(responseObserver);
}
@Override
public RemoveBlockResponse removeBlock(final RemoveBlockRequest request) {
return mRpcBlockingStub.withDeadlineAfter(mRpcTimeoutMs, TimeUnit.MILLISECONDS)
.removeBlock(request);
}
@Override
public MoveBlockResponse moveBlock(MoveBlockRequest request) {
return mRpcBlockingStub.withDeadlineAfter(mRpcTimeoutMs, TimeUnit.MILLISECONDS)
.moveBlock(request);
}
@Override
public ClearMetricsResponse clearMetrics(ClearMetricsRequest request) {
return mRpcBlockingStub.withDeadlineAfter(mRpcTimeoutMs, TimeUnit.MILLISECONDS)
.clearMetrics(request);
}
@Override
public void cache(CacheRequest request) {
boolean async = request.getAsync();
try {
mRpcBlockingStub.withDeadlineAfter(mRpcTimeoutMs, TimeUnit.MILLISECONDS).cache(request);
} catch (Exception e) {
if (!async) {
throw e;
}
LOG.warn("Error sending async cache request {} to worker {}.", request, mAddress, e);
}
}
}
| apache-2.0 |
vorburger/mifos-head | acceptanceTests/src/test/java/org/mifos/test/acceptance/framework/loan/CreateLoanAccountSearchParameters.java | 1290 | /*
* Copyright (c) 2005-2010 Grameen Foundation USA
* 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.
*
* See also http://www.apache.org/licenses/LICENSE-2.0.html for an
* explanation of the license and how it is applied.
*/
package org.mifos.test.acceptance.framework.loan;
public class CreateLoanAccountSearchParameters {
private String searchString;
private String loanProduct;
public String getSearchString() {
return this.searchString;
}
public void setSearchString(String searchString) {
this.searchString = searchString;
}
public String getLoanProduct() {
return this.loanProduct;
}
public void setLoanProduct(String loanProduct) {
this.loanProduct = loanProduct;
}
}
| apache-2.0 |
ShikaSD/realm-java | realm/realm-library/src/androidTest/java/io/realm/internal/test/CodeGenTest.java | 901 | /*
* Copyright 2014 Realm 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.realm.internal.test;
import io.realm.internal.DefineTable;
/**
* A helper class containing model(s) for simple code generation tests.
*/
class CodeGenTest {
@DefineTable // this is enabled only for occasional local tests
class someModel {
String name;
int age;
}
}
| apache-2.0 |
WillJiang/WillJiang | src/plugins/json/src/test/java/org/apache/struts2/json/WrapperClassBean.java | 4821 | /*
* $Id: WrapperClassBean.java 799110 2009-07-29 22:44:26Z musachy $
*
* 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.struts2.json;
import java.util.List;
import java.util.Map;
public class WrapperClassBean {
private String stringField;
private Integer intField;
private int nullIntField;
private Boolean booleanField;
private boolean primitiveBooleanField1;
private boolean primitiveBooleanField2;
private boolean primitiveBooleanField3;
private Character charField;
private Long longField;
private Float floatField;
private Double doubleField;
private Object objectField;
private Byte byteField;
private List<SimpleValue> listField;
private List<Map<String, Long>> listMapField;
private Map<String, List<Long>> mapListField;
private Map<String, Long>[] arrayMapField;
public List<SimpleValue> getListField() {
return listField;
}
public void setListField(List<SimpleValue> listField) {
this.listField = listField;
}
public List<Map<String, Long>> getListMapField() {
return listMapField;
}
public void setListMapField(List<Map<String, Long>> listMapField) {
this.listMapField = listMapField;
}
public Map<String, List<Long>> getMapListField() {
return mapListField;
}
public void setMapListField(Map<String, List<Long>> mapListField) {
this.mapListField = mapListField;
}
public Map<String, Long>[] getArrayMapField() {
return arrayMapField;
}
public void setArrayMapField(Map<String, Long>[] arrayMapField) {
this.arrayMapField = arrayMapField;
}
public Boolean getBooleanField() {
return booleanField;
}
public void setBooleanField(Boolean booleanField) {
this.booleanField = booleanField;
}
public boolean isPrimitiveBooleanField1() {
return primitiveBooleanField1;
}
public void setPrimitiveBooleanField1(boolean primitiveBooleanField1) {
this.primitiveBooleanField1 = primitiveBooleanField1;
}
public boolean isPrimitiveBooleanField2() {
return primitiveBooleanField2;
}
public void setPrimitiveBooleanField2(boolean primitiveBooleanField2) {
this.primitiveBooleanField2 = primitiveBooleanField2;
}
public boolean isPrimitiveBooleanField3() {
return primitiveBooleanField3;
}
public void setPrimitiveBooleanField3(boolean primitiveBooleanField3) {
this.primitiveBooleanField3 = primitiveBooleanField3;
}
public Byte getByteField() {
return byteField;
}
public void setByteField(Byte byteField) {
this.byteField = byteField;
}
public Character getCharField() {
return charField;
}
public void setCharField(Character charField) {
this.charField = charField;
}
public Double getDoubleField() {
return doubleField;
}
public void setDoubleField(Double doubleField) {
this.doubleField = doubleField;
}
public Float getFloatField() {
return floatField;
}
public void setFloatField(Float floatField) {
this.floatField = floatField;
}
public Integer getIntField() {
return intField;
}
public void setIntField(Integer intField) {
this.intField = intField;
}
public int getNullIntField() {
return nullIntField;
}
public void setNullIntField(int nullIntField) {
this.nullIntField = nullIntField;
}
public Long getLongField() {
return longField;
}
public void setLongField(Long longField) {
this.longField = longField;
}
public Object getObjectField() {
return objectField;
}
public void setObjectField(Object objectField) {
this.objectField = objectField;
}
public String getStringField() {
return stringField;
}
public void setStringField(String stringField) {
this.stringField = stringField;
}
}
| apache-2.0 |
loicalbertin/alien4cloud | alien4cloud-core/src/main/java/alien4cloud/tosca/parser/mapping/generator/MappingGenerator.java | 12944 | package alien4cloud.tosca.parser.mapping.generator;
import java.io.IOException;
import java.util.AbstractMap;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.yaml.snakeyaml.nodes.MappingNode;
import org.yaml.snakeyaml.nodes.Node;
import org.yaml.snakeyaml.nodes.NodeTuple;
import org.yaml.snakeyaml.nodes.ScalarNode;
import org.yaml.snakeyaml.nodes.SequenceNode;
import alien4cloud.tosca.parser.IChecker;
import alien4cloud.tosca.parser.INodeParser;
import alien4cloud.tosca.parser.KeyValueMappingTarget;
import alien4cloud.tosca.parser.MappingTarget;
import alien4cloud.tosca.parser.ParserUtils;
import alien4cloud.tosca.parser.ParsingContextExecution;
import alien4cloud.tosca.parser.ParsingError;
import alien4cloud.tosca.parser.ParsingException;
import alien4cloud.tosca.parser.ParsingResult;
import alien4cloud.tosca.parser.YamlSimpleParser;
import alien4cloud.tosca.parser.impl.ErrorCode;
import alien4cloud.tosca.parser.impl.base.CheckedTypeNodeParser;
import alien4cloud.tosca.parser.impl.base.ScalarParser;
import alien4cloud.tosca.parser.impl.base.TypeNodeParser;
import alien4cloud.tosca.parser.mapping.DefaultParser;
import com.google.common.collect.Maps;
/**
* Load type mapping definition from yaml and add it to the type mapping registry.
*/
@Slf4j
@Component
public class MappingGenerator extends DefaultParser<Map<String, INodeParser>> {
@Resource
private ApplicationContext applicationContext;
private Map<String, INodeParser> parsers = Maps.newHashMap();
private Map<String, IMappingBuilder> mappingBuilders = Maps.newHashMap();
private Map<String, IChecker> checkers = Maps.newHashMap();
@PostConstruct
public void initialize() {
Map<String, INodeParser> contextParsers = applicationContext.getBeansOfType(INodeParser.class);
// register parsers based on their class name.
for (INodeParser parser : contextParsers.values()) {
parsers.put(parser.getClass().getName(), parser);
}
Map<String, IMappingBuilder> contextMappingBuilders = applicationContext.getBeansOfType(IMappingBuilder.class);
for (IMappingBuilder mappingBuilder : contextMappingBuilders.values()) {
mappingBuilders.put(mappingBuilder.getKey(), mappingBuilder);
}
Map<String, IChecker> contextCheckers = applicationContext.getBeansOfType(IChecker.class);
for (IChecker checker : contextCheckers.values()) {
checkers.put(checker.getName(), checker);
}
}
public Map<String, INodeParser> process(String resourceLocation) throws ParsingException {
org.springframework.core.io.Resource resource = applicationContext.getResource(resourceLocation);
YamlSimpleParser<Map<String, INodeParser>> nodeParser = new YamlSimpleParser<>(this);
try {
ParsingResult<Map<String, INodeParser>> result = nodeParser.parseFile(resource.getURI().toString(), resource.getFilename(),
resource.getInputStream(), null);
if (result.getContext().getParsingErrors().isEmpty()) {
return result.getResult();
}
throw new ParsingException(resource.getFilename(), result.getContext().getParsingErrors());
} catch (IOException e) {
log.error("Failed to open stream", e);
throw new ParsingException(resource.getFilename(), new ParsingError(ErrorCode.MISSING_FILE, "Unable to load file.", null, e.getMessage(), null,
resourceLocation));
}
}
public Map<String, INodeParser> parse(Node node, ParsingContextExecution context) {
Map<String, INodeParser> parsers = Maps.newHashMap();
if (node instanceof SequenceNode) {
SequenceNode types = (SequenceNode) node;
for (Node mapping : types.getValue()) {
Map.Entry<String, INodeParser<?>> entry = processTypeMapping(mapping, context);
if (entry != null) {
parsers.put(entry.getKey(), entry.getValue());
}
}
} else {
context.getParsingErrors().add(
new ParsingError(ErrorCode.SYNTAX_ERROR, "Mapping should be a sequence of type mappings", node.getStartMark(), "Actually was "
+ node.getClass().getSimpleName(), node.getEndMark(), ""));
}
return parsers;
}
private Map.Entry<String, INodeParser<?>> processTypeMapping(Node node, ParsingContextExecution context) {
try {
return doProcessTypeMapping(node, context);
} catch (ClassNotFoundException | IllegalAccessException | InstantiationException e) {
log.error("Failed to load class while parsing mapping", e);
context.getParsingErrors().add(
new ParsingError(ErrorCode.SYNTAX_ERROR, "Unable to load class", node.getStartMark(), e.getMessage(), node.getEndMark(), ""));
return null;
}
}
private Map.Entry<String, INodeParser<?>> doProcessTypeMapping(Node node, ParsingContextExecution context) throws ClassNotFoundException,
IllegalAccessException, InstantiationException {
if (node instanceof MappingNode) {
MappingNode mapping = (MappingNode) node;
String yamlType = null;
INodeParser<?> parser = null;
for (NodeTuple tuple : mapping.getValue()) {
if (yamlType == null) {
yamlType = ParserUtils.getScalar(tuple.getKeyNode(), context);
String type = ParserUtils.getScalar(tuple.getValueNode(), context);
if (type.startsWith("__")) {
parser = getWrapperParser(type, mapping, context);
return new AbstractMap.SimpleEntry<String, INodeParser<?>>(yamlType, parser);
}
parser = this.parsers.get(type);
if (parser != null) {
log.debug("Mapping yaml type <" + yamlType + "> using parser <" + type + ">");
return new AbstractMap.SimpleEntry<String, INodeParser<?>>(yamlType, parser);
}
parser = buildTypeNodeParser(yamlType, type);
// log.debug("Mapping yaml type <" + yamlType + "> to class <" + type + ">");
// Class<?> javaClass = Class.forName(type);
// parser = new TypeNodeParser<>(javaClass, yamlType);
} else {
// process a mapping
map(tuple, (TypeNodeParser) parser, context);
}
}
return new AbstractMap.SimpleEntry<String, INodeParser<?>>(yamlType, parser);
} else {
context.getParsingErrors().add(
new ParsingError(ErrorCode.SYNTAX_ERROR, "Unable to process type mapping.", node.getStartMark(),
"Mapping must be defined using a mapping node.", node.getEndMark(), ""));
}
return null;
}
private TypeNodeParser<?> buildTypeNodeParser(String yamlType, String javaType) throws ClassNotFoundException {
String realJavaType = javaType;
IChecker checker = null;
if (javaType.contains("|")) {
realJavaType = javaType.substring(0, javaType.indexOf("|"));
String checkerName = javaType.substring(javaType.indexOf("|") + 1);
log.debug(String.format("After parsing <%s>, realJavaType is <%s>, checkerName is <%s>", javaType, realJavaType, checkerName));
checker = checkers.get(checkerName);
if (checker == null) {
log.warn(String.format("Can not find checker <%s>, using a standard TypeNodeParser", checkerName));
}
}
Class<?> javaClass = Class.forName(realJavaType);
if (checker == null) {
log.debug("Mapping yaml type <" + yamlType + "> to class <" + realJavaType + ">");
return new TypeNodeParser<>(javaClass, yamlType);
} else {
// TODO check that the type are compatible
log.debug("Mapping yaml type <" + yamlType + "> to class <" + realJavaType + "> using checker " + checker.toString());
return new CheckedTypeNodeParser<>(javaClass, yamlType, checker);
}
}
private INodeParser<?> getWrapperParser(String wrapperKey, MappingNode mapping, ParsingContextExecution context) {
IMappingBuilder builder = this.mappingBuilders.get(wrapperKey.substring(2));
return builder.buildMapping(mapping, context).getParser();
}
private void map(NodeTuple tuple, TypeNodeParser<?> parser, ParsingContextExecution context) {
String key = ParserUtils.getScalar(tuple.getKeyNode(), context);
int positionMappingIndex = positionMappingIndex(key);
if (positionMappingIndex > -1) {
mapPositionMapping(positionMappingIndex, tuple.getValueNode(), parser, context);
} else {
MappingTarget mappingTarget = getMappingTarget(tuple.getValueNode(), context);
if (mappingTarget != null) {
parser.getYamlToObjectMapping().put(key, mappingTarget);
}
}
}
private MappingTarget getMappingTarget(Node mappingNode, ParsingContextExecution context) {
if (mappingNode instanceof ScalarNode) {
// create a scalar mapping
String value = ParserUtils.getScalar(mappingNode, context);
return new MappingTarget(value, parsers.get(ScalarParser.class.getName()));
} else if (mappingNode instanceof MappingNode) {
return mapMappingNode((MappingNode) mappingNode, context);
}
return null;
}
private int positionMappingIndex(String key) {
if (key.startsWith("__")) {
try {
int position = Integer.valueOf(key.substring(2));
return position;
} catch (NumberFormatException e) {
// not a position mapping
return -1;
}
}
return -1;
}
private void mapPositionMapping(Integer index, Node positionMapping, TypeNodeParser<?> parser, ParsingContextExecution context) {
if (positionMapping instanceof MappingNode) {
MappingNode mappingNode = (MappingNode) positionMapping;
String key = null;
MappingTarget valueMappingTarget = null;
for (NodeTuple tuple : mappingNode.getValue()) {
String tupleKey = ParserUtils.getScalar(tuple.getKeyNode(), context);
if (tupleKey.equals("key")) {
key = ParserUtils.getScalar(tuple.getValueNode(), context);
} else if (tupleKey.equals("value")) {
valueMappingTarget = getMappingTarget(tuple.getValueNode(), context);
} else {
context.getParsingErrors().add(
new ParsingError(ErrorCode.SYNTAX_ERROR, "Unknown key for position mapping.", tuple.getKeyNode().getStartMark(), tupleKey, tuple
.getKeyNode().getEndMark(), ""));
}
}
if (valueMappingTarget == null) {
return;
}
if (key == null) {
parser.getYamlOrderedToObjectMapping().put(index, valueMappingTarget);
} else {
parser.getYamlOrderedToObjectMapping().put(index, new KeyValueMappingTarget(key, valueMappingTarget.getPath(), valueMappingTarget.getParser()));
}
} else {
context.getParsingErrors().add(
new ParsingError(ErrorCode.SYNTAX_ERROR, "Position mapping must be a mapping node with key and value fields.", positionMapping
.getStartMark(), "", positionMapping.getEndMark(), ""));
}
}
private MappingTarget mapMappingNode(MappingNode mappingNode, ParsingContextExecution context) {
String key = ParserUtils.getScalar(mappingNode.getValue().get(0).getKeyNode(), context);
IMappingBuilder mappingBuilder = mappingBuilders.get(key);
if (mappingBuilder != null) {
log.debug("Mapping yaml key <" + key + "> using mapping builder " + mappingBuilder.getClass().getName());
return mappingBuilder.buildMapping(mappingNode, context);
}
context.getParsingErrors().add(
new ParsingError(ErrorCode.SYNTAX_ERROR, "No mapping target found for key", mappingNode.getValue().get(0).getKeyNode().getStartMark(), key,
mappingNode.getValue().get(0).getKeyNode().getEndMark(), ""));
return null;
}
} | apache-2.0 |
foryou2030/incubator-carbondata | core/src/test/java/org/apache/carbondata/core/writer/sortindex/CarbonDictionarySortIndexWriterImplTest.java | 6533 | /*
* 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.carbondata.core.writer.sortindex;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import org.apache.carbondata.core.carbon.CarbonTableIdentifier;
import org.apache.carbondata.core.carbon.ColumnIdentifier;
import org.apache.carbondata.core.datastorage.store.filesystem.CarbonFile;
import org.apache.carbondata.core.datastorage.store.impl.FileFactory;
import org.apache.carbondata.core.reader.sortindex.CarbonDictionarySortIndexReader;
import org.apache.carbondata.core.reader.sortindex.CarbonDictionarySortIndexReaderImpl;
import org.apache.carbondata.core.util.CarbonUtil;
import org.apache.carbondata.core.writer.CarbonDictionaryWriter;
import org.apache.carbondata.core.writer.CarbonDictionaryWriterImpl;
import org.apache.commons.lang.ArrayUtils;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
/**
* class contains the unit test cases of the dictionary sort index & sort index inverted writing
*/
public class CarbonDictionarySortIndexWriterImplTest {
private String hdfsStorePath;
@Before public void setUp() throws Exception {
hdfsStorePath = "target/carbonStore";
}
@After public void tearDown() throws Exception {
//deleteStorePath();
}
/**
* s
* Method to test the write of sortIndex file.
*
* @throws Exception
*/
@Test public void write() throws Exception {
String storePath = hdfsStorePath;
CarbonTableIdentifier carbonTableIdentifier = new CarbonTableIdentifier("testSchema", "carbon", UUID.randomUUID().toString());
ColumnIdentifier columnIdentifier = new ColumnIdentifier("Name", null, null);
String metaFolderPath =hdfsStorePath+File.separator+carbonTableIdentifier.getDatabaseName()+File.separator+carbonTableIdentifier.getTableName()+File.separator+"Metadata";
CarbonUtil.checkAndCreateFolder(metaFolderPath);
CarbonDictionaryWriter dictionaryWriter = new CarbonDictionaryWriterImpl(hdfsStorePath,
carbonTableIdentifier, columnIdentifier);
CarbonDictionarySortIndexWriter dictionarySortIndexWriter =
new CarbonDictionarySortIndexWriterImpl(carbonTableIdentifier, columnIdentifier, storePath);
List<int[]> indexList = prepareExpectedData();
int[] data = indexList.get(0);
for(int i=0;i<data.length;i++) {
dictionaryWriter.write(String.valueOf(data[i]));
}
dictionaryWriter.close();
dictionaryWriter.commit();
List<Integer> sortIndex = Arrays.asList(ArrayUtils.toObject(indexList.get(0)));
List<Integer> invertedSortIndex = Arrays.asList(ArrayUtils.toObject(indexList.get(1)));
dictionarySortIndexWriter.writeSortIndex(sortIndex);
dictionarySortIndexWriter.writeInvertedSortIndex(invertedSortIndex);
dictionarySortIndexWriter.close();
CarbonDictionarySortIndexReader carbonDictionarySortIndexReader =
new CarbonDictionarySortIndexReaderImpl(carbonTableIdentifier, columnIdentifier, storePath);
List<Integer> actualSortIndex = carbonDictionarySortIndexReader.readSortIndex();
List<Integer> actualInvertedSortIndex = carbonDictionarySortIndexReader.readInvertedSortIndex();
for (int i = 0; i < actualSortIndex.size(); i++) {
Assert.assertEquals(sortIndex.get(i), actualSortIndex.get(i));
Assert.assertEquals(invertedSortIndex.get(i), actualInvertedSortIndex.get(i));
}
}
/**
* @throws Exception
*/
@Test public void writingEmptyValue() throws Exception {
String storePath = hdfsStorePath;
CarbonTableIdentifier carbonTableIdentifier = new CarbonTableIdentifier("testSchema", "carbon", UUID.randomUUID().toString());
ColumnIdentifier columnIdentifier = new ColumnIdentifier("Name", null, null);
CarbonDictionarySortIndexWriter dictionarySortIndexWriter =
new CarbonDictionarySortIndexWriterImpl(carbonTableIdentifier, columnIdentifier, storePath);
List<Integer> sortIndex = new ArrayList<>();
List<Integer> invertedSortIndex = new ArrayList<>();
dictionarySortIndexWriter.writeSortIndex(sortIndex);
dictionarySortIndexWriter.writeInvertedSortIndex(invertedSortIndex);
dictionarySortIndexWriter.close();
CarbonDictionarySortIndexReader carbonDictionarySortIndexReader =
new CarbonDictionarySortIndexReaderImpl(carbonTableIdentifier, columnIdentifier, storePath);
List<Integer> actualSortIndex = carbonDictionarySortIndexReader.readSortIndex();
List<Integer> actualInvertedSortIndex = carbonDictionarySortIndexReader.readInvertedSortIndex();
for (int i = 0; i < actualSortIndex.size(); i++) {
Assert.assertEquals(sortIndex.get(i), actualSortIndex.get(i));
Assert.assertEquals(invertedSortIndex.get(i), actualInvertedSortIndex.get(i));
}
}
private List<int[]> prepareExpectedData() {
List<int[]> indexList = new ArrayList<>(2);
int[] sortIndex = { 0, 3, 2, 4, 1 };
int[] sortIndexInverted = { 0, 2, 4, 1, 2 };
indexList.add(0, sortIndex);
indexList.add(1, sortIndexInverted);
return indexList;
}
/**
* this method will delete the store path
*/
private void deleteStorePath() {
FileFactory.FileType fileType = FileFactory.getFileType(this.hdfsStorePath);
CarbonFile carbonFile = FileFactory.getCarbonFile(this.hdfsStorePath, fileType);
deleteRecursiveSilent(carbonFile);
}
/**
* this method will delete the folders recursively
*/
private static void deleteRecursiveSilent(CarbonFile f) {
if (f.isDirectory()) {
if (f.listFiles() != null) {
for (CarbonFile c : f.listFiles()) {
deleteRecursiveSilent(c);
}
}
}
if (f.exists() && !f.delete()) {
return;
}
}
}
| apache-2.0 |
bbrehman/wte4j | wte4j-core/src/main/java/org/wte4j/impl/service/MapperSqlType.java | 2743 | /**
* Copyright (C) 2015 Born Informatik AG (www.born.ch)
*
* 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.wte4j.impl.service;
import org.wte4j.WteException;
/**
* Map JDBC types (as defined in <code>java.sql.Types</code>) to Java types. The
* mappings have been taken from [1]
* "JDBC 4.0 Specification, JSR 221, November 7, 2006, Appendix B, Table B-3"
*
*/
final class MapperSqlType {
private MapperSqlType() {
};
public static Class<?> map(int jdbcType) {
switch (jdbcType) {
case java.sql.Types.BIT:
case java.sql.Types.BOOLEAN:
return java.lang.Boolean.class;
case java.sql.Types.TINYINT:
case java.sql.Types.SMALLINT:
case java.sql.Types.INTEGER:
return java.lang.Integer.class;
case java.sql.Types.BIGINT:
return java.lang.Long.class;
case java.sql.Types.FLOAT:
case java.sql.Types.DOUBLE:
return java.lang.Double.class;
case java.sql.Types.REAL:
return java.lang.Float.class;
case java.sql.Types.NUMERIC: // according to [1] Table B-1
case java.sql.Types.DECIMAL:
return java.math.BigDecimal.class;
case java.sql.Types.CHAR:
case java.sql.Types.VARCHAR:
case java.sql.Types.LONGVARCHAR:
return java.lang.String.class;
case java.sql.Types.DATE:
return java.sql.Date.class;
case java.sql.Types.TIME:
return java.sql.Time.class;
case java.sql.Types.TIMESTAMP:
return java.sql.Timestamp.class;
case java.sql.Types.STRUCT:
return java.sql.Struct.class;
case java.sql.Types.ARRAY:
return java.sql.Array.class;
case java.sql.Types.BLOB:
return java.sql.Blob.class;
case java.sql.Types.CLOB:
return java.sql.Clob.class;
case java.sql.Types.REF:
return java.sql.Ref.class;
case java.sql.Types.DATALINK:
return java.net.URL.class;
case java.sql.Types.ROWID:
return java.sql.RowId.class;
case java.sql.Types.NULL:
case java.sql.Types.OTHER:
case java.sql.Types.JAVA_OBJECT:
case java.sql.Types.DISTINCT:
case java.sql.Types.BINARY:
case java.sql.Types.VARBINARY:
case java.sql.Types.LONGVARBINARY:
default:
throw new WteException("invalid or unmapped SQL type (" + jdbcType
+ ")");
}
}
}
| apache-2.0 |
yrcourage/netty | handler/src/main/java/io/netty/handler/ssl/OpenSsl.java | 11625 | /*
* Copyright 2014 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.handler.ssl;
import io.netty.buffer.ByteBuf;
import io.netty.util.internal.NativeLibraryLoader;
import io.netty.util.internal.SystemPropertyUtil;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import org.apache.tomcat.jni.Buffer;
import org.apache.tomcat.jni.Library;
import org.apache.tomcat.jni.Pool;
import org.apache.tomcat.jni.SSL;
import org.apache.tomcat.jni.SSLContext;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Locale;
import java.util.Set;
/**
* Tells if <a href="http://netty.io/wiki/forked-tomcat-native.html">{@code netty-tcnative}</a> and its OpenSSL support
* are available.
*/
public final class OpenSsl {
private static final InternalLogger logger = InternalLoggerFactory.getInstance(OpenSsl.class);
private static final String LINUX = "linux";
private static final String UNKNOWN = "unknown";
private static final Throwable UNAVAILABILITY_CAUSE;
private static final Set<String> AVAILABLE_CIPHER_SUITES;
static {
Throwable cause = null;
// Test if netty-tcnative is in the classpath first.
try {
Class.forName("org.apache.tomcat.jni.SSL", false, OpenSsl.class.getClassLoader());
} catch (ClassNotFoundException t) {
cause = t;
logger.debug(
"netty-tcnative not in the classpath; " +
OpenSslEngine.class.getSimpleName() + " will be unavailable.");
}
// If in the classpath, try to load the native library and initialize netty-tcnative.
if (cause == null) {
try {
// The JNI library was not already loaded. Load it now.
loadTcNative();
} catch (Throwable t) {
cause = t;
logger.debug(
"Failed to load netty-tcnative; " +
OpenSslEngine.class.getSimpleName() + " will be unavailable, unless the " +
"application has already loaded the symbols by some other means. " +
"See http://netty.io/wiki/forked-tomcat-native.html for more information.", t);
}
try {
initializeTcNative();
// The library was initialized successfully. If loading the library failed above,
// reset the cause now since it appears that the library was loaded by some other
// means.
cause = null;
} catch (Throwable t) {
if (cause == null) {
cause = t;
}
logger.debug(
"Failed to initialize netty-tcnative; " +
OpenSslEngine.class.getSimpleName() + " will be unavailable. " +
"See http://netty.io/wiki/forked-tomcat-native.html for more information.", t);
}
}
UNAVAILABILITY_CAUSE = cause;
if (cause == null) {
final Set<String> availableCipherSuites = new LinkedHashSet<String>(128);
final long aprPool = Pool.create(0);
try {
final long sslCtx = SSLContext.make(aprPool, SSL.SSL_PROTOCOL_ALL, SSL.SSL_MODE_SERVER);
try {
SSLContext.setOptions(sslCtx, SSL.SSL_OP_ALL);
SSLContext.setCipherSuite(sslCtx, "ALL");
final long ssl = SSL.newSSL(sslCtx, true);
try {
for (String c: SSL.getCiphers(ssl)) {
// Filter out bad input.
if (c == null || c.length() == 0 || availableCipherSuites.contains(c)) {
continue;
}
availableCipherSuites.add(c);
}
} finally {
SSL.freeSSL(ssl);
}
} finally {
SSLContext.free(sslCtx);
}
} catch (Exception e) {
logger.warn("Failed to get the list of available OpenSSL cipher suites.", e);
} finally {
Pool.destroy(aprPool);
}
AVAILABLE_CIPHER_SUITES = Collections.unmodifiableSet(availableCipherSuites);
} else {
AVAILABLE_CIPHER_SUITES = Collections.emptySet();
}
}
/**
* Returns {@code true} if and only if
* <a href="http://netty.io/wiki/forked-tomcat-native.html">{@code netty-tcnative}</a> and its OpenSSL support
* are available.
*/
public static boolean isAvailable() {
return UNAVAILABILITY_CAUSE == null;
}
/**
* Returns {@code true} if the used version of openssl supports
* <a href="https://tools.ietf.org/html/rfc7301">ALPN</a>.
*/
public static boolean isAlpnSupported() {
return version() >= 0x10002000L;
}
/**
* Returns the version of the used available OpenSSL library or {@code -1} if {@link #isAvailable()}
* returns {@code false}.
*/
public static int version() {
if (isAvailable()) {
return SSL.version();
}
return -1;
}
/**
* Returns the version string of the used available OpenSSL library or {@code null} if {@link #isAvailable()}
* returns {@code false}.
*/
public static String versionString() {
if (isAvailable()) {
return SSL.versionString();
}
return null;
}
/**
* Ensure that <a href="http://netty.io/wiki/forked-tomcat-native.html">{@code netty-tcnative}</a> and
* its OpenSSL support are available.
*
* @throws UnsatisfiedLinkError if unavailable
*/
public static void ensureAvailability() {
if (UNAVAILABILITY_CAUSE != null) {
throw (Error) new UnsatisfiedLinkError(
"failed to load the required native library").initCause(UNAVAILABILITY_CAUSE);
}
}
/**
* Returns the cause of unavailability of
* <a href="http://netty.io/wiki/forked-tomcat-native.html">{@code netty-tcnative}</a> and its OpenSSL support.
*
* @return the cause if unavailable. {@code null} if available.
*/
public static Throwable unavailabilityCause() {
return UNAVAILABILITY_CAUSE;
}
/**
* Returns all the available OpenSSL cipher suites.
* Please note that the returned array may include the cipher suites that are insecure or non-functional.
*/
public static Set<String> availableCipherSuites() {
return AVAILABLE_CIPHER_SUITES;
}
/**
* Returns {@code true} if and only if the specified cipher suite is available in OpenSSL.
* Both Java-style cipher suite and OpenSSL-style cipher suite are accepted.
*/
public static boolean isCipherSuiteAvailable(String cipherSuite) {
String converted = CipherSuiteConverter.toOpenSsl(cipherSuite);
if (converted != null) {
cipherSuite = converted;
}
return AVAILABLE_CIPHER_SUITES.contains(cipherSuite);
}
static boolean isError(long errorCode) {
return errorCode != SSL.SSL_ERROR_NONE;
}
static long memoryAddress(ByteBuf buf) {
assert buf.isDirect();
return buf.hasMemoryAddress() ? buf.memoryAddress() : Buffer.address(buf.nioBuffer());
}
private OpenSsl() { }
private static void loadTcNative() throws Exception {
String os = normalizeOs(SystemPropertyUtil.get("os.name", ""));
String arch = normalizeArch(SystemPropertyUtil.get("os.arch", ""));
Set<String> libNames = new LinkedHashSet<String>(3);
// First, try loading the platform-specific library. Platform-specific
// libraries will be available if using a tcnative uber jar.
libNames.add("netty-tcnative-" + os + '-' + arch);
if (LINUX.equalsIgnoreCase(os)) {
// Fedora SSL lib so naming (libssl.so.10 vs libssl.so.1.0.0)..
libNames.add("netty-tcnative-" + os + '-' + arch + "-fedora");
}
// finally the default library.
libNames.add("netty-tcnative");
NativeLibraryLoader.loadFirstAvailable(SSL.class.getClassLoader(),
libNames.toArray(new String[libNames.size()]));
}
private static void initializeTcNative() throws Exception {
Library.initialize("provided");
SSL.initialize(null);
}
private static String normalizeOs(String value) {
value = normalize(value);
if (value.startsWith("aix")) {
return "aix";
}
if (value.startsWith("hpux")) {
return "hpux";
}
if (value.startsWith("os400")) {
// Avoid the names such as os4000
if (value.length() <= 5 || !Character.isDigit(value.charAt(5))) {
return "os400";
}
}
if (value.startsWith(LINUX)) {
return LINUX;
}
if (value.startsWith("macosx") || value.startsWith("osx")) {
return "osx";
}
if (value.startsWith("freebsd")) {
return "freebsd";
}
if (value.startsWith("openbsd")) {
return "openbsd";
}
if (value.startsWith("netbsd")) {
return "netbsd";
}
if (value.startsWith("solaris") || value.startsWith("sunos")) {
return "sunos";
}
if (value.startsWith("windows")) {
return "windows";
}
return UNKNOWN;
}
private static String normalizeArch(String value) {
value = normalize(value);
if (value.matches("^(x8664|amd64|ia32e|em64t|x64)$")) {
return "x86_64";
}
if (value.matches("^(x8632|x86|i[3-6]86|ia32|x32)$")) {
return "x86_32";
}
if (value.matches("^(ia64|itanium64)$")) {
return "itanium_64";
}
if (value.matches("^(sparc|sparc32)$")) {
return "sparc_32";
}
if (value.matches("^(sparcv9|sparc64)$")) {
return "sparc_64";
}
if (value.matches("^(arm|arm32)$")) {
return "arm_32";
}
if ("aarch64".equals(value)) {
return "aarch_64";
}
if (value.matches("^(ppc|ppc32)$")) {
return "ppc_32";
}
if ("ppc64".equals(value)) {
return "ppc_64";
}
if ("ppc64le".equals(value)) {
return "ppcle_64";
}
if ("s390".equals(value)) {
return "s390_32";
}
if ("s390x".equals(value)) {
return "s390_64";
}
return UNKNOWN;
}
private static String normalize(String value) {
return value.toLowerCase(Locale.US).replaceAll("[^a-z0-9]+", "");
}
}
| apache-2.0 |
igniterealtime/Smack | smack-omemo/src/main/java/org/jivesoftware/smackx/omemo/OmemoManager.java | 49782 | /**
*
* Copyright 2017 Paul Schaub, 2020 Florian Schmaus
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smackx.omemo;
import static org.jivesoftware.smackx.omemo.util.OmemoConstants.OMEMO_NAMESPACE_V_AXOLOTL;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.WeakHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jivesoftware.smack.ConnectionListener;
import org.jivesoftware.smack.Manager;
import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.SmackException.NotConnectedException;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.MessageBuilder;
import org.jivesoftware.smack.packet.Stanza;
import org.jivesoftware.smack.util.Async;
import org.jivesoftware.smackx.carbons.CarbonManager;
import org.jivesoftware.smackx.carbons.packet.CarbonExtension;
import org.jivesoftware.smackx.disco.ServiceDiscoveryManager;
import org.jivesoftware.smackx.hints.element.StoreHint;
import org.jivesoftware.smackx.mam.MamManager;
import org.jivesoftware.smackx.muc.MultiUserChat;
import org.jivesoftware.smackx.muc.MultiUserChatManager;
import org.jivesoftware.smackx.muc.RoomInfo;
import org.jivesoftware.smackx.omemo.element.OmemoBundleElement;
import org.jivesoftware.smackx.omemo.element.OmemoDeviceListElement;
import org.jivesoftware.smackx.omemo.element.OmemoDeviceListElement_VAxolotl;
import org.jivesoftware.smackx.omemo.element.OmemoElement;
import org.jivesoftware.smackx.omemo.exceptions.CannotEstablishOmemoSessionException;
import org.jivesoftware.smackx.omemo.exceptions.CorruptedOmemoKeyException;
import org.jivesoftware.smackx.omemo.exceptions.CryptoFailedException;
import org.jivesoftware.smackx.omemo.exceptions.NoOmemoSupportException;
import org.jivesoftware.smackx.omemo.exceptions.NoRawSessionException;
import org.jivesoftware.smackx.omemo.exceptions.UndecidedOmemoIdentityException;
import org.jivesoftware.smackx.omemo.internal.OmemoCachedDeviceList;
import org.jivesoftware.smackx.omemo.internal.OmemoDevice;
import org.jivesoftware.smackx.omemo.listener.OmemoMessageListener;
import org.jivesoftware.smackx.omemo.listener.OmemoMucMessageListener;
import org.jivesoftware.smackx.omemo.trust.OmemoFingerprint;
import org.jivesoftware.smackx.omemo.trust.OmemoTrustCallback;
import org.jivesoftware.smackx.omemo.trust.TrustState;
import org.jivesoftware.smackx.omemo.util.MessageOrOmemoMessage;
import org.jivesoftware.smackx.omemo.util.OmemoConstants;
import org.jivesoftware.smackx.pep.PepEventListener;
import org.jivesoftware.smackx.pep.PepManager;
import org.jivesoftware.smackx.pubsub.PubSubException;
import org.jivesoftware.smackx.pubsub.PubSubManager;
import org.jivesoftware.smackx.pubsub.packet.PubSub;
import org.jxmpp.jid.BareJid;
import org.jxmpp.jid.DomainBareJid;
import org.jxmpp.jid.EntityBareJid;
import org.jxmpp.jid.EntityFullJid;
/**
* Manager that allows sending messages encrypted with OMEMO.
* This class also provides some methods useful for a client that implements OMEMO.
*
* @author Paul Schaub
*/
public final class OmemoManager extends Manager {
private static final Logger LOGGER = Logger.getLogger(OmemoManager.class.getName());
private static final Integer UNKNOWN_DEVICE_ID = -1;
private static final WeakHashMap<XMPPConnection, TreeMap<Integer, OmemoManager>> INSTANCES = new WeakHashMap<>();
private final OmemoService<?, ?, ?, ?, ?, ?, ?, ?, ?> service;
private final HashSet<OmemoMessageListener> omemoMessageListeners = new HashSet<>();
private final HashSet<OmemoMucMessageListener> omemoMucMessageListeners = new HashSet<>();
private final PepManager pepManager;
private OmemoTrustCallback trustCallback;
private BareJid ownJid;
private Integer deviceId;
/**
* Private constructor.
*
* @param connection connection
* @param deviceId deviceId
*/
private OmemoManager(XMPPConnection connection, Integer deviceId) {
super(connection);
service = OmemoService.getInstance();
pepManager = PepManager.getInstanceFor(connection);
this.deviceId = deviceId;
if (connection.isAuthenticated()) {
initBareJidAndDeviceId(this);
} else {
connection.addConnectionListener(new ConnectionListener() {
@Override
public void authenticated(XMPPConnection connection, boolean resumed) {
initBareJidAndDeviceId(OmemoManager.this);
}
});
}
service.registerRatchetForManager(this);
// StanzaListeners
resumeStanzaAndPEPListeners();
}
/**
* Return an OmemoManager instance for the given connection and deviceId.
* If there was an OmemoManager for the connection and id before, return it. Otherwise create a new OmemoManager
* instance and return it.
*
* @param connection XmppConnection.
* @param deviceId MUST NOT be null and MUST be greater than 0.
*
* @return OmemoManager instance for the given connection and deviceId.
*/
public static synchronized OmemoManager getInstanceFor(XMPPConnection connection, Integer deviceId) {
if (deviceId == null || deviceId < 1) {
throw new IllegalArgumentException("DeviceId MUST NOT be null and MUST be greater than 0.");
}
TreeMap<Integer, OmemoManager> managersOfConnection = INSTANCES.get(connection);
if (managersOfConnection == null) {
managersOfConnection = new TreeMap<>();
INSTANCES.put(connection, managersOfConnection);
}
OmemoManager manager = managersOfConnection.get(deviceId);
if (manager == null) {
manager = new OmemoManager(connection, deviceId);
managersOfConnection.put(deviceId, manager);
}
return manager;
}
/**
* Returns an OmemoManager instance for the given connection. If there was one manager for the connection before,
* return it. If there were multiple managers before, return the one with the lowest deviceId.
* If there was no manager before, return a new one. As soon as the connection gets authenticated, the manager
* will look for local deviceIDs and select the lowest one as its id. If there are not local deviceIds, the manager
* will assign itself a random id.
*
* @param connection XmppConnection.
*
* @return OmemoManager instance for the given connection and a determined deviceId.
*/
public static synchronized OmemoManager getInstanceFor(XMPPConnection connection) {
TreeMap<Integer, OmemoManager> managers = INSTANCES.get(connection);
if (managers == null) {
managers = new TreeMap<>();
INSTANCES.put(connection, managers);
}
OmemoManager manager;
if (managers.size() == 0) {
manager = new OmemoManager(connection, UNKNOWN_DEVICE_ID);
managers.put(UNKNOWN_DEVICE_ID, manager);
} else {
manager = managers.get(managers.firstKey());
}
return manager;
}
/**
* Set a TrustCallback for this particular OmemoManager.
* TrustCallbacks are used to query and modify trust decisions.
*
* @param callback trustCallback.
*/
public void setTrustCallback(OmemoTrustCallback callback) {
if (trustCallback != null) {
throw new IllegalStateException("TrustCallback can only be set once.");
}
trustCallback = callback;
}
/**
* Return the TrustCallback of this manager.
*
* @return callback that is used for trust decisions.
*/
OmemoTrustCallback getTrustCallback() {
return trustCallback;
}
/**
* Initializes the OmemoManager. This method must be called before the manager can be used.
*
* @throws CorruptedOmemoKeyException if the OMEMO key is corrupted.
* @throws InterruptedException if the calling thread was interrupted.
* @throws SmackException.NoResponseException if there was no response from the remote entity.
* @throws SmackException.NotConnectedException if the XMPP connection is not connected.
* @throws XMPPException.XMPPErrorException if there was an XMPP error returned.
* @throws SmackException.NotLoggedInException if the XMPP connection is not authenticated.
* @throws PubSubException.NotALeafNodeException if a PubSub leaf node operation was attempted on a non-leaf node.
* @throws IOException if an I/O error occurred.
*/
public synchronized void initialize()
throws SmackException.NotLoggedInException, CorruptedOmemoKeyException, InterruptedException,
SmackException.NoResponseException, SmackException.NotConnectedException, XMPPException.XMPPErrorException,
PubSubException.NotALeafNodeException, IOException {
if (!connection().isAuthenticated()) {
throw new SmackException.NotLoggedInException();
}
if (getTrustCallback() == null) {
throw new IllegalStateException("No TrustCallback set.");
}
getOmemoService().init(new LoggedInOmemoManager(this));
}
/**
* Initialize the manager without blocking. Once the manager is successfully initialized, the finishedCallback will
* be notified. It will also get notified, if an error occurs.
*
* @param finishedCallback callback that gets called once the manager is initialized.
*/
public void initializeAsync(final InitializationFinishedCallback finishedCallback) {
Async.go(new Runnable() {
@Override
public void run() {
try {
initialize();
finishedCallback.initializationFinished(OmemoManager.this);
} catch (Exception e) {
finishedCallback.initializationFailed(e);
}
}
});
}
/**
* Return a set of all OMEMO capable devices of a contact.
* Note, that this method does not explicitly refresh the device list of the contact, so it might be outdated.
*
* @see #requestDeviceListUpdateFor(BareJid)
*
* @param contact contact we want to get a set of device of.
* @return set of known devices of that contact.
*
* @throws IOException if an I/O error occurred.
*/
public Set<OmemoDevice> getDevicesOf(BareJid contact) throws IOException {
OmemoCachedDeviceList list = getOmemoService().getOmemoStoreBackend().loadCachedDeviceList(getOwnDevice(), contact);
HashSet<OmemoDevice> devices = new HashSet<>();
for (int deviceId : list.getActiveDevices()) {
devices.add(new OmemoDevice(contact, deviceId));
}
return devices;
}
/**
* OMEMO encrypt a cleartext message for a single recipient.
* Note that this method does NOT set the 'to' attribute of the message.
*
* @param recipient recipients bareJid
* @param message text to encrypt
* @return encrypted message
*
* @throws CryptoFailedException when something crypto related fails
* @throws UndecidedOmemoIdentityException When there are undecided devices
* @throws InterruptedException if the calling thread was interrupted.
* @throws SmackException.NotConnectedException if the XMPP connection is not connected.
* @throws SmackException.NoResponseException if there was no response from the remote entity.
* @throws SmackException.NotLoggedInException if the XMPP connection is not authenticated.
* @throws IOException if an I/O error occurred.
*/
public OmemoMessage.Sent encrypt(BareJid recipient, String message)
throws CryptoFailedException, UndecidedOmemoIdentityException,
InterruptedException, SmackException.NotConnectedException,
SmackException.NoResponseException, SmackException.NotLoggedInException, IOException {
Set<BareJid> recipients = new HashSet<>();
recipients.add(recipient);
return encrypt(recipients, message);
}
/**
* OMEMO encrypt a cleartext message for multiple recipients.
*
* @param recipients recipients barejids
* @param message text to encrypt
* @return encrypted message.
*
* @throws CryptoFailedException When something crypto related fails
* @throws UndecidedOmemoIdentityException When there are undecided devices.
* @throws InterruptedException if the calling thread was interrupted.
* @throws SmackException.NotConnectedException if the XMPP connection is not connected.
* @throws SmackException.NoResponseException if there was no response from the remote entity.
* @throws SmackException.NotLoggedInException if the XMPP connection is not authenticated.
* @throws IOException if an I/O error occurred.
*/
public synchronized OmemoMessage.Sent encrypt(Set<BareJid> recipients, String message)
throws CryptoFailedException, UndecidedOmemoIdentityException,
InterruptedException, SmackException.NotConnectedException,
SmackException.NoResponseException, SmackException.NotLoggedInException, IOException {
LoggedInOmemoManager guard = new LoggedInOmemoManager(this);
Set<OmemoDevice> devices = getDevicesOf(getOwnJid());
for (BareJid recipient : recipients) {
devices.addAll(getDevicesOf(recipient));
}
return service.createOmemoMessage(guard, devices, message);
}
/**
* Encrypt a message for all recipients in the MultiUserChat.
*
* @param muc multiUserChat
* @param message message to send
* @return encrypted message
*
* @throws UndecidedOmemoIdentityException when there are undecided devices.
* @throws CryptoFailedException if the OMEMO cryptography failed.
* @throws XMPPException.XMPPErrorException if there was an XMPP error returned.
* @throws SmackException.NotConnectedException if the XMPP connection is not connected.
* @throws InterruptedException if the calling thread was interrupted.
* @throws SmackException.NoResponseException if there was no response from the remote entity.
* @throws NoOmemoSupportException When the muc doesn't support OMEMO.
* @throws SmackException.NotLoggedInException if the XMPP connection is not authenticated.
* @throws IOException if an I/O error occurred.
*/
public synchronized OmemoMessage.Sent encrypt(MultiUserChat muc, String message)
throws UndecidedOmemoIdentityException, CryptoFailedException,
XMPPException.XMPPErrorException, SmackException.NotConnectedException, InterruptedException,
SmackException.NoResponseException, NoOmemoSupportException,
SmackException.NotLoggedInException, IOException {
if (!multiUserChatSupportsOmemo(muc)) {
throw new NoOmemoSupportException();
}
Set<BareJid> recipients = new HashSet<>();
for (EntityFullJid e : muc.getOccupants()) {
recipients.add(muc.getOccupant(e).getJid().asBareJid());
}
return encrypt(recipients, message);
}
/**
* Manually decrypt an OmemoElement.
* This method should only be used for use-cases, where the internal listeners don't pick up on an incoming message.
* (for example MAM query results).
*
* @param sender bareJid of the message sender (must be the jid of the contact who sent the message)
* @param omemoElement omemoElement
* @return decrypted OmemoMessage
*
* @throws SmackException.NotLoggedInException if the Manager is not authenticated
* @throws CorruptedOmemoKeyException if our or their key is corrupted
* @throws NoRawSessionException if the message was not a preKeyMessage, but we had no session with the contact
* @throws CryptoFailedException if decryption fails
* @throws IOException if an I/O error occurred.
*/
public OmemoMessage.Received decrypt(BareJid sender, OmemoElement omemoElement)
throws SmackException.NotLoggedInException, CorruptedOmemoKeyException, NoRawSessionException,
CryptoFailedException, IOException {
LoggedInOmemoManager managerGuard = new LoggedInOmemoManager(this);
return getOmemoService().decryptMessage(managerGuard, sender, omemoElement);
}
/**
* Decrypt messages from a MAM query.
*
* @param mamQuery The MAM query
* @return list of decrypted OmemoMessages
*
* @throws SmackException.NotLoggedInException if the Manager is not authenticated.
* @throws IOException if an I/O error occurred.
*/
public List<MessageOrOmemoMessage> decryptMamQueryResult(MamManager.MamQuery mamQuery)
throws SmackException.NotLoggedInException, IOException {
return new ArrayList<>(getOmemoService().decryptMamQueryResult(new LoggedInOmemoManager(this), mamQuery));
}
/**
* Trust that a fingerprint belongs to an OmemoDevice.
* The fingerprint must be the lowercase, hexadecimal fingerprint of the identityKey of the device and must
* be of length 64.
*
* @param device device
* @param fingerprint fingerprint
*/
public void trustOmemoIdentity(OmemoDevice device, OmemoFingerprint fingerprint) {
if (trustCallback == null) {
throw new IllegalStateException("No TrustCallback set.");
}
trustCallback.setTrust(device, fingerprint, TrustState.trusted);
}
/**
* Distrust the fingerprint/OmemoDevice tuple.
* The fingerprint must be the lowercase, hexadecimal fingerprint of the identityKey of the device and must
* be of length 64.
*
* @param device device
* @param fingerprint fingerprint
*/
public void distrustOmemoIdentity(OmemoDevice device, OmemoFingerprint fingerprint) {
if (trustCallback == null) {
throw new IllegalStateException("No TrustCallback set.");
}
trustCallback.setTrust(device, fingerprint, TrustState.untrusted);
}
/**
* Returns true, if the fingerprint/OmemoDevice tuple is trusted, otherwise false.
* The fingerprint must be the lowercase, hexadecimal fingerprint of the identityKey of the device and must
* be of length 64.
*
* @param device device
* @param fingerprint fingerprint
* @return <code>true</code> if this is a trusted OMEMO identity.
*/
public boolean isTrustedOmemoIdentity(OmemoDevice device, OmemoFingerprint fingerprint) {
if (trustCallback == null) {
throw new IllegalStateException("No TrustCallback set.");
}
return trustCallback.getTrust(device, fingerprint) == TrustState.trusted;
}
/**
* Returns true, if the fingerprint/OmemoDevice tuple is decided by the user.
* The fingerprint must be the lowercase, hexadecimal fingerprint of the identityKey of the device and must
* be of length 64.
*
* @param device device
* @param fingerprint fingerprint
* @return <code>true</code> if the trust is decided for the identity.
*/
public boolean isDecidedOmemoIdentity(OmemoDevice device, OmemoFingerprint fingerprint) {
if (trustCallback == null) {
throw new IllegalStateException("No TrustCallback set.");
}
return trustCallback.getTrust(device, fingerprint) != TrustState.undecided;
}
/**
* Send a ratchet update message. This can be used to advance the ratchet of a session in order to maintain forward
* secrecy.
*
* @param recipient recipient
*
* @throws CorruptedOmemoKeyException When the used identityKeys are corrupted
* @throws CryptoFailedException When something fails with the crypto
* @throws CannotEstablishOmemoSessionException When we can't establish a session with the recipient
* @throws SmackException.NotLoggedInException if the XMPP connection is not authenticated.
* @throws InterruptedException if the calling thread was interrupted.
* @throws SmackException.NoResponseException if there was no response from the remote entity.
* @throws NoSuchAlgorithmException if no such algorithm is available.
* @throws SmackException.NotConnectedException if the XMPP connection is not connected.
* @throws IOException if an I/O error occurred.
*/
public synchronized void sendRatchetUpdateMessage(OmemoDevice recipient)
throws SmackException.NotLoggedInException, CorruptedOmemoKeyException, InterruptedException,
SmackException.NoResponseException, NoSuchAlgorithmException, SmackException.NotConnectedException,
CryptoFailedException, CannotEstablishOmemoSessionException, IOException {
XMPPConnection connection = connection();
MessageBuilder message = connection.getStanzaFactory()
.buildMessageStanza()
.to(recipient.getJid());
OmemoElement element = getOmemoService().createRatchetUpdateElement(new LoggedInOmemoManager(this), recipient);
message.addExtension(element);
// Set MAM Storage hint
StoreHint.set(message);
connection.sendStanza(message.build());
}
/**
* Returns true, if the contact has any active devices published in a deviceList.
*
* @param contact contact
* @return true if contact has at least one OMEMO capable device.
*
* @throws SmackException.NotConnectedException if the XMPP connection is not connected.
* @throws InterruptedException if the calling thread was interrupted.
* @throws SmackException.NoResponseException if there was no response from the remote entity.
* @throws PubSubException.NotALeafNodeException if a PubSub leaf node operation was attempted on a non-leaf node.
* @throws XMPPException.XMPPErrorException if there was an XMPP error returned.
* @throws IOException if an I/O error occurred.
*/
public synchronized boolean contactSupportsOmemo(BareJid contact)
throws InterruptedException, PubSubException.NotALeafNodeException, XMPPException.XMPPErrorException,
SmackException.NotConnectedException, SmackException.NoResponseException, IOException {
OmemoCachedDeviceList deviceList = getOmemoService().refreshDeviceList(connection(), getOwnDevice(), contact);
return !deviceList.getActiveDevices().isEmpty();
}
/**
* Returns true, if the MUC with the EntityBareJid multiUserChat is non-anonymous and members only (prerequisite
* for OMEMO encryption in MUC).
*
* @param multiUserChat MUC
* @return true if chat supports OMEMO
*
* @throws XMPPException.XMPPErrorException if there was an XMPP protocol level error
* @throws SmackException.NotConnectedException if the connection is not connected
* @throws InterruptedException if the thread is interrupted
* @throws SmackException.NoResponseException if the server does not respond
*/
public boolean multiUserChatSupportsOmemo(MultiUserChat multiUserChat)
throws XMPPException.XMPPErrorException, SmackException.NotConnectedException, InterruptedException,
SmackException.NoResponseException {
EntityBareJid jid = multiUserChat.getRoom();
RoomInfo roomInfo = MultiUserChatManager.getInstanceFor(connection()).getRoomInfo(jid);
return roomInfo.isNonanonymous() && roomInfo.isMembersOnly();
}
/**
* Returns true, if the Server supports PEP.
*
* @param connection XMPPConnection
* @param server domainBareJid of the server to test
* @return true if server supports pep
*
* @throws XMPPException.XMPPErrorException if there was an XMPP error returned.
* @throws SmackException.NotConnectedException if the XMPP connection is not connected.
* @throws InterruptedException if the calling thread was interrupted.
* @throws SmackException.NoResponseException if there was no response from the remote entity.
*/
public static boolean serverSupportsOmemo(XMPPConnection connection, DomainBareJid server)
throws XMPPException.XMPPErrorException, SmackException.NotConnectedException, InterruptedException,
SmackException.NoResponseException {
return ServiceDiscoveryManager.getInstanceFor(connection)
.discoverInfo(server).containsFeature(PubSub.NAMESPACE);
}
/**
* Return the fingerprint of our identity key.
*
* @return our own OMEMO fingerprint
*
* @throws SmackException.NotLoggedInException if we don't know our bareJid yet.
* @throws CorruptedOmemoKeyException if our identityKey is corrupted.
* @throws IOException if an I/O error occurred.
*/
public synchronized OmemoFingerprint getOwnFingerprint()
throws SmackException.NotLoggedInException, CorruptedOmemoKeyException, IOException {
if (getOwnJid() == null) {
throw new SmackException.NotLoggedInException();
}
return getOmemoService().getOmemoStoreBackend().getFingerprint(getOwnDevice());
}
/**
* Get the fingerprint of a contacts device.
*
* @param device contacts OmemoDevice
* @return fingerprint of the given OMEMO device.
*
* @throws CannotEstablishOmemoSessionException if we have no session yet, and are unable to create one.
* @throws SmackException.NotLoggedInException if the XMPP connection is not authenticated.
* @throws CorruptedOmemoKeyException if the copy of the fingerprint we have is corrupted.
* @throws SmackException.NotConnectedException if the XMPP connection is not connected.
* @throws InterruptedException if the calling thread was interrupted.
* @throws SmackException.NoResponseException if there was no response from the remote entity.
* @throws IOException if an I/O error occurred.
*/
public synchronized OmemoFingerprint getFingerprint(OmemoDevice device)
throws CannotEstablishOmemoSessionException, SmackException.NotLoggedInException,
CorruptedOmemoKeyException, SmackException.NotConnectedException, InterruptedException,
SmackException.NoResponseException, IOException {
if (getOwnJid() == null) {
throw new SmackException.NotLoggedInException();
}
if (device.equals(getOwnDevice())) {
return getOwnFingerprint();
}
return getOmemoService().getOmemoStoreBackend()
.getFingerprintAndMaybeBuildSession(new LoggedInOmemoManager(this), device);
}
/**
* Return all OmemoFingerprints of active devices of a contact.
* TODO: Make more fail-safe
*
* @param contact contact
* @return Map of all active devices of the contact and their fingerprints.
*
* @throws SmackException.NotLoggedInException if the XMPP connection is not authenticated.
* @throws CorruptedOmemoKeyException if the OMEMO key is corrupted.
* @throws CannotEstablishOmemoSessionException if no OMEMO session could be established.
* @throws SmackException.NotConnectedException if the XMPP connection is not connected.
* @throws InterruptedException if the calling thread was interrupted.
* @throws SmackException.NoResponseException if there was no response from the remote entity.
* @throws IOException if an I/O error occurred.
*/
public synchronized HashMap<OmemoDevice, OmemoFingerprint> getActiveFingerprints(BareJid contact)
throws SmackException.NotLoggedInException, CorruptedOmemoKeyException,
CannotEstablishOmemoSessionException, SmackException.NotConnectedException, InterruptedException,
SmackException.NoResponseException, IOException {
if (getOwnJid() == null) {
throw new SmackException.NotLoggedInException();
}
HashMap<OmemoDevice, OmemoFingerprint> fingerprints = new HashMap<>();
OmemoCachedDeviceList deviceList = getOmemoService().getOmemoStoreBackend().loadCachedDeviceList(getOwnDevice(),
contact);
for (int id : deviceList.getActiveDevices()) {
OmemoDevice device = new OmemoDevice(contact, id);
OmemoFingerprint fingerprint = getFingerprint(device);
if (fingerprint != null) {
fingerprints.put(device, fingerprint);
}
}
return fingerprints;
}
/**
* Add an OmemoMessageListener. This listener will be informed about incoming OMEMO messages
* (as well as KeyTransportMessages) and OMEMO encrypted message carbons.
*
* @param listener OmemoMessageListener
*/
public void addOmemoMessageListener(OmemoMessageListener listener) {
omemoMessageListeners.add(listener);
}
/**
* Remove an OmemoMessageListener.
*
* @param listener OmemoMessageListener
*/
public void removeOmemoMessageListener(OmemoMessageListener listener) {
omemoMessageListeners.remove(listener);
}
/**
* Add an OmemoMucMessageListener. This listener will be informed about incoming OMEMO encrypted MUC messages.
*
* @param listener OmemoMessageListener.
*/
public void addOmemoMucMessageListener(OmemoMucMessageListener listener) {
omemoMucMessageListeners.add(listener);
}
/**
* Remove an OmemoMucMessageListener.
*
* @param listener OmemoMucMessageListener
*/
public void removeOmemoMucMessageListener(OmemoMucMessageListener listener) {
omemoMucMessageListeners.remove(listener);
}
/**
* Request a deviceList update from contact contact.
*
* @param contact contact we want to obtain the deviceList from.
*
* @throws InterruptedException if the calling thread was interrupted.
* @throws PubSubException.NotALeafNodeException if a PubSub leaf node operation was attempted on a non-leaf node.
* @throws XMPPException.XMPPErrorException if there was an XMPP error returned.
* @throws SmackException.NotConnectedException if the XMPP connection is not connected.
* @throws SmackException.NoResponseException if there was no response from the remote entity.
* @throws IOException if an I/O error occurred.
*/
public synchronized void requestDeviceListUpdateFor(BareJid contact)
throws InterruptedException, PubSubException.NotALeafNodeException, XMPPException.XMPPErrorException,
SmackException.NotConnectedException, SmackException.NoResponseException, IOException {
getOmemoService().refreshDeviceList(connection(), getOwnDevice(), contact);
}
/**
* Publish a new device list with just our own deviceId in it.
*
* @throws SmackException.NotLoggedInException if the XMPP connection is not authenticated.
* @throws InterruptedException if the calling thread was interrupted.
* @throws XMPPException.XMPPErrorException if there was an XMPP error returned.
* @throws SmackException.NotConnectedException if the XMPP connection is not connected.
* @throws SmackException.NoResponseException if there was no response from the remote entity.
* @throws IOException if an I/O error occurred.
* @throws PubSubException.NotALeafNodeException if a PubSub leaf node operation was attempted on a non-leaf node.
*/
public void purgeDeviceList()
throws SmackException.NotLoggedInException, InterruptedException, XMPPException.XMPPErrorException,
SmackException.NotConnectedException, SmackException.NoResponseException, IOException, PubSubException.NotALeafNodeException {
getOmemoService().purgeDeviceList(new LoggedInOmemoManager(this));
}
public List<Exception> purgeEverything() throws NotConnectedException, InterruptedException, IOException {
List<Exception> exceptions = new ArrayList<>(5);
PubSubManager pm = PubSubManager.getInstanceFor(getConnection(), getOwnJid());
try {
requestDeviceListUpdateFor(getOwnJid());
} catch (SmackException.NoResponseException | PubSubException.NotALeafNodeException
| XMPPException.XMPPErrorException e) {
exceptions.add(e);
}
OmemoCachedDeviceList deviceList = OmemoService.getInstance().getOmemoStoreBackend()
.loadCachedDeviceList(getOwnDevice(), getOwnJid());
for (int id : deviceList.getAllDevices()) {
try {
pm.getLeafNode(OmemoConstants.PEP_NODE_BUNDLE_FROM_DEVICE_ID(id)).deleteAllItems();
} catch (SmackException.NoResponseException | PubSubException.NotALeafNodeException
| XMPPException.XMPPErrorException | PubSubException.NotAPubSubNodeException e) {
exceptions.add(e);
}
try {
pm.deleteNode(OmemoConstants.PEP_NODE_BUNDLE_FROM_DEVICE_ID(id));
} catch (SmackException.NoResponseException | XMPPException.XMPPErrorException e) {
exceptions.add(e);
}
}
try {
pm.getLeafNode(OmemoConstants.PEP_NODE_DEVICE_LIST).deleteAllItems();
} catch (SmackException.NoResponseException | PubSubException.NotALeafNodeException
| XMPPException.XMPPErrorException | PubSubException.NotAPubSubNodeException e) {
exceptions.add(e);
}
try {
pm.deleteNode(OmemoConstants.PEP_NODE_DEVICE_LIST);
} catch (SmackException.NoResponseException | XMPPException.XMPPErrorException e) {
exceptions.add(e);
}
return exceptions;
}
/**
* Rotate the signedPreKey published in our OmemoBundle and republish it. This should be done every now and
* then (7-14 days). The old signedPreKey should be kept for some more time (a month or so) to enable decryption
* of messages that have been sent since the key was changed.
*
* @throws CorruptedOmemoKeyException When the IdentityKeyPair is damaged.
* @throws InterruptedException XMPP error
* @throws XMPPException.XMPPErrorException XMPP error
* @throws SmackException.NotConnectedException XMPP error
* @throws SmackException.NoResponseException XMPP error
* @throws SmackException.NotLoggedInException if the XMPP connection is not authenticated.
* @throws IOException if an I/O error occurred.
* @throws PubSubException.NotALeafNodeException if a PubSub leaf node operation was attempted on a non-leaf node.
*/
public synchronized void rotateSignedPreKey()
throws CorruptedOmemoKeyException, SmackException.NotLoggedInException, XMPPException.XMPPErrorException,
SmackException.NotConnectedException, InterruptedException, SmackException.NoResponseException,
IOException, PubSubException.NotALeafNodeException {
if (!connection().isAuthenticated()) {
throw new SmackException.NotLoggedInException();
}
// generate key
getOmemoService().getOmemoStoreBackend().changeSignedPreKey(getOwnDevice());
// publish
OmemoBundleElement bundle = getOmemoService().getOmemoStoreBackend().packOmemoBundle(getOwnDevice());
OmemoService.publishBundle(connection(), getOwnDevice(), bundle);
}
/**
* Return true, if the given Stanza contains an OMEMO element 'encrypted'.
*
* @param stanza stanza
* @return true if stanza has extension 'encrypted'
*/
static boolean stanzaContainsOmemoElement(Stanza stanza) {
return stanza.hasExtension(OmemoElement.NAME_ENCRYPTED, OMEMO_NAMESPACE_V_AXOLOTL);
}
/**
* Throw an IllegalStateException if no OmemoService is set.
*/
private void throwIfNoServiceSet() {
if (service == null) {
throw new IllegalStateException("No OmemoService set in OmemoManager.");
}
}
/**
* Returns a pseudo random number from the interval [1, Integer.MAX_VALUE].
*
* @return a random deviceId.
*/
public static int randomDeviceId() {
return new Random().nextInt(Integer.MAX_VALUE - 1) + 1;
}
/**
* Return the BareJid of the user.
*
* @return our own bare JID.
*/
public BareJid getOwnJid() {
if (ownJid == null && connection().isAuthenticated()) {
ownJid = connection().getUser().asBareJid();
}
return ownJid;
}
/**
* Return the deviceId of this OmemoManager.
*
* @return this OmemoManagers deviceId.
*/
public synchronized Integer getDeviceId() {
return deviceId;
}
/**
* Return the OmemoDevice of the user.
*
* @return our own OmemoDevice
*/
public synchronized OmemoDevice getOwnDevice() {
BareJid jid = getOwnJid();
if (jid == null) {
return null;
}
return new OmemoDevice(jid, getDeviceId());
}
/**
* Set the deviceId of the manager to nDeviceId.
*
* @param nDeviceId new deviceId
*/
synchronized void setDeviceId(int nDeviceId) {
// Move this instance inside the HashMaps
INSTANCES.get(connection()).remove(getDeviceId());
INSTANCES.get(connection()).put(nDeviceId, this);
this.deviceId = nDeviceId;
}
/**
* Notify all registered OmemoMessageListeners about a received OmemoMessage.
*
* @param stanza original stanza
* @param decryptedMessage decrypted OmemoMessage.
*/
void notifyOmemoMessageReceived(Stanza stanza, OmemoMessage.Received decryptedMessage) {
for (OmemoMessageListener l : omemoMessageListeners) {
l.onOmemoMessageReceived(stanza, decryptedMessage);
}
}
/**
* Notify all registered OmemoMucMessageListeners of an incoming OmemoMessageElement in a MUC.
*
* @param muc MultiUserChat the message was received in.
* @param stanza Original Stanza.
* @param decryptedMessage Decrypted OmemoMessage.
*/
void notifyOmemoMucMessageReceived(MultiUserChat muc,
Stanza stanza,
OmemoMessage.Received decryptedMessage) {
for (OmemoMucMessageListener l : omemoMucMessageListeners) {
l.onOmemoMucMessageReceived(muc, stanza, decryptedMessage);
}
}
/**
* Notify all registered OmemoMessageListeners of an incoming OMEMO encrypted Carbon Copy.
* Remember: If you want to receive OMEMO encrypted carbon copies, you have to enable carbons using
* {@link CarbonManager#enableCarbons()}.
*
* @param direction direction of the carbon copy
* @param carbonCopy carbon copy itself
* @param wrappingMessage wrapping message
* @param decryptedCarbonCopy decrypted carbon copy OMEMO element
*/
void notifyOmemoCarbonCopyReceived(CarbonExtension.Direction direction,
Message carbonCopy,
Message wrappingMessage,
OmemoMessage.Received decryptedCarbonCopy) {
for (OmemoMessageListener l : omemoMessageListeners) {
l.onOmemoCarbonCopyReceived(direction, carbonCopy, wrappingMessage, decryptedCarbonCopy);
}
}
/**
* Register stanza listeners needed for OMEMO.
* This method is called automatically in the constructor and should only be used to restore the previous state
* after {@link #stopStanzaAndPEPListeners()} was called.
*/
public void resumeStanzaAndPEPListeners() {
CarbonManager carbonManager = CarbonManager.getInstanceFor(connection());
// Remove listeners to avoid them getting added twice
connection().removeAsyncStanzaListener(this::internalOmemoMessageStanzaListener);
carbonManager.removeCarbonCopyReceivedListener(this::internalOmemoCarbonCopyListener);
// Add listeners
pepManager.addPepEventListener(OmemoConstants.PEP_NODE_DEVICE_LIST, OmemoDeviceListElement.class, pepOmemoDeviceListEventListener);
connection().addAsyncStanzaListener(this::internalOmemoMessageStanzaListener, OmemoManager::isOmemoMessage);
carbonManager.addCarbonCopyReceivedListener(this::internalOmemoCarbonCopyListener);
}
/**
* Remove active stanza listeners needed for OMEMO.
*/
public void stopStanzaAndPEPListeners() {
pepManager.removePepEventListener(pepOmemoDeviceListEventListener);
connection().removeAsyncStanzaListener(this::internalOmemoMessageStanzaListener);
CarbonManager.getInstanceFor(connection()).removeCarbonCopyReceivedListener(this::internalOmemoCarbonCopyListener);
}
/**
* Build a fresh session with a contacts device.
* This might come in handy if a session is broken.
*
* @param contactsDevice OmemoDevice of a contact.
*
* @throws InterruptedException if the calling thread was interrupted.
* @throws SmackException.NoResponseException if there was no response from the remote entity.
* @throws CorruptedOmemoKeyException if our or their identityKey is corrupted.
* @throws SmackException.NotConnectedException if the XMPP connection is not connected.
* @throws CannotEstablishOmemoSessionException if no new session can be established.
* @throws SmackException.NotLoggedInException if the connection is not authenticated.
*/
public void rebuildSessionWith(OmemoDevice contactsDevice)
throws InterruptedException, SmackException.NoResponseException, CorruptedOmemoKeyException,
SmackException.NotConnectedException, CannotEstablishOmemoSessionException,
SmackException.NotLoggedInException {
if (!connection().isAuthenticated()) {
throw new SmackException.NotLoggedInException();
}
getOmemoService().buildFreshSessionWithDevice(connection(), getOwnDevice(), contactsDevice);
}
/**
* Get our connection.
*
* @return the connection of this manager
*/
XMPPConnection getConnection() {
return connection();
}
/**
* Return the OMEMO service object.
*
* @return the OmemoService object related to this OmemoManager.
*/
OmemoService<?, ?, ?, ?, ?, ?, ?, ?, ?> getOmemoService() {
throwIfNoServiceSet();
return service;
}
/**
* StanzaListener that listens for incoming Stanzas which contain OMEMO elements.
*/
private void internalOmemoMessageStanzaListener(final Stanza packet) {
Async.go(new Runnable() {
@Override
public void run() {
try {
getOmemoService().onOmemoMessageStanzaReceived(packet,
new LoggedInOmemoManager(OmemoManager.this));
} catch (SmackException.NotLoggedInException | IOException e) {
LOGGER.log(Level.SEVERE, "Exception while processing OMEMO stanza", e);
}
}
});
}
/**
* CarbonCopyListener that listens for incoming carbon copies which contain OMEMO elements.
*/
private void internalOmemoCarbonCopyListener(final CarbonExtension.Direction direction,
final Message carbonCopy,
final Message wrappingMessage) {
Async.go(new Runnable() {
@Override
public void run() {
if (isOmemoMessage(carbonCopy)) {
try {
getOmemoService().onOmemoCarbonCopyReceived(direction, carbonCopy, wrappingMessage,
new LoggedInOmemoManager(OmemoManager.this));
} catch (SmackException.NotLoggedInException | IOException e) {
LOGGER.log(Level.SEVERE, "Exception while processing OMEMO stanza", e);
}
}
}
});
}
@SuppressWarnings("UnnecessaryLambda")
private final PepEventListener<OmemoDeviceListElement> pepOmemoDeviceListEventListener =
(from, receivedDeviceList, id, message) -> {
// Device List <list>
OmemoCachedDeviceList deviceList;
try {
getOmemoService().getOmemoStoreBackend().mergeCachedDeviceList(getOwnDevice(), from,
receivedDeviceList);
if (!from.asBareJid().equals(getOwnJid())) {
return;
}
deviceList = getOmemoService().cleanUpDeviceList(getOwnDevice());
} catch (IOException e) {
LOGGER.log(Level.SEVERE,
"IOException while processing OMEMO PEP device updates. Message: " + message,
e);
return;
}
final OmemoDeviceListElement_VAxolotl newDeviceList = new OmemoDeviceListElement_VAxolotl(deviceList);
if (!newDeviceList.copyDeviceIds().equals(receivedDeviceList.copyDeviceIds())) {
LOGGER.log(Level.FINE, "Republish deviceList due to changes:" +
" Received: " + Arrays.toString(receivedDeviceList.copyDeviceIds().toArray()) +
" Published: " + Arrays.toString(newDeviceList.copyDeviceIds().toArray()));
Async.go(new Runnable() {
@Override
public void run() {
try {
OmemoService.publishDeviceList(connection(), newDeviceList);
} catch (InterruptedException | XMPPException.XMPPErrorException |
SmackException.NotConnectedException | SmackException.NoResponseException | PubSubException.NotALeafNodeException e) {
LOGGER.log(Level.WARNING, "Could not publish our deviceList upon an received update.", e);
}
}
});
}
};
/**
* StanzaFilter that filters messages containing a OMEMO element.
*/
private static boolean isOmemoMessage(Stanza stanza) {
return stanza instanceof Message && OmemoManager.stanzaContainsOmemoElement(stanza);
}
/**
* Guard class which ensures that the wrapped OmemoManager knows its BareJid.
*/
public static class LoggedInOmemoManager {
private final OmemoManager manager;
public LoggedInOmemoManager(OmemoManager manager)
throws SmackException.NotLoggedInException {
if (manager == null) {
throw new IllegalArgumentException("OmemoManager cannot be null.");
}
if (manager.getOwnJid() == null) {
if (manager.getConnection().isAuthenticated()) {
manager.ownJid = manager.getConnection().getUser().asBareJid();
} else {
throw new SmackException.NotLoggedInException();
}
}
this.manager = manager;
}
public OmemoManager get() {
return manager;
}
}
/**
* Callback which can be used to get notified, when the OmemoManager finished initializing.
*/
public interface InitializationFinishedCallback {
void initializationFinished(OmemoManager manager);
void initializationFailed(Exception cause);
}
/**
* Get the bareJid of the user from the authenticated XMPP connection.
* If our deviceId is unknown, use the bareJid to look up deviceIds available in the omemoStore.
* If there are ids available, choose the smallest one. Otherwise generate a random deviceId.
*
* @param manager OmemoManager
*/
private static void initBareJidAndDeviceId(OmemoManager manager) {
if (!manager.getConnection().isAuthenticated()) {
throw new IllegalStateException("Connection MUST be authenticated.");
}
if (manager.ownJid == null) {
manager.ownJid = manager.getConnection().getUser().asBareJid();
}
if (UNKNOWN_DEVICE_ID.equals(manager.deviceId)) {
SortedSet<Integer> storedDeviceIds = manager.getOmemoService().getOmemoStoreBackend().localDeviceIdsOf(manager.ownJid);
if (storedDeviceIds.size() > 0) {
manager.setDeviceId(storedDeviceIds.first());
} else {
manager.setDeviceId(randomDeviceId());
}
}
}
}
| apache-2.0 |
AndroidX/androidx | vectordrawable/integration-tests/testapp/src/main/java/com/example/android/support/vectordrawable/app/SeekableDemo.java | 4134 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.support.vectordrawable.app;
import android.os.Bundle;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SeekBar;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.vectordrawable.graphics.drawable.SeekableAnimatedVectorDrawable;
import com.example.android.support.vectordrawable.R;
/**
* Demonstrates usage of {@link SeekableAnimatedVectorDrawable}.
*/
public class SeekableDemo extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.seekable_demo);
final ImageView image = findViewById(R.id.image);
final Button start = findViewById(R.id.start);
final Button stop = findViewById(R.id.stop);
final SeekBar seekBar = findViewById(R.id.seek);
final SeekableAnimatedVectorDrawable avd =
SeekableAnimatedVectorDrawable.create(this, R.drawable.ic_hourglass_animation);
if (avd == null) {
finish();
return;
}
avd.registerAnimationCallback(new SeekableAnimatedVectorDrawable.AnimationCallback() {
@Override
public void onAnimationStart(@NonNull SeekableAnimatedVectorDrawable drawable) {
onAnimationRunning();
}
@Override
public void onAnimationEnd(@NonNull SeekableAnimatedVectorDrawable drawable) {
start.setEnabled(true);
start.setText(R.string.start);
stop.setEnabled(false);
seekBar.setProgress(0);
}
@Override
public void onAnimationPause(@NonNull SeekableAnimatedVectorDrawable drawable) {
start.setEnabled(true);
start.setText(R.string.resume);
stop.setEnabled(true);
}
@Override
public void onAnimationResume(@NonNull SeekableAnimatedVectorDrawable drawable) {
onAnimationRunning();
}
private void onAnimationRunning() {
start.setEnabled(true);
start.setText(R.string.pause);
stop.setEnabled(true);
}
@Override
public void onAnimationUpdate(@NonNull SeekableAnimatedVectorDrawable drawable) {
seekBar.setProgress((int) drawable.getCurrentPlayTime());
}
});
image.setImageDrawable(avd);
seekBar.setMax((int) avd.getTotalDuration());
start.setOnClickListener((v) -> {
if (!avd.isRunning()) {
avd.start();
} else if (!avd.isPaused()) {
avd.pause();
} else {
avd.resume();
}
});
stop.setOnClickListener((v) -> avd.stop());
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (fromUser) {
avd.setCurrentPlayTime(progress);
}
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
}
| apache-2.0 |
freeVM/freeVM | enhanced/java/classlib/modules/sql/src/test/java/org/apache/harmony/sql/tests/javax/sql/rowset/serial/SerialExceptionTest.java | 1516 | /*
* 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.harmony.sql.tests.javax.sql.rowset.serial;
import javax.sql.rowset.serial.SerialException;
import junit.framework.TestCase;
import org.apache.harmony.testframework.serialization.SerializationTest;
public class SerialExceptionTest extends TestCase {
/**
* @tests serialization/deserialization compatibility.
*/
public void testSerializationSelf() throws Exception {
SerializationTest.verifySelf(new SerialException());
}
/**
* @tests serialization/deserialization compatibility with RI.
*/
public void testSerializationCompatibility() throws Exception {
SerializationTest.verifyGolden(this, new SerialException());
}
}
| apache-2.0 |
arvindsv/gocd | common/src/main/java/com/thoughtworks/go/domain/materials/scm/PluggableSCMMaterialAgent.java | 4585 | /*
* Copyright 2020 ThoughtWorks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.thoughtworks.go.domain.materials.scm;
import com.thoughtworks.go.config.materials.PluggableSCMMaterial;
import com.thoughtworks.go.domain.MaterialRevision;
import com.thoughtworks.go.domain.config.Configuration;
import com.thoughtworks.go.domain.config.ConfigurationProperty;
import com.thoughtworks.go.domain.materials.MaterialAgent;
import com.thoughtworks.go.domain.materials.Modification;
import com.thoughtworks.go.domain.scm.SCM;
import com.thoughtworks.go.plugin.access.scm.SCMExtension;
import com.thoughtworks.go.plugin.access.scm.SCMProperty;
import com.thoughtworks.go.plugin.access.scm.SCMPropertyConfiguration;
import com.thoughtworks.go.plugin.access.scm.revision.SCMRevision;
import com.thoughtworks.go.plugin.api.response.Result;
import com.thoughtworks.go.util.command.ConsoleOutputStreamConsumer;
import org.apache.commons.lang3.StringUtils;
import java.io.File;
import static com.thoughtworks.go.util.command.TaggedStreamConsumer.PREP_ERR;
public class PluggableSCMMaterialAgent implements MaterialAgent {
private SCMExtension scmExtension;
private MaterialRevision revision;
private File workingDirectory;
private final ConsoleOutputStreamConsumer consumer;
public PluggableSCMMaterialAgent(SCMExtension scmExtension,
MaterialRevision revision,
File workingDirectory,
ConsoleOutputStreamConsumer consumer) {
this.scmExtension = scmExtension;
this.revision = revision;
this.workingDirectory = workingDirectory;
this.consumer = consumer;
}
@Override
public void prepare() {
try {
PluggableSCMMaterial material = (PluggableSCMMaterial) revision.getMaterial();
Modification latestModification = revision.getLatestModification();
SCMRevision scmRevision = new SCMRevision(latestModification.getRevision(), latestModification.getModifiedTime(), null, null, latestModification.getAdditionalDataMap(), null);
File destinationFolder = material.workingDirectory(workingDirectory);
Result result = scmExtension.checkout(material.getScmConfig().getPluginConfiguration().getId(), buildSCMPropertyConfigurations(material.getScmConfig()), destinationFolder.getAbsolutePath(), scmRevision);
handleCheckoutResult(material, result);
} catch (Exception e) {
consumer.taggedErrOutput(PREP_ERR, String.format("Material %s checkout failed: %s", revision.getMaterial().getDisplayName(), e.getMessage()));
throw e;
}
}
private void handleCheckoutResult(PluggableSCMMaterial material, Result result) {
if (result.isSuccessful()) {
if (StringUtils.isNotBlank(result.getMessagesForDisplay())) {
consumer.stdOutput(result.getMessagesForDisplay());
}
} else {
consumer.taggedErrOutput(PREP_ERR, String.format("Material %s checkout failed: %s", material.getDisplayName(), result.getMessagesForDisplay()));
throw new RuntimeException(String.format("Material %s checkout failed: %s", material.getDisplayName(), result.getMessagesForDisplay()));
}
}
private SCMPropertyConfiguration buildSCMPropertyConfigurations(SCM scmConfig) {
SCMPropertyConfiguration scmPropertyConfiguration = new SCMPropertyConfiguration();
populateConfiguration(scmConfig.getConfiguration(), scmPropertyConfiguration);
return scmPropertyConfiguration;
}
private void populateConfiguration(Configuration configuration,
com.thoughtworks.go.plugin.api.config.Configuration pluginConfiguration) {
for (ConfigurationProperty configurationProperty : configuration) {
pluginConfiguration.add(new SCMProperty(configurationProperty.getConfigurationKey().getName(), configurationProperty.getValue()));
}
}
}
| apache-2.0 |
sunmeng007/oozie | core/src/main/java/org/apache/oozie/service/ActionCheckerService.java | 9013 | /**
* Copyright (c) 2010 Yahoo! 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. See accompanying LICENSE file.
*/
package org.apache.oozie.service;
import java.util.ArrayList;
import java.util.List;
import org.apache.hadoop.conf.Configuration;
import org.apache.oozie.CoordinatorActionBean;
import org.apache.oozie.ErrorCode;
import org.apache.oozie.WorkflowActionBean;
import org.apache.oozie.command.CommandException;
import org.apache.oozie.command.coord.CoordActionCheckCommand;
import org.apache.oozie.command.coord.CoordActionCheckXCommand;
import org.apache.oozie.command.wf.ActionCheckCommand;
import org.apache.oozie.command.wf.ActionCheckXCommand;
import org.apache.oozie.executor.jpa.CoordActionsRunningGetJPAExecutor;
import org.apache.oozie.executor.jpa.JPAExecutorException;
import org.apache.oozie.executor.jpa.WorkflowActionsRunningGetJPAExecutor;
import org.apache.oozie.util.XCallable;
import org.apache.oozie.util.XLog;
/**
* The Action Checker Service queue ActionCheckCommands to check the status of
* running actions and CoordActionCheckCommands to check the status of
* coordinator actions. The delay between checks on the same action can be
* configured.
*/
public class ActionCheckerService implements Service {
public static final String CONF_PREFIX = Service.CONF_PREFIX + "ActionCheckerService.";
/**
* The frequency at which the ActionCheckService will run.
*/
public static final String CONF_ACTION_CHECK_INTERVAL = CONF_PREFIX + "action.check.interval";
/**
* The time, in seconds, between an ActionCheck for the same action.
*/
public static final String CONF_ACTION_CHECK_DELAY = CONF_PREFIX + "action.check.delay";
/**
* The number of callables to be queued in a batch.
*/
public static final String CONF_CALLABLE_BATCH_SIZE = CONF_PREFIX + "callable.batch.size";
protected static final String INSTRUMENTATION_GROUP = "actionchecker";
protected static final String INSTR_CHECK_ACTIONS_COUNTER = "checks_wf_actions";
protected static final String INSTR_CHECK_COORD_ACTIONS_COUNTER = "checks_coord_actions";
private static boolean useXCommand = true;
/**
* {@link ActionCheckRunnable} is the runnable which is scheduled to run and
* queue Action checks.
*/
static class ActionCheckRunnable implements Runnable {
private int actionCheckDelay;
private List<XCallable<Void>> callables;
private StringBuilder msg = null;
public ActionCheckRunnable(int actionCheckDelay) {
this.actionCheckDelay = actionCheckDelay;
}
public void run() {
XLog.Info.get().clear();
XLog LOG = XLog.getLog(getClass());
msg = new StringBuilder();
try {
runWFActionCheck();
runCoordActionCheck();
}
catch (CommandException ce) {
LOG.error("Unable to run action checks, ", ce);
}
LOG.debug("QUEUING [{0}] for potential checking", msg.toString());
if (null != callables) {
boolean ret = Services.get().get(CallableQueueService.class).queueSerial(callables);
if (ret == false) {
LOG.warn("Unable to queue the callables commands for CheckerService. "
+ "Most possibly command queue is full. Queue size is :"
+ Services.get().get(CallableQueueService.class).queueSize());
}
callables = null;
}
}
/**
* check workflow actions
*
* @throws CommandException
*/
private void runWFActionCheck() throws CommandException {
JPAService jpaService = Services.get().get(JPAService.class);
if (jpaService == null) {
throw new CommandException(ErrorCode.E0610);
}
List<WorkflowActionBean> actions;
try {
actions = jpaService
.execute(new WorkflowActionsRunningGetJPAExecutor(actionCheckDelay));
}
catch (JPAExecutorException je) {
throw new CommandException(je);
}
if (actions == null || actions.size() == 0) {
return;
}
msg.append(" WF_ACTIONS : " + actions.size());
for (WorkflowActionBean action : actions) {
Services.get().get(InstrumentationService.class).get().incr(INSTRUMENTATION_GROUP,
INSTR_CHECK_ACTIONS_COUNTER, 1);
if (useXCommand) {
queueCallable(new ActionCheckXCommand(action.getId()));
}
else {
queueCallable(new ActionCheckCommand(action.getId()));
}
}
}
/**
* check coordinator actions
*
* @throws CommandException
*/
private void runCoordActionCheck() throws CommandException {
JPAService jpaService = Services.get().get(JPAService.class);
if (jpaService == null) {
throw new CommandException(ErrorCode.E0610);
}
List<CoordinatorActionBean> cactions;
try {
cactions = jpaService.execute(new CoordActionsRunningGetJPAExecutor(
actionCheckDelay));
}
catch (JPAExecutorException je) {
throw new CommandException(je);
}
if (cactions == null || cactions.size() == 0) {
return;
}
msg.append(" COORD_ACTIONS : " + cactions.size());
for (CoordinatorActionBean caction : cactions) {
Services.get().get(InstrumentationService.class).get().incr(INSTRUMENTATION_GROUP,
INSTR_CHECK_COORD_ACTIONS_COUNTER, 1);
if (useXCommand) {
queueCallable(new CoordActionCheckXCommand(caction.getId(), actionCheckDelay));
}
else {
queueCallable(new CoordActionCheckCommand(caction.getId(), actionCheckDelay));
}
}
}
/**
* Adds callables to a list. If the number of callables in the list
* reaches {@link ActionCheckerService#CONF_CALLABLE_BATCH_SIZE}, the
* entire batch is queued and the callables list is reset.
*
* @param callable the callable to queue.
*/
private void queueCallable(XCallable<Void> callable) {
if (callables == null) {
callables = new ArrayList<XCallable<Void>>();
}
callables.add(callable);
if (callables.size() == Services.get().getConf().getInt(CONF_CALLABLE_BATCH_SIZE, 10)) {
boolean ret = Services.get().get(CallableQueueService.class).queueSerial(callables);
if (ret == false) {
XLog.getLog(getClass()).warn(
"Unable to queue the callables commands for CheckerService. "
+ "Most possibly command queue is full. Queue size is :"
+ Services.get().get(CallableQueueService.class).queueSize());
}
callables = new ArrayList<XCallable<Void>>();
}
}
}
/**
* Initializes the Action Check service.
*
* @param services services instance.
*/
@Override
public void init(Services services) {
Configuration conf = services.getConf();
Runnable actionCheckRunnable = new ActionCheckRunnable(conf.getInt(CONF_ACTION_CHECK_DELAY, 600));
services.get(SchedulerService.class).schedule(actionCheckRunnable, 10,
conf.getInt(CONF_ACTION_CHECK_INTERVAL, 60), SchedulerService.Unit.SEC);
if (Services.get().getConf().getBoolean(USE_XCOMMAND, true) == false) {
useXCommand = false;
}
}
/**
* Destroy the Action Checker Services.
*/
@Override
public void destroy() {
}
/**
* Return the public interface for the action checker service.
*
* @return {@link ActionCheckerService}.
*/
@Override
public Class<? extends Service> getInterface() {
return ActionCheckerService.class;
}
}
| apache-2.0 |
shyTNT/googleads-java-lib | modules/dfp_appengine/src/main/java/com/google/api/ads/dfp/jaxws/v201508/ContentPartnerError.java | 1711 |
package com.google.api.ads.dfp.jaxws.v201508;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
/**
*
* The content partner related validation errors.
*
*
* <p>Java class for ContentPartnerError complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="ContentPartnerError">
* <complexContent>
* <extension base="{https://www.google.com/apis/ads/publisher/v201508}ApiError">
* <sequence>
* <element name="reason" type="{https://www.google.com/apis/ads/publisher/v201508}ContentPartnerError.Reason" minOccurs="0"/>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ContentPartnerError", propOrder = {
"reason"
})
public class ContentPartnerError
extends ApiError
{
@XmlSchemaType(name = "string")
protected ContentPartnerErrorReason reason;
/**
* Gets the value of the reason property.
*
* @return
* possible object is
* {@link ContentPartnerErrorReason }
*
*/
public ContentPartnerErrorReason getReason() {
return reason;
}
/**
* Sets the value of the reason property.
*
* @param value
* allowed object is
* {@link ContentPartnerErrorReason }
*
*/
public void setReason(ContentPartnerErrorReason value) {
this.reason = value;
}
}
| apache-2.0 |
xiahome/ambry | ambry-store/src/main/java/com.github.ambry.store/ScanResults.java | 10385 | /**
* Copyright 2017 LinkedIn Corp. 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.
*/
package com.github.ambry.store;
import com.github.ambry.utils.Pair;
import java.util.HashMap;
import java.util.Map;
import java.util.NavigableMap;
import java.util.TreeMap;
/**
* Hold the data structures needed by {@link BlobStoreStats} to serve requests. The class also exposes helper methods
* used to modify and access the stored data structures.
*/
class ScanResults {
// A NavigableMap that stores buckets for container valid data size. The key of the map is the end time of each
// bucket and the value is the corresponding valid data size map. For example, there are two buckets with end time
// t1 and t2. Bucket with end time t2 includes all events whose operation time is greater than or equal to t1 but
// strictly less than t2.
// Each bucket except for the very first one contains the delta in valid data size that occurred prior to the bucket
// end time. The very first bucket's end time is the forecast start time for containers and it contains the valid data
// size map at the forecast start time. The very first bucket is used as a base value, requested valid data size is
// computed by applying the deltas from appropriate buckets on the base value.
private final NavigableMap<Long, Map<String, Map<String, Long>>> containerBuckets = new TreeMap<>();
// A NavigableMap that stores buckets for log segment valid data size. The rest of the structure is similar
// to containerBuckets.
private final NavigableMap<Long, NavigableMap<String, Long>> logSegmentBuckets = new TreeMap<>();
final long containerForecastStartTimeMs;
final long containerLastBucketTimeMs;
final long containerForecastEndTimeMs;
final long logSegmentForecastStartTimeMs;
final long logSegmentLastBucketTimeMs;
final long logSegmentForecastEndTimeMs;
Offset scannedEndOffset = null;
/**
* Create the bucket data structures in advance based on the given scanStartTime and segmentScanTimeOffset.
*/
ScanResults(long startTimeInMs, long logSegmentForecastOffsetMs, int bucketCount, long bucketSpanInMs) {
long containerBucketTimeMs = startTimeInMs;
long logSegmentBucketTimeMs = startTimeInMs - logSegmentForecastOffsetMs;
for (int i = 0; i < bucketCount; i++) {
containerBuckets.put(containerBucketTimeMs, new HashMap<>());
logSegmentBuckets.put(logSegmentBucketTimeMs, new TreeMap<>(LogSegmentNameHelper.COMPARATOR));
containerBucketTimeMs += bucketSpanInMs;
logSegmentBucketTimeMs += bucketSpanInMs;
}
containerForecastStartTimeMs = containerBuckets.firstKey();
containerLastBucketTimeMs = containerBuckets.lastKey();
containerForecastEndTimeMs = containerLastBucketTimeMs + bucketSpanInMs;
logSegmentForecastStartTimeMs = logSegmentBuckets.firstKey();
logSegmentLastBucketTimeMs = logSegmentBuckets.lastKey();
logSegmentForecastEndTimeMs = logSegmentLastBucketTimeMs + bucketSpanInMs;
}
/**
* Given a reference time, return the key of the appropriate container bucket whose end time is strictly greater than
* the reference time.
* @param referenceTimeInMs the reference time or operation time of an event.
* @return the appropriate bucket key (bucket end time) to indicate which bucket will an event with
* the given reference time as operation time belong to.
*/
Long getContainerBucketKey(long referenceTimeInMs) {
return containerBuckets.higherKey(referenceTimeInMs);
}
/**
* Given a reference time, return the key of the appropriate log segment bucket whose end time is strictly greater
* than the reference time.
* @param referenceTimeInMs the reference time or operation time of an event.
* @return the appropriate bucket key (bucket end time) to indicate which bucket will an event with
* the given reference time as operation time belong to.
*/
Long getLogSegmentBucketKey(long referenceTimeInMs) {
return logSegmentBuckets.higherKey(referenceTimeInMs);
}
/**
* Helper function to update the container base value bucket with the given value.
* @param serviceId the serviceId of the map entry to be updated
* @param containerId the containerId of the map entry to be updated
* @param value the value to be added
*/
void updateContainerBaseBucket(String serviceId, String containerId, long value) {
updateContainerBucket(containerBuckets.firstKey(), serviceId, containerId, value);
}
/**
* Helper function to update the log segment base value bucket with the given value.
* @param logSegmentName the log segment name of the map entry to be updated
* @param value the value to be added
*/
void updateLogSegmentBaseBucket(String logSegmentName, long value) {
updateLogSegmentBucket(logSegmentBuckets.firstKey(), logSegmentName, value);
}
/**
* Helper function to update a container bucket with the given value.
* @param bucketKey the bucket key to specify which bucket will be updated
* @param serviceId the serviceId of the map entry to be updated
* @param containerId the containerId of the map entry to be updated
* @param value the value to be added
*/
void updateContainerBucket(Long bucketKey, String serviceId, String containerId, long value) {
if (bucketKey != null && containerBuckets.containsKey(bucketKey)) {
Map<String, Map<String, Long>> existingBucketEntry = containerBuckets.get(bucketKey);
updateNestedMapHelper(existingBucketEntry, serviceId, containerId, value);
}
}
/**
* Helper function to update a log segment bucket with a given value.
* @param bucketKey the bucket key to specify which bucket will be updated
* @param logSegmentName the log segment name of the map entry to be updated
* @param value the value to be added
*/
void updateLogSegmentBucket(Long bucketKey, String logSegmentName, long value) {
if (bucketKey != null && logSegmentBuckets.containsKey(bucketKey)) {
Map<String, Long> existingBucketEntry = logSegmentBuckets.get(bucketKey);
updateMapHelper(existingBucketEntry, logSegmentName, value);
}
}
/**
* Given a reference time in milliseconds return the corresponding valid data size per log segment map by aggregating
* all buckets whose end time is less than or equal to the reference time.
* @param referenceTimeInMS the reference time in ms until which deletes and expiration are relevant
* @return a {@link Pair} whose first element is the end time of the last bucket that was aggregated and whose second
* element is the requested valid data size per log segment {@link NavigableMap}.
*/
Pair<Long, NavigableMap<String, Long>> getValidSizePerLogSegment(Long referenceTimeInMS) {
NavigableMap<String, Long> validSizePerLogSegment = new TreeMap<>(logSegmentBuckets.firstEntry().getValue());
NavigableMap<Long, NavigableMap<String, Long>> subMap =
logSegmentBuckets.subMap(logSegmentBuckets.firstKey(), false, referenceTimeInMS, true);
for (Map.Entry<Long, NavigableMap<String, Long>> bucket : subMap.entrySet()) {
for (Map.Entry<String, Long> bucketEntry : bucket.getValue().entrySet()) {
updateMapHelper(validSizePerLogSegment, bucketEntry.getKey(), bucketEntry.getValue());
}
}
Long lastReferenceBucketTimeInMs = subMap.isEmpty() ? logSegmentBuckets.firstKey() : subMap.lastKey();
return new Pair<>(lastReferenceBucketTimeInMs, validSizePerLogSegment);
}
/**
* Given a reference time in ms return the corresponding valid data size per container map by aggregating all buckets
* whose end time is less than or equal to the reference time.
* @param referenceTimeInMs the reference time in ms until which deletes and expiration are relevant.
* @return a {@link Pair} whose first element is the end time of the last bucket that was aggregated and whose second
* element is the requested valid data size per container {@link Map}.
*/
Map<String, Map<String, Long>> getValidSizePerContainer(Long referenceTimeInMs) {
Map<String, Map<String, Long>> validSizePerContainer = new HashMap<>();
for (Map.Entry<String, Map<String, Long>> accountEntry : containerBuckets.firstEntry().getValue().entrySet()) {
validSizePerContainer.put(accountEntry.getKey(), new HashMap<>(accountEntry.getValue()));
}
NavigableMap<Long, Map<String, Map<String, Long>>> subMap =
containerBuckets.subMap(containerBuckets.firstKey(), false, referenceTimeInMs, true);
for (Map.Entry<Long, Map<String, Map<String, Long>>> bucket : subMap.entrySet()) {
for (Map.Entry<String, Map<String, Long>> accountEntry : bucket.getValue().entrySet()) {
for (Map.Entry<String, Long> containerEntry : accountEntry.getValue().entrySet()) {
updateNestedMapHelper(validSizePerContainer, accountEntry.getKey(), containerEntry.getKey(),
containerEntry.getValue());
}
}
}
return validSizePerContainer;
}
/**
* Helper function to update nested map data structure.
* @param nestedMap nested {@link Map} to be updated
* @param firstKey of the nested map
* @param secondKey of the nested map
* @param value the value to be added at the corresponding entry
*/
private void updateNestedMapHelper(Map<String, Map<String, Long>> nestedMap, String firstKey, String secondKey,
Long value) {
if (!nestedMap.containsKey(firstKey)) {
nestedMap.put(firstKey, new HashMap<String, Long>());
}
updateMapHelper(nestedMap.get(firstKey), secondKey, value);
}
/**
* Helper function to update map data structure.
* @param map {@link Map} to be updated
* @param key of the map
* @param value the value to be added at the corresponding entry
*/
private void updateMapHelper(Map<String, Long> map, String key, Long value) {
Long newValue = map.containsKey(key) ? map.get(key) + value : value;
map.put(key, newValue);
}
}
| apache-2.0 |
mafulafunk/wicket | wicket-core/src/main/java/org/apache/wicket/application/ReloadingClassLoader.java | 9526 | /*
* 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.wicket.application;
import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import org.apache.wicket.util.collections.UrlExternalFormComparator;
import org.apache.wicket.util.file.File;
import org.apache.wicket.util.listener.IChangeListener;
import org.apache.wicket.util.time.Duration;
import org.apache.wicket.util.watch.IModificationWatcher;
import org.apache.wicket.util.watch.ModificationWatcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Custom ClassLoader that reverses the classloader lookups, and that is able to notify a listener
* when a class file is changed.
*
* @author <a href="mailto:jbq@apache.org">Jean-Baptiste Quenot</a>
*/
public class ReloadingClassLoader extends URLClassLoader
{
private static final Logger log = LoggerFactory.getLogger(ReloadingClassLoader.class);
private static final Set<URL> urls = new TreeSet<URL>(new UrlExternalFormComparator());
private static final List<String> patterns = new ArrayList<String>();
private IChangeListener listener;
private final Duration pollFrequency = Duration.seconds(3);
private final IModificationWatcher watcher;
static
{
addClassLoaderUrls(ReloadingClassLoader.class.getClassLoader());
excludePattern("org.apache.wicket.*");
includePattern("org.apache.wicket.examples.*");
}
/**
*
* @param name
* @return true if class if found, false otherwise
*/
protected boolean tryClassHere(String name)
{
// don't include classes in the java or javax.servlet package
if (name != null && (name.startsWith("java.") || name.startsWith("javax.servlet")))
{
return false;
}
// Scan includes, then excludes
boolean tryHere;
// If no explicit includes, try here
if (patterns == null || patterns.size() == 0)
{
tryHere = true;
}
else
{
// See if it matches include patterns
tryHere = false;
for (String rawpattern : patterns)
{
if (rawpattern.length() <= 1)
{
continue;
}
// FIXME it seems that only "includes" are handled. "Excludes" are ignored
boolean isInclude = rawpattern.substring(0, 1).equals("+");
String pattern = rawpattern.substring(1);
if (WildcardMatcherHelper.match(pattern, name) != null)
{
tryHere = isInclude;
}
}
}
return tryHere;
}
/**
* Include a pattern
*
* @param pattern
* the pattern to include
*/
public static void includePattern(String pattern)
{
patterns.add("+" + pattern);
}
/**
* Exclude a pattern
*
* @param pattern
* the pattern to exclude
*/
public static void excludePattern(String pattern)
{
patterns.add("-" + pattern);
}
/**
* Returns the list of all configured inclusion or exclusion patterns
*
* @return list of patterns as String
*/
public static List<String> getPatterns()
{
return patterns;
}
/**
* Add the location of a directory containing class files
*
* @param url
* the URL for the directory
*/
public static void addLocation(URL url)
{
urls.add(url);
}
/**
* Returns the list of all configured locations of directories containing class files
*
* @return list of locations as URL
*/
public static Set<URL> getLocations()
{
return urls;
}
/**
* Add all the url locations we can find for the provided class loader
*
* @param loader
* class loader
*/
private static void addClassLoaderUrls(ClassLoader loader)
{
if (loader != null)
{
final Enumeration<URL> resources;
try
{
resources = loader.getResources("");
}
catch (IOException e)
{
throw new RuntimeException(e);
}
while (resources.hasMoreElements())
{
URL location = resources.nextElement();
ReloadingClassLoader.addLocation(location);
}
}
}
/**
* Create a new reloading ClassLoader from a list of URLs, and initialize the
* ModificationWatcher to detect class file modifications
*
* @param parent
* the parent classloader in case the class file cannot be loaded from the above
* locations
*/
public ReloadingClassLoader(ClassLoader parent)
{
super(new URL[] { }, parent);
// probably doubles from this class, but just in case
addClassLoaderUrls(parent);
for (URL url : urls)
{
addURL(url);
}
watcher = new ModificationWatcher(pollFrequency);
}
/**
* Gets a resource from this <code>ClassLoader</class>. If the
* resource does not exist in this one, we check the parent.
* Please note that this is the exact opposite of the
* <code>ClassLoader</code> spec. We use it to work around inconsistent class loaders from third
* party vendors.
*
* @param name
* of resource
*/
@Override
public final URL getResource(final String name)
{
URL resource = findResource(name);
ClassLoader parent = getParent();
if (resource == null && parent != null)
{
resource = parent.getResource(name);
}
return resource;
}
/**
* Loads the class from this <code>ClassLoader</class>. If the
* class does not exist in this one, we check the parent. Please
* note that this is the exact opposite of the
* <code>ClassLoader</code> spec. We use it to load the class from the same classloader as
* WicketFilter or WicketServlet. When found, the class file is watched for modifications.
*
* @param name
* the name of the class
* @param resolve
* if <code>true</code> then resolve the class
* @return the resulting <code>Class</code> object
* @exception ClassNotFoundException
* if the class could not be found
*/
@Override
public final Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException
{
// First check if it's already loaded
Class<?> clazz = findLoadedClass(name);
if (clazz == null)
{
final ClassLoader parent = getParent();
if (tryClassHere(name))
{
try
{
clazz = findClass(name);
watchForModifications(clazz);
}
catch (ClassNotFoundException cnfe)
{
if (parent == null)
{
// Propagate exception
throw cnfe;
}
}
}
if (clazz == null)
{
if (parent == null)
{
throw new ClassNotFoundException(name);
}
else
{
// Will throw a CFNE if not found in parent
// see http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6500212
// clazz = parent.loadClass(name);
clazz = Class.forName(name, false, parent);
}
}
}
if (resolve)
{
resolveClass(clazz);
}
return clazz;
}
/**
* Sets the listener that will be notified when a class changes
*
* @param listener
* the listener to notify upon class change
*/
public void setListener(IChangeListener listener)
{
this.listener = listener;
}
/**
* Watch changes of a class file by locating it in the list of location URLs and adding the
* corresponding file to the ModificationWatcher
*
* @param clz
* the class to watch
*/
private void watchForModifications(Class<?> clz)
{
// Watch class in the future
Iterator<URL> locationsIterator = urls.iterator();
File clzFile = null;
while (locationsIterator.hasNext())
{
// FIXME only works for directories, but JARs etc could be checked
// as well
URL location = locationsIterator.next();
String clzLocation = location.getFile() + clz.getName().replaceAll("\\.", "/") +
".class";
log.debug("clzLocation=" + clzLocation);
clzFile = new File(clzLocation);
final File finalClzFile = clzFile;
if (clzFile.exists())
{
log.info("Watching changes of class " + clzFile);
watcher.add(clzFile, new IChangeListener()
{
@Override
public void onChange()
{
log.info("Class file " + finalClzFile + " has changed, reloading");
try
{
listener.onChange();
}
catch (Exception e)
{
log.error("Could not notify listener", e);
// If an error occurs when the listener is notified,
// remove the watched object to avoid rethrowing the
// exception at next check
// FIXME check if class file has been deleted
watcher.remove(finalClzFile);
}
}
});
break;
}
else
{
log.debug("Class file does not exist: " + clzFile);
}
}
if (clzFile != null && !clzFile.exists())
{
log.debug("Could not locate class " + clz.getName());
}
}
/**
* Remove the ModificationWatcher from the current reloading class loader
*/
public void destroy()
{
watcher.destroy();
}
}
| apache-2.0 |
skylot/jadx | jadx-core/src/test/java/jadx/tests/integration/conditions/TestTernary4.java | 944 | package jadx.tests.integration.conditions;
import org.junit.jupiter.api.Test;
import jadx.tests.api.SmaliTest;
import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat;
@SuppressWarnings("CommentedOutCode")
public class TestTernary4 extends SmaliTest {
// @formatter:off
/*
private Set test(HashMap<String, Object> hashMap) {
boolean z;
HashSet hashSet = new HashSet();
synchronized (this.defaultValuesByPath) {
for (String next : this.defaultValuesByPath.keySet()) {
Object obj = hashMap.get(next);
if (obj != null) {
z = !getValueObject(next).equals(obj);
} else {
z = this.valuesByPath.get(next) != null;;
}
if (z) {
hashSet.add(next);
}
}
}
return hashSet;
}
*/
// @formatter:on
@Test
public void test() {
assertThat(getClassNodeFromSmali())
.code()
.removeBlockComments()
.doesNotContain("5")
.doesNotContain("try");
}
}
| apache-2.0 |
skylot/jadx | jadx-core/src/test/java/jadx/tests/integration/debuginfo/TestVariablesNames.java | 1206 | package jadx.tests.integration.debuginfo;
import org.junit.jupiter.api.Test;
import jadx.core.dex.nodes.ClassNode;
import jadx.tests.api.SmaliTest;
import static jadx.tests.api.utils.JadxMatchers.containsOne;
import static org.hamcrest.MatcherAssert.assertThat;
public class TestVariablesNames extends SmaliTest {
// @formatter:off
/*
public static class TestCls {
public void test(String s, int k) {
f1(s);
int i = k + 3;
String s2 = "i" + i;
f2(i, s2);
double d = i * 5;
String s3 = "d" + d;
f3(d, s3);
}
private void f1(String s) {
}
private void f2(int i, String i2) {
}
private void f3(double d, String d2) {
}
}
*/
// @formatter:on
/**
* Parameter register reused in variables assign with different types and names
* No variables names in debug info
*/
@Test
public void test() {
ClassNode cls = getClassNodeFromSmaliWithPath("debuginfo", "TestVariablesNames");
String code = cls.getCode().toString();
// TODO: don't use current variables naming in tests
assertThat(code, containsOne("f1(str);"));
assertThat(code, containsOne("f2(i2, \"i\" + i2);"));
assertThat(code, containsOne("f3(d, \"d\" + d);"));
}
}
| apache-2.0 |
Cardshifter/Cardshifter | gdx/core/src/com/cardshifter/gdx/screens/GameScreen.java | 17117 | package com.cardshifter.gdx.screens;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.ui.*;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.cardshifter.api.incoming.UseAbilityMessage;
import com.cardshifter.api.messages.Message;
import com.cardshifter.api.outgoing.*;
import com.cardshifter.gdx.*;
import com.cardshifter.gdx.ui.CardshifterClientContext;
import com.cardshifter.gdx.ui.EntityView;
import com.cardshifter.gdx.ui.PlayerView;
import com.cardshifter.gdx.ui.cards.CardView;
import com.cardshifter.gdx.ui.cards.CardViewSmall;
import com.cardshifter.gdx.ui.zones.CompactHiddenZoneView;
import com.cardshifter.gdx.ui.zones.DefaultZoneView;
import com.cardshifter.gdx.ui.zones.ZoneView;
import java.util.*;
import java.util.List;
/**
* Created by Simon on 1/31/2015.
*/
public class GameScreen implements Screen, TargetableCallback {
private final CardshifterGame game;
private final CardshifterClient client;
private final int playerIndex;
private final int gameId;
private final Table table;
private final Map<Integer, ZoneView> zoneViews = new HashMap<Integer, ZoneView>();
private final Map<Integer, EntityView> entityViews = new HashMap<Integer, EntityView>();
private final Map<String, Container<Actor>> holders = new HashMap<String, Container<Actor>>();
private final List<EntityView> targetsSelected = new ArrayList<EntityView>();
private final Screen parentScreen;
private AvailableTargetsMessage targetsAvailable;
private final TargetableCallback onTarget = new TargetableCallback() {
@Override
public boolean addEntity(EntityView view) {
if (targetsSelected.contains(view)) {
targetsSelected.remove(view);
Gdx.app.log("GameScreen", "Removing selection " + view.getId());
view.setTargetable(TargetStatus.TARGETABLE, this);
return false;
}
if (targetsAvailable != null && targetsAvailable.getMax() == 1 && targetsAvailable.getMin() == 1) {
Gdx.app.log("GameScreen", "Sending selection " + view.getId());
client.send(new UseAbilityMessage(gameId, targetsAvailable.getEntity(), targetsAvailable.getAction(), new int[]{ view.getId() }));
return false;
}
Gdx.app.log("GameScreen", "Adding selection " + view.getId());
view.setTargetable(TargetStatus.TARGETED, this);
return targetsSelected.add(view);
}
};
private final CardshifterClientContext context;
//private final float screenWidth;
private final float screenHeight;
public GameScreen(final CardshifterGame game, final CardshifterClient client, NewGameMessage message, final Screen parentScreen) {
this.parentScreen = parentScreen;
this.game = game;
this.client = client;
this.playerIndex = message.getPlayerIndex();
this.gameId = message.getGameId();
this.context = new CardshifterClientContext(game.skin, message.getGameId(), client, game.stage);
//this.screenWidth = CardshifterGame.STAGE_WIDTH;
this.screenHeight = CardshifterGame.STAGE_HEIGHT;
this.table = new Table(game.skin);
Table leftTable = new Table(game.skin);
Table topTable = new Table(game.skin);
//Table rightTable = new Table(game.skin);
Table centerTable = new Table(game.skin);
TextButton backToMenu = new TextButton("Back to menu", game.skin);
backToMenu.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
game.setScreen(parentScreen);
}
});
leftTable.add(backToMenu).expandX().fill().row();
addZoneHolder(leftTable, 1 - this.playerIndex, "").expandY().fillY();
addZoneHolder(leftTable, this.playerIndex, "").expandY().fillY();
leftTable.add("controls").row();
TextButton actionDone = new TextButton("Done", game.skin);
actionDone.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
if (targetsAvailable != null) {
int selected = targetsSelected.size();
if (selected >= targetsAvailable.getMin() && selected <= targetsAvailable.getMax()) {
int[] targets = new int[targetsSelected.size()];
for (int i = 0; i < targets.length; i++) {
targets[i] = targetsSelected.get(i).getId();
}
UseAbilityMessage message = new UseAbilityMessage(gameId, targetsAvailable.getEntity(), targetsAvailable.getAction(), targets);
client.send(message);
}
}
}
});
leftTable.add(actionDone);
topTable.add(leftTable).left().expandY().fillY();
topTable.add(centerTable).center().expandX().expandY().fill();
//topTable.add(rightTable).right().width(150).expandY().fillY();
addZoneHolder(centerTable, 1 - this.playerIndex, "Hand").top().height(this.screenHeight/4);
addZoneHolder(centerTable, 1 - this.playerIndex, "Battlefield").height(this.screenHeight/4);
addZoneHolder(centerTable, this.playerIndex, "Battlefield").height(this.screenHeight/4);
this.table.add(topTable).expand().fill().row();
addZoneHolder(this.table, this.playerIndex, "Hand").height(140).expandX().fill();
this.table.setFillParent(true);
}
private Cell<Container<Actor>> addZoneHolder(Table table, int i, String name) {
Container<Actor> container = new Container<Actor>();
container.setName(name);
// container.fill();
Cell<Container<Actor>> cell = table.add(container).expandX().fillX();
table.row();
holders.put(i + name, container);
return cell;
}
@Override
public void render(float delta) {
}
@Override
public void resize(int width, int height) {
}
@Override
public void show() {
game.stage.addActor(table);
}
@Override
public void hide() {
table.remove();
}
@Override
public void pause() {
}
@Override
public void resume() {
}
@Override
public void dispose() {
}
public Map<Class<? extends Message>, SpecificHandler<?>> getHandlers() {
Map<Class<? extends Message>, SpecificHandler<?>> handlers =
new HashMap<Class<? extends Message>, SpecificHandler<?>>();
handlers.put(AvailableTargetsMessage.class, new SpecificHandler<AvailableTargetsMessage>() {
@Override
public void handle(AvailableTargetsMessage message) {
targetsAvailable = message;
targetsSelected.clear();
for (EntityView view : entityViews.values()) {
view.setTargetable(TargetStatus.NOT_TARGETABLE, onTarget);
}
for (int id : message.getTargets()) {
EntityView view = entityViews.get(id);
if (view != null) {
view.setTargetable(TargetStatus.TARGETABLE, onTarget);
}
}
}
});
handlers.put(UsableActionMessage.class, new SpecificHandler<UsableActionMessage>() {
@Override
public void handle(UsableActionMessage message) {
int id = message.getId();
EntityView view = entityViews.get(id);
if (view != null) {
view.usableAction(message);
if (view instanceof CardViewSmall) {
((CardViewSmall)view).setUsable(GameScreen.this);
}
}
}
});
handlers.put(CardInfoMessage.class, new SpecificHandler<CardInfoMessage>() {
@Override
public void handle(CardInfoMessage message) {
ZoneView zone = getZoneView(message.getZone());
if (zone != null) {
zone.removeCard(message.getId());
}
EntityView entityView = entityViews.remove(message.getId());
if (entityView != null) {
entityView.remove();
}
if (zone != null) {
entityViews.put(message.getId(), zone.addCard(message));
}
}
});
handlers.put(EntityRemoveMessage.class, new SpecificHandler<EntityRemoveMessage>() {
@Override
public void handle(EntityRemoveMessage message) {
EntityView view = entityViews.get(message.getEntity());
for (ZoneView zone : zoneViews.values()) {
if (zone.hasCard(message.getEntity())) {
zone.removeCard(message.getEntity());
}
}
if (view != null) {
view.entityRemoved();
entityViews.remove(message.getEntity());
}
}
});
handlers.put(GameOverMessage.class, new SpecificHandler<GameOverMessage>() {
@Override
public void handle(GameOverMessage message) {
Dialog dialog = new Dialog("Game Over!", context.getSkin()) {
@Override
protected void result(Object object) {
game.setScreen(parentScreen);
}
};
dialog.button("OK");
dialog.show(context.getStage());
}
});
handlers.put(PlayerMessage.class, new SpecificHandler<PlayerMessage>() {
@Override
public void handle(PlayerMessage message) {
PlayerView playerView = new PlayerView(context, message);
entityViews.put(message.getId(), playerView);
Container<Actor> holder = holders.get(String.valueOf(message.getIndex()));
if (holder != null) {
holder.setActor(playerView.getActor());
}
}
});
handlers.put(ResetAvailableActionsMessage.class, new SpecificHandler<ResetAvailableActionsMessage>() {
@Override
public void handle(ResetAvailableActionsMessage message) {
for (EntityView view : entityViews.values()) {
view.setTargetable(TargetStatus.NOT_TARGETABLE, null);
view.clearUsableActions();
}
}
});
handlers.put(UpdateMessage.class, new SpecificHandler<UpdateMessage>() {
@Override
public void handle(UpdateMessage message) {
EntityView entityView = entityViews.get(message.getId());
if (entityView != null) {
entityView.set(message.getKey(), message.getValue());
}
}
});
handlers.put(ZoneChangeMessage.class, new SpecificHandler<ZoneChangeMessage>() {
@Override
public void handle(ZoneChangeMessage message) {
ZoneView oldZone = getZoneView(message.getSourceZone()); // can be null
ZoneView destinationZone = getZoneView(message.getDestinationZone());
int id = message.getEntity();
CardView entityView = (CardView) entityViews.remove(id); // can be null
if (oldZone != null) {
oldZone.removeCard(id);
}
if (destinationZone != null) {
CardView newCardView = destinationZone.addCard(new CardInfoMessage(message.getDestinationZone(), id,
entityView == null ? null : entityView.getInfo()));
if (entityView != null) {
entityView.zoneMove(message, destinationZone, newCardView);
}
entityViews.put(id, newCardView);
}
else {
if (entityView != null) {
entityView.zoneMove(message, destinationZone, null);
}
}
/*
Send to AI Medium: ZoneChangeMessage [entity=95, sourceZone=72, destinationZone=73]
Send to AI Medium: CardInfo: 95 in zone 73 - {SCRAP=1, TAUNT=1, MAX_HEALTH=1, SICKNESS=1, MANA_COST=2, name=The Chopper, ATTACK=2, creatureType=Mech, HEALTH=1, ATTACK_AVAILABLE=1}
Send to Zomis: ZoneChangeMessage [entity=95, sourceZone=72, destinationZone=73]
if card is already known, send ZoneChange only
if card is not known, send ZoneChange first and then CardInfo
when cards are created from nowhere, ZoneChange with source -1 is sent and then CardInfo
*/
}
});
handlers.put(ZoneMessage.class, new SpecificHandler<ZoneMessage>() {
@Override
public void handle(ZoneMessage message) {
Gdx.app.log("GameScreen", "Zone " + message);
ZoneView zoneView = createZoneView(message);
if (zoneView != null) {
PlayerView view = (PlayerView) entityViews.get(message.getOwner());
if (view == null) {
Gdx.app.log("GameScreen", "no playerView for " + message.getOwner());
return;
}
String key = view.getIndex() + message.getName();
Container<Actor> container = holders.get(key);
if (container == null) {
Gdx.app.log("GameScreen", "no container for " + key);
return;
}
Gdx.app.log("GameScreen", "putting zoneview for " + key);
container.setActor(zoneView.getActor());
zoneViews.put(message.getId(), zoneView);
}
}
});
return handlers;
}
private ZoneView createZoneView(ZoneMessage message) {
String type = message.getName();
if (type.equals("Battlefield")) {
return new DefaultZoneView(context, message, this.entityViews);
}
if (type.equals("Hand")) {
return new DefaultZoneView(context, message, this.entityViews);
}
if (type.equals("Deck")) {
return new CompactHiddenZoneView(game, message);
}
if (type.equals("Cards")) {
return null; // Card models only
}
throw new RuntimeException("Unknown ZoneView type: " + message.getName());
}
private ZoneView getZoneView(int id) {
return this.zoneViews.get(id);
}
public boolean checkCardDrop(CardViewSmall cardView) {
Table table = (Table)cardView.getActor();
Vector2 stageLoc = table.localToStageCoordinates(new Vector2());
Rectangle tableRect = new Rectangle(stageLoc.x, stageLoc.y, table.getWidth(), table.getHeight());
for (Container<Actor> actor : this.holders.values()) {
if (actor.getName() == "Battlefield") {
Vector2 stageBattlefieldLoc = actor.localToStageCoordinates(new Vector2(actor.getActor().getX(), actor.getActor().getY()));
Vector2 modifiedSBL = new Vector2(stageBattlefieldLoc.x - actor.getWidth()/2, stageBattlefieldLoc.y - actor.getHeight()/2);
Rectangle deckRect = new Rectangle(modifiedSBL.x, modifiedSBL.y, actor.getWidth() * 0.8f, actor.getHeight());
//uncomment this to see the bug where battlefields pop up in strange places
/*
Image squareImage = new Image(new Texture(Gdx.files.internal("cardbg.png")));
squareImage.setPosition(modifiedSBL.x, modifiedSBL.y);
squareImage.setSize(deckRect.width, deckRect.height);
this.game.stage.addActor(squareImage);
*/
if (tableRect.overlaps(deckRect)) {
//this.addEntity(cardView);
System.out.println("target found!");
return true;
}
}
}
return false;
//these can be used to double check the location of the rectangles
/*
Image squareImage = new Image(new Texture(Gdx.files.internal("cardbg.png")));
squareImage.setPosition(modifiedSBL.x, modifiedSBL.y);
squareImage.setSize(deckRect.width, deckRect.height);
this.game.stage.addActor(squareImage);
*/
/*
Image squareImage = new Image(new Texture(Gdx.files.internal("cardbg.png")));
squareImage.setPosition(stageLoc.x, stageLoc.y);
squareImage.setSize(tableRect.width, tableRect.height);
this.game.stage.addActor(squareImage);
*/
}
@Override
public boolean addEntity(EntityView view) {
//called by the CardViewSmall when not in mulligan mode, nothing will happen
return false;
}
}
| apache-2.0 |
jk1/intellij-community | python/src/com/jetbrains/python/inspections/quickfix/AddFieldQuickFix.java | 10326 | /*
* 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.jetbrains.python.inspections.quickfix;
import com.intellij.codeInsight.CodeInsightUtilCore;
import com.intellij.codeInsight.FileModificationService;
import com.intellij.codeInsight.template.TemplateBuilder;
import com.intellij.codeInsight.template.TemplateBuilderFactory;
import com.intellij.codeInspection.LocalQuickFix;
import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.openapi.application.WriteAction;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.fileEditor.OpenFileDescriptor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.MessageType;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.Function;
import com.jetbrains.python.PyBundle;
import com.jetbrains.python.PyNames;
import com.jetbrains.python.psi.*;
import com.jetbrains.python.psi.impl.PyPsiUtils;
import com.jetbrains.python.psi.types.PyClassType;
import com.jetbrains.python.psi.types.PyClassTypeImpl;
import com.jetbrains.python.psi.types.PyType;
import com.jetbrains.python.psi.types.TypeEvalContext;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* Available on self.my_something when my_something is unresolved.
* User: dcheryasov
*/
public class AddFieldQuickFix implements LocalQuickFix {
private final String myInitializer;
private final String myClassName;
private final String myIdentifier;
private boolean replaceInitializer = false;
public AddFieldQuickFix(@NotNull final String identifier, @NotNull final String initializer, final String className, boolean replace) {
myIdentifier = identifier;
myInitializer = initializer;
myClassName = className;
replaceInitializer = replace;
}
@NotNull
public String getName() {
return PyBundle.message("QFIX.NAME.add.field.$0.to.class.$1", myIdentifier, myClassName);
}
@NotNull
public String getFamilyName() {
return "Add field to class";
}
@NotNull
public static PsiElement appendToMethod(PyFunction init, Function<String, PyStatement> callback) {
// add this field as the last stmt of the constructor
final PyStatementList statementList = init.getStatementList();
// name of 'self' may be different for fancier styles
String selfName = PyNames.CANONICAL_SELF;
final PyParameter[] params = init.getParameterList().getParameters();
if (params.length > 0) {
selfName = params[0].getName();
}
final PyStatement newStmt = callback.fun(selfName);
final PsiElement result = PyUtil.addElementToStatementList(newStmt, statementList, true);
PyPsiUtils.removeRedundantPass(statementList);
return result;
}
public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
// expect the descriptor to point to the unresolved identifier.
final PsiElement element = descriptor.getPsiElement();
final PyClassType type = getClassType(element);
if (type == null) return;
final PyClass cls = type.getPyClass();
if (!FileModificationService.getInstance().preparePsiElementForWrite(cls)) return;
WriteAction.run(() -> {
PsiElement initStatement;
if (!type.isDefinition()) {
initStatement = addFieldToInit(project, cls, myIdentifier, new CreateFieldCallback(project, myIdentifier, myInitializer));
}
else {
PyStatement field = PyElementGenerator.getInstance(project)
.createFromText(LanguageLevel.getDefault(), PyStatement.class, myIdentifier + " = " + myInitializer);
initStatement = PyUtil.addElementToStatementList(field, cls.getStatementList(), true);
}
if (initStatement != null) {
showTemplateBuilder(initStatement, cls.getContainingFile());
return;
}
// somehow we failed. tell about this
PyUtil.showBalloon(project, PyBundle.message("QFIX.failed.to.add.field"), MessageType.ERROR);
});
}
@Override
public boolean startInWriteAction() {
return false;
}
private static PyClassType getClassType(@NotNull final PsiElement element) {
if (element instanceof PyQualifiedExpression) {
final PyExpression qualifier = ((PyQualifiedExpression)element).getQualifier();
if (qualifier == null) return null;
final PyType type = TypeEvalContext.userInitiated(element.getProject(), element.getContainingFile()).getType(qualifier);
return type instanceof PyClassType ? (PyClassType)type : null;
}
final PyClass aClass = PsiTreeUtil.getParentOfType(element, PyClass.class);
return aClass != null ? new PyClassTypeImpl(aClass, false) : null;
}
private void showTemplateBuilder(PsiElement initStatement, @NotNull final PsiFile file) {
initStatement = CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(initStatement);
if (initStatement instanceof PyAssignmentStatement) {
final TemplateBuilder builder = TemplateBuilderFactory.getInstance().createTemplateBuilder(initStatement);
final PyExpression assignedValue = ((PyAssignmentStatement)initStatement).getAssignedValue();
final PyExpression leftExpression = ((PyAssignmentStatement)initStatement).getLeftHandSideExpression();
if (assignedValue != null && leftExpression != null) {
if (replaceInitializer)
builder.replaceElement(assignedValue, myInitializer);
else
builder.replaceElement(leftExpression.getLastChild(), myIdentifier);
final VirtualFile virtualFile = file.getVirtualFile();
if (virtualFile == null) return;
final Editor editor = FileEditorManager.getInstance(file.getProject()).openTextEditor(
new OpenFileDescriptor(file.getProject(), virtualFile), true);
if (editor == null) return;
builder.run(editor, false);
}
}
}
@Nullable
public static PsiElement addFieldToInit(Project project, PyClass cls, String itemName, Function<String, PyStatement> callback) {
if (cls != null && itemName != null) {
PyFunction init = cls.findMethodByName(PyNames.INIT, false, null);
if (init != null) {
return appendToMethod(init, callback);
}
else { // no init! boldly copy ancestor's.
for (PyClass ancestor : cls.getAncestorClasses(null)) {
init = ancestor.findMethodByName(PyNames.INIT, false, null);
if (init != null) break;
}
PyFunction newInit = createInitMethod(project, cls, init);
appendToMethod(newInit, callback);
PsiElement addAnchor = null;
PyFunction[] meths = cls.getMethods();
if (meths.length > 0) addAnchor = meths[0].getPrevSibling();
PyStatementList clsContent = cls.getStatementList();
newInit = (PyFunction) clsContent.addAfter(newInit, addAnchor);
PyUtil.showBalloon(project, PyBundle.message("QFIX.added.constructor.$0.for.field.$1", cls.getName(), itemName), MessageType.INFO);
final PyStatementList statementList = newInit.getStatementList();
final PyStatement[] statements = statementList.getStatements();
return statements.length != 0 ? statements[0] : null;
}
}
return null;
}
@NotNull
private static PyFunction createInitMethod(Project project, PyClass cls, @Nullable PyFunction ancestorInit) {
// found it; copy its param list and make a call to it.
String paramList = ancestorInit != null ? ancestorInit.getParameterList().getText() : "(self)";
String functionText = "def " + PyNames.INIT + paramList + ":\n";
if (ancestorInit == null) functionText += " pass";
else {
final PyClass ancestorClass = ancestorInit.getContainingClass();
if (ancestorClass != null && !PyUtil.isObjectClass(ancestorClass)) {
StringBuilder sb = new StringBuilder();
PyParameter[] params = ancestorInit.getParameterList().getParameters();
boolean seen = false;
if (cls.isNewStyleClass(null)) {
// form the super() call
sb.append("super(");
if (!LanguageLevel.forElement(cls).isPy3K()) {
sb.append(cls.getName());
// NOTE: assume that we have at least the first param
String self_name = params[0].getName();
sb.append(", ").append(self_name);
}
sb.append(").").append(PyNames.INIT).append("(");
}
else {
sb.append(ancestorClass.getName());
sb.append(".__init__(self");
seen = true;
}
for (int i = 1; i < params.length; i += 1) {
if (seen) sb.append(", ");
else seen = true;
sb.append(params[i].getText());
}
sb.append(")");
functionText += " " + sb.toString();
}
else {
functionText += " pass";
}
}
return PyElementGenerator.getInstance(project).createFromText(
LanguageLevel.getDefault(), PyFunction.class, functionText,
new int[]{0}
);
}
private static class CreateFieldCallback implements Function<String, PyStatement> {
private final Project myProject;
private final String myItemName;
private final String myInitializer;
private CreateFieldCallback(Project project, String itemName, String initializer) {
myProject = project;
myItemName = itemName;
myInitializer = initializer;
}
public PyStatement fun(String selfName) {
return PyElementGenerator.getInstance(myProject).createFromText(LanguageLevel.getDefault(), PyStatement.class, selfName + "." + myItemName + " = " + myInitializer);
}
}
}
| apache-2.0 |
AndroidX/androidx | emoji/emoji/src/androidTest/java/androidx/emoji/text/MetadataRepoTest.java | 3654 | /*
* Copyright 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.emoji.text;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.filters.SdkSuppress;
import androidx.test.filters.SmallTest;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@SmallTest
@RunWith(AndroidJUnit4.class)
@SdkSuppress(minSdkVersion = 19)
public class MetadataRepoTest {
MetadataRepo mMetadataRepo;
@Before
public void clearResourceIndex() {
mMetadataRepo = new MetadataRepo();
}
@Test(expected = NullPointerException.class)
public void testPut_withNullMetadata() {
mMetadataRepo.put(null);
}
@Test(expected = IllegalArgumentException.class)
public void testPut_withEmptyKeys() {
mMetadataRepo.put(new TestEmojiMetadata(new int[0]));
}
@Test
public void testPut_withSingleCodePointMapping() {
final int[] codePoint = new int[]{1};
final TestEmojiMetadata metadata = new TestEmojiMetadata(codePoint);
mMetadataRepo.put(metadata);
assertSame(metadata, getNode(codePoint));
}
@Test
public void testPut_withMultiCodePointsMapping() {
final int[] codePoint = new int[]{1, 2, 3, 4};
final TestEmojiMetadata metadata = new TestEmojiMetadata(codePoint);
mMetadataRepo.put(metadata);
assertSame(metadata, getNode(codePoint));
assertEquals(null, getNode(new int[]{1}));
assertEquals(null, getNode(new int[]{1, 2}));
assertEquals(null, getNode(new int[]{1, 2, 3}));
assertEquals(null, getNode(new int[]{1, 2, 3, 5}));
}
@Test
public void testPut_sequentialCodePoints() {
final int[] codePoint1 = new int[]{1, 2, 3, 4};
final EmojiMetadata metadata1 = new TestEmojiMetadata(codePoint1);
final int[] codePoint2 = new int[]{1, 2, 3};
final EmojiMetadata metadata2 = new TestEmojiMetadata(codePoint2);
final int[] codePoint3 = new int[]{1, 2};
final EmojiMetadata metadata3 = new TestEmojiMetadata(codePoint3);
mMetadataRepo.put(metadata1);
mMetadataRepo.put(metadata2);
mMetadataRepo.put(metadata3);
assertSame(metadata1, getNode(codePoint1));
assertSame(metadata2, getNode(codePoint2));
assertSame(metadata3, getNode(codePoint3));
assertEquals(null, getNode(new int[]{1}));
assertEquals(null, getNode(new int[]{1, 2, 3, 4, 5}));
}
final EmojiMetadata getNode(final int[] codepoints) {
return getNode(mMetadataRepo.getRootNode(), codepoints, 0);
}
final EmojiMetadata getNode(MetadataRepo.Node node, final int[] codepoints, int start) {
if (codepoints.length < start) return null;
if (codepoints.length == start) return node.getData();
final MetadataRepo.Node childNode = node.get(codepoints[start]);
if (childNode == null) return null;
return getNode(childNode, codepoints, start + 1);
}
}
| apache-2.0 |