repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15
values |
|---|---|---|---|---|
lburgazzoli/apache-camel | components/camel-test/src/main/java/org/apache/camel/test/junit4/CamelTestSupport.java | 37249 | /**
* 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.test.junit4;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import javax.management.AttributeNotFoundException;
import javax.management.InstanceNotFoundException;
import javax.management.MBeanException;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.management.ReflectionException;
import javax.naming.Context;
import javax.naming.InitialContext;
import org.apache.camel.CamelContext;
import org.apache.camel.ConsumerTemplate;
import org.apache.camel.Endpoint;
import org.apache.camel.Exchange;
import org.apache.camel.Expression;
import org.apache.camel.FluentProducerTemplate;
import org.apache.camel.Message;
import org.apache.camel.NoSuchEndpointException;
import org.apache.camel.Predicate;
import org.apache.camel.Processor;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.Route;
import org.apache.camel.RoutesBuilder;
import org.apache.camel.Service;
import org.apache.camel.ServiceStatus;
import org.apache.camel.api.management.mbean.ManagedCamelContextMBean;
import org.apache.camel.api.management.mbean.ManagedProcessorMBean;
import org.apache.camel.api.management.mbean.ManagedRouteMBean;
import org.apache.camel.builder.AdviceWithRouteBuilder;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.component.properties.PropertiesComponent;
import org.apache.camel.impl.BreakpointSupport;
import org.apache.camel.impl.DefaultCamelBeanPostProcessor;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.impl.DefaultDebugger;
import org.apache.camel.impl.InterceptSendToMockEndpointStrategy;
import org.apache.camel.impl.JndiRegistry;
import org.apache.camel.management.JmxSystemPropertyKeys;
import org.apache.camel.model.ModelCamelContext;
import org.apache.camel.model.ProcessorDefinition;
import org.apache.camel.spi.Language;
import org.apache.camel.util.IOHelper;
import org.apache.camel.util.StopWatch;
import org.apache.camel.util.TimeUtils;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.Rule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A useful base class which creates a {@link org.apache.camel.CamelContext} with some routes
* along with a {@link org.apache.camel.ProducerTemplate} for use in the test case
*
* @version
*/
public abstract class CamelTestSupport extends TestSupport {
private static final Logger LOG = LoggerFactory.getLogger(CamelTestSupport.class);
private static final ThreadLocal<Boolean> INIT = new ThreadLocal<Boolean>();
private static ThreadLocal<ModelCamelContext> threadCamelContext = new ThreadLocal<ModelCamelContext>();
private static ThreadLocal<ProducerTemplate> threadTemplate = new ThreadLocal<ProducerTemplate>();
private static ThreadLocal<FluentProducerTemplate> threadFluentTemplate = new ThreadLocal<FluentProducerTemplate>();
private static ThreadLocal<ConsumerTemplate> threadConsumer = new ThreadLocal<ConsumerTemplate>();
private static ThreadLocal<Service> threadService = new ThreadLocal<Service>();
protected volatile ModelCamelContext context;
protected volatile ProducerTemplate template;
protected volatile FluentProducerTemplate fluentTemplate;
protected volatile ConsumerTemplate consumer;
protected volatile Service camelContextService;
protected boolean dumpRouteStats;
private boolean useRouteBuilder = true;
private final DebugBreakpoint breakpoint = new DebugBreakpoint();
private final StopWatch watch = new StopWatch();
private final Map<String, String> fromEndpoints = new HashMap<String, String>();
private CamelTestWatcher camelTestWatcher = new CamelTestWatcher();
/**
* Use the RouteBuilder or not
* @return <tt>true</tt> then {@link CamelContext} will be auto started,
* <tt>false</tt> then {@link CamelContext} will <b>not</b> be auto started (you will have to start it manually)
*/
public boolean isUseRouteBuilder() {
return useRouteBuilder;
}
public void setUseRouteBuilder(boolean useRouteBuilder) {
this.useRouteBuilder = useRouteBuilder;
}
/**
* Whether to dump route coverage stats at the end of the test.
* <p/>
* This allows tooling or manual inspection of the stats, so you can generate a route trace diagram of which EIPs
* have been in use and which have not. Similar concepts as a code coverage report.
*
* @return <tt>true</tt> to write route coverage status in an xml file in the <tt>target/camel-route-coverage</tt> directory after the test has finished.
*/
public boolean isDumpRouteCoverage() {
return false;
}
/**
* Override when using <a href="http://camel.apache.org/advicewith.html">advice with</a> and return <tt>true</tt>.
* This helps knowing advice with is to be used, and {@link CamelContext} will not be started before
* the advice with takes place. This helps by ensuring the advice with has been property setup before the
* {@link CamelContext} is started
* <p/>
* <b>Important:</b> Its important to start {@link CamelContext} manually from the unit test
* after you are done doing all the advice with.
*
* @return <tt>true</tt> if you use advice with in your unit tests.
*/
public boolean isUseAdviceWith() {
return false;
}
/**
* Override to control whether {@link CamelContext} should be setup per test or per class.
* <p/>
* By default it will be setup/teardown per test (per test method). If you want to re-use
* {@link CamelContext} between test methods you can override this method and return <tt>true</tt>
* <p/>
* <b>Important:</b> Use this with care as the {@link CamelContext} will carry over state
* from previous tests, such as endpoints, components etc. So you cannot use this in all your tests.
* <p/>
* Setting up {@link CamelContext} uses the {@link #doPreSetup()}, {@link #doSetUp()}, and {@link #doPostSetup()}
* methods in that given order.
*
* @return <tt>true</tt> per class, <tt>false</tt> per test.
*/
public boolean isCreateCamelContextPerClass() {
return false;
}
/**
* Override to enable auto mocking endpoints based on the pattern.
* <p/>
* Return <tt>*</tt> to mock all endpoints.
*
* @see org.apache.camel.util.EndpointHelper#matchEndpoint(String, String)
*/
public String isMockEndpoints() {
return null;
}
/**
* Override to enable auto mocking endpoints based on the pattern, and <b>skip</b> sending
* to original endpoint.
* <p/>
* Return <tt>*</tt> to mock all endpoints.
*
* @see org.apache.camel.util.EndpointHelper#matchEndpoint(String, String)
*/
public String isMockEndpointsAndSkip() {
return null;
}
public void replaceRouteFromWith(String routeId, String fromEndpoint) {
fromEndpoints.put(routeId, fromEndpoint);
}
/**
* Override to enable debugger
* <p/>
* Is default <tt>false</tt>
*/
public boolean isUseDebugger() {
return false;
}
public Service getCamelContextService() {
return camelContextService;
}
public Service camelContextService() {
return camelContextService;
}
public CamelContext context() {
return context;
}
public ProducerTemplate template() {
return template;
}
public FluentProducerTemplate fluentTemplate() {
return fluentTemplate;
}
public ConsumerTemplate consumer() {
return consumer;
}
/**
* Allows a service to be registered a separate lifecycle service to start
* and stop the context; such as for Spring when the ApplicationContext is
* started and stopped, rather than directly stopping the CamelContext
*/
public void setCamelContextService(Service service) {
camelContextService = service;
threadService.set(camelContextService);
}
@Before
public void setUp() throws Exception {
log.info("********************************************************************************");
log.info("Testing: " + getTestMethodName() + "(" + getClass().getName() + ")");
log.info("********************************************************************************");
if (isCreateCamelContextPerClass()) {
// test is per class, so only setup once (the first time)
boolean first = INIT.get() == null;
if (first) {
doPreSetup();
doSetUp();
doPostSetup();
} else {
// and in between tests we must do IoC and reset mocks
postProcessTest();
resetMocks();
}
} else {
// test is per test so always setup
doPreSetup();
doSetUp();
doPostSetup();
}
// only start timing after all the setup
watch.restart();
}
/**
* Strategy to perform any pre setup, before {@link CamelContext} is created
*/
protected void doPreSetup() throws Exception {
// noop
}
/**
* Strategy to perform any post setup after {@link CamelContext} is created
*/
protected void doPostSetup() throws Exception {
// noop
}
private void doSetUp() throws Exception {
log.debug("setUp test");
// jmx is enabled if we have configured to use it, or if dump route coverage is enabled (it requires JMX)
boolean jmx = useJmx() || isDumpRouteCoverage();
if (jmx) {
enableJMX();
} else {
disableJMX();
}
context = (ModelCamelContext)createCamelContext();
threadCamelContext.set(context);
assertNotNull("No context found!", context);
// reduce default shutdown timeout to avoid waiting for 300 seconds
context.getShutdownStrategy().setTimeout(getShutdownTimeout());
// set debugger if enabled
if (isUseDebugger()) {
if (context.getStatus().equals(ServiceStatus.Started)) {
log.info("Cannot setting the Debugger to the starting CamelContext, stop the CamelContext now.");
// we need to stop the context first to setup the debugger
context.stop();
}
context.setDebugger(new DefaultDebugger());
context.getDebugger().addBreakpoint(breakpoint);
// note: when stopping CamelContext it will automatic remove the breakpoint
}
template = context.createProducerTemplate();
template.start();
fluentTemplate = context.createFluentProducerTemplate();
fluentTemplate.start();
consumer = context.createConsumerTemplate();
consumer.start();
threadTemplate.set(template);
threadFluentTemplate.set(fluentTemplate);
threadConsumer.set(consumer);
// enable auto mocking if enabled
String pattern = isMockEndpoints();
if (pattern != null) {
context.addRegisterEndpointCallback(new InterceptSendToMockEndpointStrategy(pattern));
}
pattern = isMockEndpointsAndSkip();
if (pattern != null) {
context.addRegisterEndpointCallback(new InterceptSendToMockEndpointStrategy(pattern, true));
}
// configure properties component (mandatory for testing)
PropertiesComponent pc = context.getComponent("properties", PropertiesComponent.class);
Properties extra = useOverridePropertiesWithPropertiesComponent();
if (extra != null && !extra.isEmpty()) {
pc.setOverrideProperties(extra);
}
Boolean ignore = ignoreMissingLocationWithPropertiesComponent();
if (ignore != null) {
pc.setIgnoreMissingLocation(ignore);
}
postProcessTest();
if (isUseRouteBuilder()) {
RoutesBuilder[] builders = createRouteBuilders();
for (RoutesBuilder builder : builders) {
log.debug("Using created route builder: " + builder);
context.addRoutes(builder);
}
replaceFromEndpoints();
boolean skip = "true".equalsIgnoreCase(System.getProperty("skipStartingCamelContext"));
if (skip) {
log.info("Skipping starting CamelContext as system property skipStartingCamelContext is set to be true.");
} else if (isUseAdviceWith()) {
log.info("Skipping starting CamelContext as isUseAdviceWith is set to true.");
} else {
startCamelContext();
}
} else {
replaceFromEndpoints();
log.debug("Using route builder from the created context: " + context);
}
log.debug("Routing Rules are: " + context.getRoutes());
assertValidContext(context);
INIT.set(true);
}
private void replaceFromEndpoints() throws Exception {
for (final Map.Entry<String, String> entry : fromEndpoints.entrySet()) {
context.getRouteDefinition(entry.getKey()).adviceWith(context, new AdviceWithRouteBuilder() {
@Override
public void configure() throws Exception {
replaceFromWith(entry.getValue());
}
});
}
}
@After
public void tearDown() throws Exception {
long time = watch.stop();
log.info("********************************************************************************");
log.info("Testing done: " + getTestMethodName() + "(" + getClass().getName() + ")");
log.info("Took: " + TimeUtils.printDuration(time) + " (" + time + " millis)");
// if we should dump route stats, then write that to a file
if (isDumpRouteCoverage()) {
String className = this.getClass().getSimpleName();
String dir = "target/camel-route-coverage";
String name = className + "-" + getTestMethodName() + ".xml";
ManagedCamelContextMBean managedCamelContext = context.getManagedCamelContext();
if (managedCamelContext == null) {
log.warn("Cannot dump route coverage to file as JMX is not enabled. Override useJmx() method to enable JMX in the unit test classes.");
} else {
logCoverageSummary(managedCamelContext);
String xml = managedCamelContext.dumpRoutesCoverageAsXml();
String combined = "<camelRouteCoverage>\n" + gatherTestDetailsAsXml() + xml + "\n</camelRouteCoverage>";
File file = new File(dir);
// ensure dir exists
file.mkdirs();
file = new File(dir, name);
log.info("Dumping route coverage to file: " + file);
InputStream is = new ByteArrayInputStream(combined.getBytes());
OutputStream os = new FileOutputStream(file, false);
IOHelper.copyAndCloseInput(is, os);
IOHelper.close(os);
}
}
log.info("********************************************************************************");
if (isCreateCamelContextPerClass()) {
// we tear down in after class
return;
}
LOG.debug("tearDown test");
doStopTemplates(consumer, template, fluentTemplate);
doStopCamelContext(context, camelContextService);
}
/**
* Logs route coverage summary:
* - which routes are uncovered
* - what is the coverage of each processor in each route
*/
private void logCoverageSummary(ManagedCamelContextMBean managedCamelContext) throws Exception {
StringBuilder builder = new StringBuilder("\nCoverage summary\n");
int routes = managedCamelContext.getTotalRoutes();
long contextExchangesTotal = managedCamelContext.getExchangesTotal();
List<String> uncoveredRoutes = new ArrayList<>();
StringBuilder routesSummary = new StringBuilder();
routesSummary.append("\tProcessor coverage\n");
MBeanServer server = context.getManagementStrategy().getManagementAgent().getMBeanServer();
Map<String, List<ManagedProcessorMBean>> processorsForRoute = findProcessorsForEachRoute(server);
// log processor coverage for each route
for (Route route : context.getRoutes()) {
ManagedRouteMBean managedRoute = context.getManagedRoute(route.getId(), ManagedRouteMBean.class);
if (managedRoute.getExchangesTotal() == 0) {
uncoveredRoutes.add(route.getId());
}
long routeCoveragePercentage = Math.round((double) managedRoute.getExchangesTotal() / contextExchangesTotal * 100);
routesSummary.append("\t\tRoute ").append(route.getId()).append(" total: ").append(managedRoute.getExchangesTotal()).append(" (").append(routeCoveragePercentage).append("%)\n");
if (server != null) {
for (ManagedProcessorMBean managedProcessor : processorsForRoute.get(route.getId())) {
String processorId = managedProcessor.getProcessorId();
long processorExchangesTotal = managedProcessor.getExchangesTotal();
long processorCoveragePercentage = Math.round((double) processorExchangesTotal / contextExchangesTotal * 100);
routesSummary.append("\t\t\tProcessor ").append(processorId).append(" total: ").append(processorExchangesTotal).append(" (").append(processorCoveragePercentage).append("%)\n");
}
}
}
int used = routes - uncoveredRoutes.size();
long contextPercentage = Math.round((double) used / routes * 100);
builder.append("\tRoute coverage: ").append(used).append(" out of ").append(routes).append(" routes used (").append(contextPercentage).append("%)\n");
builder.append("\t\tCamelContext (").append(managedCamelContext.getCamelId()).append(") total: ").append(contextExchangesTotal).append("\n");
if (uncoveredRoutes.size() > 0) {
builder.append("\t\tUncovered routes: ").append(uncoveredRoutes.stream().collect(Collectors.joining(", "))).append("\n");
}
builder.append(routesSummary);
log.info(builder.toString());
}
/**
* Groups all processors from Camel context by route id
*/
private Map<String, List<ManagedProcessorMBean>> findProcessorsForEachRoute(MBeanServer server)
throws MalformedObjectNameException, MBeanException, AttributeNotFoundException, InstanceNotFoundException, ReflectionException {
String domain = context.getManagementStrategy().getManagementAgent().getMBeanServerDefaultDomain();
Map<String, List<ManagedProcessorMBean>> processorsForRoute = new HashMap<>();
ObjectName processorsObjectName = new ObjectName(domain + ":context=" + context.getManagementName() + ",type=processors,name=*");
Set<ObjectName> objectNames = server.queryNames(processorsObjectName, null);
if (server != null) {
for (ObjectName objectName : objectNames) {
String routeId = server.getAttribute(objectName, "RouteId").toString();
String name = objectName.getKeyProperty("name");
name = ObjectName.unquote(name);
ManagedProcessorMBean managedProcessor = context.getManagedProcessor(name, ManagedProcessorMBean.class);
if (managedProcessor != null) {
if (processorsForRoute.get(routeId) == null) {
List<ManagedProcessorMBean> processorsList = new ArrayList<>();
processorsList.add(managedProcessor);
processorsForRoute.put(routeId, processorsList);
} else {
processorsForRoute.get(routeId).add(managedProcessor);
}
}
}
}
// sort processors by position in route definition
for (Map.Entry<String, List<ManagedProcessorMBean>> entry : processorsForRoute.entrySet()) {
Collections.sort(entry.getValue(), (o1, o2) -> o1.getIndex().compareTo(o2.getIndex()));
}
return processorsForRoute;
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
INIT.remove();
LOG.debug("tearDownAfterClass test");
doStopTemplates(threadConsumer.get(), threadTemplate.get(), threadFluentTemplate.get());
doStopCamelContext(threadCamelContext.get(), threadService.get());
}
/**
* Gathers test details as xml
*/
private String gatherTestDetailsAsXml() {
StringBuilder sb = new StringBuilder();
sb.append("<test>\n");
sb.append(" <class>").append(getClass().getName()).append("</class>\n");
sb.append(" <method>").append(getTestMethodName()).append("</method>\n");
sb.append(" <time>").append(getCamelTestWatcher().timeTaken()).append("</time>\n");
sb.append("</test>\n");
return sb.toString();
}
/**
* Returns the timeout to use when shutting down (unit in seconds).
* <p/>
* Will default use 10 seconds.
*
* @return the timeout to use
*/
protected int getShutdownTimeout() {
return 10;
}
/**
* Whether or not JMX should be used during testing.
*
* @return <tt>false</tt> by default.
*/
protected boolean useJmx() {
return false;
}
/**
* Whether or not type converters should be lazy loaded (notice core converters is always loaded)
*
* @return <tt>false</tt> by default.
*/
@Deprecated
protected boolean isLazyLoadingTypeConverter() {
return false;
}
/**
* Override this method to include and override properties
* with the Camel {@link PropertiesComponent}.
*
* @return additional properties to add/override.
*/
protected Properties useOverridePropertiesWithPropertiesComponent() {
return null;
}
@Rule
public CamelTestWatcher getCamelTestWatcher() {
return camelTestWatcher;
}
/**
* Whether to ignore missing locations with the {@link PropertiesComponent}.
* For example when unit testing you may want to ignore locations that are
* not available in the environment you use for testing.
*
* @return <tt>true</tt> to ignore, <tt>false</tt> to not ignore, and <tt>null</tt> to leave as configured
* on the {@link PropertiesComponent}
*/
protected Boolean ignoreMissingLocationWithPropertiesComponent() {
return null;
}
protected void postProcessTest() throws Exception {
context = threadCamelContext.get();
template = threadTemplate.get();
fluentTemplate = threadFluentTemplate.get();
consumer = threadConsumer.get();
camelContextService = threadService.get();
applyCamelPostProcessor();
}
/**
* Applies the {@link DefaultCamelBeanPostProcessor} to this instance.
*
* Derived classes using IoC / DI frameworks may wish to turn this into a NoOp such as for CDI
* we would just use CDI to inject this
*/
protected void applyCamelPostProcessor() throws Exception {
// use the default bean post processor from camel-core
DefaultCamelBeanPostProcessor processor = new DefaultCamelBeanPostProcessor(context);
processor.postProcessBeforeInitialization(this, getClass().getName());
processor.postProcessAfterInitialization(this, getClass().getName());
}
protected void stopCamelContext() throws Exception {
doStopCamelContext(context, camelContextService);
}
private static void doStopCamelContext(CamelContext context, Service camelContextService) throws Exception {
if (camelContextService != null) {
if (camelContextService == threadService.get()) {
threadService.remove();
}
camelContextService.stop();
} else {
if (context != null) {
if (context == threadCamelContext.get()) {
threadCamelContext.remove();
}
context.stop();
}
}
}
private static void doStopTemplates(ConsumerTemplate consumer, ProducerTemplate template, FluentProducerTemplate fluentTemplate) throws Exception {
if (consumer != null) {
if (consumer == threadConsumer.get()) {
threadConsumer.remove();
}
consumer.stop();
}
if (template != null) {
if (template == threadTemplate.get()) {
threadTemplate.remove();
}
template.stop();
}
if (fluentTemplate != null) {
if (fluentTemplate == threadFluentTemplate.get()) {
threadFluentTemplate.remove();
}
fluentTemplate.stop();
}
}
protected void startCamelContext() throws Exception {
if (camelContextService != null) {
camelContextService.start();
} else {
if (context instanceof DefaultCamelContext) {
DefaultCamelContext defaultCamelContext = (DefaultCamelContext)context;
if (!defaultCamelContext.isStarted()) {
defaultCamelContext.start();
}
} else {
context.start();
}
}
}
@SuppressWarnings("deprecation")
protected CamelContext createCamelContext() throws Exception {
CamelContext context = new DefaultCamelContext(createRegistry());
context.setLazyLoadTypeConverters(isLazyLoadingTypeConverter());
return context;
}
protected JndiRegistry createRegistry() throws Exception {
return new JndiRegistry(createJndiContext());
}
protected Context createJndiContext() throws Exception {
Properties properties = new Properties();
// jndi.properties is optional
InputStream in = getClass().getClassLoader().getResourceAsStream("jndi.properties");
if (in != null) {
log.debug("Using jndi.properties from classpath root");
properties.load(in);
} else {
properties.put("java.naming.factory.initial", "org.apache.camel.util.jndi.CamelInitialContextFactory");
}
return new InitialContext(new Hashtable<Object, Object>(properties));
}
/**
* Factory method which derived classes can use to create a {@link RouteBuilder}
* to define the routes for testing
*/
protected RoutesBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
@Override
public void configure() {
// no routes added by default
}
};
}
/**
* Factory method which derived classes can use to create an array of
* {@link org.apache.camel.builder.RouteBuilder}s to define the routes for testing
*
* @see #createRouteBuilder()
*/
protected RoutesBuilder[] createRouteBuilders() throws Exception {
return new RoutesBuilder[] {createRouteBuilder()};
}
/**
* Resolves a mandatory endpoint for the given URI or an exception is thrown
*
* @param uri the Camel <a href="">URI</a> to use to create or resolve an endpoint
* @return the endpoint
*/
protected Endpoint resolveMandatoryEndpoint(String uri) {
return resolveMandatoryEndpoint(context, uri);
}
/**
* Resolves a mandatory endpoint for the given URI and expected type or an exception is thrown
*
* @param uri the Camel <a href="">URI</a> to use to create or resolve an endpoint
* @return the endpoint
*/
protected <T extends Endpoint> T resolveMandatoryEndpoint(String uri, Class<T> endpointType) {
return resolveMandatoryEndpoint(context, uri, endpointType);
}
/**
* Resolves the mandatory Mock endpoint using a URI of the form <code>mock:someName</code>
*
* @param uri the URI which typically starts with "mock:" and has some name
* @return the mandatory mock endpoint or an exception is thrown if it could not be resolved
*/
protected MockEndpoint getMockEndpoint(String uri) {
return getMockEndpoint(uri, true);
}
/**
* Resolves the {@link MockEndpoint} using a URI of the form <code>mock:someName</code>, optionally
* creating it if it does not exist.
*
* @param uri the URI which typically starts with "mock:" and has some name
* @param create whether or not to allow the endpoint to be created if it doesn't exist
* @return the mock endpoint or an {@link NoSuchEndpointException} is thrown if it could not be resolved
* @throws NoSuchEndpointException is the mock endpoint does not exists
*/
protected MockEndpoint getMockEndpoint(String uri, boolean create) throws NoSuchEndpointException {
if (create) {
return resolveMandatoryEndpoint(uri, MockEndpoint.class);
} else {
Endpoint endpoint = context.hasEndpoint(uri);
if (endpoint instanceof MockEndpoint) {
return (MockEndpoint) endpoint;
}
throw new NoSuchEndpointException(String.format("MockEndpoint %s does not exist.", uri));
}
}
/**
* Sends a message to the given endpoint URI with the body value
*
* @param endpointUri the URI of the endpoint to send to
* @param body the body for the message
*/
protected void sendBody(String endpointUri, final Object body) {
template.send(endpointUri, new Processor() {
public void process(Exchange exchange) {
Message in = exchange.getIn();
in.setBody(body);
}
});
}
/**
* Sends a message to the given endpoint URI with the body value and specified headers
*
* @param endpointUri the URI of the endpoint to send to
* @param body the body for the message
* @param headers any headers to set on the message
*/
protected void sendBody(String endpointUri, final Object body, final Map<String, Object> headers) {
template.send(endpointUri, new Processor() {
public void process(Exchange exchange) {
Message in = exchange.getIn();
in.setBody(body);
for (Map.Entry<String, Object> entry : headers.entrySet()) {
in.setHeader(entry.getKey(), entry.getValue());
}
}
});
}
/**
* Sends messages to the given endpoint for each of the specified bodies
*
* @param endpointUri the endpoint URI to send to
* @param bodies the bodies to send, one per message
*/
protected void sendBodies(String endpointUri, Object... bodies) {
for (Object body : bodies) {
sendBody(endpointUri, body);
}
}
/**
* Creates an exchange with the given body
*/
protected Exchange createExchangeWithBody(Object body) {
return createExchangeWithBody(context, body);
}
/**
* Asserts that the given language name and expression evaluates to the
* given value on a specific exchange
*/
protected void assertExpression(Exchange exchange, String languageName, String expressionText, Object expectedValue) {
Language language = assertResolveLanguage(languageName);
Expression expression = language.createExpression(expressionText);
assertNotNull("No Expression could be created for text: " + expressionText + " language: " + language, expression);
assertExpression(expression, exchange, expectedValue);
}
/**
* Asserts that the given language name and predicate expression evaluates
* to the expected value on the message exchange
*/
protected void assertPredicate(String languageName, String expressionText, Exchange exchange, boolean expected) {
Language language = assertResolveLanguage(languageName);
Predicate predicate = language.createPredicate(expressionText);
assertNotNull("No Predicate could be created for text: " + expressionText + " language: " + language, predicate);
assertPredicate(predicate, exchange, expected);
}
/**
* Asserts that the language name can be resolved
*/
protected Language assertResolveLanguage(String languageName) {
Language language = context.resolveLanguage(languageName);
assertNotNull("No language found for name: " + languageName, language);
return language;
}
/**
* Asserts that all the expectations of the Mock endpoints are valid
*/
protected void assertMockEndpointsSatisfied() throws InterruptedException {
MockEndpoint.assertIsSatisfied(context);
}
/**
* Asserts that all the expectations of the Mock endpoints are valid
*/
protected void assertMockEndpointsSatisfied(long timeout, TimeUnit unit) throws InterruptedException {
MockEndpoint.assertIsSatisfied(context, timeout, unit);
}
/**
* Reset all Mock endpoints.
*/
protected void resetMocks() {
MockEndpoint.resetMocks(context);
}
protected void assertValidContext(CamelContext context) {
assertNotNull("No context found!", context);
}
protected <T extends Endpoint> T getMandatoryEndpoint(String uri, Class<T> type) {
T endpoint = context.getEndpoint(uri, type);
assertNotNull("No endpoint found for uri: " + uri, endpoint);
return endpoint;
}
protected Endpoint getMandatoryEndpoint(String uri) {
Endpoint endpoint = context.getEndpoint(uri);
assertNotNull("No endpoint found for uri: " + uri, endpoint);
return endpoint;
}
/**
* Disables the JMX agent. Must be called before the {@link #setUp()} method.
*/
protected void disableJMX() {
System.setProperty(JmxSystemPropertyKeys.DISABLED, "true");
}
/**
* Enables the JMX agent. Must be called before the {@link #setUp()} method.
*/
protected void enableJMX() {
System.setProperty(JmxSystemPropertyKeys.DISABLED, "false");
}
/**
* Single step debugs and Camel invokes this method before entering the given processor
*/
protected void debugBefore(Exchange exchange, Processor processor, ProcessorDefinition<?> definition,
String id, String label) {
}
/**
* Single step debugs and Camel invokes this method after processing the given processor
*/
protected void debugAfter(Exchange exchange, Processor processor, ProcessorDefinition<?> definition,
String id, String label, long timeTaken) {
}
/**
* To easily debug by overriding the <tt>debugBefore</tt> and <tt>debugAfter</tt> methods.
*/
private class DebugBreakpoint extends BreakpointSupport {
@Override
public void beforeProcess(Exchange exchange, Processor processor, ProcessorDefinition<?> definition) {
CamelTestSupport.this.debugBefore(exchange, processor, definition, definition.getId(), definition.getLabel());
}
@Override
public void afterProcess(Exchange exchange, Processor processor, ProcessorDefinition<?> definition, long timeTaken) {
CamelTestSupport.this.debugAfter(exchange, processor, definition, definition.getId(), definition.getLabel(), timeTaken);
}
}
} | apache-2.0 |
aahlenst/spring-boot | spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/method/DeprecatedMethodConfig.java | 1312 | /*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.configurationsample.method;
import org.springframework.boot.configurationsample.ConfigurationProperties;
/**
* Sample for testing deprecated method configuration.
*
* @author Stephane Nicoll
*/
public class DeprecatedMethodConfig {
@ConfigurationProperties(prefix = "foo")
@Deprecated
public Foo foo() {
return new Foo();
}
public static class Foo {
private String name;
private boolean flag;
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public boolean isFlag() {
return this.flag;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
}
}
| apache-2.0 |
nagyistoce/camunda-bpm-platform | engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/task/UserDto.java | 2085 | /* 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.engine.rest.dto.task;
/**
* @author: drobisch
*/
public class UserDto {
private String firstName;
private String lastName;
private String displayName;
private String id;
public UserDto(String id, String firstName, String lastName) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
if (firstName == null && lastName == null) {
this.displayName = id;
}else {
this.displayName = (lastName != null) ? firstName + " " + lastName : firstName;
}
}
public String getFirstName() {
return firstName;
}
public String getId() {
return id;
}
public String getLastName() {
return lastName;
}
public String getDisplayName() {
return displayName;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
UserDto userDto = (UserDto) o;
if (firstName != null ? !firstName.equals(userDto.firstName) : userDto.firstName != null) return false;
if (id != null ? !id.equals(userDto.id) : userDto.id != null) return false;
if (lastName != null ? !lastName.equals(userDto.lastName) : userDto.lastName != null) return false;
return true;
}
@Override
public int hashCode() {
int result = firstName != null ? firstName.hashCode() : 0;
result = 31 * result + (lastName != null ? lastName.hashCode() : 0);
result = 31 * result + (id != null ? id.hashCode() : 0);
return result;
}
}
| apache-2.0 |
coupang/pinpoint | web/src/test/java/com/navercorp/pinpoint/web/applicationmap/histogram/ApplicationTimeHistogramTest.java | 2774 | /*
* Copyright 2014 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.web.applicationmap.histogram;
import com.navercorp.pinpoint.common.trace.ServiceType;
import com.navercorp.pinpoint.web.applicationmap.histogram.ApplicationTimeHistogram;
import com.navercorp.pinpoint.web.applicationmap.histogram.ApplicationTimeHistogramBuilder;
import com.navercorp.pinpoint.web.view.ResponseTimeViewModel;
import com.navercorp.pinpoint.web.vo.Application;
import com.navercorp.pinpoint.web.vo.Range;
import com.navercorp.pinpoint.web.vo.ResponseTime;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.ObjectWriter;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* @author emeroad
*/
public class ApplicationTimeHistogramTest {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
private final ObjectMapper mapper = new ObjectMapper();
@Test
public void testViewModel() throws IOException {
Application app = new Application("test", ServiceType.STAND_ALONE);
ApplicationTimeHistogramBuilder builder = new ApplicationTimeHistogramBuilder(app, new Range(0, 10*6000));
List<ResponseTime> responseHistogramList = createResponseTime(app);
ApplicationTimeHistogram histogram = builder.build(responseHistogramList);
List<ResponseTimeViewModel> viewModel = histogram.createViewModel();
logger.debug("{}", viewModel);
ObjectWriter writer = mapper.writer();
String s = writer.writeValueAsString(viewModel);
logger.debug(s);
}
private List<ResponseTime> createResponseTime(Application app) {
List<ResponseTime> responseTimeList = new ArrayList<ResponseTime>();
ResponseTime one = new ResponseTime(app.getName(), app.getServiceType(), 0);
one.addResponseTime("test", (short) 1000, 1);
responseTimeList.add(one);
ResponseTime two = new ResponseTime(app.getName(), app.getServiceType(), 1000*60);
two .addResponseTime("test", (short) 3000, 1);
responseTimeList.add(two);
return responseTimeList;
}
}
| apache-2.0 |
bhutchinson/rice | rice-middleware/it/kew/src/test/java/org/kuali/rice/kew/xml/DocumentTypeXmlParserTest.java | 33715 | /**
* Copyright 2005-2014 The Kuali Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl2.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kuali.rice.kew.xml;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.junit.BeforeClass;
import org.junit.Test;
import org.kuali.rice.core.api.util.xml.XmlException;
import org.kuali.rice.kew.api.KewApiConstants;
import org.kuali.rice.kew.api.WorkflowDocument;
import org.kuali.rice.kew.api.WorkflowDocumentFactory;
import org.kuali.rice.kew.api.WorkflowRuntimeException;
import org.kuali.rice.kew.api.action.ActionType;
import org.kuali.rice.kew.doctype.ApplicationDocumentStatus;
import org.kuali.rice.kew.doctype.ApplicationDocumentStatusCategory;
import org.kuali.rice.kew.doctype.DocumentTypeAttributeBo;
import org.kuali.rice.kew.doctype.DocumentTypePolicy;
import org.kuali.rice.kew.doctype.bo.DocumentType;
import org.kuali.rice.kew.engine.node.ProcessDefinitionBo;
import org.kuali.rice.kew.engine.node.RouteNode;
import org.kuali.rice.kew.service.KEWServiceLocator;
import org.kuali.rice.kew.test.KEWTestCase;
import org.kuali.rice.krad.exception.GroupNotFoundException;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import static org.junit.Assert.*;
public class DocumentTypeXmlParserTest extends KEWTestCase {
private static String applicationStatusDocumentTypeTemplate;
@BeforeClass
public static void beforeClass() throws Exception {
applicationStatusDocumentTypeTemplate =
IOUtils.toString(DocumentTypeXmlParserTest.class.getResourceAsStream("BadKEWAppDocStatusTemplate.xml"));
}
private boolean validate(String docName) throws Exception {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setValidating(true);
dbf.setNamespaceAware( true );
dbf.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage", XMLConstants.W3C_XML_SCHEMA_NS_URI);
DocumentBuilder db = dbf.newDocumentBuilder();
db.setEntityResolver(new org.kuali.rice.core.impl.impex.xml.ClassLoaderEntityResolver());
db.setErrorHandler(new DefaultHandler() {
@Override
public void error(SAXParseException e) throws SAXException {
this.fatalError(e);
}
@Override
public void fatalError(SAXParseException e) throws SAXException {
super.fatalError(e);
}
});
try {
db.parse(getClass().getResourceAsStream(docName + ".xml"));
return true;
} catch (SAXException se) {
log.error("Error validating " + docName + ".xml", se);
return false;
}
}
private List<DocumentType> testDoc(String docName, Class expectedException) throws Exception {
return testDoc(docName, true, expectedException);
}
private List<DocumentType> testDoc(String docName, boolean valid, Class expectedException) throws Exception {
assertEquals(valid, validate(docName));
DocumentTypeXmlParser parser = new DocumentTypeXmlParser();
try {
List<DocumentType> docTypes = parser.parseDocumentTypes(getClass().getResourceAsStream(docName + ".xml"));
if (expectedException != null) {
fail(docName + " successfully loaded");
}
return docTypes;
} catch (Exception e) {
if (expectedException == null || !(expectedException.isAssignableFrom(e.getClass()))) {
throw e;
} else {
log.error(docName + " exception: " + e);
return new ArrayList();
}
}
}
/**
* This method tests that the new document type with overwrite mode set to true will insert a
* new document type.
*/
@Test public void testLoadOverwriteDocumentType() throws Exception {
testDoc("OverwriteDocumentType", null);
assertNotNull("Document type should exist after ingestion", KEWServiceLocator.getDocumentTypeService().findByName("DocumentTypeXmlParserTestDoc_OverwriteDocumentType"));
}
@Test public void testLoadDocWithVariousActivationTypes() throws Exception {
testDoc("ValidActivationTypes", null);
}
@Test public void testLoadDocWithInvalidActivationType() throws Exception {
testDoc("BadActivationType", false, IllegalArgumentException.class);
}
@Test public void testLoadDocWithValidPolicyNames() throws Exception {
testDoc("ValidPolicyNames", null);
}
@Test public void testLoadDocWithValidRuleSelector() throws Exception {
testDoc("ValidRuleSelector", null);
}
@Test public void testLoadDocWithDuplicatePolicyName() throws Exception {
testDoc("DuplicatePolicyName", XmlException.class);
}
@Test public void testLoadDocWithBadPolicyName() throws Exception {
testDoc("BadPolicyName", false, IllegalArgumentException.class);
}
@Test public void testLoadDocWithBadNextNode() throws Exception {
testDoc("BadNextNode", XmlException.class);
}
@Test public void testLoadDocWithNoDocHandler() throws Exception {
testDoc("NoDocHandler", null);
DocumentType documentType = KEWServiceLocator.getDocumentTypeService().findByName("DocumentTypeXmlParserTestDoc1");
assertTrue("Doc type unresolved doc handler should be empty.", StringUtils.isBlank(documentType.getUnresolvedDocHandlerUrl()));
assertTrue("Doc type doc handler should be empty.", StringUtils.isBlank(documentType.getUnresolvedDocHandlerUrl()));
}
@Test public void testLoadDocWithBadExceptionWG() throws Exception {
testDoc("BadExceptionWorkgroup", false, GroupNotFoundException.class);
}
@Test public void testLoadDocWithBadSuperUserWG() throws Exception {
testDoc("BadSuperUserWorkgroup", false, GroupNotFoundException.class);
}
@Test public void testLoadDocWithBadBlanketApproveWG() throws Exception {
testDoc("BadBlanketApproveWorkgroup", false, GroupNotFoundException.class);
}
@Test public void testLoadDocWithBadRuleTemplate() throws Exception {
testDoc("BadRuleTemplate", XmlException.class);
}
@Test public void testLoadDocWithInvalidParent() throws Exception {
testDoc("InvalidParent", XmlException.class);
}
@Test public void testLoadDocWithOrphanedNodes() throws Exception {
testDoc("OrphanedNodes", XmlException.class);
}
@Test public void testBlanketApprovePolicy() throws Exception {
testDoc("BlanketApprovePolicy", null);
// on BlanketApprovePolicy1 anyone can blanket approve
WorkflowDocument document = WorkflowDocumentFactory.createDocument(getPrincipalIdForName("pzhang"), "BlanketApprovePolicy1");
document.saveDocumentData();
assertTrue(isActionCodeValidForDocument(document, KewApiConstants.ACTION_TAKEN_BLANKET_APPROVE_CD));
document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("ewestfal"), document.getDocumentId());
assertFalse(isActionCodeValidForDocument(document, KewApiConstants.ACTION_TAKEN_BLANKET_APPROVE_CD));
// on BlanketApprovePolicy2 no-one can blanket approve
document = WorkflowDocumentFactory.createDocument(getPrincipalIdForName("pzhang"), "BlanketApprovePolicy2");
document.saveDocumentData();
assertFalse(isActionCodeValidForDocument(document, KewApiConstants.ACTION_TAKEN_BLANKET_APPROVE_CD));
document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("ewestfal"), document.getDocumentId());
assertFalse(isActionCodeValidForDocument(document, KewApiConstants.ACTION_TAKEN_BLANKET_APPROVE_CD));
// on BlanketApprovePolicy3 no-one can blanket approve
document = WorkflowDocumentFactory.createDocument(getPrincipalIdForName("ewestfal"), "BlanketApprovePolicy3");
document.saveDocumentData();
assertFalse(isActionCodeValidForDocument(document, KewApiConstants.ACTION_TAKEN_BLANKET_APPROVE_CD));
document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("ewestfal"), document.getDocumentId());
assertFalse(isActionCodeValidForDocument(document, KewApiConstants.ACTION_TAKEN_BLANKET_APPROVE_CD));
// on BlanketApprovePolicy4 TestWorkgroup can blanket approve
/*document = WorkflowDocumentFactory.createDocument(new NetworkIdVO("ewestfal"), "BlanketApprovePolicy4");
document.saveDocumentData();
assertFalse(isActionCodeValidForDocument(document, KewApiConstants.ACTION_TAKEN_BLANKET_APPROVE_CD));*/
// on Blanket ApprovePolicy 5, BlanketApprovePolicy is not allowed since no elements are defined on any document types in the hierarchy
document = WorkflowDocumentFactory.createDocument(getPrincipalIdForName("pzhang"), "BlanketApprovePolicy5");
document.saveDocumentData();
assertFalse(isActionCodeValidForDocument(document, KewApiConstants.ACTION_TAKEN_BLANKET_APPROVE_CD));
document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("ewestfal"), document.getDocumentId());
assertFalse(isActionCodeValidForDocument(document, KewApiConstants.ACTION_TAKEN_BLANKET_APPROVE_CD));
// on Blanket ApprovePolicy 6, BlanketApprovePolicy is not allowed since no elements are defined on any document types in the hierarchy
document = WorkflowDocumentFactory.createDocument(getPrincipalIdForName("pzhang"), "BlanketApprovePolicy6");
document.saveDocumentData();
assertFalse(isActionCodeValidForDocument(document, KewApiConstants.ACTION_TAKEN_BLANKET_APPROVE_CD));
document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("ewestfal"), document.getDocumentId());
assertFalse(isActionCodeValidForDocument(document, KewApiConstants.ACTION_TAKEN_BLANKET_APPROVE_CD));
// on Blanket ApprovePolicy 7, BlanketApprovePolicy is not allowed since no elements are defined on any document types in the hierarchy
document = WorkflowDocumentFactory.createDocument(getPrincipalIdForName("pzhang"), "BlanketApprovePolicy7");
document.saveDocumentData();
assertTrue(isActionCodeValidForDocument(document, KewApiConstants.ACTION_TAKEN_BLANKET_APPROVE_CD));
document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("ewestfal"), document.getDocumentId());
assertTrue(isActionCodeValidForDocument(document, KewApiConstants.ACTION_TAKEN_BLANKET_APPROVE_CD));
// on BlanketApprovePolicy_Override_NONE, BlanketApprovePolicy is not allowed since no elements are defined on any document types in the hierarchy
document = WorkflowDocumentFactory.createDocument(getPrincipalIdForName("pzhang"), "BlanketApprovePolicy_Override_NONE");
document.saveDocumentData();
assertFalse(isActionCodeValidForDocument(document, KewApiConstants.ACTION_TAKEN_BLANKET_APPROVE_CD));
document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("ewestfal"), document.getDocumentId());
assertFalse(isActionCodeValidForDocument(document, KewApiConstants.ACTION_TAKEN_BLANKET_APPROVE_CD));
// on BlanketApprovePolicy_Override_ANY, BlanketApprovePolicy is not allowed since no elements are defined on any document types in the hierarchy
document = WorkflowDocumentFactory.createDocument(getPrincipalIdForName("pzhang"), "BlanketApprovePolicy_Override_ANY");
document.saveDocumentData();
assertTrue(isActionCodeValidForDocument(document, KewApiConstants.ACTION_TAKEN_BLANKET_APPROVE_CD));
document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("ewestfal"), document.getDocumentId());
assertTrue(isActionCodeValidForDocument(document, KewApiConstants.ACTION_TAKEN_BLANKET_APPROVE_CD));
// on BlanketApprovePolicy_Override_ANY, BlanketApprovePolicy is not allowed since no elements are defined on any document types in the hierarchy
document = WorkflowDocumentFactory.createDocument(getPrincipalIdForName("pzhang"), "BlanketApprovePolicy_NoOverride");
document.saveDocumentData();
assertFalse(isActionCodeValidForDocument(document, KewApiConstants.ACTION_TAKEN_BLANKET_APPROVE_CD));
document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("ewestfal"), document.getDocumentId());
assertTrue(isActionCodeValidForDocument(document, KewApiConstants.ACTION_TAKEN_BLANKET_APPROVE_CD));
}
@Test public void testReportingWorkgroupName() throws Exception {
testDoc("ReportingWorkgroupName", null);
DocumentType documentType1 = KEWServiceLocator.getDocumentTypeService().findByName("ReportingWorkgroupName1");
assertNotNull("Should have a reporting workgroup.", documentType1.getReportingWorkgroup());
assertEquals("Should be WorkflowAdmin reporting workgroup", "WorkflowAdmin", documentType1.getReportingWorkgroup().getName());
DocumentType documentType2 = KEWServiceLocator.getDocumentTypeService().findByName("ReportingWorkgroupName2");
assertNull("Should not have a reporting workgroup.", documentType2.getReportingWorkgroup());
}
@Test public void testCurrentDocumentNotMaxVersionNumber() throws Exception {
String fileNameToIngest = "VersionNumberCheck";
String documentTypeName = "VersionCheckDocument";
testDoc(fileNameToIngest, null);
testDoc(fileNameToIngest, null);
testDoc(fileNameToIngest, null);
DocumentType originalCurrentDocType = KEWServiceLocator.getDocumentTypeService().findByName(documentTypeName);
assertNotNull("Should have found document for doc type '" + documentTypeName + "'",originalCurrentDocType);
assertNotNull("Doc Type should have previous doc type id",originalCurrentDocType.getPreviousVersionId());
assertEquals("Doc Type should be current",Boolean.TRUE,originalCurrentDocType.getCurrentInd());
DocumentType previousDocType1 = KEWServiceLocator.getDocumentTypeService().findById(originalCurrentDocType.getPreviousVersionId());
assertNotNull("Should have found document for doc type '" + documentTypeName + "' and previous version " + originalCurrentDocType.getPreviousVersionId(),previousDocType1);
assertNotNull("Doc Type should have previous doc type id",previousDocType1.getPreviousVersionId());
DocumentType firstDocType = KEWServiceLocator.getDocumentTypeService().findById(previousDocType1.getPreviousVersionId());
assertNotNull("Should have found document for doc type '" + documentTypeName + "' and previous version " + previousDocType1.getPreviousVersionId(),firstDocType);
assertNull("Doc type retrieved should have been first doc type",firstDocType.getPreviousVersionId());
// reset the current document to the previous one to replicate bug conditions
originalCurrentDocType.setCurrentInd(Boolean.FALSE);
KEWServiceLocator.getDocumentTypeService().save(originalCurrentDocType);
firstDocType.setCurrentInd(Boolean.TRUE);
KEWServiceLocator.getDocumentTypeService().save(firstDocType);
DocumentType newCurrentDocType = KEWServiceLocator.getDocumentTypeService().findByName(documentTypeName);
assertNotNull("Should have found document for doc type '" + documentTypeName + "'",newCurrentDocType);
assertEquals("Version of new doc type should match that of first doc type", firstDocType.getVersion(), newCurrentDocType.getVersion());
// ingest the doc type again and verify correct version number
try {
testDoc(fileNameToIngest, null);
} catch (Exception e) {
fail("File should have ingested correctly" + e.getLocalizedMessage());
}
DocumentType currentDocType = KEWServiceLocator.getDocumentTypeService().findByName(documentTypeName);
assertNotNull("Should have found document for doc type '" + documentTypeName + "'",currentDocType);
assertEquals("Doc Type should be current",Boolean.TRUE,currentDocType.getCurrentInd());
assertNotNull("Doc Type should have previous doc type id",currentDocType.getPreviousVersionId());
assertEquals("New current document should have version 1 greater than ", Integer.valueOf(originalCurrentDocType.getVersion().intValue() + 1), currentDocType.getVersion());
previousDocType1 = KEWServiceLocator.getDocumentTypeService().findById(currentDocType.getPreviousVersionId());
assertNotNull("Should have found document for doc type '" + documentTypeName + "' and previous version " + newCurrentDocType.getPreviousVersionId(),previousDocType1);
assertFalse("Doc Type should be current",previousDocType1.getCurrentInd());
assertNull("Doc type retrieved should not have previous doc type",previousDocType1.getPreviousVersionId());
}
@Test public void testLoadDocWithOrderedAttributes() throws Exception {
List documentTypes = testDoc("ValidActivationTypes", null);
assertEquals("Should only be one doc type parsed", 1, documentTypes.size());
DocumentType docType = (DocumentType) documentTypes.get(0);
for (int i = 0; i < docType.getDocumentTypeAttributes().size(); i++) {
DocumentTypeAttributeBo attribute = docType.getDocumentTypeAttributes().get(i);
assertEquals("Invalid Index Number", i+1, attribute.getOrderIndex());
}
DocumentType docTypeFresh = KEWServiceLocator.getDocumentTypeService().findByName("DocumentTypeXmlParserTestDoc_ValidActivationTypes");
assertEquals("Should be 3 doc type attributes", 3, docTypeFresh.getDocumentTypeAttributes().size());
int index = 0;
DocumentTypeAttributeBo attribute = docTypeFresh.getDocumentTypeAttributes().get(index);
assertEquals("Invalid Index Number", index+1, attribute.getOrderIndex());
assertEquals("Invalid attribute name for order value " + index+1, "TestRuleAttribute2", attribute.getRuleAttribute().getName());
index = 1;
attribute = docTypeFresh.getDocumentTypeAttributes().get(index);
assertEquals("Invalid Index Number", index+1, attribute.getOrderIndex());
assertEquals("Invalid attribute name for order value " + index+1, "TestRuleAttribute3", attribute.getRuleAttribute().getName());
index = 2;
attribute = docTypeFresh.getDocumentTypeAttributes().get(index);
assertEquals("Invalid Index Number", index+1, attribute.getOrderIndex());
assertEquals("Invalid attribute name for order value " + index+1, "TestRuleAttribute", attribute.getRuleAttribute().getName());
}
@Test public void testLoadDocWithNoLabel() throws Exception {
List documentTypes = testDoc("DocTypeWithNoLabel", false, null);
assertEquals("Should have parsed 1 document type", 1, documentTypes.size());
DocumentType documentType = (DocumentType)documentTypes.get(0);
assertEquals("Document type has incorrect name", "DocumentTypeXmlParserTestDoc_DocTypeWithNoLabel", documentType.getName());
assertEquals("Document type has incorrect label", KewApiConstants.DEFAULT_DOCUMENT_TYPE_LABEL, documentType.getLabel());
// now test a DocumentType ingestion with no label for a DocumentType that has a previous version
// in this case we use TestDocumentType3 which should have been ingested from DefaultTestData.xml
DocumentType testDocType3 = KEWServiceLocator.getDocumentTypeService().findByName("TestDocumentType3");
assertNotNull("TestDocumentType3 should exist.", testDocType3);
// the current label for TestDocumentType3 should be TestDocumentType
String expectedLabel = "TestDocumentType";
assertEquals("Incorrect label", expectedLabel, testDocType3.getLabel());
// now let's ingest a new version without the label, it should maintain the original label and not
// end up with a value of Undefined
documentTypes = testDoc("DocTypeWithNoLabelPreviousVersion", false, null);
assertEquals("Should have parsed 1 document type", 1, documentTypes.size());
testDocType3 = (DocumentType)documentTypes.get(0);
assertEquals("Document type has incorrect name", "TestDocumentType3", testDocType3.getName());
assertEquals("Document type has incorrect label", expectedLabel, testDocType3.getLabel());
}
@Test public void testLoadOverwriteModeDocumentType() throws Exception {
String docTypeName = "LoadRoutePathOnlyAdjustsDocument";
testDoc("RoutePathAdjustment1", null);
DocumentType docType1 = KEWServiceLocator.getDocumentTypeService().findByName(docTypeName);
assertNotNull("Document type should exist", docType1);
assertEquals("The blanket approve workgroup name is incorrect", "TestWorkgroup", docType1.getBlanketApproveWorkgroup().getName());
assertEquals("The blanket approve workgroup namespace is incorrect", "KR-WKFLW", docType1.getBlanketApproveWorkgroup().getNamespaceCode());
assertEquals("The super user workgroup name is incorrect", "TestWorkgroup", docType1.getSuperUserWorkgroup().getName());
assertEquals("The super user workgroup namespace is incorrect", "KR-WKFLW", docType1.getSuperUserWorkgroup().getNamespaceCode());
List routeNodes = KEWServiceLocator.getRouteNodeService().getFlattenedNodes(docType1, true);
assertEquals("Incorrect document route node count", 1, routeNodes.size());
assertEquals("Expected Route Node Name is incorrect", "First", ((RouteNode)routeNodes.get(0)).getRouteNodeName());
testDoc("RoutePathAdjustment2", null);
DocumentType docType2 = KEWServiceLocator.getDocumentTypeService().findByName(docTypeName);
assertNotNull("Document type should exist", docType1);
assertEquals("The blanket approve workgroup name is incorrect", "WorkflowAdmin", docType2.getBlanketApproveWorkgroup().getName());
assertEquals("The blanket approve workgroup namespace is incorrect", "KR-WKFLW", docType2.getBlanketApproveWorkgroup().getNamespaceCode());
assertEquals("The super user workgroup name is incorrect", "TestWorkgroup", docType2.getSuperUserWorkgroup().getName());
assertEquals("The super user workgroup namespace is incorrect", "KR-WKFLW", docType2.getSuperUserWorkgroup().getNamespaceCode());
routeNodes = KEWServiceLocator.getRouteNodeService().getFlattenedNodes(docType2, true);
assertEquals("Incorrect document route node count", 2, routeNodes.size());
assertEquals("Expected Route Node Name is incorrect", "First", ((RouteNode)routeNodes.get(0)).getRouteNodeName());
assertEquals("Expected Route Node Name is incorrect", "Second", ((RouteNode)routeNodes.get(1)).getRouteNodeName());
}
/**
* Checks if a child document can be processed when it precedes its parent.
*
* @throws Exception
*/
@Test public void testLoadDocWithOneChildPrecedingParent() throws Exception {
List<?> docTypeList;
// Test a case where there is a single child document preceding its parent.
docTypeList = testDoc("ChildParentTestConfig1_Reordered", null);
assertEquals("There should be 5 document types.", 5, docTypeList.size());
}
/**
* Checks if a child routing document can be processed when it precedes its parent.
*
* @throws Exception
*/
@Test public void testRouteDocWithOneChildPrecedingParent() throws Exception {
List<?> docTypeList;
this.loadXmlFile("ChildParentTestConfig1_Reordered.xml");
// Test a case where there is a single router child document preceding its parent.
docTypeList = testDoc("ChildParentTestConfig1_Routing", null);
assertEquals("There should be 5 document types.", 5, docTypeList.size());
}
/**
* Checks if the child-parent resolution works with a larger inheritance tree.
*
* @throws Exception
*/
@Test public void testLoadDocWithLargerChildPrecedenceInheritanceTree() throws Exception {
List<?> docTypeList;
// Test a case where there are multiple inheritance tree layers to resolve.
docTypeList = testDoc("ChildParentTestConfig1_Reordered2", null);
assertEquals("There should be 10 document types.", 10, docTypeList.size());
}
/**
* Checks if the child-parent resolution works with a larger inheritance tree and a mix of standard & routing documents.
*
* @throws Exception
*/
@Test public void testRouteDocWithLargerChildPrecedenceInheritanceTree() throws Exception {
List<?> docTypeList;
this.loadXmlFile("ChildParentTestConfig1_Routing2_Prep.xml");
// Test a case where there are multiple inheritance tree layers to resolve.
docTypeList = testDoc("ChildParentTestConfig1_Routing2", null);
assertEquals("There should be 10 document types.", 10, docTypeList.size());
}
private void tryLoadingBadDocument(String docTypeFileName, String failToFailMessage) {
try {
loadXmlFile(docTypeFileName);
fail(failToFailMessage);
} catch (WorkflowRuntimeException e) {
// Good, that is what we expect
}
}
/**
* Tests a number of forms of invalid application document status XML to ensure that ingestion fails
* @throws Exception
*/
@Test public void testLoadBadDocWithAppDocStatus() throws Exception {
loadDocWithBadAppDocStatus(
" <validApplicationStatuses>\n"
+ " <status>bogus1</status>\n"
+ " <category name=\"bogus1\">\n"
+ " <status>Completed</status>\n"
+ " </category>\n"
+ " </validApplicationStatuses>",
"duplicate category and status name should cause failure to ingest");
loadDocWithBadAppDocStatus(
" <validApplicationStatuses>\n"
+ " <category name=\"bogus1\">\n"
+ " <status>Approved</status>\n"
+ " </category>\n"
+ " <category name=\"bogus1\">\n"
+ " <status>Completed</status>\n"
+ " </category>\n"
+ " </validApplicationStatuses>",
"duplicate category name should cause failure to ingest");
loadDocWithBadAppDocStatus(
" <validApplicationStatuses>\n"
+ " <category name=\"\">\n"
+ " <status>Approved</status>\n"
+ " </category>\n"
+ " </validApplicationStatuses>",
"empty category name should cause failure to ingest");
loadDocWithBadAppDocStatus(
" <validApplicationStatuses>\n"
+ " <category>\n"
+ " <status>Approved</status>\n"
+ " </category>\n"
+ " </validApplicationStatuses>",
"no category name should cause failure to ingest");
loadDocWithBadAppDocStatus(
" <validApplicationStatuses>\n"
+ " <status>bogus1</status>\n"
+ " <category name=\"IN PROGRESS\">\n"
+ " </category>\n"
+ " </validApplicationStatuses>",
"empty category should cause failure to ingest");
loadDocWithBadAppDocStatus(
" <validApplicationStatuses>\n"
+ " <status>bogus1</status>\n"
+ " <status>bogus1</status>\n"
+ " </validApplicationStatuses>",
"duplicate status name should cause failure to ingest");
loadDocWithBadAppDocStatus(
" <validApplicationStatuses>\n"
+ " <status></status>\n"
+ " </validApplicationStatuses>",
"empty status content should cause failure to ingest");
loadDocWithBadAppDocStatus(
" <validApplicationStatuses>\n"
+ " <status/>\n"
+ " </validApplicationStatuses>",
"no status content should cause failure to ingest");
loadDocWithBadAppDocStatus(
" <validApplicationStatuses>\n"
+ " <status/>\n"
+ " </validApplicationStatuses>",
"no status content should cause failure to ingest");
}
/**
* Helper method to test bad validAppStatuses content
* @param validAppStatusesContent xml content for the validAppStatuses section
* @param failureMessage the message to call junit's fail with
*/
private void loadDocWithBadAppDocStatus(String validAppStatusesContent, String failureMessage) {
try {
String docTypeContent = applicationStatusDocumentTypeTemplate.replace("VALIDAPPSTATUSES", validAppStatusesContent);
loadXmlStream(new ByteArrayInputStream(docTypeContent.getBytes()));
fail(failureMessage);
} catch (WorkflowRuntimeException e) {
// good, this is what we want.
}
}
@Test public void testLoadDocWithAppDocStatus() throws Exception {
loadXmlFile("TestKEWAppDocStatus.xml");
DocumentType documentType = KEWServiceLocator.getDocumentTypeService().findByName("TestAppDocStatusDoc2");
// verify DocumentStatusPolicy = "APP"
assertFalse("DocumentStatusPolicy should not be set to KEW, or BOTH", documentType.isKEWStatusInUse());
assertTrue("DocumentStatusPolicy should be set to APP", documentType.isAppDocStatusInUse());
// verify Valid Statuses defined
assertTrue("6 Valid Application Statuses should be defined", documentType.getValidApplicationStatuses().size() == 6);
Iterator<ApplicationDocumentStatus> iter = documentType.getValidApplicationStatuses().iterator();
while (iter.hasNext()){
ApplicationDocumentStatus myStatus = iter.next();
String myStatusName = myStatus.getStatusName();
assertTrue("Valid Status value is incorrect: " + myStatusName,
("Approval In Progress".equalsIgnoreCase(myStatusName) ||
"Submitted".equalsIgnoreCase(myStatusName) ||
"Pending".equalsIgnoreCase(myStatusName) ||
"Completed".equalsIgnoreCase(myStatusName) ||
"Approved".equalsIgnoreCase(myStatusName) ||
"Rejected".equalsIgnoreCase(myStatusName) ));
}
//verify next_doc_status in RouteNode
List procs = documentType.getProcesses();
ProcessDefinitionBo myProc = (ProcessDefinitionBo) procs.get(0);
RouteNode myNode = myProc.getInitialRouteNode();
String nextDocStatus = myNode.getNextDocStatus();
assertTrue("RouteNode nextDocStatus is Invalid", "Approval in Progress".equalsIgnoreCase(nextDocStatus));
// Test that a document type with app doc status categories has the configured structure
DocumentType documentType4 = KEWServiceLocator.getDocumentTypeService().findByName("TestAppDocStatusDoc4");
List<ApplicationDocumentStatusCategory> categories = documentType4.getApplicationStatusCategories();
assertTrue(2 == categories.size());
assertTrue(9 == documentType4.getValidApplicationStatuses().size());
}
@Test public void testLoadDocWithInvalidDocumentStatusPolicy() throws Exception {
testDoc("DocumentStatusPolicyInvalidStringValue", XmlException.class);
}
@Test public void testLoadDocWithBlankDocumentStatusPolicyStringValue() throws Exception {
testDoc("DocumentStatusPolicyMissingStringValue", false, XmlException.class);
}
@Test public void testLoadDocWithDocTypePolicyXMLConfig() throws Exception {
List<DocumentType> docTypes = testDoc("DocumentTypePolicyConfig", null);
assertEquals(1, docTypes.size());
DocumentType docType = docTypes.get(0);
DocumentTypePolicy policy = docType.getRecallNotification();
assertNotNull(policy);
assertNotNull(policy.getPolicyStringValue());
assertEquals("<config>"
+ "<recipients xmlns:r=\"ns:workflow/Rule\" xsi:schemaLocation=\"ns:workflow/Rule resource:Rule\">"
+ "<r:principalName>quickstart</r:principalName>"
+ "<r:user>quickstart</r:user>"
+ "<role name=\"foobar\" namespace=\"KEW\"/>"
+ "</recipients>"
+ "</config>", policy.getPolicyStringValue().replaceAll("\\n*", ""));
}
private boolean isActionCodeValidForDocument(WorkflowDocument document, String actionCode) {
return document.isValidAction(ActionType.fromCode(actionCode));
}
}
| apache-2.0 |
inoshperera/carbon-device-mgt-plugins | components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.v09.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/WebClip.java | 2004 | /*
* Copyright (c) 2016, 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.mdm.services.android.bean;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
/**
* This class represents the information of setting up webclip.
*/
@ApiModel(value = "WebClip", description = "This class represents the information of setting up webclip")
public class WebClip extends AndroidOperation implements Serializable {
@ApiModelProperty(name = "identity", value = "The URL of the application", required = true)
private String identity;
@ApiModelProperty(name = "title", value = "The name of the web application", required = true)
private String title;
@ApiModelProperty(name = "type", value = "The type of the operation. Following are the possible operation"
+ " types: install and uninstall. If the operation type is install, the web clip is added, and "
+ "if the operation type is uninstall, the existing web clip is removed", required = true)
private String type;
public String getIdentity() {
return identity;
}
public void setIdentity(String identity) {
this.identity = identity;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
| apache-2.0 |
antoaravinth/incubator-groovy | src/main/org/codehaus/groovy/runtime/HandleMetaClass.java | 4229 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.codehaus.groovy.runtime;
import groovy.lang.*;
import java.lang.reflect.Method;
public class HandleMetaClass extends DelegatingMetaClass {
private Object object;
private static MetaClass myMetaClass;
private static final Object NONE = new Object();
public HandleMetaClass(MetaClass mc) {
this(mc, null);
}
public HandleMetaClass(MetaClass mc, Object obj) {
super(mc);
if (obj != null) {
if (InvokerHelper.getMetaClass(obj.getClass()) == mc || !(mc instanceof ExpandoMetaClass))
object = obj; // object has default meta class, so we need to replace it on demand
else
object = NONE; // object already has per instance meta class
}
if (myMetaClass == null)
myMetaClass = InvokerHelper.getMetaClass(getClass());
}
public void initialize() {
replaceDelegate();
delegate.initialize();
}
public GroovyObject replaceDelegate() {
if (object == null) {
if (!(delegate instanceof ExpandoMetaClass)) {
delegate = new ExpandoMetaClass(delegate.getTheClass(), true, true);
delegate.initialize();
}
DefaultGroovyMethods.setMetaClass(delegate.getTheClass(), delegate);
}
else {
if (object != NONE) {
final MetaClass metaClass = delegate;
delegate = new ExpandoMetaClass(delegate.getTheClass(), false, true);
if (metaClass instanceof ExpandoMetaClass) {
ExpandoMetaClass emc = (ExpandoMetaClass) metaClass;
for (MetaMethod method : emc.getExpandoMethods())
((ExpandoMetaClass)delegate).registerInstanceMethod(method);
}
delegate.initialize();
MetaClassHelper.doSetMetaClass(object, delegate);
object = NONE;
}
}
return (GroovyObject)delegate;
}
public Object invokeMethod(String name, Object args) {
return replaceDelegate().invokeMethod(name, args);
}
// this method mimics EMC behavior
public Object getProperty(String property) {
if(ExpandoMetaClass.isValidExpandoProperty(property)) {
if(property.equals(ExpandoMetaClass.STATIC_QUALIFIER) ||
property.equals(ExpandoMetaClass.CONSTRUCTOR) ||
myMetaClass.hasProperty(this, property) == null) {
return replaceDelegate().getProperty(property);
}
}
return myMetaClass.getProperty(this, property);
}
public void setProperty(String property, Object newValue) {
replaceDelegate().setProperty(property, newValue);
}
public void addNewInstanceMethod(Method method) {
throw new UnsupportedOperationException();
}
public void addNewStaticMethod(Method method) {
throw new UnsupportedOperationException();
}
public void addMetaMethod(MetaMethod metaMethod) {
throw new UnsupportedOperationException();
}
public void addMetaBeanProperty(MetaBeanProperty metaBeanProperty) {
throw new UnsupportedOperationException();
}
public boolean equals(Object obj) {
return super.equals(obj) || getAdaptee().equals(obj) || (obj instanceof HandleMetaClass && equals(((HandleMetaClass)obj).getAdaptee()));
}
}
| apache-2.0 |
rokn/Count_Words_2015 | testing/openjdk/jdk/src/share/classes/java/awt/MenuBar.java | 15517 | /*
* Copyright (c) 1995, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.Vector;
import java.util.Enumeration;
import java.awt.peer.MenuBarPeer;
import java.awt.event.KeyEvent;
import javax.accessibility.*;
/**
* The <code>MenuBar</code> class encapsulates the platform's
* concept of a menu bar bound to a frame. In order to associate
* the menu bar with a <code>Frame</code> object, call the
* frame's <code>setMenuBar</code> method.
* <p>
* <A NAME="mbexample"></A><!-- target for cross references -->
* This is what a menu bar might look like:
* <p>
* <img src="doc-files/MenuBar-1.gif"
* <alt="Diagram of MenuBar containing 2 menus: Examples and Options.
* Examples menu is expanded showing items: Basic, Simple, Check, and More Examples."
* ALIGN=center HSPACE=10 VSPACE=7>
* <p>
* A menu bar handles keyboard shortcuts for menu items, passing them
* along to its child menus.
* (Keyboard shortcuts, which are optional, provide the user with
* an alternative to the mouse for invoking a menu item and the
* action that is associated with it.)
* Each menu item can maintain an instance of <code>MenuShortcut</code>.
* The <code>MenuBar</code> class defines several methods,
* {@link MenuBar#shortcuts} and
* {@link MenuBar#getShortcutMenuItem}
* that retrieve information about the shortcuts a given
* menu bar is managing.
*
* @author Sami Shaio
* @see java.awt.Frame
* @see java.awt.Frame#setMenuBar(java.awt.MenuBar)
* @see java.awt.Menu
* @see java.awt.MenuItem
* @see java.awt.MenuShortcut
* @since JDK1.0
*/
public class MenuBar extends MenuComponent implements MenuContainer, Accessible {
static {
/* ensure that the necessary native libraries are loaded */
Toolkit.loadLibraries();
if (!GraphicsEnvironment.isHeadless()) {
initIDs();
}
}
/**
* This field represents a vector of the
* actual menus that will be part of the MenuBar.
*
* @serial
* @see #countMenus()
*/
Vector menus = new Vector();
/**
* This menu is a special menu dedicated to
* help. The one thing to note about this menu
* is that on some platforms it appears at the
* right edge of the menubar.
*
* @serial
* @see #getHelpMenu()
* @see #setHelpMenu(Menu)
*/
Menu helpMenu;
private static final String base = "menubar";
private static int nameCounter = 0;
/*
* JDK 1.1 serialVersionUID
*/
private static final long serialVersionUID = -4930327919388951260L;
/**
* Creates a new menu bar.
* @exception HeadlessException if GraphicsEnvironment.isHeadless()
* returns true.
* @see java.awt.GraphicsEnvironment#isHeadless
*/
public MenuBar() throws HeadlessException {
}
/**
* Construct a name for this MenuComponent. Called by getName() when
* the name is null.
*/
String constructComponentName() {
synchronized (MenuBar.class) {
return base + nameCounter++;
}
}
/**
* Creates the menu bar's peer. The peer allows us to change the
* appearance of the menu bar without changing any of the menu bar's
* functionality.
*/
public void addNotify() {
synchronized (getTreeLock()) {
if (peer == null)
peer = Toolkit.getDefaultToolkit().createMenuBar(this);
int nmenus = getMenuCount();
for (int i = 0 ; i < nmenus ; i++) {
getMenu(i).addNotify();
}
}
}
/**
* Removes the menu bar's peer. The peer allows us to change the
* appearance of the menu bar without changing any of the menu bar's
* functionality.
*/
public void removeNotify() {
synchronized (getTreeLock()) {
int nmenus = getMenuCount();
for (int i = 0 ; i < nmenus ; i++) {
getMenu(i).removeNotify();
}
super.removeNotify();
}
}
/**
* Gets the help menu on the menu bar.
* @return the help menu on this menu bar.
*/
public Menu getHelpMenu() {
return helpMenu;
}
/**
* Sets the specified menu to be this menu bar's help menu.
* If this menu bar has an existing help menu, the old help menu is
* removed from the menu bar, and replaced with the specified menu.
* @param m the menu to be set as the help menu
*/
public void setHelpMenu(Menu m) {
synchronized (getTreeLock()) {
if (helpMenu == m) {
return;
}
if (helpMenu != null) {
remove(helpMenu);
}
if (m.parent != this) {
add(m);
}
helpMenu = m;
if (m != null) {
m.isHelpMenu = true;
m.parent = this;
MenuBarPeer peer = (MenuBarPeer)this.peer;
if (peer != null) {
if (m.peer == null) {
m.addNotify();
}
peer.addHelpMenu(m);
}
}
}
}
/**
* Adds the specified menu to the menu bar.
* If the menu has been part of another menu bar,
* removes it from that menu bar.
*
* @param m the menu to be added
* @return the menu added
* @see java.awt.MenuBar#remove(int)
* @see java.awt.MenuBar#remove(java.awt.MenuComponent)
*/
public Menu add(Menu m) {
synchronized (getTreeLock()) {
if (m.parent != null) {
m.parent.remove(m);
}
menus.addElement(m);
m.parent = this;
MenuBarPeer peer = (MenuBarPeer)this.peer;
if (peer != null) {
if (m.peer == null) {
m.addNotify();
}
peer.addMenu(m);
}
return m;
}
}
/**
* Removes the menu located at the specified
* index from this menu bar.
* @param index the position of the menu to be removed.
* @see java.awt.MenuBar#add(java.awt.Menu)
*/
public void remove(int index) {
synchronized (getTreeLock()) {
Menu m = getMenu(index);
menus.removeElementAt(index);
MenuBarPeer peer = (MenuBarPeer)this.peer;
if (peer != null) {
m.removeNotify();
m.parent = null;
peer.delMenu(index);
}
}
}
/**
* Removes the specified menu component from this menu bar.
* @param m the menu component to be removed.
* @see java.awt.MenuBar#add(java.awt.Menu)
*/
public void remove(MenuComponent m) {
synchronized (getTreeLock()) {
int index = menus.indexOf(m);
if (index >= 0) {
remove(index);
}
}
}
/**
* Gets the number of menus on the menu bar.
* @return the number of menus on the menu bar.
* @since JDK1.1
*/
public int getMenuCount() {
return countMenus();
}
/**
* @deprecated As of JDK version 1.1,
* replaced by <code>getMenuCount()</code>.
*/
@Deprecated
public int countMenus() {
return getMenuCountImpl();
}
/*
* This is called by the native code, so client code can't
* be called on the toolkit thread.
*/
final int getMenuCountImpl() {
return menus.size();
}
/**
* Gets the specified menu.
* @param i the index position of the menu to be returned.
* @return the menu at the specified index of this menu bar.
*/
public Menu getMenu(int i) {
return getMenuImpl(i);
}
/*
* This is called by the native code, so client code can't
* be called on the toolkit thread.
*/
final Menu getMenuImpl(int i) {
return (Menu)menus.elementAt(i);
}
/**
* Gets an enumeration of all menu shortcuts this menu bar
* is managing.
* @return an enumeration of menu shortcuts that this
* menu bar is managing.
* @see java.awt.MenuShortcut
* @since JDK1.1
*/
public synchronized Enumeration<MenuShortcut> shortcuts() {
Vector shortcuts = new Vector();
int nmenus = getMenuCount();
for (int i = 0 ; i < nmenus ; i++) {
Enumeration e = getMenu(i).shortcuts();
while (e.hasMoreElements()) {
shortcuts.addElement(e.nextElement());
}
}
return shortcuts.elements();
}
/**
* Gets the instance of <code>MenuItem</code> associated
* with the specified <code>MenuShortcut</code> object,
* or <code>null</code> if none of the menu items being managed
* by this menu bar is associated with the specified menu
* shortcut.
* @param s the specified menu shortcut.
* @see java.awt.MenuItem
* @see java.awt.MenuShortcut
* @since JDK1.1
*/
public MenuItem getShortcutMenuItem(MenuShortcut s) {
int nmenus = getMenuCount();
for (int i = 0 ; i < nmenus ; i++) {
MenuItem mi = getMenu(i).getShortcutMenuItem(s);
if (mi != null) {
return mi;
}
}
return null; // MenuShortcut wasn't found
}
/*
* Post an ACTION_EVENT to the target of the MenuPeer
* associated with the specified keyboard event (on
* keydown). Returns true if there is an associated
* keyboard event.
*/
boolean handleShortcut(KeyEvent e) {
// Is it a key event?
int id = e.getID();
if (id != KeyEvent.KEY_PRESSED && id != KeyEvent.KEY_RELEASED) {
return false;
}
// Is the accelerator modifier key pressed?
int accelKey = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
if ((e.getModifiers() & accelKey) == 0) {
return false;
}
// Pass MenuShortcut on to child menus.
int nmenus = getMenuCount();
for (int i = 0 ; i < nmenus ; i++) {
Menu m = getMenu(i);
if (m.handleShortcut(e)) {
return true;
}
}
return false;
}
/**
* Deletes the specified menu shortcut.
* @param s the menu shortcut to delete.
* @since JDK1.1
*/
public void deleteShortcut(MenuShortcut s) {
int nmenus = getMenuCount();
for (int i = 0 ; i < nmenus ; i++) {
getMenu(i).deleteShortcut(s);
}
}
/* Serialization support. Restore the (transient) parent
* fields of Menubar menus here.
*/
/**
* The MenuBar's serialized data version.
*
* @serial
*/
private int menuBarSerializedDataVersion = 1;
/**
* Writes default serializable fields to stream.
*
* @param s the <code>ObjectOutputStream</code> to write
* @see AWTEventMulticaster#save(ObjectOutputStream, String, EventListener)
* @see #readObject(java.io.ObjectInputStream)
*/
private void writeObject(java.io.ObjectOutputStream s)
throws java.lang.ClassNotFoundException,
java.io.IOException
{
s.defaultWriteObject();
}
/**
* Reads the <code>ObjectInputStream</code>.
* Unrecognized keys or values will be ignored.
*
* @param s the <code>ObjectInputStream</code> to read
* @exception HeadlessException if
* <code>GraphicsEnvironment.isHeadless</code> returns
* <code>true</code>
* @see java.awt.GraphicsEnvironment#isHeadless
* @see #writeObject(java.io.ObjectOutputStream)
*/
private void readObject(ObjectInputStream s)
throws ClassNotFoundException, IOException, HeadlessException
{
// HeadlessException will be thrown from MenuComponent's readObject
s.defaultReadObject();
for (int i = 0; i < menus.size(); i++) {
Menu m = (Menu)menus.elementAt(i);
m.parent = this;
}
}
/**
* Initialize JNI field and method IDs
*/
private static native void initIDs();
/////////////////
// Accessibility support
////////////////
/**
* Gets the AccessibleContext associated with this MenuBar.
* For menu bars, the AccessibleContext takes the form of an
* AccessibleAWTMenuBar.
* A new AccessibleAWTMenuBar instance is created if necessary.
*
* @return an AccessibleAWTMenuBar that serves as the
* AccessibleContext of this MenuBar
* @since 1.3
*/
public AccessibleContext getAccessibleContext() {
if (accessibleContext == null) {
accessibleContext = new AccessibleAWTMenuBar();
}
return accessibleContext;
}
/**
* Defined in MenuComponent. Overridden here.
*/
int getAccessibleChildIndex(MenuComponent child) {
return menus.indexOf(child);
}
/**
* Inner class of MenuBar used to provide default support for
* accessibility. This class is not meant to be used directly by
* application developers, but is instead meant only to be
* subclassed by menu component developers.
* <p>
* This class implements accessibility support for the
* <code>MenuBar</code> class. It provides an implementation of the
* Java Accessibility API appropriate to menu bar user-interface elements.
* @since 1.3
*/
protected class AccessibleAWTMenuBar extends AccessibleAWTMenuComponent
{
/*
* JDK 1.3 serialVersionUID
*/
private static final long serialVersionUID = -8577604491830083815L;
/**
* Get the role of this object.
*
* @return an instance of AccessibleRole describing the role of the
* object
* @since 1.4
*/
public AccessibleRole getAccessibleRole() {
return AccessibleRole.MENU_BAR;
}
} // class AccessibleAWTMenuBar
}
| mit |
raincs13/phd | tests/org/jfree/chart/plot/PieLabelRecordTest.java | 4574 | /* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2013, by Object Refinery Limited and Contributors.
*
* Project Info: http://www.jfree.org/jfreechart/index.html
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
* [Oracle and Java are registered trademarks of Oracle and/or its affiliates.
* Other names may be trademarks of their respective owners.]
*
* -----------------------
* PieLabelRecordTest.java
* -----------------------
* (C) Copyright 2007-2013, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 21-Nov-2007 : Version 1 (DG);
*
*/
package org.jfree.chart.plot;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.jfree.chart.TestUtilities;
import org.jfree.text.TextBox;
import org.junit.Test;
/**
* Some tests for the {@link PieLabelRecord} class.
*/
public class PieLabelRecordTest {
/**
* Confirm that the equals method can distinguish all the required fields.
*/
@Test
public void testEquals() {
PieLabelRecord p1 = new PieLabelRecord("A", 1.0, 2.0, new TextBox("B"),
3.0, 4.0, 5.0);
PieLabelRecord p2 = new PieLabelRecord("A", 1.0, 2.0, new TextBox("B"),
3.0, 4.0, 5.0);
assertTrue(p1.equals(p2));
assertTrue(p2.equals(p1));
p1 = new PieLabelRecord("B", 1.0, 2.0, new TextBox("B"), 3.0, 4.0, 5.0);
assertFalse(p1.equals(p2));
p2 = new PieLabelRecord("B", 1.0, 2.0, new TextBox("B"), 3.0, 4.0, 5.0);
assertTrue(p1.equals(p2));
p1 = new PieLabelRecord("B", 1.1, 2.0, new TextBox("B"), 3.0, 4.0, 5.0);
assertFalse(p1.equals(p2));
p2 = new PieLabelRecord("B", 1.1, 2.0, new TextBox("B"), 3.0, 4.0, 5.0);
assertTrue(p1.equals(p2));
p1 = new PieLabelRecord("B", 1.1, 2.2, new TextBox("B"), 3.0, 4.0, 5.0);
assertFalse(p1.equals(p2));
p2 = new PieLabelRecord("B", 1.1, 2.2, new TextBox("B"), 3.0, 4.0, 5.0);
assertTrue(p1.equals(p2));
p1 = new PieLabelRecord("B", 1.1, 2.2, new TextBox("C"), 3.0, 4.0, 5.0);
assertFalse(p1.equals(p2));
p2 = new PieLabelRecord("B", 1.1, 2.2, new TextBox("C"), 3.0, 4.0, 5.0);
assertTrue(p1.equals(p2));
p1 = new PieLabelRecord("B", 1.1, 2.2, new TextBox("C"), 3.3, 4.0, 5.0);
assertFalse(p1.equals(p2));
p2 = new PieLabelRecord("B", 1.1, 2.2, new TextBox("C"), 3.3, 4.0, 5.0);
assertTrue(p1.equals(p2));
p1 = new PieLabelRecord("B", 1.1, 2.2, new TextBox("C"), 3.3, 4.4, 5.0);
assertFalse(p1.equals(p2));
p2 = new PieLabelRecord("B", 1.1, 2.2, new TextBox("C"), 3.3, 4.4, 5.0);
assertTrue(p1.equals(p2));
p1 = new PieLabelRecord("B", 1.1, 2.2, new TextBox("C"), 3.3, 4.4, 5.5);
assertFalse(p1.equals(p2));
p2 = new PieLabelRecord("B", 1.1, 2.2, new TextBox("C"), 3.3, 4.4, 5.5);
assertTrue(p1.equals(p2));
}
/**
* Confirm that cloning is not implemented.
*/
@Test
public void testCloning() {
PieLabelRecord p1 = new PieLabelRecord("A", 1.0, 2.0, new TextBox("B"),
3.0, 4.0, 5.0);
assertFalse(p1 instanceof Cloneable);
}
/**
* Serialize an instance, restore it, and check for equality.
*/
@Test
public void testSerialization() {
PieLabelRecord p1 = new PieLabelRecord("A", 1.0, 2.0, new TextBox("B"),
3.0, 4.0, 5.0);
PieLabelRecord p2 = (PieLabelRecord) TestUtilities.serialised(p1);
boolean b = p1.equals(p2);
assertTrue(b);
}
}
| lgpl-2.1 |
aakashysharma/opengse | testing/server-side/webapps-src/servlet-tests/web/WEB-INF/java/tests/javax_servlet/UnavailableException/UnavailableException_Constructor2TestServlet.java | 5243 | /*
* $Header: /home/cvs/jakarta-watchdog-4.0/src/server/servlet-tests/WEB-INF/classes/tests/javax_servlet/UnavailableException/UnavailableException_Constructor2TestServlet.java,v 1.2 2002/01/11 22:21:01 rlubke Exp $
* $Revision: 1.2 $
* $Date: 2002/01/11 22:21:01 $
*
* ====================================================================
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2002 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package tests.javax_servlet.UnavailableException;
import javax.servlet.*;
import java.io.IOException;
import java.io.PrintWriter;
public class UnavailableException_Constructor2TestServlet extends GenericServlet {
/*
* UnavailableException(String mesg,int sec)
* constructs an UnavailabaleException object for
* the specified servlet. This constructor reports
* Temporary Unavailability
*/
public void service ( ServletRequest request, ServletResponse response ) throws ServletException, IOException {
/*
* Constructing one and throwing it.
* catching the exception
*/
PrintWriter out = response.getWriter();
String expectedResult1 = "Exceptional";
int expectedResult2 = 20;
UnavailableException ue = new UnavailableException( expectedResult1, expectedResult2 );
try {
throw ue;
} catch ( Exception e ) {
if ( e instanceof UnavailableException ) {
int result2 = ue.getUnavailableSeconds();
String result1 = e.getMessage();
if ( result2 == expectedResult2 && result1.equals( expectedResult1 ) ) {
out.println( "UnavailableException_Constructor2Test test PASSED" );
} else {
if ( !result1.equals( expectedResult1 ) ) {
out.println( "UnavailableException_Constructor2Test test FAILED <BR>" );
out.println( "Message from Exception does not contain 'Exceptional' <BR>" );
}
if ( result2 != expectedResult2 ) {
out.println( "UnavailableException_Constructor2Test test FAILED <BR>" );
out.println( "UnavailableException.getUnavailableSeconds() returned an incorrect result<BR>" );
out.println( " Expected result = " + expectedResult2 + " <BR>" );
out.println( " Actual result = |" + result2 + "| <BR>" );
}
}
} else {
out.println( "UnavailableException_Constructor2Test test FAILED <BR>" );
out.println( "Exception is not an instance of UnavailableException <BR>" );
}
}
}
}
| apache-2.0 |
minmay/spring-boot | spring-boot/src/test/java/org/springframework/boot/web/servlet/AbstractFilterRegistrationBeanTests.java | 8639 | /*
* Copyright 2012-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.web.servlet;
import java.util.Arrays;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import javax.servlet.DispatcherType;
import javax.servlet.Filter;
import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.anyObject;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
/**
* Abstract base for {@link AbstractFilterRegistrationBean} tests.
*
* @author Phillip Webb
*/
public abstract class AbstractFilterRegistrationBeanTests {
private static final EnumSet<DispatcherType> ASYNC_DISPATCHER_TYPES = EnumSet.of(
DispatcherType.FORWARD, DispatcherType.INCLUDE, DispatcherType.REQUEST,
DispatcherType.ASYNC);
private static final EnumSet<DispatcherType> NON_ASYNC_DISPATCHER_TYPES = EnumSet
.of(DispatcherType.FORWARD, DispatcherType.INCLUDE, DispatcherType.REQUEST);
@Rule
public ExpectedException thrown = ExpectedException.none();
@Mock
ServletContext servletContext;
@Mock
FilterRegistration.Dynamic registration;
@Before
public void setupMocks() {
MockitoAnnotations.initMocks(this);
given(this.servletContext.addFilter(anyString(), (Filter) anyObject()))
.willReturn(this.registration);
}
@Test
public void startupWithDefaults() throws Exception {
AbstractFilterRegistrationBean bean = createFilterRegistrationBean();
bean.onStartup(this.servletContext);
verify(this.servletContext).addFilter(eq("mockFilter"), getExpectedFilter());
verify(this.registration).setAsyncSupported(true);
verify(this.registration).addMappingForUrlPatterns(ASYNC_DISPATCHER_TYPES, false,
"/*");
}
@Test
public void startupWithSpecifiedValues() throws Exception {
AbstractFilterRegistrationBean bean = createFilterRegistrationBean();
bean.setName("test");
bean.setAsyncSupported(false);
bean.setInitParameters(Collections.singletonMap("a", "b"));
bean.addInitParameter("c", "d");
bean.setUrlPatterns(new LinkedHashSet<String>(Arrays.asList("/a", "/b")));
bean.addUrlPatterns("/c");
bean.setServletNames(new LinkedHashSet<String>(Arrays.asList("s1", "s2")));
bean.addServletNames("s3");
bean.setServletRegistrationBeans(
Collections.singleton(mockServletRegistration("s4")));
bean.addServletRegistrationBeans(mockServletRegistration("s5"));
bean.setMatchAfter(true);
bean.onStartup(this.servletContext);
verify(this.servletContext).addFilter(eq("test"), getExpectedFilter());
verify(this.registration).setAsyncSupported(false);
Map<String, String> expectedInitParameters = new HashMap<String, String>();
expectedInitParameters.put("a", "b");
expectedInitParameters.put("c", "d");
verify(this.registration).setInitParameters(expectedInitParameters);
verify(this.registration).addMappingForUrlPatterns(NON_ASYNC_DISPATCHER_TYPES,
true, "/a", "/b", "/c");
verify(this.registration).addMappingForServletNames(NON_ASYNC_DISPATCHER_TYPES,
true, "s4", "s5", "s1", "s2", "s3");
}
@Test
public void specificName() throws Exception {
AbstractFilterRegistrationBean bean = createFilterRegistrationBean();
bean.setName("specificName");
bean.onStartup(this.servletContext);
verify(this.servletContext).addFilter(eq("specificName"), getExpectedFilter());
}
@Test
public void deducedName() throws Exception {
AbstractFilterRegistrationBean bean = createFilterRegistrationBean();
bean.onStartup(this.servletContext);
verify(this.servletContext).addFilter(eq("mockFilter"), getExpectedFilter());
}
@Test
public void disable() throws Exception {
AbstractFilterRegistrationBean bean = createFilterRegistrationBean();
bean.setEnabled(false);
bean.onStartup(this.servletContext);
verify(this.servletContext, times(0)).addFilter(eq("mockFilter"),
getExpectedFilter());
}
@Test
public void setServletRegistrationBeanMustNotBeNull() throws Exception {
AbstractFilterRegistrationBean bean = createFilterRegistrationBean();
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("ServletRegistrationBeans must not be null");
bean.setServletRegistrationBeans(null);
}
@Test
public void addServletRegistrationBeanMustNotBeNull() throws Exception {
AbstractFilterRegistrationBean bean = createFilterRegistrationBean();
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("ServletRegistrationBeans must not be null");
bean.addServletRegistrationBeans((ServletRegistrationBean[]) null);
}
@Test
public void setServletRegistrationBeanReplacesValue() throws Exception {
AbstractFilterRegistrationBean bean = createFilterRegistrationBean(
mockServletRegistration("a"));
bean.setServletRegistrationBeans(new LinkedHashSet<ServletRegistrationBean>(
Arrays.asList(mockServletRegistration("b"))));
bean.onStartup(this.servletContext);
verify(this.registration).addMappingForServletNames(ASYNC_DISPATCHER_TYPES, false,
"b");
}
@Test
public void modifyInitParameters() throws Exception {
AbstractFilterRegistrationBean bean = createFilterRegistrationBean();
bean.addInitParameter("a", "b");
bean.getInitParameters().put("a", "c");
bean.onStartup(this.servletContext);
verify(this.registration).setInitParameters(Collections.singletonMap("a", "c"));
}
@Test
public void setUrlPatternMustNotBeNull() throws Exception {
AbstractFilterRegistrationBean bean = createFilterRegistrationBean();
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("UrlPatterns must not be null");
bean.setUrlPatterns(null);
}
@Test
public void addUrlPatternMustNotBeNull() throws Exception {
AbstractFilterRegistrationBean bean = createFilterRegistrationBean();
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("UrlPatterns must not be null");
bean.addUrlPatterns((String[]) null);
}
@Test
public void setServletNameMustNotBeNull() throws Exception {
AbstractFilterRegistrationBean bean = createFilterRegistrationBean();
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("ServletNames must not be null");
bean.setServletNames(null);
}
@Test
public void addServletNameMustNotBeNull() throws Exception {
AbstractFilterRegistrationBean bean = createFilterRegistrationBean();
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("ServletNames must not be null");
bean.addServletNames((String[]) null);
}
@Test
public void withSpecificDispatcherTypes() throws Exception {
AbstractFilterRegistrationBean bean = createFilterRegistrationBean();
bean.setDispatcherTypes(DispatcherType.INCLUDE, DispatcherType.FORWARD);
bean.onStartup(this.servletContext);
verify(this.registration).addMappingForUrlPatterns(
EnumSet.of(DispatcherType.INCLUDE, DispatcherType.FORWARD), false, "/*");
}
@Test
public void withSpecificDispatcherTypesEnumSet() throws Exception {
AbstractFilterRegistrationBean bean = createFilterRegistrationBean();
EnumSet<DispatcherType> types = EnumSet.of(DispatcherType.INCLUDE,
DispatcherType.FORWARD);
bean.setDispatcherTypes(types);
bean.onStartup(this.servletContext);
verify(this.registration).addMappingForUrlPatterns(types, false, "/*");
}
protected abstract Filter getExpectedFilter();
protected abstract AbstractFilterRegistrationBean createFilterRegistrationBean(
ServletRegistrationBean... servletRegistrationBeans);
protected final ServletRegistrationBean mockServletRegistration(String name) {
ServletRegistrationBean bean = new ServletRegistrationBean();
bean.setName(name);
return bean;
}
}
| apache-2.0 |
dennishuo/hadoop | hadoop-mapreduce-project/hadoop-mapreduce-examples/src/test/java/org/apache/hadoop/examples/pi/math/TestModular.java | 10739 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.examples.pi.math;
import java.math.BigInteger;
import java.util.Random;
import org.apache.hadoop.examples.pi.Util.Timer;
import org.junit.Assert;
import org.junit.Test;
public class TestModular{
private static final Random RANDOM = new Random();
private static final BigInteger TWO = BigInteger.valueOf(2);
static final int DIV_VALID_BIT = 32;
static final long DIV_LIMIT = 1L << DIV_VALID_BIT;
// return r/n for n > r > 0
static long div(long sum, long r, long n) {
long q = 0;
int i = DIV_VALID_BIT - 1;
for(r <<= 1; r < n; r <<= 1) i--;
//System.out.printf(" r=%d, n=%d, q=%d\n", r, n, q);
for(; i >= 0 ;) {
r -= n;
q |= (1L << i);
if (r <= 0) break;
for(; r < n; r <<= 1) i--;
//System.out.printf(" r=%d, n=%d, q=%d\n", r, n, q);
}
sum += q;
return sum < DIV_LIMIT? sum: sum - DIV_LIMIT;
}
@Test
public void testDiv() {
for(long n = 2; n < 100; n++)
for(long r = 1; r < n; r++) {
final long a = div(0, r, n);
final long b = (long)((r*1.0/n) * (1L << DIV_VALID_BIT));
final String s = String.format("r=%d, n=%d, a=%X, b=%X", r, n, a, b);
Assert.assertEquals(s, b, a);
}
}
static long[][][] generateRN(int nsize, int rsize) {
final long[][][] rn = new long[nsize][][];
for(int i = 0; i < rn.length; i++) {
rn[i] = new long[rsize + 1][];
long n = RANDOM.nextLong() & 0xFFFFFFFFFFFFFFFL;
if (n <= 1) n = 0xFFFFFFFFFFFFFFFL - n;
rn[i][0] = new long[]{n};
final BigInteger N = BigInteger.valueOf(n);
for(int j = 1; j < rn[i].length; j++) {
long r = RANDOM.nextLong();
if (r < 0) r = -r;
if (r >= n) r %= n;
final BigInteger R = BigInteger.valueOf(r);
rn[i][j] = new long[]{r, R.multiply(R).mod(N).longValue()};
}
}
return rn;
}
static long square_slow(long z, final long n) {
long r = 0;
for(long s = z; z > 0; z >>= 1) {
if ((((int)z) & 1) == 1) {
r += s;
if (r >= n) r -= n;
}
s <<= 1;
if (s >= n) s -= n;
}
return r;
}
//0 <= r < n < max/2
static long square(long r, final long n, long r2p64) {
if (r <= Modular.MAX_SQRT_LONG) {
r *= r;
if (r >= n) r %= n;
} else {
final int HALF = (63 - Long.numberOfLeadingZeros(n)) >> 1;
final int FULL = HALF << 1;
final long ONES = (1 << HALF) - 1;
final long high = r >>> HALF;
final long low = r &= ONES;
r *= r;
if (r >= n) r %= n;
if (high != 0) {
long s = high * high;
if (s >= n) s %= n;
for(int i = 0; i < FULL; i++)
if ((s <<= 1) >= n) s -= n;
if (low == 0)
r = s;
else {
long t = high * low;
if (t >= n) t %= n;
for(int i = -1; i < HALF; i++)
if ((t <<= 1) >= n) t -= n;
r += s;
if (r >= n) r -= n;
r += t;
if (r >= n) r -= n;
}
}
}
return r;
}
static void squareBenchmarks() {
final Timer t = new Timer(false);
t.tick("squareBenchmarks(), MAX_SQRT=" + Modular.MAX_SQRT_LONG);
final long[][][] rn = generateRN(1000, 1000);
t.tick("generateRN");
for(int i = 0; i < rn.length; i++) {
final long n = rn[i][0][0];
for(int j = 1; j < rn[i].length; j++) {
final long r = rn[i][j][0];
final long answer = rn[i][j][1];
final long s = square_slow(r, n);
if (s != answer) {
Assert.assertEquals(
"r=" + r + ", n=" + n + ", answer=" + answer + " but s=" + s,
answer, s);
}
}
}
t.tick("square_slow");
for(int i = 0; i < rn.length; i++) {
final long n = rn[i][0][0];
long r2p64 = (0x4000000000000000L % n) << 1;
if (r2p64 >= n) r2p64 -= n;
for(int j = 1; j < rn[i].length; j++) {
final long r = rn[i][j][0];
final long answer = rn[i][j][1];
final long s = square(r, n, r2p64);
if (s != answer) {
Assert.assertEquals(
"r=" + r + ", n=" + n + ", answer=" + answer + " but s=" + s,
answer, s);
}
}
}
t.tick("square");
for(int i = 0; i < rn.length; i++) {
final long n = rn[i][0][0];
final BigInteger N = BigInteger.valueOf(n);
for(int j = 1; j < rn[i].length; j++) {
final long r = rn[i][j][0];
final long answer = rn[i][j][1];
final BigInteger R = BigInteger.valueOf(r);
final long s = R.multiply(R).mod(N).longValue();
if (s != answer) {
Assert.assertEquals(
"r=" + r + ", n=" + n + ", answer=" + answer + " but s=" + s,
answer, s);
}
}
}
t.tick("R.multiply(R).mod(N)");
for(int i = 0; i < rn.length; i++) {
final long n = rn[i][0][0];
final BigInteger N = BigInteger.valueOf(n);
for(int j = 1; j < rn[i].length; j++) {
final long r = rn[i][j][0];
final long answer = rn[i][j][1];
final BigInteger R = BigInteger.valueOf(r);
final long s = R.modPow(TWO, N).longValue();
if (s != answer) {
Assert.assertEquals(
"r=" + r + ", n=" + n + ", answer=" + answer + " but s=" + s,
answer, s);
}
}
}
t.tick("R.modPow(TWO, N)");
}
static long[][][] generateEN(int nsize, int esize) {
final long[][][] en = new long[nsize][][];
for(int i = 0; i < en.length; i++) {
en[i] = new long[esize + 1][];
long n = (RANDOM.nextLong() & 0xFFFFFFFFFFFFFFFL) | 1L;
if (n == 1) n = 3;
en[i][0] = new long[]{n};
final BigInteger N = BigInteger.valueOf(n);
for(int j = 1; j < en[i].length; j++) {
long e = RANDOM.nextLong();
if (e < 0) e = -e;
final BigInteger E = BigInteger.valueOf(e);
en[i][j] = new long[]{e, TWO.modPow(E, N).longValue()};
}
}
return en;
}
/** Compute $2^e \mod n$ for e > 0, n > 2 */
static long modBigInteger(final long e, final long n) {
long mask = (e & 0xFFFFFFFF00000000L) == 0 ? 0x00000000FFFFFFFFL
: 0xFFFFFFFF00000000L;
mask &= (e & 0xFFFF0000FFFF0000L & mask) == 0 ? 0x0000FFFF0000FFFFL
: 0xFFFF0000FFFF0000L;
mask &= (e & 0xFF00FF00FF00FF00L & mask) == 0 ? 0x00FF00FF00FF00FFL
: 0xFF00FF00FF00FF00L;
mask &= (e & 0xF0F0F0F0F0F0F0F0L & mask) == 0 ? 0x0F0F0F0F0F0F0F0FL
: 0xF0F0F0F0F0F0F0F0L;
mask &= (e & 0xCCCCCCCCCCCCCCCCL & mask) == 0 ? 0x3333333333333333L
: 0xCCCCCCCCCCCCCCCCL;
mask &= (e & 0xAAAAAAAAAAAAAAAAL & mask) == 0 ? 0x5555555555555555L
: 0xAAAAAAAAAAAAAAAAL;
final BigInteger N = BigInteger.valueOf(n);
long r = 2;
for (mask >>= 1; mask > 0; mask >>= 1) {
if (r <= Modular.MAX_SQRT_LONG) {
r *= r;
if (r >= n) r %= n;
} else {
final BigInteger R = BigInteger.valueOf(r);
r = R.multiply(R).mod(N).longValue();
}
if ((e & mask) != 0) {
r <<= 1;
if (r >= n) r -= n;
}
}
return r;
}
static class Montgomery2 extends Montgomery {
/** Compute 2^y mod N for N odd. */
long mod2(final long y) {
long r0 = R - N;
long r1 = r0 << 1;
if (r1 >= N) r1 -= N;
for(long mask = Long.highestOneBit(y); mask > 0; mask >>>= 1) {
if ((mask & y) == 0) {
r1 = product.m(r0, r1);
r0 = product.m(r0, r0);
} else {
r0 = product.m(r0, r1);
r1 = product.m(r1, r1);
}
}
return product.m(r0, 1);
}
}
static void modBenchmarks() {
final Timer t = new Timer(false);
t.tick("modBenchmarks()");
final long[][][] en = generateEN(10000, 10);
t.tick("generateEN");
for(int i = 0; i < en.length; i++) {
final long n = en[i][0][0];
for(int j = 1; j < en[i].length; j++) {
final long e = en[i][j][0];
final long answer = en[i][j][1];
final long s = Modular.mod(e, n);
if (s != answer) {
Assert.assertEquals(
"e=" + e + ", n=" + n + ", answer=" + answer + " but s=" + s,
answer, s);
}
}
}
t.tick("Modular.mod");
final Montgomery2 m2 = new Montgomery2();
for(int i = 0; i < en.length; i++) {
final long n = en[i][0][0];
m2.set(n);
for(int j = 1; j < en[i].length; j++) {
final long e = en[i][j][0];
final long answer = en[i][j][1];
final long s = m2.mod(e);
if (s != answer) {
Assert.assertEquals(
"e=" + e + ", n=" + n + ", answer=" + answer + " but s=" + s,
answer, s);
}
}
}
t.tick("montgomery.mod");
for(int i = 0; i < en.length; i++) {
final long n = en[i][0][0];
m2.set(n);
for(int j = 1; j < en[i].length; j++) {
final long e = en[i][j][0];
final long answer = en[i][j][1];
final long s = m2.mod2(e);
if (s != answer) {
Assert.assertEquals(
"e=" + e + ", n=" + n + ", answer=" + answer + " but s=" + s,
answer, s);
}
}
}
t.tick("montgomery.mod2");
for(int i = 0; i < en.length; i++) {
final long n = en[i][0][0];
final BigInteger N = BigInteger.valueOf(n);
for(int j = 1; j < en[i].length; j++) {
final long e = en[i][j][0];
final long answer = en[i][j][1];
final long s = TWO.modPow(BigInteger.valueOf(e), N).longValue();
if (s != answer) {
Assert.assertEquals(
"e=" + e + ", n=" + n + ", answer=" + answer + " but s=" + s,
answer, s);
}
}
}
t.tick("BigInteger.modPow(e, n)");
}
public static void main(String[] args) {
squareBenchmarks();
modBenchmarks();
}
} | apache-2.0 |
luchuangbin/test1 | src/org/jivesoftware/smack/filter/PacketIDFilter.java | 1467 | /**
* $RCSfile$
* $Revision$
* $Date$
*
* Copyright 2003-2007 Jive Software.
*
* 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.jivesoftware.smack.filter;
import org.jivesoftware.smack.packet.Packet;
/**
* Filters for packets with a particular packet ID.
*
* @author Matt Tucker
*/
public class PacketIDFilter implements PacketFilter {
private String packetID;
/**
* Creates a new packet ID filter using the specified packet ID.
*
* @param packetID the packet ID to filter for.
*/
public PacketIDFilter(String packetID) {
if (packetID == null) {
throw new IllegalArgumentException("Packet ID cannot be null.");
}
this.packetID = packetID;
}
public boolean accept(Packet packet) {
return packetID.equals(packet.getPacketID());
}
public String toString() {
return "PacketIDFilter by id: " + packetID;
}
}
| apache-2.0 |
neonichu/buck | src/com/facebook/buck/util/DefaultPropertyFinder.java | 4861 | /*
* Copyright 2013-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.util;
import com.facebook.buck.io.ProjectFilesystem;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableMap;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;
public class DefaultPropertyFinder implements PropertyFinder {
private static final Path LOCAL_PROPERTIES_PATH = Paths.get("local.properties");
private final ProjectFilesystem projectFilesystem;
private final ImmutableMap<String, String> environment;
public DefaultPropertyFinder(
ProjectFilesystem projectFilesystem,
ImmutableMap<String, String> environment) {
this.projectFilesystem = projectFilesystem;
this.environment = environment;
}
/**
* @param propertyName The name of the property to look for in local.properties.
* @param environmentVariables The name of the environment variables to try.
* @return If present, the value is confirmed to be a directory.
*/
@Override
public Optional<Path> findDirectoryByPropertiesThenEnvironmentVariable(
String propertyName,
String... environmentVariables) {
Optional<Properties> localProperties;
try {
localProperties = Optional.of(projectFilesystem.readPropertiesFile(LOCAL_PROPERTIES_PATH));
} catch (FileNotFoundException e) {
localProperties = Optional.absent();
} catch (IOException e) {
throw new RuntimeException(
String.format("Couldn't read properties file [%s].", LOCAL_PROPERTIES_PATH),
e);
}
return
findDirectoryByPropertiesThenEnvironmentVariable(
localProperties,
new HostFilesystem(),
environment,
propertyName,
environmentVariables);
}
@VisibleForTesting
static Optional<Path> findDirectoryByPropertiesThenEnvironmentVariable(
Optional<Properties> localProperties,
HostFilesystem hostFilesystem,
Map<String, String> systemEnvironment,
String propertyName,
String... environmentVariables) {
// First, try to find a value in local.properties using the specified propertyName.
Path dirPath = null;
if (localProperties.isPresent()) {
String propertyValue = localProperties.get().getProperty(propertyName);
if (propertyValue != null) {
dirPath = Paths.get(propertyValue);
}
}
String dirPathEnvironmentVariable = null;
// If dirPath is not set, try each of the environment variables, in order, to find it.
for (String environmentVariable : environmentVariables) {
if (dirPath == null) {
String environmentVariableValue = systemEnvironment.get(environmentVariable);
if (environmentVariableValue != null) {
dirPath = Paths.get(environmentVariableValue);
dirPathEnvironmentVariable = environmentVariable;
}
} else {
break;
}
}
// If a dirPath was found, verify that it maps to a directory before returning it.
if (dirPath == null) {
return Optional.absent();
} else {
if (!hostFilesystem.isDirectory(dirPath)) {
String message;
if (dirPathEnvironmentVariable != null) {
message = String.format(
"Environment variable %s points to invalid path [%s].",
dirPathEnvironmentVariable,
dirPath);
} else {
message = String.format(
"Properties file %s contains invalid path [%s] for key %s.",
LOCAL_PROPERTIES_PATH,
dirPath,
propertyName);
}
throw new RuntimeException(message);
}
return Optional.of(dirPath);
}
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof DefaultPropertyFinder)) {
return false;
}
DefaultPropertyFinder that = (DefaultPropertyFinder) other;
return Objects.equals(projectFilesystem, that.projectFilesystem);
}
@Override
public int hashCode() {
return Objects.hash(projectFilesystem);
}
}
| apache-2.0 |
njlawton/elasticsearch | core/src/main/java/org/elasticsearch/index/fielddata/IndexFieldData.java | 9784 | /*
* 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.index.fielddata;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReaderContext;
import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.index.ReaderUtil;
import org.apache.lucene.search.DocIdSet;
import org.apache.lucene.search.DocIdSetIterator;
import org.apache.lucene.search.FieldComparatorSource;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.Scorer;
import org.apache.lucene.search.SortField;
import org.apache.lucene.search.Weight;
import org.apache.lucene.search.join.BitSetProducer;
import org.apache.lucene.util.BitDocIdSet;
import org.apache.lucene.util.BitSet;
import org.apache.lucene.util.BytesRef;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.index.IndexComponent;
import org.elasticsearch.index.IndexSettings;
import org.elasticsearch.index.fielddata.IndexFieldData.XFieldComparatorSource.Nested;
import org.elasticsearch.index.mapper.MappedFieldType;
import org.elasticsearch.index.mapper.MapperService;
import org.elasticsearch.indices.breaker.CircuitBreakerService;
import org.elasticsearch.search.MultiValueMode;
import java.io.IOException;
/**
* Thread-safe utility class that allows to get per-segment values via the
* {@link #load(LeafReaderContext)} method.
*/
public interface IndexFieldData<FD extends AtomicFieldData> extends IndexComponent {
class CommonSettings {
public static final String SETTING_MEMORY_STORAGE_HINT = "memory_storage_hint";
public enum MemoryStorageFormat {
ORDINALS, PACKED, PAGED;
public static MemoryStorageFormat fromString(String string) {
for (MemoryStorageFormat e : MemoryStorageFormat.values()) {
if (e.name().equalsIgnoreCase(string)) {
return e;
}
}
return null;
}
}
}
/**
* The field name.
*/
String getFieldName();
/**
* Loads the atomic field data for the reader, possibly cached.
*/
FD load(LeafReaderContext context);
/**
* Loads directly the atomic field data for the reader, ignoring any caching involved.
*/
FD loadDirect(LeafReaderContext context) throws Exception;
/**
* Comparator used for sorting.
*/
XFieldComparatorSource comparatorSource(@Nullable Object missingValue, MultiValueMode sortMode, Nested nested);
/**
* Clears any resources associated with this field data.
*/
void clear();
// we need this extended source we we have custom comparators to reuse our field data
// in this case, we need to reduce type that will be used when search results are reduced
// on another node (we don't have the custom source them...)
abstract class XFieldComparatorSource extends FieldComparatorSource {
/**
* Simple wrapper class around a filter that matches parent documents
* and a filter that matches child documents. For every root document R,
* R will be in the parent filter and its children documents will be the
* documents that are contained in the inner set between the previous
* parent + 1, or 0 if there is no previous parent, and R (excluded).
*/
public static class Nested {
private final BitSetProducer rootFilter;
private final Query innerQuery;
public Nested(BitSetProducer rootFilter, Query innerQuery) {
this.rootFilter = rootFilter;
this.innerQuery = innerQuery;
}
/**
* Get a {@link BitDocIdSet} that matches the root documents.
*/
public BitSet rootDocs(LeafReaderContext ctx) throws IOException {
return rootFilter.getBitSet(ctx);
}
/**
* Get a {@link DocIdSet} that matches the inner documents.
*/
public DocIdSetIterator innerDocs(LeafReaderContext ctx) throws IOException {
final IndexReaderContext topLevelCtx = ReaderUtil.getTopLevelContext(ctx);
IndexSearcher indexSearcher = new IndexSearcher(topLevelCtx);
Weight weight = indexSearcher.createNormalizedWeight(innerQuery, false);
Scorer s = weight.scorer(ctx);
return s == null ? null : s.iterator();
}
}
/** Whether missing values should be sorted first. */
protected final boolean sortMissingFirst(Object missingValue) {
return "_first".equals(missingValue);
}
/** Whether missing values should be sorted last, this is the default. */
protected final boolean sortMissingLast(Object missingValue) {
return missingValue == null || "_last".equals(missingValue);
}
/** Return the missing object value according to the reduced type of the comparator. */
protected final Object missingObject(Object missingValue, boolean reversed) {
if (sortMissingFirst(missingValue) || sortMissingLast(missingValue)) {
final boolean min = sortMissingFirst(missingValue) ^ reversed;
switch (reducedType()) {
case INT:
return min ? Integer.MIN_VALUE : Integer.MAX_VALUE;
case LONG:
return min ? Long.MIN_VALUE : Long.MAX_VALUE;
case FLOAT:
return min ? Float.NEGATIVE_INFINITY : Float.POSITIVE_INFINITY;
case DOUBLE:
return min ? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY;
case STRING:
case STRING_VAL:
return null;
default:
throw new UnsupportedOperationException("Unsupported reduced type: " + reducedType());
}
} else {
switch (reducedType()) {
case INT:
if (missingValue instanceof Number) {
return ((Number) missingValue).intValue();
} else {
return Integer.parseInt(missingValue.toString());
}
case LONG:
if (missingValue instanceof Number) {
return ((Number) missingValue).longValue();
} else {
return Long.parseLong(missingValue.toString());
}
case FLOAT:
if (missingValue instanceof Number) {
return ((Number) missingValue).floatValue();
} else {
return Float.parseFloat(missingValue.toString());
}
case DOUBLE:
if (missingValue instanceof Number) {
return ((Number) missingValue).doubleValue();
} else {
return Double.parseDouble(missingValue.toString());
}
case STRING:
case STRING_VAL:
if (missingValue instanceof BytesRef) {
return (BytesRef) missingValue;
} else if (missingValue instanceof byte[]) {
return new BytesRef((byte[]) missingValue);
} else {
return new BytesRef(missingValue.toString());
}
default:
throw new UnsupportedOperationException("Unsupported reduced type: " + reducedType());
}
}
}
public abstract SortField.Type reducedType();
/**
* Return a missing value that is understandable by {@link SortField#setMissingValue(Object)}.
* Most implementations return null because they already replace the value at the fielddata level.
* However this can't work in case of strings since there is no such thing as a string which
* compares greater than any other string, so in that case we need to return
* {@link SortField#STRING_FIRST} or {@link SortField#STRING_LAST} so that the coordinating node
* knows how to deal with null values.
*/
public Object missingValue(boolean reversed) {
return null;
}
}
interface Builder {
IndexFieldData<?> build(IndexSettings indexSettings, MappedFieldType fieldType, IndexFieldDataCache cache,
CircuitBreakerService breakerService, MapperService mapperService);
}
interface Global<FD extends AtomicFieldData> extends IndexFieldData<FD> {
IndexFieldData<FD> loadGlobal(DirectoryReader indexReader);
IndexFieldData<FD> localGlobalDirect(DirectoryReader indexReader) throws Exception;
}
}
| apache-2.0 |
marktriggs/nyu-sakai-10.4 | web/news-api/api/src/java/org/sakaiproject/news/api/NewsFormatException.java | 1255 | /**********************************************************************************
* $URL$
* $Id$
***********************************************************************************
*
* Copyright (c) 2003, 2004, 2005, 2006, 2008 The Sakai Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ECL-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**********************************************************************************/
package org.sakaiproject.news.api;
/**
* <p>
* NewsFormatException is thrown whenever a news feed cannot be read by the NewsService because a source URL specifies a file that is not in RSS format.
* </p>
*/
public class NewsFormatException extends Exception
{
public NewsFormatException(String message)
{
super(message);
}
}
| apache-2.0 |
rokn/Count_Words_2015 | testing/openjdk2/langtools/src/share/classes/com/sun/tools/doclets/formats/html/markup/DocType.java | 3591 | /*
* Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.doclets.formats.html.markup;
import java.io.IOException;
import java.io.Writer;
import com.sun.tools.doclets.internal.toolkit.Content;
import com.sun.tools.doclets.internal.toolkit.util.*;
/**
* Class for generating document type for HTML pages of javadoc output.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*
* @author Bhavesh Patel
*/
public class DocType extends Content {
private String docType;
public static final DocType TRANSITIONAL =
new DocType("Transitional", "http://www.w3.org/TR/html4/loose.dtd");
public static final DocType FRAMESET =
new DocType("Frameset", "http://www.w3.org/TR/html4/frameset.dtd");
/**
* Constructor to construct a DocType object.
*
* @param type the doctype to be added
*/
private DocType(String type, String dtd) {
docType = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 " + type +
"//EN\" \"" + dtd + "\">" + DocletConstants.NL;
}
/**
* This method is not supported by the class.
*
* @param content content that needs to be added
* @throws DocletAbortException this method will always throw a
* DocletAbortException because it
* is not supported.
*/
public void addContent(Content content) {
throw new DocletAbortException("not supported");
}
/**
* This method is not supported by the class.
*
* @param stringContent string content that needs to be added
* @throws DocletAbortException this method will always throw a
* DocletAbortException because it
* is not supported.
*/
public void addContent(String stringContent) {
throw new DocletAbortException("not supported");
}
/**
* {@inheritDoc}
*/
public boolean isEmpty() {
return (docType.length() == 0);
}
/**
* {@inheritDoc}
*/
@Override
public boolean write(Writer out, boolean atNewline) throws IOException {
out.write(docType);
return true; // guaranteed by constructor
}
}
| mit |
xuzha/aws-sdk-java | aws-java-sdk-sqs/src/main/java/com/amazonaws/services/sqs/model/transform/QueueNameExistsExceptionUnmarshaller.java | 1519 | /*
* Copyright 2010-2015 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.sqs.model.transform;
import org.w3c.dom.Node;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.util.XpathUtils;
import com.amazonaws.transform.StandardErrorUnmarshaller;
import com.amazonaws.services.sqs.model.QueueNameExistsException;
public class QueueNameExistsExceptionUnmarshaller extends StandardErrorUnmarshaller {
public QueueNameExistsExceptionUnmarshaller() {
super(QueueNameExistsException.class);
}
public AmazonServiceException unmarshall(Node node) throws Exception {
// Bail out if this isn't the right error code that this
// marshaller understands.
String errorCode = parseErrorCode(node);
if (errorCode == null || !errorCode.equals("QueueAlreadyExists"))
return null;
QueueNameExistsException e = (QueueNameExistsException)super.unmarshall(node);
return e;
}
}
| apache-2.0 |
mahaliachante/aws-sdk-java | aws-java-sdk-lambda/src/main/java/com/amazonaws/services/lambda/model/FunctionCode.java | 12525 | /*
* Copyright 2010-2015 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.lambda.model;
import java.io.Serializable;
/**
* <p>
* The code for the Lambda function.
* </p>
*/
public class FunctionCode implements Serializable, Cloneable {
/**
* A base64-encoded .zip file containing your deployment package. For
* more information about creating a .zip file, go to <a
* href="http://docs.aws.amazon.com/lambda/latest/dg/intro-permission-model.html#lambda-intro-execution-role.html">Execution
* Permissions</a> in the <i>AWS Lambda Developer Guide</i>.
*/
private java.nio.ByteBuffer zipFile;
/**
* Amazon S3 bucket name where the .zip file containing your deployment
* package is stored. This bucket must reside in the same AWS region
* where you are creating the Lambda function.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>3 - 63<br/>
* <b>Pattern: </b>^[0-9A-Za-z\.\-_]*(?<!\.)$<br/>
*/
private String s3Bucket;
/**
* The Amazon S3 object (the deployment package) key name you want to
* upload.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>1 - 1024<br/>
*/
private String s3Key;
/**
* The Amazon S3 object (the deployment package) version you want to
* upload.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>1 - 1024<br/>
*/
private String s3ObjectVersion;
/**
* A base64-encoded .zip file containing your deployment package. For
* more information about creating a .zip file, go to <a
* href="http://docs.aws.amazon.com/lambda/latest/dg/intro-permission-model.html#lambda-intro-execution-role.html">Execution
* Permissions</a> in the <i>AWS Lambda Developer Guide</i>.
*
* @return A base64-encoded .zip file containing your deployment package. For
* more information about creating a .zip file, go to <a
* href="http://docs.aws.amazon.com/lambda/latest/dg/intro-permission-model.html#lambda-intro-execution-role.html">Execution
* Permissions</a> in the <i>AWS Lambda Developer Guide</i>.
*/
public java.nio.ByteBuffer getZipFile() {
return zipFile;
}
/**
* A base64-encoded .zip file containing your deployment package. For
* more information about creating a .zip file, go to <a
* href="http://docs.aws.amazon.com/lambda/latest/dg/intro-permission-model.html#lambda-intro-execution-role.html">Execution
* Permissions</a> in the <i>AWS Lambda Developer Guide</i>.
*
* @param zipFile A base64-encoded .zip file containing your deployment package. For
* more information about creating a .zip file, go to <a
* href="http://docs.aws.amazon.com/lambda/latest/dg/intro-permission-model.html#lambda-intro-execution-role.html">Execution
* Permissions</a> in the <i>AWS Lambda Developer Guide</i>.
*/
public void setZipFile(java.nio.ByteBuffer zipFile) {
this.zipFile = zipFile;
}
/**
* A base64-encoded .zip file containing your deployment package. For
* more information about creating a .zip file, go to <a
* href="http://docs.aws.amazon.com/lambda/latest/dg/intro-permission-model.html#lambda-intro-execution-role.html">Execution
* Permissions</a> in the <i>AWS Lambda Developer Guide</i>.
* <p>
* Returns a reference to this object so that method calls can be chained together.
*
* @param zipFile A base64-encoded .zip file containing your deployment package. For
* more information about creating a .zip file, go to <a
* href="http://docs.aws.amazon.com/lambda/latest/dg/intro-permission-model.html#lambda-intro-execution-role.html">Execution
* Permissions</a> in the <i>AWS Lambda Developer Guide</i>.
*
* @return A reference to this updated object so that method calls can be chained
* together.
*/
public FunctionCode withZipFile(java.nio.ByteBuffer zipFile) {
this.zipFile = zipFile;
return this;
}
/**
* Amazon S3 bucket name where the .zip file containing your deployment
* package is stored. This bucket must reside in the same AWS region
* where you are creating the Lambda function.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>3 - 63<br/>
* <b>Pattern: </b>^[0-9A-Za-z\.\-_]*(?<!\.)$<br/>
*
* @return Amazon S3 bucket name where the .zip file containing your deployment
* package is stored. This bucket must reside in the same AWS region
* where you are creating the Lambda function.
*/
public String getS3Bucket() {
return s3Bucket;
}
/**
* Amazon S3 bucket name where the .zip file containing your deployment
* package is stored. This bucket must reside in the same AWS region
* where you are creating the Lambda function.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>3 - 63<br/>
* <b>Pattern: </b>^[0-9A-Za-z\.\-_]*(?<!\.)$<br/>
*
* @param s3Bucket Amazon S3 bucket name where the .zip file containing your deployment
* package is stored. This bucket must reside in the same AWS region
* where you are creating the Lambda function.
*/
public void setS3Bucket(String s3Bucket) {
this.s3Bucket = s3Bucket;
}
/**
* Amazon S3 bucket name where the .zip file containing your deployment
* package is stored. This bucket must reside in the same AWS region
* where you are creating the Lambda function.
* <p>
* Returns a reference to this object so that method calls can be chained together.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>3 - 63<br/>
* <b>Pattern: </b>^[0-9A-Za-z\.\-_]*(?<!\.)$<br/>
*
* @param s3Bucket Amazon S3 bucket name where the .zip file containing your deployment
* package is stored. This bucket must reside in the same AWS region
* where you are creating the Lambda function.
*
* @return A reference to this updated object so that method calls can be chained
* together.
*/
public FunctionCode withS3Bucket(String s3Bucket) {
this.s3Bucket = s3Bucket;
return this;
}
/**
* The Amazon S3 object (the deployment package) key name you want to
* upload.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>1 - 1024<br/>
*
* @return The Amazon S3 object (the deployment package) key name you want to
* upload.
*/
public String getS3Key() {
return s3Key;
}
/**
* The Amazon S3 object (the deployment package) key name you want to
* upload.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>1 - 1024<br/>
*
* @param s3Key The Amazon S3 object (the deployment package) key name you want to
* upload.
*/
public void setS3Key(String s3Key) {
this.s3Key = s3Key;
}
/**
* The Amazon S3 object (the deployment package) key name you want to
* upload.
* <p>
* Returns a reference to this object so that method calls can be chained together.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>1 - 1024<br/>
*
* @param s3Key The Amazon S3 object (the deployment package) key name you want to
* upload.
*
* @return A reference to this updated object so that method calls can be chained
* together.
*/
public FunctionCode withS3Key(String s3Key) {
this.s3Key = s3Key;
return this;
}
/**
* The Amazon S3 object (the deployment package) version you want to
* upload.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>1 - 1024<br/>
*
* @return The Amazon S3 object (the deployment package) version you want to
* upload.
*/
public String getS3ObjectVersion() {
return s3ObjectVersion;
}
/**
* The Amazon S3 object (the deployment package) version you want to
* upload.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>1 - 1024<br/>
*
* @param s3ObjectVersion The Amazon S3 object (the deployment package) version you want to
* upload.
*/
public void setS3ObjectVersion(String s3ObjectVersion) {
this.s3ObjectVersion = s3ObjectVersion;
}
/**
* The Amazon S3 object (the deployment package) version you want to
* upload.
* <p>
* Returns a reference to this object so that method calls can be chained together.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>1 - 1024<br/>
*
* @param s3ObjectVersion The Amazon S3 object (the deployment package) version you want to
* upload.
*
* @return A reference to this updated object so that method calls can be chained
* together.
*/
public FunctionCode withS3ObjectVersion(String s3ObjectVersion) {
this.s3ObjectVersion = s3ObjectVersion;
return this;
}
/**
* Returns a string representation of this object; useful for testing and
* debugging.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getZipFile() != null) sb.append("ZipFile: " + getZipFile() + ",");
if (getS3Bucket() != null) sb.append("S3Bucket: " + getS3Bucket() + ",");
if (getS3Key() != null) sb.append("S3Key: " + getS3Key() + ",");
if (getS3ObjectVersion() != null) sb.append("S3ObjectVersion: " + getS3ObjectVersion() );
sb.append("}");
return sb.toString();
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getZipFile() == null) ? 0 : getZipFile().hashCode());
hashCode = prime * hashCode + ((getS3Bucket() == null) ? 0 : getS3Bucket().hashCode());
hashCode = prime * hashCode + ((getS3Key() == null) ? 0 : getS3Key().hashCode());
hashCode = prime * hashCode + ((getS3ObjectVersion() == null) ? 0 : getS3ObjectVersion().hashCode());
return hashCode;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (obj instanceof FunctionCode == false) return false;
FunctionCode other = (FunctionCode)obj;
if (other.getZipFile() == null ^ this.getZipFile() == null) return false;
if (other.getZipFile() != null && other.getZipFile().equals(this.getZipFile()) == false) return false;
if (other.getS3Bucket() == null ^ this.getS3Bucket() == null) return false;
if (other.getS3Bucket() != null && other.getS3Bucket().equals(this.getS3Bucket()) == false) return false;
if (other.getS3Key() == null ^ this.getS3Key() == null) return false;
if (other.getS3Key() != null && other.getS3Key().equals(this.getS3Key()) == false) return false;
if (other.getS3ObjectVersion() == null ^ this.getS3ObjectVersion() == null) return false;
if (other.getS3ObjectVersion() != null && other.getS3ObjectVersion().equals(this.getS3ObjectVersion()) == false) return false;
return true;
}
@Override
public FunctionCode clone() {
try {
return (FunctionCode) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException(
"Got a CloneNotSupportedException from Object.clone() "
+ "even though we're Cloneable!",
e);
}
}
}
| apache-2.0 |
asedunov/intellij-community | python/pluginJava/com/jetbrains/python/psi/impl/PyJavaPackageType.java | 3919 | /*
* 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.psi.impl;
import com.intellij.codeInsight.lookup.LookupElementBuilder;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.psi.JavaPsiFacade;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiPackage;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.ProjectScope;
import com.intellij.util.ArrayUtil;
import com.intellij.util.ProcessingContext;
import com.jetbrains.python.psi.AccessDirection;
import com.jetbrains.python.psi.PyExpression;
import com.jetbrains.python.psi.resolve.PyResolveContext;
import com.jetbrains.python.psi.resolve.RatedResolveResult;
import com.jetbrains.python.psi.types.PyType;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
/**
* @author yole
*/
public class PyJavaPackageType implements PyType {
private final PsiPackage myPackage;
@Nullable private final Module myModule;
public PyJavaPackageType(PsiPackage aPackage, @Nullable Module module) {
myPackage = aPackage;
myModule = module;
}
@Override
public List<? extends RatedResolveResult> resolveMember(@NotNull String name,
@Nullable PyExpression location,
@NotNull AccessDirection direction,
@NotNull PyResolveContext resolveContext) {
Project project = myPackage.getProject();
JavaPsiFacade facade = JavaPsiFacade.getInstance(project);
String childName = myPackage.getQualifiedName() + "." + name;
GlobalSearchScope scope = getScope(project);
ResolveResultList result = new ResolveResultList();
final PsiClass[] classes = facade.findClasses(childName, scope);
for (PsiClass aClass : classes) {
result.poke(aClass, RatedResolveResult.RATE_NORMAL);
}
final PsiPackage psiPackage = facade.findPackage(childName);
if (psiPackage != null) {
result.poke(psiPackage, RatedResolveResult.RATE_NORMAL);
}
return result;
}
private GlobalSearchScope getScope(Project project) {
return myModule != null ? myModule.getModuleWithDependenciesAndLibrariesScope(false) : ProjectScope.getAllScope(project);
}
@Override
public Object[] getCompletionVariants(String completionPrefix, PsiElement location, ProcessingContext context) {
List<Object> variants = new ArrayList<>();
final GlobalSearchScope scope = getScope(location.getProject());
final PsiClass[] classes = myPackage.getClasses(scope);
for (PsiClass psiClass : classes) {
variants.add(LookupElementBuilder.create(psiClass).withIcon(psiClass.getIcon(0)));
}
final PsiPackage[] subPackages = myPackage.getSubPackages(scope);
for (PsiPackage subPackage : subPackages) {
variants.add(LookupElementBuilder.create(subPackage).withIcon(subPackage.getIcon(0)));
}
return ArrayUtil.toObjectArray(variants);
}
@Override
public String getName() {
return myPackage.getQualifiedName();
}
@Override
public boolean isBuiltin() {
return false;
}
@Override
public void assertValid(String message) {
}
}
| apache-2.0 |
nadeembhati/interview | src/main/java/com/interview/tree/PrintTwoBSTInSortedForm.java | 2775 | package com.interview.tree;
import java.util.Deque;
import java.util.LinkedList;
/**
* http://www.geeksforgeeks.org/merge-two-bsts-with-limited-extra-space/
* Test cases
* Both tree are null
* One of the tree is null
* All elements of one tree occur before other tree
* All elements of one tree occur after other tree
* Elements are mixed
* All same elements
*/
public class PrintTwoBSTInSortedForm {
public void print(Node root1, Node root2){
Deque<Node> s1 = new LinkedList<Node>();
Deque<Node> s2 = new LinkedList<Node>();
while(true){
if(root1 != null){
s1.addFirst(root1);
root1 = root1.left;
continue;
}
if(root2 != null){
s2.addFirst(root2);
root2 = root2.left;
continue;
}
if(!s1.isEmpty()){
root1 = s1.peekFirst();
}
if(!s2.isEmpty()){
root2 = s2.peekFirst();
}
if(root1 != null && root2 != null){
if(root1.data <= root2.data){
System.out.println(root1.data);
root1 = s1.pollFirst();
root1 = root1.right;
root2 = null;
}else{
System.out.println(root2.data);
root2 = s2.pollFirst();
root2 = root2.right;
root1 = null;
}
}
else if(root1 != null){
System.out.println(root1.data);
root1 = s1.pollFirst();
root1 = root1.right;
}else if(root2 != null){
System.out.println(root2.data);
root2 = s2.pollFirst();
root2 = root2.right;
}
if(root1 == null && root2 == null && s1.isEmpty() && s2.isEmpty()){
break;
}
}
}
public static void main(String args[]){
PrintTwoBSTInSortedForm ptb = new PrintTwoBSTInSortedForm();
BinaryTree bt = new BinaryTree();
Node head = null;
head = bt.addNode(10, head);
head = bt.addNode(15, head);
head = bt.addNode(5, head);
head = bt.addNode(7, head);
head = bt.addNode(19, head);
head = bt.addNode(20, head);
head = bt.addNode(-1, head);
Node head1 = null;
head1 = bt.addNode(-4, head1);
head1 = bt.addNode(-3, head1);
head1 = bt.addNode(6, head1);
head1 = bt.addNode(11, head1);
head1 = bt.addNode(22, head1);
head1 = bt.addNode(26, head1);
ptb.print(head, head1);
}
}
| apache-2.0 |
hackbuteer59/sakai | reset-pass/reset-pass/src/java/org/sakaiproject/tool/resetpass/FormHandler.java | 7272 | package org.sakaiproject.tool.resetpass;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sakaiproject.accountvalidator.logic.ValidationLogic;
import org.sakaiproject.accountvalidator.model.ValidationAccount;
import org.sakaiproject.authz.api.SecurityAdvisor;
import org.sakaiproject.authz.api.SecurityService;
import org.sakaiproject.component.api.ServerConfigurationService;
import org.sakaiproject.email.api.EmailService;
import org.sakaiproject.event.api.EventTrackingService;
import org.sakaiproject.user.api.UserDirectoryService;
import org.sakaiproject.user.api.UserEdit;
import uk.org.ponder.messageutil.MessageLocator;
public class FormHandler {
private static java.lang.String SECURE_UPDATE_USER_ANY = org.sakaiproject.user.api.UserDirectoryService.SECURE_UPDATE_USER_ANY;
private MessageLocator messageLocator;
public void setMessageLocator(MessageLocator messageLocator) {
this.messageLocator = messageLocator;
}
private UserDirectoryService userDirectoryService;
public void setUserDirectoryService(UserDirectoryService ds){
this.userDirectoryService = ds;
}
private ServerConfigurationService serverConfigurationService;
public void setServerConfigurationService(ServerConfigurationService s) {
this.serverConfigurationService = s;
}
private EmailService emailService;
public void setEmailService(EmailService e) {
this.emailService = e;
}
private RetUser userBean;
public void setUserBean(RetUser u){
this.userBean = u;
}
private EventTrackingService eventService;
public void setEventService(EventTrackingService etc) {
eventService=etc;
}
private SecurityService securityService;
public void setSecurityService(SecurityService ss) {
securityService = ss;
}
private ValidationLogic validationLogic;
public void setValidationLogic(ValidationLogic validationLogic) {
this.validationLogic = validationLogic;
}
private static Log m_log = LogFactory.getLog(FormHandler.class);
public String processAction() {
//siteManage.validateNewUsers = false use the classic method:
boolean validatingAccounts = serverConfigurationService.getBoolean("siteManage.validateNewUsers", true);
if (! validatingAccounts) {
return resetPassClassic();
}
//otherwise lets we need some info on the user.
//is the user validated?
String userId = userBean.getUser().getId().trim();
// SAK-26189 record event in similar way to resetPassClassic()
eventService.post(eventService.newEvent("user.resetpass", userBean.getUser().getReference() , true));
if (!validationLogic.isAccountValidated(userId)) {
m_log.debug("account is not validated");
//its possible that the user has an outstanding Validation
ValidationAccount va = validationLogic.getVaLidationAcountByUserId(userId);
if (va == null) {
//we need to validate the account.
m_log.debug("This is a legacy user to validate!");
validationLogic.createValidationAccount(userBean.getUser().getId(), ValidationAccount.ACCOUNT_STATUS_PASSWORD_RESET);
} else {
m_log.debug("resending validation");
validationLogic.resendValidation(va.getValidationToken());
}
return "Success";
} else {
//there may be a pending VA that needs to be verified
ValidationAccount va = validationLogic.getVaLidationAcountByUserId(userId);
if (va == null ) {
//the account is validated we need to send a password reset
m_log.info("no account found!");
validationLogic.createValidationAccount(userId, ValidationAccount.ACCOUNT_STATUS_PASSWORD_RESET);
} else if (va.getValidationReceived() == null) {
m_log.debug("no response on validation!");
validationLogic.resendValidation(va.getValidationToken());
} else {
m_log.debug("creating a new validation for password reset");
validationLogic.createValidationAccount(userId, ValidationAccount.ACCOUNT_STATUS_PASSWORD_RESET);
}
return "Success";
}
}
/**
* The classic method that mails a new password
* template is constructed from strings in resource bundle
* @return
*/
private String resetPassClassic() {
m_log.info("getting password for " + userBean.getEmail());
String from = serverConfigurationService.getString("setup.request", null);
if (from == null)
{
m_log.warn(this + " - no 'setup.request' in configuration");
from = "postmaster@".concat(serverConfigurationService.getServerName());
}
//now we need to reset the password
SecurityAdvisor sa = new SecurityAdvisor() {
public SecurityAdvice isAllowed(String userId, String function, String reference) {
if (SECURE_UPDATE_USER_ANY.equals(function)) {
return SecurityAdvice.ALLOWED;
}
return SecurityAdvice.PASS;
}
};
try {
// Need: SECURE_UPDATE_USER_ANY
securityService.pushAdvisor(sa);
UserEdit userE = userDirectoryService.editUser(userBean.getUser().getId().trim());
String pass = getRandPass();
userE.setPassword(pass);
userDirectoryService.commitEdit(userE);
//securityService.popAdvisor(sa);
String productionSiteName = serverConfigurationService.getString("reset-pass.productionSiteName", "");
if(productionSiteName == null || "".equals(productionSiteName))
productionSiteName = serverConfigurationService.getString("ui.service", "");
StringBuffer buff = new StringBuffer();
buff.setLength(0);
buff.append(messageLocator.getMessage("mailBodyPre",userE.getDisplayName()) + "\n\n");
buff.append(messageLocator.getMessage("mailBody1",new Object[]{productionSiteName, serverConfigurationService.getPortalUrl()})+ "\n\n");
buff.append(messageLocator.getMessage("mailBody2",new Object[]{userE.getEid()})+ "\n");
buff.append(messageLocator.getMessage("mailBody3",new Object[]{pass})+ "\n\n");
if (serverConfigurationService.getString("support.email", null) != null )
buff.append(messageLocator.getMessage("mailBody4",new Object[]{serverConfigurationService.getString("support.email")}) + "\n\n");
m_log.debug(messageLocator.getMessage("mailBody1",new Object[]{productionSiteName}));
buff.append(messageLocator.getMessage("mailBodySalut")+"\n");
buff.append(messageLocator.getMessage("mailBodySalut1",productionSiteName));
String body = buff.toString();
List<String> headers = new ArrayList<String>();
headers.add("Precedence: bulk");
emailService.send(from,userBean.getUser().getEmail(),messageLocator.getMessage("mailSubject", new Object[]{productionSiteName}),body,
userBean.getUser().getEmail(), null, headers);
m_log.info("New password emailed to: " + userE.getEid() + " (" + userE.getId() + ")");
eventService.post(eventService.newEvent("user.resetpass", userE.getReference() , true));
}
catch (Exception e) {
e.printStackTrace();
return null;
}
finally {
securityService.popAdvisor(sa);
}
return "Success";
}
//borrowed from siteaction
private String getRandPass() {
// set password to a random positive number
Random generator = new Random(System.currentTimeMillis());
Integer num = Integer.valueOf(generator.nextInt(Integer.MAX_VALUE));
if (num.intValue() < 0) num = Integer.valueOf(num.intValue() *-1);
return num.toString();
}
}
| apache-2.0 |
shaotuanchen/sunflower_exp | tools/source/gcc-4.2.4/libjava/classpath/gnu/java/beans/IntrospectionIncubator.java | 14186 | /* gnu.java.beans.IntrospectionIncubator
Copyright (C) 1998, 2004 Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package gnu.java.beans;
import gnu.java.lang.ArrayHelper;
import gnu.java.lang.ClassHelper;
import java.beans.BeanInfo;
import java.beans.EventSetDescriptor;
import java.beans.IndexedPropertyDescriptor;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.MethodDescriptor;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Array;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
/**
** IntrospectionIncubator takes in a bunch of Methods, and
** Introspects only those Methods you give it.<br/>
**
** See {@link addMethod(Method)} for details which rules apply to
** the methods.
**
** @author John Keiser
** @author Robert Schuster
** @see gnu.java.beans.ExplicitBeanInfo
** @see java.beans.BeanInfo
**/
public class IntrospectionIncubator {
Hashtable propertyMethods = new Hashtable();
Hashtable listenerMethods = new Hashtable();
Vector otherMethods = new Vector();
Class propertyStopClass;
Class eventStopClass;
Class methodStopClass;
public IntrospectionIncubator() {
}
/** Examines the given method and files it in a suitable collection.
* It files the method as a property method if it finds:
* <ul>
* <li>boolean "is" getter</li>
* <li>"get" style getter</li>
* <li>single argument setter</li>
* <li>indiced setter and getter</li>
* </ul>
* It files the method as a listener method if all of these rules apply:
* <ul>
* <li>the method name starts with "add" or "remove"</li>
* <li>there is only a single argument</li>
* <li>the argument type is a subclass of <code>java.util.EventListener</code></li>
* </ul>
* All public methods are filed as such.
*
* @param method The method instance to examine.
*/
public void addMethod(Method method) {
if(Modifier.isPublic(method.getModifiers())) {
String name = ClassHelper.getTruncatedName(method.getName());
Class retType = method.getReturnType();
Class[] params = method.getParameterTypes();
boolean isVoid = retType.equals(java.lang.Void.TYPE);
Class methodClass = method.getDeclaringClass();
/* Accepts the method for examination if no stop class is given or the method is declared in a subclass of the stop class.
* The rules for this are described in {@link java.beans.Introspector.getBeanInfo(Class, Class)}.
* This block finds out whether the method is a suitable getter or setter method (or read/write method).
*/
if(isReachable(propertyStopClass, methodClass)) {
/* At this point a method may regarded as a property's read or write method if its name
* starts with "is", "get" or "set". However, if a method is static it cannot be part
* of a property.
*/
if(Modifier.isStatic(method.getModifiers())) {
// files method as other because it is static
otherMethods.addElement(method);
} else if(name.startsWith("is")
&& retType.equals(java.lang.Boolean.TYPE)
&& params.length == 0) {
// files method as boolean "is" style getter
addToPropertyHash(name,method,IS);
} else if(name.startsWith("get") && !isVoid) {
if(params.length == 0) {
// files as legal non-argument getter
addToPropertyHash(name,method,GET);
} else if(params.length == 1 && params[0].equals(java.lang.Integer.TYPE)) {
// files as legal indiced getter
addToPropertyHash(name,method,GET_I);
} else {
// files as other because the method's signature is not Bean-like
otherMethods.addElement(method);
}
} else if(name.startsWith("set") && isVoid) {
if(params.length == 1) {
// files as legal single-argument setter method
addToPropertyHash(name,method,SET);
} else if(params.length == 2 && params[0].equals(java.lang.Integer.TYPE)) {
// files as legal indiced setter method
addToPropertyHash(name,method,SET_I);
} else {
// files as other because the method's signature is not Bean-like
otherMethods.addElement(method);
}
}
}
if(isReachable(eventStopClass, methodClass)) {
if(name.startsWith("add")
&& isVoid
&& params.length == 1
&& java.util.EventListener.class.isAssignableFrom(params[0])) {
addToListenerHash(name,method,ADD);
} else if(name.startsWith("remove")
&& isVoid
&& params.length == 1
&& java.util.EventListener.class.isAssignableFrom(params[0])) {
addToListenerHash(name,method,REMOVE);
}
}
if(isReachable(methodStopClass, methodClass)) {
// files as reachable public method
otherMethods.addElement(method);
}
}
}
public void addMethods(Method[] m) {
for(int i=0;i<m.length;i++) {
addMethod(m[i]);
}
}
public void setPropertyStopClass(Class c) {
propertyStopClass = c;
}
public void setEventStopClass(Class c) {
eventStopClass = c;
}
public void setMethodStopClass(Class c) {
methodStopClass = c;
}
public BeanInfoEmbryo getBeanInfoEmbryo() throws IntrospectionException {
BeanInfoEmbryo b = new BeanInfoEmbryo();
findXXX(b,IS);
findXXXInt(b,GET_I);
findXXXInt(b,SET_I);
findXXX(b,GET);
findXXX(b,SET);
findAddRemovePairs(b);
for(int i=0;i<otherMethods.size();i++) {
MethodDescriptor newMethod = new MethodDescriptor((Method)otherMethods.elementAt(i));
if(!b.hasMethod(newMethod)) {
b.addMethod(new MethodDescriptor((Method)otherMethods.elementAt(i)));
}
}
return b;
}
public BeanInfo getBeanInfo() throws IntrospectionException {
return getBeanInfoEmbryo().getBeanInfo();
}
void findAddRemovePairs(BeanInfoEmbryo b) throws IntrospectionException {
Enumeration listenerEnum = listenerMethods.keys();
while(listenerEnum.hasMoreElements()) {
DoubleKey k = (DoubleKey)listenerEnum.nextElement();
Method[] m = (Method[])listenerMethods.get(k);
if(m[ADD] != null && m[REMOVE] != null) {
EventSetDescriptor e = new EventSetDescriptor(Introspector.decapitalize(k.getName()),
k.getType(), k.getType().getMethods(),
m[ADD],m[REMOVE]);
e.setUnicast(ArrayHelper.contains(m[ADD].getExceptionTypes(),java.util.TooManyListenersException.class));
if(!b.hasEvent(e)) {
b.addEvent(e);
}
}
}
}
void findXXX(BeanInfoEmbryo b, int funcType) throws IntrospectionException {
Enumeration keys = propertyMethods.keys();
while(keys.hasMoreElements()) {
DoubleKey k = (DoubleKey)keys.nextElement();
Method[] m = (Method[])propertyMethods.get(k);
if(m[funcType] != null) {
PropertyDescriptor p = new PropertyDescriptor(Introspector.decapitalize(k.getName()),
m[IS] != null ? m[IS] : m[GET],
m[SET]);
if(m[SET] != null) {
p.setConstrained(ArrayHelper.contains(m[SET].getExceptionTypes(),java.beans.PropertyVetoException.class));
}
if(!b.hasProperty(p)) {
b.addProperty(p);
}
}
}
}
void findXXXInt(BeanInfoEmbryo b, int funcType) throws IntrospectionException {
Enumeration keys = propertyMethods.keys();
while(keys.hasMoreElements()) {
DoubleKey k = (DoubleKey)keys.nextElement();
Method[] m = (Method[])propertyMethods.get(k);
if(m[funcType] != null) {
boolean constrained;
if(m[SET_I] != null) {
constrained = ArrayHelper.contains(m[SET_I].getExceptionTypes(),java.beans.PropertyVetoException.class);
} else {
constrained = false;
}
/** Find out if there is an array type get or set **/
Class arrayType = Array.newInstance(k.getType(),0).getClass();
DoubleKey findSetArray = new DoubleKey(arrayType,k.getName());
Method[] m2 = (Method[])propertyMethods.get(findSetArray);
IndexedPropertyDescriptor p;
if(m2 == null) {
p = new IndexedPropertyDescriptor(Introspector.decapitalize(k.getName()),
null,null,
m[GET_I],m[SET_I]);
} else {
if(constrained && m2[SET] != null) {
constrained = ArrayHelper.contains(m2[SET].getExceptionTypes(),java.beans.PropertyVetoException.class);
}
p = new IndexedPropertyDescriptor(Introspector.decapitalize(k.getName()),
m2[GET],m2[SET],
m[GET_I],m[SET_I]);
}
p.setConstrained(constrained);
if(!b.hasProperty(p)) {
b.addProperty(p);
}
}
}
}
static final int IS=0;
static final int GET_I=1;
static final int SET_I=2;
static final int GET=3;
static final int SET=4;
static final int ADD=0;
static final int REMOVE=1;
void addToPropertyHash(String name, Method method, int funcType) {
String newName;
Class type;
switch(funcType) {
case IS:
type = java.lang.Boolean.TYPE;
newName = name.substring(2);
break;
case GET_I:
type = method.getReturnType();
newName = name.substring(3);
break;
case SET_I:
type = method.getParameterTypes()[1];
newName = name.substring(3);
break;
case GET:
type = method.getReturnType();
newName = name.substring(3);
break;
case SET:
type = method.getParameterTypes()[0];
newName = name.substring(3);
break;
default:
return;
}
newName = capitalize(newName);
if (newName.length() == 0)
return;
DoubleKey k = new DoubleKey(type,newName);
Method[] methods = (Method[])propertyMethods.get(k);
if(methods == null) {
methods = new Method[5];
propertyMethods.put(k,methods);
}
methods[funcType] = method;
}
void addToListenerHash(String name, Method method, int funcType) {
String newName;
Class type;
switch(funcType) {
case ADD:
type = method.getParameterTypes()[0];
newName = name.substring(3,name.length()-8);
break;
case REMOVE:
type = method.getParameterTypes()[0];
newName = name.substring(6,name.length()-8);
break;
default:
return;
}
newName = capitalize(newName);
if (newName.length() == 0)
return;
DoubleKey k = new DoubleKey(type,newName);
Method[] methods = (Method[])listenerMethods.get(k);
if(methods == null) {
methods = new Method[2];
listenerMethods.put(k,methods);
}
methods[funcType] = method;
}
/* Determines whether <code>stopClass</code> is <code>null</code>
* or <code>declaringClass<code> is a true subclass of <code>stopClass</code>.
* This expression is useful to detect whether a method should be introspected or not.
* The rules for this are described in {@link java.beans.Introspector.getBeanInfo(Class, Class)}.
*/
static boolean isReachable(Class stopClass, Class declaringClass) {
return stopClass == null || (stopClass.isAssignableFrom(declaringClass) && !stopClass.equals(declaringClass));
}
/** Transforms a property name into a part of a method name.
* E.g. "value" becomes "Value" which can then concatenated with
* "set", "get" or "is" to form a valid method name.
*
* Implementation notes:
* If "" is the argument, it is returned without changes.
* If <code>null</code> is the argument, <code>null</code> is returned.
*
* @param name Name of a property.
* @return Part of a method name of a property.
*/
static String capitalize(String name) {
try {
if(Character.isUpperCase(name.charAt(0))) {
return name;
} else {
char[] c = name.toCharArray();
c[0] = Character.toLowerCase(c[0]);
return new String(c);
}
} catch(StringIndexOutOfBoundsException E) {
return name;
} catch(NullPointerException E) {
return null;
}
}
}
/** This class is a hashmap key that consists of a <code>Class</code> and a
* <code>String</code> element.
*
* It is used for XXX: find out what this is used for
*
* @author John Keiser
* @author Robert Schuster
*/
class DoubleKey {
Class type;
String name;
DoubleKey(Class type, String name) {
this.type = type;
this.name = name;
}
Class getType() {
return type;
}
String getName() {
return name;
}
public boolean equals(Object o) {
if(o instanceof DoubleKey) {
DoubleKey d = (DoubleKey)o;
return d.type.equals(type) && d.name.equals(name);
} else {
return false;
}
}
public int hashCode() {
return type.hashCode() ^ name.hashCode();
}
}
| bsd-3-clause |
millmanorama/autopsy | thirdparty/jdiff/v-custom/src/jdiff/ClassAPI.java | 2675 | package jdiff;
import java.io.*;
import java.util.*;
/**
* Class to represent a class, analogous to ClassDoc in the
* Javadoc doclet API.
*
* The method used for Collection comparison (compareTo) must make its
* comparison based upon everything that is known about this class.
*
* See the file LICENSE.txt for copyright details.
* @author Matthew Doar, mdoar@pobox.com
*/
class ClassAPI implements Comparable {
/** Name of the class, not fully qualified. */
public String name_;
/** Set if this class is an interface. */
public boolean isInterface_;
/** Set if this class is abstract. */
boolean isAbstract_ = false;
/** Modifiers for this class. */
public Modifiers modifiers_;
/** Name of the parent class, or null if there is no parent. */
public String extends_; // Can only extend zero or one class or interface
/** Interfaces implemented by this class. */
public List implements_; // String[]
/** Constructors in this class. */
public List ctors_; // ConstructorAPI[]
/** Methods in this class. */
public List methods_; // MethodAPI[]
/** Fields in this class. */
public List fields_; //FieldAPI[]
/** The doc block, default is null. */
public String doc_ = null;
/** Constructor. */
public ClassAPI(String name, String parent, boolean isInterface,
boolean isAbstract, Modifiers modifiers) {
name_ = name;
extends_ = parent;
isInterface_ = isInterface;
isAbstract_ = isAbstract;
modifiers_ = modifiers;
implements_ = new ArrayList(); // String[]
ctors_ = new ArrayList(); // ConstructorAPI[]
methods_ = new ArrayList(); // MethodAPI[]
fields_ = new ArrayList(); // FieldAPI[]
}
/** Compare two ClassAPI objects by all the known information. */
public int compareTo(Object o) {
ClassAPI oClassAPI = (ClassAPI)o;
int comp = name_.compareTo(oClassAPI.name_);
if (comp != 0)
return comp;
if (isInterface_ != oClassAPI.isInterface_)
return -1;
if (isAbstract_ != oClassAPI.isAbstract_)
return -1;
comp = modifiers_.compareTo(oClassAPI.modifiers_);
if (comp != 0)
return comp;
if (APIComparator.docChanged(doc_, oClassAPI.doc_))
return -1;
return 0;
}
/**
* Tests two methods for equality using just the class name,
* used by indexOf().
*/
public boolean equals(Object o) {
if (name_.compareTo(((ClassAPI)o).name_) == 0)
return true;
return false;
}
}
| apache-2.0 |
asedunov/intellij-community | plugins/InspectionGadgets/test/com/siyeh/igfixes/migration/for_can_be_foreach/ForThisClass.java | 819 | /*
* 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.
*/
// "Replace with 'foreach'" "true"
import java.util.*;
public class Test extends ArrayList<String> {
public void print() {
fo<caret>r (int i = 0; i < size(); i++) {
System.out.println(get(i));
}
}
} | apache-2.0 |
shakamunyi/beam | sdks/java/io/mongodb/src/test/java/org/apache/beam/sdk/io/mongodb/package-info.java | 907 | /*
* 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.
*/
/**
* Transforms for reading and writing from MongoDB.
*/
package org.apache.beam.sdk.io.mongodb;
| apache-2.0 |
bloomberg/presto | presto-main/src/test/java/com/facebook/presto/sql/planner/assertions/MatchResult.java | 2032 | /*
* 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.sql.planner.assertions;
import com.facebook.presto.sql.tree.SymbolReference;
import static java.util.Objects.requireNonNull;
public class MatchResult
{
public static final MatchResult NO_MATCH = new MatchResult(false, new SymbolAliases());
private final boolean matches;
private final SymbolAliases newAliases;
public static MatchResult match()
{
return new MatchResult(true, new SymbolAliases());
}
public static MatchResult match(String alias, SymbolReference symbolReference)
{
SymbolAliases newAliases = SymbolAliases.builder()
.put(alias, symbolReference)
.build();
return new MatchResult(true, newAliases);
}
public static MatchResult match(SymbolAliases newAliases)
{
return new MatchResult(true, newAliases);
}
public MatchResult(boolean matches)
{
this(matches, new SymbolAliases());
}
private MatchResult(boolean matches, SymbolAliases newAliases)
{
this.matches = matches;
this.newAliases = requireNonNull(newAliases, "newAliases is null");
}
public boolean isMatch()
{
return matches;
}
public SymbolAliases getAliases()
{
return newAliases;
}
@Override
public String toString()
{
if (matches) {
return "MATCH";
}
else {
return "NO MATCH";
}
}
}
| apache-2.0 |
WilliamNouet/nifi | nifi-framework-api/src/main/java/org/apache/nifi/authorization/UserGroupProviderInitializationContext.java | 1287 | /*
* 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.nifi.authorization;
/**
* Initialization content for UserGroupProviders.
*/
public interface UserGroupProviderInitializationContext {
/**
* The identifier of the UserGroupProvider.
*
* @return The identifier
*/
String getIdentifier();
/**
* The lookup for accessing other configured UserGroupProviders.
*
* @return The UserGroupProvider lookup
*/
UserGroupProviderLookup getUserGroupProviderLookup();
}
| apache-2.0 |
GlenRSmith/elasticsearch | x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/aggregate/StatsEnclosed.java | 357 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
package org.elasticsearch.xpack.sql.expression.function.aggregate;
public interface StatsEnclosed {
}
| apache-2.0 |
rogerchina/maven | maven-model/src/test/java/org/apache/maven/model/ReportSetTest.java | 1485 | package org.apache.maven.model;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import junit.framework.TestCase;
/**
* Tests {@code ReportSet}.
*
* @author Benjamin Bentmann
*/
public class ReportSetTest
extends TestCase
{
public void testHashCodeNullSafe()
{
new ReportSet().hashCode();
}
public void testEqualsNullSafe()
{
assertFalse( new ReportSet().equals( null ) );
new ReportSet().equals( new ReportSet() );
}
public void testEqualsIdentity()
{
ReportSet thing = new ReportSet();
assertTrue( thing.equals( thing ) );
}
public void testToStringNullSafe()
{
assertNotNull( new ReportSet().toString() );
}
}
| apache-2.0 |
rokn/Count_Words_2015 | testing/openjdk2/jdk/src/share/classes/com/sun/jmx/mbeanserver/ClassLoaderRepositorySupport.java | 12238 | /*
* Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.jmx.mbeanserver;
import static com.sun.jmx.defaults.JmxProperties.MBEANSERVER_LOGGER;
import java.security.Permission;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import javax.management.MBeanPermission;
import javax.management.ObjectName;
import javax.management.loading.PrivateClassLoader;
import sun.reflect.misc.ReflectUtil;
/**
* This class keeps the list of Class Loaders registered in the MBean Server.
* It provides the necessary methods to load classes using the
* registered Class Loaders.
*
* @since 1.5
*/
final class ClassLoaderRepositorySupport
implements ModifiableClassLoaderRepository {
/* We associate an optional ObjectName with each entry so that
we can remove the correct entry when unregistering an MBean
that is a ClassLoader. The same object could be registered
under two different names (even though this is not recommended)
so if we did not do this we could disturb the defined
semantics for the order of ClassLoaders in the repository. */
private static class LoaderEntry {
ObjectName name; // can be null
ClassLoader loader;
LoaderEntry(ObjectName name, ClassLoader loader) {
this.name = name;
this.loader = loader;
}
}
private static final LoaderEntry[] EMPTY_LOADER_ARRAY = new LoaderEntry[0];
/**
* List of class loaders
* Only read-only actions should be performed on this object.
*
* We do O(n) operations on this array, e.g. when removing
* a ClassLoader. The assumption is that the number of elements
* is small, probably less than ten, and that the vast majority
* of operations are searches (loadClass) which are by definition
* linear.
*/
private LoaderEntry[] loaders = EMPTY_LOADER_ARRAY;
/**
* Same behavior as add(Object o) in {@link java.util.List}.
* Replace the loader list with a new one in which the new
* loader has been added.
**/
private synchronized boolean add(ObjectName name, ClassLoader cl) {
List<LoaderEntry> l =
new ArrayList<LoaderEntry>(Arrays.asList(loaders));
l.add(new LoaderEntry(name, cl));
loaders = l.toArray(EMPTY_LOADER_ARRAY);
return true;
}
/**
* Same behavior as remove(Object o) in {@link java.util.List}.
* Replace the loader list with a new one in which the old loader
* has been removed.
*
* The ObjectName may be null, in which case the entry to
* be removed must also have a null ObjectName and the ClassLoader
* values must match. If the ObjectName is not null, then
* the first entry with a matching ObjectName is removed,
* regardless of whether ClassLoader values match. (In fact,
* the ClassLoader parameter will usually be null in this case.)
**/
private synchronized boolean remove(ObjectName name, ClassLoader cl) {
final int size = loaders.length;
for (int i = 0; i < size; i++) {
LoaderEntry entry = loaders[i];
boolean match =
(name == null) ?
cl == entry.loader :
name.equals(entry.name);
if (match) {
LoaderEntry[] newloaders = new LoaderEntry[size - 1];
System.arraycopy(loaders, 0, newloaders, 0, i);
System.arraycopy(loaders, i + 1, newloaders, i,
size - 1 - i);
loaders = newloaders;
return true;
}
}
return false;
}
/**
* List of valid search
*/
private final Map<String,List<ClassLoader>> search =
new Hashtable<String,List<ClassLoader>>(10);
/**
* List of named class loaders.
*/
private final Map<ObjectName,ClassLoader> loadersWithNames =
new Hashtable<ObjectName,ClassLoader>(10);
// from javax.management.loading.DefaultLoaderRepository
public final Class<?> loadClass(String className)
throws ClassNotFoundException {
return loadClass(loaders, className, null, null);
}
// from javax.management.loading.DefaultLoaderRepository
public final Class<?> loadClassWithout(ClassLoader without, String className)
throws ClassNotFoundException {
if (MBEANSERVER_LOGGER.isLoggable(Level.FINER)) {
MBEANSERVER_LOGGER.logp(Level.FINER,
ClassLoaderRepositorySupport.class.getName(),
"loadClassWithout", className + " without " + without);
}
// without is null => just behave as loadClass
//
if (without == null)
return loadClass(loaders, className, null, null);
// We must try to load the class without the given loader.
//
startValidSearch(without, className);
try {
return loadClass(loaders, className, without, null);
} finally {
stopValidSearch(without, className);
}
}
public final Class<?> loadClassBefore(ClassLoader stop, String className)
throws ClassNotFoundException {
if (MBEANSERVER_LOGGER.isLoggable(Level.FINER)) {
MBEANSERVER_LOGGER.logp(Level.FINER,
ClassLoaderRepositorySupport.class.getName(),
"loadClassBefore", className + " before " + stop);
}
if (stop == null)
return loadClass(loaders, className, null, null);
startValidSearch(stop, className);
try {
return loadClass(loaders, className, null, stop);
} finally {
stopValidSearch(stop, className);
}
}
private Class<?> loadClass(final LoaderEntry list[],
final String className,
final ClassLoader without,
final ClassLoader stop)
throws ClassNotFoundException {
ReflectUtil.checkPackageAccess(className);
final int size = list.length;
for(int i=0; i<size; i++) {
try {
final ClassLoader cl = list[i].loader;
if (cl == null) // bootstrap class loader
return Class.forName(className, false, null);
if (cl == without)
continue;
if (cl == stop)
break;
if (MBEANSERVER_LOGGER.isLoggable(Level.FINER)) {
MBEANSERVER_LOGGER.logp(Level.FINER,
ClassLoaderRepositorySupport.class.getName(),
"loadClass", "Trying loader = " + cl);
}
/* We used to have a special case for "instanceof
MLet" here, where we invoked the method
loadClass(className, null) to prevent infinite
recursion. But the rule whereby the MLet only
consults loaders that precede it in the CLR (via
loadClassBefore) means that the recursion can't
happen, and the test here caused some legitimate
classloading to fail. For example, if you have
dependencies C->D->E with loaders {E D C} in the
CLR in that order, you would expect to be able to
load C. The problem is that while resolving D, CLR
delegation is disabled, so it can't find E. */
return Class.forName(className, false, cl);
} catch (ClassNotFoundException e) {
// OK: continue with next class
}
}
throw new ClassNotFoundException(className);
}
private synchronized void startValidSearch(ClassLoader aloader,
String className)
throws ClassNotFoundException {
// Check if we have such a current search
//
List<ClassLoader> excluded = search.get(className);
if ((excluded!= null) && (excluded.contains(aloader))) {
if (MBEANSERVER_LOGGER.isLoggable(Level.FINER)) {
MBEANSERVER_LOGGER.logp(Level.FINER,
ClassLoaderRepositorySupport.class.getName(),
"startValidSearch", "Already requested loader = " +
aloader + " class = " + className);
}
throw new ClassNotFoundException(className);
}
// Add an entry
//
if (excluded == null) {
excluded = new ArrayList<ClassLoader>(1);
search.put(className, excluded);
}
excluded.add(aloader);
if (MBEANSERVER_LOGGER.isLoggable(Level.FINER)) {
MBEANSERVER_LOGGER.logp(Level.FINER,
ClassLoaderRepositorySupport.class.getName(),
"startValidSearch",
"loader = " + aloader + " class = " + className);
}
}
private synchronized void stopValidSearch(ClassLoader aloader,
String className) {
// Retrieve the search.
//
List<ClassLoader> excluded = search.get(className);
if (excluded != null) {
excluded.remove(aloader);
if (MBEANSERVER_LOGGER.isLoggable(Level.FINER)) {
MBEANSERVER_LOGGER.logp(Level.FINER,
ClassLoaderRepositorySupport.class.getName(),
"stopValidSearch",
"loader = " + aloader + " class = " + className);
}
}
}
public final void addClassLoader(ClassLoader loader) {
add(null, loader);
}
public final void removeClassLoader(ClassLoader loader) {
remove(null, loader);
}
public final synchronized void addClassLoader(ObjectName name,
ClassLoader loader) {
loadersWithNames.put(name, loader);
if (!(loader instanceof PrivateClassLoader))
add(name, loader);
}
public final synchronized void removeClassLoader(ObjectName name) {
ClassLoader loader = loadersWithNames.remove(name);
if (!(loader instanceof PrivateClassLoader))
remove(name, loader);
}
public final ClassLoader getClassLoader(ObjectName name) {
ClassLoader instance = loadersWithNames.get(name);
if (instance != null) {
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
Permission perm =
new MBeanPermission(instance.getClass().getName(),
null,
name,
"getClassLoader");
sm.checkPermission(perm);
}
}
return instance;
}
}
| mit |
supunmalinga/carbon-commons | components/reporting/org.wso2.carbon.reporting.template.core/src/main/java/org/wso2/carbon/reporting/template/core/handler/database/DataSourceHandler.java | 8884 | /**
* Copyright (c) 2009, WSO2 Inc. (http://www.wso2.org) 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.wso2.carbon.reporting.template.core.handler.database;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.reporting.api.ReportingException;
import org.wso2.carbon.reporting.template.core.client.DatasourceClient;
import org.wso2.carbon.reporting.template.core.factory.ClientFactory;
import org.wso2.carbon.reporting.template.core.util.chart.ChartReportDTO;
import org.wso2.carbon.reporting.template.core.util.chart.DataDTO;
import org.wso2.carbon.reporting.template.core.util.chart.SeriesDTO;
import org.wso2.carbon.reporting.template.core.util.table.ColumnDTO;
import org.wso2.carbon.reporting.template.core.util.table.TableReportDTO;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class DataSourceHandler {
private static Log log = LogFactory.getLog(DataSourceHandler.class);
public Map[] createMapDataSource(TableReportDTO tableReport) throws ReportingException {
String dsName = tableReport.getDsName();
ColumnDTO[] columns = tableReport.getColumns();
String[] fields = getTableFields(columns);
//assuming the report is dedicated to one
String tableName = columns[0].getColumnFamilyName();
String query = getQueryString(tableName, fields);
DatasourceClient client = ClientFactory.getDSClient();
try {
Connection connection= client.getConnection(dsName);
ResultSet resultSet =client.queryDatasource(query, connection);
Map[] mapData = getMapReportTableData(resultSet, fields);
connection.close();
return mapData;
} catch (SQLException e) {
log.error("SQL error while querying the data for "+ dsName+" to fill report" + tableReport.getReportName(), e);
throw new ReportingException("SQL error while querying the data for "+ dsName+" to fill report" + tableReport.getReportName(), e);
}
}
private String[] getTableFields(ColumnDTO[] columns){
String[] columnNames = new String[columns.length];
int id = 0;
for(ColumnDTO column: columns){
columnNames[id] = column.getColumnName();
id++;
}
return columnNames;
}
private String[] getChartFields(SeriesDTO[] series){
ArrayList<String> fieldNames = new ArrayList<String>();
for(SeriesDTO aSeries: series){
DataDTO xData = aSeries.getXdata();
if(!fieldNames.contains(xData.getDsColumnName())){
fieldNames.add(xData.getDsColumnName());
}
DataDTO yData = aSeries.getYdata();
if(!fieldNames.contains(yData.getDsColumnName())){
fieldNames.add(yData.getDsColumnName());
}
}
String[] fieldArray = new String[fieldNames.size()];
return fieldNames.toArray(fieldArray);
}
private String getQueryString(String tableName, String[] columnNames){
String query = "SELECT ";
for(String columNames : columnNames){
query = query +columNames+" , ";
}
query = query.substring(0, query.length()-3); //to remove the last comma
query = query + " FROM " +tableName;
return query;
}
private Map[] getMapReportTableData(ResultSet resultSet, String[] columns) throws SQLException {
ArrayList<HashMap> maps = new ArrayList<HashMap>();
while (resultSet.next()){
HashMap<String, String> rowData = new HashMap<String, String>();
for(int i=0; i< columns.length; i++){
String value = resultSet.getString(columns[i]);
String key = String.valueOf(i+1);
rowData.put(key, value);
}
maps.add(rowData);
}
return maps.toArray(new HashMap[maps.size()]);
}
private Map[] getMapReportChartData(ResultSet resultSet, SeriesDTO[] series) throws SQLException, ReportingException {
ArrayList<HashMap> maps = new ArrayList<HashMap>();
while (resultSet.next()){
HashMap<String, Object> rowData = new HashMap<String, Object>();
for(int i=0; i< series.length; i++){
DataDTO xData = series[i].getXdata();
String value = resultSet.getString(xData.getDsColumnName());
String key = String.valueOf(xData.getFieldId());
rowData.put(key, value);
DataDTO yData = series[i].getYdata();
value = resultSet.getString(yData.getDsColumnName());
Number yNumber = getNumber(value);
if(yNumber == null){
log.error("Y axis can be only number! It can't hold other values");
throw new ReportingException("Y axis can be only number! It can't hold other values");
}
key = String.valueOf(yData.getFieldId());
rowData.put(key, yNumber);
}
maps.add(rowData);
}
return maps.toArray(new HashMap[maps.size()]);
}
private Map[] getMapReportXYChartData(ResultSet resultSet, SeriesDTO[] series) throws SQLException, ReportingException {
ArrayList<HashMap> maps = new ArrayList<HashMap>();
while (resultSet.next()){
HashMap<String, Object> rowData = new HashMap<String, Object>();
for(int i=0; i< series.length; i++){
DataDTO xData = series[i].getXdata();
String key = String.valueOf(xData.getFieldId());
String value = resultSet.getString(xData.getDsColumnName());
Number xNumber = getNumber(value);
if(xNumber == null){
log.error("X axis can be only number! It can't hold other values");
throw new ReportingException("X axis can be only number! It can't hold other values");
}
rowData.put(key, xNumber);
DataDTO yData = series[i].getYdata();
value = resultSet.getString(yData.getDsColumnName());
Number yNumber = getNumber(value);
if(yNumber == null){
log.error("Y axis can be only number! It can't hold other values");
throw new ReportingException("Y axis can be only number! It can't hold other values");
}
key = String.valueOf(yData.getFieldId());
rowData.put(key, yNumber);
}
maps.add(rowData);
}
return maps.toArray(new HashMap[maps.size()]);
}
private Number getNumber(String strNumber) {
try {
Integer intValue = Integer.parseInt(strNumber);
return intValue;
} catch (NumberFormatException ex) {
try {
Double doubleValue = Double.parseDouble(strNumber);
return doubleValue;
} catch (NumberFormatException dEx) {
return null;
}
}
}
public Map[] createMapDataSource(ChartReportDTO chartReport) throws ReportingException {
String dsName = chartReport.getDsName();
SeriesDTO[] series = chartReport.getCategorySeries();
String[] fields = getChartFields(series);
//assuming the report is getting data from one table
String tableName = series[0].getXdata().getDsTableName();
String query = getQueryString(tableName, fields);
DatasourceClient client = ClientFactory.getDSClient();
try {
Connection connection= client.getConnection(dsName);
ResultSet resultSet =client.queryDatasource(query, connection);
Map[] mapData = null;
if(chartReport.getReportType().contains("xy")){
mapData = getMapReportXYChartData(resultSet, series);
}
else{
mapData = getMapReportChartData(resultSet, series);
}
connection.close();
return mapData;
} catch (SQLException e) {
throw new ReportingException("SQL error while querying the data for "+ dsName+" to fill report" + chartReport.getReportName());
}
}
}
| apache-2.0 |
TangHao1987/intellij-community | platform/platform-impl/src/com/intellij/ui/messages/SheetMessage.java | 9029 | /*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.ui.messages;
import com.apple.eawt.FullScreenUtilities;
import com.intellij.openapi.application.impl.LaterInvocator;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.wm.IdeFocusManager;
import com.intellij.ui.Gray;
import com.intellij.ui.JBColor;
import com.intellij.ui.mac.MacMainFrameDecorator;
import com.intellij.util.IJSwingUtilities;
import com.intellij.util.ui.Animator;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.lang.ref.WeakReference;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* Created by Denis Fokin
*/
public class SheetMessage {
private static final Logger LOG = Logger.getInstance("#com.intellij.ui.messages.SheetMessage");
private final JDialog myWindow;
private final Window myParent;
private final SheetController myController;
private final static int TIME_TO_SHOW_SHEET = 250;
private Image staticImage;
private int imageHeight;
private final boolean restoreFullScreenButton;
private final ComponentAdapter myPositionListener = new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent event) {
setPositionRelativeToParent();
}
@Override
public void componentMoved(ComponentEvent event) {
setPositionRelativeToParent();
}
};
public SheetMessage(final Window owner,
final String title,
final String message,
final Icon icon,
final String[] buttons,
final DialogWrapper.DoNotAskOption doNotAskOption,
final String defaultButton,
final String focusedButton)
{
final Window activeWindow = KeyboardFocusManager.getCurrentKeyboardFocusManager().getActiveWindow();
final Component recentFocusOwner = activeWindow == null ? null : activeWindow.getMostRecentFocusOwner();
WeakReference<Component> beforeShowFocusOwner = new WeakReference<Component>(recentFocusOwner);
maximizeIfNeeded(owner);
myWindow = new JDialog(owner, "This should not be shown", Dialog.ModalityType.APPLICATION_MODAL);
myWindow.getRootPane().putClientProperty("apple.awt.draggableWindowBackground", Boolean.FALSE);
myWindow.addWindowListener(new WindowAdapter() {
@Override
public void windowActivated(@NotNull WindowEvent e) {
super.windowActivated(e);
}
});
myParent = owner;
myWindow.setUndecorated(true);
myWindow.setBackground(Gray.TRANSPARENT);
myController = new SheetController(this, title, message, icon, buttons, defaultButton, doNotAskOption, focusedButton);
imageHeight = 0;
myParent.addComponentListener(myPositionListener);
myWindow.setFocusable(true);
myWindow.setFocusableWindowState(true);
if (SystemInfo.isJavaVersionAtLeast("1.7")) {
myWindow.setSize(myController.SHEET_NC_WIDTH, 0);
setWindowOpacity(0.0f);
myWindow.addComponentListener(new ComponentAdapter() {
@Override
public void componentShown(@NotNull ComponentEvent e) {
super.componentShown(e);
setWindowOpacity(1.0f);
myWindow.setSize(myController.SHEET_NC_WIDTH, myController.SHEET_NC_HEIGHT);
}
});
} else {
myWindow.setModal(true);
myWindow.setSize(myController.SHEET_NC_WIDTH, myController.SHEET_NC_HEIGHT);
setPositionRelativeToParent();
}
startAnimation(true);
restoreFullScreenButton = couldBeInFullScreen();
if (restoreFullScreenButton) {
FullScreenUtilities.setWindowCanFullScreen(myParent, false);
}
LaterInvocator.enterModal(myWindow);
myWindow.setVisible(true);
LaterInvocator.leaveModal(myWindow);
Component focusCandidate = beforeShowFocusOwner.get();
if (focusCandidate == null) {
focusCandidate = IdeFocusManager.getGlobalInstance().getLastFocusedFor(IdeFocusManager.getGlobalInstance().getLastFocusedFrame());
}
// focusCandidate is null if a welcome screen is closed and ide frame is not opened.
// this is ok. We set focus correctly on our frame activation.
if (focusCandidate != null) {
focusCandidate.requestFocus();
}
}
private static void maximizeIfNeeded(final Window owner) {
if (owner == null) return;
if (owner instanceof Frame) {
Frame f = (Frame)owner;
if (f.getState() == Frame.ICONIFIED) {
f.setState(Frame.NORMAL);
}
}
}
private void setWindowOpacity(float opacity) {
try {
Method setOpacityMethod = myWindow.getClass().getMethod("setOpacity", Float.TYPE);
setOpacityMethod.invoke(myWindow, opacity);
}
catch (NoSuchMethodException e) {
LOG.error(e);
}
catch (InvocationTargetException e) {
LOG.error(e);
}
catch (IllegalAccessException e) {
LOG.error(e);
}
}
private boolean couldBeInFullScreen() {
if (myParent instanceof JFrame) {
JRootPane rootPane = ((JFrame)myParent).getRootPane();
return rootPane.getClientProperty(MacMainFrameDecorator.FULL_SCREEN) == null;
}
return false;
}
public boolean toBeShown() {
return !myController.getDoNotAskResult();
}
public String getResult() {
return myController.getResult();
}
void startAnimation (final boolean enlarge) {
staticImage = myController.getStaticImage();
JPanel staticPanel = new JPanel() {
@Override
public void paint(@NotNull Graphics g) {
super.paint(g);
if (staticImage != null) {
Graphics2D g2d = (Graphics2D) g.create();
g2d.setBackground(new JBColor(new Color(255, 255, 255, 0), new Color(110, 110, 110, 0)));
g2d.clearRect(0, 0, myController.SHEET_NC_WIDTH, myController.SHEET_NC_HEIGHT);
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.95f));
int multiplyFactor = staticImage.getWidth(null)/myController.SHEET_NC_WIDTH;
g.drawImage(staticImage, 0, 0,
myController.SHEET_NC_WIDTH, imageHeight,
0, staticImage.getHeight(null) - imageHeight * multiplyFactor,
staticImage.getWidth(null), staticImage.getHeight(null),
null);
}
}
};
staticPanel.setOpaque(false);
staticPanel.setSize(myController.SHEET_NC_WIDTH,myController.SHEET_NC_HEIGHT);
myWindow.setContentPane(staticPanel);
Animator myAnimator = new Animator("Roll Down Sheet Animator", myController.SHEET_NC_HEIGHT ,
TIME_TO_SHOW_SHEET, false) {
@Override
public void paintNow(int frame, int totalFrames, int cycle) {
setPositionRelativeToParent();
float percentage = (float)frame/(float)totalFrames;
imageHeight = enlarge ? (int)(((float)myController.SHEET_NC_HEIGHT) * percentage):
(int)(myController.SHEET_NC_HEIGHT - percentage * myController.SHEET_HEIGHT);
myWindow.repaint();
}
@Override
protected void paintCycleEnd() {
setPositionRelativeToParent();
if (enlarge) {
imageHeight = myController.SHEET_NC_HEIGHT;
staticImage = null;
myWindow.setContentPane(myController.getPanel(myWindow));
IJSwingUtilities.moveMousePointerOn(myWindow.getRootPane().getDefaultButton());
myController.requestFocus();
} else {
if (restoreFullScreenButton) {
FullScreenUtilities.setWindowCanFullScreen(myParent, true);
}
myParent.removeComponentListener(myPositionListener);
myController.dispose();
myWindow.dispose();
}
}
};
myAnimator.resume();
}
private void setPositionRelativeToParent () {
int width = myParent.getWidth();
myWindow.setBounds(width / 2 - myController.SHEET_NC_WIDTH / 2 + myParent.getLocation().x,
myParent.getInsets().top + myParent.getLocation().y,
myController.SHEET_NC_WIDTH,
myController.SHEET_NC_HEIGHT);
}
}
| apache-2.0 |
sigmoidanalytics/spork | src/org/apache/pig/impl/io/NullableBytesWritable.java | 1751 | /*
* 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.pig.impl.io;
import org.apache.pig.backend.executionengine.ExecException;
import org.apache.pig.data.Tuple;
import org.apache.pig.data.TupleFactory;
/**
*
*/
public class NullableBytesWritable extends PigNullableWritable {
private static final TupleFactory mTupleFactory = TupleFactory.getInstance();
public NullableBytesWritable() {
mValue = mTupleFactory.newTuple();
}
/**
* @param obj
*/
public NullableBytesWritable(Object obj) {
mValue = mTupleFactory.newTuple(1);
try {
((Tuple)mValue).set(0, obj);
} catch (ExecException e) {
throw new RuntimeException(e);
}
}
public Object getValueAsPigType() {
if (isNull()) {
return null;
}
try {
return ((Tuple)mValue).get(0);
} catch (ExecException e) {
throw new RuntimeException(e);
}
}
}
| apache-2.0 |
rodriguezdevera/sakai | sitestats/sitestats-tool/src/java/org/sakaiproject/sitestats/tool/wicket/pages/PreferencesPage.java | 8281 | /**
* $URL$
* $Id$
*
* Copyright (c) 2006-2009 The Sakai Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ECL-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sakaiproject.sitestats.tool.wicket.pages;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.apache.wicket.AttributeModifier;
import org.apache.wicket.markup.head.IHeaderResponse;
import org.apache.wicket.markup.head.JavaScriptHeaderItem;
import org.apache.wicket.markup.head.OnDomReadyHeaderItem;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.CheckBox;
import org.apache.wicket.markup.html.form.DropDownChoice;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.IChoiceRenderer;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.ResourceModel;
import org.sakaiproject.sitestats.api.PrefsData;
import org.sakaiproject.sitestats.api.StatsManager;
import org.sakaiproject.sitestats.api.Util;
import org.sakaiproject.sitestats.api.event.ToolInfo;
import org.sakaiproject.sitestats.api.parser.EventParserTip;
import org.sakaiproject.sitestats.tool.facade.Locator;
import org.sakaiproject.sitestats.tool.wicket.components.CSSFeedbackPanel;
import org.sakaiproject.sitestats.tool.wicket.components.EventRegistryTree;
import org.sakaiproject.sitestats.tool.wicket.components.Menus;
/**
* @author Nuno Fernandes
*/
public class PreferencesPage extends BasePage {
private static final long serialVersionUID = 1L;
private String realSiteId;
private String siteId;
// UI
private FeedbackPanel feedback = null;
private EventRegistryTree eventRegistryTree = null;
private static final String[] transparencyChoices = { "100", "90", "80", "70", "60", "50", "40", "30", "20", "10" };
private static final List<String> chartTransparencyChoices = Arrays.asList(transparencyChoices);
// Model
private PrefsData prefsdata = null;
public PreferencesPage() {
this(null);
}
public PreferencesPage(PageParameters pageParameters) {
realSiteId = Locator.getFacade().getToolManager().getCurrentPlacement().getContext();
if(pageParameters != null) {
siteId = pageParameters.get("siteId").toString();
}
if(siteId == null){
siteId = realSiteId;
}
boolean allowed = Locator.getFacade().getStatsAuthz().isUserAbleToViewSiteStats(siteId);
if(allowed) {
setDefaultModel(new CompoundPropertyModel(this));
renderBody();
}else{
setResponsePage(NotAuthorizedPage.class);
}
}
@Override
public void renderHead(IHeaderResponse response) {
super.renderHead(response);
response.render(JavaScriptHeaderItem.forUrl(JQUERYSCRIPT));
response.render(OnDomReadyHeaderItem.forScript("toggleCheckboxAll();"));
}
@SuppressWarnings("serial")
private void renderBody() {
add(new Menus("menu", siteId));
Form form = new Form("prefsForm");
form.setOutputMarkupId(true);
form.setMarkupId("prefsForm");
add(form);
feedback = new CSSFeedbackPanel("messages");
form.add(feedback);
// Section: General
CheckBox listToolEventsOnlyAvailableInSite = new CheckBox("listToolEventsOnlyAvailableInSite");
form.add(listToolEventsOnlyAvailableInSite);
// Section: Chart
WebMarkupContainer chartPrefs = new WebMarkupContainer("chartPrefs");
boolean chartPrefsVisible = Locator.getFacade().getStatsManager().isEnableSiteVisits() || Locator.getFacade().getStatsManager().isEnableSiteActivity();
chartPrefs.setVisible(chartPrefsVisible);
form.add(chartPrefs);
//CheckBox chartIn3D = new CheckBox("chartIn3D");
//chartPrefs.add(chartIn3D);
CheckBox itemLabelsVisible = new CheckBox("itemLabelsVisible");
chartPrefs.add(itemLabelsVisible);
DropDownChoice chartTransparency = new DropDownChoice("chartTransparency", chartTransparencyChoices, new IChoiceRenderer() {
public Object getDisplayValue(Object object) {
return (String) object + "%";
}
public String getIdValue(Object object, int index) {
return (String) object;
}
});
chartPrefs.add(chartTransparency);
// Section: Activity Definition
CheckBox useAllTools = new CheckBox("useAllTools");
useAllTools.add(AttributeModifier.replace("onclick", "toggleCheckboxAll();"));
useAllTools.setOutputMarkupId(true);
useAllTools.setMarkupId("useAllTools");
form.add(useAllTools);
eventRegistryTree = new EventRegistryTree("eventRegistryTree", getPrefsdata().getToolEventsDef()) {
@Override
public boolean isToolSuported(final ToolInfo toolInfo) {
if(Locator.getFacade().getStatsManager().isEventContextSupported()){
return true;
}else{
List<ToolInfo> siteTools = Locator.getFacade().getEventRegistryService().getEventRegistry(siteId, getPrefsdata().isListToolEventsOnlyAvailableInSite());
Iterator<ToolInfo> i = siteTools.iterator();
while (i.hasNext()){
ToolInfo t = i.next();
if(t.getToolId().equals(toolInfo.getToolId())){
EventParserTip parserTip = t.getEventParserTip();
if(parserTip != null && parserTip.getFor().equals(StatsManager.PARSERTIP_FOR_CONTEXTID)){
return true;
}
}
}
}
return false;
}
};
form.add(eventRegistryTree);
// Bottom Buttons
Button update = new Button("update") {
@Override
public void onSubmit() {
savePreferences();
prefsdata = null;
super.onSubmit();
}
};
update.setDefaultFormProcessing(true);
form.add(update);
Button cancel = new Button("cancel") {
@Override
public void onSubmit() {
prefsdata = null;
super.onSubmit();
}
};
cancel.setDefaultFormProcessing(false);
form.add(cancel);
}
private PrefsData getPrefsdata() {
if(prefsdata == null) {
prefsdata = Locator.getFacade().getStatsManager().getPreferences(siteId, true);
}
return prefsdata;
}
private void savePreferences() {
if(isUseAllTools()) {
getPrefsdata().setToolEventsDef(Locator.getFacade().getEventRegistryService().getEventRegistry(siteId, isListToolEventsOnlyAvailableInSite()));
}else{
getPrefsdata().setToolEventsDef((List<ToolInfo>) eventRegistryTree.getEventRegistry());
}
boolean opOk = Locator.getFacade().getStatsManager().setPreferences(siteId, getPrefsdata());
if(opOk){
info((String) new ResourceModel("prefs_updated").getObject());
}else{
error((String) new ResourceModel("prefs_not_updated").getObject());
}
}
public void setListToolEventsOnlyAvailableInSite(boolean listToolEventsOnlyAvailableInSite) {
prefsdata.setListToolEventsOnlyAvailableInSite(listToolEventsOnlyAvailableInSite);
}
public boolean isListToolEventsOnlyAvailableInSite() {
return getPrefsdata().isListToolEventsOnlyAvailableInSite();
}
public void setChartIn3D(boolean chartIn3D) {
prefsdata.setChartIn3D(chartIn3D);
}
public boolean isChartIn3D() {
return getPrefsdata().isChartIn3D();
}
public void setUseAllTools(boolean useAllTools) {
prefsdata.setUseAllTools(useAllTools);
}
public boolean isUseAllTools() {
return getPrefsdata().isUseAllTools();
}
public void setItemLabelsVisible(boolean itemLabelsVisible) {
prefsdata.setItemLabelsVisible(itemLabelsVisible);
}
public boolean isItemLabelsVisible() {
return getPrefsdata().isItemLabelsVisible();
}
public void setChartTransparency(String value) {
float converted = (float) Util.round(Double.parseDouble(value)/100,1);
getPrefsdata().setChartTransparency(converted);
}
public String getChartTransparency() {
return Integer.toString((int) Util.round(getPrefsdata().getChartTransparency()*100,0) );
}
}
| apache-2.0 |
gfyoung/elasticsearch | libs/nio/src/main/java/org/elasticsearch/nio/RoundRobinSupplier.java | 1842 | /*
* 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.nio;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Supplier;
final class RoundRobinSupplier<S> implements Supplier<S> {
private final AtomicBoolean selectorsSet = new AtomicBoolean(false);
private volatile S[] selectors;
private AtomicInteger counter = new AtomicInteger(0);
RoundRobinSupplier() {
this.selectors = null;
}
RoundRobinSupplier(S[] selectors) {
this.selectors = selectors;
this.selectorsSet.set(true);
}
@Override
public S get() {
S[] selectors = this.selectors;
return selectors[counter.getAndIncrement() % selectors.length];
}
void setSelectors(S[] selectors) {
if (selectorsSet.compareAndSet(false, true)) {
this.selectors = selectors;
} else {
throw new AssertionError("Selectors already set. Should only be set once.");
}
}
int count() {
return selectors.length;
}
}
| apache-2.0 |
beobal/cassandra | test/unit/org/apache/cassandra/io/util/MmappedRegionsTest.java | 13001 | /*
* 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.cassandra.io.util;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Random;
import com.google.common.primitives.Ints;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.db.ClusteringComparator;
import org.apache.cassandra.db.marshal.BytesType;
import org.apache.cassandra.io.compress.CompressedSequentialWriter;
import org.apache.cassandra.io.compress.CompressionMetadata;
import org.apache.cassandra.io.sstable.metadata.MetadataCollector;
import org.apache.cassandra.schema.CompressionParams;
import static junit.framework.Assert.assertNull;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
public class MmappedRegionsTest
{
private static final Logger logger = LoggerFactory.getLogger(MmappedRegionsTest.class);
@BeforeClass
public static void setupDD()
{
DatabaseDescriptor.daemonInitialization();
}
private static ByteBuffer allocateBuffer(int size)
{
ByteBuffer ret = ByteBuffer.allocate(Ints.checkedCast(size));
long seed = System.nanoTime();
//seed = 365238103404423L;
logger.info("Seed {}", seed);
new Random(seed).nextBytes(ret.array());
return ret;
}
private static File writeFile(String fileName, ByteBuffer buffer) throws IOException
{
File ret = FileUtils.createTempFile(fileName, "1");
ret.deleteOnExit();
try (SequentialWriter writer = new SequentialWriter(ret))
{
writer.write(buffer);
writer.finish();
}
assert ret.exists();
assert ret.length() >= buffer.capacity();
return ret;
}
@Test
public void testEmpty() throws Exception
{
ByteBuffer buffer = allocateBuffer(1024);
try(ChannelProxy channel = new ChannelProxy(writeFile("testEmpty", buffer));
MmappedRegions regions = MmappedRegions.empty(channel))
{
assertTrue(regions.isEmpty());
assertTrue(regions.isValid(channel));
}
}
@Test
public void testTwoSegments() throws Exception
{
ByteBuffer buffer = allocateBuffer(2048);
try(ChannelProxy channel = new ChannelProxy(writeFile("testTwoSegments", buffer));
MmappedRegions regions = MmappedRegions.empty(channel))
{
regions.extend(1024);
for (int i = 0; i < 1024; i++)
{
MmappedRegions.Region region = regions.floor(i);
assertNotNull(region);
assertEquals(0, region.offset());
assertEquals(1024, region.end());
}
regions.extend(2048);
for (int i = 0; i < 2048; i++)
{
MmappedRegions.Region region = regions.floor(i);
assertNotNull(region);
if (i < 1024)
{
assertEquals(0, region.offset());
assertEquals(1024, region.end());
}
else
{
assertEquals(1024, region.offset());
assertEquals(2048, region.end());
}
}
}
}
@Test
public void testSmallSegmentSize() throws Exception
{
int OLD_MAX_SEGMENT_SIZE = MmappedRegions.MAX_SEGMENT_SIZE;
MmappedRegions.MAX_SEGMENT_SIZE = 1024;
ByteBuffer buffer = allocateBuffer(4096);
try(ChannelProxy channel = new ChannelProxy(writeFile("testSmallSegmentSize", buffer));
MmappedRegions regions = MmappedRegions.empty(channel))
{
regions.extend(1024);
regions.extend(2048);
regions.extend(4096);
final int SIZE = MmappedRegions.MAX_SEGMENT_SIZE;
for (int i = 0; i < buffer.capacity(); i++)
{
MmappedRegions.Region region = regions.floor(i);
assertNotNull(region);
assertEquals(SIZE * (i / SIZE), region.offset());
assertEquals(SIZE + (SIZE * (i / SIZE)), region.end());
}
}
finally
{
MmappedRegions.MAX_SEGMENT_SIZE = OLD_MAX_SEGMENT_SIZE;
}
}
@Test
public void testAllocRegions() throws Exception
{
int OLD_MAX_SEGMENT_SIZE = MmappedRegions.MAX_SEGMENT_SIZE;
MmappedRegions.MAX_SEGMENT_SIZE = 1024;
ByteBuffer buffer = allocateBuffer(MmappedRegions.MAX_SEGMENT_SIZE * MmappedRegions.REGION_ALLOC_SIZE * 3);
try(ChannelProxy channel = new ChannelProxy(writeFile("testAllocRegions", buffer));
MmappedRegions regions = MmappedRegions.empty(channel))
{
regions.extend(buffer.capacity());
final int SIZE = MmappedRegions.MAX_SEGMENT_SIZE;
for (int i = 0; i < buffer.capacity(); i++)
{
MmappedRegions.Region region = regions.floor(i);
assertNotNull(region);
assertEquals(SIZE * (i / SIZE), region.offset());
assertEquals(SIZE + (SIZE * (i / SIZE)), region.end());
}
}
finally
{
MmappedRegions.MAX_SEGMENT_SIZE = OLD_MAX_SEGMENT_SIZE;
}
}
@Test
public void testCopy() throws Exception
{
ByteBuffer buffer = allocateBuffer(128 * 1024);
MmappedRegions snapshot;
ChannelProxy channelCopy;
try(ChannelProxy channel = new ChannelProxy(writeFile("testSnapshot", buffer));
MmappedRegions regions = MmappedRegions.map(channel, buffer.capacity() / 4))
{
// create 3 more segments, one per quater capacity
regions.extend(buffer.capacity() / 2);
regions.extend(3 * buffer.capacity() / 4);
regions.extend(buffer.capacity());
// make a snapshot
snapshot = regions.sharedCopy();
// keep the channel open
channelCopy = channel.sharedCopy();
}
assertFalse(snapshot.isCleanedUp());
final int SIZE = buffer.capacity() / 4;
for (int i = 0; i < buffer.capacity(); i++)
{
MmappedRegions.Region region = snapshot.floor(i);
assertNotNull(region);
assertEquals(SIZE * (i / SIZE), region.offset());
assertEquals(SIZE + (SIZE * (i / SIZE)), region.end());
// check we can access the buffer
assertNotNull(region.buffer.duplicate().getInt());
}
assertNull(snapshot.close(null));
assertNull(channelCopy.close(null));
assertTrue(snapshot.isCleanedUp());
}
@Test(expected = AssertionError.class)
public void testCopyCannotExtend() throws Exception
{
ByteBuffer buffer = allocateBuffer(128 * 1024);
MmappedRegions snapshot;
ChannelProxy channelCopy;
try(ChannelProxy channel = new ChannelProxy(writeFile("testSnapshotCannotExtend", buffer));
MmappedRegions regions = MmappedRegions.empty(channel))
{
regions.extend(buffer.capacity() / 2);
// make a snapshot
snapshot = regions.sharedCopy();
// keep the channel open
channelCopy = channel.sharedCopy();
}
try
{
snapshot.extend(buffer.capacity());
}
finally
{
assertNull(snapshot.close(null));
assertNull(channelCopy.close(null));
}
}
@Test
public void testExtendOutOfOrder() throws Exception
{
ByteBuffer buffer = allocateBuffer(4096);
try(ChannelProxy channel = new ChannelProxy(writeFile("testExtendOutOfOrder", buffer));
MmappedRegions regions = MmappedRegions.empty(channel))
{
regions.extend(4096);
regions.extend(1024);
regions.extend(2048);
for (int i = 0; i < buffer.capacity(); i++)
{
MmappedRegions.Region region = regions.floor(i);
assertNotNull(region);
assertEquals(0, region.offset());
assertEquals(4096, region.end());
}
}
}
@Test(expected = IllegalArgumentException.class)
public void testNegativeExtend() throws Exception
{
ByteBuffer buffer = allocateBuffer(1024);
try(ChannelProxy channel = new ChannelProxy(writeFile("testNegativeExtend", buffer));
MmappedRegions regions = MmappedRegions.empty(channel))
{
regions.extend(-1);
}
}
@Test
public void testMapForCompressionMetadata() throws Exception
{
int OLD_MAX_SEGMENT_SIZE = MmappedRegions.MAX_SEGMENT_SIZE;
MmappedRegions.MAX_SEGMENT_SIZE = 1024;
ByteBuffer buffer = allocateBuffer(128 * 1024);
File f = FileUtils.createTempFile("testMapForCompressionMetadata", "1");
f.deleteOnExit();
File cf = FileUtils.createTempFile(f.getName() + ".metadata", "1");
cf.deleteOnExit();
MetadataCollector sstableMetadataCollector = new MetadataCollector(new ClusteringComparator(BytesType.instance));
try(SequentialWriter writer = new CompressedSequentialWriter(f, cf.getAbsolutePath(),
null, SequentialWriterOption.DEFAULT,
CompressionParams.snappy(), sstableMetadataCollector))
{
writer.write(buffer);
writer.finish();
}
CompressionMetadata metadata = new CompressionMetadata(cf.getAbsolutePath(), f.length(), true);
try(ChannelProxy channel = new ChannelProxy(f);
MmappedRegions regions = MmappedRegions.map(channel, metadata))
{
assertFalse(regions.isEmpty());
int i = 0;
while(i < buffer.capacity())
{
CompressionMetadata.Chunk chunk = metadata.chunkFor(i);
MmappedRegions.Region region = regions.floor(chunk.offset);
assertNotNull(region);
ByteBuffer compressedChunk = region.buffer.duplicate();
assertNotNull(compressedChunk);
assertEquals(chunk.length + 4, compressedChunk.capacity());
assertEquals(chunk.offset, region.offset());
assertEquals(chunk.offset + chunk.length + 4, region.end());
i += metadata.chunkLength();
}
}
finally
{
MmappedRegions.MAX_SEGMENT_SIZE = OLD_MAX_SEGMENT_SIZE;
metadata.close();
}
}
@Test(expected = IllegalArgumentException.class)
public void testIllegalArgForMap1() throws Exception
{
ByteBuffer buffer = allocateBuffer(1024);
try(ChannelProxy channel = new ChannelProxy(writeFile("testIllegalArgForMap1", buffer));
MmappedRegions regions = MmappedRegions.map(channel, 0))
{
assertTrue(regions.isEmpty());
}
}
@Test(expected = IllegalArgumentException.class)
public void testIllegalArgForMap2() throws Exception
{
ByteBuffer buffer = allocateBuffer(1024);
try(ChannelProxy channel = new ChannelProxy(writeFile("testIllegalArgForMap2", buffer));
MmappedRegions regions = MmappedRegions.map(channel, -1L))
{
assertTrue(regions.isEmpty());
}
}
@Test(expected = IllegalArgumentException.class)
public void testIllegalArgForMap3() throws Exception
{
ByteBuffer buffer = allocateBuffer(1024);
try(ChannelProxy channel = new ChannelProxy(writeFile("testIllegalArgForMap3", buffer));
MmappedRegions regions = MmappedRegions.map(channel, null))
{
assertTrue(regions.isEmpty());
}
}
}
| apache-2.0 |
jonathanmcelroy/DataCommunicationsProgram456 | twitter4j/twitter4j-examples/src/main/java/twitter4j/examples/list/ShowUserListSubscription.java | 2128 | /*
* Copyright 2007 Yusuke Yamamoto
*
* 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 twitter4j.examples.list;
import twitter4j.*;
/**
* Checks list subscription.
*
* @author Yusuke Yamamoto - yusuke at mac.com
*/
public final class ShowUserListSubscription {
/**
* Usage: java twitter4j.examples.list.ShowUserListSubscription [list id] [user id]
*
* @param args message
*/
public static void main(String[] args) {
if (args.length < 2) {
System.out.println("Usage: java twitter4j.examples.list.ShowUserListSubscription [list id] [user id]");
System.exit(-1);
}
try {
Twitter twitter = new TwitterFactory().getInstance();
long listId = Long.parseLong(args[0]);
UserList list = twitter.showUserList(listId);
long userId = Integer.parseInt(args[1]);
User user = twitter.showUser(userId);
try {
twitter.showUserListSubscription(listId, userId);
System.out.println("@" + user.getScreenName() + " is subscribing the list:" + list.getName());
} catch (TwitterException te) {
if (te.getStatusCode() == 404) {
System.out.println("@" + user.getScreenName() + " is not subscribing the list:" + list.getName());
}
}
System.exit(0);
} catch (TwitterException te) {
te.printStackTrace();
System.out.println("Failed to check user subscription: " + te.getMessage());
System.exit(-1);
}
}
}
| gpl-2.0 |
PlanetWaves/clockworkengine | trunk/jme3-blender/src/main/java/com/jme3/scene/plugins/blender/textures/UVProjectionGenerator.java | 11074 | package com.jme3.scene.plugins.blender.textures;
import com.jme3.bounding.BoundingBox;
import com.jme3.bounding.BoundingSphere;
import com.jme3.math.FastMath;
import com.jme3.math.Triangle;
import com.jme3.math.Vector3f;
import com.jme3.scene.plugins.blender.textures.UVCoordinatesGenerator.BoundingTube;
/**
* This class helps with projection calculations.
*
* @author Marcin Roguski (Kaelthas)
*/
/* package */class UVProjectionGenerator {
/**
* 2D texture mapping (projection)
* @author Marcin Roguski (Kaelthas)
*/
public static enum UVProjectionType {
PROJECTION_FLAT(0), PROJECTION_CUBE(1), PROJECTION_TUBE(2), PROJECTION_SPHERE(3);
public final int blenderValue;
private UVProjectionType(int blenderValue) {
this.blenderValue = blenderValue;
}
public static UVProjectionType valueOf(int blenderValue) {
for (UVProjectionType projectionType : UVProjectionType.values()) {
if (projectionType.blenderValue == blenderValue) {
return projectionType;
}
}
return null;
}
}
/**
* Flat projection for 2D textures.
*
* @param mesh
* mesh that is to be projected
* @param bb
* the bounding box for projecting
* @return UV coordinates after the projection
*/
public static float[] flatProjection(float[] positions, BoundingBox bb) {
Vector3f min = bb.getMin(null);
float[] ext = new float[] { bb.getXExtent() * 2.0f, bb.getZExtent() * 2.0f };
float[] uvCoordinates = new float[positions.length / 3 * 2];
for (int i = 0, j = 0; i < positions.length; i += 3, j += 2) {
uvCoordinates[j] = (positions[i] - min.x) / ext[0];
// skip the Y-coordinate
uvCoordinates[j + 1] = (positions[i + 2] - min.z) / ext[1];
}
return uvCoordinates;
}
/**
* Cube projection for 2D textures.
*
* @param positions
* points to be projected
* @param bb
* the bounding box for projecting
* @return UV coordinates after the projection
*/
public static float[] cubeProjection(float[] positions, BoundingBox bb) {
Triangle triangle = new Triangle();
Vector3f x = new Vector3f(1, 0, 0);
Vector3f y = new Vector3f(0, 1, 0);
Vector3f z = new Vector3f(0, 0, 1);
Vector3f min = bb.getMin(null);
float[] ext = new float[] { bb.getXExtent() * 2.0f, bb.getYExtent() * 2.0f, bb.getZExtent() * 2.0f };
float[] uvCoordinates = new float[positions.length / 3 * 2];
float borderAngle = (float) Math.sqrt(2.0f) / 2.0f;
for (int i = 0, pointIndex = 0; i < positions.length; i += 9) {
triangle.set(0, positions[i], positions[i + 1], positions[i + 2]);
triangle.set(1, positions[i + 3], positions[i + 4], positions[i + 5]);
triangle.set(2, positions[i + 6], positions[i + 7], positions[i + 8]);
Vector3f n = triangle.getNormal();
float dotNX = Math.abs(n.dot(x));
float dorNY = Math.abs(n.dot(y));
float dotNZ = Math.abs(n.dot(z));
if (dotNX > borderAngle) {
if (dotNZ < borderAngle) {// discard X-coordinate
uvCoordinates[pointIndex++] = (triangle.get1().y - min.y) / ext[1];
uvCoordinates[pointIndex++] = (triangle.get1().z - min.z) / ext[2];
uvCoordinates[pointIndex++] = (triangle.get2().y - min.y) / ext[1];
uvCoordinates[pointIndex++] = (triangle.get2().z - min.z) / ext[2];
uvCoordinates[pointIndex++] = (triangle.get3().y - min.y) / ext[1];
uvCoordinates[pointIndex++] = (triangle.get3().z - min.z) / ext[2];
} else {// discard Z-coordinate
uvCoordinates[pointIndex++] = (triangle.get1().x - min.x) / ext[0];
uvCoordinates[pointIndex++] = (triangle.get1().y - min.y) / ext[1];
uvCoordinates[pointIndex++] = (triangle.get2().x - min.x) / ext[0];
uvCoordinates[pointIndex++] = (triangle.get2().y - min.y) / ext[1];
uvCoordinates[pointIndex++] = (triangle.get3().x - min.x) / ext[0];
uvCoordinates[pointIndex++] = (triangle.get3().y - min.y) / ext[1];
}
} else {
if (dorNY > borderAngle) {// discard Y-coordinate
uvCoordinates[pointIndex++] = (triangle.get1().x - min.x) / ext[0];
uvCoordinates[pointIndex++] = (triangle.get1().z - min.z) / ext[2];
uvCoordinates[pointIndex++] = (triangle.get2().x - min.x) / ext[0];
uvCoordinates[pointIndex++] = (triangle.get2().z - min.z) / ext[2];
uvCoordinates[pointIndex++] = (triangle.get3().x - min.x) / ext[0];
uvCoordinates[pointIndex++] = (triangle.get3().z - min.z) / ext[2];
} else {// discard Z-coordinate
uvCoordinates[pointIndex++] = (triangle.get1().x - min.x) / ext[0];
uvCoordinates[pointIndex++] = (triangle.get1().y - min.y) / ext[1];
uvCoordinates[pointIndex++] = (triangle.get2().x - min.x) / ext[0];
uvCoordinates[pointIndex++] = (triangle.get2().y - min.y) / ext[1];
uvCoordinates[pointIndex++] = (triangle.get3().x - min.x) / ext[0];
uvCoordinates[pointIndex++] = (triangle.get3().y - min.y) / ext[1];
}
}
triangle.setNormal(null);// clear the previous normal vector
}
return uvCoordinates;
}
/**
* Tube projection for 2D textures.
*
* @param positions
* points to be projected
* @param bt
* the bounding tube for projecting
* @return UV coordinates after the projection
*/
public static float[] tubeProjection(float[] positions, BoundingTube bt) {
float[] uvCoordinates = new float[positions.length / 3 * 2];
Vector3f v = new Vector3f();
float cx = bt.getCenter().x, cz = bt.getCenter().z;
Vector3f uBase = new Vector3f(0, 0, -1);
float vBase = bt.getCenter().y - bt.getHeight() * 0.5f;
for (int i = 0, j = 0; i < positions.length; i += 3, j += 2) {
// calculating U
v.set(positions[i] - cx, 0, positions[i + 2] - cz);
v.normalizeLocal();
float angle = v.angleBetween(uBase);// result between [0; PI]
if (v.x < 0) {// the angle should be greater than PI, we're on the other part of the image then
angle = FastMath.TWO_PI - angle;
}
uvCoordinates[j] = angle / FastMath.TWO_PI;
// calculating V
float y = positions[i + 1];
uvCoordinates[j + 1] = (y - vBase) / bt.getHeight();
}
// looking for splitted triangles
Triangle triangle = new Triangle();
for (int i = 0; i < positions.length; i += 9) {
triangle.set(0, positions[i], positions[i + 1], positions[i + 2]);
triangle.set(1, positions[i + 3], positions[i + 4], positions[i + 5]);
triangle.set(2, positions[i + 6], positions[i + 7], positions[i + 8]);
float sgn1 = Math.signum(triangle.get1().x - cx);
float sgn2 = Math.signum(triangle.get2().x - cx);
float sgn3 = Math.signum(triangle.get3().x - cx);
float xSideFactor = sgn1 + sgn2 + sgn3;
float ySideFactor = Math.signum(triangle.get1().z - cz) + Math.signum(triangle.get2().z - cz) + Math.signum(triangle.get3().z - cz);
if ((xSideFactor > -3 || xSideFactor < 3) && ySideFactor < 0) {// the triangle is on the splitting plane
if (sgn1 == 1.0f) {
uvCoordinates[i / 3 * 2] += 1.0f;
}
if (sgn2 == 1.0f) {
uvCoordinates[(i / 3 + 1) * 2] += 1.0f;
}
if (sgn3 == 1.0f) {
uvCoordinates[(i / 3 + 2) * 2] += 1.0f;
}
}
}
return uvCoordinates;
}
/**
* Sphere projection for 2D textures.
*
* @param positions
* points to be projected
* @param bb
* the bounding box for projecting
* @return UV coordinates after the projection
*/
public static float[] sphereProjection(float[] positions, BoundingSphere bs) {// TODO: rotate it to be vertical
float[] uvCoordinates = new float[positions.length / 3 * 2];
Vector3f v = new Vector3f();
float cx = bs.getCenter().x, cy = bs.getCenter().y, cz = bs.getCenter().z;
Vector3f uBase = new Vector3f(0, -1, 0);
Vector3f vBase = new Vector3f(0, 0, -1);
for (int i = 0, j = 0; i < positions.length; i += 3, j += 2) {
// calculating U
v.set(positions[i] - cx, positions[i + 1] - cy, 0);
v.normalizeLocal();
float angle = v.angleBetween(uBase);// result between [0; PI]
if (v.x < 0) {// the angle should be greater than PI, we're on the other part of the image then
angle = FastMath.TWO_PI - angle;
}
uvCoordinates[j] = angle / FastMath.TWO_PI;
// calculating V
v.set(positions[i] - cx, positions[i + 1] - cy, positions[i + 2] - cz);
v.normalizeLocal();
angle = v.angleBetween(vBase);// result between [0; PI]
uvCoordinates[j + 1] = angle / FastMath.PI;
}
// looking for splitted triangles
Triangle triangle = new Triangle();
for (int i = 0; i < positions.length; i += 9) {
triangle.set(0, positions[i], positions[i + 1], positions[i + 2]);
triangle.set(1, positions[i + 3], positions[i + 4], positions[i + 5]);
triangle.set(2, positions[i + 6], positions[i + 7], positions[i + 8]);
float sgn1 = Math.signum(triangle.get1().x - cx);
float sgn2 = Math.signum(triangle.get2().x - cx);
float sgn3 = Math.signum(triangle.get3().x - cx);
float xSideFactor = sgn1 + sgn2 + sgn3;
float ySideFactor = Math.signum(triangle.get1().y - cy) + Math.signum(triangle.get2().y - cy) + Math.signum(triangle.get3().y - cy);
if ((xSideFactor > -3 || xSideFactor < 3) && ySideFactor < 0) {// the triangle is on the splitting plane
if (sgn1 == 1.0f) {
uvCoordinates[i / 3 * 2] += 1.0f;
}
if (sgn2 == 1.0f) {
uvCoordinates[(i / 3 + 1) * 2] += 1.0f;
}
if (sgn3 == 1.0f) {
uvCoordinates[(i / 3 + 2) * 2] += 1.0f;
}
}
}
return uvCoordinates;
}
}
| apache-2.0 |
Nimco/sling | bundles/scripting/javascript/src/main/java/org/apache/sling/scripting/javascript/wrapper/ScriptableVersion.java | 1679 | /*
* 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.sling.scripting.javascript.wrapper;
import javax.jcr.version.Version;
/** Scriptable wrapper for the JCR Version class */
@SuppressWarnings("serial")
public class ScriptableVersion extends ScriptableNode {
public static final String CLASSNAME = "Version";
private static final Class<?> [] WRAPPED_CLASSES = { Version.class };
private Version version;
@Override
public void jsConstructor(Object res) {
super.jsConstructor(res);
version = (Version)res;
}
@Override
protected Class<?> getStaticType() {
return Version.class;
}
@Override
public String getClassName() {
return CLASSNAME;
}
@Override
public Class<?>[] getWrappedClasses() {
return WRAPPED_CLASSES;
}
@Override
protected Object getWrappedObject() {
return version;
}
} | apache-2.0 |
machine16/xerces-for-android | src/mf/org/apache/xerces/xni/XMLResourceIdentifier.java | 2296 | /*
* 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 mf.org.apache.xerces.xni;
/**
* <p> This represents the basic physical description of the location of any
* XML resource (a Schema grammar, a DTD, a general entity etc.) </p>
*
* @author Neil Graham, IBM
* @version $Id: XMLResourceIdentifier.java 570132 2007-08-27 14:12:43Z mrglavas $
*/
public interface XMLResourceIdentifier {
/** Sets the public identifier. */
public void setPublicId(String publicId);
/** Returns the public identifier. */
public String getPublicId();
/** Sets the expanded system identifier. */
public void setExpandedSystemId(String systemId);
/** Returns the expanded system identifier. */
public String getExpandedSystemId();
/** Sets the literal system identifier. */
public void setLiteralSystemId(String systemId);
/** Returns the literal system identifier. */
public String getLiteralSystemId();
/** Sets the base URI against which the literal SystemId is to be
resolved.*/
public void setBaseSystemId(String systemId);
/** <p> Returns the base URI against which the literal SystemId is to be
resolved. </p> */
public String getBaseSystemId();
/** Sets the namespace of the resource. */
public void setNamespace(String namespace);
/** Returns the namespace of the resource. */
public String getNamespace();
} // XMLResourceIdentifier
| apache-2.0 |
JetBrains/jdk8u_nashorn | src/jdk/nashorn/internal/runtime/events/RuntimeEvent.java | 2922 | /*
* Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.internal.runtime.events;
import java.util.logging.Level;
import jdk.nashorn.internal.objects.NativeDebug;
import jdk.nashorn.internal.runtime.options.Options;
/**
* Class for representing a runtime event, giving less global dependencies than logger.
* Every {@link NativeDebug} object keeps a queue of RuntimeEvents that can be explored
* through the debug API.
*
* @param <T> class of the value this event wraps
*/
public class RuntimeEvent<T> {
/** Queue size for the runtime event buffer */
public static final int RUNTIME_EVENT_QUEUE_SIZE = Options.getIntProperty("nashorn.runtime.event.queue.size", 1024);
private final Level level;
private final T value;
/**
* Constructor
*
* @param level log level for runtime event to create
* @param object object to wrap
*/
public RuntimeEvent(final Level level, final T object) {
this.level = level;
this.value = object;
}
/**
* Return the value wrapped in this runtime event
* @return value
*/
public final T getValue() {
return value;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append('[').
append(level).
append("] ").
append(value == null ? "null" : getValueClass().getSimpleName()).
append(" value=").
append(value);
return sb.toString();
}
/**
* Descriptor for this runtime event, must be overridden and
* implemented, e.g. "RewriteException"
* @return event name
*/
public final Class<?> getValueClass() {
return value.getClass();
}
}
| gpl-2.0 |
dennishuo/hadoop | hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/web/resources/ConcatSourcesParam.java | 1928 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hdfs.web.resources;
import org.apache.hadoop.fs.Path;
/** The concat source paths parameter. */
public class ConcatSourcesParam extends StringParam {
/** Parameter name. */
public static final String NAME = "sources";
public static final String DEFAULT = "";
private static final Domain DOMAIN = new Domain(NAME, null);
private static String paths2String(Path[] paths) {
if (paths == null || paths.length == 0) {
return "";
}
final StringBuilder b = new StringBuilder(paths[0].toUri().getPath());
for(int i = 1; i < paths.length; i++) {
b.append(',').append(paths[i].toUri().getPath());
}
return b.toString();
}
/**
* Constructor.
* @param str a string representation of the parameter value.
*/
public ConcatSourcesParam(String str) {
super(DOMAIN, str);
}
public ConcatSourcesParam(Path[] paths) {
this(paths2String(paths));
}
@Override
public String getName() {
return NAME;
}
/** @return the absolute path. */
public final String[] getAbsolutePaths() {
return getValue().split(",");
}
}
| apache-2.0 |
sintjuri/openmrs-core | web/src/main/java/org/openmrs/module/web/extension/UserOptionExtension.java | 999 | /**
* This Source Code Form is subject to the terms of the Mozilla Public License,
* v. 2.0. If a copy of the MPL was not distributed with this file, You can
* obtain one at http://mozilla.org/MPL/2.0/. OpenMRS is also distributed under
* the terms of the Healthcare Disclaimer located at http://openmrs.org/license.
*
* Copyright (C) OpenMRS Inc. OpenMRS is a registered trademark and the OpenMRS
* graphic logo is a trademark of OpenMRS Inc.
*/
package org.openmrs.module.web.extension;
public abstract class UserOptionExtension extends PortletExt {
/**
* page views are controlled by privileges. The user must have this privilege to be able to view
* @return the privilege name.
*/
public abstract String getRequiredPrivilege();
/**
* @return the tab unique name without spaces.
*/
public abstract String getTabId();
/**
* @return The visible name of this tab. This can return either a string or a spring message code
*/
public abstract String getTabName();
}
| mpl-2.0 |
thomasdarimont/keycloak | integration/admin-client/src/main/java/org/keycloak/admin/client/resource/AggregatePoliciesResource.java | 1650 | /*
* Copyright 2016 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.admin.client.resource;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
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.MediaType;
import javax.ws.rs.core.Response;
import org.jboss.resteasy.annotations.cache.NoCache;
import org.keycloak.representations.idm.authorization.AggregatePolicyRepresentation;
/**
* @author <a href="mailto:psilva@redhat.com">Pedro Igor</a>
*/
public interface AggregatePoliciesResource {
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
Response create(AggregatePolicyRepresentation representation);
@Path("{id}")
AggregatePolicyResource findById(@PathParam("id") String id);
@Path("/search")
@GET
@Produces(MediaType.APPLICATION_JSON)
@NoCache
AggregatePolicyRepresentation findByName(@QueryParam("name") String name);
}
| apache-2.0 |
PavelSozonov/JodaTimeTesting | src/test/java/org/joda/time/TestYearMonth_Properties.java | 15196 | /*
* Copyright 2001-2010 Stephen Colebourne
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.joda.time;
import java.util.Locale;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.joda.time.chrono.CopticChronology;
import org.joda.time.chrono.LenientChronology;
import org.joda.time.chrono.StrictChronology;
/**
* This class is a Junit unit test for YearMonth.
*
* @author Stephen Colebourne
*/
public class TestYearMonth_Properties extends TestCase {
private static final DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris");
private static final Chronology COPTIC_PARIS = CopticChronology.getInstance(PARIS);
private long TEST_TIME_NOW =
(31L + 28L + 31L + 30L + 31L + 9L -1L) * DateTimeConstants.MILLIS_PER_DAY;
private long TEST_TIME1 =
(31L + 28L + 31L + 6L -1L) * DateTimeConstants.MILLIS_PER_DAY
+ 12L * DateTimeConstants.MILLIS_PER_HOUR
+ 24L * DateTimeConstants.MILLIS_PER_MINUTE;
private long TEST_TIME2 =
(365L + 31L + 28L + 31L + 30L + 7L -1L) * DateTimeConstants.MILLIS_PER_DAY
+ 14L * DateTimeConstants.MILLIS_PER_HOUR
+ 28L * DateTimeConstants.MILLIS_PER_MINUTE;
private DateTimeZone zone = null;
private Locale systemDefaultLocale = null;
public static void main(String[] args) {
junit.textui.TestRunner.run(suite());
}
public static TestSuite suite() {
return new TestSuite(TestYearMonth_Properties.class);
}
public TestYearMonth_Properties(String name) {
super(name);
}
protected void setUp() throws Exception {
DateTimeUtils.setCurrentMillisFixed(TEST_TIME_NOW);
zone = DateTimeZone.getDefault();
DateTimeZone.setDefault(DateTimeZone.UTC);
systemDefaultLocale = Locale.getDefault();
Locale.setDefault(Locale.ENGLISH);
}
protected void tearDown() throws Exception {
DateTimeUtils.setCurrentMillisSystem();
DateTimeZone.setDefault(zone);
zone = null;
Locale.setDefault(systemDefaultLocale);
systemDefaultLocale = null;
}
//-----------------------------------------------------------------------
public void testPropertyGetYear() {
YearMonth test = new YearMonth(1972, 6);
assertSame(test.getChronology().year(), test.year().getField());
assertEquals("year", test.year().getName());
assertEquals("Property[year]", test.year().toString());
assertSame(test, test.year().getReadablePartial());
assertSame(test, test.year().getYearMonth());
assertEquals(1972, test.year().get());
assertEquals("1972", test.year().getAsString());
assertEquals("1972", test.year().getAsText());
assertEquals("1972", test.year().getAsText(Locale.FRENCH));
assertEquals("1972", test.year().getAsShortText());
assertEquals("1972", test.year().getAsShortText(Locale.FRENCH));
assertEquals(test.getChronology().years(), test.year().getDurationField());
assertEquals(null, test.year().getRangeDurationField());
assertEquals(9, test.year().getMaximumTextLength(null));
assertEquals(9, test.year().getMaximumShortTextLength(null));
}
public void testPropertyGetMaxMinValuesYear() {
YearMonth test = new YearMonth(1972, 6);
assertEquals(-292275054, test.year().getMinimumValue());
assertEquals(-292275054, test.year().getMinimumValueOverall());
assertEquals(292278993, test.year().getMaximumValue());
assertEquals(292278993, test.year().getMaximumValueOverall());
}
public void testPropertyAddYear() {
YearMonth test = new YearMonth(1972, 6);
YearMonth copy = test.year().addToCopy(9);
check(test, 1972, 6);
check(copy, 1981, 6);
copy = test.year().addToCopy(0);
check(copy, 1972, 6);
copy = test.year().addToCopy(292277023 - 1972);
check(copy, 292277023, 6);
try {
test.year().addToCopy(292278993 - 1972 + 1);
fail();
} catch (IllegalArgumentException ex) {}
check(test, 1972, 6);
copy = test.year().addToCopy(-1972);
check(copy, 0, 6);
copy = test.year().addToCopy(-1973);
check(copy, -1, 6);
try {
test.year().addToCopy(-292275054 - 1972 - 1);
fail();
} catch (IllegalArgumentException ex) {}
check(test, 1972, 6);
}
public void testPropertyAddWrapFieldYear() {
YearMonth test = new YearMonth(1972, 6);
YearMonth copy = test.year().addWrapFieldToCopy(9);
check(test, 1972, 6);
check(copy, 1981, 6);
copy = test.year().addWrapFieldToCopy(0);
check(copy, 1972, 6);
copy = test.year().addWrapFieldToCopy(292278993 - 1972 + 1);
check(copy, -292275054, 6);
copy = test.year().addWrapFieldToCopy(-292275054 - 1972 - 1);
check(copy, 292278993, 6);
}
public void testPropertySetYear() {
YearMonth test = new YearMonth(1972, 6);
YearMonth copy = test.year().setCopy(12);
check(test, 1972, 6);
check(copy, 12, 6);
}
public void testPropertySetTextYear() {
YearMonth test = new YearMonth(1972, 6);
YearMonth copy = test.year().setCopy("12");
check(test, 1972, 6);
check(copy, 12, 6);
}
public void testPropertyCompareToYear() {
YearMonth test1 = new YearMonth(TEST_TIME1);
YearMonth test2 = new YearMonth(TEST_TIME2);
assertEquals(true, test1.year().compareTo(test2) < 0);
assertEquals(true, test2.year().compareTo(test1) > 0);
assertEquals(true, test1.year().compareTo(test1) == 0);
try {
test1.year().compareTo((ReadablePartial) null);
fail();
} catch (IllegalArgumentException ex) {}
DateTime dt1 = new DateTime(TEST_TIME1);
DateTime dt2 = new DateTime(TEST_TIME2);
assertEquals(true, test1.year().compareTo(dt2) < 0);
assertEquals(true, test2.year().compareTo(dt1) > 0);
assertEquals(true, test1.year().compareTo(dt1) == 0);
try {
test1.year().compareTo((ReadableInstant) null);
fail();
} catch (IllegalArgumentException ex) {}
}
//-----------------------------------------------------------------------
public void testPropertyGetMonth() {
YearMonth test = new YearMonth(1972, 6);
assertSame(test.getChronology().monthOfYear(), test.monthOfYear().getField());
assertEquals("monthOfYear", test.monthOfYear().getName());
assertEquals("Property[monthOfYear]", test.monthOfYear().toString());
assertSame(test, test.monthOfYear().getReadablePartial());
assertSame(test, test.monthOfYear().getYearMonth());
assertEquals(6, test.monthOfYear().get());
assertEquals("6", test.monthOfYear().getAsString());
assertEquals("June", test.monthOfYear().getAsText());
assertEquals("juin", test.monthOfYear().getAsText(Locale.FRENCH));
assertEquals("Jun", test.monthOfYear().getAsShortText());
assertEquals("juin", test.monthOfYear().getAsShortText(Locale.FRENCH));
assertEquals(test.getChronology().months(), test.monthOfYear().getDurationField());
assertEquals(test.getChronology().years(), test.monthOfYear().getRangeDurationField());
assertEquals(9, test.monthOfYear().getMaximumTextLength(null));
assertEquals(3, test.monthOfYear().getMaximumShortTextLength(null));
test = new YearMonth(1972, 7);
assertEquals("juillet", test.monthOfYear().getAsText(Locale.FRENCH));
assertEquals("juil.", test.monthOfYear().getAsShortText(Locale.FRENCH));
}
public void testPropertyGetMaxMinValuesMonth() {
YearMonth test = new YearMonth(1972, 6);
assertEquals(1, test.monthOfYear().getMinimumValue());
assertEquals(1, test.monthOfYear().getMinimumValueOverall());
assertEquals(12, test.monthOfYear().getMaximumValue());
assertEquals(12, test.monthOfYear().getMaximumValueOverall());
}
public void testPropertyAddMonth() {
YearMonth test = new YearMonth(1972, 6);
YearMonth copy = test.monthOfYear().addToCopy(6);
check(test, 1972, 6);
check(copy, 1972, 12);
copy = test.monthOfYear().addToCopy(7);
check(copy, 1973, 1);
copy = test.monthOfYear().addToCopy(-5);
check(copy, 1972, 1);
copy = test.monthOfYear().addToCopy(-6);
check(copy, 1971, 12);
}
public void testPropertyAddWrapFieldMonth() {
YearMonth test = new YearMonth(1972, 6);
YearMonth copy = test.monthOfYear().addWrapFieldToCopy(4);
check(test, 1972, 6);
check(copy, 1972, 10);
copy = test.monthOfYear().addWrapFieldToCopy(8);
check(copy, 1972, 2);
copy = test.monthOfYear().addWrapFieldToCopy(-8);
check(copy, 1972, 10);
}
public void testPropertySetMonth() {
YearMonth test = new YearMonth(1972, 6);
YearMonth copy = test.monthOfYear().setCopy(12);
check(test, 1972, 6);
check(copy, 1972, 12);
try {
test.monthOfYear().setCopy(13);
fail();
} catch (IllegalArgumentException ex) {}
try {
test.monthOfYear().setCopy(0);
fail();
} catch (IllegalArgumentException ex) {}
}
public void testPropertySetTextMonth() {
YearMonth test = new YearMonth(1972, 6);
YearMonth copy = test.monthOfYear().setCopy("12");
check(test, 1972, 6);
check(copy, 1972, 12);
copy = test.monthOfYear().setCopy("December");
check(test, 1972, 6);
check(copy, 1972, 12);
copy = test.monthOfYear().setCopy("Dec");
check(test, 1972, 6);
check(copy, 1972, 12);
}
public void testPropertyCompareToMonth() {
YearMonth test1 = new YearMonth(TEST_TIME1);
YearMonth test2 = new YearMonth(TEST_TIME2);
assertEquals(true, test1.monthOfYear().compareTo(test2) < 0);
assertEquals(true, test2.monthOfYear().compareTo(test1) > 0);
assertEquals(true, test1.monthOfYear().compareTo(test1) == 0);
try {
test1.monthOfYear().compareTo((ReadablePartial) null);
fail();
} catch (IllegalArgumentException ex) {}
DateTime dt1 = new DateTime(TEST_TIME1);
DateTime dt2 = new DateTime(TEST_TIME2);
assertEquals(true, test1.monthOfYear().compareTo(dt2) < 0);
assertEquals(true, test2.monthOfYear().compareTo(dt1) > 0);
assertEquals(true, test1.monthOfYear().compareTo(dt1) == 0);
try {
test1.monthOfYear().compareTo((ReadableInstant) null);
fail();
} catch (IllegalArgumentException ex) {}
}
//-----------------------------------------------------------------------
public void testPropertyEquals() {
YearMonth test1 = new YearMonth(11, 11);
YearMonth test2 = new YearMonth(11, 12);
YearMonth test3 = new YearMonth(11, 11, CopticChronology.getInstanceUTC());
assertEquals(true, test1.monthOfYear().equals(test1.monthOfYear()));
assertEquals(false, test1.monthOfYear().equals(test1.year()));
assertEquals(false, test1.monthOfYear().equals(test2.monthOfYear()));
assertEquals(false, test1.monthOfYear().equals(test2.year()));
assertEquals(false, test1.year().equals(test1.monthOfYear()));
assertEquals(true, test1.year().equals(test1.year()));
assertEquals(false, test1.year().equals(test2.monthOfYear()));
assertEquals(true, test1.year().equals(test2.year()));
assertEquals(false, test1.monthOfYear().equals(null));
assertEquals(false, test1.monthOfYear().equals("any"));
// chrono
assertEquals(false, test1.monthOfYear().equals(test3.monthOfYear()));
}
public void testPropertyHashCode() {
YearMonth test1 = new YearMonth(2005, 11);
YearMonth test2 = new YearMonth(2005, 12);
assertEquals(true, test1.monthOfYear().hashCode() == test1.monthOfYear().hashCode());
assertEquals(false, test1.monthOfYear().hashCode() == test2.monthOfYear().hashCode());
assertEquals(true, test1.year().hashCode() == test1.year().hashCode());
assertEquals(true, test1.year().hashCode() == test2.year().hashCode());
}
public void testPropertyEqualsHashCodeLenient() {
YearMonth test1 = new YearMonth(1970, 6, LenientChronology.getInstance(COPTIC_PARIS));
YearMonth test2 = new YearMonth(1970, 6, LenientChronology.getInstance(COPTIC_PARIS));
assertEquals(true, test1.monthOfYear().equals(test2.monthOfYear()));
assertEquals(true, test2.monthOfYear().equals(test1.monthOfYear()));
assertEquals(true, test1.monthOfYear().equals(test1.monthOfYear()));
assertEquals(true, test2.monthOfYear().equals(test2.monthOfYear()));
assertEquals(true, test1.monthOfYear().hashCode() == test2.monthOfYear().hashCode());
assertEquals(true, test1.monthOfYear().hashCode() == test1.monthOfYear().hashCode());
assertEquals(true, test2.monthOfYear().hashCode() == test2.monthOfYear().hashCode());
}
public void testPropertyEqualsHashCodeStrict() {
YearMonth test1 = new YearMonth(1970, 6, StrictChronology.getInstance(COPTIC_PARIS));
YearMonth test2 = new YearMonth(1970, 6, StrictChronology.getInstance(COPTIC_PARIS));
assertEquals(true, test1.monthOfYear().equals(test2.monthOfYear()));
assertEquals(true, test2.monthOfYear().equals(test1.monthOfYear()));
assertEquals(true, test1.monthOfYear().equals(test1.monthOfYear()));
assertEquals(true, test2.monthOfYear().equals(test2.monthOfYear()));
assertEquals(true, test1.monthOfYear().hashCode() == test2.monthOfYear().hashCode());
assertEquals(true, test1.monthOfYear().hashCode() == test1.monthOfYear().hashCode());
assertEquals(true, test2.monthOfYear().hashCode() == test2.monthOfYear().hashCode());
}
//-----------------------------------------------------------------------
private void check(YearMonth test, int year, int month) {
assertEquals(year, test.getYear());
assertEquals(month, test.getMonthOfYear());
}
}
| apache-2.0 |
olezhuravlev/spring-security | web/src/main/java/org/springframework/security/web/authentication/rememberme/JdbcTokenRepositoryImpl.java | 5063 | /*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.web.authentication.rememberme;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.dao.IncorrectResultSizeDataAccessException;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
/**
* JDBC based persistent login token repository implementation.
*
* @author Luke Taylor
* @since 2.0
*/
public class JdbcTokenRepositoryImpl extends JdbcDaoSupport implements
PersistentTokenRepository {
// ~ Static fields/initializers
// =====================================================================================
/** Default SQL for creating the database table to store the tokens */
public static final String CREATE_TABLE_SQL = "create table persistent_logins (username varchar(64) not null, series varchar(64) primary key, "
+ "token varchar(64) not null, last_used timestamp not null)";
/** The default SQL used by the <tt>getTokenBySeries</tt> query */
public static final String DEF_TOKEN_BY_SERIES_SQL = "select username,series,token,last_used from persistent_logins where series = ?";
/** The default SQL used by <tt>createNewToken</tt> */
public static final String DEF_INSERT_TOKEN_SQL = "insert into persistent_logins (username, series, token, last_used) values(?,?,?,?)";
/** The default SQL used by <tt>updateToken</tt> */
public static final String DEF_UPDATE_TOKEN_SQL = "update persistent_logins set token = ?, last_used = ? where series = ?";
/** The default SQL used by <tt>removeUserTokens</tt> */
public static final String DEF_REMOVE_USER_TOKENS_SQL = "delete from persistent_logins where username = ?";
// ~ Instance fields
// ================================================================================================
private String tokensBySeriesSql = DEF_TOKEN_BY_SERIES_SQL;
private String insertTokenSql = DEF_INSERT_TOKEN_SQL;
private String updateTokenSql = DEF_UPDATE_TOKEN_SQL;
private String removeUserTokensSql = DEF_REMOVE_USER_TOKENS_SQL;
private boolean createTableOnStartup;
protected void initDao() {
if (createTableOnStartup) {
getJdbcTemplate().execute(CREATE_TABLE_SQL);
}
}
public void createNewToken(PersistentRememberMeToken token) {
getJdbcTemplate().update(insertTokenSql, token.getUsername(), token.getSeries(),
token.getTokenValue(), token.getDate());
}
public void updateToken(String series, String tokenValue, Date lastUsed) {
getJdbcTemplate().update(updateTokenSql, tokenValue, lastUsed, series);
}
/**
* Loads the token data for the supplied series identifier.
*
* If an error occurs, it will be reported and null will be returned (since the result
* should just be a failed persistent login).
*
* @param seriesId
* @return the token matching the series, or null if no match found or an exception
* occurred.
*/
public PersistentRememberMeToken getTokenForSeries(String seriesId) {
try {
return getJdbcTemplate().queryForObject(tokensBySeriesSql,
new RowMapper<PersistentRememberMeToken>() {
public PersistentRememberMeToken mapRow(ResultSet rs, int rowNum)
throws SQLException {
return new PersistentRememberMeToken(rs.getString(1), rs
.getString(2), rs.getString(3), rs.getTimestamp(4));
}
}, seriesId);
}
catch (EmptyResultDataAccessException zeroResults) {
if (logger.isDebugEnabled()) {
logger.debug("Querying token for series '" + seriesId
+ "' returned no results.", zeroResults);
}
}
catch (IncorrectResultSizeDataAccessException moreThanOne) {
logger.error("Querying token for series '" + seriesId
+ "' returned more than one value. Series" + " should be unique");
}
catch (DataAccessException e) {
logger.error("Failed to load token for series " + seriesId, e);
}
return null;
}
public void removeUserTokens(String username) {
getJdbcTemplate().update(removeUserTokensSql, username);
}
/**
* Intended for convenience in debugging. Will create the persistent_tokens database
* table when the class is initialized during the initDao method.
*
* @param createTableOnStartup set to true to execute the
*/
public void setCreateTableOnStartup(boolean createTableOnStartup) {
this.createTableOnStartup = createTableOnStartup;
}
}
| apache-2.0 |
akosyakov/intellij-community | platform/lang-impl/src/com/intellij/application/options/colors/OptionsPanelImpl.java | 6414 | /*
* 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.application.options.colors;
import com.intellij.ide.DataManager;
import com.intellij.ide.util.PropertiesComponent;
import com.intellij.openapi.options.SearchableConfigurable;
import com.intellij.openapi.options.ex.Settings;
import com.intellij.openapi.util.ActionCallback;
import com.intellij.ui.ScrollPaneFactory;
import com.intellij.util.EventDispatcher;
import com.intellij.util.ui.JBUI;
import javax.swing.*;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.Element;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.util.HashSet;
import java.util.Set;
public class OptionsPanelImpl extends JPanel implements OptionsPanel {
public static final String SELECTED_COLOR_OPTION_PROPERTY = "selected.color.option.type";
private final ColorOptionsTree myOptionsTree;
private final ColorAndFontDescriptionPanel myOptionsPanel;
private final ColorAndFontOptions myOptions;
private final SchemesPanel mySchemesProvider;
private final String myCategoryName;
private final PropertiesComponent myProperties;
private final EventDispatcher<ColorAndFontSettingsListener> myDispatcher = EventDispatcher.create(ColorAndFontSettingsListener.class);
public OptionsPanelImpl(ColorAndFontOptions options,
SchemesPanel schemesProvider,
String categoryName) {
super(new BorderLayout());
myOptions = options;
mySchemesProvider = schemesProvider;
myCategoryName = categoryName;
myProperties = PropertiesComponent.getInstance();
myOptionsPanel = new ColorAndFontDescriptionPanel() {
@Override
protected void onSettingsChanged(ActionEvent e) {
super.onSettingsChanged(e);
myDispatcher.getMulticaster().settingsChanged();
}
@Override
protected void onHyperLinkClicked(HyperlinkEvent e) {
if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
Settings settings = Settings.KEY.getData(DataManager.getInstance().getDataContext(OptionsPanelImpl.this));
String attrName = e.getDescription();
Element element = e.getSourceElement();
String pageName;
try {
pageName = element.getDocument().getText(element.getStartOffset(), element.getEndOffset() - element.getStartOffset());
}
catch (BadLocationException e1) {
return;
}
final SearchableConfigurable page = myOptions.findSubConfigurable(pageName);
if (page != null && settings != null) {
Runnable runnable = page.enableSearch(attrName);
ActionCallback callback = settings.select(page);
if (runnable != null) callback.doWhenDone(runnable);
}
}
}
};
myOptionsTree = new ColorOptionsTree(myCategoryName);
myOptionsTree.addTreeSelectionListener(new TreeSelectionListener() {
@Override
public void valueChanged(TreeSelectionEvent e) {
if (!mySchemesProvider.areSchemesLoaded()) return;
processListValueChanged();
}
});
JScrollPane scrollPane = ScrollPaneFactory.createScrollPane(myOptionsTree);
scrollPane.setPreferredSize(JBUI.size(230, 60));
JPanel north = new JPanel(new BorderLayout());
north.add(scrollPane, BorderLayout.CENTER);
north.add(myOptionsPanel, BorderLayout.EAST);
add(north, BorderLayout.NORTH);
}
@Override
public void addListener(ColorAndFontSettingsListener listener) {
myDispatcher.addListener(listener);
}
private void processListValueChanged() {
Object selectedValue = myOptionsTree.getSelectedValue();
ColorAndFontDescription description = selectedValue instanceof ColorAndFontDescription ? (ColorAndFontDescription)selectedValue : null;
if (description == null) {
if (selectedValue == null) {
String preselectedType = myProperties.getValue(SELECTED_COLOR_OPTION_PROPERTY);
if (preselectedType != null) {
myOptionsTree.selectOptionByType(preselectedType);
description = myOptionsTree.getSelectedDescriptor();
}
}
}
if (description != null) {
myProperties.setValue(SELECTED_COLOR_OPTION_PROPERTY, description.getType());
myOptionsPanel.reset(description);
myDispatcher.getMulticaster().selectedOptionChanged(description);
}
else {
myOptionsPanel.resetDefault();
}
}
private void fillOptionsList() {
myOptionsTree.fillOptions(myOptions);
}
@Override
public JPanel getPanel() {
return this;
}
@Override
public void updateOptionsList() {
fillOptionsList();
processListValueChanged();
}
@Override
public Runnable showOption(final String attributeDisplayName) {
return new Runnable() {
@Override
public void run() {
myOptionsTree.selectOptionByName(attributeDisplayName);
}
};
}
@Override
public void applyChangesToScheme() {
ColorAndFontDescription descriptor = myOptionsTree.getSelectedDescriptor();
if (descriptor != null) {
myOptionsPanel.apply(descriptor, myOptions.getSelectedScheme());
}
}
@Override
public void selectOption(String attributeType) {
myOptionsTree.selectOptionByType(attributeType);
}
@Override
public Set<String> processListOptions() {
HashSet<String> result = new HashSet<String>();
EditorSchemeAttributeDescriptor[] descriptions = myOptions.getCurrentDescriptions();
for (EditorSchemeAttributeDescriptor description : descriptions) {
if (description.getGroup().equals(myCategoryName)) {
result.add(description.toString());
}
}
return result;
}
}
| apache-2.0 |
paulirwin/Stanford.NER.Net | stanford-ner-3.2.0-sources/edu/stanford/nlp/stats/MultiClassPrecisionRecallStats.java | 7768 | package edu.stanford.nlp.stats;
import edu.stanford.nlp.classify.Classifier;
import edu.stanford.nlp.classify.GeneralDataset;
import edu.stanford.nlp.classify.ProbabilisticClassifier;
import edu.stanford.nlp.ling.Datum;
import edu.stanford.nlp.util.HashIndex;
import edu.stanford.nlp.util.Index;
import edu.stanford.nlp.util.Triple;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
/**
* @author Jenny Finkel
*/
public class MultiClassPrecisionRecallStats<L> implements Scorer<L> {
/**
* Count of true positives.
*/
protected int[] tpCount;
/**
* Count of false positives.
*/
protected int[] fpCount;
/**
* Count of false negatives.
*/
protected int[] fnCount;
protected Index<L> labelIndex;
protected L negLabel;
protected int negIndex = -1;
public <F> MultiClassPrecisionRecallStats(Classifier<L,F> classifier, GeneralDataset<L,F> data, L negLabel)
{
this.negLabel = negLabel;
score(classifier, data);
}
public MultiClassPrecisionRecallStats(L negLabel)
{
this.negLabel = negLabel;
}
public L getNegLabel() {
return negLabel;
}
public <F> double score(ProbabilisticClassifier<L,F> classifier, GeneralDataset<L,F> data) {
return score((Classifier<L,F>)classifier, data);
}
public <F> double score(Classifier<L,F> classifier, GeneralDataset<L,F> data) {
List<L> guesses = new ArrayList<L>();
List<L> labels = new ArrayList<L>();
for (int i = 0; i < data.size(); i++) {
Datum<L, F> d = data.getRVFDatum(i);
L guess = classifier.classOf(d);
guesses.add(guess);
}
int[] labelsArr = data.getLabelsArray();
labelIndex = data.labelIndex;
for (int i = 0; i < data.size(); i++) {
labels.add(labelIndex.get(labelsArr[i]));
}
labelIndex = new HashIndex<L>();
labelIndex.addAll(data.labelIndex().objectsList());
labelIndex.addAll(classifier.labels());
int numClasses = labelIndex.size();
tpCount = new int[numClasses];
fpCount = new int[numClasses];
fnCount = new int[numClasses];
negIndex = labelIndex.indexOf(negLabel);
for (int i=0; i < guesses.size(); ++i)
{
L guess = guesses.get(i);
int guessIndex = labelIndex.indexOf(guess);
L label = labels.get(i);
int trueIndex = labelIndex.indexOf(label);
if (guessIndex == trueIndex) {
if (guessIndex != negIndex) {
tpCount[guessIndex]++;
}
} else {
if (guessIndex != negIndex) {
fpCount[guessIndex]++;
}
if (trueIndex != negIndex) {
fnCount[trueIndex]++;
}
}
}
return getFMeasure();
}
/**
* Returns the current precision: <tt>tp/(tp+fp)</tt>.
* Returns 1.0 if tp and fp are both 0.
*/
public Triple<Double, Integer, Integer> getPrecisionInfo(L label) {
int i = labelIndex.indexOf(label);
if (tpCount[i] == 0 && fpCount[i] == 0) {
return new Triple<Double, Integer, Integer>(1.0, tpCount[i], fpCount[i]);
}
return new Triple<Double, Integer, Integer>((((double) tpCount[i]) / (tpCount[i] + fpCount[i])), tpCount[i], fpCount[i]);
}
public double getPrecision(L label) {
return getPrecisionInfo(label).first();
}
public Triple<Double, Integer, Integer> getPrecisionInfo() {
int tp = 0, fp = 0;
for (int i = 0; i < labelIndex.size(); i++) {
if (i == negIndex) { continue; }
tp += tpCount[i];
fp += fpCount[i];
}
return new Triple<Double, Integer, Integer>((((double) tp) / (tp + fp)), tp, fp);
}
public double getPrecision() {
return getPrecisionInfo().first();
}
/**
* Returns a String summarizing precision that will print nicely.
*/
public String getPrecisionDescription(int numDigits) {
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setMaximumFractionDigits(numDigits);
Triple<Double, Integer, Integer> prec = getPrecisionInfo();
return nf.format(prec.first()) + " (" + prec.second() + "/" + (prec.second() + prec.third()) + ")";
}
public String getPrecisionDescription(int numDigits, L label) {
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setMaximumFractionDigits(numDigits);
Triple<Double, Integer, Integer> prec = getPrecisionInfo(label);
return nf.format(prec.first()) + " (" + prec.second() + "/" + (prec.second() + prec.third()) + ")";
}
public Triple<Double, Integer, Integer> getRecallInfo(L label) {
int i = labelIndex.indexOf(label);
if (tpCount[i] == 0 && fnCount[i] == 0) {
return new Triple<Double, Integer, Integer>(1.0, tpCount[i], fnCount[i]);
}
return new Triple<Double, Integer, Integer>((((double) tpCount[i]) / (tpCount[i] + fnCount[i])), tpCount[i], fnCount[i]);
}
public double getRecall(L label) {
return getRecallInfo(label).first();
}
public Triple<Double, Integer, Integer> getRecallInfo() {
int tp = 0, fn = 0;
for (int i = 0; i < labelIndex.size(); i++) {
if (i == negIndex) { continue; }
tp += tpCount[i];
fn += fnCount[i];
}
return new Triple<Double, Integer, Integer>((((double) tp) / (tp + fn)), tp, fn);
}
public double getRecall() {
return getRecallInfo().first();
}
/**
* Returns a String summarizing precision that will print nicely.
*/
public String getRecallDescription(int numDigits) {
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setMaximumFractionDigits(numDigits);
Triple<Double, Integer, Integer> recall = getRecallInfo();
return nf.format(recall.first()) + " (" + recall.second() + "/" + (recall.second() + recall.third()) + ")";
}
public String getRecallDescription(int numDigits, L label) {
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setMaximumFractionDigits(numDigits);
Triple<Double, Integer, Integer> recall = getRecallInfo(label);
return nf.format(recall.first()) + " (" + recall.second() + "/" + (recall.second() + recall.third()) + ")";
}
public double getFMeasure(L label) {
double p = getPrecision(label);
double r = getRecall(label);
double f = (2 * p * r) / (p + r);
return f;
}
public double getFMeasure() {
double p = getPrecision();
double r = getRecall();
double f = (2 * p * r) / (p + r);
return f;
}
/**
* Returns a String summarizing F1 that will print nicely.
*/
public String getF1Description(int numDigits) {
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setMaximumFractionDigits(numDigits);
return nf.format(getFMeasure());
}
public String getF1Description(int numDigits, L label) {
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setMaximumFractionDigits(numDigits);
return nf.format(getFMeasure(label));
}
/**
* Returns a String summarizing F1 that will print nicely.
*/
public String getDescription(int numDigits) {
StringBuffer sb = new StringBuffer();
sb.append("--- PR Stats ---").append("\n");
for (L label : labelIndex) {
if (label == null || label.equals(negLabel)) { continue; }
sb.append("** ").append(label.toString()).append(" **\n");
sb.append("\tPrec: ").append(getPrecisionDescription(numDigits, label)).append("\n");
sb.append("\tRecall: ").append(getRecallDescription(numDigits, label)).append("\n");
sb.append("\tF1: ").append(getF1Description(numDigits, label)).append("\n");
}
sb.append("** Overall **\n");
sb.append("\tPrec: ").append(getPrecisionDescription(numDigits)).append("\n");
sb.append("\tRecall: ").append(getRecallDescription(numDigits)).append("\n");
sb.append("\tF1: ").append(getF1Description(numDigits));
return sb.toString();
}
}
| gpl-2.0 |
kdwink/intellij-community | java/java-impl/src/com/intellij/refactoring/rename/RenameJavaClassProcessor.java | 16477 | /*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.refactoring.rename;
import com.intellij.codeInsight.ChangeContextUtil;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Pair;
import com.intellij.psi.*;
import com.intellij.psi.impl.light.LightElement;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.LocalSearchScope;
import com.intellij.psi.search.SearchScope;
import com.intellij.psi.search.searches.ClassInheritorsSearch;
import com.intellij.psi.search.searches.ReferencesSearch;
import com.intellij.psi.util.ClassUtil;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtilCore;
import com.intellij.refactoring.HelpID;
import com.intellij.refactoring.JavaRefactoringSettings;
import com.intellij.refactoring.RefactoringBundle;
import com.intellij.refactoring.listeners.RefactoringElementListener;
import com.intellij.refactoring.util.MoveRenameUsageInfo;
import com.intellij.refactoring.util.RefactoringUIUtil;
import com.intellij.refactoring.util.RefactoringUtil;
import com.intellij.usageView.UsageInfo;
import com.intellij.util.ArrayUtilRt;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.Processor;
import com.intellij.util.containers.MultiMap;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
import java.util.regex.Pattern;
/**
* @author yole
*/
public class RenameJavaClassProcessor extends RenamePsiElementProcessor {
private static final Logger LOG = Logger.getInstance("#com.intellij.refactoring.rename.RenameJavaClassProcessor");
public boolean canProcessElement(@NotNull final PsiElement element) {
return element instanceof PsiClass;
}
public void renameElement(final PsiElement element,
final String newName,
final UsageInfo[] usages,
@Nullable RefactoringElementListener listener) throws IncorrectOperationException {
PsiClass aClass = (PsiClass) element;
ArrayList<UsageInfo> postponedCollisions = new ArrayList<UsageInfo>();
List<MemberHidesOuterMemberUsageInfo> hidesOut = new ArrayList<MemberHidesOuterMemberUsageInfo>();
// rename all references
for (final UsageInfo usage : usages) {
if (usage instanceof ResolvableCollisionUsageInfo) {
if (usage instanceof CollidingClassImportUsageInfo) {
((CollidingClassImportUsageInfo)usage).getImportStatement().delete();
} else if (usage instanceof MemberHidesOuterMemberUsageInfo) {
final PsiElement usageElement = usage.getElement();
final PsiJavaCodeReferenceElement collidingRef = (PsiJavaCodeReferenceElement)usageElement;
if (collidingRef != null) {
hidesOut.add(new MemberHidesOuterMemberUsageInfo(usageElement, (PsiClass)collidingRef.resolve()));
}
}
else {
postponedCollisions.add(usage);
}
}
}
// do actual rename
ChangeContextUtil.encodeContextInfo(aClass.getContainingFile(), true, false);
aClass.setName(newName);
for (UsageInfo usage : usages) {
if (!(usage instanceof ResolvableCollisionUsageInfo)) {
final PsiReference ref = usage.getReference();
if (ref == null) continue;
try {
ref.bindToElement(aClass);
}
catch (IncorrectOperationException e) {//fall back to old scheme
ref.handleElementRename(newName);
}
}
}
ChangeContextUtil.decodeContextInfo(aClass.getContainingFile(), null, null); //to make refs to other classes from this one resolve to their old referent
// resolve collisions
for (UsageInfo postponedCollision : postponedCollisions) {
ClassHidesImportedClassUsageInfo collision = (ClassHidesImportedClassUsageInfo) postponedCollision;
collision.resolveCollision();
}
for (MemberHidesOuterMemberUsageInfo usage : hidesOut) {
PsiJavaCodeReferenceElement collidingRef = (PsiJavaCodeReferenceElement)usage.getElement();
PsiMember member = (PsiMember)usage.getReferencedElement();
if (collidingRef != null && collidingRef.isValid() && member != null && member.isValid()) {
final PsiManager manager = member.getManager();
final PsiElementFactory factory = JavaPsiFacade.getElementFactory(member.getProject());
final String name = member.getName();
final PsiClass containingClass = member.getContainingClass();
if (name != null && containingClass != null) {
if (manager.areElementsEquivalent(factory.createReferenceFromText(name, collidingRef).resolve(), member)) continue;
final PsiJavaCodeReferenceElement ref = factory.createReferenceFromText("A." + name, collidingRef);
final PsiJavaCodeReferenceElement qualifier = (PsiJavaCodeReferenceElement)ref.getQualifier();
LOG.assertTrue(qualifier != null);
final PsiJavaCodeReferenceElement classReference = factory.createClassReferenceElement(containingClass);
qualifier.replace(classReference);
collidingRef.replace(ref);
}
}
}
if (listener != null) {
listener.elementRenamed(aClass);
}
}
@Nullable
public Pair<String, String> getTextOccurrenceSearchStrings(@NotNull final PsiElement element, @NotNull final String newName) {
if (element instanceof PsiClass) {
final PsiClass aClass = (PsiClass)element;
if (aClass.getParent() instanceof PsiClass) {
final String dollaredStringToSearch = ClassUtil.getJVMClassName(aClass);
final String dollaredStringToReplace = dollaredStringToSearch == null ? null : RefactoringUtil.getNewInnerClassName(aClass, dollaredStringToSearch, newName);
if (dollaredStringToReplace != null) {
return Pair.create(dollaredStringToSearch, dollaredStringToReplace);
}
}
}
return null;
}
public String getQualifiedNameAfterRename(final PsiElement element, final String newName, final boolean nonJava) {
if (nonJava) {
final PsiClass aClass = (PsiClass)element;
return PsiUtilCore.getQualifiedNameAfterRename(aClass.getQualifiedName(), newName);
}
else {
return newName;
}
}
@Override
public void prepareRenaming(PsiElement element, String newName, Map<PsiElement, String> allRenames, SearchScope scope) {
final PsiMethod[] constructors = ((PsiClass) element).getConstructors();
for (PsiMethod constructor : constructors) {
if (constructor instanceof PsiMirrorElement) {
final PsiElement prototype = ((PsiMirrorElement)constructor).getPrototype();
if (prototype instanceof PsiNamedElement) {
allRenames.put(prototype, newName);
}
}
else if (!(constructor instanceof LightElement)) {
allRenames.put(constructor, newName);
}
}
}
public void findCollisions(final PsiElement element, final String newName, final Map<? extends PsiElement, String> allRenames, final List<UsageInfo> result) {
final PsiClass aClass = (PsiClass)element;
final ClassCollisionsDetector classCollisionsDetector = new ClassCollisionsDetector(aClass);
Collection<UsageInfo> initialResults = new ArrayList<UsageInfo>(result);
for(UsageInfo usageInfo: initialResults) {
if (usageInfo instanceof MoveRenameUsageInfo) {
classCollisionsDetector.addClassCollisions(usageInfo.getElement(), newName, result);
}
}
findSubmemberHidesMemberCollisions(aClass, newName, result);
if (aClass instanceof PsiTypeParameter) {
final PsiTypeParameterListOwner owner = ((PsiTypeParameter)aClass).getOwner();
if (owner != null) {
for (PsiTypeParameter typeParameter : owner.getTypeParameters()) {
if (Comparing.equal(newName, typeParameter.getName())) {
result.add(new UnresolvableCollisionUsageInfo(aClass, typeParameter) {
@Override
public String getDescription() {
return "There is already type parameter in " + RefactoringUIUtil.getDescription(aClass, false) + " with name " + newName;
}
});
}
}
}
}
}
public static void findSubmemberHidesMemberCollisions(final PsiClass aClass, final String newName, final List<UsageInfo> result) {
if (aClass.getParent() instanceof PsiClass) {
PsiClass parent = (PsiClass)aClass.getParent();
Collection<PsiClass> inheritors = ClassInheritorsSearch.search(parent, true).findAll();
for (PsiClass inheritor : inheritors) {
if (newName.equals(inheritor.getName())) {
final ClassCollisionsDetector classCollisionsDetector = new ClassCollisionsDetector(aClass);
for (PsiReference reference : ReferencesSearch.search(inheritor, new LocalSearchScope(inheritor))) {
classCollisionsDetector.addClassCollisions(reference.getElement(), newName, result);
}
}
PsiClass[] inners = inheritor.getInnerClasses();
for (PsiClass inner : inners) {
if (newName.equals(inner.getName())) {
result.add(new SubmemberHidesMemberUsageInfo(inner, aClass));
}
}
}
} else if (aClass instanceof PsiTypeParameter) {
final PsiTypeParameterListOwner owner = ((PsiTypeParameter)aClass).getOwner();
if (owner instanceof PsiClass) {
final PsiClass[] supers = ((PsiClass)owner).getSupers();
for (PsiClass superClass : supers) {
if (newName.equals(superClass.getName())) {
final ClassCollisionsDetector classCollisionsDetector = new ClassCollisionsDetector(aClass);
for (PsiReference reference : ReferencesSearch.search(superClass, new LocalSearchScope(superClass))) {
classCollisionsDetector.addClassCollisions(reference.getElement(), newName, result);
}
}
PsiClass[] inners = superClass.getInnerClasses();
for (final PsiClass inner : inners) {
if (newName.equals(inner.getName())) {
ReferencesSearch.search(inner).forEach(new Processor<PsiReference>() {
public boolean process(final PsiReference reference) {
PsiElement refElement = reference.getElement();
if (refElement instanceof PsiReferenceExpression && ((PsiReferenceExpression)refElement).isQualified()) return true;
MemberHidesOuterMemberUsageInfo info = new MemberHidesOuterMemberUsageInfo(refElement, aClass);
result.add(info);
return true;
}
});
}
}
}
}
}
}
private static class ClassCollisionsDetector {
final HashSet<PsiFile> myProcessedFiles = new HashSet<PsiFile>();
final PsiClass myRenamedClass;
private final String myRenamedClassQualifiedName;
public ClassCollisionsDetector(PsiClass renamedClass) {
myRenamedClass = renamedClass;
myRenamedClassQualifiedName = myRenamedClass.getQualifiedName();
}
public void addClassCollisions(PsiElement referenceElement, String newName, List<UsageInfo> results) {
final PsiResolveHelper resolveHelper = JavaPsiFacade.getInstance(referenceElement.getProject()).getResolveHelper();
final PsiClass aClass = resolveHelper.resolveReferencedClass(newName, referenceElement);
if (aClass == null) return;
if (aClass instanceof PsiTypeParameter && myRenamedClass instanceof PsiTypeParameter) {
final PsiTypeParameterListOwner member = PsiTreeUtil.getParentOfType(referenceElement, PsiTypeParameterListOwner.class);
if (member != null) {
final PsiTypeParameterList typeParameterList = member.getTypeParameterList();
if (typeParameterList != null && ArrayUtilRt.find(typeParameterList.getTypeParameters(), myRenamedClass) > -1) {
if (member.hasModifierProperty(PsiModifier.STATIC)) return;
}
}
}
final PsiFile containingFile = referenceElement.getContainingFile();
final String text = referenceElement.getText();
if (Comparing.equal(myRenamedClassQualifiedName, removeSpaces(text))) return;
if (myProcessedFiles.contains(containingFile)) return;
for (PsiReference reference : ReferencesSearch.search(aClass, new LocalSearchScope(containingFile))) {
final PsiElement collisionReferenceElement = reference.getElement();
if (collisionReferenceElement instanceof PsiJavaCodeReferenceElement) {
final PsiElement parent = collisionReferenceElement.getParent();
if (parent instanceof PsiImportStatement) {
results.add(new CollidingClassImportUsageInfo((PsiImportStatement)parent, myRenamedClass));
}
else {
if (aClass.getQualifiedName() != null) {
results.add(new ClassHidesImportedClassUsageInfo((PsiJavaCodeReferenceElement)collisionReferenceElement,
myRenamedClass, aClass));
}
else {
results.add(new ClassHidesUnqualifiableClassUsageInfo((PsiJavaCodeReferenceElement)collisionReferenceElement,
myRenamedClass, aClass));
}
}
}
}
myProcessedFiles.add(containingFile);
}
}
@NonNls private static final Pattern WHITE_SPACE_PATTERN = Pattern.compile("\\s");
private static String removeSpaces(String s) {
return WHITE_SPACE_PATTERN.matcher(s).replaceAll("");
}
public void findExistingNameConflicts(final PsiElement element, final String newName, final MultiMap<PsiElement,String> conflicts) {
if (element instanceof PsiCompiledElement) return;
final PsiClass aClass = (PsiClass)element;
if (newName.equals(aClass.getName())) return;
final PsiClass containingClass = aClass.getContainingClass();
if (containingClass != null) { // innerClass
PsiClass[] innerClasses = containingClass.getInnerClasses();
for (PsiClass innerClass : innerClasses) {
if (newName.equals(innerClass.getName())) {
conflicts.putValue(innerClass, RefactoringBundle.message("inner.class.0.is.already.defined.in.class.1", newName, containingClass.getQualifiedName()));
break;
}
}
}
else if (!(aClass instanceof PsiTypeParameter)) {
final String qualifiedNameAfterRename = PsiUtilCore.getQualifiedNameAfterRename(aClass.getQualifiedName(), newName);
Project project = element.getProject();
final PsiClass conflictingClass =
JavaPsiFacade.getInstance(project).findClass(qualifiedNameAfterRename, GlobalSearchScope.allScope(project));
if (conflictingClass != null) {
conflicts.putValue(conflictingClass, RefactoringBundle.message("class.0.already.exists", qualifiedNameAfterRename));
}
}
}
@Nullable
@NonNls
public String getHelpID(final PsiElement element) {
return HelpID.RENAME_CLASS;
}
public boolean isToSearchInComments(final PsiElement psiElement) {
return JavaRefactoringSettings.getInstance().RENAME_SEARCH_IN_COMMENTS_FOR_CLASS;
}
public void setToSearchInComments(final PsiElement element, final boolean enabled) {
JavaRefactoringSettings.getInstance().RENAME_SEARCH_IN_COMMENTS_FOR_CLASS = enabled;
}
public boolean isToSearchForTextOccurrences(final PsiElement element) {
return JavaRefactoringSettings.getInstance().RENAME_SEARCH_FOR_TEXT_FOR_CLASS;
}
public void setToSearchForTextOccurrences(final PsiElement element, final boolean enabled) {
JavaRefactoringSettings.getInstance().RENAME_SEARCH_FOR_TEXT_FOR_CLASS = enabled;
}
}
| apache-2.0 |
hongliangpan/manydesigns.cn | trunk/portofino-database/liquibase-core-2.0.5-sources/liquibase/database/jvm/SybaseConnection.java | 751 | package liquibase.database.jvm;
import liquibase.exception.DatabaseException;
import java.sql.Connection;
import java.sql.Savepoint;
/**
* A Sybase specific Delegate that removes the calls to commit
* and rollback as Sybase requires that autocommit be set to true.
*
* @author <a href="mailto:csuml@yahoo.co.uk">Paul Keeble</a>
*
*/
public class SybaseConnection extends JdbcConnection {
public SybaseConnection(Connection delegate) {
super(delegate);
}
@Override
public void commit() throws DatabaseException {
}
@Override
public void rollback() throws DatabaseException {
}
@Override
public void rollback(Savepoint savepoint) throws DatabaseException {
}
}
| lgpl-3.0 |
ahmadOwais/spring-security-oauth | spring-security-jwt/src/test/java/org/springframework/security/jwt/JwtSpecData.java | 1456 | /*
* Copyright 2006-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package org.springframework.security.jwt;
import java.math.BigInteger;
import org.springframework.security.jwt.crypto.cipher.RsaTestKeyData;
/**
* @author Luke Taylor
*/
public class JwtSpecData {
final static byte[] HMAC_KEY;
static {
int[] keyInts = new int[] {3, 35, 53, 75, 43, 15, 165, 188, 131, 126, 6, 101, 119, 123, 166, 143, 90, 179, 40, 230, 240, 84, 201, 40, 169, 15, 132, 178, 210, 80, 46, 191, 211, 251, 90, 146, 210, 6, 71, 239, 150, 138, 180, 195, 119, 98, 61, 34, 61, 46, 33, 114, 5, 46, 79, 8, 192, 205, 154, 245, 103, 208, 128, 163};
HMAC_KEY = new byte[keyInts.length];
for (int i=0; i < keyInts.length; i++) {
HMAC_KEY[i] = (byte)keyInts[i];
}
}
// RSA Key parts
static final BigInteger N = RsaTestKeyData.N;
static final BigInteger E = RsaTestKeyData.E;
static final BigInteger D = RsaTestKeyData.D;
}
| apache-2.0 |
jmandawg/camel | components/camel-netty4/src/test/java/org/apache/camel/component/netty4/Netty2978IssueTest.java | 4395 | /**
* 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.netty4;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.apache.camel.CamelContext;
import org.apache.camel.Endpoint;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.junit.Ignore;
import org.junit.Test;
/**
* @version
*/
@Ignore("This test can cause CI servers to hang")
public class Netty2978IssueTest extends BaseNettyTest {
@Test
public void testNetty2978() throws Exception {
CamelClient client = new CamelClient(context);
try {
for (int i = 0; i < 1000; i++) {
Object reply = client.lookup(i);
assertEquals("Bye " + i, reply);
}
} finally {
client.close();
}
}
@Test
public void testNetty2978Concurrent() throws Exception {
final CamelClient client = new CamelClient(context);
try {
final List<Callable<String>> callables = new ArrayList<Callable<String>>();
for (int count = 0; count < 1000; count++) {
final int i = count;
callables.add(new Callable<String>() {
public String call() {
return client.lookup(i);
}
});
}
final ExecutorService executorService = Executors.newFixedThreadPool(10);
final List<Future<String>> results = executorService.invokeAll(callables);
final Set<String> replies = new HashSet<String>();
for (Future<String> future : results) {
// wait at most 60 sec to not hang test
String reply = future.get(60, TimeUnit.SECONDS);
assertTrue(reply.startsWith("Bye "));
replies.add(reply);
}
// should be 1000 unique replies
assertEquals(1000, replies.size());
executorService.shutdownNow();
} finally {
client.close();
}
}
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
from("netty4:tcp://localhost:{{port}}?sync=true")
.process(new Processor() {
public void process(final Exchange exchange) {
String body = exchange.getIn().getBody(String.class);
exchange.getOut().setBody("Bye " + body);
}
});
}
};
}
private static final class CamelClient {
private final Endpoint endpoint;
private final ProducerTemplate producerTemplate;
CamelClient(CamelContext camelContext) {
this.endpoint = camelContext.getEndpoint("netty4:tcp://localhost:{{port}}?sync=true");
this.producerTemplate = camelContext.createProducerTemplate();
}
public void close() throws Exception {
producerTemplate.stop();
}
public String lookup(int num) {
return producerTemplate.requestBody(endpoint, num, String.class);
}
}
}
| apache-2.0 |
quangou365/sub | subadmin/src/main/java/com/thinkgem/jeesite/test/web/TestTreeController.java | 4415 | /**
* Copyright © 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.thinkgem.jeesite.test.web;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.test.entity.TestTree;
import com.thinkgem.jeesite.test.service.TestTreeService;
/**
* 树结构生成Controller
* @author ThinkGem
* @version 2015-04-06
*/
@Controller
@RequestMapping(value = "${adminPath}/test/testTree")
public class TestTreeController extends BaseController {
@Autowired
private TestTreeService testTreeService;
@ModelAttribute
public TestTree get(@RequestParam(required=false) String id) {
TestTree entity = null;
if (StringUtils.isNotBlank(id)){
entity = testTreeService.get(id);
}
if (entity == null){
entity = new TestTree();
}
return entity;
}
@RequiresPermissions("test:testTree:view")
@RequestMapping(value = {"list", ""})
public String list(TestTree testTree, HttpServletRequest request, HttpServletResponse response, Model model) {
List<TestTree> list = testTreeService.findList(testTree);
model.addAttribute("list", list);
return "jeesite/test/testTreeList";
}
@RequiresPermissions("test:testTree:view")
@RequestMapping(value = "form")
public String form(TestTree testTree, Model model) {
if (testTree.getParent()!=null && StringUtils.isNotBlank(testTree.getParent().getId())){
testTree.setParent(testTreeService.get(testTree.getParent().getId()));
// 获取排序号,最末节点排序号+30
if (StringUtils.isBlank(testTree.getId())){
TestTree testTreeChild = new TestTree();
testTreeChild.setParent(new TestTree(testTree.getParent().getId()));
List<TestTree> list = testTreeService.findList(testTree);
if (list.size() > 0){
testTree.setSort(list.get(list.size()-1).getSort());
if (testTree.getSort() != null){
testTree.setSort(testTree.getSort() + 30);
}
}
}
}
if (testTree.getSort() == null){
testTree.setSort(30);
}
model.addAttribute("testTree", testTree);
return "jeesite/test/testTreeForm";
}
@RequiresPermissions("test:testTree:edit")
@RequestMapping(value = "save")
public String save(TestTree testTree, Model model, RedirectAttributes redirectAttributes) {
if (!beanValidator(model, testTree)){
return form(testTree, model);
}
testTreeService.save(testTree);
addMessage(redirectAttributes, "保存树结构成功");
return "redirect:"+Global.getAdminPath()+"/test/testTree/?repage";
}
@RequiresPermissions("test:testTree:edit")
@RequestMapping(value = "delete")
public String delete(TestTree testTree, RedirectAttributes redirectAttributes) {
testTreeService.delete(testTree);
addMessage(redirectAttributes, "删除树结构成功");
return "redirect:"+Global.getAdminPath()+"/test/testTree/?repage";
}
@RequiresPermissions("user")
@ResponseBody
@RequestMapping(value = "treeData")
public List<Map<String, Object>> treeData(@RequestParam(required=false) String extId, HttpServletResponse response) {
List<Map<String, Object>> mapList = Lists.newArrayList();
List<TestTree> list = testTreeService.findList(new TestTree());
for (int i=0; i<list.size(); i++){
TestTree e = list.get(i);
if (StringUtils.isBlank(extId) || (extId!=null && !extId.equals(e.getId()) && e.getParentIds().indexOf(","+extId+",")==-1)){
Map<String, Object> map = Maps.newHashMap();
map.put("id", e.getId());
map.put("pId", e.getParentId());
map.put("name", e.getName());
mapList.add(map);
}
}
return mapList;
}
} | apache-2.0 |
AkechiNEET/cw-omnibus | ViewPager/TabPager/src/com/commonsware/android/tabpager/ViewPagerFragmentDemoActivity.java | 2750 | /***
Copyright (c) 2012 CommonsWare, LLC
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.
From _The Busy Coder's Guide to Android Development_
https://commonsware.com/Android
*/
package com.commonsware.android.tabpager;
import android.app.ActionBar;
import android.app.Activity;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
public class ViewPagerFragmentDemoActivity extends
Activity implements ActionBar.TabListener,
OnPageChangeListener {
private static final String KEY_POSITION="position";
private ViewPager pager=null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
pager=(ViewPager)findViewById(R.id.pager);
pager.setAdapter(new SampleAdapter(getFragmentManager()));
pager.setOnPageChangeListener(this);
ActionBar bar=getActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
for (int i=0; i < 10; i++) {
bar.addTab(bar.newTab()
.setText("Editor #" + String.valueOf(i + 1))
.setTabListener(this).setTag(i));
}
}
@Override
public void onRestoreInstanceState(Bundle state) {
super.onRestoreInstanceState(state);
pager.setCurrentItem(state.getInt(KEY_POSITION));
}
@Override
public void onSaveInstanceState(Bundle state) {
super.onSaveInstanceState(state);
state.putInt(KEY_POSITION, pager.getCurrentItem());
}
@Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
Integer position=(Integer)tab.getTag();
pager.setCurrentItem(position);
}
@Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
// no-op
}
@Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
// no-op
}
@Override
public void onPageScrollStateChanged(int arg0) {
// no-op
}
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// no-op
}
@Override
public void onPageSelected(int position) {
getActionBar().setSelectedNavigationItem(position);
}
} | apache-2.0 |
willkara/sakai | citations/citations-osid/xserver/src/java/org/sakaibrary/osid/repository/xserver/SubjectPartStructure.java | 3910 | /**********************************************************************************
* $URL$
* $Id$
***********************************************************************************
*
* Copyright (c) 2006, 2007, 2008 The Sakai Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ECL-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**********************************************************************************/
package org.sakaibrary.osid.repository.xserver;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class SubjectPartStructure
implements org.osid.repository.PartStructure
{
private org.osid.shared.Id SUBJECT_PART_STRUCTURE_ID = null;
private org.osid.shared.Type type = new Type("mit.edu", "partStructure",
"subject", "Subject");
private String displayName = "Subject";
private String description = "Typically, Subject will be expressed as keywords, key phrases or classification codes that describe a topic of the resource.";
private boolean mandatory = false;
private boolean populatedByRepository = false;
private boolean repeatable = true;
private static SubjectPartStructure subjectPartStructure;
private SubjectPartStructure()
{
try
{
this.SUBJECT_PART_STRUCTURE_ID = Managers.getIdManager().getId(
"a8a1541f201080006d751920168000100");
}
catch (Throwable t)
{
log.warn( "SubjectPartStructure() failed to get partStructure id: "
+ t.getMessage() );
}
}
protected static synchronized SubjectPartStructure getInstance()
{
if( subjectPartStructure == null ) {
subjectPartStructure = new SubjectPartStructure();
}
return subjectPartStructure;
}
public String getDisplayName()
throws org.osid.repository.RepositoryException
{
return this.displayName;
}
public String getDescription()
throws org.osid.repository.RepositoryException
{
return this.description;
}
public boolean isMandatory()
throws org.osid.repository.RepositoryException
{
return this.mandatory;
}
public boolean isPopulatedByRepository()
throws org.osid.repository.RepositoryException
{
return this.populatedByRepository;
}
public boolean isRepeatable()
throws org.osid.repository.RepositoryException
{
return this.repeatable;
}
public void updateDisplayName(String displayName)
throws org.osid.repository.RepositoryException
{
throw new org.osid.repository.RepositoryException(org.osid.OsidException.UNIMPLEMENTED);
}
public org.osid.shared.Id getId()
throws org.osid.repository.RepositoryException
{
return this.SUBJECT_PART_STRUCTURE_ID;
}
public org.osid.shared.Type getType()
throws org.osid.repository.RepositoryException
{
return this.type;
}
public org.osid.repository.RecordStructure getRecordStructure()
throws org.osid.repository.RepositoryException
{
return RecordStructure.getInstance();
}
public boolean validatePart(org.osid.repository.Part part)
throws org.osid.repository.RepositoryException
{
return true;
}
public org.osid.repository.PartStructureIterator getPartStructures()
throws org.osid.repository.RepositoryException
{
return new PartStructureIterator(new java.util.Vector());
}
}
| apache-2.0 |
seem-sky/FrameworkBenchmarks | grizzly-bm/src/main/java/org/glassfish/grizzly/bm/PlainTextHttpHandler.java | 987 | package org.glassfish.grizzly.bm;
import org.glassfish.grizzly.http.server.HttpHandler;
import org.glassfish.grizzly.http.server.Request;
import org.glassfish.grizzly.http.server.RequestExecutorProvider;
import org.glassfish.grizzly.http.server.Response;
import org.glassfish.grizzly.http.util.ContentType;
import org.glassfish.grizzly.http.util.Header;
/**
* Plain text usecase
*/
public class PlainTextHttpHandler extends HttpHandler {
private static final ContentType CONTENT_TYPE =
ContentType.newContentType("text/plain", "utf-8").prepare();
@Override
public void service(final Request request, final Response response)
throws Exception {
response.setContentType(CONTENT_TYPE);
response.setHeader(Header.Server, Server.SERVER_VERSION);
response.getWriter().write("Hello, World!");
}
@Override
public RequestExecutorProvider getRequestExecutorProvider() {
return Server.EXECUTOR_PROVIDER;
}
}
| bsd-3-clause |
rokn/Count_Words_2015 | testing/openjdk2/corba/src/share/classes/com/sun/corba/se/impl/ior/TaggedProfileTemplateFactoryFinderImpl.java | 1855 | /*
* Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.corba.se.impl.ior;
import com.sun.corba.se.spi.ior.Identifiable ;
import com.sun.corba.se.spi.orb.ORB ;
import com.sun.corba.se.impl.ior.IdentifiableFactoryFinderBase ;
import org.omg.CORBA_2_3.portable.InputStream ;
import org.omg.CORBA.INTERNAL ;
/**
* @author
*/
public class TaggedProfileTemplateFactoryFinderImpl extends
IdentifiableFactoryFinderBase
{
public TaggedProfileTemplateFactoryFinderImpl( ORB orb )
{
super( orb ) ;
}
public Identifiable handleMissingFactory( int id, InputStream is)
{
throw wrapper.taggedProfileTemplateFactoryNotFound( new Integer(id) ) ;
}
}
| mit |
Aloomaio/incubator-storm | storm-core/src/jvm/storm/trident/state/map/TransactionalMap.java | 3891 | /**
* 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 storm.trident.state.map;
import storm.trident.state.TransactionalValue;
import storm.trident.state.ValueUpdater;
import java.util.ArrayList;
import java.util.List;
public class TransactionalMap<T> implements MapState<T> {
public static <T> MapState<T> build(IBackingMap<TransactionalValue> backing) {
return new TransactionalMap<T>(backing);
}
CachedBatchReadsMap<TransactionalValue> _backing;
Long _currTx;
protected TransactionalMap(IBackingMap<TransactionalValue> backing) {
_backing = new CachedBatchReadsMap(backing);
}
@Override
public List<T> multiGet(List<List<Object>> keys) {
List<CachedBatchReadsMap.RetVal<TransactionalValue>> vals = _backing.multiGet(keys);
List<T> ret = new ArrayList<T>(vals.size());
for(CachedBatchReadsMap.RetVal<TransactionalValue> retval: vals) {
TransactionalValue v = retval.val;
if(v!=null) {
ret.add((T) v.getVal());
} else {
ret.add(null);
}
}
return ret;
}
@Override
public List<T> multiUpdate(List<List<Object>> keys, List<ValueUpdater> updaters) {
List<CachedBatchReadsMap.RetVal<TransactionalValue>> curr = _backing.multiGet(keys);
List<TransactionalValue> newVals = new ArrayList<TransactionalValue>(curr.size());
List<List<Object>> newKeys = new ArrayList();
List<T> ret = new ArrayList<T>();
for(int i=0; i<curr.size(); i++) {
CachedBatchReadsMap.RetVal<TransactionalValue> retval = curr.get(i);
TransactionalValue<T> val = retval.val;
ValueUpdater<T> updater = updaters.get(i);
TransactionalValue<T> newVal;
boolean changed = false;
if(val==null) {
newVal = new TransactionalValue<T>(_currTx, updater.update(null));
changed = true;
} else {
if(_currTx!=null && _currTx.equals(val.getTxid()) && !retval.cached) {
newVal = val;
} else {
newVal = new TransactionalValue<T>(_currTx, updater.update(val.getVal()));
changed = true;
}
}
ret.add(newVal.getVal());
if(changed) {
newVals.add(newVal);
newKeys.add(keys.get(i));
}
}
if(!newKeys.isEmpty()) {
_backing.multiPut(newKeys, newVals);
}
return ret;
}
@Override
public void multiPut(List<List<Object>> keys, List<T> vals) {
List<TransactionalValue> newVals = new ArrayList<TransactionalValue>(vals.size());
for(T val: vals) {
newVals.add(new TransactionalValue<T>(_currTx, val));
}
_backing.multiPut(keys, newVals);
}
@Override
public void beginCommit(Long txid) {
_currTx = txid;
_backing.reset();
}
@Override
public void commit(Long txid) {
_currTx = null;
_backing.reset();
}
}
| apache-2.0 |
stevechlin/mobilecloud-15 | ex/WeatherServiceProvider/src/vandy/mooc/utils/GenericAsyncTask.java | 1280 | package vandy.mooc.utils;
import android.os.AsyncTask;
/**
* Defines a generic framework for running an AsyncTask that delegates
* its operations to the @a Ops parameter.
*/
public class GenericAsyncTask<Params,
Progress,
Result,
Ops extends GenericAsyncTaskOps<Params, Progress, Result>>
extends AsyncTask<Params, Progress, Result> {
/**
* Debugging tag used by the Android logger.
*/
protected final String TAG = getClass().getSimpleName();
/**
* Params instance.
*/
private Params mParam;
/**
* Reference to the enclosing Ops object.
*/
protected Ops mOps;
/**
* Constructor initializes the field.
*/
public GenericAsyncTask(Ops ops) {
mOps = ops;
}
/**
* Run in a background thread to avoid blocking the UI thread.
*/
@SuppressWarnings("unchecked")
protected Result doInBackground(Params... params) {
mParam = params[0];
return mOps.doInBackground(mParam);
}
/**
* Process results in the UI Thread.
*/
protected void onPostExecute(Result result) {
mOps.onPostExecute(result,
mParam);
}
}
| apache-2.0 |
s20121035/rk3288_android5.1_repo | external/chromium_org/content/public/android/java/src/org/chromium/content/browser/input/SelectPopupDialog.java | 4999 | // Copyright 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.content.browser.input;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.TypedArray;
import android.util.SparseBooleanArray;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import org.chromium.content.R;
import org.chromium.content.browser.ContentViewCore;
import java.util.List;
/**
* Handles the popup dialog for the <select> HTML tag support.
*/
public class SelectPopupDialog implements SelectPopup {
private static final int[] SELECT_DIALOG_ATTRS = {
R.attr.select_dialog_multichoice,
R.attr.select_dialog_singlechoice
};
// The dialog hosting the popup list view.
private final AlertDialog mListBoxPopup;
private final ContentViewCore mContentViewCore;
private final Context mContext;
private boolean mSelectionNotified;
public SelectPopupDialog(ContentViewCore contentViewCore, List<SelectPopupItem> items,
boolean multiple, int[] selected) {
mContentViewCore = contentViewCore;
mContext = mContentViewCore.getContext();
final ListView listView = new ListView(mContext);
listView.setCacheColorHint(0);
AlertDialog.Builder b = new AlertDialog.Builder(mContext)
.setView(listView)
.setCancelable(true)
.setInverseBackgroundForced(true);
if (multiple) {
b.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
notifySelection(getSelectedIndices(listView));
}
});
b.setNegativeButton(android.R.string.cancel,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
notifySelection(null);
}
});
}
mListBoxPopup = b.create();
final SelectPopupAdapter adapter = new SelectPopupAdapter(
mContext, getSelectDialogLayout(multiple), items);
listView.setAdapter(adapter);
listView.setFocusableInTouchMode(true);
if (multiple) {
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
for (int i = 0; i < selected.length; ++i) {
listView.setItemChecked(selected[i], true);
}
} else {
listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
notifySelection(getSelectedIndices(listView));
mListBoxPopup.dismiss();
}
});
if (selected.length > 0) {
listView.setSelection(selected[0]);
listView.setItemChecked(selected[0], true);
}
}
mListBoxPopup.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
notifySelection(null);
}
});
}
private int getSelectDialogLayout(boolean isMultiChoice) {
int resourceId;
TypedArray styledAttributes = mContext.obtainStyledAttributes(
R.style.SelectPopupDialog, SELECT_DIALOG_ATTRS);
resourceId = styledAttributes.getResourceId(isMultiChoice ? 0 : 1, 0);
styledAttributes.recycle();
return resourceId;
}
private static int[] getSelectedIndices(ListView listView) {
SparseBooleanArray sparseArray = listView.getCheckedItemPositions();
int selectedCount = 0;
for (int i = 0; i < sparseArray.size(); ++i) {
if (sparseArray.valueAt(i)) {
selectedCount++;
}
}
int[] indices = new int[selectedCount];
for (int i = 0, j = 0; i < sparseArray.size(); ++i) {
if (sparseArray.valueAt(i)) {
indices[j++] = sparseArray.keyAt(i);
}
}
return indices;
}
private void notifySelection(int[] indicies) {
if (mSelectionNotified) return;
mContentViewCore.selectPopupMenuItems(indicies);
mSelectionNotified = true;
}
@Override
public void show() {
mListBoxPopup.show();
}
@Override
public void hide() {
mListBoxPopup.cancel();
notifySelection(null);
}
}
| gpl-3.0 |
adelatorrefoss/talk-businesslogic-code | whereiputmybusinesslogic/target/work/plugins/cache-1.1.1/src/java/grails/plugin/cache/BlockingCache.java | 840 | /* Copyright 2012-2013 SpringSource.
*
* 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 grails.plugin.cache;
/**
* @author Burt Beckwith
*/
public interface BlockingCache extends GrailsCache {
CacheConfiguration getCacheConfiguration();
boolean isDisabled();
void setTimeoutMillis(int blockingTimeoutMillis);
}
| apache-2.0 |
rokn/Count_Words_2015 | testing/openjdk2/jdk/src/share/classes/javax/xml/crypto/dsig/CanonicalizationMethod.java | 4173 | /*
* Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* $Id: CanonicalizationMethod.java,v 1.6 2005/05/10 16:03:45 mullan Exp $
*/
package javax.xml.crypto.dsig;
import java.security.spec.AlgorithmParameterSpec;
import javax.xml.crypto.dsig.spec.C14NMethodParameterSpec;
/**
* A representation of the XML <code>CanonicalizationMethod</code>
* element as defined in the
* <a href="http://www.w3.org/TR/xmldsig-core/">
* W3C Recommendation for XML-Signature Syntax and Processing</a>. The XML
* Schema Definition is defined as:
* <p>
* <pre>
* <element name="CanonicalizationMethod" type="ds:CanonicalizationMethodType"/>
* <complexType name="CanonicalizationMethodType" mixed="true">
* <sequence>
* <any namespace="##any" minOccurs="0" maxOccurs="unbounded"/>
* <!-- (0,unbounded) elements from (1,1) namespace -->
* </sequence>
* <attribute name="Algorithm" type="anyURI" use="required"/>
* </complexType>
* </pre>
*
* A <code>CanonicalizationMethod</code> instance may be created by invoking
* the {@link XMLSignatureFactory#newCanonicalizationMethod
* newCanonicalizationMethod} method of the {@link XMLSignatureFactory} class.
*
* @author Sean Mullan
* @author JSR 105 Expert Group
* @since 1.6
* @see XMLSignatureFactory#newCanonicalizationMethod(String, C14NMethodParameterSpec)
*/
public interface CanonicalizationMethod extends Transform {
/**
* The <a href="http://www.w3.org/TR/2001/REC-xml-c14n-20010315">Canonical
* XML (without comments)</a> canonicalization method algorithm URI.
*/
final static String INCLUSIVE =
"http://www.w3.org/TR/2001/REC-xml-c14n-20010315";
/**
* The
* <a href="http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments">
* Canonical XML with comments</a> canonicalization method algorithm URI.
*/
final static String INCLUSIVE_WITH_COMMENTS =
"http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments";
/**
* The <a href="http://www.w3.org/2001/10/xml-exc-c14n#">Exclusive
* Canonical XML (without comments)</a> canonicalization method algorithm
* URI.
*/
final static String EXCLUSIVE =
"http://www.w3.org/2001/10/xml-exc-c14n#";
/**
* The <a href="http://www.w3.org/2001/10/xml-exc-c14n#WithComments">
* Exclusive Canonical XML with comments</a> canonicalization method
* algorithm URI.
*/
final static String EXCLUSIVE_WITH_COMMENTS =
"http://www.w3.org/2001/10/xml-exc-c14n#WithComments";
/**
* Returns the algorithm-specific input parameters associated with this
* <code>CanonicalizationMethod</code>.
*
* <p>The returned parameters can be typecast to a
* {@link C14NMethodParameterSpec} object.
*
* @return the algorithm-specific input parameters (may be
* <code>null</code> if not specified)
*/
AlgorithmParameterSpec getParameterSpec();
}
| mit |
CJstar/android-maven-plugin | src/test/projects/apidemos-android-16/apidemos-application/src/main/java/com/example/android/apis/app/ReceiveResult.java | 5777 | /*
* Copyright (C) 2007 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.apis.app;
// Need the following import to get access to the app resources, since this
// class is in a sub-package.
import com.example.android.apis.R;
import android.app.Activity;
import android.content.Intent;
import android.text.Editable;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
/**
* Shows how an activity can send data to its launching activity when done.y.
* <p>This can be used, for example, to implement a dialog alowing the user to
pick an e-mail address or image -- the picking activity sends the selected
data back to the originating activity when done.</p>
<p>The example here is composed of two activities: ReceiveResult launches
the picking activity and receives its results; SendResult allows the user
to pick something and sends the selection back to its caller. Implementing
this functionality involves the
{@link android.app.Activity#setResult setResult()} method for sending a
result and
{@link android.app.Activity#onActivityResult onActivityResult()} to
receive it.</p>
<h4>Demo</h4>
App/Activity/Receive Result
<h4>Source files</h4>
<table class="LinkTable">
<tr>
<td class="LinkColumn">src/com.example.android.apis/app/ReceiveResult.java</td>
<td class="DescrColumn">Launches pick activity and receives its result</td>
</tr>
<tr>
<td class="LinkColumn">src/com.example.android.apis/app/SendResult.java</td>
<td class="DescrColumn">Allows user to pick an option and sends it back to its caller</td>
</tr>
<tr>
<td class="LinkColumn">/res/any/layout/receive_result.xml</td>
<td class="DescrColumn">Defines contents of the ReceiveResult screen</td>
</tr>
<tr>
<td class="LinkColumn">/res/any/layout/send_result.xml</td>
<td class="DescrColumn">Defines contents of the SendResult screen</td>
</tr>
</table>
*/
public class ReceiveResult extends Activity {
/**
* Initialization of the Activity after it is first created. Must at least
* call {@link android.app.Activity#setContentView setContentView()} to
* describe what is to be displayed in the screen.
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
// Be sure to call the super class.
super.onCreate(savedInstanceState);
// See assets/res/any/layout/hello_world.xml for this
// view layout definition, which is being set here as
// the content of our screen.
setContentView(R.layout.receive_result);
// Retrieve the TextView widget that will display results.
mResults = (TextView)findViewById(R.id.results);
// This allows us to later extend the text buffer.
mResults.setText(mResults.getText(), TextView.BufferType.EDITABLE);
// Watch for button clicks.
Button getButton = (Button)findViewById(R.id.get);
getButton.setOnClickListener(mGetListener);
}
/**
* This method is called when the sending activity has finished, with the
* result it supplied.
*
* @param requestCode The original request code as given to
* startActivity().
* @param resultCode From sending activity as per setResult().
* @param data From sending activity as per setResult().
*/
@Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
// You can use the requestCode to select between multiple child
// activities you may have started. Here there is only one thing
// we launch.
if (requestCode == GET_CODE) {
// We will be adding to our text.
Editable text = (Editable)mResults.getText();
// This is a standard resultCode that is sent back if the
// activity doesn't supply an explicit result. It will also
// be returned if the activity failed to launch.
if (resultCode == RESULT_CANCELED) {
text.append("(cancelled)");
// Our protocol with the sending activity is that it will send
// text in 'data' as its result.
} else {
text.append("(okay ");
text.append(Integer.toString(resultCode));
text.append(") ");
if (data != null) {
text.append(data.getAction());
}
}
text.append("\n");
}
}
// Definition of the one requestCode we use for receiving resuls.
static final private int GET_CODE = 0;
private OnClickListener mGetListener = new OnClickListener() {
public void onClick(View v) {
// Start the activity whose result we want to retrieve. The
// result will come back with request code GET_CODE.
Intent intent = new Intent(ReceiveResult.this, SendResult.class);
startActivityForResult(intent, GET_CODE);
}
};
private TextView mResults;
}
| apache-2.0 |
forestqqqq/spring-boot | spring-boot/src/main/java/org/springframework/boot/context/embedded/undertow/UndertowEmbeddedServletContainerFactory.java | 20176 | /*
* Copyright 2012-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.context.embedded.undertow;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.servlet.ServletContainerInitializer;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import org.springframework.boot.ApplicationTemp;
import org.springframework.boot.context.embedded.AbstractEmbeddedServletContainerFactory;
import org.springframework.boot.context.embedded.EmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory;
import org.springframework.boot.context.embedded.ErrorPage;
import org.springframework.boot.context.embedded.MimeMappings.Mapping;
import org.springframework.boot.context.embedded.ServletContextInitializer;
import org.springframework.boot.context.embedded.Ssl;
import org.springframework.boot.context.embedded.Ssl.ClientAuth;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.core.io.ResourceLoader;
import org.springframework.util.Assert;
import org.springframework.util.ResourceUtils;
import org.xnio.OptionMap;
import org.xnio.Options;
import org.xnio.SslClientAuthMode;
import org.xnio.Xnio;
import org.xnio.XnioWorker;
import io.undertow.Undertow;
import io.undertow.Undertow.Builder;
import io.undertow.UndertowMessages;
import io.undertow.server.HandlerWrapper;
import io.undertow.server.HttpHandler;
import io.undertow.server.handlers.accesslog.AccessLogHandler;
import io.undertow.server.handlers.accesslog.AccessLogReceiver;
import io.undertow.server.handlers.accesslog.DefaultAccessLogReceiver;
import io.undertow.server.handlers.resource.ClassPathResourceManager;
import io.undertow.server.handlers.resource.FileResourceManager;
import io.undertow.server.handlers.resource.Resource;
import io.undertow.server.handlers.resource.ResourceChangeListener;
import io.undertow.server.handlers.resource.ResourceManager;
import io.undertow.server.handlers.resource.URLResource;
import io.undertow.server.session.SessionManager;
import io.undertow.servlet.Servlets;
import io.undertow.servlet.api.DeploymentInfo;
import io.undertow.servlet.api.DeploymentManager;
import io.undertow.servlet.api.MimeMapping;
import io.undertow.servlet.api.ServletContainerInitializerInfo;
import io.undertow.servlet.api.ServletStackTraces;
import io.undertow.servlet.handlers.DefaultServlet;
import io.undertow.servlet.util.ImmediateInstanceFactory;
/**
* {@link EmbeddedServletContainerFactory} that can be used to create
* {@link UndertowEmbeddedServletContainer}s.
* <p>
* Unless explicitly configured otherwise, the factory will create containers that listen
* for HTTP requests on port 8080.
*
* @author Ivan Sopov
* @author Andy Wilkinson
* @author Marcos Barbero
* @since 1.2.0
* @see UndertowEmbeddedServletContainer
*/
public class UndertowEmbeddedServletContainerFactory extends
AbstractEmbeddedServletContainerFactory implements ResourceLoaderAware {
private static final Set<Class<?>> NO_CLASSES = Collections.emptySet();
private List<UndertowBuilderCustomizer> builderCustomizers = new ArrayList<UndertowBuilderCustomizer>();
private List<UndertowDeploymentInfoCustomizer> deploymentInfoCustomizers = new ArrayList<UndertowDeploymentInfoCustomizer>();
private ResourceLoader resourceLoader;
private Integer bufferSize;
private Integer buffersPerRegion;
private Integer ioThreads;
private Integer workerThreads;
private Boolean directBuffers;
private File accessLogDirectory;
private String accessLogPattern;
private boolean accessLogEnabled = false;
/**
* Create a new {@link UndertowEmbeddedServletContainerFactory} instance.
*/
public UndertowEmbeddedServletContainerFactory() {
super();
getJspServlet().setRegistered(false);
}
/**
* Create a new {@link UndertowEmbeddedServletContainerFactory} that listens for
* requests using the specified port.
* @param port the port to listen on
*/
public UndertowEmbeddedServletContainerFactory(int port) {
super(port);
getJspServlet().setRegistered(false);
}
/**
* Create a new {@link UndertowEmbeddedServletContainerFactory} with the specified
* context path and port.
* @param contextPath root the context path
* @param port the port to listen on
*/
public UndertowEmbeddedServletContainerFactory(String contextPath, int port) {
super(contextPath, port);
getJspServlet().setRegistered(false);
}
/**
* Set {@link UndertowBuilderCustomizer}s that should be applied to the Undertow
* {@link Builder}. Calling this method will replace any existing customizers.
* @param customizers the customizers to set
*/
public void setBuilderCustomizers(
Collection<? extends UndertowBuilderCustomizer> customizers) {
Assert.notNull(customizers, "Customizers must not be null");
this.builderCustomizers = new ArrayList<UndertowBuilderCustomizer>(customizers);
}
/**
* Returns a mutable collection of the {@link UndertowBuilderCustomizer}s that will be
* applied to the Undertow {@link Builder} .
* @return the customizers that will be applied
*/
public Collection<UndertowBuilderCustomizer> getBuilderCustomizers() {
return this.builderCustomizers;
}
/**
* Add {@link UndertowBuilderCustomizer}s that should be used to customize the
* Undertow {@link Builder}.
* @param customizers the customizers to add
*/
public void addBuilderCustomizers(UndertowBuilderCustomizer... customizers) {
Assert.notNull(customizers, "Customizers must not be null");
this.builderCustomizers.addAll(Arrays.asList(customizers));
}
/**
* Set {@link UndertowDeploymentInfoCustomizer}s that should be applied to the
* Undertow {@link DeploymentInfo}. Calling this method will replace any existing
* customizers.
* @param customizers the customizers to set
*/
public void setDeploymentInfoCustomizers(
Collection<? extends UndertowDeploymentInfoCustomizer> customizers) {
Assert.notNull(customizers, "Customizers must not be null");
this.deploymentInfoCustomizers = new ArrayList<UndertowDeploymentInfoCustomizer>(
customizers);
}
/**
* Returns a mutable collection of the {@link UndertowDeploymentInfoCustomizer}s that
* will be applied to the Undertow {@link DeploymentInfo} .
* @return the customizers that will be applied
*/
public Collection<UndertowDeploymentInfoCustomizer> getDeploymentInfoCustomizers() {
return this.deploymentInfoCustomizers;
}
/**
* Add {@link UndertowDeploymentInfoCustomizer}s that should be used to customize the
* Undertow {@link DeploymentInfo}.
* @param customizers the customizers to add
*/
public void addDeploymentInfoCustomizers(
UndertowDeploymentInfoCustomizer... customizers) {
Assert.notNull(customizers, "UndertowDeploymentInfoCustomizers must not be null");
this.deploymentInfoCustomizers.addAll(Arrays.asList(customizers));
}
@Override
public EmbeddedServletContainer getEmbeddedServletContainer(
ServletContextInitializer... initializers) {
DeploymentManager manager = createDeploymentManager(initializers);
int port = getPort();
Builder builder = createBuilder(port);
return new UndertowEmbeddedServletContainer(builder, manager, getContextPath(),
port, port >= 0, getCompression());
}
private Builder createBuilder(int port) {
Builder builder = Undertow.builder();
if (this.bufferSize != null) {
builder.setBufferSize(this.bufferSize);
}
if (this.buffersPerRegion != null) {
builder.setBuffersPerRegion(this.buffersPerRegion);
}
if (this.ioThreads != null) {
builder.setIoThreads(this.ioThreads);
}
if (this.workerThreads != null) {
builder.setWorkerThreads(this.workerThreads);
}
if (this.directBuffers != null) {
builder.setDirectBuffers(this.directBuffers);
}
if (getSsl() != null && getSsl().isEnabled()) {
configureSsl(getSsl(), port, builder);
}
else {
builder.addHttpListener(port, getListenAddress());
}
for (UndertowBuilderCustomizer customizer : this.builderCustomizers) {
customizer.customize(builder);
}
return builder;
}
private void configureSsl(Ssl ssl, int port, Builder builder) {
try {
SSLContext sslContext = SSLContext.getInstance(ssl.getProtocol());
sslContext.init(getKeyManagers(), getTrustManagers(), null);
builder.addHttpsListener(port, getListenAddress(), sslContext);
builder.setSocketOption(Options.SSL_CLIENT_AUTH_MODE,
getSslClientAuthMode(ssl));
}
catch (NoSuchAlgorithmException ex) {
throw new IllegalStateException(ex);
}
catch (KeyManagementException ex) {
throw new IllegalStateException(ex);
}
}
private String getListenAddress() {
if (getAddress() == null) {
return "0.0.0.0";
}
return getAddress().getHostAddress();
}
private SslClientAuthMode getSslClientAuthMode(Ssl ssl) {
if (ssl.getClientAuth() == ClientAuth.NEED) {
return SslClientAuthMode.REQUIRED;
}
if (ssl.getClientAuth() == ClientAuth.WANT) {
return SslClientAuthMode.REQUESTED;
}
return SslClientAuthMode.NOT_REQUESTED;
}
private KeyManager[] getKeyManagers() {
try {
Ssl ssl = getSsl();
String keyStoreType = ssl.getKeyStoreType();
if (keyStoreType == null) {
keyStoreType = "JKS";
}
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
URL url = ResourceUtils.getURL(ssl.getKeyStore());
keyStore.load(url.openStream(), ssl.getKeyStorePassword().toCharArray());
// Get key manager to provide client credentials.
KeyManagerFactory keyManagerFactory = KeyManagerFactory
.getInstance(KeyManagerFactory.getDefaultAlgorithm());
char[] keyPassword = ssl.getKeyPassword() != null ? ssl.getKeyPassword()
.toCharArray() : ssl.getKeyStorePassword().toCharArray();
keyManagerFactory.init(keyStore, keyPassword);
return keyManagerFactory.getKeyManagers();
}
catch (Exception ex) {
throw new IllegalStateException(ex);
}
}
private TrustManager[] getTrustManagers() {
try {
Ssl ssl = getSsl();
String trustStoreType = ssl.getTrustStoreType();
if (trustStoreType == null) {
trustStoreType = "JKS";
}
String trustStore = ssl.getTrustStore();
if (trustStore == null) {
return null;
}
KeyStore trustedKeyStore = KeyStore.getInstance(trustStoreType);
URL url = ResourceUtils.getURL(trustStore);
trustedKeyStore.load(url.openStream(), ssl.getTrustStorePassword()
.toCharArray());
TrustManagerFactory trustManagerFactory = TrustManagerFactory
.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(trustedKeyStore);
return trustManagerFactory.getTrustManagers();
}
catch (Exception ex) {
throw new IllegalStateException(ex);
}
}
private DeploymentManager createDeploymentManager(
ServletContextInitializer... initializers) {
DeploymentInfo deployment = Servlets.deployment();
registerServletContainerInitializerToDriveServletContextInitializers(deployment,
initializers);
deployment.setClassLoader(getServletClassLoader());
deployment.setContextPath(getContextPath());
deployment.setDisplayName(getDisplayName());
deployment.setDeploymentName("spring-boot");
if (isRegisterDefaultServlet()) {
deployment.addServlet(Servlets.servlet("default", DefaultServlet.class));
}
configureErrorPages(deployment);
deployment.setServletStackTraces(ServletStackTraces.NONE);
deployment.setResourceManager(getDocumentRootResourceManager());
configureMimeMappings(deployment);
for (UndertowDeploymentInfoCustomizer customizer : this.deploymentInfoCustomizers) {
customizer.customize(deployment);
}
if (isAccessLogEnabled()) {
configureAccessLog(deployment);
}
if (isPersistSession()) {
File folder = new ApplicationTemp().getFolder("undertow-sessions");
deployment.setSessionPersistenceManager(new FileSessionPersistence(folder));
}
DeploymentManager manager = Servlets.defaultContainer().addDeployment(deployment);
manager.deploy();
SessionManager sessionManager = manager.getDeployment().getSessionManager();
int sessionTimeout = (getSessionTimeout() > 0 ? getSessionTimeout() : -1);
sessionManager.setDefaultSessionTimeout(sessionTimeout);
return manager;
}
private void configureAccessLog(DeploymentInfo deploymentInfo) {
deploymentInfo.addInitialHandlerChainWrapper(new HandlerWrapper() {
@Override
public HttpHandler wrap(HttpHandler handler) {
return createAccessLogHandler(handler);
}
});
}
private AccessLogHandler createAccessLogHandler(HttpHandler handler) {
try {
createAccessLogDirectoryIfNecessary();
AccessLogReceiver accessLogReceiver = new DefaultAccessLogReceiver(
createWorker(), this.accessLogDirectory, "access_log");
String formatString = (this.accessLogPattern != null) ? this.accessLogPattern
: "common";
return new AccessLogHandler(handler, accessLogReceiver, formatString,
Undertow.class.getClassLoader());
}
catch (IOException ex) {
throw new IllegalStateException("Failed to create AccessLogHandler", ex);
}
}
private void createAccessLogDirectoryIfNecessary() {
Assert.state(this.accessLogDirectory != null, "Access log directory is not set");
if (!this.accessLogDirectory.isDirectory() && !this.accessLogDirectory.mkdirs()) {
throw new IllegalStateException("Failed to create access log directory '"
+ this.accessLogDirectory + "'");
}
}
private XnioWorker createWorker() throws IOException {
Xnio xnio = Xnio.getInstance(Undertow.class.getClassLoader());
OptionMap.Builder builder = OptionMap.builder();
return xnio.createWorker(builder.getMap());
}
private void registerServletContainerInitializerToDriveServletContextInitializers(
DeploymentInfo deployment, ServletContextInitializer... initializers) {
ServletContextInitializer[] mergedInitializers = mergeInitializers(initializers);
Initializer initializer = new Initializer(mergedInitializers);
deployment.addServletContainerInitalizer(new ServletContainerInitializerInfo(
Initializer.class,
new ImmediateInstanceFactory<ServletContainerInitializer>(initializer),
NO_CLASSES));
}
private ClassLoader getServletClassLoader() {
if (this.resourceLoader != null) {
return this.resourceLoader.getClassLoader();
}
return getClass().getClassLoader();
}
private ResourceManager getDocumentRootResourceManager() {
File root = getValidDocumentRoot();
if (root != null && root.isDirectory()) {
return new FileResourceManager(root, 0);
}
if (root != null && root.isFile()) {
return new JarResourcemanager(root);
}
if (this.resourceLoader != null) {
return new ClassPathResourceManager(this.resourceLoader.getClassLoader(), "");
}
return new ClassPathResourceManager(getClass().getClassLoader(), "");
}
private void configureErrorPages(DeploymentInfo servletBuilder) {
for (ErrorPage errorPage : getErrorPages()) {
servletBuilder.addErrorPage(getUndertowErrorPage(errorPage));
}
}
private io.undertow.servlet.api.ErrorPage getUndertowErrorPage(ErrorPage errorPage) {
if (errorPage.getStatus() != null) {
return new io.undertow.servlet.api.ErrorPage(errorPage.getPath(),
errorPage.getStatusCode());
}
if (errorPage.getException() != null) {
return new io.undertow.servlet.api.ErrorPage(errorPage.getPath(),
errorPage.getException());
}
return new io.undertow.servlet.api.ErrorPage(errorPage.getPath());
}
private void configureMimeMappings(DeploymentInfo servletBuilder) {
for (Mapping mimeMapping : getMimeMappings()) {
servletBuilder.addMimeMapping(new MimeMapping(mimeMapping.getExtension(),
mimeMapping.getMimeType()));
}
}
/**
* Factory method called to create the {@link UndertowEmbeddedServletContainer}.
* Subclasses can override this method to return a different
* {@link UndertowEmbeddedServletContainer} or apply additional processing to the
* {@link Builder} and {@link DeploymentManager} used to bootstrap Undertow
* @param builder the builder
* @param manager the deployment manager
* @param port the port that Undertow should listen on
* @return a new {@link UndertowEmbeddedServletContainer} instance
*/
protected UndertowEmbeddedServletContainer getUndertowEmbeddedServletContainer(
Builder builder, DeploymentManager manager, int port) {
return new UndertowEmbeddedServletContainer(builder, manager, getContextPath(),
port, port >= 0, getCompression());
}
@Override
public void setResourceLoader(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}
public void setBufferSize(Integer bufferSize) {
this.bufferSize = bufferSize;
}
public void setBuffersPerRegion(Integer buffersPerRegion) {
this.buffersPerRegion = buffersPerRegion;
}
public void setIoThreads(Integer ioThreads) {
this.ioThreads = ioThreads;
}
public void setWorkerThreads(Integer workerThreads) {
this.workerThreads = workerThreads;
}
public void setDirectBuffers(Boolean directBuffers) {
this.directBuffers = directBuffers;
}
public void setAccessLogDirectory(File accessLogDirectory) {
this.accessLogDirectory = accessLogDirectory;
}
public void setAccessLogPattern(String accessLogPattern) {
this.accessLogPattern = accessLogPattern;
}
public void setAccessLogEnabled(boolean accessLogEnabled) {
this.accessLogEnabled = accessLogEnabled;
}
public boolean isAccessLogEnabled() {
return this.accessLogEnabled;
}
/**
* Undertow {@link ResourceManager} for JAR resources.
*/
private static class JarResourcemanager implements ResourceManager {
private final String jarPath;
JarResourcemanager(File jarFile) {
this(jarFile.getAbsolutePath());
}
JarResourcemanager(String jarPath) {
this.jarPath = jarPath;
}
@Override
public Resource getResource(String path) throws IOException {
URL url = new URL("jar:file:" + this.jarPath + "!" + path);
URLResource resource = new URLResource(url, url.openConnection(), path);
if (resource.getContentLength() < 0) {
return null;
}
return resource;
}
@Override
public boolean isResourceChangeListenerSupported() {
return false;
}
@Override
public void registerResourceChangeListener(ResourceChangeListener listener) {
throw UndertowMessages.MESSAGES.resourceChangeListenerNotSupported();
}
@Override
public void removeResourceChangeListener(ResourceChangeListener listener) {
throw UndertowMessages.MESSAGES.resourceChangeListenerNotSupported();
}
@Override
public void close() throws IOException {
}
}
/**
* {@link ServletContainerInitializer} to initialize {@link ServletContextInitializer
* ServletContextInitializers}.
*/
private static class Initializer implements ServletContainerInitializer {
private final ServletContextInitializer[] initializers;
Initializer(ServletContextInitializer[] initializers) {
this.initializers = initializers;
}
@Override
public void onStartup(Set<Class<?>> classes, ServletContext servletContext)
throws ServletException {
for (ServletContextInitializer initializer : this.initializers) {
initializer.onStartup(servletContext);
}
}
}
}
| apache-2.0 |
1yvT0s/libgdx | extensions/gdx-bullet/jni/swig-src/linearmath/com/badlogic/gdx/physics/bullet/linearmath/SWIGTYPE_p_btAlignedObjectArrayT_ConvexH__HalfEdge_t.java | 878 | /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.2
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.badlogic.gdx.physics.bullet.linearmath;
public class SWIGTYPE_p_btAlignedObjectArrayT_ConvexH__HalfEdge_t {
private long swigCPtr;
protected SWIGTYPE_p_btAlignedObjectArrayT_ConvexH__HalfEdge_t(long cPtr, boolean futureUse) {
swigCPtr = cPtr;
}
protected SWIGTYPE_p_btAlignedObjectArrayT_ConvexH__HalfEdge_t() {
swigCPtr = 0;
}
protected static long getCPtr(SWIGTYPE_p_btAlignedObjectArrayT_ConvexH__HalfEdge_t obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
}
| apache-2.0 |
dut3062796s/react-native | ReactAndroid/src/main/java/com/facebook/react/bridge/ReadableMap.java | 948 | /**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
package com.facebook.react.bridge;
/**
* Interface for a map that allows typed access to its members. Used to pass parameters from JS to
* Java.
*/
public interface ReadableMap {
boolean hasKey(String name);
boolean isNull(String name);
boolean getBoolean(String name);
double getDouble(String name);
int getInt(String name);
// Check CatalystStylesDiffMap#getColorInt() to see why this is needed
int getColorInt(String name);
String getString(String name);
ReadableArray getArray(String name);
ReadableMap getMap(String name);
ReadableType getType(String name);
ReadableMapKeySeyIterator keySetIterator();
}
| bsd-3-clause |
ahb0327/intellij-community | platform/lang-api/src/com/intellij/lang/LanguageBraceMatching.java | 908 | /*
* 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.lang;
/**
* @author yole
*/
public class LanguageBraceMatching extends LanguageExtension<PairedBraceMatcher> {
public static final LanguageBraceMatching INSTANCE = new LanguageBraceMatching();
private LanguageBraceMatching() {
super("com.intellij.lang.braceMatcher");
}
} | apache-2.0 |
marktriggs/nyu-sakai-10.4 | entitybroker/api/src/java/org/sakaiproject/entitybroker/entityprovider/extension/EntityData.java | 15451 | /**
* $Id$
* $URL$
* EntityData.java - entity-broker - Aug 3, 2008 6:03:53 PM - azeckoski
**************************************************************************
* Copyright (c) 2008 The Sakai Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ECL-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sakaiproject.entitybroker.entityprovider.extension;
import java.io.Serializable;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import org.sakaiproject.entitybroker.EntityReference;
import org.sakaiproject.entitybroker.EntityView;
import org.sakaiproject.entitybroker.entityprovider.capabilities.Resolvable;
/**
* This is an object to hold entity data (e.g. from a search which would normally return entity references),
* This is basically a POJO which allows us to return a few results instead of only the reference,
* it helps us get the entity data back more efficiently and makes it easier on developers who
* need to search for entities
*
* @author Aaron Zeckoski (azeckoski @ gmail.com)
*/
public class EntityData {
/**
* (OPTIONAL - may be null)
* This is the entity data object itself (if there is one),
* this is included at the discretion of the entity provider author,
* if this is null then the entity data is not available or would be prohibitively large (i.e. typically left out for efficiency)
*/
private Object data;
public void setData(Object entity) {
this.data = entity;
// if (data != null) {
// this.entity = new WeakReference<Object>(data);
// } else {
// this.entity = null;
// }
}
/**
* (OPTIONAL - may be null)
* This is the entity data object itself (if there is one),
* this is included at the discretion of the entity provider author,
* if this is null then the entity data is not available or would be prohibitively large (i.e. typically left out for efficiency)
*/
public Object getData() {
return this.data;
// if (this.entity == null) {
// return null;
// } else {
// return this.entity.get();
// }
}
private String entityId = null;
/**
* @return the unique local id of the entity (null if there is none)
*/
public String getEntityId() {
return entityId;
}
/**
* The entity reference - a globally unique reference to an entity,
* consists of the entity prefix and optional segments (normally the id at least),
* this should be set by the constructor only
*/
private String entityReference;
/**
* The entity reference - a globally unique reference to an entity,
* consists of the entity prefix and optional segments (normally the id at least)
*/
public String getEntityReference() {
return entityReference;
}
/**
* The entity reference object which makes it easy to get to the prefix or id of this entity,
* this should be set by the constructor only
*/
private transient EntityReference entityRef;
/**
* The entity reference object which makes it easy to get to the prefix or id of this entity if needed
*/
public EntityReference getEntityRef() {
return entityRef;
}
/**
* A string which is suitable for display and provides a short summary of the entity,
* typically 100 chars or less, this may be the name or title of the data represented by an entity
*/
private String entityDisplayTitle;
/**
* A string which is suitable for display and provides a short summary of the entity,
* typically 100 chars or less, this may be the name or title of the data represented by an entity
*/
public void setDisplayTitle(String displayTitle) {
this.entityDisplayTitle = displayTitle;
}
/**
* A string which is suitable for display and provides a short summary of the entity,
* typically 100 chars or less, this may be the name or title of the data represented by an entity
*/
public String getDisplayTitle() {
if (this.entityDisplayTitle == null) {
if (this.entityRef != null) {
return this.entityRef.getPrefix() + " : " + entityReference;
} else {
return "data";
}
}
return entityDisplayTitle;
}
private transient boolean displayTitleSet = false; // needed to avoid encoding
/**
* @return true if the display title is actually set, false if it is null and will return an auto-generated value
*/
public boolean isDisplayTitleSet() {
displayTitleSet = entityDisplayTitle != null;
return displayTitleSet;
}
/**
* (OPTIONAL - may be null)
* The entityURL to the entity represented by this reference,
* should be an absolute entityURL (server name optional),
* if this is null then the entityURL is formed from the reference
*/
private String entityURL;
/**
* WARNING: for internal use only
* @param url the url to access this entity
*/
public void setEntityURL(String url) {
entityURL = url;
}
/**
* The entityURL to the entity represented by this reference,
* should be an absolute entityURL (server name optional)
*/
public String getEntityURL() {
return entityURL;
}
/**
* (OPTIONAL - may be null)
* A set of properties to return along with the entity information,
* this may be presented and used for filtering,
* this will be null or empty if it is not used
*/
private Map<String, Object> entityProperties;
/**
* (OPTIONAL - may be null)
* A set of properties to return along with the entity information,
* this may be presented and used for filtering,
* should be null or empty if not used
* @param entityProperties a map of property name => value
*/
public void setEntityProperties(Map<String, Object> entityProperties) {
this.entityProperties = entityProperties;
}
/**
* A set of properties to return along with the entity information,
* this may be presented and used for filtering,
* this will be empty if it is not used
*/
public Map<String, Object> getEntityProperties() {
if (entityProperties == null) {
entityProperties = new HashMap<String, Object>(0);
}
return entityProperties;
}
/**
* used to ensure that we do not accidently attempt to populate this twice
*/
private transient boolean populated = false;
/**
* FOR INTERNAL USE ONLY - do not use
*/
public void setPopulated(boolean populated) {
this.populated = populated;
}
/**
* @return true if this object was populated, false otherwise
*/
public boolean isPopulated() {
return populated;
}
/**
* indicates that this is a holder and should be discarded and the data
* rendered into the given format without it
*/
private transient boolean dataOnly = false;
/**
* FOR INTERNAL USE ONLY - do not use
*/
public void setDataOnly(boolean dataOnly) {
this.dataOnly = dataOnly;
}
/**
* @return true if this is a data holder and the data inside it should be rendered alone without this wrapper
*/
public boolean isDataOnly() {
return dataOnly;
}
/**
* Minimal constructor - used for most basic cases<br/>
* Use the setters to add in properties or the entity if desired
*
* @param reference a globally unique reference to an entity,
* consists of the entity prefix and id (e.g. /prefix/id)
* @param entityDisplayTitle a string which is suitable for display and provides a short summary of the entity,
* typically 100 chars or less, this may be the name or title of the entity represented by an entity
*/
public EntityData(String reference, String displayTitle) {
this(reference, displayTitle, null, null);
}
/**
* Basic constructor<br/>
* Use this to construct a search result using the typical minimal amount of information,
* Use the setters to add in properties or the entity if desired
*
* @param reference a globally unique reference to an entity,
* consists of the entity prefix and id (e.g. /prefix/id)
* @param entityDisplayTitle a string which is suitable for display and provides a short summary of the entity,
* typically 100 chars or less, this may be the name or title of the entity represented by an entity
* @param data an entity data object, see {@link Resolvable}
*/
public EntityData(String reference, String displayTitle, Object entity) {
this(reference, displayTitle, entity, null);
}
/**
* Full constructor<br/>
* Use this if you want to return the entity itself along with the key meta data and properties
*
* @param reference a globally unique reference to an entity,
* consists of the entity prefix and id (e.g. /prefix/id)
* @param entityDisplayTitle a string which is suitable for display and provides a short summary of the entity,
* typically 100 chars or less, this may be the name or title of the entity represented by an entity
* @param data an entity data object, see {@link Resolvable}
* @param entityProperties a set of properties to return along with the entity information,
* this may be presented and used for filtering,
*/
public EntityData(String reference, String displayTitle, Object entity, Map<String, Object> entityProperties) {
this.entityRef = new EntityReference(reference);
this.entityReference = this.entityRef.getReference();
this.entityId = this.entityRef.getId();
this.entityDisplayTitle = displayTitle;
this.entityURL = EntityView.DIRECT_PREFIX + this.entityReference;
setData(entity);
setEntityProperties(entityProperties);
}
/**
* Minimal constructor - used for most basic cases<br/>
* Use the setters to add in properties or the entity data if desired
*
* @param ref an object which represents a globally unique reference to an entity,
* consists of the entity prefix and id
* @param entityDisplayTitle a string which is suitable for display and provides a short summary of the entity,
* typically 100 chars or less, this may be the name or title of the entity represented by an entity
*/
public EntityData(EntityReference ref, String displayTitle) {
this(ref, displayTitle, null, null);
}
/**
* Basic constructor<br/>
* Use this to construct a search result using the typical minimal amount of information,
* Use the setters to add in properties or the entity data if desired
*
* @param ref an object which represents a globally unique reference to an entity,
* consists of the entity prefix and id
* @param entityDisplayTitle a string which is suitable for display and provides a short summary of the entity,
* typically 100 chars or less, this may be the name or title of the entity represented by an entity
* @param data an entity data object, see {@link Resolvable}
*/
public EntityData(EntityReference ref, String displayTitle, Object entity) {
this(ref, displayTitle, entity, null);
}
/**
* Full constructor<br/>
* Use this if you want to return the entity itself along with the key meta data and properties
*
* @param ref an object which represents a globally unique reference to an entity,
* consists of the entity prefix and id
* @param entityDisplayTitle a string which is suitable for display and provides a short summary of the entity,
* typically 100 chars or less, this may be the name or title of the entity represented by an entity
* @param data an entity data object, see {@link Resolvable}
* @param entityProperties a set of properties to return along with the entity information,
* this may be presented and used for filtering,
*/
public EntityData(EntityReference ref, String displayTitle,
Object entity, Map<String, Object> entityProperties) {
if (ref == null || ref.isEmpty()) {
throw new IllegalArgumentException("reference object cannot be null and must have values set");
}
this.entityRef = ref;
this.entityReference = this.entityRef.getReference();
this.entityId = this.entityRef.getId();
this.entityDisplayTitle = displayTitle;
this.entityURL = EntityView.DIRECT_PREFIX + this.entityReference;
this.entityDisplayTitle = displayTitle;
setData(entity);
setEntityProperties(entityProperties);
}
/**
* Using this as a data wrapper only
* @param data any data to wrap this in
*/
public EntityData(Object data) {
this(data, null);
}
/**
* Using this as a data wrapper only
* @param data any data to wrap this in
* @param entityProperties a set of properties to return along with the entity information,
* this may be presented and used for filtering,
*/
public EntityData(Object data, Map<String, Object> entityProperties) {
setData(data);
setEntityProperties(entityProperties);
this.dataOnly = true;
}
@Override
public boolean equals(Object obj) {
if (null == obj)
return false;
if (!(obj instanceof EntityData))
return false;
else {
EntityData castObj = (EntityData) obj;
if (null == this.entityReference || null == castObj.entityReference)
return false;
else
return (this.entityReference.equals(castObj.entityReference));
}
}
@Override
public int hashCode() {
String hashStr = this.getClass().getName() + ":" + this.entityReference.hashCode();
return hashStr.hashCode();
}
@Override
public String toString() {
return "ED: ref="+entityReference+":display="+entityDisplayTitle+":url="+entityURL+":props("+getEntityProperties().size()+"):dataOnly="+dataOnly+":data="+data;
}
public static class ReferenceComparator implements Comparator<EntityData>, Serializable {
public final static long serialVersionUID = 1l;
public int compare(EntityData o1, EntityData o2) {
return o1.entityReference.compareTo(o2.entityReference);
}
}
public static class TitleComparator implements Comparator<EntityData>, Serializable {
public final static long serialVersionUID = 1l;
public int compare(EntityData o1, EntityData o2) {
return o1.getDisplayTitle().compareTo(o2.getDisplayTitle());
}
}
}
| apache-2.0 |
asedunov/intellij-community | java/java-tests/testData/codeInsight/completion/normal/KeywordSmartEnter_after.java | 119 | public class Bar {
{
String nullity = "";
if (this != null) {
<caret>
}
}
} | apache-2.0 |
asedunov/intellij-community | plugins/testng/testData/javadoc2Annotation/before3.java | 109 | /**
* @<caret>testng.test groups = "group1"
*/
public class Testt {
public void testGroups(){
}
}
| apache-2.0 |
android-ia/platform_tools_idea | java/java-tests/testData/psi/parser-full/declarationParsing/method/Errors0.java | 133 | // illegal modifier combinations
abstract public class a {
public static <error descr="2">protected int f1 = 0;
}
class ff {
} | apache-2.0 |
007slm/kissy | tools/module-compiler/src/com/google/javascript/jscomp/graph/Annotation.java | 791 | /*
* Copyright 2008 The Closure Compiler 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.javascript.jscomp.graph;
/**
* Information that can be annotated to a {@link GraphNode} or
* {@link Graph.GraphEdge}.
*/
public interface Annotation {
}
| mit |
asedunov/intellij-community | java/java-tests/testData/refactoring/inlineParameter/RefLocalConstantInitializer.java | 229 | public class A {
void test(String s1, String <caret>s2) {
System.out.println(s1);
System.out.println(s2);
}
void callTest() {
String s = "";
String t = "";
test(s, t);
}
}
| apache-2.0 |
YMartsynkevych/camel | components/camel-mina/src/test/java/org/apache/camel/component/mina/MinaProducerConcurrentTest.java | 3416 | /**
* 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.mina;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.junit.Test;
/**
* @version
*/
public class MinaProducerConcurrentTest extends BaseMinaTest {
@Test
public void testNoConcurrentProducers() throws Exception {
doSendMessages(1, 1);
}
@Test
public void testConcurrentProducers() throws Exception {
doSendMessages(10, 5);
}
private void doSendMessages(int files, int poolSize) throws Exception {
getMockEndpoint("mock:result").expectedMessageCount(files);
ExecutorService executor = Executors.newFixedThreadPool(poolSize);
// we access the responses Map below only inside the main thread,
// so no need for a thread-safe Map implementation
Map<Integer, Future<String>> responses = new HashMap<Integer, Future<String>>();
for (int i = 0; i < files; i++) {
final int index = i;
Future<String> out = executor.submit(new Callable<String>() {
public String call() throws Exception {
return template.requestBody("mina:tcp://localhost:{{port}}?sync=true", index, String.class);
}
});
responses.put(index, out);
}
assertMockEndpointsSatisfied();
assertEquals(files, responses.size());
// get all responses
Set<String> unique = new HashSet<String>();
for (Future<String> future : responses.values()) {
unique.add(future.get());
}
// should be 'files' unique responses
assertEquals("Should be " + files + " unique responses", files, unique.size());
executor.shutdownNow();
}
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
public void configure() throws Exception {
from("mina:tcp://localhost:{{port}}?sync=true").process(new Processor() {
public void process(Exchange exchange) throws Exception {
String body = exchange.getIn().getBody(String.class);
exchange.getOut().setBody("Bye " + body);
}
}).to("mock:result");
}
};
}
}
| apache-2.0 |
YMartsynkevych/camel | camel-core/src/test/java/org/apache/camel/processor/SplitterOnPrepareTest.java | 2724 | /**
* 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.processor;
import java.util.ArrayList;
import java.util.List;
import org.apache.camel.ContextTestSupport;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
/**
*
*/
public class SplitterOnPrepareTest extends ContextTestSupport {
public void testSplitterOnPrepare() throws Exception {
getMockEndpoint("mock:a").expectedMessageCount(2);
getMockEndpoint("mock:a").allMessages().body(String.class).isEqualTo("1 Tony the Tiger");
List<Animal> animals = new ArrayList<Animal>();
animals.add(new Animal(1, "Tiger"));
animals.add(new Animal(1, "Tiger"));
template.sendBody("direct:start", animals);
assertMockEndpointsSatisfied();
}
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
from("direct:start")
.split(body()).onPrepare(new FixNamePrepare())
.to("direct:a");
from("direct:a").process(new ProcessorA()).to("mock:a");
}
};
}
public static class ProcessorA implements Processor {
@Override
public void process(Exchange exchange) throws Exception {
Animal body = exchange.getIn().getBody(Animal.class);
assertEquals(1, body.getId());
assertEquals("Tony the Tiger", body.getName());
}
}
public static final class FixNamePrepare implements Processor {
public void process(Exchange exchange) throws Exception {
Animal body = exchange.getIn().getBody(Animal.class);
assertEquals(1, body.getId());
assertEquals("Tiger", body.getName());
body.setName("Tony the Tiger");
}
}
}
| apache-2.0 |
boneman1231/org.apache.felix | trunk/org.osgi.compendium/src/main/java/org/osgi/service/deploymentadmin/spi/ResourceProcessor.java | 6530 | /*
* Copyright (c) OSGi Alliance (2005, 2008). 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.osgi.service.deploymentadmin.spi;
import java.io.InputStream;
/**
* ResourceProcessor interface is implemented by processors handling resource files
* in deployment packages. Resource Processors expose their services as standard OSGi services.
* Bundles exporting the service may arrive in the deployment package (customizers) or may be
* preregistered (they are installed previously). Resource processors has to define the
* <code>service.pid</code> standard OSGi service property which should be a unique string.<p>
*
* The order of the method calls on a particular Resource Processor in case of install/update
* session is the following:<p>
*
* <ol>
* <li>{@link #begin(DeploymentSession)}</li>
* <li>{@link #process(String, InputStream)} calls till there are resources to process
* or {@link #rollback()} and the further steps are ignored</li>
* <li>{@link #dropped(String)} calls till there are resources to drop
* <li>{@link #prepare()}</li>
* <li>{@link #commit()} or {@link #rollback()}</li>
* </ol>
*
* The order of the method calls on a particular Resource Processor in case of uninstall
* session is the following:<p>
*
* <ol>
* <li>{@link #begin(DeploymentSession)}</li>
* <li>{@link #dropAllResources()} or {@link #rollback()} and the further steps are ignored</li>
* <li>{@link #prepare()}</li>
* <li>{@link #commit()} or {@link #rollback()}</li>
* </ol>
*/
public interface ResourceProcessor {
/**
* Called when the Deployment Admin starts a new operation on the given deployment package,
* and the resource processor is associated a resource within the package. Only one
* deployment package can be processed at a time.
*
* @param session object that represents the current session to the resource processor
* @see DeploymentSession
*/
void begin(DeploymentSession session);
/**
* Called when a resource is encountered in the deployment package for which this resource
* processor has been selected to handle the processing of that resource.
*
* @param name The name of the resource relative to the deployment package root directory.
* @param stream The stream for the resource.
* @throws ResourceProcessorException if the resource cannot be processed. Only
* {@link ResourceProcessorException#CODE_RESOURCE_SHARING_VIOLATION} and
* {@link ResourceProcessorException#CODE_OTHER_ERROR} error codes are allowed.
*/
void process(String name, InputStream stream) throws ResourceProcessorException;
/**
* Called when a resource, associated with a particular resource processor, had belonged to
* an earlier version of a deployment package but is not present in the current version of
* the deployment package. This provides an opportunity for the processor to cleanup any
* memory and persistent data being maintained for the particular resource.
* This method will only be called during "update" deployment sessions.
*
* @param resource the name of the resource to drop (it is the same as the value of the
* "Name" attribute in the deployment package's manifest)
* @throws ResourceProcessorException if the resource is not allowed to be dropped. Only the
* {@link ResourceProcessorException#CODE_OTHER_ERROR} error code is allowed
*/
void dropped(String resource) throws ResourceProcessorException;
/**
* This method is called during an "uninstall" deployment session.
* This method will be called on all resource processors that are associated with resources
* in the deployment package being uninstalled. This provides an opportunity for the processor
* to cleanup any memory and persistent data being maintained for the deployment package.
*
* @throws ResourceProcessorException if all resources could not be dropped. Only the
* {@link ResourceProcessorException#CODE_OTHER_ERROR} is allowed.
*/
void dropAllResources() throws ResourceProcessorException;
/**
* This method is called on the Resource Processor immediately before calling the
* <code>commit</code> method. The Resource Processor has to check whether it is able
* to commit the operations since the last <code>begin</code> method call. If it determines
* that it is not able to commit the changes, it has to raise a
* <code>ResourceProcessorException</code> with the {@link ResourceProcessorException#CODE_PREPARE}
* error code.
*
* @throws ResourceProcessorException if the resource processor is able to determine it is
* not able to commit. Only the {@link ResourceProcessorException#CODE_PREPARE} error
* code is allowed.
*/
void prepare() throws ResourceProcessorException;
/**
* Called when the processing of the current deployment package is finished.
* This method is called if the processing of the current deployment package was successful,
* and the changes must be made permanent.
*/
void commit();
/**
* Called when the processing of the current deployment package is finished.
* This method is called if the processing of the current deployment package was unsuccessful,
* and the changes made during the processing of the deployment package should be removed.
*/
void rollback();
/**
* Processing of a resource passed to the resource processor may take long.
* The <code>cancel()</code> method notifies the resource processor that it should
* interrupt the processing of the current resource. This method is called by the
* <code>DeploymentAdmin</code> implementation after the
* <code>DeploymentAdmin.cancel()</code> method is called.
*/
void cancel();
}
| apache-2.0 |
cnfire/hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-sharedcachemanager/src/main/java/org/apache/hadoop/yarn/server/sharedcachemanager/metrics/ClientSCMMetrics.java | 2961 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.yarn.server.sharedcachemanager.metrics;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.classification.InterfaceAudience.Private;
import org.apache.hadoop.classification.InterfaceStability.Unstable;
import org.apache.hadoop.metrics2.MetricsSystem;
import org.apache.hadoop.metrics2.annotation.Metric;
import org.apache.hadoop.metrics2.annotation.Metrics;
import org.apache.hadoop.metrics2.lib.DefaultMetricsSystem;
import org.apache.hadoop.metrics2.lib.MetricsRegistry;
import org.apache.hadoop.metrics2.lib.MutableCounterLong;
/**
* This class is for maintaining client requests metrics
* and publishing them through the metrics interfaces.
*/
@Private
@Unstable
@Metrics(about="Client SCM metrics", context="yarn")
public class ClientSCMMetrics {
private static final Log LOG = LogFactory.getLog(ClientSCMMetrics.class);
final MetricsRegistry registry;
private final static ClientSCMMetrics INSTANCE = create();
private ClientSCMMetrics() {
registry = new MetricsRegistry("clientRequests");
LOG.debug("Initialized " + registry);
}
public static ClientSCMMetrics getInstance() {
return INSTANCE;
}
static ClientSCMMetrics create() {
MetricsSystem ms = DefaultMetricsSystem.instance();
ClientSCMMetrics metrics = new ClientSCMMetrics();
ms.register("clientRequests", null, metrics);
return metrics;
}
@Metric("Number of cache hits") MutableCounterLong cacheHits;
@Metric("Number of cache misses") MutableCounterLong cacheMisses;
@Metric("Number of cache releases") MutableCounterLong cacheReleases;
/**
* One cache hit event
*/
public void incCacheHitCount() {
cacheHits.incr();
}
/**
* One cache miss event
*/
public void incCacheMissCount() {
cacheMisses.incr();
}
/**
* One cache release event
*/
public void incCacheRelease() {
cacheReleases.incr();
}
public long getCacheHits() { return cacheHits.value(); }
public long getCacheMisses() { return cacheMisses.value(); }
public long getCacheReleases() { return cacheReleases.value(); }
}
| apache-2.0 |
SanDisk-Open-Source/SSD_Dashboard | uefi/gcc/gcc-4.6.3/libjava/classpath/javax/swing/text/CompositeView.java | 26996 | /* CompositeView.java -- An abstract view that manages child views
Copyright (C) 2005, 2006 Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package javax.swing.text;
import java.awt.Rectangle;
import java.awt.Shape;
import javax.swing.SwingConstants;
/**
* An abstract base implementation of {@link View} that manages child
* <code>View</code>s.
*
* @author Roman Kennke (roman@kennke.org)
*/
public abstract class CompositeView
extends View
{
/**
* The child views of this <code>CompositeView</code>.
*/
private View[] children;
/**
* The number of child views.
*/
private int numChildren;
/**
* The allocation of this <code>View</code> minus its insets. This is
* initialized in {@link #getInsideAllocation} and reused and modified in
* {@link #childAllocation(int, Rectangle)}.
*/
private final Rectangle insideAllocation = new Rectangle();
/**
* The insets of this <code>CompositeView</code>. This is initialized
* in {@link #setInsets}.
*/
private short top;
private short bottom;
private short left;
private short right;
/**
* Creates a new <code>CompositeView</code> for the given
* <code>Element</code>.
*
* @param element the element that is rendered by this CompositeView
*/
public CompositeView(Element element)
{
super(element);
children = new View[0];
top = 0;
bottom = 0;
left = 0;
right = 0;
}
/**
* Loads the child views of this <code>CompositeView</code>. This method
* is called from {@link #setParent} to initialize the child views of
* this composite view.
*
* @param f the view factory to use for creating new child views
*
* @see #setParent
*/
protected void loadChildren(ViewFactory f)
{
if (f != null)
{
Element el = getElement();
int count = el.getElementCount();
View[] newChildren = new View[count];
for (int i = 0; i < count; ++i)
{
Element child = el.getElement(i);
View view = f.create(child);
newChildren[i] = view;
}
// I'd have called replace(0, getViewCount(), newChildren) here
// in order to replace all existing views. However according to
// Harmony's tests this is not what the RI does.
replace(0, 0, newChildren);
}
}
/**
* Sets the parent of this <code>View</code>.
* In addition to setting the parent, this calls {@link #loadChildren}, if
* this <code>View</code> does not already have its children initialized.
*
* @param parent the parent to set
*/
public void setParent(View parent)
{
super.setParent(parent);
if (parent != null && numChildren == 0)
loadChildren(getViewFactory());
}
/**
* Returns the number of child views.
*
* @return the number of child views
*/
public int getViewCount()
{
return numChildren;
}
/**
* Returns the child view at index <code>n</code>.
*
* @param n the index of the requested child view
*
* @return the child view at index <code>n</code>
*/
public View getView(int n)
{
return children[n];
}
/**
* Replaces child views by some other child views. If there are no views to
* remove (<code>length == 0</code>), the result is a simple insert, if
* there are no children to add (<code>view == null</code>) the result
* is a simple removal.
*
* @param offset the start offset from where to remove children
* @param length the number of children to remove
* @param views the views that replace the removed children
*/
public void replace(int offset, int length, View[] views)
{
// Make sure we have an array. The Harmony testsuite indicates that we
// have to do something like this.
if (views == null)
views = new View[0];
// First we set the parent of the removed children to null.
int endOffset = offset + length;
for (int i = offset; i < endOffset; ++i)
{
if (children[i].getParent() == this)
children[i].setParent(null);
children[i] = null;
}
// Update the children array.
int delta = views.length - length;
int src = offset + length;
int numMove = numChildren - src;
int dst = src + delta;
if (numChildren + delta > children.length)
{
// Grow array.
int newLength = Math.max(2 * children.length, numChildren + delta);
View[] newChildren = new View[newLength];
System.arraycopy(children, 0, newChildren, 0, offset);
System.arraycopy(views, 0, newChildren, offset, views.length);
System.arraycopy(children, src, newChildren, dst, numMove);
children = newChildren;
}
else
{
// Patch existing array.
System.arraycopy(children, src, children, dst, numMove);
System.arraycopy(views, 0, children, offset, views.length);
}
numChildren += delta;
// Finally we set the parent of the added children to this.
for (int i = 0; i < views.length; ++i)
views[i].setParent(this);
}
/**
* Returns the allocation for the specified child <code>View</code>.
*
* @param index the index of the child view
* @param a the allocation for this view
*
* @return the allocation for the specified child <code>View</code>
*/
public Shape getChildAllocation(int index, Shape a)
{
Rectangle r = getInsideAllocation(a);
childAllocation(index, r);
return r;
}
/**
* Maps a position in the document into the coordinate space of the View.
* The output rectangle usually reflects the font height but has a width
* of zero.
*
* @param pos the position of the character in the model
* @param a the area that is occupied by the view
* @param bias either {@link Position.Bias#Forward} or
* {@link Position.Bias#Backward} depending on the preferred
* direction bias. If <code>null</code> this defaults to
* <code>Position.Bias.Forward</code>
*
* @return a rectangle that gives the location of the document position
* inside the view coordinate space
*
* @throws BadLocationException if <code>pos</code> is invalid
* @throws IllegalArgumentException if b is not one of the above listed
* valid values
*/
public Shape modelToView(int pos, Shape a, Position.Bias bias)
throws BadLocationException
{
boolean backward = bias == Position.Bias.Backward;
int testpos = backward ? Math.max(0, pos - 1) : pos;
Shape ret = null;
if (! backward || testpos >= getStartOffset())
{
int childIndex = getViewIndexAtPosition(testpos);
if (childIndex != -1 && childIndex < getViewCount())
{
View child = getView(childIndex);
if (child != null && testpos >= child.getStartOffset()
&& testpos < child.getEndOffset())
{
Shape childAlloc = getChildAllocation(childIndex, a);
if (childAlloc != null)
{
ret = child.modelToView(pos, childAlloc, bias);
// Handle corner case.
if (ret == null && child.getEndOffset() == pos)
{
childIndex++;
if (childIndex < getViewCount())
{
child = getView(childIndex);
childAlloc = getChildAllocation(childIndex, a);
ret = child.modelToView(pos, childAlloc, bias);
}
}
}
}
}
}
if (ret == null)
throw new BadLocationException("Position " + pos
+ " is not represented by view.", pos);
return ret;
}
/**
* Maps a region in the document into the coordinate space of the View.
*
* @param p1 the beginning position inside the document
* @param b1 the direction bias for the beginning position
* @param p2 the end position inside the document
* @param b2 the direction bias for the end position
* @param a the area that is occupied by the view
*
* @return a rectangle that gives the span of the document region
* inside the view coordinate space
*
* @throws BadLocationException if <code>p1</code> or <code>p2</code> are
* invalid
* @throws IllegalArgumentException if b1 or b2 is not one of the above
* listed valid values
*/
public Shape modelToView(int p1, Position.Bias b1,
int p2, Position.Bias b2, Shape a)
throws BadLocationException
{
// TODO: This is most likely not 100% ok, figure out what else is to
// do here.
return super.modelToView(p1, b1, p2, b2, a);
}
/**
* Maps coordinates from the <code>View</code>'s space into a position
* in the document model.
*
* @param x the x coordinate in the view space, x >= 0
* @param y the y coordinate in the view space, y >= 0
* @param a the allocation of this <code>View</code>
* @param b the bias to use
*
* @return the position in the document that corresponds to the screen
* coordinates <code>x, y</code> >= 0
*/
public int viewToModel(float x, float y, Shape a, Position.Bias[] b)
{
if (x >= 0 && y >= 0)
{
Rectangle r = getInsideAllocation(a);
View view = getViewAtPoint((int) x, (int) y, r);
return view.viewToModel(x, y, r, b);
}
return 0;
}
/**
* Returns the next model location that is visible in eiter north / south
* direction or east / west direction. This is used to determine the placement
* of the caret when navigating around the document with the arrow keys. This
* is a convenience method for {@link #getNextNorthSouthVisualPositionFrom}
* and {@link #getNextEastWestVisualPositionFrom}.
*
* @param pos
* the model position to start search from
* @param b
* the bias for <code>pos</code>
* @param a
* the allocated region for this view
* @param direction
* the direction from the current position, can be one of the
* following:
* <ul>
* <li>{@link SwingConstants#WEST}</li>
* <li>{@link SwingConstants#EAST}</li>
* <li>{@link SwingConstants#NORTH}</li>
* <li>{@link SwingConstants#SOUTH}</li>
* </ul>
* @param biasRet
* the bias of the return value gets stored here
* @return the position inside the model that represents the next visual
* location
* @throws BadLocationException
* if <code>pos</code> is not a valid location inside the document
* model
* @throws IllegalArgumentException
* if <code>direction</code> is invalid
*/
public int getNextVisualPositionFrom(int pos, Position.Bias b, Shape a,
int direction, Position.Bias[] biasRet)
throws BadLocationException
{
int retVal = -1;
switch (direction)
{
case SwingConstants.WEST:
case SwingConstants.EAST:
retVal = getNextEastWestVisualPositionFrom(pos, b, a, direction,
biasRet);
break;
case SwingConstants.NORTH:
case SwingConstants.SOUTH:
retVal = getNextNorthSouthVisualPositionFrom(pos, b, a, direction,
biasRet);
break;
default:
throw new IllegalArgumentException("Illegal value for direction.");
}
return retVal;
}
/**
* Returns the index of the child view that represents the specified
* model location.
*
* @param pos the model location for which to determine the child view index
* @param b the bias to be applied to <code>pos</code>
*
* @return the index of the child view that represents the specified
* model location
*/
public int getViewIndex(int pos, Position.Bias b)
{
if (b == Position.Bias.Backward)
pos -= 1;
int i = -1;
if (pos >= getStartOffset() && pos < getEndOffset())
i = getViewIndexAtPosition(pos);
return i;
}
/**
* Returns <code>true</code> if the specified point lies before the
* given <code>Rectangle</code>, <code>false</code> otherwise.
*
* "Before" is typically defined as being to the left or above.
*
* @param x the X coordinate of the point
* @param y the Y coordinate of the point
* @param r the rectangle to test the point against
*
* @return <code>true</code> if the specified point lies before the
* given <code>Rectangle</code>, <code>false</code> otherwise
*/
protected abstract boolean isBefore(int x, int y, Rectangle r);
/**
* Returns <code>true</code> if the specified point lies after the
* given <code>Rectangle</code>, <code>false</code> otherwise.
*
* "After" is typically defined as being to the right or below.
*
* @param x the X coordinate of the point
* @param y the Y coordinate of the point
* @param r the rectangle to test the point against
*
* @return <code>true</code> if the specified point lies after the
* given <code>Rectangle</code>, <code>false</code> otherwise
*/
protected abstract boolean isAfter(int x, int y, Rectangle r);
/**
* Returns the child <code>View</code> at the specified location.
*
* @param x the X coordinate
* @param y the Y coordinate
* @param r the inner allocation of this <code>BoxView</code> on entry,
* the allocation of the found child on exit
*
* @return the child <code>View</code> at the specified location
*/
protected abstract View getViewAtPoint(int x, int y, Rectangle r);
/**
* Computes the allocation for a child <code>View</code>. The parameter
* <code>a</code> stores the allocation of this <code>CompositeView</code>
* and is then adjusted to hold the allocation of the child view.
*
* @param index the index of the child <code>View</code>
* @param a the allocation of this <code>CompositeView</code> before the
* call, the allocation of the child on exit
*/
protected abstract void childAllocation(int index, Rectangle a);
/**
* Returns the child <code>View</code> that contains the given model
* position. The given <code>Rectangle</code> gives the parent's allocation
* and is changed to the child's allocation on exit.
*
* @param pos the model position to query the child <code>View</code> for
* @param a the parent allocation on entry and the child allocation on exit
*
* @return the child view at the given model position
*/
protected View getViewAtPosition(int pos, Rectangle a)
{
View view = null;
int i = getViewIndexAtPosition(pos);
if (i >= 0 && i < getViewCount() && a != null)
{
view = getView(i);
childAllocation(i, a);
}
return view;
}
/**
* Returns the index of the child <code>View</code> for the given model
* position.
*
* @param pos the model position for whicht the child <code>View</code> is
* queried
*
* @return the index of the child <code>View</code> for the given model
* position
*/
protected int getViewIndexAtPosition(int pos)
{
// We have a 1:1 mapping of elements to views here, so we forward
// this to the element.
Element el = getElement();
return el.getElementIndex(pos);
}
/**
* Returns the allocation that is given to this <code>CompositeView</code>
* minus this <code>CompositeView</code>'s insets.
*
* Also this translates from an immutable allocation to a mutable allocation
* that is typically reused and further narrowed, like in
* {@link #childAllocation}.
*
* @param a the allocation given to this <code>CompositeView</code>
*
* @return the allocation that is given to this <code>CompositeView</code>
* minus this <code>CompositeView</code>'s insets or
* <code>null</code> if a was <code>null</code>
*/
protected Rectangle getInsideAllocation(Shape a)
{
if (a == null)
return null;
// Try to avoid allocation of Rectangle here.
Rectangle alloc = a instanceof Rectangle ? (Rectangle) a : a.getBounds();
// Initialize the inside allocation rectangle. This is done inside
// a synchronized block in order to avoid multiple threads creating
// this instance simultanously.
Rectangle inside = insideAllocation;
inside.x = alloc.x + getLeftInset();
inside.y = alloc.y + getTopInset();
inside.width = alloc.width - getLeftInset() - getRightInset();
inside.height = alloc.height - getTopInset() - getBottomInset();
return inside;
}
/**
* Sets the insets defined by attributes in <code>attributes</code>. This
* queries the attribute keys {@link StyleConstants#SpaceAbove},
* {@link StyleConstants#SpaceBelow}, {@link StyleConstants#LeftIndent} and
* {@link StyleConstants#RightIndent} and calls {@link #setInsets} to
* actually set the insets on this <code>CompositeView</code>.
*
* @param attributes the attributes from which to query the insets
*/
protected void setParagraphInsets(AttributeSet attributes)
{
top = (short) StyleConstants.getSpaceAbove(attributes);
bottom = (short) StyleConstants.getSpaceBelow(attributes);
left = (short) StyleConstants.getLeftIndent(attributes);
right = (short) StyleConstants.getRightIndent(attributes);
}
/**
* Sets the insets of this <code>CompositeView</code>.
*
* @param t the top inset
* @param l the left inset
* @param b the bottom inset
* @param r the right inset
*/
protected void setInsets(short t, short l, short b, short r)
{
top = t;
left = l;
bottom = b;
right = r;
}
/**
* Returns the left inset of this <code>CompositeView</code>.
*
* @return the left inset of this <code>CompositeView</code>
*/
protected short getLeftInset()
{
return left;
}
/**
* Returns the right inset of this <code>CompositeView</code>.
*
* @return the right inset of this <code>CompositeView</code>
*/
protected short getRightInset()
{
return right;
}
/**
* Returns the top inset of this <code>CompositeView</code>.
*
* @return the top inset of this <code>CompositeView</code>
*/
protected short getTopInset()
{
return top;
}
/**
* Returns the bottom inset of this <code>CompositeView</code>.
*
* @return the bottom inset of this <code>CompositeView</code>
*/
protected short getBottomInset()
{
return bottom;
}
/**
* Returns the next model location that is visible in north or south
* direction.
* This is used to determine the
* placement of the caret when navigating around the document with
* the arrow keys.
*
* @param pos the model position to start search from
* @param b the bias for <code>pos</code>
* @param a the allocated region for this view
* @param direction the direction from the current position, can be one of
* the following:
* <ul>
* <li>{@link SwingConstants#NORTH}</li>
* <li>{@link SwingConstants#SOUTH}</li>
* </ul>
* @param biasRet the bias of the return value gets stored here
*
* @return the position inside the model that represents the next visual
* location
*
* @throws BadLocationException if <code>pos</code> is not a valid location
* inside the document model
* @throws IllegalArgumentException if <code>direction</code> is invalid
*/
protected int getNextNorthSouthVisualPositionFrom(int pos, Position.Bias b,
Shape a, int direction,
Position.Bias[] biasRet)
throws BadLocationException
{
// TODO: It is unknown to me how this method has to be implemented and
// there is no specification telling me how to do it properly. Therefore
// the implementation was done for cases that are known.
//
// If this method ever happens to act silly for your particular case then
// it is likely that it is a cause of not knowing about your case when it
// was implemented first. You are free to fix the behavior.
//
// Here are the assumptions that lead to the implementation:
// If direction is NORTH chose the View preceding the one that contains the
// offset 'pos' (imagine the views are stacked on top of each other where
// the top is 0 and the bottom is getViewCount()-1.
// Consecutively when the direction is SOUTH the View following the one
// the offset 'pos' lies in is questioned.
//
// This limitation is described as PR 27345.
int index = getViewIndex(pos, b);
View v = null;
if (index == -1)
return pos;
switch (direction)
{
case NORTH:
// If we cannot calculate a proper offset return the one that was
// provided.
if (index <= 0)
return pos;
v = getView(index - 1);
break;
case SOUTH:
// If we cannot calculate a proper offset return the one that was
// provided.
if (index >= getViewCount() - 1)
return pos;
v = getView(index + 1);
break;
default:
throw new IllegalArgumentException();
}
return v.getNextVisualPositionFrom(pos, b, a, direction, biasRet);
}
/**
* Returns the next model location that is visible in east or west
* direction.
* This is used to determine the
* placement of the caret when navigating around the document with
* the arrow keys.
*
* @param pos the model position to start search from
* @param b the bias for <code>pos</code>
* @param a the allocated region for this view
* @param direction the direction from the current position, can be one of
* the following:
* <ul>
* <li>{@link SwingConstants#EAST}</li>
* <li>{@link SwingConstants#WEST}</li>
* </ul>
* @param biasRet the bias of the return value gets stored here
*
* @return the position inside the model that represents the next visual
* location
*
* @throws BadLocationException if <code>pos</code> is not a valid location
* inside the document model
* @throws IllegalArgumentException if <code>direction</code> is invalid
*/
protected int getNextEastWestVisualPositionFrom(int pos, Position.Bias b,
Shape a, int direction,
Position.Bias[] biasRet)
throws BadLocationException
{
// TODO: It is unknown to me how this method has to be implemented and
// there is no specification telling me how to do it properly. Therefore
// the implementation was done for cases that are known.
//
// If this method ever happens to act silly for your particular case then
// it is likely that it is a cause of not knowing about your case when it
// was implemented first. You are free to fix the behavior.
//
// Here are the assumptions that lead to the implementation:
// If direction is EAST increase the offset by one and ask the View to
// which that index belong to calculate the 'next visual position'.
// If the direction is WEST do the same with offset 'pos' being decreased
// by one.
// This behavior will fail in a right-to-left or bidi environment!
//
// This limitation is described as PR 27346.
int index;
View v = null;
switch (direction)
{
case EAST:
index = getViewIndex(pos + 1, b);
// If we cannot calculate a proper offset return the one that was
// provided.
if (index == -1)
return pos;
v = getView(index);
break;
case WEST:
index = getViewIndex(pos - 1, b);
// If we cannot calculate a proper offset return the one that was
// provided.
if (index == -1)
return pos;
v = getView(index);
break;
default:
throw new IllegalArgumentException();
}
return v.getNextVisualPositionFrom(pos,
b,
a,
direction,
biasRet);
}
/**
* Determines if the next view in horinzontal direction is located to
* the east or west of the view at position <code>pos</code>. Usually
* the <code>View</code>s are laid out from the east to the west, so
* we unconditionally return <code>false</code> here. Subclasses that
* support bidirectional text may wish to override this method.
*
* @param pos the position in the document
* @param bias the bias to be applied to <code>pos</code>
*
* @return <code>true</code> if the next <code>View</code> is located
* to the EAST, <code>false</code> otherwise
*/
protected boolean flipEastAndWestAtEnds(int pos, Position.Bias bias)
{
return false;
}
}
| gpl-2.0 |
SanDisk-Open-Source/SSD_Dashboard | uefi/gcc/gcc-4.6.3/libjava/classpath/javax/swing/text/TabExpander.java | 1839 | /* TabExpander.java --
Copyright (C) 2004 Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package javax.swing.text;
public interface TabExpander
{
float nextTabStop(float x, int tabOffset);
}
| gpl-2.0 |
SanDisk-Open-Source/SSD_Dashboard | uefi/gcc/gcc-4.6.3/libjava/classpath/tools/external/asm/org/objectweb/asm/util/attrs/ASMStackMapTableAttribute.java | 7930 | /**
* ASM: a very small and fast Java bytecode manipulation framework
* Copyright (c) 2000-2005 INRIA, France Telecom
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.objectweb.asm.util.attrs;
import java.util.List;
import java.util.Map;
import org.objectweb.asm.Attribute;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.Label;
import org.objectweb.asm.attrs.StackMapTableAttribute;
import org.objectweb.asm.attrs.StackMapFrame;
import org.objectweb.asm.attrs.StackMapType;
/**
* An {@link ASMifiable} {@link StackMapTableAttribute} sub class.
*
* @author Eugene Kuleshov
*/
public class ASMStackMapTableAttribute extends StackMapTableAttribute implements
ASMifiable,
Traceable
{
/**
* Length of the attribute used for comparison
*/
private int len;
public ASMStackMapTableAttribute() {
super();
}
public ASMStackMapTableAttribute(List frames, int len) {
super(frames);
this.len = len;
}
protected Attribute read(
ClassReader cr,
int off,
int len,
char[] buf,
int codeOff,
Label[] labels)
{
StackMapTableAttribute attr = (StackMapTableAttribute) super.read(cr,
off,
len,
buf,
codeOff,
labels);
return new ASMStackMapTableAttribute(attr.getFrames(), len);
}
public void asmify(StringBuffer buf, String varName, Map labelNames) {
List frames = getFrames();
if (frames.size() == 0) {
buf.append("List frames = Collections.EMPTY_LIST;\n");
} else {
buf.append("List frames = new ArrayList();\n");
for (int i = 0; i < frames.size(); i++) {
buf.append("{\n");
StackMapFrame f = (StackMapFrame) frames.get(i);
declareLabel(buf, labelNames, f.label);
String frameVar = varName + "frame" + i;
asmifyTypeInfo(buf, frameVar, labelNames, f.locals, "locals");
asmifyTypeInfo(buf, frameVar, labelNames, f.stack, "stack");
buf.append("StackMapFrame ")
.append(frameVar)
.append(" = new StackMapFrame(")
.append(labelNames.get(f.label))
.append(", locals, stack);\n");
buf.append("frames.add(").append(frameVar).append(");\n");
buf.append("}\n");
}
}
buf.append("StackMapTableAttribute ").append(varName);
buf.append(" = new StackMapTableAttribute(frames);\n");
}
void asmifyTypeInfo(
StringBuffer buf,
String varName,
Map labelNames,
List infos,
String field)
{
if (infos.size() == 0) {
buf.append("List ")
.append(field)
.append(" = Collections.EMPTY_LIST;\n");
} else {
buf.append("List ").append(field).append(" = new ArrayList();\n");
buf.append("{\n");
for (int i = 0; i < infos.size(); i++) {
StackMapType typeInfo = (StackMapType) infos.get(i);
String localName = varName + "Info" + i;
int type = typeInfo.getType();
buf.append("StackMapType ")
.append(localName)
.append(" = StackMapType.getTypeInfo( StackMapType.ITEM_")
.append(StackMapType.ITEM_NAMES[type])
.append(");\n");
switch (type) {
case StackMapType.ITEM_Object: //
buf.append(localName)
.append(".setObject(\"")
.append(typeInfo.getObject())
.append("\");\n");
break;
case StackMapType.ITEM_Uninitialized: //
declareLabel(buf, labelNames, typeInfo.getLabel());
buf.append(localName)
.append(".setLabel(")
.append(labelNames.get(typeInfo.getLabel()))
.append(");\n");
break;
}
buf.append(field)
.append(".add(")
.append(localName)
.append(");\n");
}
buf.append("}\n");
}
}
static void declareLabel(StringBuffer buf, Map labelNames, Label l) {
String name = (String) labelNames.get(l);
if (name == null) {
name = "l" + labelNames.size();
labelNames.put(l, name);
buf.append("Label ").append(name).append(" = new Label();\n");
}
}
public void trace(StringBuffer buf, Map labelNames) {
List frames = getFrames();
buf.append("[\n");
for (int i = 0; i < frames.size(); i++) {
StackMapFrame f = (StackMapFrame) frames.get(i);
buf.append(" Frame:");
appendLabel(buf, labelNames, f.label);
buf.append(" locals[");
traceTypeInfo(buf, labelNames, f.locals);
buf.append("]");
buf.append(" stack[");
traceTypeInfo(buf, labelNames, f.stack);
buf.append("]\n");
}
buf.append(" ] length:").append(len).append("\n");
}
private void traceTypeInfo(StringBuffer buf, Map labelNames, List infos) {
String sep = "";
for (int i = 0; i < infos.size(); i++) {
StackMapType t = (StackMapType) infos.get(i);
buf.append(sep).append(StackMapType.ITEM_NAMES[t.getType()]);
sep = ", ";
if (t.getType() == StackMapType.ITEM_Object) {
buf.append(":").append(t.getObject());
}
if (t.getType() == StackMapType.ITEM_Uninitialized) {
buf.append(":");
appendLabel(buf, labelNames, t.getLabel());
}
}
}
protected void appendLabel(StringBuffer buf, Map labelNames, Label l) {
String name = (String) labelNames.get(l);
if (name == null) {
name = "L" + labelNames.size();
labelNames.put(l, name);
}
buf.append(name);
}
}
| gpl-2.0 |
jawedm/coursera-android | Examples/ContentProviderCustom/src/course/examples/contentproviders/stringcontentprovider/StringsContentProvider.java | 3464 | package course.examples.contentproviders.stringcontentprovider;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.net.Uri;
import android.util.SparseArray;
// Note: Currently, this data does not persist across device reboot
public class StringsContentProvider extends ContentProvider {
// Data storage
private static final SparseArray<DataRecord> db = new SparseArray<DataRecord>();
@SuppressWarnings("unused")
private static final String TAG = "StringsContentProvider";
// Delete some or all data items
@Override
public synchronized int delete(Uri uri, String selection,
String[] selectionArgs) {
int numRecordsRemoved = 0;
// If last segment is the table name, delete all data items
if (isTableUri(uri)) {
numRecordsRemoved = db.size();
db.clear();
// If last segment is the digit, delete data item with that ID
} else if (isItemUri(uri)) {
Integer requestId = Integer.parseInt(uri.getLastPathSegment());
if (null != db.get(requestId)) {
db.remove(requestId);
numRecordsRemoved++;
}
}
//return number of items deleted
return numRecordsRemoved;
}
// Return MIME type for given uri
@Override
public synchronized String getType(Uri uri) {
String contentType = DataContract.CONTENT_ITEM_TYPE;
if (isTableUri(uri)) {
contentType = DataContract.CONTENT_DIR_TYPE;
}
return contentType;
}
// Insert specified value into ContentProvider
@Override
public synchronized Uri insert(Uri uri, ContentValues value) {
if (value.containsKey(DataContract.DATA)) {
DataRecord dataRecord = new DataRecord(value.getAsString(DataContract.DATA));
db.put(dataRecord.getID(), dataRecord);
// return Uri associated with newly-added data item
return Uri.withAppendedPath(DataContract.CONTENT_URI,
String.valueOf(dataRecord.getID()));
}
return null;
}
// return all or some rows from ContentProvider based on specified Uri
// all other parameters are ignored
@Override
public synchronized Cursor query(Uri uri, String[] projection,
String selection, String[] selectionArgs, String sortOrder) {
// Create simple cursor
MatrixCursor cursor = new MatrixCursor(DataContract.ALL_COLUMNS);
if (isTableUri(uri)) {
// Add all rows to cursor
for (int idx = 0; idx < db.size(); idx++) {
DataRecord dataRecord = db.get(db.keyAt(idx));
cursor.addRow(new Object[] { dataRecord.getID(),
dataRecord.getData() });
}
} else if (isItemUri(uri)){
// Add single row to cursor
Integer requestId = Integer.parseInt(uri.getLastPathSegment());
if (null != db.get(requestId)) {
DataRecord dr = db.get(requestId);
cursor.addRow(new Object[] { dr.getID(), dr.getData() });
}
}
return cursor;
}
// Ignore request
@Override
public synchronized int update(Uri uri, ContentValues values,
String selection, String[] selectionArgs) {
return 0;
}
// Initialize ContentProvider
// Nothing to do in this case
@Override
public boolean onCreate() {
return true;
}
// Does last segment of the Uri match a string of digits?
private boolean isItemUri(Uri uri) {
return uri.getLastPathSegment().matches("\\d+");
}
// Is the last segment of the Uri the name of the data table?
private boolean isTableUri(Uri uri) {
return uri.getLastPathSegment().equals(DataContract.DATA_TABLE);
}
}
| mit |
tseen/Federated-HDFS | tseenliu/FedHDFS-hadoop-src/hadoop-tools/hadoop-gridmix/src/main/java/org/apache/hadoop/mapred/gridmix/FilePool.java | 8894 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.mapred.gridmix;
import java.io.IOException;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.BlockLocation;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.mapred.gridmix.RandomAlgorithms.Selector;
/**
* Class for caching a pool of input data to be used by synthetic jobs for
* simulating read traffic.
*/
class FilePool {
public static final Log LOG = LogFactory.getLog(FilePool.class);
/**
* The minimum file size added to the pool. Default 128MiB.
*/
public static final String GRIDMIX_MIN_FILE = "gridmix.min.file.size";
/**
* The maximum size for files added to the pool. Defualts to 100TiB.
*/
public static final String GRIDMIX_MAX_TOTAL = "gridmix.max.total.scan";
private Node root;
private final Path path;
private final FileSystem fs;
private final Configuration conf;
private final ReadWriteLock updateLock;
/**
* Initialize a filepool under the path provided, but do not populate the
* cache.
*/
public FilePool(Configuration conf, Path input) throws IOException {
root = null;
this.conf = conf;
this.path = input;
this.fs = path.getFileSystem(conf);
updateLock = new ReentrantReadWriteLock();
}
/**
* Gather a collection of files at least as large as minSize.
* @return The total size of files returned.
*/
public long getInputFiles(long minSize, Collection<FileStatus> files)
throws IOException {
updateLock.readLock().lock();
try {
return root.selectFiles(minSize, files);
} finally {
updateLock.readLock().unlock();
}
}
/**
* (Re)generate cache of input FileStatus objects.
*/
public void refresh() throws IOException {
updateLock.writeLock().lock();
try {
root = new InnerDesc(fs, fs.getFileStatus(path),
new MinFileFilter(conf.getLong(GRIDMIX_MIN_FILE, 128 * 1024 * 1024),
conf.getLong(GRIDMIX_MAX_TOTAL, 100L * (1L << 40))));
if (0 == root.getSize()) {
throw new IOException("Found no satisfactory file in " + path);
}
} finally {
updateLock.writeLock().unlock();
}
}
/**
* Get a set of locations for the given file.
*/
public BlockLocation[] locationsFor(FileStatus stat, long start, long len)
throws IOException {
// TODO cache
return fs.getFileBlockLocations(stat, start, len);
}
static abstract class Node {
protected final static Random rand = new Random();
/**
* Total size of files and directories under the current node.
*/
abstract long getSize();
/**
* Return a set of files whose cumulative size is at least
* <tt>targetSize</tt>.
* TODO Clearly size is not the only criterion, e.g. refresh from
* generated data without including running task output, tolerance
* for permission issues, etc.
*/
abstract long selectFiles(long targetSize, Collection<FileStatus> files)
throws IOException;
}
/**
* Files in current directory of this Node.
*/
static class LeafDesc extends Node {
final long size;
final ArrayList<FileStatus> curdir;
LeafDesc(ArrayList<FileStatus> curdir, long size) {
this.size = size;
this.curdir = curdir;
}
@Override
public long getSize() {
return size;
}
@Override
public long selectFiles(long targetSize, Collection<FileStatus> files)
throws IOException {
if (targetSize >= getSize()) {
files.addAll(curdir);
return getSize();
}
Selector selector = new Selector(curdir.size(), (double) targetSize
/ getSize(), rand);
ArrayList<Integer> selected = new ArrayList<Integer>();
long ret = 0L;
do {
int index = selector.next();
selected.add(index);
ret += curdir.get(index).getLen();
} while (ret < targetSize);
for (Integer i : selected) {
files.add(curdir.get(i));
}
return ret;
}
}
/**
* A subdirectory of the current Node.
*/
static class InnerDesc extends Node {
final long size;
final double[] dist;
final Node[] subdir;
private static final Comparator<Node> nodeComparator =
new Comparator<Node>() {
public int compare(Node n1, Node n2) {
return n1.getSize() < n2.getSize() ? -1
: n1.getSize() > n2.getSize() ? 1 : 0;
}
};
InnerDesc(final FileSystem fs, FileStatus thisDir, MinFileFilter filter)
throws IOException {
long fileSum = 0L;
final ArrayList<FileStatus> curFiles = new ArrayList<FileStatus>();
final ArrayList<FileStatus> curDirs = new ArrayList<FileStatus>();
for (FileStatus stat : fs.listStatus(thisDir.getPath())) {
if (stat.isDirectory()) {
curDirs.add(stat);
} else if (filter.accept(stat)) {
curFiles.add(stat);
fileSum += stat.getLen();
}
}
ArrayList<Node> subdirList = new ArrayList<Node>();
if (!curFiles.isEmpty()) {
subdirList.add(new LeafDesc(curFiles, fileSum));
}
for (Iterator<FileStatus> i = curDirs.iterator();
!filter.done() && i.hasNext();) {
// add subdirectories
final Node d = new InnerDesc(fs, i.next(), filter);
final long dSize = d.getSize();
if (dSize > 0) {
fileSum += dSize;
subdirList.add(d);
}
}
size = fileSum;
LOG.debug(size + " bytes in " + thisDir.getPath());
subdir = subdirList.toArray(new Node[subdirList.size()]);
Arrays.sort(subdir, nodeComparator);
dist = new double[subdir.length];
for (int i = dist.length - 1; i > 0; --i) {
fileSum -= subdir[i].getSize();
dist[i] = fileSum / (1.0 * size);
}
}
@Override
public long getSize() {
return size;
}
@Override
public long selectFiles(long targetSize, Collection<FileStatus> files)
throws IOException {
long ret = 0L;
if (targetSize >= getSize()) {
// request larger than all subdirs; add everything
for (Node n : subdir) {
long added = n.selectFiles(targetSize, files);
ret += added;
targetSize -= added;
}
return ret;
}
// can satisfy request in proper subset of contents
// select random set, weighted by size
final HashSet<Node> sub = new HashSet<Node>();
do {
assert sub.size() < subdir.length;
final double r = rand.nextDouble();
int pos = Math.abs(Arrays.binarySearch(dist, r) + 1) - 1;
while (sub.contains(subdir[pos])) {
pos = (pos + 1) % subdir.length;
}
long added = subdir[pos].selectFiles(targetSize, files);
ret += added;
targetSize -= added;
sub.add(subdir[pos]);
} while (targetSize > 0);
return ret;
}
}
/**
* Filter enforcing the minFile/maxTotal parameters of the scan.
*/
private static class MinFileFilter {
private long totalScan;
private final long minFileSize;
public MinFileFilter(long minFileSize, long totalScan) {
this.minFileSize = minFileSize;
this.totalScan = totalScan;
}
public boolean done() {
return totalScan <= 0;
}
public boolean accept(FileStatus stat) {
final boolean done = done();
if (!done && stat.getLen() >= minFileSize) {
totalScan -= stat.getLen();
return true;
}
return false;
}
}
}
| apache-2.0 |
xuzha/elasticsearch | test/framework/src/main/java/org/elasticsearch/test/rest/RestTestCandidate.java | 2096 | /*
* 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.test.rest;
import org.elasticsearch.test.rest.section.RestTestSuite;
import org.elasticsearch.test.rest.section.SetupSection;
import org.elasticsearch.test.rest.section.TestSection;
/**
* Wraps {@link org.elasticsearch.test.rest.section.TestSection}s ready to be run.
* Each test section is associated to its {@link org.elasticsearch.test.rest.section.RestTestSuite}.
*/
public class RestTestCandidate {
private final RestTestSuite restTestSuite;
private final TestSection testSection;
public RestTestCandidate(RestTestSuite restTestSuite, TestSection testSection) {
this.restTestSuite = restTestSuite;
this.testSection = testSection;
}
public String getApi() {
return restTestSuite.getApi();
}
public String getName() {
return restTestSuite.getName();
}
public String getSuitePath() {
return restTestSuite.getPath();
}
public String getTestPath() {
return restTestSuite.getPath() + "/" + testSection.getName();
}
public SetupSection getSetupSection() {
return restTestSuite.getSetupSection();
}
public TestSection getTestSection() {
return testSection;
}
@Override
public String toString() {
return getTestPath();
}
}
| apache-2.0 |
io7m/jmurmur | com.io7m.jmurmur.core/src/main/java/module-info.java | 933 | /*
* Copyright © 2014 <code@io7m.com> http://io7m.com
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
* IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/**
* Murmur hash function (Core)
*/
module com.io7m.jmurmur.core
{
requires com.io7m.junreachable.core;
exports com.io7m.jmurmur;
} | isc |
Endeal/patron-for-android | src/main/java/com/endeal/patron/fragments/CustomizeFragmentPagerAdapter.java | 1183 | package com.endeal.patron.fragments;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class CustomizeFragmentPagerAdapter extends FragmentPagerAdapter
{
private com.endeal.patron.model.Fragment fragment;
public CustomizeFragmentPagerAdapter(FragmentManager fragmentManager, com.endeal.patron.model.Fragment fragment)
{
super(fragmentManager);
this.fragment = fragment;
}
@Override
public CharSequence getPageTitle(int position)
{
if (position == 0)
return "Attributes";
return "Additions";
}
@Override
public Fragment getItem(int position)
{
if (position == 0)
{
FragmentAttributes fragmentAttributes = new FragmentAttributes();
fragmentAttributes.setFragment(this.fragment);
return fragmentAttributes;
}
FragmentOptions fragmentOptions = new FragmentOptions();
fragmentOptions.setFragment(this.fragment);
return fragmentOptions;
}
@Override
public int getCount()
{
return 2;
}
}
| isc |
AWildridge/ProtoScape | src/org/apollo/net/release/r317/TalismanLocateOptionEventDecoder.java | 1140 | package org.apollo.net.release.r317;
import org.apollo.game.event.impl.TalismanLocateEvent;
import org.apollo.net.codec.game.DataOrder;
import org.apollo.net.codec.game.DataTransformation;
import org.apollo.net.codec.game.DataType;
import org.apollo.net.codec.game.GamePacket;
import org.apollo.net.codec.game.GamePacketReader;
import org.apollo.net.release.EventDecoder;
/**
* TalismanLocateOptionPacketHandler.java
* @author The Wanderer
*/
public class TalismanLocateOptionEventDecoder extends EventDecoder<TalismanLocateEvent> {
@Override
public TalismanLocateEvent decode(GamePacket packet) {
GamePacketReader reader = new GamePacketReader(packet);
int interfaceId = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE, DataTransformation.ADD);
int slot = (int) reader.getUnsigned(DataType.SHORT, DataOrder.LITTLE);
int item = (int) reader.getUnsigned(DataType.SHORT, DataTransformation.ADD);
System.out.println("[TALISMAN LOCATING]: interface - " + interfaceId + ", slot - " + slot + ", item - " + item);
return new TalismanLocateEvent(interfaceId, item, slot);
}
}
| isc |
DealerNextDoor/ApolloDev | src/org/apollo/game/model/InventoryConstants.java | 544 | package org.apollo.game.model;
/**
* Holds {@link Inventory}-related constants.
*
* @author Graham
*/
public final class InventoryConstants {
/**
* The capacity of the bank.
*/
public static final int BANK_CAPACITY = 352;
/**
* The capacity of the equipment inventory.
*/
public static final int EQUIPMENT_CAPACITY = 14;
/**
* The capacity of the inventory.
*/
public static final int INVENTORY_CAPACITY = 28;
/**
* Default private constructor to prevent instantiation.
*/
private InventoryConstants() {
}
} | isc |
joshiejack/Harvest-Festival | src/main/java/uk/joshiejack/husbandry/item/ItemFood.java | 1491 | package uk.joshiejack.husbandry.item;
import uk.joshiejack.husbandry.Husbandry;
import uk.joshiejack.penguinlib.item.base.ItemMultiEdible;
import uk.joshiejack.penguinlib.item.interfaces.Edible;
import net.minecraft.util.ResourceLocation;
import static uk.joshiejack.husbandry.Husbandry.MODID;
public class ItemFood extends ItemMultiEdible<ItemFood.Food> {
public ItemFood() {
super(new ResourceLocation(MODID, "food"), Food.class);
setCreativeTab(Husbandry.TAB);
}
public enum Food implements Edible {
SMALL_MAYONNAISE(3, 0.6F), MEDIUM_MAYONNAISE(4, 0.8F), LARGE_MAYONNAISE(5, 1F),
BUTTER(1, 0.2F), /*//TODO: food values >>>*/DINNERROLL(1, 0.1F), BOILED_EGG(1, 0.1F),
ICE_CREAM(1, 0.1F), SMALL_CHEESE(1, 0.1F), MEDIUM_CHEESE(1, 0.1F), LARGE_CHEESE(1, 0.1F),
SMALL_EGG(1, 0.1F), MEDIUM_EGG(1, 0.1F), LARGE_EGG(1, 0.1F), HONEY(1, 0.1F),
SMALL_DUCK_EGG(1, 0.1F), MEDIUM_DUCK_EGG(1, 0.1F), LARGE_DUCK_EGG(1, 0.1F),
SMALL_DUCK_MAYONNAISE(3, 0.6F), MEDIUM_DUCK_MAYONNAISE(4, 0.8F), LARGE_DUCK_MAYONNAISE(5, 1F);
private final int hunger;
private final float saturation;
Food(int hunger, float saturation) {
this.hunger = hunger;
this.saturation = saturation;
}
@Override
public int getHunger() {
return hunger;
}
@Override
public float getSaturation() {
return saturation;
}
}
}
| mit |
alienscience/http-server | src/main/java/uk/org/alienscience/HttpConnectionFactory.java | 474 | package uk.org.alienscience;
import java.nio.channels.SocketChannel;
/**
* Creates new connection objects when a new connection is made
*/
public class HttpConnectionFactory implements TcpConnectionFactory {
private final HttpRoutes routes;
public HttpConnectionFactory(HttpRoutes routes) {
this.routes = routes;
}
@Override
public Runnable newConnection(SocketChannel channel) {
return new HttpConnection(channel, routes);
}
}
| mit |
ivelin1936/Studing-SoftUni- | Databases Frameworks - Hibernate & Spring Data - март 2018/Exercises JSON Processing/product-shop/src/main/java/json/processing/util/serialize/Serializer.java | 177 | package json.processing.util.serialize;
public interface Serializer {
<T> void serialize(T t, String fileName);
<T> T deserialize(Class<T> clazz, String fileName);
}
| mit |
sjfloat/cyclops | cyclops-tuples/src/main/java/com/aol/cyclops/lambda/tuple/lazymap/LazyMap8PTuple8.java | 1076 | package com.aol.cyclops.lambda.tuple.lazymap;
import com.aol.cyclops.lambda.tuple.PTuple8;
import com.aol.cyclops.lambda.tuple.TupleImpl;
import com.aol.cyclops.lambda.utils.LazyImmutable;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.function.Function;
/**
* Created by johnmcclean on 5/21/15.
*/
public class LazyMap8PTuple8<T,T1,T2,T3,T4,T5,T6,T7,T8> extends TupleImpl<T1,T2,T3,T4,T5,T6,T7,T> {
private final LazyImmutable<T> value = LazyImmutable.def();
private final Function<T8, T> fn;
private final PTuple8<T1,T2,T3,T4,T5,T6,T7,T8> host;
public LazyMap8PTuple8( Function<T8, T> fn,PTuple8<T1,T2,T3,T4,T5,T6,T7,T8> host){
super(host.arity());
this.host = host;
this.fn = fn;
}
public T v8(){
return value.computeIfAbsent(()->fn.apply(host.v8()));
}
@Override
public List<Object> getCachedValues() {
return Arrays.asList(v1(), v2());
}
@Override
public Iterator iterator() {
return getCachedValues().iterator();
}
}
| mit |
christoandrew/Gula | layouts/src/main/java/org/lucasr/twowayview/widget/TwoWayView.java | 4034 | /*
* Copyright (C) 2014 Lucas Rocha
*
* 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.lucasr.twowayview.widget;
import android.content.Context;
import android.content.res.TypedArray;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.AttributeSet;
import org.lucasr.twowayview.TwoWayLayoutManager;
import org.lucasr.twowayview.TwoWayLayoutManager.Orientation;
import java.lang.reflect.Constructor;
public class TwoWayView extends RecyclerView {
private static final String LOGTAG = "TwoWayView";
private static final Class<?>[] sConstructorSignature = new Class[]{
Context.class, AttributeSet.class};
final Object[] sConstructorArgs = new Object[2];
public TwoWayView(Context context) {
this(context, null);
}
public TwoWayView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public TwoWayView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
final TypedArray a =
context.obtainStyledAttributes(attrs, R.styleable.twowayview_TwoWayView, defStyle, 0);
final String name = a.getString(R.styleable.twowayview_TwoWayView_twowayview_layoutManager);
if (!TextUtils.isEmpty(name)) {
loadLayoutManagerFromName(context, attrs, name);
}
a.recycle();
}
private void loadLayoutManagerFromName(Context context, AttributeSet attrs, String name) {
try {
final int dotIndex = name.indexOf('.');
if (dotIndex == -1) {
name = "org.lucasr.twowayview.widget." + name;
} else if (dotIndex == 0) {
final String packageName = context.getPackageName();
name = packageName + "." + name;
}
Class<? extends TwoWayLayoutManager> clazz =
context.getClassLoader().loadClass(name).asSubclass(TwoWayLayoutManager.class);
Constructor<? extends TwoWayLayoutManager> constructor =
clazz.getConstructor(sConstructorSignature);
sConstructorArgs[0] = context;
sConstructorArgs[1] = attrs;
setLayoutManager(constructor.newInstance(sConstructorArgs));
} catch (Exception e) {
throw new IllegalStateException("Could not load TwoWayLayoutManager from " +
"class: " + name, e);
}
}
@Override
public void setLayoutManager(LayoutManager layout) {
if (!(layout instanceof TwoWayLayoutManager)) {
throw new IllegalArgumentException("TwoWayView can only use TwoWayLayoutManager " +
"subclasses as its layout manager");
}
super.setLayoutManager(layout);
}
public Orientation getOrientation() {
TwoWayLayoutManager layout = (TwoWayLayoutManager) getLayoutManager();
return layout.getOrientation();
}
public void setOrientation(Orientation orientation) {
TwoWayLayoutManager layout = (TwoWayLayoutManager) getLayoutManager();
layout.setOrientation(orientation);
}
public int getFirstVisiblePosition() {
TwoWayLayoutManager layout = (TwoWayLayoutManager) getLayoutManager();
return layout.getFirstVisiblePosition();
}
public int getLastVisiblePosition() {
TwoWayLayoutManager layout = (TwoWayLayoutManager) getLayoutManager();
return layout.getLastVisiblePosition();
}
}
| mit |
3pillarlabs/socialauth-android | sharebar/src/main/java/org/brickred/socialbar/ShareBarActivity.java | 8143 | /*
===========================================================================
Copyright (c) 2012 Three Pillar Global Inc. http://threepillarglobal.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sub-license, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
===========================================================================
*/
package org.brickred.socialbar;
import java.io.File;
import org.brickred.socialauth.android.DialogListener;
import org.brickred.socialauth.android.SocialAuthAdapter;
import org.brickred.socialauth.android.SocialAuthAdapter.Provider;
import org.brickred.socialauth.android.SocialAuthError;
import org.brickred.socialauth.android.SocialAuthListener;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
/**
*
* Main class of the ShareBar Example for SocialAuth Android SDK. <br>
*
* The main objective of this example is to create a bar of social media
* providers Facebook, Twitter and others. It enables user to access the
* respective provider on single click and update the status.
*
* The class first creates a bar in main.xml. It then adds bar to SocialAuth
* Android Library <br>
*
* Then it adds providers Facebook, Twitter and others to library object by
* addProvider method and finally enables the providers by calling enable method<br>
*
* After successful authentication of provider, it receives the response in
* responseListener and then automatically update status by updatestatus()
* method.
*
* It's Primarly use is to share message but developers can use to access other
* functionalites like getting profile , contacts , sharing images etc.
*
* Now you can use share -bar to share message via email and mms.See example
* below
*
* This example shows how you can use addconfig method to define key and secrets
* in code.Therefore we have remove oauthconsumers.properties.
*
* <br>
*
* @author vineet.aggarwal@3pillarglobal.com
*
*/
public class ShareBarActivity extends Activity {
// SocialAuth Component
SocialAuthAdapter adapter;
boolean status;
// Android Components
Button update;
EditText edit;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Welcome Message
TextView textview = (TextView) findViewById(R.id.text);
textview.setText("Welcome to SocialAuth Demo. Connect any provider and then press Update button to Share Update.");
LinearLayout bar = (LinearLayout) findViewById(R.id.linearbar);
bar.setBackgroundResource(R.drawable.bar_gradient);
// Add Bar to library
adapter = new SocialAuthAdapter(new ResponseListener());
// Please note : Update status functionality is only supported by
// Facebook, Twitter, Linkedin, MySpace, Yahoo and Yammer.
// Add providers
adapter.addProvider(Provider.FACEBOOK, R.drawable.facebook);
adapter.addProvider(Provider.TWITTER, R.drawable.twitter);
adapter.addProvider(Provider.LINKEDIN, R.drawable.linkedin);
// Add email and mms providers
adapter.addProvider(Provider.EMAIL, R.drawable.email);
adapter.addProvider(Provider.MMS, R.drawable.mms);
// For twitter use add callback method. Put your own callback url here.
adapter.addCallBack(Provider.TWITTER, "http://socialauth.in/socialauthdemo/socialAuthSuccessAction.do");
// Add keys and Secrets
try {
adapter.addConfig(Provider.FACEBOOK, "297841130364674", "dc9c59d0c72d4f2533580e80ba4c2a59", null);
adapter.addConfig(Provider.TWITTER, "5jwyYJia583EEczmdAmlOA", "j0rQkJjTjwVdv7HFiE4zz2qKJKzqjksR2aviVU8fSc",
null);
adapter.addConfig(Provider.LINKEDIN, "bh82t52rdos6", "zQ1LLrGbhDZ36fH8", null);
} catch (Exception e) {
e.printStackTrace();
}
adapter.enable(bar);
}
/**
* Listens Response from Library
*
*/
private final class ResponseListener implements DialogListener {
@Override
public void onComplete(Bundle values) {
// Variable to receive message status
Log.d("Share-Bar", "Authentication Successful");
// Get name of provider after authentication
final String providerName = values.getString(SocialAuthAdapter.PROVIDER);
Log.d("Share-Bar", "Provider Name = " + providerName);
Toast.makeText(ShareBarActivity.this, providerName + " connected", Toast.LENGTH_SHORT).show();
update = (Button) findViewById(R.id.update);
edit = (EditText) findViewById(R.id.editTxt);
// Please avoid sending duplicate message. Social Media Providers
// block duplicate messages.
update.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// Call updateStatus to share message via oAuth providers
// adapter.updateStatus(edit.getText().toString(), new
// MessageListener(), false);
// call to update on all connected providers at once
adapter.updateStatus(edit.getText().toString(), new MessageListener(), true);
}
});
// Share via Email Intent
if (providerName.equalsIgnoreCase("share_mail")) {
Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("mailto",
"vineet.aggarwal@3pillarglobal.com", null));
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Test");
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),
"image5964402.png");
Uri uri = Uri.fromFile(file);
emailIntent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(emailIntent, "Test"));
}
// Share via mms intent
if (providerName.equalsIgnoreCase("share_mms")) {
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),
"image5964402.png");
Uri uri = Uri.fromFile(file);
Intent mmsIntent = new Intent(Intent.ACTION_SEND, uri);
mmsIntent.putExtra("sms_body", "Test");
mmsIntent.putExtra(Intent.EXTRA_STREAM, uri);
mmsIntent.setType("image/png");
startActivity(mmsIntent);
}
}
@Override
public void onError(SocialAuthError error) {
error.printStackTrace();
Log.d("Share-Bar", error.getMessage());
}
@Override
public void onCancel() {
Log.d("Share-Bar", "Authentication Cancelled");
}
@Override
public void onBack() {
Log.d("Share-Bar", "Dialog Closed by pressing Back Key");
}
}
// To get status of message after authentication
private final class MessageListener implements SocialAuthListener<Integer> {
@Override
public void onExecute(String provider, Integer t) {
Integer status = t;
if (status.intValue() == 200 || status.intValue() == 201 || status.intValue() == 204)
Toast.makeText(ShareBarActivity.this, "Message posted on " + provider, Toast.LENGTH_LONG).show();
else
Toast.makeText(ShareBarActivity.this, "Message not posted on" + provider, Toast.LENGTH_LONG).show();
}
@Override
public void onError(SocialAuthError e) {
}
}
} | mit |
kits-ab/gakusei | src/main/java/se/kits/gakusei/util/csv/CSV.java | 1947 | package se.kits.gakusei.util.csv;
import com.univocity.parsers.common.processor.ConcurrentRowProcessor;
import com.univocity.parsers.common.processor.RowListProcessor;
import com.univocity.parsers.csv.CsvParser;
import com.univocity.parsers.csv.CsvParserSettings;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import se.kits.gakusei.util.ParserFailureException;
public class CSV {
/**
* Parse a CSV file and return a map with its headers and rows.
*
* @param csvInput
* @param expectedNbrOfHeaders
* @return Map
*/
public static Map<String, List<String[]>> parse(
InputStream csvInput,
int expectedNbrOfHeaders
) {
CsvParserSettings settings = new CsvParserSettings();
RowListProcessor rowProcessor = new RowListProcessor();
settings.setLineSeparatorDetectionEnabled(true);
settings.setProcessor(new ConcurrentRowProcessor(rowProcessor));
settings.setHeaderExtractionEnabled(true);
CsvParser parser = new CsvParser(settings);
Map<String, List<String[]>> result = new HashMap<
String,
List<String[]>
>();
parser.parse(csvInput, "UTF-8");
List<String[]> headerList = new ArrayList<String[]>();
String[] headers = rowProcessor.getHeaders();
if (headers.length != expectedNbrOfHeaders) {
throw new ParserFailureException(
"Unexpected number of headers" + "\nExpected " + Integer.toString(
expectedNbrOfHeaders
) + " but got " + Integer.toString(headers.length)
);
}
List<String[]> rows = rowProcessor.getRows();
headerList.add(headers);
result.put("HEADERS", headerList);
result.put("ROWS", rows);
return result;
}
}
| mit |
JeroMiya/androidmono | MonoJavaBridge/MonoBridge/src/android/media/MediaScannerConnection_OnScanCompletedListenerDelegateWrapper.java | 627 | package android.media;
import com.koushikdutta.monojavabridge.MonoBridge;
import com.koushikdutta.monojavabridge.MonoProxy;
public class MediaScannerConnection_OnScanCompletedListenerDelegateWrapper extends com.koushikdutta.monojavabridge.MonoProxyBase implements MonoProxy, android.media.MediaScannerConnection.OnScanCompletedListener
{
static
{
MonoBridge.link(MediaScannerConnection_OnScanCompletedListenerDelegateWrapper.class, "onScanCompleted", "(Ljava/lang/String;Landroid/net/Uri;)V", "java.lang.String,android.net.Uri");
}
public native void onScanCompleted(java.lang.String arg0,android.net.Uri arg1);
}
| mit |
gabox8888/mclab-web-generator | src/com/web/program/PartialParts.java | 188 | package com.web.program;
public enum PartialParts {
HEADER,FUNCTIONS,EXPORTS,JSON,END_POINT_COMPILE,END_POINT_ANALYSIS,USER_FILES,ACTIVE_SIDE_PANEL,API_DOC_ANALYSIS,API_DOC_COMPILE
} | mit |
AFR0N1NJAZ/Twilight-Forest-Rewrite | src/main/java/ninjaz/twilight/common/entities/EntityTFMistWolf.java | 1818 | package twilightforest.entity;
import java.util.Random;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.potion.Potion;
import net.minecraft.potion.PotionEffect;
import net.minecraft.world.EnumDifficulty;
import net.minecraft.world.World;
public class EntityTFMistWolf extends EntityTFHostileWolf
{
public EntityTFMistWolf(World world)
{
super(world);
func_70105_a(1.4F, 1.9F);
}
protected void func_110147_ax()
{
super.func_110147_ax();
func_110148_a(net.minecraft.entity.SharedMonsterAttributes.field_111267_a).func_111128_a(30.0D);
}
public int getAttackStrength(Entity par1Entity)
{
return 6;
}
public boolean func_70652_k(Entity par1Entity)
{
int damage = getAttackStrength(par1Entity);
if (par1Entity.func_70097_a(net.minecraft.util.DamageSource.func_76358_a(this), damage))
{
float myBrightness = func_70013_c(1.0F);
if (((par1Entity instanceof EntityLivingBase)) && (myBrightness < 0.1F))
{
byte effectDuration = 0;
if (field_70170_p.field_73013_u != EnumDifficulty.EASY)
{
if (field_70170_p.field_73013_u == EnumDifficulty.NORMAL)
{
effectDuration = 7;
}
else if (field_70170_p.field_73013_u == EnumDifficulty.HARD)
{
effectDuration = 15;
}
}
if (effectDuration > 0)
{
((EntityLivingBase)par1Entity).func_70690_d(new PotionEffect(field_76440_qfield_76415_H, effectDuration * 20, 0));
}
}
return true;
}
return false;
}
protected float func_70647_i()
{
return (field_70146_Z.nextFloat() - field_70146_Z.nextFloat()) * 0.2F + 0.6F;
}
}
| mit |
SkaceKamen/sqflint | src/cz/zipek/sqflint/sqf/SQFForExpressionStatement.java | 3276 | /*
* The MIT License
*
* Copyright 2016 Jan Zípek (jan at zipek.cz).
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package cz.zipek.sqflint.sqf;
import cz.zipek.sqflint.linter.Linter;
import cz.zipek.sqflint.linter.SQFVariable;
import cz.zipek.sqflint.parser.SQFParser;
import cz.zipek.sqflint.parser.Token;
/**
*
* @author Jan Zípek (jan at zipek.cz)
*/
public final class SQFForExpressionStatement extends SQFForStatement {
private final SQFExpression variable;
private final SQFExpression from;
private final SQFExpression to;
private final SQFExpression step;
public SQFForExpressionStatement(Linter linter, SQFExpression variable, SQFExpression from, SQFExpression to, SQFExpression step, SQFBlock block) {
super(linter);
this.variable = variable;
this.from = from;
this.to = to;
this.step = step;
this.block = block;
this.revalidate();
}
/**
* @return the variable
*/
public SQFExpression getVariable() {
return variable;
}
/**
* @return the from
*/
public SQFExpression getFrom() {
return from;
}
/**
* @return the to
*/
public SQFExpression getTo() {
return to;
}
/**
* @return the step
*/
public SQFExpression getStep() {
return step;
}
@Override
public void analyze(Linter source, SQFBlock context) {
if (block != null) {
block.analyze(source, context);
}
}
@Override
public void revalidate() {
if (variable != null
&& variable.getMain() != null
&& variable.getMain() instanceof SQFString) {
SQFString lit = (SQFString)variable.getMain();
String ident = lit.getStringContents()
.toLowerCase();
if (block.getInnerContext() != null) {
block.getInnerContext().clear();
SQFVariable var = block
.getInnerContext()
.getVariable(ident, lit.getStringContents(), true);
Token unquoted = new Token(SQFParser.IDENTIFIER, lit.getStringContents());
unquoted.beginLine = lit.getContents().beginLine;
unquoted.endLine = lit.getContents().endLine;
unquoted.beginColumn = lit.getContents().beginColumn + 1;
unquoted.endColumn = lit.getContents().endColumn - 1;
var.usage.add(unquoted);
var.definitions.add(unquoted);
var.comments.add(null);
}
}
super.revalidate();
}
}
| mit |
jesg/hadoop-patterns | order-inversion/src/main/java/jesg/FreqDriver.java | 1796 | package jesg;
import jesg.avro.Pair;
import org.apache.avro.mapred.AvroKey;
import org.apache.avro.mapreduce.AvroJob;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.DoubleWritable;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
public class FreqDriver extends Configured implements Tool {
@Override
public int run(String[] args) throws Exception {
if (args.length != 2) {
System.err.printf(
"Usage: %s [generic options] <input> <output> \n",
getClass().getSimpleName());
ToolRunner.printGenericCommandUsage(System.err);
return -1;
}
Job job = new Job(getConf());
job.setJobName("freq");
job.setJarByClass(getClass());
AvroJob.setMapOutputKeySchema(job, Pair.getClassSchema());
AvroJob.setOutputKeySchema(job, Pair.getClassSchema());
FileInputFormat.addInputPath(job, new Path(args[0]));
FileOutputFormat.setOutputPath(job, new Path(args[1]));
job.setMapperClass(FreqMapper.class);
job.setReducerClass(FreqReducer.class);
job.setCombinerClass(FreqCombiner.class);
job.setPartitionerClass(FreqPartitioner.class);
job.setMapOutputKeyClass(AvroKey.class);
job.setMapOutputValueClass(IntWritable.class);
job.setOutputKeyClass(AvroKey.class);
job.setOutputValueClass(DoubleWritable.class);
return job.waitForCompletion(true) ? 0 : 1;
}
public static void main(String[] args) throws Exception {
int exitCode = ToolRunner.run(new FreqDriver(), args);
System.exit(exitCode);
}
}
| mit |