code
stringlengths
5
1.04M
repo_name
stringlengths
7
108
path
stringlengths
6
299
language
stringclasses
1 value
license
stringclasses
15 values
size
int64
5
1.04M
/** * Copyright (c) 2015 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.trustedanalytics.serviceinfo; import org.springframework.cloud.service.BaseServiceInfo; public class ZookeeperServiceInfo extends BaseServiceInfo { private String cluster; public ZookeeperServiceInfo(String id, String cluster) { super(id); this.cluster = cluster; } public String getCluster() { return cluster; } }
trustedanalytics/space-shuttle-demo
src/main/java/org/trustedanalytics/serviceinfo/ZookeeperServiceInfo.java
Java
apache-2.0
983
/** * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * * Copyright 2012-2016 the original author or authors. */ package org.assertj.core.api; import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; /** * Tests for <code>{@link Assertions#assertThat(float)}</code>. * * @author Alex Ruiz */ public class Assertions_assertThat_with_primitive_float_Test { @Test public void should_create_Assert() { AbstractFloatAssert<?> assertions = Assertions.assertThat(0f); assertThat(assertions).isNotNull(); } @Test public void should_pass_actual() { AbstractFloatAssert<?> assertions = Assertions.assertThat(8f); assertThat(assertions.actual).isEqualTo(new Float(8)); } }
dorzey/assertj-core
src/test/java/org/assertj/core/api/Assertions_assertThat_with_primitive_float_Test.java
Java
apache-2.0
1,219
/* * Copyright (C) 2013 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 io.airlift.drift.transport.netty.client; import com.google.common.base.Splitter; import com.google.common.collect.ImmutableList; import com.google.common.net.HostAndPort; import io.airlift.configuration.Config; import io.airlift.drift.transport.netty.codec.Protocol; import io.airlift.drift.transport.netty.codec.Transport; import io.airlift.units.DataSize; import io.airlift.units.Duration; import io.airlift.units.MaxDataSize; import io.airlift.units.MinDuration; import javax.validation.constraints.AssertTrue; import javax.validation.constraints.NotNull; import java.io.File; import java.util.List; import static io.airlift.drift.transport.netty.codec.Protocol.BINARY; import static io.airlift.drift.transport.netty.codec.Transport.FRAMED; import static io.airlift.units.DataSize.Unit.MEGABYTE; import static java.util.Objects.requireNonNull; import static java.util.concurrent.TimeUnit.DAYS; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.MINUTES; public class DriftNettyClientConfig { private Transport transport = FRAMED; private Protocol protocol = BINARY; private DataSize maxFrameSize = new DataSize(16, MEGABYTE); private Duration connectTimeout = new Duration(500, MILLISECONDS); private Duration requestTimeout = new Duration(1, MINUTES); private HostAndPort socksProxy; private boolean sslEnabled; private List<String> ciphers = ImmutableList.of(); private File trustCertificate; private File key; private String keyPassword; private long sessionCacheSize = 10_000; private Duration sessionTimeout = new Duration(1, DAYS); @NotNull public Transport getTransport() { return transport; } @Config("thrift.client.transport") public DriftNettyClientConfig setTransport(Transport transport) { this.transport = transport; return this; } @NotNull public Protocol getProtocol() { return protocol; } @Config("thrift.client.protocol") public DriftNettyClientConfig setProtocol(Protocol protocol) { this.protocol = protocol; return this; } @NotNull @MinDuration("1ms") public Duration getConnectTimeout() { return connectTimeout; } @Config("thrift.client.connect-timeout") public DriftNettyClientConfig setConnectTimeout(Duration connectTimeout) { this.connectTimeout = connectTimeout; return this; } @NotNull @MinDuration("1ms") public Duration getRequestTimeout() { return requestTimeout; } @Config("thrift.client.request-timeout") public DriftNettyClientConfig setRequestTimeout(Duration requestTimeout) { this.requestTimeout = requestTimeout; return this; } public HostAndPort getSocksProxy() { return socksProxy; } @Config("thrift.client.socks-proxy") public DriftNettyClientConfig setSocksProxy(HostAndPort socksProxy) { this.socksProxy = socksProxy; return this; } @MaxDataSize("1023MB") public DataSize getMaxFrameSize() { return maxFrameSize; } @Config("thrift.client.max-frame-size") public DriftNettyClientConfig setMaxFrameSize(DataSize maxFrameSize) { this.maxFrameSize = maxFrameSize; return this; } public boolean isSslEnabled() { return sslEnabled; } @Config("thrift.client.ssl.enabled") public DriftNettyClientConfig setSslEnabled(boolean sslEnabled) { this.sslEnabled = sslEnabled; return this; } public File getTrustCertificate() { return trustCertificate; } @Config("thrift.client.ssl.trust-certificate") public DriftNettyClientConfig setTrustCertificate(File trustCertificate) { this.trustCertificate = trustCertificate; return this; } public File getKey() { return key; } @Config("thrift.client.ssl.key") public DriftNettyClientConfig setKey(File key) { this.key = key; return this; } public String getKeyPassword() { return keyPassword; } @Config("thrift.client.ssl.key-password") public DriftNettyClientConfig setKeyPassword(String keyPassword) { this.keyPassword = keyPassword; return this; } public long getSessionCacheSize() { return sessionCacheSize; } @Config("thrift.client.ssl.session-cache-size") public DriftNettyClientConfig setSessionCacheSize(long sessionCacheSize) { this.sessionCacheSize = sessionCacheSize; return this; } public Duration getSessionTimeout() { return sessionTimeout; } @Config("thrift.client.ssl.session-timeout") public DriftNettyClientConfig setSessionTimeout(Duration sessionTimeout) { this.sessionTimeout = sessionTimeout; return this; } public List<String> getCiphers() { return ciphers; } @Config("thrift.client.ssl.ciphers") public DriftNettyClientConfig setCiphers(String ciphers) { this.ciphers = Splitter .on(',') .trimResults() .omitEmptyStrings() .splitToList(requireNonNull(ciphers, "ciphers is null")); return this; } @AssertTrue(message = "Trust certificate must be provided when SSL is enabled") public boolean isTruststorePathValid() { return !isSslEnabled() || getTrustCertificate() != null; } }
airlift/drift
drift-transport-netty/src/main/java/io/airlift/drift/transport/netty/client/DriftNettyClientConfig.java
Java
apache-2.0
6,216
// Copyright 2018 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.lib.bazel.commands; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.devtools.build.lib.analysis.NoBuildEvent; import com.google.devtools.build.lib.analysis.NoBuildRequestFinishedEvent; import com.google.devtools.build.lib.bazel.repository.RepositoryOrderEvent; import com.google.devtools.build.lib.bazel.repository.starlark.StarlarkRepositoryFunction; import com.google.devtools.build.lib.cmdline.Label; import com.google.devtools.build.lib.cmdline.LabelConstants; import com.google.devtools.build.lib.cmdline.LabelSyntaxException; import com.google.devtools.build.lib.cmdline.RepositoryName; import com.google.devtools.build.lib.events.Event; import com.google.devtools.build.lib.events.ExtendedEventHandler.ResolvedEvent; import com.google.devtools.build.lib.packages.Rule; import com.google.devtools.build.lib.packages.WorkspaceFileValue; import com.google.devtools.build.lib.pkgcache.PackageOptions; import com.google.devtools.build.lib.rules.repository.RepositoryDelegatorFunction; import com.google.devtools.build.lib.rules.repository.RepositoryDirectoryValue; import com.google.devtools.build.lib.rules.repository.ResolvedHashesFunction; import com.google.devtools.build.lib.runtime.BlazeCommand; import com.google.devtools.build.lib.runtime.BlazeCommandResult; import com.google.devtools.build.lib.runtime.Command; import com.google.devtools.build.lib.runtime.CommandEnvironment; import com.google.devtools.build.lib.runtime.KeepGoingOption; import com.google.devtools.build.lib.runtime.LoadingPhaseThreadsOption; import com.google.devtools.build.lib.server.FailureDetails; import com.google.devtools.build.lib.server.FailureDetails.FailureDetail; import com.google.devtools.build.lib.server.FailureDetails.Interrupted; import com.google.devtools.build.lib.server.FailureDetails.SyncCommand.Code; import com.google.devtools.build.lib.skyframe.PackageLookupValue; import com.google.devtools.build.lib.skyframe.PrecomputedValue; import com.google.devtools.build.lib.skyframe.SkyframeExecutor; import com.google.devtools.build.lib.syntax.Starlark; import com.google.devtools.build.lib.util.AbruptExitException; import com.google.devtools.build.lib.util.DetailedExitCode; import com.google.devtools.build.lib.util.ExitCode; import com.google.devtools.build.lib.util.InterruptedFailureDetails; import com.google.devtools.build.lib.vfs.RootedPath; import com.google.devtools.build.skyframe.EvaluationContext; import com.google.devtools.build.skyframe.EvaluationResult; import com.google.devtools.build.skyframe.SkyKey; import com.google.devtools.build.skyframe.SkyValue; import com.google.devtools.common.options.OptionsParsingResult; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; /** Syncs all repositories specified in the workspace file */ @Command( name = SyncCommand.NAME, options = { PackageOptions.class, KeepGoingOption.class, LoadingPhaseThreadsOption.class, SyncOptions.class }, help = "resource:sync.txt", shortDescription = "Syncs all repositories specified in the workspace file", allowResidue = false) public final class SyncCommand implements BlazeCommand { public static final String NAME = "sync"; static final ImmutableSet<String> WHITELISTED_NATIVE_RULES = ImmutableSet.of("local_repository", "new_local_repository", "local_config_platform"); private static void reportError(CommandEnvironment env, EvaluationResult<SkyValue> value) { if (value.getError().getException() != null) { env.getReporter().handle(Event.error(value.getError().getException().getMessage())); } else { env.getReporter().handle(Event.error(value.getError().toString())); } } @Override public BlazeCommandResult exec(CommandEnvironment env, OptionsParsingResult options) { try { env.getReporter() .post( new NoBuildEvent( env.getCommandName(), env.getCommandStartTime(), true, true, env.getCommandId().toString())); env.syncPackageLoading(options); SkyframeExecutor skyframeExecutor = env.getSkyframeExecutor(); SyncOptions syncOptions = options.getOptions(SyncOptions.class); if (syncOptions.configure) { skyframeExecutor.injectExtraPrecomputedValues( ImmutableList.of( PrecomputedValue.injected( RepositoryDelegatorFunction.DEPENDENCY_FOR_UNCONDITIONAL_CONFIGURING, env.getCommandId().toString()))); } else { skyframeExecutor.injectExtraPrecomputedValues( ImmutableList.of( PrecomputedValue.injected( RepositoryDelegatorFunction.DEPENDENCY_FOR_UNCONDITIONAL_FETCHING, env.getCommandId().toString()))); } // Obtain the key for the top-level WORKSPACE file SkyKey packageLookupKey = PackageLookupValue.key(LabelConstants.EXTERNAL_PACKAGE_IDENTIFIER); LoadingPhaseThreadsOption threadsOption = options.getOptions(LoadingPhaseThreadsOption.class); EvaluationContext evaluationContext = EvaluationContext.newBuilder() .setNumThreads(threadsOption.threads) .setEventHandler(env.getReporter()) .build(); EvaluationResult<SkyValue> packageLookupValue = skyframeExecutor.prepareAndGet(ImmutableSet.of(packageLookupKey), evaluationContext); if (packageLookupValue.hasError()) { reportError(env, packageLookupValue); return blazeCommandResultWithNoBuildReport( env, ExitCode.ANALYSIS_FAILURE, Code.PACKAGE_LOOKUP_ERROR, packageLookupValue.getError(packageLookupKey).toString()); } RootedPath workspacePath = ((PackageLookupValue) packageLookupValue.get(packageLookupKey)) .getRootedPath(LabelConstants.EXTERNAL_PACKAGE_IDENTIFIER); SkyKey workspace = WorkspaceFileValue.key(workspacePath); // read and evaluate the WORKSPACE file to its end ImmutableList.Builder<String> repositoryOrder = new ImmutableList.Builder<>(); Set<String> namesSeen = new HashSet<>(); WorkspaceFileValue fileValue = null; while (workspace != null) { EvaluationResult<SkyValue> value = skyframeExecutor.prepareAndGet(ImmutableSet.of(workspace), evaluationContext); if (value.hasError()) { reportError(env, value); return blazeCommandResultWithNoBuildReport( env, ExitCode.ANALYSIS_FAILURE, Code.WORKSPACE_EVALUATION_ERROR, value.getError(workspace).toString()); } fileValue = (WorkspaceFileValue) value.get(workspace); for (Rule rule : fileValue.getPackage().getTargets(Rule.class)) { String name = rule.getName(); if (!namesSeen.contains(name)) { repositoryOrder.add(name); namesSeen.add(name); } } workspace = fileValue.next(); } env.getReporter() .post( genericArgsCall( "register_toolchains", fileValue.getPackage().getRegisteredToolchains())); env.getReporter() .post( genericArgsCall( "register_execution_platforms", fileValue.getPackage().getRegisteredExecutionPlatforms())); env.getReporter().post(new RepositoryOrderEvent(repositoryOrder.build())); // take all Starlark workspace rules and get their values ImmutableSet.Builder<SkyKey> repositoriesToFetch = new ImmutableSet.Builder<>(); for (Rule rule : fileValue.getPackage().getTargets(Rule.class)) { if (rule.getRuleClass().equals("bind")) { // The bind rule is special in that the name is not that of an external repository. // Moreover, it is not affected by the invalidation mechanism as there is nothing to // fetch anyway. So the only task remaining is to record the use of "bind" for whoever // collects resolved information. env.getReporter().post(resolveBind(rule)); } else if (shouldSync(rule, syncOptions)) { // TODO(aehlig): avoid the detour of serializing and then parsing the repository name try { repositoriesToFetch.add( RepositoryDirectoryValue.key(RepositoryName.create("@" + rule.getName()))); } catch (LabelSyntaxException e) { String errorMessage = String.format( "Internal error queuing %s to fetch: %s", rule.getName(), e.getMessage()); env.getReporter().handle(Event.error(errorMessage)); return blazeCommandResultWithNoBuildReport( env, ExitCode.BLAZE_INTERNAL_ERROR, Code.REPOSITORY_NAME_INVALID, errorMessage); } } } EvaluationResult<SkyValue> fetchValue; fetchValue = skyframeExecutor.prepareAndGet(repositoriesToFetch.build(), evaluationContext); if (fetchValue.hasError()) { reportError(env, fetchValue); return blazeCommandResultWithNoBuildReport( env, ExitCode.ANALYSIS_FAILURE, Code.REPOSITORY_FETCH_ERRORS, "Repository fetch failure."); } } catch (InterruptedException e) { reportNoBuildRequestFinished(env, ExitCode.INTERRUPTED); BlazeCommandResult.detailedExitCode( InterruptedFailureDetails.detailedExitCode( e.getMessage(), Interrupted.Code.SYNC_COMMAND)); } catch (AbruptExitException e) { env.getReporter().handle(Event.error(e.getMessage())); reportNoBuildRequestFinished(env, ExitCode.LOCAL_ENVIRONMENTAL_ERROR); return BlazeCommandResult.detailedExitCode(e.getDetailedExitCode()); } reportNoBuildRequestFinished(env, ExitCode.SUCCESS); return BlazeCommandResult.success(); } private static boolean shouldSync(Rule rule, SyncOptions options) { if (!rule.getRuleClassObject().getWorkspaceOnly()) { // We should only sync workspace rules return false; } if (options.only != null && !options.only.isEmpty() && !options.only.contains(rule.getName())) { // There is a whitelist of what to sync, but the rule is not in this white list return false; } if (options.configure) { // If this is only a configure run, only sync Starlark rules that // declare themselves as configure-like. return StarlarkRepositoryFunction.isConfigureRule(rule); } if (rule.getRuleClassObject().isStarlark()) { // Starlark rules are all whitelisted return true; } return WHITELISTED_NATIVE_RULES.contains(rule.getRuleClassObject().getName()); } private static ResolvedEvent resolveBind(Rule rule) { String name = rule.getName(); Label actual = (Label) rule.getAttr("actual"); String nativeCommand = Starlark.format("bind(name = %r, actual = %r)", name, actual.getCanonicalForm()); return new ResolvedEvent() { @Override public String getName() { return name; } @Override public Object getResolvedInformation() { return ImmutableMap.<String, Object>builder() .put(ResolvedHashesFunction.ORIGINAL_RULE_CLASS, "bind") .put( ResolvedHashesFunction.ORIGINAL_ATTRIBUTES, ImmutableMap.<String, Object>of("name", name, "actual", actual)) .put(ResolvedHashesFunction.NATIVE, nativeCommand) .build(); } }; } private static ResolvedEvent genericArgsCall(String ruleName, List<String> args) { // For the name attribute we are in a slightly tricky situation, as the ResolvedEvents are // designed for external repositories and hence are indexted by their unique // names. Technically, however, things like the list of toolchains are not associated with any // external repository (but still a workspace command); so we take a name that syntactially can // never be the name of a repository, as it starts with a '//'. String name = "//external/" + ruleName; StringBuilder nativeCommandBuilder = new StringBuilder().append(ruleName).append("("); nativeCommandBuilder.append( args.stream().map(Starlark::repr).collect(Collectors.joining(", "))); nativeCommandBuilder.append(")"); String nativeCommand = nativeCommandBuilder.toString(); return new ResolvedEvent() { @Override public String getName() { return name; } @Override public Object getResolvedInformation() { return ImmutableMap.<String, Object>builder() .put(ResolvedHashesFunction.ORIGINAL_RULE_CLASS, ruleName) .put( ResolvedHashesFunction.ORIGINAL_ATTRIBUTES, // The original attributes are a bit of a problem, as the arguments to // the rule do not at all look like those of a repository rule: // they're all positional, and, in particular, there is no keyword argument // called "name". A lot of uses of the resolved file, however, blindly assume // that "name" is always part of the original arguments; so we provide our // fake name here as well, and the actual arguments under the keyword "*args", // which hopefully reminds everyone inspecting the file of the actual syntax of // that rule. Note that the original arguments are always ignored when bazel uses // a resolved file instead of a workspace file. ImmutableMap.<String, Object>of("name", name, "*args", args)) .put(ResolvedHashesFunction.NATIVE, nativeCommand) .build(); } }; } private static BlazeCommandResult blazeCommandResultWithNoBuildReport( CommandEnvironment env, ExitCode exitCode, Code syncCommandCode, String message) { reportNoBuildRequestFinished(env, exitCode); return createFailedBlazeCommandResult(exitCode, syncCommandCode, message); } private static void reportNoBuildRequestFinished(CommandEnvironment env, ExitCode exitCode) { long finishTimeMillis = env.getRuntime().getClock().currentTimeMillis(); env.getReporter().post(new NoBuildRequestFinishedEvent(exitCode, finishTimeMillis)); } private static BlazeCommandResult createFailedBlazeCommandResult( ExitCode exitCode, Code syncCommandCode, String message) { return BlazeCommandResult.detailedExitCode( DetailedExitCode.of( exitCode, FailureDetail.newBuilder() .setMessage(message) .setSyncCommand( FailureDetails.SyncCommand.newBuilder().setCode(syncCommandCode).build()) .build())); } }
werkt/bazel
src/main/java/com/google/devtools/build/lib/bazel/commands/SyncCommand.java
Java
apache-2.0
15,665
/* * Copyright 2017-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.jvm.java; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import com.facebook.buck.core.model.BuildTarget; import com.facebook.buck.core.sourcepath.SourcePath; import com.facebook.buck.core.sourcepath.resolver.impl.DefaultSourcePathResolver; import com.facebook.buck.io.filesystem.ProjectFilesystem; import com.facebook.buck.model.BuildTargetFactory; import com.facebook.buck.rules.FakeSourcePath; import com.facebook.buck.testutil.FakeProjectFilesystem; import com.facebook.buck.util.ClassLoaderCache; import java.io.IOException; import java.net.MalformedURLException; import javax.tools.ToolProvider; import org.junit.Test; public class AnnotationProcessorFactoryTest { @Test public void testAnnotationProcessorClassloadersNotReusedIfMarkedUnsafe() throws MalformedURLException { assertFalse( isAnnotationProcessorClassLoaderReused( "some.Processor", // processor false)); // safe processors } @Test public void testAnnotationProcessorClassloadersReusedIfMarkedSafe() throws MalformedURLException { assertTrue( isAnnotationProcessorClassLoaderReused( "some.Processor", // processor true)); // safe processors } private boolean isAnnotationProcessorClassLoaderReused( String annotationProcessor, boolean canReuseClasspath) { ProjectFilesystem filesystem = new FakeProjectFilesystem(); SourcePath classpath = FakeSourcePath.of("some/path/to.jar"); ClassLoader baseClassLoader = ToolProvider.getSystemToolClassLoader(); ClassLoaderCache classLoaderCache = new ClassLoaderCache(); BuildTarget buildTarget = BuildTargetFactory.newInstance("//:test"); ResolvedJavacPluginProperties processorGroup = new ResolvedJavacPluginProperties( JavacPluginProperties.builder() .addClasspathEntries(classpath) .addProcessorNames(annotationProcessor) .setCanReuseClassLoader(canReuseClasspath) .setDoesNotAffectAbi(false) .setSupportsAbiGenerationFromSource(false) .build(), filesystem, DefaultSourcePathResolver.from(null)); try (AnnotationProcessorFactory factory1 = new AnnotationProcessorFactory(null, baseClassLoader, classLoaderCache, buildTarget); AnnotationProcessorFactory factory2 = new AnnotationProcessorFactory(null, baseClassLoader, classLoaderCache, buildTarget)) { JavacPluginJsr199Fields fields = processorGroup.getJavacPluginJsr199Fields(); ClassLoader classLoader1 = factory1.getClassLoaderForProcessorGroup(fields); ClassLoader classLoader2 = factory2.getClassLoaderForProcessorGroup(fields); return classLoader1 == classLoader2; } catch (IOException e) { throw new AssertionError(e); } } }
LegNeato/buck
test/com/facebook/buck/jvm/java/AnnotationProcessorFactoryTest.java
Java
apache-2.0
3,510
/* * Copyright 2005-2007 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.lang.BooleanUtils; import org.apache.commons.lang.StringUtils; import org.jdom.Attribute; import org.jdom.Document; import org.jdom.Element; import org.jdom.JDOMException; import org.kuali.rice.core.api.util.RiceConstants; import org.kuali.rice.core.api.util.xml.XmlException; import org.kuali.rice.core.api.util.xml.XmlHelper; import org.kuali.rice.kew.api.action.DelegationType; import org.kuali.rice.kew.rule.RuleBaseValues; import org.kuali.rice.kew.rule.RuleDelegationBo; import org.kuali.rice.kew.rule.RuleTemplateOptionBo; import org.kuali.rice.kew.rule.bo.RuleAttribute; import org.kuali.rice.kew.rule.bo.RuleTemplateBo; import org.kuali.rice.kew.rule.bo.RuleTemplateAttributeBo; import org.kuali.rice.kew.service.KEWServiceLocator; import org.kuali.rice.kew.util.KEWConstants; import org.xml.sax.SAXException; import javax.xml.parsers.ParserConfigurationException; import java.io.IOException; import java.io.InputStream; import java.sql.Timestamp; import java.text.ParseException; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import static org.kuali.rice.core.api.impex.xml.XmlConstants.*; /** * Parses {@link org.kuali.rice.kew.rule.bo.RuleTemplateBo}s from XML. * * @see org.kuali.rice.kew.rule.bo.RuleTemplateBo * * @author Kuali Rice Team (rice.collab@kuali.org) */ public class RuleTemplateXmlParser { private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(RuleTemplateXmlParser.class); /** * By default make attributes defined without a &lt;required&gt; element */ private static final boolean DEFAULT_ATTRIBUTE_REQUIRED = true; private static final boolean DEFAULT_ATTRIBUTE_ACTIVE = true; /** * A dummy document type used in the default rule */ private static final String DUMMY_DOCUMENT_TYPE = "dummyDocumentType"; /** * Used to set the display order of attributes encountered in parsing runs during the lifetime of this object */ private int templateAttributeCounter = 0; public List<RuleTemplateBo> parseRuleTemplates(InputStream input) throws IOException, XmlException { try { Document doc = XmlHelper.trimSAXXml(input); Element root = doc.getRootElement(); return parseRuleTemplates(root); } catch (JDOMException e) { throw new XmlException("Parse error.", e); } catch (SAXException e) { throw new XmlException("Parse error.", e); } catch (ParserConfigurationException e) { throw new XmlException("Parse error.", e); } } public List<RuleTemplateBo> parseRuleTemplates(Element element) throws XmlException { List<RuleTemplateBo> ruleTemplates = new ArrayList<RuleTemplateBo>(); // iterate over any RULE_TEMPLATES elements Collection<Element> ruleTemplatesElements = XmlHelper.findElements(element, RULE_TEMPLATES); Iterator ruleTemplatesIterator = ruleTemplatesElements.iterator(); while (ruleTemplatesIterator.hasNext()) { Element ruleTemplatesElement = (Element) ruleTemplatesIterator.next(); Collection<Element> ruleTemplateElements = XmlHelper.findElements(ruleTemplatesElement, RULE_TEMPLATE); for (Iterator iterator = ruleTemplateElements.iterator(); iterator.hasNext();) { ruleTemplates.add(parseRuleTemplate((Element) iterator.next(), ruleTemplates)); } } return ruleTemplates; } private RuleTemplateBo parseRuleTemplate(Element element, List<RuleTemplateBo> ruleTemplates) throws XmlException { String name = element.getChildText(NAME, RULE_TEMPLATE_NAMESPACE); String description = element.getChildText(DESCRIPTION, RULE_TEMPLATE_NAMESPACE); Attribute allowOverwriteAttrib = element.getAttribute("allowOverwrite"); boolean allowOverwrite = false; if (allowOverwriteAttrib != null) { allowOverwrite = Boolean.valueOf(allowOverwriteAttrib.getValue()).booleanValue(); } if (org.apache.commons.lang.StringUtils.isEmpty(name)) { throw new XmlException("RuleTemplate must have a name"); } if (org.apache.commons.lang.StringUtils.isEmpty(description)) { throw new XmlException("RuleTemplate must have a description"); } // look up the rule template by name first RuleTemplateBo ruleTemplate = KEWServiceLocator.getRuleTemplateService().findByRuleTemplateName(name); if (ruleTemplate == null) { // if it does not exist create a new one ruleTemplate = new RuleTemplateBo(); } else { // if it does exist, update it, only if allowOverwrite is set if (!allowOverwrite) { throw new RuntimeException("Attempting to overwrite template " + name + " without allowOverwrite set"); } // the name should be equal if one was actually found assert(name.equals(ruleTemplate.getName())) : "Existing template definition name does not match incoming definition name"; } // overwrite simple properties ruleTemplate.setName(name); ruleTemplate.setDescription(description); // update the delegation template updateDelegationTemplate(element, ruleTemplate, ruleTemplates); // update the attribute relationships updateRuleTemplateAttributes(element, ruleTemplate); // save the rule template first so that the default/template rule that is generated // in the process of setting defaults is associated properly with this rule template KEWServiceLocator.getRuleTemplateService().save(ruleTemplate); // update the default options updateRuleTemplateDefaultOptions(element, ruleTemplate); KEWServiceLocator.getRuleTemplateService().save(ruleTemplate); return ruleTemplate; } /** * Updates the rule template default options. Updates any existing options, removes any omitted ones. * @param ruleTemplateElement the rule template XML element * @param updatedRuleTemplate the RuleTemplate being updated * @throws XmlException */ /* <element name="description" type="c:LongStringType"/> <element name="fromDate" type="c:ShortStringType" minOccurs="0"/> <element name="toDate" type="c:ShortStringType" minOccurs="0"/> <element name="forceAction" type="boolean"/> <element name="active" type="boolean"/> <element name="defaultActionRequested" type="c:ShortStringType"/> <element name="supportsComplete" type="boolean" default="true"/> <element name="supportsApprove" type="boolean" default="true"/> <element name="supportsAcknowledge" type="boolean" default="true"/> <element name="supportsFYI" type="boolean" default="true"/> */ protected void updateRuleTemplateDefaultOptions(Element ruleTemplateElement, RuleTemplateBo updatedRuleTemplate) throws XmlException { Element defaultsElement = ruleTemplateElement.getChild(RULE_DEFAULTS, RULE_TEMPLATE_NAMESPACE); // update the rule defaults; this yields whether or not this is a delegation rule template boolean isDelegation = updateRuleDefaults(defaultsElement, updatedRuleTemplate); // update the rule template options updateRuleTemplateOptions(defaultsElement, updatedRuleTemplate, isDelegation); } /** * Updates the rule template defaults options with those in the defaults element * @param defaultsElement the ruleDefaults element * @param updatedRuleTemplate the Rule Template being updated */ protected void updateRuleTemplateOptions(Element defaultsElement, RuleTemplateBo updatedRuleTemplate, boolean isDelegation) throws XmlException { // the possible defaults options // NOTE: the current implementation will remove any existing RuleTemplateOption records for any values which are null, i.e. not set in the incoming XML. // to pro-actively set default values for omitted options, simply set those values here, and records will be added if not present String defaultActionRequested = null; Boolean supportsComplete = null; Boolean supportsApprove = null; Boolean supportsAcknowledge = null; Boolean supportsFYI = null; // remove any RuleTemplateOptions the template may have but that we know we aren't going to update/reset // (not sure if this case even exists...does anything else set rule template options?) updatedRuleTemplate.removeNonDefaultOptions(); // read in new settings if (defaultsElement != null) { defaultActionRequested = defaultsElement.getChildText(DEFAULT_ACTION_REQUESTED, RULE_TEMPLATE_NAMESPACE); supportsComplete = BooleanUtils.toBooleanObject(defaultsElement.getChildText(SUPPORTS_COMPLETE, RULE_TEMPLATE_NAMESPACE)); supportsApprove = BooleanUtils.toBooleanObject(defaultsElement.getChildText(SUPPORTS_APPROVE, RULE_TEMPLATE_NAMESPACE)); supportsAcknowledge = BooleanUtils.toBooleanObject(defaultsElement.getChildText(SUPPORTS_ACKNOWLEDGE, RULE_TEMPLATE_NAMESPACE)); supportsFYI = BooleanUtils.toBooleanObject(defaultsElement.getChildText(SUPPORTS_FYI, RULE_TEMPLATE_NAMESPACE)); } if (!isDelegation) { // if this is not a delegation template, store the template options that govern rule action constraints // in the RuleTemplateOptions of the template // we have two options for this behavior: // 1) conditionally parse above, and then unconditionally set/unset the properties; this will have the effect of REMOVING // any of these previously specified rule template options (and is arguably the right thing to do) // 2) unconditionally parse above, and then conditionally set/unset the properties; this will have the effect of PRESERVING // the existing rule template options on this template if it is a delegation template (which of course will be overwritten // by this very same code if they subsequently upload without the delegation flag) // This is a minor point, but the second implementation is chosen as it preserved the current behavior updateOrDeleteRuleTemplateOption(updatedRuleTemplate, KEWConstants.ACTION_REQUEST_DEFAULT_CD, defaultActionRequested); updateOrDeleteRuleTemplateOption(updatedRuleTemplate, KEWConstants.ACTION_REQUEST_APPROVE_REQ, supportsApprove); updateOrDeleteRuleTemplateOption(updatedRuleTemplate, KEWConstants.ACTION_REQUEST_ACKNOWLEDGE_REQ, supportsAcknowledge); updateOrDeleteRuleTemplateOption(updatedRuleTemplate, KEWConstants.ACTION_REQUEST_FYI_REQ, supportsFYI); updateOrDeleteRuleTemplateOption(updatedRuleTemplate, KEWConstants.ACTION_REQUEST_COMPLETE_REQ, supportsComplete); } } /** * * Updates the default/template rule options with those in the defaults element * @param defaultsElement the ruleDefaults element * @param updatedRuleTemplate the Rule Template being updated * @return whether this is a delegation rule template */ protected boolean updateRuleDefaults(Element defaultsElement, RuleTemplateBo updatedRuleTemplate) throws XmlException { // NOTE: implementation detail: in contrast with the other options, the delegate template, and the rule attributes, // we unconditionally blow away the default rule and re-create it (we don't update the existing one, if there is one) if (updatedRuleTemplate.getId() != null) { RuleBaseValues ruleDefaults = KEWServiceLocator.getRuleService().findDefaultRuleByRuleTemplateId(updatedRuleTemplate.getId()); if (ruleDefaults != null) { List ruleDelegationDefaults = KEWServiceLocator.getRuleDelegationService().findByDelegateRuleId(ruleDefaults.getId()); // delete the rule KEWServiceLocator.getRuleService().delete(ruleDefaults.getId()); // delete the associated rule delegation defaults for (Iterator iterator = ruleDelegationDefaults.iterator(); iterator.hasNext();) { RuleDelegationBo ruleDelegation = (RuleDelegationBo) iterator.next(); KEWServiceLocator.getRuleDelegationService().delete(ruleDelegation.getRuleDelegationId()); } } } boolean isDelegation = false; if (defaultsElement != null) { String delegationType = defaultsElement.getChildText(DELEGATION_TYPE, RULE_TEMPLATE_NAMESPACE); isDelegation = !org.apache.commons.lang.StringUtils.isEmpty(delegationType); String description = defaultsElement.getChildText(DESCRIPTION, RULE_TEMPLATE_NAMESPACE); // would normally be validated via schema but might not be present if invoking RuleXmlParser directly if (description == null) { throw new XmlException("Description must be specified in rule defaults"); } String fromDate = defaultsElement.getChildText(FROM_DATE, RULE_TEMPLATE_NAMESPACE); String toDate = defaultsElement.getChildText(TO_DATE, RULE_TEMPLATE_NAMESPACE); // toBooleanObject ensures that if the value is null (not set) that the Boolean object will likewise be null (will not default to a value) Boolean forceAction = BooleanUtils.toBooleanObject(defaultsElement.getChildText(FORCE_ACTION, RULE_TEMPLATE_NAMESPACE)); Boolean active = BooleanUtils.toBooleanObject(defaultsElement.getChildText(ACTIVE, RULE_TEMPLATE_NAMESPACE)); if (isDelegation && !DelegationType.PRIMARY.getCode().equals(delegationType) && !DelegationType.SECONDARY.getCode().equals(delegationType)) { throw new XmlException("Invalid delegation type '" + delegationType + "'." + " Expected one of: " + DelegationType.PRIMARY.getCode() + "," + DelegationType.SECONDARY.getCode()); } // create our "default rule" which encapsulates the defaults for the rule RuleBaseValues ruleDefaults = new RuleBaseValues(); // set simple values ruleDefaults.setRuleTemplate(updatedRuleTemplate); ruleDefaults.setDocTypeName(DUMMY_DOCUMENT_TYPE); ruleDefaults.setTemplateRuleInd(Boolean.TRUE); ruleDefaults.setCurrentInd(Boolean.TRUE); ruleDefaults.setVersionNbr(new Integer(0)); ruleDefaults.setDescription(description); // these are non-nullable fields, so default them if they were not set in the defaults section ruleDefaults.setForceAction(Boolean.valueOf(BooleanUtils.isTrue(forceAction))); ruleDefaults.setActive(Boolean.valueOf(BooleanUtils.isTrue(active))); if (ruleDefaults.getActivationDate() == null) { ruleDefaults.setActivationDate(new Timestamp(System.currentTimeMillis())); } ruleDefaults.setFromDateValue(formatDate("fromDate", fromDate)); ruleDefaults.setToDateValue(formatDate("toDate", toDate)); // ok, if this is a "Delegate Template", then we need to set this other RuleDelegation object which contains // some delegation-related info RuleDelegationBo ruleDelegationDefaults = null; if (isDelegation) { ruleDelegationDefaults = new RuleDelegationBo(); ruleDelegationDefaults.setDelegationRule(ruleDefaults); ruleDelegationDefaults.setDelegationType(delegationType); ruleDelegationDefaults.setResponsibilityId(KEWConstants.ADHOC_REQUEST_RESPONSIBILITY_ID); } // explicitly save the new rule delegation defaults and default rule KEWServiceLocator.getRuleTemplateService().saveRuleDefaults(ruleDelegationDefaults, ruleDefaults); } else { // do nothing, rule defaults will be deleted if ruleDefaults element is omitted } return isDelegation; } /** * Updates or deletes a specified rule template option on the rule template * @param updatedRuleTemplate the RuleTemplate being updated * @param key the option key * @param value the option value */ protected void updateOrDeleteRuleTemplateOption(RuleTemplateBo updatedRuleTemplate, String key, Object value) { if (value != null) { // if the option exists and the incoming value is non-null (it's set), update it RuleTemplateOptionBo option = updatedRuleTemplate.getRuleTemplateOption(key); if (option != null) { option.setValue(value.toString()); } else { updatedRuleTemplate.getRuleTemplateOptions().add(new RuleTemplateOptionBo(key, value.toString())); } } else { // otherwise if the incoming value IS null (not set), then explicitly remove the entry (if it exists) Iterator<RuleTemplateOptionBo> options = updatedRuleTemplate.getRuleTemplateOptions().iterator(); while (options.hasNext()) { RuleTemplateOptionBo opt = options.next(); if (key.equals(opt.getCode())) { options.remove(); break; } } } } /** * Updates the rule template delegation template with the one specified in the XML (if any) * @param ruleTemplateElement the XML ruleTemplate element * @param updatedRuleTemplate the rule template to update * @param parsedRuleTemplates the rule templates parsed in this parsing run * @throws XmlException if a delegation template was specified but could not be found */ protected void updateDelegationTemplate(Element ruleTemplateElement, RuleTemplateBo updatedRuleTemplate, List<RuleTemplateBo> parsedRuleTemplates) throws XmlException { String delegateTemplateName = ruleTemplateElement.getChildText(DELEGATION_TEMPLATE, RULE_TEMPLATE_NAMESPACE); if (delegateTemplateName != null) { // if a delegateTemplate was set in the XML, then look it up and set it on the RuleTemplate object // first try looking up an existing delegateTemplate in the system RuleTemplateBo delegateTemplate = KEWServiceLocator.getRuleTemplateService().findByRuleTemplateName(delegateTemplateName); // if not found, try the list of templates currently parsed if (delegateTemplate == null) { for (RuleTemplateBo rt: parsedRuleTemplates) { if (delegateTemplateName.equalsIgnoreCase(rt.getName())) { // set the expected next rule template id on the target delegateTemplate String ruleTemplateId = KEWServiceLocator.getRuleTemplateService().getNextRuleTemplateId(); rt.setId(ruleTemplateId); delegateTemplate = rt; break; } } } if (delegateTemplate == null) { throw new XmlException("Cannot find delegation template " + delegateTemplateName); } updatedRuleTemplate.setDelegationTemplateId(delegateTemplate.getDelegationTemplateId()); updatedRuleTemplate.setDelegationTemplate(delegateTemplate); } else { // the previously referenced template is left in the system } } /** * Updates the attributes set on the RuleTemplate * @param ruleTemplateElement the XML ruleTemplate element * @param updatedRuleTemplate the RuleTemplate being updated * @throws XmlException if there was a problem parsing the rule template attributes */ protected void updateRuleTemplateAttributes(Element ruleTemplateElement, RuleTemplateBo updatedRuleTemplate) throws XmlException { // add any newly defined rule template attributes to the rule template, // update the active and required flags of any existing ones. // if this is an update of an existing rule template, related attribute objects will be present in this rule template object, // otherwise none will be present (so they'll all be new) Element attributesElement = ruleTemplateElement.getChild(ATTRIBUTES, RULE_TEMPLATE_NAMESPACE); List<RuleTemplateAttributeBo> incomingAttributes = new ArrayList<RuleTemplateAttributeBo>(); if (attributesElement != null) { incomingAttributes.addAll(parseRuleTemplateAttributes(attributesElement, updatedRuleTemplate)); } // inactivate all current attributes for (RuleTemplateAttributeBo currentRuleTemplateAttribute: updatedRuleTemplate.getRuleTemplateAttributes()) { String ruleAttributeName = (currentRuleTemplateAttribute.getRuleAttribute() != null) ? currentRuleTemplateAttribute.getRuleAttribute().getName() : "(null)"; LOG.debug("Inactivating rule template attribute with id " + currentRuleTemplateAttribute.getId() + " and rule attribute with name " + ruleAttributeName); currentRuleTemplateAttribute.setActive(Boolean.FALSE); } // NOTE: attributes are deactivated, not removed // add/update any new attributes for (RuleTemplateAttributeBo ruleTemplateAttribute: incomingAttributes) { RuleTemplateAttributeBo potentialExistingTemplateAttribute = updatedRuleTemplate.getRuleTemplateAttribute(ruleTemplateAttribute); if (potentialExistingTemplateAttribute != null) { // template attribute exists on rule template already; update the options potentialExistingTemplateAttribute.setActive(ruleTemplateAttribute.getActive()); potentialExistingTemplateAttribute.setRequired(ruleTemplateAttribute.getRequired()); } else { // template attribute does not yet exist on template so add it updatedRuleTemplate.getRuleTemplateAttributes().add(ruleTemplateAttribute); } } } /** * Parses the RuleTemplateAttributes defined on the rule template element * @param attributesElement the jdom Element object for the Rule Template attributes * @param ruleTemplate the RuleTemplate object * @return the RuleTemplateAttributes defined on the rule template element * @throws XmlException */ private List<RuleTemplateAttributeBo> parseRuleTemplateAttributes(Element attributesElement, RuleTemplateBo ruleTemplate) throws XmlException { List<RuleTemplateAttributeBo> ruleTemplateAttributes = new ArrayList<RuleTemplateAttributeBo>(); Collection<Element> attributeElements = XmlHelper.findElements(attributesElement, ATTRIBUTE); for (Iterator iterator = attributeElements.iterator(); iterator.hasNext();) { ruleTemplateAttributes.add(parseRuleTemplateAttribute((Element) iterator.next(), ruleTemplate)); } return ruleTemplateAttributes; } /** * Parses a rule template attribute * @param element the attribute XML element * @param ruleTemplate the ruleTemplate to update * @return a parsed rule template attribute * @throws XmlException if the attribute does not exist */ private RuleTemplateAttributeBo parseRuleTemplateAttribute(Element element, RuleTemplateBo ruleTemplate) throws XmlException { String attributeName = element.getChildText(NAME, RULE_TEMPLATE_NAMESPACE); String requiredValue = element.getChildText(REQUIRED, RULE_TEMPLATE_NAMESPACE); String activeValue = element.getChildText(ACTIVE, RULE_TEMPLATE_NAMESPACE); if (org.apache.commons.lang.StringUtils.isEmpty(attributeName)) { throw new XmlException("Attribute name must be non-empty"); } boolean required = DEFAULT_ATTRIBUTE_REQUIRED; if (requiredValue != null) { required = Boolean.parseBoolean(requiredValue); } boolean active = DEFAULT_ATTRIBUTE_ACTIVE; if (activeValue != null) { active = Boolean.parseBoolean(activeValue); } RuleAttribute ruleAttribute = KEWServiceLocator.getRuleAttributeService().findByName(attributeName); if (ruleAttribute == null) { throw new XmlException("Could not locate rule attribute for name '" + attributeName + "'"); } RuleTemplateAttributeBo templateAttribute = new RuleTemplateAttributeBo(); templateAttribute.setRuleAttribute(ruleAttribute); templateAttribute.setRuleAttributeId(ruleAttribute.getId()); templateAttribute.setRuleTemplate(ruleTemplate); templateAttribute.setRequired(Boolean.valueOf(required)); templateAttribute.setActive(Boolean.valueOf(active)); templateAttribute.setDisplayOrder(new Integer(templateAttributeCounter++)); return templateAttribute; } public Timestamp formatDate(String dateLabel, String dateString) throws XmlException { if (StringUtils.isBlank(dateString)) { return null; } try { return new Timestamp(RiceConstants.getDefaultDateFormat().parse(dateString).getTime()); } catch (ParseException e) { throw new XmlException(dateLabel + " is not in the proper format. Should have been: " + RiceConstants.DEFAULT_DATE_FORMAT_PATTERN); } } }
sbower/kuali-rice-1
impl/src/main/java/org/kuali/rice/kew/xml/RuleTemplateXmlParser.java
Java
apache-2.0
26,437
/* * 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. */ /** * <h1>Model-view presenter package</h1> * <h2>How to use?</h2> * <p> * <a href="http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93presenter">MVP</a> pattern implementation with only view and presenter for now. * <dl> * <dt>Presenter</dt> * <dd>Handles all business logic and has <strong>no</strong> references to awt/swing, so it is 100% testable</dd> * <dt>View</dt> * <dd>Handles only view: it may import any swing/awt packages but should contain almost no logic, because it is untestable.</dd> * </dl> * One implements <strong>Presenter</strong> and <strong>View</strong>. Both may have links to each other. * You run {@link vgrechka.phizdetsidea.phizdets.vp.ViewPresenterUtils#linkViewWithPresenterAndLaunch(Class, Class, Creator)} to link and launch them. * See its javadoc * </p> * <h2>Threading issues</h2> * * <p> * Presenter and View should be thread-agnostic. * Any call to <strong>view</strong> is invoked in EDT automatically. <br/> * Call to <strong>presenter</strong> may be invoked in background (not implemented yet, see {@link vgrechka.phizdetsidea.phizdets.vp.PresenterHandler}) * </p> * * @author Ilya.Kazakevich */ package vgrechka.phizdetsidea.phizdets.vp;
vovagrechka/fucking-everything
phizdets/phizdets-idea/src/vgrechka/phizdetsidea/phizdets/vp/package-info.java
Java
apache-2.0
1,829
// Copyright 2019 Google LLC // Copyright 2016 Piotr Andzel // // 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 com.google.sps.webcrawler; import com.google.cloud.datastore.Datastore; import com.google.cloud.datastore.DatastoreOptions; import com.google.cloud.datastore.Entity; import com.google.cloud.datastore.Key; import com.google.cloud.datastore.StringValue; import com.google.cloud.datastore.TimestampValue; import com.google.cloud.Timestamp; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.google.sps.data.NewsArticle; import com.google.sps.infocompiler.Config; import com.google.sps.infocompiler.InfoCompiler; import com.google.sps.webcrawler.NewsContentExtractor; import com.google.sps.webcrawler.NewsContentProcessor; import com.google.sps.webcrawler.RelevancyChecker; import com.panforge.robotstxt.Grant; import com.panforge.robotstxt.RobotsTxt; import java.io.InputStream; import java.io.IOException; import java.net.URL; import java.net.URLConnection; import java.net.URLEncoder; import java.time.DateTimeException; import java.time.format.DateTimeFormatter; import java.time.Instant; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.concurrent.TimeUnit; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.ResponseHandler; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; /** A web crawler for compiling candidate-specific news articles information. */ public class WebCrawler { static final String CUSTOM_SEARCH_URL_METATAG = "og:url"; static final List<String> CUSTOM_SEARCH_PUBLISHER_METATAGS = Arrays.asList("article:publisher", "og:site_name", "twitter:app:name:googleplay", "dc.source"); static final List<String> CUSTOM_SEARCH_PUBLISHED_DATE_METATAGS = Arrays.asList("article:published_time", "article:published", "datepublished", "og:pubdate", "pubdate", "published", "article:modified_time", "article:modified", "modified"); private static final List<DateTimeFormatter> DATE_TIME_FORMATTERS = Arrays.asList(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSX"), DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssX"), DateTimeFormatter.ISO_OFFSET_DATE_TIME); public static final int CUSTOM_SEARCH_RESULT_COUNT = 10; private static final int URL_CONNECT_TIMEOUT_MILLISECONDS = 1000; private static final int URL_READ_TIMEOUT_MILLISECONDS = 1000; private static final int MAX_CRAWL_DELAY = 30 * 1000; private Datastore datastore; private NewsContentExtractor newsContentExtractor; private RelevancyChecker relevancyChecker; // Mappings of (website robots.txt URL, the next allowed time to access, in milliseconds) for // respecting the required crawl delay. private Map<String, Long> nextAccessTimes = new HashMap<>(); /** * Constructs a {@code WebCrawler} instance. * * @throws IOException if {@code RelevancyChecker} instantiation fails, such as because of lack * of permission to access required libraries. */ public WebCrawler() throws IOException { this(DatastoreOptions.getDefaultInstance().getService(), new NewsContentExtractor(), new RelevancyChecker()); } /** For testing purposes. */ public WebCrawler(Datastore datastore, NewsContentExtractor newsContentExtractor, RelevancyChecker relevancyChecker) throws IOException { this.datastore = datastore; this.newsContentExtractor = newsContentExtractor; this.relevancyChecker = relevancyChecker; } /** * Compiles news articles for the candidate with the specified {@code candidateName} and * {@code candidateId}: * 1. Obtains news article URLs and metadata from Google Custom Search. * 2. Checks for permission to web-scrape. * 3. Web-scrapes if permitted. * 4. Extracts content from HTML structure. * 5. Checks content relevancy to the candidate of interest. * 6. Processes content. * 7. Stores processed content in the database. */ public void compileNewsArticle(String candidateName, String candidateId, String partyName) { List<NewsArticle> newsArticles = getUrlsFromCustomSearch(candidateName); for (NewsArticle newsArticle : newsArticles) { scrapeAndExtractFromHtml(newsArticle); if (!relevancyChecker.isRelevant(newsArticle, candidateName, partyName)) { continue; } NewsContentProcessor.abbreviate(newsArticle); NewsContentProcessor.summarize(newsArticle); storeInDatabase(candidateId, newsArticle); } } // [Might adopt in {@code compileNewsArticle}.] /** * Controls the web scraping frequency by delaying the @{code WebCrawler} for the maximum amount * of time as required by webpages encountered so far. This method is for frequency-tuning * purposes only. {@code WebCrawler} will confirm that the required crawl delay is met, before * actually moving forward with the web-scraping. */ // private void waitForMaxCrawlDelay() { // if (nextAccessTimes.isEmpty()) { // return; // } // long timeToDelay = Collections.max(nextAccessTimes.values()) - System.currentTimeMillis(); // timeToDelay = Math.min(MAX_CRAWL_DELAY, timeToDelay); // try { // TimeUnit.MILLISECONDS.sleep(timeToDelay); // } catch (InterruptedException e) {} // } /** * Searches for {@code candidateName} on News.google using the Google Custom Search engine and * finds URLs and metadata of news articles. Returns an empty list if no valid URLs are found. * * @see <a href="https://hc.apache.org/httpcomponents-client-ga/httpclient/examples/org/apache/" * + "http/examples/client/ClientWithResponseHandler.java">Code reference</a> */ public List<NewsArticle> getUrlsFromCustomSearch(String candidateName) { String request = String.format( "https://www.googleapis.com/customsearch/v1?key=%s&cx=%s&q=%s", Config.CUSTOM_SEARCH_KEY, Config.CUSTOM_SEARCH_ENGINE_ID, URLEncoder.encode(candidateName)); CloseableHttpClient httpClient = HttpClients.createDefault(); try { HttpGet httpGet = new HttpGet(request); JsonObject json = InfoCompiler.requestHttpAndBuildJsonResponse(httpClient, httpGet); return extractUrlsAndMetadataFromCustomSearchJson(json); } catch (IOException e) { System.out.println("[ERROR] Error occurred with fetching URLs from Custom Search: " + e); return Arrays.asList(); } } /** * Parses {@code json}, which is in Google Custom Search's JSON response format, and extracts * news articles' URLs (URLs from the source website, instead of from News.google) and metadata, * including the publisher and published date. Packages extracted data into {@code NewsArticle}. * Set news articles' priority based on the order in which they are returned by Custom Search. */ List<NewsArticle> extractUrlsAndMetadataFromCustomSearchJson(JsonObject json) { List<NewsArticle> newsArticles = new ArrayList<>(CUSTOM_SEARCH_RESULT_COUNT); JsonArray searchResults = json.getAsJsonArray("items"); if (searchResults == null) { return Arrays.asList(); } int priority = 1; for (JsonElement result : searchResults) { JsonObject metadata; String url; try { metadata = (JsonObject) (((JsonObject) result) .getAsJsonObject("pagemap") .getAsJsonArray("metatags") .get(0)); url = extractUrlMetadata(metadata); } catch (NullPointerException e) { continue; } String publisher = extractPublisherMetadata(metadata); Date publishedDate = extractPublishedDateMetadata(metadata); newsArticles.add(new NewsArticle(url, publisher, publishedDate, priority)); priority++; } return newsArticles; } /** * Extracts the URL from {@code metadata}. Throws an exception if the URL wasn't found, * because the news article content relies on the URL. * * @throws NullPointerException if the metatag {@code CUSTOM_SEARCH_URL_METATAG} doesn't * exist. */ private String extractUrlMetadata(JsonObject metadata) { return metadata.get(CUSTOM_SEARCH_URL_METATAG).getAsString(); } /** * Extracts the publisher from {@code metadata} by examining in order * {@code CUSTOM_SEARCH_PUBLISHER_METATAGS}. Returns null if no matching metatags are found. */ private String extractPublisherMetadata(JsonObject metadata) { for (String potentialPublisherMetatag : CUSTOM_SEARCH_PUBLISHER_METATAGS) { if (metadata.has(potentialPublisherMetatag)) { return metadata.get(potentialPublisherMetatag).getAsString(); } } return null; } /** * Extracts the published date from {@code metadata} by examining in order * {@code CUSTOM_SEARCH_PUBLISHED_DATE_METATAGS} and parsing the date string. Returns null if no * matching metatags are found or if no date strings could be parsed. */ private Date extractPublishedDateMetadata(JsonObject metadata) { for (String potentialDateMetatag : CUSTOM_SEARCH_PUBLISHED_DATE_METATAGS) { if (!metadata.has(potentialDateMetatag)) { continue; } String date = metadata.get(potentialDateMetatag).getAsString(); for (DateTimeFormatter potentialDateTimeFormatter : DATE_TIME_FORMATTERS) { try { return Date.from(Instant.from(potentialDateTimeFormatter.parse(date))); } catch (IllegalArgumentException | DateTimeException e) {} } } return null; } /** * Checks robots.txt for permission to web-scrape, scrapes webpage if permitted and extracts * textual content to put into {@code newsArticle}. Sets "content" to empty in the event of an * exception. */ public void scrapeAndExtractFromHtml(NewsArticle newsArticle) { try { URL url = new URL(newsArticle.getUrl()); URL robotsUrl = new URL(url.getProtocol(), url.getHost(), "/robots.txt"); InputStream robotsTxtStream = setTimeoutAndOpenStream(robotsUrl); RobotsTxt robotsTxt = RobotsTxt.read(robotsTxtStream); robotsTxtStream.close(); String webpagePath = url.getPath(); Grant grant = robotsTxt.ask("*", webpagePath); politelyScrapeAndExtractFromHtml(grant, robotsUrl, newsArticle); } catch (Exception e) { System.out.println("[ERROR] Error occured in scrapeAndExtractHtml(): " + e); newsArticle.setTitle(""); newsArticle.setContent(""); } } /** * Checks robots.txt for permission to web-scrape, scrapes webpage if permitted and extracts * textual content to put into {@code newsArticle}. Sets "content" to empty in the event of an * exception. */ void politelyScrapeAndExtractFromHtml(Grant grant, URL robotsUrl, NewsArticle newsArticle) { try { // Check permission to access and respect the required crawl delay. if (grant == null || (grant.hasAccess() && waitForAndSetCrawlDelay(grant, robotsUrl.toString()))) { InputStream webpageStream = setTimeoutAndOpenStream(new URL(newsArticle.getUrl())); newsContentExtractor.extractContentFromHtml(webpageStream, newsArticle); webpageStream.close(); } else { newsArticle.setTitle(""); newsArticle.setContent(""); return; } } catch (Exception e) { System.out.println("[ERROR] Error occured in politelyScrapeAndExtractHtml(): " + e); newsArticle.setTitle(""); newsArticle.setContent(""); } } /** * Opens a readable {@code InputStream} from {@code url}, while setting a connect and read * timeout so that opening stream wouldn't hang. Timeout will trigger exceptions. */ private InputStream setTimeoutAndOpenStream(URL url) throws IOException { URLConnection connection = url.openConnection(); connection.setConnectTimeout(URL_CONNECT_TIMEOUT_MILLISECONDS); connection.setReadTimeout(URL_READ_TIMEOUT_MILLISECONDS); return connection.getInputStream(); } /** * Waits for the required crawl delay to pass if necessary and makes a note of the required crawl * delay. Returns true if the aforementioned process succeeded. {@code grant} is expected to be * non-null. This method is made default for testing purposes. */ boolean waitForAndSetCrawlDelay(Grant grant, String url) { if (grant.getCrawlDelay() == null) { return true; } if (nextAccessTimes.containsKey(url)) { if (!waitIfNecessary(url)) { return false; } nextAccessTimes.replace(url, System.currentTimeMillis() + grant.getCrawlDelay() * 1000); } else { nextAccessTimes.put(url, System.currentTimeMillis() + grant.getCrawlDelay() * 1000); } return true; } /** * Waits for {@code timeToDelay} milliseconds if necessary and returns true if the pause * succeeded or if the pause was unnecessary. Waits for a maximum of {@code MAX_CRAWL_DELAY} * milliseconds. */ private boolean waitIfNecessary(String url) { if (System.currentTimeMillis() < nextAccessTimes.get(url)) { try { long sleepDuration = nextAccessTimes.get(url) - System.currentTimeMillis(); if (sleepDuration > MAX_CRAWL_DELAY) { return false; } TimeUnit.MILLISECONDS.sleep(sleepDuration); } catch (InterruptedException e) { return false; } } return true; } /** * Stores {@code NewsArticle}'s metadata and content into the database, following a predesigned * database schema. Requires "gcloud config set project project-ID" to be set correctly. {@code * content} and {@code abbreviatedContent} are excluded form database indexes, which are * additional data structures built to enable efficient lookup on non-keyed properties. Because * we will not query {@code NewsArticle} Datastore entities via {@code content} or * {@code abbreviatedContent}, we will not use indexes regardless. Set the last modified time * for deletion purposes. */ public void storeInDatabase(String candidateId, NewsArticle newsArticle) { Key newsArticleKey = datastore .newKeyFactory() .setKind("NewsArticle") .newKey((long) newsArticle.getUrl().hashCode()); Entity newsArticleEntity = Entity.newBuilder(newsArticleKey) .set("candidateId", datastore.newKeyFactory() .setKind("Candidate") .newKey(Long.parseLong(candidateId))) .set("title", newsArticle.getTitle()) .set("url", newsArticle.getUrl()) .set("content", excludeStringFromIndexes(newsArticle.getContent())) .set( "abbreviatedContent", excludeStringFromIndexes(newsArticle.getAbbreviatedContent())) .set("summarizedContent", excludeStringFromIndexes(newsArticle.getSummarizedContent())) .set("publisher", newsArticle.getPublisher()) .set("publishedDate", TimestampValue.newBuilder( Timestamp.of( newsArticle.getPublishedDate())).build()) .set("priority", newsArticle.getPriority()) .set("lastModified", Timestamp.now()) .build(); datastore.put(newsArticleEntity); } /** * Converts {@code String} to {@code StringValue} and excludes the data from indexes, to avoid * the 1500-byte size limit for indexed data. */ private StringValue excludeStringFromIndexes(String content) { return StringValue .newBuilder(content == null ? "" : content) .setExcludeFromIndexes(true) .build(); } /** For testing purposes. */ Map<String, Long> getNextAccessTimes() { return this.nextAccessTimes; } }
googleinterns/voter-central
info-compiler/src/main/java/com/google/sps/webcrawler/WebCrawler.java
Java
apache-2.0
16,887
package br.edu.unipampa.geketcc.dao; import br.edu.unipampa.geketcc.model.Matricula; import br.edu.unipampa.geketcc.model.Matriculaarquivo; import java.util.List; import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.criterion.Order; import org.hibernate.criterion.Restrictions; /* * Matricula Arquivo TCC * * @author Douglas Giordano * @since 07/12/2014 */ public class MatriculaArquivoDAO { /** * Salvar o registro do arquivo de TCC * * @param MatriculaArquivo * @return */ public boolean salvar(Matriculaarquivo matriculaArquivo) { return CRUD.salvar(matriculaArquivo); } public Matricula buscarUltimaMatricula(int codigoAluno) { Object objeto = null; Session session = HibernateUtil.openSession(); Transaction tx = null; try { tx = session.beginTransaction();//cria uma transação para o hibernate conectar no banco Criteria criteria = session.createCriteria(Matricula.class); criteria.add(Restrictions.eq("aluno.codigo", codigoAluno)); criteria.addOrder(Order.desc("codigo")); criteria.setMaxResults(1); objeto = criteria.uniqueResult(); tx.commit(); } catch (Exception e) { if (tx != null) { tx.rollback(); } e.printStackTrace(); } finally { session.close(); } return (Matricula) objeto; } public List<Matriculaarquivo> buscarUltimosArquivos(int codigoMatricula) { List<Matriculaarquivo> matriculasArquivos = null; Session session = HibernateUtil.openSession(); Transaction tx = null; try { tx = session.beginTransaction();//cria uma transação para o hibernate conectar no banco Criteria criteria = session.createCriteria(Matriculaarquivo.class); criteria.add(Restrictions.eq("matricula.codigo", codigoMatricula)); matriculasArquivos = criteria.list(); tx.commit(); } catch (Exception e) { if (tx != null) { tx.rollback(); } e.printStackTrace(); } finally { session.close(); } return matriculasArquivos; } public Matriculaarquivo buscarMatriculaArquivo(int codigoArquivo) { return (Matriculaarquivo) CRUD.buscarObjeto(codigoArquivo, Matriculaarquivo.class); } public List<Matriculaarquivo> buscarMatriculasArquivos(int codigoOrientador, int status) { List<Matriculaarquivo> matriculasArquivos = null; Session session = HibernateUtil.openSession(); Transaction tx = null; try { tx = session.beginTransaction();//cria uma transação para o hibernate conectar no banco Criteria criteria = session.createCriteria(Matriculaarquivo.class); criteria.add(Restrictions.eq("status", status)); criteria.add(Restrictions.eq("matricula.orientador.codigo", codigoOrientador)); matriculasArquivos = criteria.list(); tx.commit(); } catch (Exception e) { if (tx != null) { tx.rollback(); } e.printStackTrace(); } finally { session.close(); } return matriculasArquivos; } public Matriculaarquivo buscarMatriculaArquivo(int codigoOrientador, int codigoAluno, int status) { Matriculaarquivo matriculasArquivos = null; Session session = HibernateUtil.openSession(); Transaction tx = null; try { tx = session.beginTransaction();//cria uma transação para o hibernate conectar no banco Criteria criteria = session.createCriteria(Matriculaarquivo.class) .add(Restrictions.eq("status", status)); criteria.createCriteria("matricula").add(Restrictions.and(Restrictions.eq("orientador.codigo", codigoOrientador),Restrictions.eq("aluno.codigo", codigoAluno))); matriculasArquivos = (Matriculaarquivo) criteria.uniqueResult(); tx.commit(); } catch (Exception e) { if (tx != null) { tx.rollback(); } e.printStackTrace(); } finally { session.close(); } return matriculasArquivos; } public Matriculaarquivo buscar(Matricula matricula) { Matriculaarquivo matriculaArquivo = null; Session session = HibernateUtil.openSession(); Transaction tx = null; try { tx = session.beginTransaction();//cria uma transação para o hibernate conectar no banco Criteria criteria = session.createCriteria(Matriculaarquivo.class); criteria.add(Restrictions.eq("matricula.codigo", matricula.getCodigo())); criteria.setMaxResults(1); matriculaArquivo = (Matriculaarquivo) criteria.uniqueResult(); tx.commit(); } catch (Exception e) { if (tx != null) { tx.rollback(); } e.printStackTrace(); } finally { session.close(); } return matriculaArquivo; } }
alexporthal/GerenciadorTCC_UNIPAMPA
GekeTCC/src/main/java/br/edu/unipampa/geketcc/dao/MatriculaArquivoDAO.java
Java
apache-2.0
5,294
/* * 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.hyracks.util; import java.lang.reflect.Field; import java.util.IdentityHashMap; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import org.apache.commons.lang3.mutable.MutableLong; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @SuppressWarnings("squid:S1147") public class ExitUtil { private static final Logger LOGGER = LogManager.getLogger(); public static final int EC_NORMAL_TERMINATION = 0; public static final int EC_ABNORMAL_TERMINATION = 1; public static final int EC_FAILED_TO_STARTUP = 2; public static final int EC_FAILED_TO_RECOVER = 3; public static final int EC_NC_FAILED_TO_ABORT_ALL_PREVIOUS_TASKS = 4; public static final int EC_FAILED_TO_PROCESS_UN_INTERRUPTIBLE_REQUEST = 5; public static final int EC_FAILED_TO_COMMIT_METADATA_TXN = 6; public static final int EC_FAILED_TO_ABORT_METADATA_TXN = 7; public static final int EC_INCONSISTENT_METADATA = 8; public static final int EC_UNCAUGHT_THROWABLE = 9; public static final int EC_UNHANDLED_EXCEPTION = 11; public static final int EC_FAILED_TO_DELETE_CORRUPTED_RESOURCES = 12; public static final int EC_ERROR_CREATING_RESOURCES = 13; public static final int EC_TXN_LOG_FLUSHER_FAILURE = 14; public static final int EC_NODE_REGISTRATION_FAILURE = 15; public static final int EC_NETWORK_FAILURE = 16; public static final int EC_ACTIVE_SUSPEND_FAILURE = 17; public static final int EC_ACTIVE_RESUME_FAILURE = 18; public static final int EC_FAILED_TO_CANCEL_ACTIVE_START_STOP = 22; public static final int EC_IMMEDIATE_HALT = 33; public static final int EC_HALT_ABNORMAL_RESERVED_44 = 44; public static final int EC_IO_SCHEDULER_FAILED = 55; public static final int EC_HALT_SHUTDOWN_TIMED_OUT = 66; public static final int EC_HALT_WATCHDOG_FAILED = 77; public static final int EC_FLUSH_FAILED = 88; public static final int EC_TERMINATE_NC_SERVICE_DIRECTIVE = 99; private static final ExitThread exitThread = new ExitThread(); private static final ShutdownWatchdog watchdogThread = new ShutdownWatchdog(); private static final MutableLong shutdownHaltDelay = new MutableLong(10 * 60 * 1000L); // 10 minutes default static { watchdogThread.start(); } private ExitUtil() { } public static void init() { // no-op, the clinit does the work } public static void exit(int status) { synchronized (exitThread) { if (exitThread.isAlive()) { LOGGER.warn("ignoring duplicate request to exit with status " + status + "; already exiting with status " + exitThread.status + "..."); } else { exitThread.setStatus(status, new Throwable("exit callstack")); exitThread.start(); } } } public static void exit(int status, long timeBeforeHalt, TimeUnit timeBeforeHaltUnit) { shutdownHaltDelay.setValue(timeBeforeHaltUnit.toMillis(timeBeforeHalt)); exit(status); } public static synchronized void halt(int status) { LOGGER.fatal("JVM halting with status {}; thread dump at halt: {}", status, ThreadDumpUtil.takeDumpString()); // try to give time for the log to be emitted... LogManager.shutdown(); Runtime.getRuntime().halt(status); } private static class ShutdownWatchdog extends Thread { private final Semaphore startSemaphore = new Semaphore(0); private ShutdownWatchdog() { super("ShutdownWatchdog"); setDaemon(true); } @Override public void run() { startSemaphore.acquireUninterruptibly(); LOGGER.info("starting shutdown watchdog- system will halt if shutdown is not completed within {} seconds", TimeUnit.MILLISECONDS.toSeconds(shutdownHaltDelay.getValue())); try { exitThread.join(shutdownHaltDelay.getValue()); if (exitThread.isAlive()) { try { LOGGER.fatal("shutdown did not complete within configured delay; halting"); } finally { ExitUtil.halt(EC_HALT_SHUTDOWN_TIMED_OUT); } } } catch (Throwable th) { // NOSONAR must catch them all ExitUtil.halt(EC_HALT_WATCHDOG_FAILED); } } public void beginWatch() { startSemaphore.release(); } } private static class ExitThread extends Thread { private volatile int status; private volatile Throwable callstack; ExitThread() { super("JVM exit thread"); setDaemon(true); } @Override public void run() { watchdogThread.beginWatch(); try { LOGGER.warn("JVM exiting with status " + status + "; bye!", callstack); logShutdownHooks(); } finally { Runtime.getRuntime().exit(status); } } public void setStatus(int status, Throwable callstack) { this.status = status; this.callstack = callstack; } private static void logShutdownHooks() { try { Class clazz = Class.forName("java.lang.ApplicationShutdownHooks"); Field hooksField = clazz.getDeclaredField("hooks"); hooksField.setAccessible(true); IdentityHashMap hooks = (IdentityHashMap) hooksField.get(null); if (hooks != null) { LOGGER.info("the following ({}) shutdown hooks have been registered: {}", hooks::size, hooks::toString); } } catch (Exception e) { LOGGER.debug("ignoring exception trying to log shutdown hooks", e); } } } }
ecarm002/incubator-asterixdb
hyracks-fullstack/hyracks/hyracks-util/src/main/java/org/apache/hyracks/util/ExitUtil.java
Java
apache-2.0
6,837
package ro.pub.cs.systems.pdsd.lab03.phonedialer; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.provider.SyncStateContract.Constants; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class PhoneDialerActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_phone_dialer); final EditText text = (EditText) findViewById(R.id.editText); Button btn0 = (Button)findViewById(R.id.button0); btn0.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { text.getText().append('0'); } }); Button btn1 = (Button)findViewById(R.id.button1); btn1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { text.getText().append('1'); } }); Button btn2 = (Button)findViewById(R.id.button2); btn2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { text.getText().append('2'); } }); Button btn3 = (Button)findViewById(R.id.button3); btn3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { text.getText().append('3'); } }); Button btn4 = (Button)findViewById(R.id.button4); btn4.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { text.getText().append('4'); } }); Button btn5 = (Button)findViewById(R.id.button5); btn5.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { text.getText().append('5'); } }); Button btn6 = (Button)findViewById(R.id.button6); btn6.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { text.getText().append('6'); } }); Button btn7 = (Button)findViewById(R.id.button7); btn7.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { text.getText().append('7'); } }); Button btn8 = (Button)findViewById(R.id.button8); btn8.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { text.getText().append('8'); } }); Button btn9 = (Button)findViewById(R.id.button9); btn9.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { text.getText().append('9'); } }); Button btnStar = (Button)findViewById(R.id.buttonStar); btnStar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { text.getText().append('*'); } }); Button btnHashtag = (Button)findViewById(R.id.buttonHashtag); btnHashtag.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { text.getText().append('#'); } }); Button btnErase = (Button)findViewById(R.id.buttonErase); btnErase.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(text.getText().length() == 0){ return; } text.getText().replace(text.getText().length() - 1, text.getText().length(), ""); } }); Button btnCall = (Button)findViewById(R.id.buttonCall); btnCall.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(text.getText().length() == 0){ return; } Intent intent = new Intent(Intent.ACTION_CALL); intent.setData(Uri.parse("tel: "+text.getText())); startActivity(intent); } }); Button cmanager = (Button)findViewById(R.id.buttonContactsManager); cmanager.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { if (text.length() > 0) { Intent intent = new Intent("ro.pub.cs.systems.pdsd.lab04.ContactsManagerActivity"); intent.putExtra("ro.pub.cs.systems.pdsd.lab04.contactsmanager.PHONE_NUMBER_KEY", text.getText().toString()); startActivityForResult(intent, 80085); } else { Toast.makeText(getApplication(), "Introduceti numarul de telefon", Toast.LENGTH_LONG).show(); } } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.phone_dialer, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
DanielPopovici/Lab3
PhoneDialer/src/ro/pub/cs/systems/pdsd/lab03/phonedialer/PhoneDialerActivity.java
Java
apache-2.0
5,640
package com.github.jengo.java.program.design10; public class TestIntegerMatrix { public static void main(String[] args) { // Create Integer arrays m1, m2 Integer[][] m1 = new Integer[][]{{1, 2, 3}, {4, 5, 6}, {1, 1, 1}}; Integer[][] m2 = new Integer[][]{{1, 1, 1}, {2, 2, 2}, {0, 0, 0}}; // Create an instance of IntegerMatrix IntegerMatrix integerMatrix = new IntegerMatrix(); System.out.println("\nm1 + m2 is "); GenericMatrix.printResult( m1, m2, integerMatrix.addMatrix(m1, m2), '+'); System.out.println("\nm1 * m2 is "); GenericMatrix.printResult( m1, m2, integerMatrix.multiplyMatrix(m1, m2), '*'); } }
jengowong/java_program_design_10
src/main/java/com/github/jengo/java/program/design10/TestIntegerMatrix.java
Java
apache-2.0
745
/* * Copyright (C) 2010 Google 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.cellbots; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; /** * The initial splash screen that a user sees when starting up the cellbot * application. * * @author css@google.com (Charles Spirakis) */ public class LauncherActivity extends Activity { private static final String TAG = "CellbotLauncher"; public static final String PREF_SHOW_SPLASH = "SHOW_SPLASH"; public static final String PREFERENCES_NAME = "cellbotRobotPreferences"; private SharedPreferences mRobotPrefs; private SharedPreferences mGlobalPrefs; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.launcher); final Activity self = this; // See if the user wants this page shown mGlobalPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); mRobotPrefs = getSharedPreferences(PREFERENCES_NAME, MODE_PRIVATE); boolean showSplash = mGlobalPrefs.getBoolean(PREF_SHOW_SPLASH, true); final RobotList robotProfiles = new RobotList(mRobotPrefs); robotProfiles.load(); Button continueButton = (Button) findViewById(R.id.launcher_continue); continueButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { boolean currentCheck = mGlobalPrefs.getBoolean(PREF_SHOW_SPLASH, true); Intent i = new Intent(); i.setClass(self, com.cellbots.RobotSelectionActivity.class); if (robotProfiles.size() > 0) { Log.d(TAG, "Has bots, starting bot list"); i.putExtra(RobotSelectionActivity.EXTRA_CREATE_NOW, false); } else { Log.d(TAG, "No bots, starting bot create"); i.putExtra(RobotSelectionActivity.EXTRA_CREATE_NOW, true); } startActivity(i); // If the user doesn't want the splash screen any longer // don't leave it lying around. if (!currentCheck) { finish(); } } }); if (!showSplash) { Intent i = new Intent(); i.setClass(self, com.cellbots.RobotSelectionActivity.class); if (robotProfiles.size() > 0) { Log.d(TAG, "Has bots, starting bot list"); i.putExtra(RobotSelectionActivity.EXTRA_CREATE_NOW, false); } else { Log.d(TAG, "No bots, starting bot create"); i.putExtra(RobotSelectionActivity.EXTRA_CREATE_NOW, true); } startActivity(i); finish(); } } }
saasmath/Turtlebot
src/com/cellbots/LauncherActivity.java
Java
apache-2.0
3,636
package jflowmap.util.piccolo; import java.awt.Color; import java.awt.Paint; import java.awt.geom.Rectangle2D; import edu.umd.cs.piccolo.nodes.PPath; /** * @author Ilya Boyandin */ public class PPaths { private PPaths() { } public static PPath rect(double x, double y, double w, double h) { return rect(x, y, w, h, Color.black, Color.white); } public static PPath rect(double x, double y, double w, double h, Paint stroke, Paint fill) { PPath rect = new PPath(new Rectangle2D.Double(x, y, w, h)); rect.setPaint(fill); rect.setStrokePaint(stroke); return rect; } }
e3bo/jflowmap
src/jflowmap/util/piccolo/PPaths.java
Java
apache-2.0
605
package net.cbean.io; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.net.JarURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.jar.JarEntry; import java.util.jar.JarFile; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Classpath Utilities, static methods * * @author wutao [e-mail: twu@hp.com] * */ public class ClasspathUtil { private static final Log log = LogFactory.getLog(ClasspathUtil.class); /** * Scans all classes accessible from the context class loader which belong * to the given package and subpackages. * * @param packageName * The base package * @param annotated * class have annotation or not * @return The classes * @throws IOException */ public static List<InputStream> findPackageFiles(String packageName, String fileName) throws IOException { ClassLoader classLoader = Thread.currentThread() .getContextClassLoader(); assert classLoader != null; String path = packageName.replace('.', '/'); if (path == null || "".equals(path)) { path = "."; } ArrayList<InputStream> inputStreams = new ArrayList<InputStream>(); Enumeration<URL> resources = classLoader.getResources(path); while (resources.hasMoreElements()) { URL resource = resources.nextElement(); inputStreams.addAll(findFiles(resource, packageName, fileName)); log.info("Load file from resource: " + resource); } if (inputStreams.size() == 0) { InputStream in = ClassLoader.getSystemResourceAsStream(fileName); if (in.available() > 0) { inputStreams.add(in); } log.info("Load file from resource: " + fileName); } return inputStreams; } /** * Recursive method used to find all classes in a given directory and * subdirs. * * @param directory * The base directory * @param packageName * The package name for classes found inside the base directory * @param annotated * @return The classes * @throws IOException */ private static List<InputStream> findFiles(URL resource, String packageName, String fileName) throws IOException { List<InputStream> classes = new ArrayList<InputStream>(); File directory = new File(resource.getFile()); if (directory.exists()) { findClassInDir(directory, packageName, fileName, classes); } else { JarURLConnection conn = (JarURLConnection) resource .openConnection(); JarFile jarFile = conn.getJarFile(); Enumeration<JarEntry> e = jarFile.entries(); String prefix = packageName.replace('.', '/'); while (e.hasMoreElements()) { JarEntry entry = e.nextElement(); String entryname = entry.getName(); if (entryname.startsWith(prefix) && !entry.isDirectory() && entryname.endsWith(fileName)) { classes.add(jarFile.getInputStream(entry)); } } } return classes; } private static void findClassInDir(File directory, String packageName, String fileName, List<InputStream> classes) throws FileNotFoundException { File[] files = directory.listFiles(); for (File file : files) { if (file.isDirectory()) { assert !file.getName().contains("."); findClassInDir(file, packageName + "." + file.getName(), fileName, classes); } else if (file.getName().endsWith(fileName)) { classes.add(new FileInputStream(file)); } } } }
mimousewu/cbean
cbean-utils/src/main/java/net/cbean/io/ClasspathUtil.java
Java
apache-2.0
3,641
/* * Copyright 2008 The Apache Software Foundation. * * 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.vafer.jdeb.ant; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import java.util.zip.GZIPInputStream; import junit.framework.TestCase; import org.apache.commons.compress.archivers.ar.ArArchiveEntry; import org.apache.commons.compress.archivers.ar.ArArchiveInputStream; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.DefaultLogger; import org.apache.tools.ant.Project; import org.apache.tools.ant.ProjectHelper; import org.apache.tools.bzip2.CBZip2InputStream; import org.apache.tools.tar.TarEntry; import org.apache.tools.tar.TarInputStream; import org.vafer.jdeb.ar.NonClosingInputStream; /** * @author Emmanuel Bourg */ public final class DebAntTaskTestCase extends TestCase { private Project project; protected void setUp() throws Exception { project = new Project(); project.setCoreLoader(getClass().getClassLoader()); project.init(); File buildFile = new File("target/test-classes/testbuild.xml"); project.setBaseDir(buildFile.getParentFile()); final ProjectHelper helper = ProjectHelper.getProjectHelper(); helper.parse(project, buildFile); // remove the package previously build File deb = new File("target/test.deb"); if (deb.exists()) { assertTrue("Unable to remove the test archive", deb.delete()); } } public void testMissingControl() { try { project.executeTarget("missing-control"); fail("No exception thrown"); } catch (BuildException e) { // expected } } public void testInvalidControl() { try { project.executeTarget("invalid-control"); fail("No exception thrown"); } catch (BuildException e) { // expected } } public void testMissingDestFile() { try { project.executeTarget("missing-destfile"); fail("No exception thrown"); } catch (BuildException e) { // expected } } public void testEmptyPackage() { try { project.executeTarget("empty-package"); fail("No exception thrown"); } catch (BuildException e) { // expected } } public void testPackageWithArchive() { project.executeTarget("with-archive"); assertTrue("package not build", new File("target/test-classes/test.deb").exists()); } public void testPackageWithMissingArchive() { try { project.executeTarget("with-missing-archive"); fail("No exception thrown"); } catch (BuildException e) { // expected } } public void testPackageWithDirectory() { project.executeTarget("with-directory"); assertTrue("package not build", new File("target/test-classes/test.deb").exists()); } public void testPackageWithMissingDirectory() { try { project.executeTarget("with-missing-directory"); fail("No exception thrown"); } catch (BuildException e) { // expected } } /** * Redirects the Ant output to the specified stream. */ private void redirectOutput(OutputStream out) { DefaultLogger logger = new DefaultLogger(); logger.setOutputPrintStream(new PrintStream(out)); logger.setMessageOutputLevel(Project.MSG_INFO); project.addBuildListener(logger); } public void testVerboseEnabled() { ByteArrayOutputStream out = new ByteArrayOutputStream(); redirectOutput(out); project.executeTarget("verbose-enabled"); assertTrue(out.toString().indexOf("Total size") != -1); } public void testVerboseDisabled() { ByteArrayOutputStream out = new ByteArrayOutputStream(); redirectOutput(out); project.executeTarget("verbose-disabled"); assertTrue(out.toString().indexOf("Total size") == -1); } public void testFileSet() { project.executeTarget("fileset"); assertTrue("package not build", new File("target/test-classes/test.deb").exists()); } public void testTarFileSet() throws Exception { project.executeTarget("tarfileset"); File deb = new File("target/test-classes/test.deb"); assertTrue("package not build", deb.exists()); ArArchiveInputStream in = new ArArchiveInputStream(new FileInputStream(deb)); ArArchiveEntry entry; while ((entry = in.getNextArEntry()) != null) { if (entry.getName().equals("data.tar.gz")) { TarInputStream tar = new TarInputStream(new GZIPInputStream(new NonClosingInputStream(in))); TarEntry tarentry; while ((tarentry = tar.getNextEntry()) != null) { assertTrue("prefix", tarentry.getName().startsWith("./foo/")); if (tarentry.isDirectory()) { assertEquals("directory mode (" + tarentry.getName() + ")", 040700, tarentry.getMode()); } else { assertEquals("file mode (" + tarentry.getName() + ")", 0100600, tarentry.getMode()); } assertEquals("user", "ebourg", tarentry.getUserName()); assertEquals("group", "ebourg", tarentry.getGroupName()); } tar.close(); } else { // skip to the next entry long skip = entry.getLength(); while(skip > 0) { long skipped = in.skip(skip); if (skipped == -1) { throw new IOException("Failed to skip"); } skip -= skipped; } } } in.close(); } public void testUnkownCompression() throws Exception { try { project.executeTarget("unknown-compression"); fail("No exception thrown"); } catch (BuildException e) { // expected } } public void testBZip2Compression() throws Exception { project.executeTarget("bzip2-compression"); File deb = new File("target/test-classes/test.deb"); assertTrue("package not build", deb.exists()); boolean found = false; ArArchiveInputStream in = new ArArchiveInputStream(new FileInputStream(deb)); ArArchiveEntry entry; while ((entry = in.getNextArEntry()) != null) { if (entry.getName().equals("data.tar.bz2")) { found = true; assertEquals("header 0", (byte) 'B', in.read()); assertEquals("header 1", (byte) 'Z', in.read()); TarInputStream tar = new TarInputStream(new CBZip2InputStream(in)); while (tar.getNextEntry() != null); tar.close(); break; } else { // skip to the next entry long skip = entry.getLength(); while(skip > 0) { long skipped = in.skip(skip); if (skipped == -1) { throw new IOException("Failed to skip"); } skip -= skipped; } } } in.close(); assertTrue("bz2 file not found", found); } public void testNoCompression() throws Exception { project.executeTarget("no-compression"); File deb = new File("target/test-classes/test.deb"); assertTrue("package not build", deb.exists()); boolean found = false; ArArchiveInputStream in = new ArArchiveInputStream(new FileInputStream(deb)); ArArchiveEntry entry; while ((entry = in.getNextArEntry()) != null) { if (entry.getName().equals("data.tar")) { found = true; TarInputStream tar = new TarInputStream(new NonClosingInputStream(in)); while (tar.getNextEntry() != null); tar.close(); } else { // skip to the next entry long skip = entry.getLength(); while(skip > 0) { long skipped = in.skip(skip); if (skipped == -1) { throw new IOException("Failed to skip"); } skip -= skipped; } } } in.close(); assertTrue("tar file not found", found); } }
jkeillor/jdeb
src/test/java/org/vafer/jdeb/ant/DebAntTaskTestCase.java
Java
apache-2.0
9,337
/* * 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. */ /* * This code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.billingbudgets.v1.model; /** * All date times begin at 12 AM US and Canadian Pacific Time (UTC-8). * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the Cloud Billing Budget API. For a detailed explanation * see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class GoogleCloudBillingBudgetsV1CustomPeriod extends com.google.api.client.json.GenericJson { /** * Optional. The end date of the time period. Budgets with elapsed end date won't be processed. If * unset, specifies to track all usage incurred since the start_date. * The value may be {@code null}. */ @com.google.api.client.util.Key private GoogleTypeDate endDate; /** * Required. The start date must be after January 1, 2017. * The value may be {@code null}. */ @com.google.api.client.util.Key private GoogleTypeDate startDate; /** * Optional. The end date of the time period. Budgets with elapsed end date won't be processed. If * unset, specifies to track all usage incurred since the start_date. * @return value or {@code null} for none */ public GoogleTypeDate getEndDate() { return endDate; } /** * Optional. The end date of the time period. Budgets with elapsed end date won't be processed. If * unset, specifies to track all usage incurred since the start_date. * @param endDate endDate or {@code null} for none */ public GoogleCloudBillingBudgetsV1CustomPeriod setEndDate(GoogleTypeDate endDate) { this.endDate = endDate; return this; } /** * Required. The start date must be after January 1, 2017. * @return value or {@code null} for none */ public GoogleTypeDate getStartDate() { return startDate; } /** * Required. The start date must be after January 1, 2017. * @param startDate startDate or {@code null} for none */ public GoogleCloudBillingBudgetsV1CustomPeriod setStartDate(GoogleTypeDate startDate) { this.startDate = startDate; return this; } @Override public GoogleCloudBillingBudgetsV1CustomPeriod set(String fieldName, Object value) { return (GoogleCloudBillingBudgetsV1CustomPeriod) super.set(fieldName, value); } @Override public GoogleCloudBillingBudgetsV1CustomPeriod clone() { return (GoogleCloudBillingBudgetsV1CustomPeriod) super.clone(); } }
googleapis/google-api-java-client-services
clients/google-api-services-billingbudgets/v1/1.31.0/com/google/api/services/billingbudgets/v1/model/GoogleCloudBillingBudgetsV1CustomPeriod.java
Java
apache-2.0
3,314
/* * Copyright 2005 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.drools.core.spi; import java.io.Serializable; import org.drools.core.base.ValueType; import org.drools.core.common.InternalFactHandle; import org.drools.core.common.ReteEvaluator; import org.drools.core.rule.VariableRestriction.VariableContextEntry; import org.drools.core.time.Interval; import org.kie.api.runtime.rule.Operator; /** * A public interface to be implemented by all evaluators */ public interface Evaluator extends Serializable, org.kie.api.runtime.rule.Evaluator { /** * Returns the type of the values this evaluator operates upon. * * @return */ public ValueType getValueType(); /** * Returns the operator representation object for this evaluator * * @return */ public Operator getOperator(); /** * Returns the value type this evaluator will coerce * operands to, during evaluation. This is useful for * operators like "memberOf", that always convert to * Object when evaluating, independently of the source * operand value type. * * @return */ public ValueType getCoercedValueType(); /** * Evaluates the expression using the provided parameters. * * This method is used when evaluating alpha-constraints, * i.e., a fact attribute against a constant value. * For instance: * * Person( name == "Bob" ) * * So, it uses a constant value "Bob" that is sent into * the method as the FieldValue (value), and compares it * to the value of the name field, read by using the * extractor on the fact instance (object1). * * @param workingMemory * The current working memory * @param extractor * The extractor used to get the field value from the object * @param factHandle * The source object to evaluate, i.e., the fact * @param value * The actual value to compare to, i.e., the constant value. * * @return Returns true if evaluation is successful. false otherwise. */ public boolean evaluate(ReteEvaluator reteEvaluator, InternalReadAccessor extractor, InternalFactHandle factHandle, FieldValue value); /** * Evaluates the expression using the provided parameters. * * This method is used for internal indexing and hashing, * when drools needs to extract and evaluate both left and * right values at once. * * For instance: * * Person( name == $someName ) * * This method will be used to extract and evaluate both * the "name" attribute and the "$someName" variable at once. * * @param workingMemory * The current working memory * @param leftExtractor * The extractor to read the left value. In the above example, * the "$someName" variable value. * @param left * The source object from where the value of the variable is * extracted. * @param rightExtractor * The extractor to read the right value. In the above example, * the "name" attribute value. * @param right * The right object from where to extract the value. In the * above example, that is the "Person" instance from where to * extract the "name" attribute. * * @return Returns true if evaluation is successful. false otherwise. */ public boolean evaluate(ReteEvaluator reteEvaluator, InternalReadAccessor leftExtractor, InternalFactHandle left, InternalReadAccessor rightExtractor, InternalFactHandle right); /** * Evaluates the expression using the provided parameters. * * This method is used when evaluating left-activated * beta-constraints, i.e., a fact attribute against a variable * value, that is activated from the left. * * For instance: * * Person( name == $someName ) * * This method will be used when a new $someName variable is * bound. So it will cache the value of $someName and will * iterate over the right memory (Person instances) evaluating * each occurrence. * * @param workingMemory * The current working memory * @param context * The previously cached context, including the left value * and the extractor for the right value. * @param right * The right object, from where to extract the value. In the * above example, that is the "Person" instance from where to * extract the "name" attribute. * * @return Returns true if evaluation is successful. false otherwise. */ public boolean evaluateCachedLeft(ReteEvaluator reteEvaluator, VariableContextEntry context, InternalFactHandle right); /** * Evaluates the expression using the provided parameters. * * This method is used when evaluating right-activated * beta-constraints, i.e., a fact attribute against a variable * value, that is activated from the right. * * For instance: * * Person( name == $someName ) * * This method will be used when a new Person instance is evaluated. * So it will cache the value of the "Person" instance and will * iterate over the left memory comparing it to each "$someName" bound * values. * * @param workingMemory * The current working memory * @param context * The previously cached context, including the right value * and the extractor for the left value. * @param left * The left object, from where to extract the bound variable. * In the above example, that is the "$someName" variable value. * * @return Returns true if evaluation is successful. false otherwise. */ public boolean evaluateCachedRight(ReteEvaluator reteEvaluator, VariableContextEntry context, InternalFactHandle left); /** * Returns true if this evaluator implements a temporal evaluation, * i.e., a time sensitive evaluation whose properties of matching * only events within an specific time interval can be used for * determining event expirations automatically. * * @return true if the evaluator is a temporal evaluator. */ public boolean isTemporal(); /** * In case this is a temporal evaluator, returns the interval * in which this evaluator may match the target fact * * @return */ public Interval getInterval(); }
manstis/drools
drools-core/src/main/java/org/drools/core/spi/Evaluator.java
Java
apache-2.0
7,581
/** * 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.interceptor; import java.util.ArrayList; import java.util.List; import org.apache.camel.ContextTestSupport; import org.apache.camel.Exchange; import org.apache.camel.NamedNode; import org.apache.camel.Processor; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.impl.BreakpointSupport; import org.apache.camel.impl.DefaultDebugger; import org.apache.camel.spi.Breakpoint; import org.apache.camel.spi.Condition; import org.junit.Before; import org.junit.Test; public class DebugSingleStepConditionTest extends ContextTestSupport { private List<String> logs = new ArrayList<>(); private Breakpoint breakpoint; private Condition beerCondition; @Override @Before public void setUp() throws Exception { super.setUp(); breakpoint = new BreakpointSupport() { public void beforeProcess(Exchange exchange, Processor processor, NamedNode definition) { String body = exchange.getIn().getBody(String.class); logs.add("Single stepping at " + definition.getLabel() + " with body: " + body); } }; beerCondition = new ConditionSupport() { public boolean matchProcess(Exchange exchange, Processor processor, NamedNode definition) { return "beer".equals(exchange.getFromRouteId()); } }; } @Test public void testDebug() throws Exception { // we only want to single step the beer route context.getDebugger().addSingleStepBreakpoint(breakpoint, beerCondition); getMockEndpoint("mock:result").expectedBodiesReceived("Hello World", "Carlsberg"); template.sendBody("direct:start", "Hello World"); template.sendBody("direct:beer", "Carlsberg"); assertMockEndpointsSatisfied(); assertEquals(2, logs.size()); assertEquals("Single stepping at log:beer with body: Carlsberg", logs.get(0)); assertEquals("Single stepping at mock:result with body: Carlsberg", logs.get(1)); } @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() throws Exception { // use debugger context.setDebugger(new DefaultDebugger()); from("direct:start").routeId("foo").to("log:foo").to("log:bar").to("mock:result"); from("direct:beer").routeId("beer").to("log:beer").to("mock:result"); } }; } }
punkhorn/camel-upstream
core/camel-core/src/test/java/org/apache/camel/processor/interceptor/DebugSingleStepConditionTest.java
Java
apache-2.0
3,372
/* * Copyright 2014-2019 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.amplify.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.amplify.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * StopJobResult JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class StopJobResultJsonUnmarshaller implements Unmarshaller<StopJobResult, JsonUnmarshallerContext> { public StopJobResult unmarshall(JsonUnmarshallerContext context) throws Exception { StopJobResult stopJobResult = new StopJobResult(); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) { return stopJobResult; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("jobSummary", targetDepth)) { context.nextToken(); stopJobResult.setJobSummary(JobSummaryJsonUnmarshaller.getInstance().unmarshall(context)); } } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return stopJobResult; } private static StopJobResultJsonUnmarshaller instance; public static StopJobResultJsonUnmarshaller getInstance() { if (instance == null) instance = new StopJobResultJsonUnmarshaller(); return instance; } }
jentfoo/aws-sdk-java
aws-java-sdk-amplify/src/main/java/com/amazonaws/services/amplify/model/transform/StopJobResultJsonUnmarshaller.java
Java
apache-2.0
2,728
package com.kris.services.impl; import java.util.Date; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.kris.repositories.CardDAO; import com.kris.services.CardService; import com.kris.services.models.CardDetails; @Component public class CardServiceImpl implements CardService{ @Autowired private CardDAO cardDao; @Override public CardDetails addCardToUser(Long userId, String cardNumber, Date expirationDate) { return this.cardDao.createCard(userId, cardNumber, expirationDate); } @Override public List<CardDetails> getCards(Long userId) { return this.cardDao.getCards(userId); } @Override public CardDetails getCard(Long userId, Long cardId) { CardDetails card = this.cardDao.getCard(cardId); if (card.getUserId().equals(userId)){ return card; } else return null; } @Override public void deleteCard(Long cardId) { this.cardDao.deleteCard(cardId); } }
krisgalea/spring-boot-sample
user-service/src/main/java/com/kris/services/impl/CardServiceImpl.java
Java
apache-2.0
996
/* * Copyright 2010 The Apache Software Foundation * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hbase.client.idx.exp; import junit.framework.Assert; import junit.framework.TestCase; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.io.DataInputBuffer; import org.apache.hadoop.io.DataOutputBuffer; import java.io.IOException; /** * Tests the expression class. */ public class TestExpression extends TestCase { /** * Tests that the methods to build an expression all result in equal instances * when provided the same input. */ public void testExpressionBuilder() { String columnName1 = "columnName1"; String qualifer1 = "qualifier1"; byte[] value1 = Bytes.toBytes("value1"); Comparison.Operator operator1 = Comparison.Operator.EQ; String columnName2 = "columnName2"; String qualifer2 = "qualifier2"; byte[] value2 = Bytes.toBytes("value2"); Comparison.Operator operator2 = Comparison.Operator.GT; String columnName3 = "columnName3"; String qualifer3 = "qualifier3"; byte[] value3 = Bytes.toBytes("value3"); Comparison.Operator operator3 = Comparison.Operator.LT; Expression expression1 = new Or( new Comparison(columnName1, qualifer1, operator1, value1), new And( new Comparison(columnName2, qualifer2, operator2, value2), new Comparison(columnName3, qualifer3, operator3, value3) ) ); Expression expression2 = Expression .or( Expression.comparison(columnName1, qualifer1, operator1, value1) ) .or( Expression.and() .and(Expression.comparison(columnName2, qualifer2, operator2, value2)) .and(Expression.comparison(columnName3, qualifer3, operator3, value3)) ); Expression expression3 = Expression.or( Expression.comparison(columnName1, qualifer1, operator1, value1), Expression.and( Expression.comparison(columnName2, qualifer2, operator2, value2), Expression.comparison(columnName3, qualifer3, operator3, value3) ) ); Assert.assertTrue("The expressions didn't match", expression1.equals(expression2) && expression1.equals(expression3)); } /** * Tests the an expression tree can be written and read and still be equal. * * @throws java.io.IOException if an io error occurs */ public void testWritable() throws IOException { Expression expression = Expression.or( Expression.comparison("columnName1", "qualifier1", Comparison.Operator.EQ, Bytes.toBytes("value")), Expression.and( Expression.comparison("columnName2", "qualifier2", Comparison.Operator.GT, Bytes.toBytes("value2")), Expression.comparison("columnName3", "qualifier3", Comparison.Operator.LT, Bytes.toBytes("value3")) ) ); DataOutputBuffer dataOutputBuffer = new DataOutputBuffer(); expression.write(dataOutputBuffer); DataInputBuffer dataInputBuffer = new DataInputBuffer(); dataInputBuffer.reset(dataOutputBuffer.getData(), dataOutputBuffer.getLength()); Expression clonedExpression = new Or(); clonedExpression.readFields(dataInputBuffer); Assert.assertEquals("The expression was not the same after being written and read", expression, clonedExpression); } }
ykulbak/ihbase
src/test/java/org/apache/hadoop/hbase/client/idx/exp/TestExpression.java
Java
apache-2.0
4,485
/* * Copyright (C) 2015 Google, 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 test.subcomponent; import javax.inject.Inject; final class RequiresSingleton { private final SingletonType singletonType; @Inject RequiresSingleton(SingletonType singletonType) { this.singletonType = singletonType; } SingletonType singletonType() { return singletonType; } }
yawkat/dagger
compiler/src/it/functional-tests/src/main/java/test/subcomponent/RequiresSingleton.java
Java
apache-2.0
901
/** * Copyright 2012 Kamran Zafar * * 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.kamranzafar.jddl; import java.awt.Container; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.net.URL; import javax.swing.BorderFactory; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JProgressBar; import javax.swing.border.TitledBorder; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * @author kamran * */ @RunWith(JUnit4.class) public class SwingTest { private static final String STOP = "Stop"; private static final String CANCEL = "Cancel"; private static final String PAUSE = "Pause"; private static final String RESUME = "Resume"; private static final String TOTAL = "Total"; // total progress bar private final JProgressBar totalProgressBar = new JProgressBar(); @Test public void testSwing() throws IOException, InterruptedException { JFrame f = new JFrame("jddl Swing example"); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container content = f.getContentPane(); content.setLayout(new GridLayout(4, 1)); // Some files String files[] = { "http://python.org/ftp/python/2.7.2/python-2.7.2.msi", "http://www.python.org/ftp/python/3.2.2/python-3.2.2.msi", "http://www.python.org/ftp/python/3.2.2/python-3.2.2.amd64.msi" }; // Create a DirectDownloader instance final DirectDownloader fd = new DirectDownloader(); // Progress bars for individual file downloads JProgressBar[] progressBar = new JProgressBar[3]; // Pause/Resume buttons JButton[] pauseButton = new JButton[3]; // Cancel JButton[] cancelButton = new JButton[3]; JButton stopButton = new JButton(STOP); stopButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { fd.cancelAll(); } }); // Initialize progress bars and create download tasks for (int i = 0; i < 3; i++) { String fname = files[i].substring(files[i].lastIndexOf('/') + 1); progressBar[i] = new JProgressBar(); pauseButton[i] = new JButton(PAUSE); cancelButton[i] = new JButton(CANCEL); JPanel panel = new JPanel(); BoxLayout box = new BoxLayout(panel, BoxLayout.X_AXIS); panel.setLayout(box); final DownloadTask dt = new DownloadTask(new URL(files[i]), new FileOutputStream(fname)); dt.addListener(new ProgressBarUpdator(fname, progressBar[i])); pauseButton[i].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (dt.isPaused()) { dt.setPaused(false); ((JButton) e.getSource()).setText(PAUSE); } else { dt.setPaused(true); ((JButton) e.getSource()).setText(RESUME); } } }); cancelButton[i].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { dt.setCancelled(true); } }); progressBar[i].setStringPainted(true); progressBar[i].setBorder(BorderFactory.createTitledBorder("Downloading " + fname + "...")); panel.add(progressBar[i]); panel.add(pauseButton[i]); panel.add(cancelButton[i]); content.add(panel); fd.download(dt); } totalProgressBar.setBorder(BorderFactory.createTitledBorder(TOTAL)); totalProgressBar.setStringPainted(true); totalProgressBar.setMaximum(0); JPanel panel = new JPanel(); BoxLayout box = new BoxLayout(panel, BoxLayout.X_AXIS); panel.setLayout(box); panel.add(totalProgressBar); panel.add(stopButton); content.add(panel); f.setSize(400, 200); f.setVisible(true); // Start downloading Thread t = new Thread(fd); t.start(); } // Class that updates the download progress class ProgressBarUpdator implements DownloadListener { private static final String DONE = "Done"; JProgressBar progressBar; int size = -1; String fname; public ProgressBarUpdator(String fname, JProgressBar progressBar) { this.progressBar = progressBar; this.fname = fname; } public void onComplete() { if (size == -1) { progressBar.setIndeterminate(false); progressBar.setValue(100); } ((TitledBorder) progressBar.getBorder()).setTitle(DONE); progressBar.repaint(); } public void onStart(String fname, int fsize) { if (fsize > -1) { progressBar.setMaximum(fsize); synchronized (totalProgressBar) { totalProgressBar.setMaximum(totalProgressBar.getMaximum() + fsize); } size = fsize; } else { progressBar.setIndeterminate(true); } } public void onUpdate(int bytes, int totalDownloaded) { if (size == -1) { progressBar.setString("" + totalDownloaded); } else { progressBar.setValue(totalDownloaded); synchronized (totalProgressBar) { totalProgressBar.setValue(totalProgressBar.getValue() + bytes); } } } public void onCancel() { new File(fname).delete(); } } public static void main(String[] args) throws IOException, InterruptedException { SwingTest st = new SwingTest(); st.testSwing(); } }
kamranzafar/jddl
src/test/java/org/kamranzafar/jddl/SwingTest.java
Java
apache-2.0
5,930
package com.stone.EasyTeaching.utilities; import android.content.Context; import android.util.AttributeSet; import android.widget.LinearLayout; /** * Created by hangli2 on 2015/6/24. */ public class MySquareLayout extends LinearLayout { public MySquareLayout(Context context) { super(context); } public MySquareLayout(Context context, AttributeSet attrs) { super(context, attrs); } public MySquareLayout(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { setMeasuredDimension(getDefaultSize(0, widthMeasureSpec), getDefaultSize(0, heightMeasureSpec)); int childWidthSize = getMeasuredWidth(); int childHeightSize = getMeasuredHeight(); //高度和宽度一样 heightMeasureSpec = widthMeasureSpec = MeasureSpec.makeMeasureSpec(childWidthSize, MeasureSpec.EXACTLY); super.onMeasure(widthMeasureSpec, heightMeasureSpec); } }
lhangtk/EasyTeaching
src/com/stone/EasyTeaching/utilities/MySquareLayout.java
Java
apache-2.0
1,057
/* * Copyright 1999-2018 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.csp.sentinel.adapter.sofa.rpc; import com.alipay.sofa.rpc.common.RemotingConstants; import com.alipay.sofa.rpc.core.request.SofaRequest; /** * @author cdfive */ public class SofaRpcUtils { public static String getApplicationName(SofaRequest request) { String appName = (String) request.getRequestProp(RemotingConstants.HEAD_APP_NAME); return appName == null ? "" : appName; } public static String getInterfaceResourceName(SofaRequest request) { return request.getInterfaceName(); } public static String getMethodResourceName(SofaRequest request) { StringBuilder buf = new StringBuilder(64); buf.append(request.getInterfaceName()) .append("#") .append(request.getMethodName()) .append("("); boolean isFirst = true; for (String methodArgSig : request.getMethodArgSigs()) { if (!isFirst) { buf.append(","); } else { isFirst = false; } buf.append(methodArgSig); } buf.append(")"); return buf.toString(); } public static Object[] getMethodArguments(SofaRequest request) { return request.getMethodArgs(); } private SofaRpcUtils() {} }
alibaba/Sentinel
sentinel-adapter/sentinel-sofa-rpc-adapter/src/main/java/com/alibaba/csp/sentinel/adapter/sofa/rpc/SofaRpcUtils.java
Java
apache-2.0
1,928
package com.pdsl.api; import org.junit.runner.RunWith; import org.junit.runners.Suite; @RunWith(Suite.class) @Suite.SuiteClasses({FrameworkSpecifications.class, GherkinApi.class, GherkinPolymorphicDslTestExecutor.class, GherkinTestRunWithFailures.class, PolymorphicDslGherkinExecution.class, PolymorphicDsl.class }) public class ApiSuiteTest {}
google/polymorphicDSL
src/test/java/com/pdsl/api/ApiSuiteTest.java
Java
apache-2.0
355
package com.example.sonya.grouplockapplication; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.pm.PackageManager; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.TextView; public class ChooseToDoActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_choose_to_do); Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(mToolbar); try { ActivityInfo activityInfo = getPackageManager().getActivityInfo( getComponentName(), PackageManager.GET_META_DATA); TextView tw=(TextView)findViewById(R.id.textViewPage); tw.setText(activityInfo.loadLabel(getPackageManager()) .toString()+" ▼"); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } } public void showMenu(View v) { IconizedMenu popupMenu = new IconizedMenu(this, v); MenuInflater inflater = popupMenu.getMenuInflater(); inflater.inflate(R.menu.home_menu, popupMenu.getMenu()); popupMenu.setOnMenuItemClickListener(new IconizedMenu.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { switch (item.getItemId()) { case R.id.library:{ Intent intent = new Intent(ChooseToDoActivity.this, LibraryActivity.class); startActivity(intent); return true; } case R.id.settings:{ Intent intent = new Intent(ChooseToDoActivity.this, SettingsActivity.class); startActivity(intent); return true; } case R.id.info:{ Intent intent = new Intent(ChooseToDoActivity.this, InformationActivity.class); startActivity(intent); return true; } default: return false; } } }); popupMenu.show(); } public void showInfo(View view){ //выплывающее окно TextView infoMessage = (TextView) findViewById(R.id.textViewInfoMessage); if (infoMessage.getVisibility()!=View.VISIBLE) infoMessage.setVisibility(View.VISIBLE); else infoMessage.setVisibility(View.INVISIBLE); } public void loadPage(View view) { Intent intent = new Intent(ChooseToDoActivity.this, LoadActivity.class); startActivity(intent); } public void chooseEncrypt(View v) { Intent intent = new Intent(this, LibraryActivity.class); intent.putExtra("state", LibraryActivity.LibraryState.ENCRYPT_SELECTING); startActivity(intent); } public void chooseDecrypt(View v) { Intent intent = new Intent(this, LibraryActivity.class); intent.putExtra("state", LibraryActivity.LibraryState.DECRYPT_SELECTING); startActivity(intent); } @Override public void onBackPressed() { moveTaskToBack(true); super.onDestroy(); System.runFinalizersOnExit(true); System.exit(0); } }
lanit-tercom-school/grouplock
GroupLockApplication/app/src/main/java/com/example/sonya/grouplockapplication/ChooseToDoActivity.java
Java
apache-2.0
3,646
/** * https://github.com/auzll/ * * 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 z.tool.util.image; import java.awt.Graphics2D; import java.io.IOException; /** * * @author auzll * @since 2013-7-20 上午11:40:38 */ public interface Mergeable { void draw(Graphics2D graphics2d) throws IOException; }
auzll/zTool
src/main/java/z/tool/util/image/Mergeable.java
Java
apache-2.0
1,104
package com.topie.internal.whitelist.web; import java.util.List; import java.util.Map; import javax.annotation.Resource; import com.topie.api.tenant.TenantHolder; import com.topie.core.export.Exportor; import com.topie.core.mapper.BeanMapper; import com.topie.core.page.Page; import com.topie.core.query.PropertyFilter; import com.topie.core.spring.MessageHelper; import com.topie.internal.whitelist.persistence.domain.WhitelistApp; import com.topie.internal.whitelist.persistence.manager.WhitelistAppManager; import com.topie.internal.whitelist.persistence.manager.WhitelistTypeManager; import com.topie.internal.whitelist.service.WhitelistService; 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.servlet.mvc.support.RedirectAttributes; @Controller @RequestMapping("whitelist") public class WhitelistAdminController { private WhitelistAppManager whitelistAppManager; private WhitelistTypeManager whitelistTypeManager; private WhitelistService whitelistService; private MessageHelper messageHelper; private Exportor exportor; private BeanMapper beanMapper = new BeanMapper(); private TenantHolder tenantHolder; @RequestMapping("whitelist-admin-list") public String list(@ModelAttribute Page page, @RequestParam Map<String, Object> parameterMap, Model model) { String tenantId = tenantHolder.getTenantId(); List<PropertyFilter> propertyFilters = PropertyFilter .buildFromMap(parameterMap); propertyFilters.add(new PropertyFilter("EQS_tenantId", tenantId)); page = whitelistAppManager.pagedQuery(page, propertyFilters); model.addAttribute("page", page); return "whitelist/whitelist-admin-list"; } @RequestMapping("whitelist-admin-input") public String input( @RequestParam(value = "id", required = false) Long id, @RequestParam(value = "type", required = false) String whitelistTypeCode, Model model) { String tenantId = tenantHolder.getTenantId(); WhitelistApp whitelistApp = null; if (id != null) { whitelistApp = whitelistAppManager.get(id); model.addAttribute("model", whitelistApp); } if (whitelistApp != null) { model.addAttribute("whitelistType", whitelistApp.getWhitelistType()); } else if (whitelistTypeCode != null) { model.addAttribute("whitelistType", whitelistTypeManager .findUnique( "from WhitelistType where code=? and tenantId=?", whitelistTypeCode, tenantId)); } else { model.addAttribute("whitelistTypes", whitelistTypeManager.findBy("tenantId", tenantId)); } return "whitelist/whitelist-admin-input"; } @RequestMapping("whitelist-admin-save") public String save(@ModelAttribute WhitelistApp whitelistApp, @RequestParam("typeId") Long whitelistTypeId, @RequestParam("host") String hostContent, @RequestParam("ip") String ipContent, RedirectAttributes redirectAttributes) { String tenantId = tenantHolder.getTenantId(); whitelistService.saveWhitelistApp(whitelistApp, whitelistTypeId, hostContent, ipContent, whitelistApp.getUserId(), tenantId); messageHelper.addFlashMessage(redirectAttributes, "core.success.save", "保存成功"); return "redirect:/whitelist/whitelist-admin-list.do"; } @RequestMapping("whitelist-admin-remove") public String remove(@RequestParam("selectedItem") List<Long> selectedItem, RedirectAttributes redirectAttributes) { List<WhitelistApp> whitelistApps = whitelistAppManager .findByIds(selectedItem); for (WhitelistApp whitelistApp : whitelistApps) { whitelistAppManager.removeAll(whitelistApp.getWhitelistHosts()); whitelistAppManager.removeAll(whitelistApp.getWhitelistIps()); whitelistAppManager.remove(whitelistApp); } messageHelper.addFlashMessage(redirectAttributes, "core.success.delete", "删除成功"); return "redirect:/whitelist/whitelist-admin-list.do"; } // ~ ====================================================================== @Resource public void setWhitelistAppManager(WhitelistAppManager whitelistAppManager) { this.whitelistAppManager = whitelistAppManager; } @Resource public void setWhitelistTypeManager( WhitelistTypeManager whitelistTypeManager) { this.whitelistTypeManager = whitelistTypeManager; } @Resource public void setWhitelistService(WhitelistService whitelistService) { this.whitelistService = whitelistService; } @Resource public void setMessageHelper(MessageHelper messageHelper) { this.messageHelper = messageHelper; } @Resource public void setExportor(Exportor exportor) { this.exportor = exportor; } @Resource public void setTenantHolder(TenantHolder tenantHolder) { this.tenantHolder = tenantHolder; } }
topie/topie-oa
src/main/java/com/topie/internal/whitelist/web/WhitelistAdminController.java
Java
apache-2.0
5,459
package org.sapia.corus.interop.soap.message; import org.sapia.corus.interop.api.message.MessageCommand; /** * This class represents a Corus interop command. It contains the command identifier * that is associated to every command returned by the Corus server. * * @author jcdesrochers * @author yduchesne */ public abstract class Command implements java.io.Serializable, MessageCommand{ static final long serialVersionUID = 1L; private String _theCommandId; /** * Creates a new Command instance. */ protected Command() { } @Override public String getCommandId() { return _theCommandId; } public void setCommandId(String aCommandId) { _theCommandId = aCommandId; } /** * Returns a string representation of this abstract request. * * @return A string representation of this abstract request. */ public String toString() { StringBuffer aBuffer = new StringBuffer(super.toString()); aBuffer.append("[commandId=").append(_theCommandId).append("]"); return aBuffer.toString(); } }
sapia-oss/corus_iop
modules/client/src/main/java/org/sapia/corus/interop/soap/message/Command.java
Java
apache-2.0
1,057
package com.example.animation.activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.preference.Preference; import android.preference.PreferenceFragment; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import com.example.animation.BuildConfig; import com.example.animation.R; import com.xiaomi.mistatistic.sdk.MiStatInterface; /** * Created by 刘通 on 2017/10/15. */ public class AboutActivity extends AppCompatActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_about); Button button = (Button) findViewById(R.id.about_back); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); getFragmentManager().beginTransaction().replace(R.id.ll_fragment_container,new AboutFragment()).commit(); } public static class AboutFragment extends PreferenceFragment implements Preference.OnPreferenceClickListener{ private Preference mVersion; private Preference mShare; private Preference mGithub; private Preference mWeiXinHao; private Preference mQQQun; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preference_about); mVersion = findPreference("version"); mShare = findPreference("share"); mGithub = findPreference("github"); mWeiXinHao = findPreference("weixingongzhonghao"); mQQQun = findPreference("qqqun"); mVersion.setSummary("v " + BuildConfig.VERSION_NAME); setListener(); } @Override public void onResume() { super.onResume(); MiStatInterface.recordPageStart(getActivity(),"关于"); } @Override public void onPause() { super.onPause(); MiStatInterface.recordPageEnd(); } private void setListener(){ mShare.setOnPreferenceClickListener(this); mGithub.setOnPreferenceClickListener(this); mWeiXinHao.setOnPreferenceClickListener(this); mQQQun.setOnPreferenceClickListener(this); } @Override public boolean onPreferenceClick(Preference preference) { if(preference == mShare){ share(); return true; }else if(preference == mGithub){ openUrl(preference.getSummary().toString()); return true; }else if (preference == mWeiXinHao){ Intent intent = new Intent(AboutFragment.this.getActivity(),WeiXinHao.class); intent.putExtra(WeiXinHao.TYPE,WeiXinHao.WEIXIN); AboutFragment.this.getActivity().startActivity(intent); return true; }else if (preference == mQQQun){ Intent intent = new Intent(AboutFragment.this.getActivity(),WeiXinHao.class); intent.putExtra(WeiXinHao.TYPE,WeiXinHao.QQQUN); AboutFragment.this.getActivity().startActivity(intent); return true; } return false; } private void share(){ Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("text/plain"); intent.putExtra(Intent.EXTRA_TEXT,getString(R.string.share_app,"喵搜")); startActivity(Intent.createChooser(intent,getString(R.string.share))); } private void openUrl(String url){ Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(url)); startActivity(intent); } } }
NicoLiutong/miaosou
app/src/main/java/com/example/animation/activity/AboutActivity.java
Java
apache-2.0
4,021
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.mediaconvert.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.mediaconvert.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * MotionImageInserter JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class MotionImageInserterJsonUnmarshaller implements Unmarshaller<MotionImageInserter, JsonUnmarshallerContext> { public MotionImageInserter unmarshall(JsonUnmarshallerContext context) throws Exception { MotionImageInserter motionImageInserter = new MotionImageInserter(); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) { return null; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("framerate", targetDepth)) { context.nextToken(); motionImageInserter.setFramerate(MotionImageInsertionFramerateJsonUnmarshaller.getInstance().unmarshall(context)); } if (context.testExpression("input", targetDepth)) { context.nextToken(); motionImageInserter.setInput(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("insertionMode", targetDepth)) { context.nextToken(); motionImageInserter.setInsertionMode(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("offset", targetDepth)) { context.nextToken(); motionImageInserter.setOffset(MotionImageInsertionOffsetJsonUnmarshaller.getInstance().unmarshall(context)); } if (context.testExpression("playback", targetDepth)) { context.nextToken(); motionImageInserter.setPlayback(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("startTime", targetDepth)) { context.nextToken(); motionImageInserter.setStartTime(context.getUnmarshaller(String.class).unmarshall(context)); } } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return motionImageInserter; } private static MotionImageInserterJsonUnmarshaller instance; public static MotionImageInserterJsonUnmarshaller getInstance() { if (instance == null) instance = new MotionImageInserterJsonUnmarshaller(); return instance; } }
aws/aws-sdk-java
aws-java-sdk-mediaconvert/src/main/java/com/amazonaws/services/mediaconvert/model/transform/MotionImageInserterJsonUnmarshaller.java
Java
apache-2.0
4,049
/* * Copyright 2017 haeun kim * * 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 algorithm.boj; import java.io.*; /** * Created by haeun on 2017-09-23 * Site : https://www.acmicpc.net/problem/8393 */ public class Boj8393 { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); System.out.print(n*(n+1)/2); } }
hagomy/algorithm
src/algorithm/boj/Boj8393.java
Java
apache-2.0
999
package net.mikaboshi.ant; import static net.mikaboshi.validator.SimpleValidator.validateNotBlank; import static net.mikaboshi.validator.SimpleValidator.validateNotNull; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; import java.sql.Connection; import java.sql.SQLException; import net.mikaboshi.jdbc.DbUtils; import net.mikaboshi.jdbc.QueryExecutor; import net.mikaboshi.jdbc.ResultDataFormatter; import net.mikaboshi.jdbc.ResultSetHandler; import net.mikaboshi.jdbc.SimpleFormatter; import org.apache.commons.lang.StringUtils; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.taskdefs.JDBCTask; /** * <p> * SQLで与えられたクエリ結果をファイルに出力するAntタスク抽象クラス。 * </p><p> * このクラスは同期化されない。 * </p> * @author Takuma Umezawa */ public abstract class Sql2FileTask extends JDBCTask { private final M17NTaskLogger logger; /** * 本タスクのプロパティをデフォルトに設定する。 */ public Sql2FileTask() { super(); this.logger = new M17NTaskLogger( this, AntConstants.LOG_MESSAGE_BASE_NAME); } private File outputFile; /** * 出力するファイルのパスを設定する。(必須) * @param path */ public void setOutput(String path) { this.outputFile = new File(path); if (this.outputFile.isDirectory()) { this.logger.throwBuildException( "error.must_be_file", "output"); } } /** * 出力するファイルのパスを取得する。 * @return */ protected File getOutputFile() { return this.outputFile; } private String sql; /** * 実行するSELECT SQL文を設定する。(必須) * 1ステートメントのみ指定できる(全体を1ステートメントと解釈して実行する)。 * 末尾の「;」はあってもなくてもよい。 * @param text */ public void addText(String text) { if (text == null) { return; } this.sql = StringUtils.chomp(text.trim(), ";"); } /** * 実行するSELECT SQL文を取得する。 * @return */ protected String getSql() { return this.sql; } private boolean header = true; /** * ファイルにカラム名を出力するかどうかを設定する。 * 省略可。(デフォルトはtrue:出力する) * カラム名を出力する場合、SELECT文に指定された列名が使われる。 * * @param header */ public void setHeader(boolean header) { this.header = header; } /** * ファイルにカラム名を出力するかどうかを取得する。 * @return */ protected boolean isHeaderNeeded() { return this.header; } private String nullString = StringUtils.EMPTY; /** * nullの場合の出力文字を設定する。 * 省略時は、空文字が出力される。 * * @param nullString */ public void setNullString(String nullString) { this.nullString = nullString; } /** * nullの場合の出力文字を取得する。 * @return */ protected String getNullString() { return this.nullString; } private String charset; /** * 出力ファイルの文字セットを設定する。 * 省略時は、システムデフォルトが適用される。 */ public void setCharset(String charset) { this.charset = charset; } /** * 出力ファイルの文字セットを取得する。 * @return */ protected String getCharset() { if (this.charset == null) { this.charset = Charset.defaultCharset().name(); } return this.charset; } /** * ResultSetの文字列表現を行うオブジェクトを取得する。 * @return */ protected ResultDataFormatter getFormatter() { SimpleFormatter formatter = new SimpleFormatter(); if (getNullString() != null) { formatter.setNullString(getNullString()); } return formatter; } /* (非 Javadoc) * @see org.apache.tools.ant.Task#execute() */ @Override public void execute() throws BuildException { validateNotNull(getOutputFile(), "output", BuildException.class); validateNotBlank(getSql(), "SQL", BuildException.class); Connection conn = null; try { conn = getConnection(); this.logger.info("file.output", getOutputFile().getAbsolutePath()); new QueryExecutor(conn, createHandler()).execute(getSql()); } catch (IOException e) { throw new BuildException(e); } catch (SQLException e) { throw new BuildException(e); } finally { DbUtils.closeQuietly(conn); } } /** * ResultSetをファイルに書き出すHandlerインスタンスを生成する。 * * @return * @throws IOException */ protected abstract ResultSetHandler createHandler() throws IOException; }
cwan/mikaboshi-java-utils
mikaboshi-java-utils-project/src/main/java/net/mikaboshi/ant/Sql2FileTask.java
Java
apache-2.0
4,944
/* * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights * Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.codedeploy.model.transform; import java.util.Map; import java.util.Map.Entry; import com.amazonaws.services.codedeploy.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * DeleteDeploymentGroupResult JSON Unmarshaller */ public class DeleteDeploymentGroupResultJsonUnmarshaller implements Unmarshaller<DeleteDeploymentGroupResult, JsonUnmarshallerContext> { public DeleteDeploymentGroupResult unmarshall( JsonUnmarshallerContext context) throws Exception { DeleteDeploymentGroupResult deleteDeploymentGroupResult = new DeleteDeploymentGroupResult(); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) return null; while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("hooksNotCleanedUp", targetDepth)) { context.nextToken(); deleteDeploymentGroupResult .setHooksNotCleanedUp(new ListUnmarshaller<AutoScalingGroup>( AutoScalingGroupJsonUnmarshaller .getInstance()).unmarshall(context)); } } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals( currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return deleteDeploymentGroupResult; } private static DeleteDeploymentGroupResultJsonUnmarshaller instance; public static DeleteDeploymentGroupResultJsonUnmarshaller getInstance() { if (instance == null) instance = new DeleteDeploymentGroupResultJsonUnmarshaller(); return instance; } }
dump247/aws-sdk-java
aws-java-sdk-codedeploy/src/main/java/com/amazonaws/services/codedeploy/model/transform/DeleteDeploymentGroupResultJsonUnmarshaller.java
Java
apache-2.0
3,076
/* * Copyright 2013-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 * * 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.cloud.netflix.zuul.util; import java.io.IOException; import java.nio.charset.Charset; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.stream.Collectors; import javax.servlet.http.HttpServletRequest; import org.springframework.core.io.InputStreamResource; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import org.springframework.web.util.UriComponentsBuilder; import static java.util.Arrays.stream; import static java.util.Collections.emptyMap; import static org.springframework.util.StringUtils.isEmpty; import static org.springframework.util.StringUtils.tokenizeToStringArray; import static org.springframework.util.StringUtils.uriDecode; /** * Utility class providing methods for extracting {@link HttpServletRequest} content as a * {@link MultiValueMap}. * * @author Eloi Poch * @author Spencer Gibb * @author Dmitrii Priporov * @author Ryan Baxter */ public final class RequestContentDataExtractor { private RequestContentDataExtractor() { throw new AssertionError("Must not instantiate utility class."); } public static MultiValueMap<String, Object> extract(HttpServletRequest request) throws IOException { return (request instanceof MultipartHttpServletRequest) ? extractFromMultipartRequest((MultipartHttpServletRequest) request) : extractFromRequest(request); } private static MultiValueMap<String, Object> extractFromRequest( HttpServletRequest request) throws IOException { MultiValueMap<String, Object> builder = new LinkedMultiValueMap<>(); Set<String> queryParams = findQueryParams(request); for (Entry<String, String[]> entry : request.getParameterMap().entrySet()) { String key = entry.getKey(); if (!queryParams.contains(key) && entry.getValue() != null) { for (String value : entry.getValue()) { builder.add(key, value); } } } return builder; } private static MultiValueMap<String, Object> extractFromMultipartRequest( MultipartHttpServletRequest request) throws IOException { MultiValueMap<String, Object> builder = new LinkedMultiValueMap<>(); Map<String, List<String>> queryParamsGroupedByName = findQueryParamsGroupedByName( request); Set<String> queryParams = findQueryParams(request); for (Entry<String, String[]> entry : request.getParameterMap().entrySet()) { String key = entry.getKey(); List<String> listOfAllParams = stream(request.getParameterMap().get(key)) .collect(Collectors.toList()); List<String> listOfOnlyQueryParams = queryParamsGroupedByName.get(key); if (listOfOnlyQueryParams != null) { listOfOnlyQueryParams = listOfOnlyQueryParams.stream() .map(param -> uriDecode(param, Charset.defaultCharset())) .collect(Collectors.toList()); if (!listOfOnlyQueryParams.containsAll(listOfAllParams)) { listOfAllParams.removeAll(listOfOnlyQueryParams); for (String value : listOfAllParams) { builder.add(key, new HttpEntity<>(value, newHttpHeaders(request, key))); } } } if (!queryParams.contains(key)) { for (String value : entry.getValue()) { builder.add(key, new HttpEntity<>(value, newHttpHeaders(request, key))); } } } for (Entry<String, List<MultipartFile>> parts : request.getMultiFileMap() .entrySet()) { for (MultipartFile file : parts.getValue()) { HttpHeaders headers = new HttpHeaders(); headers.setContentDispositionFormData(file.getName(), file.getOriginalFilename()); if (file.getContentType() != null) { headers.setContentType(MediaType.valueOf(file.getContentType())); } HttpEntity entity = new HttpEntity<>( new InputStreamResource(file.getInputStream()), headers); builder.add(parts.getKey(), entity); } } return builder; } private static HttpHeaders newHttpHeaders(MultipartHttpServletRequest request, String key) { HttpHeaders headers = new HttpHeaders(); String type = request.getMultipartContentType(key); if (type != null) { headers.setContentType(MediaType.valueOf(type)); } return headers; } private static Set<String> findQueryParams(HttpServletRequest request) { Set<String> result = new HashSet<>(); String query = request.getQueryString(); if (query != null) { for (String value : tokenizeToStringArray(query, "&")) { if (value.contains("=")) { value = value.substring(0, value.indexOf("=")); } result.add(value); } } return result; } static Map<String, List<String>> findQueryParamsGroupedByName( HttpServletRequest request) { String query = request.getQueryString(); if (isEmpty(query)) { return emptyMap(); } return UriComponentsBuilder.fromUriString("?" + query).build().getQueryParams(); } }
joshiste/spring-cloud-netflix
spring-cloud-netflix-zuul/src/main/java/org/springframework/cloud/netflix/zuul/util/RequestContentDataExtractor.java
Java
apache-2.0
5,740
package org.gradle.test.performance.mediummonolithicjavaproject.p290; import org.junit.Test; import static org.junit.Assert.*; public class Test5803 { Production5803 objectUnderTest = new Production5803(); @Test public void testProperty0() { String value = "value"; objectUnderTest.setProperty0(value); assertEquals(value, objectUnderTest.getProperty0()); } @Test public void testProperty1() { String value = "value"; objectUnderTest.setProperty1(value); assertEquals(value, objectUnderTest.getProperty1()); } @Test public void testProperty2() { String value = "value"; objectUnderTest.setProperty2(value); assertEquals(value, objectUnderTest.getProperty2()); } @Test public void testProperty3() { String value = "value"; objectUnderTest.setProperty3(value); assertEquals(value, objectUnderTest.getProperty3()); } @Test public void testProperty4() { String value = "value"; objectUnderTest.setProperty4(value); assertEquals(value, objectUnderTest.getProperty4()); } @Test public void testProperty5() { String value = "value"; objectUnderTest.setProperty5(value); assertEquals(value, objectUnderTest.getProperty5()); } @Test public void testProperty6() { String value = "value"; objectUnderTest.setProperty6(value); assertEquals(value, objectUnderTest.getProperty6()); } @Test public void testProperty7() { String value = "value"; objectUnderTest.setProperty7(value); assertEquals(value, objectUnderTest.getProperty7()); } @Test public void testProperty8() { String value = "value"; objectUnderTest.setProperty8(value); assertEquals(value, objectUnderTest.getProperty8()); } @Test public void testProperty9() { String value = "value"; objectUnderTest.setProperty9(value); assertEquals(value, objectUnderTest.getProperty9()); } }
oehme/analysing-gradle-performance
my-app/src/test/java/org/gradle/test/performance/mediummonolithicjavaproject/p290/Test5803.java
Java
apache-2.0
2,111
package com.psc.vote.controller; import com.psc.vote.common.util.VoteUtil; import com.psc.vote.vote.domain.Anchor; import com.psc.vote.vote.domain.Campaign; import com.psc.vote.vote.domain.CampaignOption; import com.psc.vote.vote.domain.Reward; import com.psc.vote.vote.service.VoteService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; @Controller public class CampaignController { @Autowired VoteService voteService; static SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd"); public static void main(String[] args) throws Exception { /*SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date campaignEndDate = dateFormat.parse("2015-08-10 14:58:00"); long endDate = campaignEndDate.getTime(); long sysDate = new Date().getTime(); System.out.println("End Date:" + endDate); System.out.println("Current Date:" + sysDate); long diffMilliSeconds = endDate - sysDate; System.out.println("diffMilliSeconds:" + diffMilliSeconds); System.out.println("Seconds:" + diffMilliSeconds/1000); System.out.println("Minutes:" + diffMilliSeconds/(1000*60)); System.out.println("Hours:" + diffMilliSeconds/(1000*60*60)); System.out.println("Days:" + diffMilliSeconds/(1000*60*60*24));*/ //System.out.println("Password:" + ("testpassword").substring(0, 6)); Campaign c = new Campaign(); c.setStartDate(sdf2.parse("2015-08-01")); c.setEndDate(sdf2.parse("2015-08-30")); Campaign campaign = new Campaign(); campaign.setStartDate(sdf2.parse("2015-07-01")); campaign.setEndDate(sdf2.parse("2015-08-15")); System.out.println("Existing Campaign:" + c.toString()); System.out.println("New Campaign:" + campaign.toString()); System.out.println("Value1:" + campaign.getStartDate().after(c.getStartDate())); System.out.println("Value1:" + ((campaign.getStartDate().compareTo(c.getStartDate()) ==0) ||campaign.getStartDate().after(c.getStartDate()))); System.out.println("Value2:" + campaign.getStartDate().before(c.getEndDate())); System.out.println("Value2:" + ((campaign.getStartDate().compareTo(c.getEndDate()) ==0) || campaign.getStartDate().before(c.getEndDate()))); System.out.println("Value3:" + campaign.getEndDate().after(c.getStartDate())); System.out.println("Value4:" + campaign.getEndDate().before(c.getEndDate())); boolean validCampaign = !(((campaign.getStartDate().compareTo(c.getStartDate()) ==0) ||campaign.getStartDate().after(c.getStartDate())) && ((campaign.getStartDate().compareTo(c.getEndDate()) ==0) || campaign.getStartDate().before(c.getEndDate()))); if (validCampaign) { validCampaign = !(((campaign.getEndDate().compareTo(c.getStartDate()) ==0) || campaign.getEndDate().after(c.getStartDate())) && ((campaign.getEndDate().compareTo(c.getEndDate())==0) || campaign.getEndDate().before(c.getEndDate()))); } System.out.println("validCampaign:" + validCampaign); } @RequestMapping("/createReward") @ResponseBody public String createReward(HttpServletRequest request, HttpServletResponse response) { System.out.println("in createReward"); Reward reward = new Reward(); reward.setCampaignId(request.getParameter("campaignId")); reward.setDescription(request.getParameter("rewardDescription")); reward.setImageURL(request.getParameter("imageURL")); reward.setPushRegion(request.getParameter("pushRegion")); reward.setPushLimit(request.getParameter("pushLimit")); reward.setPushFilter(request.getParameter("pushFilter")); try { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); reward.setStartDate(sdf.parse(request.getParameter("startDate"))); reward.setEndDate(sdf.parse(request.getParameter("endDate"))); voteService.createReward(reward); voteService.pushReward(reward); return "success"; } catch (Exception e) { return "fail"; } } @RequestMapping("/getCampaignFromAnchor") @ResponseBody public String getCampaignFromAnchor(HttpServletRequest request, HttpServletResponse response) { System.out.println("in getCampaignFromAnchor"); String clientId = request.getParameter("clientId"); String anchorId = request.getParameter("anchorName"); System.out.println("Client:" + clientId); System.out.println("Anchor:" + anchorId); Anchor anchor = new Anchor(); anchor.setAnchorName(anchorId); anchor.setClientId(clientId); try { System.out.println("Anchor:" + anchor); List<Campaign> campaigns = voteService.getCampaignsByAnchor(anchor); System.out.println("campaigns:" + campaigns); return VoteUtil.toJSONCampaigns(campaigns); } catch (Exception e) { return "fail"; } } @RequestMapping("/createCampaign") @ResponseBody public String createCampaign(HttpServletRequest request, HttpServletResponse response) { System.out.println("in createCampaign"); String anchorId = request.getParameter("anchorId"); String question = request.getParameter("question"); String startDate = request.getParameter("startDate"); String endDate = request.getParameter("endDate"); String region = request.getParameter("region"); String rewardInfo = request.getParameter("rewardInfo"); String option1 = request.getParameter("optionValue1"); String option2 = request.getParameter("optionValue2"); String option3 = request.getParameter("optionValue3"); String option4 = request.getParameter("optionValue4"); String option5 = request.getParameter("optionValue5"); System.out.println("anchorId:" + anchorId); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); String campaignId = ((anchorId.length() >= 16) ? anchorId.substring(0, 16) : anchorId) + sdf.format(new Date()); System.out.println("campaignId:" + campaignId); try { Campaign campaign = new Campaign(); campaign.setCampaignId(campaignId); campaign.setAnchorId(anchorId); campaign.setQuestion(question); campaign.setStartDate(sdf2.parse(startDate)); campaign.setEndDate(sdf2.parse(endDate)); campaign.setRegionCountry(region); campaign.setRewardInfo(rewardInfo); System.out.println("campaign:" + campaign.toString()); List<CampaignOption> options = new ArrayList<CampaignOption>(); if (!StringUtils.isEmpty(option1)) { options.add(new CampaignOption(option1)); } if (!StringUtils.isEmpty(option2)) { options.add(new CampaignOption(option2)); } if (!StringUtils.isEmpty(option3)) { options.add(new CampaignOption(option3)); } if (!StringUtils.isEmpty(option4)) { options.add(new CampaignOption(option4)); } if (!StringUtils.isEmpty(option5)) { options.add(new CampaignOption(option5)); } campaign.setOptions(options); System.out.println("campaign (after options):" + campaign.toString()); voteService.createCampaign(campaign); return "success"; } catch (Exception e) { return "fail:" + e.getMessage(); } } @RequestMapping("/updateCampaignStatus") @ResponseBody public String updateCampaignStatus(HttpServletRequest request, HttpServletResponse response) { System.out.println("in updateCampaignStatus"); String campaignId = request.getParameter("campaignId"); String status = request.getParameter("status"); System.out.println("campaignId:" + campaignId); System.out.println("status:" + status); try { voteService.updateCampaignStatus(campaignId, status); return "success"; } catch (Exception e) { return "fail"; } } @RequestMapping("/modifyCampaign") @ResponseBody public String modifyCampaign(HttpServletRequest request, HttpServletResponse response) { System.out.println("in modifyCampaign"); try { Campaign campaign = new Campaign(); campaign.setCampaignId(request.getParameter("campaignId")); campaign.setStartDate(sdf2.parse(request.getParameter("startDate"))); campaign.setEndDate(sdf2.parse(request.getParameter("endDate"))); campaign.setRegionCountry(request.getParameter("region")); campaign.setRewardInfo(request.getParameter("rewardInfo")); System.out.println("campaign:" + campaign); voteService.modifyCampaign(campaign); return "success"; } catch (Exception e) { return "fail"; } } }
sgudupat/psc-vote-server
src/main/java/com/psc/vote/controller/CampaignController.java
Java
apache-2.0
9,621
/* * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights * Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.datapipeline.model.transform; import static com.amazonaws.util.StringUtils.UTF8; import static com.amazonaws.util.StringUtils.COMMA_SEPARATOR; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.OutputStreamWriter; import java.io.StringWriter; import java.io.Writer; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.List; import java.util.regex.Pattern; import com.amazonaws.AmazonClientException; import com.amazonaws.Request; import com.amazonaws.DefaultRequest; import com.amazonaws.http.HttpMethodName; import com.amazonaws.services.datapipeline.model.*; import com.amazonaws.transform.Marshaller; import com.amazonaws.util.BinaryUtils; import com.amazonaws.util.StringUtils; import com.amazonaws.util.IdempotentUtils; import com.amazonaws.util.StringInputStream; import com.amazonaws.util.json.*; /** * DescribePipelinesRequest Marshaller */ public class DescribePipelinesRequestMarshaller implements Marshaller<Request<DescribePipelinesRequest>, DescribePipelinesRequest> { public Request<DescribePipelinesRequest> marshall( DescribePipelinesRequest describePipelinesRequest) { if (describePipelinesRequest == null) { throw new AmazonClientException( "Invalid argument passed to marshall(...)"); } Request<DescribePipelinesRequest> request = new DefaultRequest<DescribePipelinesRequest>( describePipelinesRequest, "DataPipeline"); request.addHeader("X-Amz-Target", "DataPipeline.DescribePipelines"); request.setHttpMethod(HttpMethodName.POST); request.setResourcePath(""); try { final SdkJsonGenerator jsonGenerator = new SdkJsonGenerator(); jsonGenerator.writeStartObject(); com.amazonaws.internal.SdkInternalList<String> pipelineIdsList = (com.amazonaws.internal.SdkInternalList<String>) describePipelinesRequest .getPipelineIds(); if (!pipelineIdsList.isEmpty() || !pipelineIdsList.isAutoConstruct()) { jsonGenerator.writeFieldName("pipelineIds"); jsonGenerator.writeStartArray(); for (String pipelineIdsListValue : pipelineIdsList) { if (pipelineIdsListValue != null) { jsonGenerator.writeValue(pipelineIdsListValue); } } jsonGenerator.writeEndArray(); } jsonGenerator.writeEndObject(); byte[] content = jsonGenerator.getBytes(); request.setContent(new ByteArrayInputStream(content)); request.addHeader("Content-Length", Integer.toString(content.length)); request.addHeader("Content-Type", "application/x-amz-json-1.1"); } catch (Throwable t) { throw new AmazonClientException( "Unable to marshall request to JSON: " + t.getMessage(), t); } return request; } }
dump247/aws-sdk-java
aws-java-sdk-datapipeline/src/main/java/com/amazonaws/services/datapipeline/model/transform/DescribePipelinesRequestMarshaller.java
Java
apache-2.0
3,704
/******************************************************************************** * Copyright (c) 2011-2017 Red Hat Inc. and/or its affiliates and others * * This program and the accompanying materials are made available under the * terms of the Apache License, Version 2.0 which is available at * http://www.apache.org/licenses/LICENSE-2.0 * * SPDX-License-Identifier: Apache-2.0 ********************************************************************************/ package org.eclipse.ceylon.compiler.java.language; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.eclipse.ceylon.compiler.java.metadata.Ceylon; import org.eclipse.ceylon.compiler.java.metadata.Class; @Ceylon(major = 8) @Class @Retention(RetentionPolicy.SOURCE) @Target({ElementType.METHOD,ElementType.PARAMETER}) public @interface Synchronized$annotation$ { }
ceylon/ceylon
language/runtime/org/eclipse/ceylon/compiler/java/language/Synchronized$annotation$.java
Java
apache-2.0
960
/* * * Copyright 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 springfox.documentation.spi.service; import springfox.documentation.RequestHandler; import java.util.List; public interface RequestHandlerProvider { List<RequestHandler> requestHandlers(); }
wjc133/springfox
springfox-spi/src/main/java/springfox/documentation/spi/service/RequestHandlerProvider.java
Java
apache-2.0
843
package org.hillview.main; import org.hillview.dataset.LocalDataSet; import org.hillview.dataset.api.Empty; import org.hillview.dataset.api.IDataSet; import org.hillview.dataset.api.IMap; import org.hillview.maps.ExtractValueFromKeyMap; import org.hillview.maps.FindFilesMap; import org.hillview.maps.LoadFilesMap; import org.hillview.maps.ProjectMap; import org.hillview.sketches.*; import org.hillview.sketches.results.*; import org.hillview.storage.FileSetDescription; import org.hillview.storage.IFileReference; import org.hillview.table.ColumnDescription; import org.hillview.table.Schema; import org.hillview.table.api.ContentsKind; import org.hillview.table.api.ITable; import org.hillview.utils.Converters; import org.hillview.utils.JsonList; import java.io.*; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.time.Instant; import java.util.ArrayList; import java.util.List; import org.apache.commons.cli.*; import javax.annotation.Nullable; /** * This class is used for generating Timestamp-errorCode heatmaps data files from syslogs of bugs. * The inputs are syslog files of format RFC5424. Rows in syslog files have a field called "errorCode" in the "StructuredData" column. * This script only extracts syslog files from nsx_manager and nsx_edge bundles separately. * It extracts value of "errorCode" from "StructuredData" as a new column, to generate heatmaps of "Timestamp" vs. "errorCode". * Each bucket in the heatmap is the count of occurrence of some errorCode in some timestamp interval among syslogs. * The default number of total timestamp intervals for each bug (each heatmap) is 50. * The heatmap data for each bug is saved as a CSV file of columns "Timestamp", "errorCode" and "Count", where each row represents one bucket in the heatmap. */ public class BatchLogAnalysis { private static class HeatmapData { @Nullable long[][] matrix; JsonList<String> errorCodeLabels = new JsonList<>(); final ArrayList<String> timeLabels = new ArrayList<>(); } /** * This method generates the HeatmapData of "Timestamp" vs. "errorCode" for a given set of syslogs. * @param desc description of files of RFC5424 log format and specific file names (paths) pattern * @param numOfTimestampBuckets number of timestamp (x-axis) intervals for each heatmap * @return heatmapData including count in each bucket in the heatmap, y-tick-labels errorCodeLabels, and x-tick-labels timeLabels. */ private static HeatmapData heatmapErrTime(FileSetDescription desc, int numOfTimestampBuckets) { /* Load data through file desc */ Empty e = Empty.getInstance(); LocalDataSet<Empty> local = new LocalDataSet<Empty>(e); IMap<Empty, List<IFileReference>> finder = new FindFilesMap<>(desc); IDataSet<IFileReference> found = local.blockingFlatMap(finder); IMap<IFileReference, ITable> loader = new LoadFilesMap(); IDataSet<ITable> table = found.blockingMap(loader); /* Restrict table columns of Schema "Timestamp" and "StructuredData" */ Schema project = new Schema(); project.append(new ColumnDescription("Timestamp", ContentsKind.Date)); project.append(new ColumnDescription("StructuredData", ContentsKind.String)); ProjectMap projectMap = new ProjectMap(project); table = table.blockingMap(projectMap); /* Extract "errorCode" from "StructuredData" as a new column */ ExtractValueFromKeyMap.Info info = new ExtractValueFromKeyMap.Info( "errorCode", new ColumnDescription("StructuredData", ContentsKind.String), "errorCode", -1); ExtractValueFromKeyMap evkm = new ExtractValueFromKeyMap(info); IDataSet<ITable> table1 = table.blockingMap(evkm); /* Find Timestamp (x-axis) buckets for the heatmap */ DoubleDataRangeSketch rangeSketch = new DoubleDataRangeSketch("Timestamp"); DataRange dataRange = table1.blockingSketch(rangeSketch); assert dataRange != null; DoubleHistogramBuckets bucketsTimestamp = new DoubleHistogramBuckets("Timestamp", dataRange.min, dataRange.max, numOfTimestampBuckets); /* Find errorCode (y-axis) buckets for the heatmap */ SampleDistinctElementsSketch sampleSketch = new SampleDistinctElementsSketch("errorCode", 0, 500); MinKSet<String> samples = table1.blockingSketch(sampleSketch); assert samples != null; JsonList<String> leftBoundaries = samples.getLeftBoundaries(500); StringHistogramBuckets bucketsErrorCode = new StringHistogramBuckets("errorCode", leftBoundaries.toArray(new String[0])); /* Generate heatmap based on Timestamp buckets and errorCode buckets, and get the count in each bucket */ Histogram2DSketch sk = new Histogram2DSketch(bucketsTimestamp, bucketsErrorCode); Groups<Groups<Count>> heatmap = table1.blockingSketch(sk); assert heatmap != null; HeatmapData heatmapData = new HeatmapData(); int numOfBucketsD1 = heatmap.size(); int numOfBucketsD2 = heatmap.perBucket.get(0).size(); heatmapData.matrix = new long[numOfBucketsD1][numOfBucketsD2]; for (int i = 0; i < numOfBucketsD1; i++){ for (int j = 0; j < numOfBucketsD2; j++){ heatmapData.matrix[i][j] = heatmap.getBucket(i).getBucket(j).count; } } /* Get y-tick-labels errorCodeLabels and x-tick-labels timeLabels */ heatmapData.errorCodeLabels = leftBoundaries; for (int x = 0; x < numOfTimestampBuckets; x++) { // save the start time only of each bucket double time = dataRange.min + x * (dataRange.max - dataRange.min) / numOfTimestampBuckets; Instant instantTime = Converters.toDate(time); String stringDate = Converters.toString(instantTime); heatmapData.timeLabels.add(stringDate); } return heatmapData; } /** * This method saves the heatmapData as a CSV file. * The file has columns "Timestamp", "errorCode" and "Count", where each row represents one bucket in the heatmap. * @param heatmapData includes count in each bucket, y-tick-labels errorCodeLabels and x-tick-labels timeLabels * @param filepath destination CSV file path */ private static void saveHeatmapToFile(HeatmapData heatmapData, String filepath) { if (!heatmapData.errorCodeLabels.contains(null)) { System.out.println(heatmapData.errorCodeLabels); try (PrintWriter writer = new PrintWriter(new File(filepath))) { StringBuilder sb = new StringBuilder(); sb.append("Timestamp"); sb.append(','); sb.append("errorCode"); sb.append(','); sb.append("Count"); sb.append('\n'); for (int x = 0; x < Converters.checkNull(heatmapData.matrix).length; x++) { for (int y = 0; y < heatmapData.matrix[0].length; y++) { if (heatmapData.matrix[x][y] >= 0) { // keep zeros or not sb.append(heatmapData.timeLabels.get(x)); sb.append(','); sb.append(heatmapData.errorCodeLabels.get(y).replaceAll(",", "")); sb.append(','); sb.append(heatmapData.matrix[x][y]); sb.append('\n'); } } } writer.write(sb.toString()); } catch (FileNotFoundException e) { System.out.println(e.getMessage()); System.exit(1); } } } /** * This method generates and saves heatmapData to CSV files given input syslogs. * @param logDir source directory of syslogs for all bugs * @param figDir destination directory to save the CSV files for all bugs * @param numOfTimestampBuckets number of timestamp (x-axis) intervals for each heatmap */ @SuppressWarnings("StringConcatenationInLoop") private static void getBugHeatmaps(String logDir, String figDir, int numOfTimestampBuckets) { File path = new File(logDir); // each subDir in logDir corresponds to one bug String[] bugIDs = path.list( (current, name) -> new File(current, name).isDirectory()); // create empty directory for nsx_manager and nsx_edge respectively boolean ignored = new File(figDir + "/nsx_manager_syslog/").mkdirs(); ignored = new File(figDir + "/nsx_edge_syslog/").mkdirs(); assert(ignored); assert bugIDs != null; for (String bugID : bugIDs) { File bugFolder = new File(logDir + "/" + bugID); String[] subFolders = bugFolder.list( (current, name) -> new File(current, name).isDirectory()); assert subFolders != null; if (subFolders.length != 0) { // exists syslogs for that bug FileSetDescription descManager = new FileSetDescription(); descManager.fileKind = "genericlog"; descManager.logFormat = "%{RFC5424}"; descManager.headerRow = false; descManager.fileNamePattern = ""; FileSetDescription descEdge = new FileSetDescription(); descEdge.fileKind = "genericlog"; descEdge.logFormat = "%{RFC5424}"; descEdge.headerRow = false; descEdge.fileNamePattern = ""; for (String subFolder : subFolders) { if (subFolder.startsWith("nsx_manager")) { descManager.fileNamePattern += logDir + "/" + bugID + "/" + subFolder + "/var/log/syslog*,"; // adding a comma at the end doesn't matter } else if (subFolder.startsWith("nsx_edge")) { descEdge.fileNamePattern += logDir + "/" + bugID + "/" + subFolder + "/var/log/syslog*,"; // adding a comma at the end doesn't matter } } if (descManager.fileNamePattern.length() != 0) { String filePathStr = figDir + "/nsx_manager_syslog/" + "Bug" + bugID + ".csv"; Path filePath = Paths.get(filePathStr); if (Files.notExists(filePath)) { // call the two step methods to get heatmap data // System.out.println("start " + descManager.fileNamePattern); HeatmapData heatmapData = heatmapErrTime(descManager, numOfTimestampBuckets); saveHeatmapToFile(heatmapData, filePathStr); // System.out.println("finish " + descManager.fileNamePattern); } } if (descEdge.fileNamePattern.length() != 0) { String filePathStr = figDir + "/nsx_edge_syslog/" + "Bug" + bugID + ".csv"; Path filePath = Paths.get(filePathStr); if (Files.notExists(filePath)) { // call the two step methods to get heatmap data // System.out.println("start " + descEdge.fileNamePattern); HeatmapData heatmapData = heatmapErrTime(descEdge, numOfTimestampBuckets); saveHeatmapToFile(heatmapData, filePathStr); // System.out.println("finish " + descEdge.fileNamePattern); } } } } } public static void main(String[] args) { /* Arguments parser for two arguments: logDir and figDir */ Options options = new Options(); options.addOption("help",false,"java BatchLogAnalysis [-l] logDir [-f] figDir"); Option l = Option.builder().argName( "logDir" ) .required() .hasArg() .desc("directory of syslog") .argName("l") .build(); options.addOption(l); Option f = Option.builder().argName( "figDir" ) .required() .hasArg() .desc("directory to store the figures") .argName("f") .build(); options.addOption(f); String logDir = ""; String figDir = ""; if (args.length > 0) { try { CommandLineParser parser = new DefaultParser(); CommandLine cmd = parser.parse(options,args); if(cmd.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp( "java BatchLogAnalysis [-l] logDir [-f] figDir", options); return; } if(cmd.hasOption("l")) { logDir = cmd.getOptionValue("l"); } if(cmd.hasOption("f")) { figDir = cmd.getOptionValue("f"); } getBugHeatmaps(logDir, figDir, 50); // default number of timestamp buckets is 50 } catch (ParseException err) { System.err.println("java BatchLogAnalysis [-l] logDir [-f] figDir"); System.exit(1); } } else { System.out.println("Please input arguments: java BatchLogAnalysis [-l] logDir [-f] figDir"); System.exit(1); } } }
mbudiu-vmw/hiero
platform/src/main/java/org/hillview/main/BatchLogAnalysis.java
Java
apache-2.0
13,527
package de.omnikryptec.core; import java.nio.FloatBuffer; import org.lwjgl.BufferUtils; import org.lwjgl.opencl.CL10; import de.omnikryptec.libapi.exposed.LibAPIManager; import de.omnikryptec.libapi.exposed.LibAPIManager.LibSetting; import de.omnikryptec.libapi.opencl.CLCommandQueue; import de.omnikryptec.libapi.opencl.CLContext; import de.omnikryptec.libapi.opencl.CLDevice; import de.omnikryptec.libapi.opencl.CLKernel; import de.omnikryptec.libapi.opencl.CLMemory; import de.omnikryptec.libapi.opencl.CLPlatform; import de.omnikryptec.libapi.opencl.CLProgram; import de.omnikryptec.libapi.opencl.DeviceType; import de.omnikryptec.libapi.opencl.OpenCL; import de.omnikryptec.util.settings.Settings; public class CLTest { private static final String KERNEL = "__kernel void sum(__global const float *a, __global const float *b, __global float *result, int const size) {\r\n" + " const int itemId = get_global_id(0); \r\n" + " if(itemId < size) {\r\n" + " result[itemId] = a[itemId] + b[itemId];\r\n" + " }\r\n" + "} "; private static final int size = 10; public static void main(final String[] args) { //Create stuff final Settings<LibSetting> s = new Settings<>(); s.set(LibSetting.DEBUG, true); s.set(LibSetting.DEBUG_LIBRARY_LOADING, true); LibAPIManager.init(s); LibAPIManager.instance().initOpenCL(); final OpenCL opc = LibAPIManager.instance().getOpenCL(); final CLPlatform platform = opc.getPlatform(0); final CLDevice device = platform.createDeviceData(DeviceType.GPU).getDevice(0); final CLContext context = new CLContext(device); final CLCommandQueue queue = new CLCommandQueue(context, device, CL10.CL_QUEUE_PROFILING_ENABLE); final CLProgram program = new CLProgram(context, KERNEL).build(device, 1024, ""); final CLKernel kernel = new CLKernel(program, "sum"); final FloatBuffer aBuff = BufferUtils.createFloatBuffer(size); final FloatBuffer bBuff = BufferUtils.createFloatBuffer(size); final CLMemory aMem = new CLMemory(context, CL10.CL_MEM_READ_ONLY | CL10.CL_MEM_COPY_HOST_PTR, aBuff); final CLMemory bMem = new CLMemory(context, CL10.CL_MEM_READ_ONLY | CL10.CL_MEM_COPY_HOST_PTR, bBuff); final CLMemory resultMem = new CLMemory(context, CL10.CL_MEM_WRITE_ONLY, 4 * size); //Fill read buffers final float[] aArray = new float[size]; for (int i = 0; i < size; i++) { aArray[i] = i; } aBuff.put(aArray); aBuff.rewind(); final float[] bArray = new float[size]; for (int j = 0, i = size - 1; j < size; j++, i--) { bArray[j] = i; } bBuff.put(bArray); bBuff.rewind(); //write buffers aMem.enqueueWriteBuffer(queue, aBuff); bMem.enqueueWriteBuffer(queue, bBuff); queue.finish(); //enqueue kernel kernel.setArg(3, size); kernel.setArg(0, aMem); kernel.setArg(1, bMem); kernel.setArg(2, resultMem); kernel.enqueue(queue, 1, size, 0); //cope with result final FloatBuffer result = BufferUtils.createFloatBuffer(size); resultMem.enqueueReadBuffer(queue, result); queue.finish(); for (int i = 0; i < size; i++) { System.out.print(result.get(i) + " "); if ((i + 1) % 100 == 0) { System.out.println(); } } System.out.println(); } }
OmniKryptec/OmniKryptec-Engine
src/test/java/de/omnikryptec/core/CLTest.java
Java
apache-2.0
3,545
/** * Copyright 2012 Neovera Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.neovera.jdiablo.internal; import org.neovera.jdiablo.ExecutionState; import org.neovera.jdiablo.annotation.Option; public class LevelTwoALaunchable extends LevelOneLaunchable { @Option(shortOption = "x", longOption="option2x", description = "Description for level 2 option x", args=1) private String _option2x; public String getOption2x() { return _option2x; } public void setOption2x(String option2x) { _option2x = option2x; } public ExecutionState mainEntryPoint() { return ExecutionState.SUCCESS; } }
neovera/jdiablo
src/test/java/org/neovera/jdiablo/internal/LevelTwoALaunchable.java
Java
apache-2.0
1,214
/** Copyright 2017 Andrea "Stock" Stocchero 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.pepstock.charba.client.impl.plugins; import org.pepstock.charba.client.IsChart; import org.pepstock.charba.client.callbacks.HtmlLegendItemCallback; import org.pepstock.charba.client.callbacks.HtmlLegendTitleCallback; import org.pepstock.charba.client.commons.AbstractBaseBuilder; import org.pepstock.charba.client.commons.IsBuilder; /** * Comfortable object to create {@link HtmlLegend#ID} plugin options by a builder. * * @author Andrea "Stock" Stocchero * */ public final class HtmlLegendOptionsBuilder extends AbstractBaseBuilder { // creates the options private final HtmlLegendOptions options; /** * To avoid any instantiation * * @param chart chart instance related to the plugin options */ private HtmlLegendOptionsBuilder(IsChart chart) { options = new HtmlLegendOptions(chart); } /** * Returns new builder instance, using the global options as default. * * @return new builder instance */ public static HtmlLegendOptionsBuilder create() { return create(null); } /** * Returns new builder instance using chart global options as default. * * @param chart chart instance related to the plugin options * @return new builder instance */ public static HtmlLegendOptionsBuilder create(IsChart chart) { return new HtmlLegendOptionsBuilder(chart); } /** * Returns a configured plugin options. * * @return a configured plugin options. */ public HtmlLegendOptions build() { // sets built status setBuilt(true); // returns options return options; } /** * Sets if the legend is shown. * * @param display if the legend is shown. * @return new builder instance */ public HtmlLegendOptionsBuilder setDisplay(boolean display) { options.setDisplay(display); return IsBuilder.checkAndGetIfValid(this); } /** * Sets the callback which can be implemented to change the text of legend for a specific item, as HTML. * * @param legendTextCallback the callback which can be implemented to change the text of legend for a specific item, as HTML * @return new builder instance */ public HtmlLegendOptionsBuilder setLegendItemCallback(HtmlLegendItemCallback legendTextCallback) { options.setLegendItemCallback(legendTextCallback); return IsBuilder.checkAndGetIfValid(this); } /** * Sets the callback which can be implemented to change the text of legend's title, as HTML. * * @param legendTitleCallback the callback which can be implemented to change the text of legend's title, as HTML * @return new builder instance */ public HtmlLegendOptionsBuilder setLegendTitleCallback(HtmlLegendTitleCallback legendTitleCallback) { options.setLegendTitleCallback(legendTitleCallback); return IsBuilder.checkAndGetIfValid(this); } /** * Sets the maximum amount of columns of legend. * * @param maxColumns the maximum amount of columns of legend * @return new builder instance */ public HtmlLegendOptionsBuilder setMaximumLegendColumns(int maxColumns) { options.setMaximumLegendColumns(maxColumns); return IsBuilder.checkAndGetIfValid(this); } }
pepstock-org/Charba
src/org/pepstock/charba/client/impl/plugins/HtmlLegendOptionsBuilder.java
Java
apache-2.0
3,812
/******************************************************************************* * Copyright 2015, The IKANOW 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.ikanow.aleph2.management_db.mongodb.services; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.EnumSet; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.function.Supplier; import java.util.Date; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.StreamSupport; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.recipes.leader.LeaderLatch; import org.apache.hadoop.fs.CreateFlag; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.FileContext; import org.apache.hadoop.fs.Path; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.bson.types.ObjectId; import scala.Tuple2; import scala.Tuple3; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.google.inject.Inject; import com.ikanow.aleph2.data_model.interfaces.data_services.IManagementDbService; import com.ikanow.aleph2.data_model.interfaces.data_services.IStorageService; import com.ikanow.aleph2.data_model.interfaces.shared_services.ICrudService; import com.ikanow.aleph2.data_model.interfaces.shared_services.ICrudService.Cursor; import com.ikanow.aleph2.data_model.interfaces.shared_services.IManagementCrudService; import com.ikanow.aleph2.data_model.interfaces.shared_services.IServiceContext; import com.ikanow.aleph2.data_model.objects.shared.AuthorizationBean; import com.ikanow.aleph2.data_model.objects.shared.BasicMessageBean; import com.ikanow.aleph2.data_model.objects.shared.SharedLibraryBean; import com.ikanow.aleph2.data_model.objects.shared.SharedLibraryBean.LibraryType; import com.ikanow.aleph2.data_model.utils.CrudUtils; import com.ikanow.aleph2.data_model.utils.CrudUtils.CommonUpdateComponent; import com.ikanow.aleph2.data_model.utils.CrudUtils.SingleQueryComponent; import com.ikanow.aleph2.data_model.utils.BeanTemplateUtils; import com.ikanow.aleph2.data_model.utils.ErrorUtils; import com.ikanow.aleph2.data_model.utils.FutureUtils.ManagementFuture; import com.ikanow.aleph2.data_model.utils.FutureUtils; import com.ikanow.aleph2.data_model.utils.Lambdas; import com.ikanow.aleph2.data_model.utils.SetOnce; import com.ikanow.aleph2.data_model.utils.Tuples; import com.ikanow.aleph2.distributed_services.services.ICoreDistributedServices; import com.ikanow.aleph2.management_db.mongodb.data_model.MongoDbManagementDbConfigBean; import com.mongodb.gridfs.GridFS; import com.mongodb.gridfs.GridFSDBFile; /** This service looks for changes to IKANOW binary shares and applies them to shared library beans * @author acp */ public class IkanowV1SyncService_LibraryJars { private static final Logger _logger = LogManager.getLogger(); protected static final ObjectMapper _mapper = BeanTemplateUtils.configureMapper(Optional.empty()); protected final MongoDbManagementDbConfigBean _config; protected final IServiceContext _context; protected final IManagementDbService _core_management_db; protected final IManagementDbService _underlying_management_db; protected final ICoreDistributedServices _core_distributed_services; protected final IStorageService _storage_service; protected SetOnce<GridFS> _mongodb_distributed_fs = new SetOnce<GridFS>(); protected final SetOnce<MutexMonitor> _library_mutex_monitor = new SetOnce<MutexMonitor>(); protected final ScheduledExecutorService _mutex_scheduler = Executors.newScheduledThreadPool(1); protected final ScheduledExecutorService _source_scheduler = Executors.newScheduledThreadPool(1); protected SetOnce<ScheduledFuture<?>> _library_monitor_handle = new SetOnce<ScheduledFuture<?>>(); protected static int _num_leader_changes = 0; // (just for debugging/testing) public final static String LIBRARY_MONITOR_MUTEX = "/app/aleph2/locks/v1/library_jars"; /** guice constructor * @param config - the management db configuration, includes whether this service is enabled * @param service_context - the service context providing all the required dependencies */ @Inject public IkanowV1SyncService_LibraryJars(final MongoDbManagementDbConfigBean config, final IServiceContext service_context) { _config = config; _context = service_context; _core_management_db = _context.getCoreManagementDbService(); _underlying_management_db = _context.getService(IManagementDbService.class, Optional.empty()).get(); _core_distributed_services = _context.getService(ICoreDistributedServices.class, Optional.empty()).get(); _storage_service = _context.getStorageService(); if (Optional.ofNullable(_config.v1_enabled()).orElse(false)) { // Launch the synchronization service // 1) Monitor sources _library_mutex_monitor.set(new MutexMonitor(LIBRARY_MONITOR_MUTEX)); _mutex_scheduler.schedule(_library_mutex_monitor.get(), 250L, TimeUnit.MILLISECONDS); _library_monitor_handle.set(_source_scheduler.scheduleWithFixedDelay(new LibraryMonitor(), 10L, 2L, TimeUnit.SECONDS)); //(give it 10 seconds before starting, let everything else settle down - eg give the bucket choose handler time to register) } } /** Immediately start (this is test code, so fine to overwrite the SetOnce) */ @SuppressWarnings("deprecation") public void start() { _library_monitor_handle.get().cancel(true); _library_monitor_handle.forceSet(_source_scheduler.scheduleWithFixedDelay(new LibraryMonitor(), 1, 1L, TimeUnit.SECONDS)); } /** Stop threads (just for testing I think) */ public void stop() { _library_monitor_handle.get().cancel(true); } //////////////////////////////////////////////////// //////////////////////////////////////////////////// // WORKER THREADS public class MutexMonitor implements Runnable { protected final String _path; protected final SetOnce<CuratorFramework> _curator = new SetOnce<CuratorFramework>(); protected final SetOnce<LeaderLatch> _leader_selector = new SetOnce<LeaderLatch>(); public MutexMonitor(final String path) { _path = path; } @Override public void run() { if (!_leader_selector.isSet()) { _curator.set(_core_distributed_services.getCuratorFramework()); try { final LeaderLatch Leader_latch = new LeaderLatch(_curator.get(), _path); Leader_latch.start(); _leader_selector.set(Leader_latch); } catch (Exception e) { _logger.error(ErrorUtils.getLongForm("{0}", e)); } _logger.info("LibraryMonitor: joined the leadership candidate cluster"); } } public boolean isLeader() { return _leader_selector.isSet() ? _leader_selector.get().hasLeadership() : false; } } public class LibraryMonitor implements Runnable { private final SetOnce<ICrudService<JsonNode>> _v1_db = new SetOnce<ICrudService<JsonNode>>(); private boolean _last_state = false; /* (non-Javadoc) * @see java.lang.Runnable#run() */ @Override public void run() { if (!_library_mutex_monitor.get().isLeader()) { _last_state = false; return; } if (!_last_state) { _logger.info("LibraryMonitor: now the leader"); _num_leader_changes++; _last_state = true; } if (!_v1_db.isSet()) { @SuppressWarnings("unchecked") final ICrudService<JsonNode> v1_config_db = _underlying_management_db.getUnderlyingPlatformDriver(ICrudService.class, Optional.of("social.share")).get(); _v1_db.set(v1_config_db); _v1_db.get().optimizeQuery(Arrays.asList("title")); } if (!_mongodb_distributed_fs.isSet()) { final GridFS fs = _underlying_management_db.getUnderlyingPlatformDriver(GridFS.class, Optional.of("file.binary_shares")).get(); _mongodb_distributed_fs.set(fs); } try { // Synchronize synchronizeLibraryJars( _core_management_db.getSharedLibraryStore(), _storage_service, _v1_db.get(), _mongodb_distributed_fs.get()) .get(); // (the get at the end just ensures that you don't get two of these scheduled results colliding - because of the 1-thread thread pool) } catch (Throwable t) { _logger.error(ErrorUtils.getLongForm("{0}", t)); } } } //////////////////////////////////////////////////// //////////////////////////////////////////////////// // CONTROL LOGIC /** Top level logic for source synchronization * @param library_mgmt * @param share_db */ protected CompletableFuture<Void> synchronizeLibraryJars( final IManagementCrudService<SharedLibraryBean> library_mgmt, final IStorageService aleph2_fs, final ICrudService<JsonNode> share_db, final GridFS share_fs ) { return compareJarsToLibaryBeans_get(library_mgmt, share_db) .thenApply(v1_v2 -> { return compareJarsToLibraryBeans_categorize(v1_v2); }) .thenCompose(create_update_delete -> { if (create_update_delete._1().isEmpty() && create_update_delete._2().isEmpty() && create_update_delete._3().isEmpty()) { //(nothing to do) return CompletableFuture.completedFuture(null); } _logger.info(ErrorUtils.get("Found [create={0}, delete={1}, update={2}] sources", create_update_delete._1().size(), create_update_delete._2().size(), create_update_delete._3().size()) ); final List<CompletableFuture<Boolean>> l1 = create_update_delete._1().stream().parallel() .<Tuple2<String, ManagementFuture<?>>>map(id -> Tuples._2T(id, createLibraryBean(id, library_mgmt, aleph2_fs, true, share_db, share_fs, _context))) .<CompletableFuture<Boolean>>map(id_fres -> updateV1ShareErrorStatus_top(id_fres._1(), id_fres._2(), library_mgmt, share_db, true)) .collect(Collectors.toList()); ; final List<CompletableFuture<Boolean>> l2 = create_update_delete._2().stream().parallel() .<Tuple2<String, ManagementFuture<?>>>map(id -> Tuples._2T(id, deleteLibraryBean(id, library_mgmt))) .<CompletableFuture<Boolean>>map(id_fres -> CompletableFuture.completedFuture(true)) .collect(Collectors.toList()); ; final List<CompletableFuture<Boolean>> l3 = create_update_delete._3().stream().parallel() .<Tuple2<String, ManagementFuture<?>>>map(id -> Tuples._2T(id, createLibraryBean(id, library_mgmt, aleph2_fs, false, share_db, share_fs, _context))) .<CompletableFuture<Boolean>>map(id_fres -> updateV1ShareErrorStatus_top(id_fres._1(), id_fres._2(), library_mgmt, share_db, false)) .collect(Collectors.toList()); ; List<CompletableFuture<?>> retval = Arrays.asList(l1, l2, l3).stream().flatMap(l -> l.stream()) .collect(Collectors.toList()); ; return CompletableFuture.allOf(retval.toArray(new CompletableFuture[0])); }); } /** Top level handler for update status based on the result * @param id * @param fres * @param disable_on_failure * @param share_db * @return */ protected CompletableFuture<Boolean> updateV1ShareErrorStatus_top(final String id, final ManagementFuture<?> fres, final IManagementCrudService<SharedLibraryBean> library_mgmt, final ICrudService<JsonNode> share_db, final boolean create_not_update) { return fres.getManagementResults() .<Boolean>thenCompose(res -> { try { fres.get(); // (check if the DB side call has failed) return updateV1ShareErrorStatus(new Date(), id, res, library_mgmt, share_db, create_not_update); } catch (Exception e) { // DB-side call has failed, create ad hoc error final Collection<BasicMessageBean> errs = res.isEmpty() ? Arrays.asList( new BasicMessageBean( new Date(), false, "(unknown)", "(unknown)", null, ErrorUtils.getLongForm("{0}", e), null ) ) : res; return updateV1ShareErrorStatus(new Date(), id, errs, library_mgmt, share_db, create_not_update); } }); } /** Want to end up with 3 lists: * - v1 objects that don't exist in v2 (Create them) * - v2 objects that don't exist in v1 (Delete them) * - matching v1/v2 objects with different modified times (Update them) * @param to_compare * @returns a 3-tuple with "to create", "to delete", "to update" - NOTE: none of the _ids here include the "v1_" */ protected static Tuple3<Collection<String>, Collection<String>, Collection<String>> compareJarsToLibraryBeans_categorize( final Tuple2<Map<String, String>, Map<String, Date>> to_compare) { // Want to end up with 3 lists: // - v1 sources that don't exist in v2 (Create them) // - v2 sources that don't exist in v1 (Delete them) // - matching v1/v2 sources with different modified times (Update them) // (do delete first, then going to filter to_compare._1() on value==null) final Set<String> v2_not_v1 = new HashSet<String>(to_compare._2().keySet()); v2_not_v1.removeAll(to_compare._1().keySet()); // OK not worried about deletes any more, not interested in isApproved:false final Set<String> to_compare_approved = to_compare._1().entrySet().stream() .filter(kv -> null != kv.getValue() && !kv.getValue().isEmpty()).map(kv -> kv.getKey()) .collect(Collectors.toSet()); final Set<String> v1_and_v2 = new HashSet<String>(to_compare_approved); v1_and_v2.retainAll(to_compare._2().keySet()); final List<String> v1_and_v2_mod = v1_and_v2.stream() .filter(id -> { try { final Date v1_date = parseJavaDate(to_compare._1().get(id)); final Date v2_date = to_compare._2().get(id); return v1_date.getTime() > v2_date.getTime(); } catch (Exception e) { return false; // (just ignore) } }) .collect(Collectors.toList()); final Set<String> v1_not_v2 = new HashSet<String>(to_compare_approved); v1_not_v2.removeAll(to_compare._2().keySet()); return Tuples._3T(v1_not_v2, v2_not_v1, v1_and_v2_mod); } //////////////////////////////////////////////////// //////////////////////////////////////////////////// // DB MANIPULATION - READ /** Gets a list of _id,modified from v1 and a list matching _id,modified from V2 * @param library_mgmt * @param share_db * @return tuple of id-vs-(date-or-null-if-not-approved) for v1, id-vs-date for v2 */ protected static CompletableFuture<Tuple2<Map<String, String>, Map<String, Date>>> compareJarsToLibaryBeans_get( final IManagementCrudService<SharedLibraryBean> library_mgmt, final ICrudService<JsonNode> share_db) { // (could make this more efficient by having a regular "did something happen" query with a slower "get everything and resync) // (don't forget to add "modified" to the compound index though) CompletableFuture<Cursor<JsonNode>> f_v1_jars = share_db.getObjectsBySpec( CrudUtils.allOf().when("type", "binary") .rangeIn("title", "/app/aleph2/library/", true, "/app/aleph2/library0", true), Arrays.asList("_id", "modified"), true ); return f_v1_jars .<Map<String, String>>thenApply(v1_jars -> { return StreamSupport.stream(v1_jars.spliterator(), false) .collect(Collectors.toMap( j -> safeJsonGet("_id", j).asText(), j -> safeJsonGet("modified", j).asText() )); }) .<Tuple2<Map<String, String>, Map<String, Date>>> thenCompose(v1_id_datestr_map -> { final SingleQueryComponent<SharedLibraryBean> library_query = CrudUtils.allOf(SharedLibraryBean.class) .rangeIn(SharedLibraryBean::_id, "v1_", true, "v1a", true) ; return library_mgmt.getObjectsBySpec(library_query, Arrays.asList("_id", "modified"), true) .<Tuple2<Map<String, String>, Map<String, Date>>> thenApply(c -> { final Map<String, Date> v2_id_date_map = StreamSupport.stream(c.spliterator(), false) .collect(Collectors.toMap( b -> b._id().substring(3), //(ie remove the "v1_") b -> b.modified() )); return Tuples._2T(v1_id_datestr_map, v2_id_date_map); }); }); } //////////////////////////////////////////////////// //////////////////////////////////////////////////// // FS - WRITE protected static void copyFile(final String binary_id, final String path, final IStorageService aleph2_fs, final GridFS share_fs ) throws IOException { try (ByteArrayOutputStream out = new ByteArrayOutputStream()) { final GridFSDBFile file = share_fs.find(new ObjectId(binary_id)); file.writeTo(out); final FileContext fs = aleph2_fs.getUnderlyingPlatformDriver(FileContext.class, Optional.empty()).get(); final Path file_path = fs.makeQualified(new Path(path)); try (FSDataOutputStream outer = fs.create(file_path, EnumSet.of(CreateFlag.CREATE, CreateFlag.OVERWRITE), org.apache.hadoop.fs.Options.CreateOpts.createParent())) { outer.write(out.toByteArray()); } } } //////////////////////////////////////////////////// //////////////////////////////////////////////////// // DB MANIPULATION - WRITE /** Create a new library bean * @param id * @param bucket_mgmt * @param create_not_update - true if create, false if update * @param share_db * @return */ protected static ManagementFuture<Supplier<Object>> createLibraryBean(final String id, final IManagementCrudService<SharedLibraryBean> library_mgmt, final IStorageService aleph2_fs, final boolean create_not_update, final ICrudService<JsonNode> share_db, final GridFS share_fs, final IServiceContext context ) { if (create_not_update) { _logger.info(ErrorUtils.get("Found new share {0}, creating library bean", id)); } else { _logger.info(ErrorUtils.get("Share {0} was modified, updating library bean", id)); } // Create a status bean: final SingleQueryComponent<JsonNode> v1_query = CrudUtils.allOf().when("_id", new ObjectId(id)); return FutureUtils.denestManagementFuture(share_db.getObjectBySpec(v1_query) .<ManagementFuture<Supplier<Object>>>thenApply(Lambdas.wrap_u(jsonopt -> { final SharedLibraryBean new_object = getLibraryBeanFromV1Share(jsonopt.get()); // Try to copy the file across before going crazy (going to leave this as single threaded for now, we'll live) final String binary_id = safeJsonGet("binaryId", jsonopt.get()).asText(); copyFile(binary_id, new_object.path_name(), aleph2_fs, share_fs); final AuthorizationBean auth = new AuthorizationBean(new_object.owner_id()); final ManagementFuture<Supplier<Object>> ret = library_mgmt.secured(context, auth).storeObject(new_object, !create_not_update); return ret; })) .exceptionally(e -> { return FutureUtils.<Supplier<Object>>createManagementFuture( FutureUtils.returnError(new RuntimeException(e)), CompletableFuture.completedFuture(Arrays.asList(new BasicMessageBean( new Date(), false, "IkanowV1SyncService_LibraryJars", "createLibraryBean", null, ErrorUtils.getLongForm("{0}", e), null ) )) ); } )) ; } /** Delete a library bean * @param id * @param library_mgmt * @return */ protected static ManagementFuture<Boolean> deleteLibraryBean(final String id, final IManagementCrudService<SharedLibraryBean> library_mgmt) { _logger.info(ErrorUtils.get("Share {0} was deleted, deleting libary bean", id)); //TODO: make it delete the JAR file in deleteObjectById return library_mgmt.deleteObjectById("v1_" + id); } /** Takes a collection of results from the management side-channel, and uses it to update a harvest node * @param key - source key / bucket id * @param status_messages * @param source_db */ protected static CompletableFuture<Boolean> updateV1ShareErrorStatus( final Date main_date, final String id, final Collection<BasicMessageBean> status_messages, final IManagementCrudService<SharedLibraryBean> library_mgmt, final ICrudService<JsonNode> share_db, final boolean create_not_update ) { final String message_block = status_messages.stream() .map(msg -> { return "[" + msg.date() + "] " + msg.source() + " (" + msg.command() + "): " + (msg.success() ? "INFO" : "ERROR") + ": " + msg.message(); }) .collect(Collectors.joining("\n")) ; final boolean any_errors = status_messages.stream().anyMatch(msg -> !msg.success()); // Only going to do something if we have errors: if (any_errors) { _logger.warn(ErrorUtils.get("Error creating/updating shared library bean: {0} error= {1}", id, message_block.replace("\n", "; "))); return share_db.getObjectById(new ObjectId(id), Arrays.asList("title", "description"), true).thenCompose(jsonopt -> { if (jsonopt.isPresent()) { // (else share has vanished, nothing to do) final CommonUpdateComponent<JsonNode> v1_update = Optional.of(CrudUtils.update() .set("description", safeJsonGet("description", jsonopt.get()).asText() + "\n\n" + message_block) ) // If shared lib already exists then can't update the title (or the existing lib bean will get deleted) .map(c -> create_not_update ? c.set("title", "ERROR:" + safeJsonGet("title", jsonopt.get()).asText()) : c ) .get(); @SuppressWarnings("unchecked") final CompletableFuture<Boolean> v2_res = Lambdas.get(() -> { if (!create_not_update) { // also make a token effort to update the timestamp on the shared lib bean, so the same error doesn't keep getting repeated final CommonUpdateComponent<SharedLibraryBean> v2_update = CrudUtils.update(SharedLibraryBean.class).set(SharedLibraryBean::modified, new Date()); //(need to do this because as of Aug 2015, the updateObjectById isn't plumbed in) final ICrudService<SharedLibraryBean> library_service = (ICrudService<SharedLibraryBean>) (ICrudService<?>)library_mgmt.getUnderlyingPlatformDriver(ICrudService.class, Optional.empty()).get(); return library_service.updateObjectById("v1_" + id, v2_update); // (just fire this off and forget about it) } else return CompletableFuture.completedFuture(true); }); final CompletableFuture<Boolean> update_res = v2_res.thenCompose(b -> { if (b) { return share_db.updateObjectById(new ObjectId(id), v1_update); } else { _logger.warn(ErrorUtils.get("Error creating/updating v2 library bean: {0} unknown error", id)); return CompletableFuture.completedFuture(false); } }) .exceptionally(t -> { _logger.warn(ErrorUtils.getLongForm("Error creating/updating shared library bean: {1} error= {0}", t, id)); return false; }) ; return update_res; } else { return CompletableFuture.completedFuture(false); } }); } else { return CompletableFuture.completedFuture(false); } } //////////////////////////////////////////////////// //////////////////////////////////////////////////// // LOW LEVEL UTILS /** Builds a V2 library bean out of a V1 share * @param src_json * @return * @throws JsonParseException * @throws JsonMappingException * @throws IOException * @throws ParseException */ protected static SharedLibraryBean getLibraryBeanFromV1Share(final JsonNode src_json) throws JsonParseException, JsonMappingException, IOException, ParseException { final String[] description_lines = Optional.ofNullable(safeJsonGet("description", src_json).asText()) .orElse("unknown").split("\r\n?|\n"); final String _id = "v1_" + safeJsonGet("_id", src_json).asText(); final String created = safeJsonGet("created", src_json).asText(); final String modified = safeJsonGet("modified", src_json).asText(); final String display_name = safeJsonGet("title", src_json).asText(); final String path_name = display_name; final List<String> description_lines_list = Arrays.asList(description_lines); // Find possible JSON config Optional<Tuple2<Integer, Integer>> json_config = IntStream.range(1, description_lines.length).boxed().filter(i -> description_lines[i].trim().startsWith("{")).findFirst() .<Tuple2<Integer, Integer>>map(start -> { return IntStream.range(start+1, description_lines.length).boxed() .filter(i -> !description_lines[i].matches("^\\s*[{}\"'].*")) .findFirst() .<Tuple2<Integer, Integer>>map(end -> Tuples._2T(start, end)) .orElse(Tuples._2T(start, description_lines.length)); }) ; @SuppressWarnings("unchecked") final Optional<Map<String, Object>> json = json_config .map(t2 ->description_lines_list.stream() .limit(t2._2()) .skip(t2._1()) .collect(Collectors.joining("\n"))) .map(Lambdas.wrap_u(s -> _mapper.readTree(s))) .<Map<String, Object>>map(j -> (Map<String, Object>) _mapper.convertValue(j, Map.class)); ; final Set<String> tags = safeTruncate(description_lines[description_lines.length - 1], 5).toLowerCase().startsWith("tags:") ? new HashSet<String>(Arrays.asList( description_lines[description_lines.length - 1] .replaceFirst("(?i)tags:\\s*", "") .split("\\s*,\\s*"))) : Collections.emptySet(); final String description = description_lines_list.stream() .limit(Optional.of(description_lines.length) .map(n -> tags.isEmpty() ? n : n-1) // skip over the tags if any .get() ) .skip(json_config.map(Tuple2::_2).orElse(1)) .collect(Collectors.joining("\n")); final LibraryType type = LibraryType.misc_archive; final String owner_id = safeJsonGet("_id", safeJsonGet("owner", src_json)).asText(); //final JsonNode comm_objs = safeJsonGet("communities", src_json); // collection of { _id: $oid } types final String misc_entry_point = description_lines[0]; final SharedLibraryBean bean = BeanTemplateUtils.build(SharedLibraryBean.class) .with(SharedLibraryBean::_id, _id) .with(SharedLibraryBean::created, parseJavaDate(created)) .with(SharedLibraryBean::modified, parseJavaDate(modified)) .with(SharedLibraryBean::display_name, display_name) .with(SharedLibraryBean::path_name, path_name) .with(SharedLibraryBean::description, description) .with(SharedLibraryBean::tags, tags) .with(SharedLibraryBean::type, type) .with(SharedLibraryBean::misc_entry_point, misc_entry_point) .with(SharedLibraryBean::owner_id, owner_id) .with(SharedLibraryBean::library_config, json.orElse(null)) .done().get(); return bean; } private static String safeTruncate(final String in, int max_len) { return in.length() < max_len ? in : in.substring(0, max_len); } /** Gets a JSON field that may not be present (justs an empty JsonNode if no) * @param fieldname * @param src * @return */ protected static JsonNode safeJsonGet(String fieldname, JsonNode src) { final JsonNode j = Optional.ofNullable(src.get(fieldname)).orElse(JsonNodeFactory.instance.objectNode()); //DEBUG //System.out.println(j); return j; } /** Quick utility to parse the result of Date::toString back into a date * @param java_date_tostring_format * @return * @throws ParseException */ protected static Date parseJavaDate(String java_date_tostring_format) throws ParseException { try { return new SimpleDateFormat("EEE MMM d HH:mm:ss zzz yyyy").parse(java_date_tostring_format); } catch (Exception e) { try { return new SimpleDateFormat("MMM d, yyyy hh:mm:ss a zzz").parse(java_date_tostring_format); } catch (Exception ee) { return new SimpleDateFormat("d MMM yyyy HH:mm:ss zzz").parse(java_date_tostring_format); } } } }
robgil/Aleph2-contrib
aleph2_management_db_service_mongodb/src/com/ikanow/aleph2/management_db/mongodb/services/IkanowV1SyncService_LibraryJars.java
Java
apache-2.0
29,392
/* * Copyright 2010-2013 Ning, Inc. * * Ning 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.killbill.billing.jaxrs.json; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import javax.annotation.Nullable; import org.apache.shiro.util.CollectionUtils; import org.joda.time.LocalDate; import org.killbill.billing.invoice.api.Invoice; import org.killbill.billing.invoice.api.InvoiceItem; import org.killbill.billing.invoice.api.InvoiceItemType; import org.killbill.billing.util.audit.AccountAuditLogs; import org.killbill.billing.util.audit.AuditLog; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.base.Predicate; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import io.swagger.annotations.ApiModelProperty; public class InvoiceJson extends JsonBase { private final BigDecimal amount; private final String currency; @ApiModelProperty(dataType = "java.util.UUID") private final String invoiceId; private final LocalDate invoiceDate; private final LocalDate targetDate; private final String invoiceNumber; private final BigDecimal balance; private final BigDecimal creditAdj; private final BigDecimal refundAdj; @ApiModelProperty(dataType = "java.util.UUID") private final String accountId; private final List<InvoiceItemJson> items; private final String bundleKeys; private final List<CreditJson> credits; private final String status; private final Boolean isParentInvoice; @JsonCreator public InvoiceJson(@JsonProperty("amount") final BigDecimal amount, @JsonProperty("currency") final String currency, @JsonProperty("status") final String status, @JsonProperty("creditAdj") final BigDecimal creditAdj, @JsonProperty("refundAdj") final BigDecimal refundAdj, @JsonProperty("invoiceId") final String invoiceId, @JsonProperty("invoiceDate") final LocalDate invoiceDate, @JsonProperty("targetDate") final LocalDate targetDate, @JsonProperty("invoiceNumber") final String invoiceNumber, @JsonProperty("balance") final BigDecimal balance, @JsonProperty("accountId") final String accountId, @JsonProperty("bundleKeys") final String bundleKeys, @JsonProperty("credits") final List<CreditJson> credits, @JsonProperty("items") final List<InvoiceItemJson> items, @JsonProperty("isParentInvoice") final Boolean isParentInvoice, @JsonProperty("auditLogs") @Nullable final List<AuditLogJson> auditLogs) { super(auditLogs); this.amount = amount; this.currency = currency; this.status = status; this.creditAdj = creditAdj; this.refundAdj = refundAdj; this.invoiceId = invoiceId; this.invoiceDate = invoiceDate; this.targetDate = targetDate; this.invoiceNumber = invoiceNumber; this.balance = balance; this.accountId = accountId; this.bundleKeys = bundleKeys; this.credits = credits; this.items = items; this.isParentInvoice = isParentInvoice; } public InvoiceJson(final Invoice input) { this(input, false, null, null); } public InvoiceJson(final Invoice input, final String bundleKeys, final List<CreditJson> credits, final List<AuditLog> auditLogs) { this(input.getChargedAmount(), input.getCurrency().toString(), input.getStatus().toString(), input.getCreditedAmount(), input.getRefundedAmount(), input.getId().toString(), input.getInvoiceDate(), input.getTargetDate(), String.valueOf(input.getInvoiceNumber()), input.getBalance(), input.getAccountId().toString(), bundleKeys, credits, null, input.isParentInvoice(), toAuditLogJson(auditLogs)); } public InvoiceJson(final Invoice input, final boolean withItems, final List<InvoiceItem> childItems, @Nullable final AccountAuditLogs accountAuditLogs) { super(toAuditLogJson(accountAuditLogs == null ? null : accountAuditLogs.getAuditLogsForInvoice(input.getId()))); this.items = new ArrayList<InvoiceItemJson>(input.getInvoiceItems().size()); if (withItems || !CollectionUtils.isEmpty(childItems)) { for (final InvoiceItem item : input.getInvoiceItems()) { ImmutableList<InvoiceItem> childItemsFiltered = null; if (item.getInvoiceItemType().equals(InvoiceItemType.PARENT_SUMMARY) && !CollectionUtils.isEmpty(childItems)) { childItemsFiltered = ImmutableList.copyOf(Iterables.filter(childItems, new Predicate<InvoiceItem>() { @Override public boolean apply(@Nullable final InvoiceItem invoice) { return invoice.getAccountId().equals(item.getChildAccountId()); } })); } this.items.add(new InvoiceItemJson(item, childItemsFiltered, accountAuditLogs == null ? null : accountAuditLogs.getAuditLogsForInvoiceItem(item.getId()))); } } this.amount = input.getChargedAmount(); this.currency = input.getCurrency().toString(); this.status = input.getStatus().toString(); this.creditAdj = input.getCreditedAmount(); this.refundAdj = input.getRefundedAmount(); this.invoiceId = input.getId().toString(); this.invoiceDate = input.getInvoiceDate(); this.targetDate = input.getTargetDate(); this.invoiceNumber = input.getInvoiceNumber() == null ? null : String.valueOf(input.getInvoiceNumber()); this.balance = input.getBalance(); this.accountId = input.getAccountId().toString(); this.bundleKeys = null; this.credits = null; this.isParentInvoice = input.isParentInvoice(); } public BigDecimal getAmount() { return amount; } public String getCurrency() { return currency; } public String getInvoiceId() { return invoiceId; } public LocalDate getInvoiceDate() { return invoiceDate; } public LocalDate getTargetDate() { return targetDate; } public String getInvoiceNumber() { return invoiceNumber; } public BigDecimal getBalance() { return balance; } public BigDecimal getCreditAdj() { return creditAdj; } public BigDecimal getRefundAdj() { return refundAdj; } public String getAccountId() { return accountId; } public List<InvoiceItemJson> getItems() { return items; } public String getBundleKeys() { return bundleKeys; } public List<CreditJson> getCredits() { return credits; } public String getStatus() { return status; } public Boolean getIsParentInvoice() { return isParentInvoice; } @Override public String toString() { return "InvoiceJson{" + "amount=" + amount + ", currency='" + currency + '\'' + ", status='" + status + '\'' + ", invoiceId='" + invoiceId + '\'' + ", invoiceDate=" + invoiceDate + ", targetDate=" + targetDate + ", invoiceNumber='" + invoiceNumber + '\'' + ", balance=" + balance + ", creditAdj=" + creditAdj + ", refundAdj=" + refundAdj + ", accountId='" + accountId + '\'' + ", items=" + items + ", bundleKeys='" + bundleKeys + '\'' + ", credits=" + credits + ", isParentInvoice=" + isParentInvoice + '}'; } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final InvoiceJson that = (InvoiceJson) o; if (accountId != null ? !accountId.equals(that.accountId) : that.accountId != null) { return false; } if (amount != null ? amount.compareTo(that.amount) != 0 : that.amount != null) { return false; } if (balance != null ? balance.compareTo(that.balance) != 0 : that.balance != null) { return false; } if (bundleKeys != null ? !bundleKeys.equals(that.bundleKeys) : that.bundleKeys != null) { return false; } if (creditAdj != null ? creditAdj.compareTo(that.creditAdj) != 0 : that.creditAdj != null) { return false; } if (credits != null ? !credits.equals(that.credits) : that.credits != null) { return false; } if (currency != null ? !currency.equals(that.currency) : that.currency != null) { return false; } if (invoiceDate != null ? invoiceDate.compareTo(that.invoiceDate) != 0 : that.invoiceDate != null) { return false; } if (invoiceId != null ? !invoiceId.equals(that.invoiceId) : that.invoiceId != null) { return false; } if (invoiceNumber != null ? !invoiceNumber.equals(that.invoiceNumber) : that.invoiceNumber != null) { return false; } if (items != null ? !items.equals(that.items) : that.items != null) { return false; } if (refundAdj != null ? refundAdj.compareTo(that.refundAdj) != 0 : that.refundAdj != null) { return false; } if (targetDate != null ? targetDate.compareTo(that.targetDate) != 0 : that.targetDate != null) { return false; } if (status != null ? !status.equals(that.status) : that.status != null) { return false; } if (isParentInvoice != null ? !isParentInvoice.equals(that.isParentInvoice) : that.isParentInvoice != null) { return false; } return true; } @Override public int hashCode() { int result = amount != null ? amount.hashCode() : 0; result = 31 * result + (currency != null ? currency.hashCode() : 0); result = 31 * result + (status != null ? status.hashCode() : 0); result = 31 * result + (invoiceId != null ? invoiceId.hashCode() : 0); result = 31 * result + (invoiceDate != null ? invoiceDate.hashCode() : 0); result = 31 * result + (targetDate != null ? targetDate.hashCode() : 0); result = 31 * result + (invoiceNumber != null ? invoiceNumber.hashCode() : 0); result = 31 * result + (balance != null ? balance.hashCode() : 0); result = 31 * result + (creditAdj != null ? creditAdj.hashCode() : 0); result = 31 * result + (refundAdj != null ? refundAdj.hashCode() : 0); result = 31 * result + (accountId != null ? accountId.hashCode() : 0); result = 31 * result + (items != null ? items.hashCode() : 0); result = 31 * result + (bundleKeys != null ? bundleKeys.hashCode() : 0); result = 31 * result + (credits != null ? credits.hashCode() : 0); result = 31 * result + (isParentInvoice != null ? isParentInvoice.hashCode() : 0); return result; } }
marksimu/killbill
jaxrs/src/main/java/org/killbill/billing/jaxrs/json/InvoiceJson.java
Java
apache-2.0
12,094
/* * Copyright (c) 2014. FarrelltonSolar * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ca.farrelltonsolar.classic; import android.app.Fragment; import android.app.FragmentManager; import android.support.v13.app.FragmentPagerAdapter; import android.util.Log; /** * Created by Graham on 03/01/2015. */ public class MonthCalendarPagerAdapter extends FragmentPagerAdapter { @Override public long getItemId(int position) { return super.getItemId(position); } public MonthCalendarPagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { Log.d(getClass().getName(), String.format("getItem DayLogCalendar position: %d thread is %s", position, Thread.currentThread().getName())); return DayLogCalendar.newInstance(position); } @Override public int getCount() { return 12; } @Override public CharSequence getPageTitle(int position) { return ""; } }
graham22/Classic
app/src/main/java/ca/farrelltonsolar/classic/MonthCalendarPagerAdapter.java
Java
apache-2.0
1,531
package tberg.murphy.opt; import java.util.ArrayList; import java.util.List; import java.util.Random; import tberg.murphy.arrays.a; import tberg.murphy.opt.Minimizer.Callback; import tberg.murphy.tuple.Pair; public class AdaGradL1Minimizer implements OnlineMinimizer { double eta; double delta; double regConstant; int epochs; public AdaGradL1Minimizer(double eta, double delta, double regConstant, int epochs) { this.eta = eta; this.delta = delta; this.regConstant = regConstant; this.epochs = epochs; } public double[] minimize(List<DifferentiableFunction> functions, double[] initial, boolean verbose, Callback iterCallbackFunction) { Random rand = new Random(0); double[] guess = a.copy(initial); double[] sqrGradSum = new double[guess.length]; a.addi(sqrGradSum, delta); final double r = eta * regConstant; for (int epoch=0; epoch<epochs; ++epoch) { double epochValSum = 0.0; double[] epochGradSum = new double[guess.length]; for (int funcIndex : a.shuffle(a.enumerate(0, functions.size()), rand)) { DifferentiableFunction func = functions.get(funcIndex); Pair<Double,double[]> valAndGrad = func.calculate(guess); epochValSum += valAndGrad.getFirst(); double[] grad = valAndGrad.getSecond(); a.combi(epochGradSum, 1.0, grad, 1.0); double[] sqrGrad = a.sqr(grad); a.combi(sqrGradSum, 1.0, sqrGrad, 1.0); for (int i=0; i<guess.length; ++i) { double s = Math.sqrt(sqrGradSum[i]); double xHalf = guess[i] - (eta/s)*grad[i]; double x = Math.abs(xHalf) - (r/s); if (x > 0) { guess[i] = (xHalf > 0 ? 1.0 : -1.0) * x; } else { guess[i] = 0.0; } } } if (verbose) System.out.println(String.format("[AdaGradMinimizer.minimize] Epoch %d ended with value %.6f", epoch, epochValSum + regConstant * a.sum(a.abs(guess)))); if (iterCallbackFunction != null) iterCallbackFunction.callback(guess, epoch, epochValSum, epochGradSum); } return guess; } public static void main(String[] args) { List<DifferentiableFunction> functions = new ArrayList<DifferentiableFunction>(); functions.add(new DifferentiableFunction() { public Pair<Double, double[]> calculate(double[] x) { return Pair.makePair(-a.sum(x) + 2.0 * a.innerProd(x, x), a.comb(a.scale(a.onesDouble(x.length), -1.0), 1.0, a.scale(x, 2.0 * 2.0), 1.0)); } }); functions.add(new DifferentiableFunction() { public Pair<Double, double[]> calculate(double[] x) { return Pair.makePair(2.0 * a.sum(x) + 2.0 * a.innerProd(x, x), a.comb(a.scale(a.onesDouble(x.length), 2.0), 1.0, a.scale(x, 2.0 * 2.0), 1.0)); } }); { OnlineMinimizer minimizer = new AdaGradL1Minimizer(1e-1, 1e-2, 0.1, 1000); minimizer.minimize(functions, a.onesDouble(10), true, null); } } }
tberg12/murphy
src/tberg/murphy/opt/AdaGradL1Minimizer.java
Java
apache-2.0
2,788
package edu.cmu.sv.ws.ssnoc.data.po; import com.google.gson.Gson; /** * This is the persistence class to save all user information in the system. * This contains information like the user's name, his role, his account status * and the password information entered by the user when signing up. <br/> * Information is saved in SSN_USERS table. * */ public class UserPO { private long userId; private String userName; private String password; private String salt; private String newUserName; private String data1; private String privilege; private String lastStatus; public long getUserId() { return userId; } public void setUserId(long userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getSalt() { return salt; } public void setSalt(String salt) { this.salt = salt; } public String getData1() { return data1; } public String getNewUserName() { return newUserName; } public void setNewUserName(String newUserName) { this.newUserName = newUserName; } public void setData1(String data1) { this.data1 = data1; } public String getPrivilege(){ return privilege; } public void setPrivilege(String privilege){ this.privilege = privilege; } public void setLastStatus(String lastStatus) {this.lastStatus = lastStatus; } public String getLastStatus() {return lastStatus;} @Override public String toString() { return new Gson().toJson(this); } }
bluebytes60/fse-F14-SA5-SSNoC-Java-REST
src/main/java/edu/cmu/sv/ws/ssnoc/data/po/UserPO.java
Java
apache-2.0
1,701
/* * Copyright 2002-2006,2009 The Apache Software Foundation. * * 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.opensymphony.xwork2.validator.metadata; import java.io.PrintWriter; import java.io.StringWriter; /** * <code>StringLengthFieldValidatorDescription</code> * * @author Rainer Hermanns * @version $Id: StringLengthFieldValidatorDescription.java 894090 2009-12-27 18:18:29Z martinc $ */ public class StringLengthFieldValidatorDescription extends AbstractFieldValidatorDescription { public boolean trim = true; public String minLength; public String maxLength; public StringLengthFieldValidatorDescription() { } /** * Creates an AbstractFieldValidatorDescription with the specified field name. * * @param fieldName */ public StringLengthFieldValidatorDescription(String fieldName) { super(fieldName); } public void setTrim(boolean trim) { this.trim = trim; } public void setMinLength(String minLength) { this.minLength = minLength; } public void setMaxLength(String maxLength) { this.maxLength = maxLength; } /** * Returns the field validator XML definition. * * @return the field validator XML definition. */ @Override public String asFieldXml() { StringWriter sw = new StringWriter(); PrintWriter writer = null; try { writer = new PrintWriter(sw); if ( shortCircuit) { writer.println("\t\t<field-validator type=\"stringlength\">"); } else { writer.println("\t\t<field-validator type=\"stringlength\" short-circuit=\"true\">"); } if ( !trim) { writer.println("\t\t\t<param name=\"trim\">" + trim + "</param>"); } if ( minLength != null && minLength.length() > 0) { writer.println("\t\t\t<param name=\"minLength\">" + minLength + "</param>"); } if ( maxLength != null && maxLength.length() > 0) { writer.println("\t\t\t<param name=\"maxLength\">" + maxLength + "</param>"); } if ( !"".equals(key)) { writer.println("\t\t\t<message key=\"" + key + "\">" + message + "</message>"); } else { writer.println("\t\t\t<message>" + message + "</message>"); } writer.println("\t</field-validator>"); } finally { if (writer != null) { writer.flush(); writer.close(); } } return sw.toString(); } /** * Returns the validator XML definition. * * @return the validator XML definition. */ @Override public String asSimpleXml() { StringWriter sw = new StringWriter(); PrintWriter writer = null; try { writer = new PrintWriter(sw); if ( shortCircuit) { writer.println("\t<validator type=\"stringlength\">"); } else { writer.println("\t<validator type=\"stringlength\" short-circuit=\"true\">"); } writer.println("\t\t<param name=\"fieldName\">" + fieldName+ "</param>"); if ( !trim) { writer.println("\t\t<param name=\"trim\">" + trim + "</param>"); } if ( minLength != null && minLength.length() > 0) { writer.println("\t\t<param name=\"minLength\">" + minLength + "</param>"); } if ( maxLength != null && maxLength.length() > 0) { writer.println("\t\t<param name=\"maxLength\">" + maxLength + "</param>"); } if ( !"".equals(key)) { writer.println("\t\t<message key=\"" + key + "\">" + message + "</message>"); } else { writer.println("\t\t<message>" + message + "</message>"); } writer.println("\t</validator>"); } finally { if (writer != null) { writer.flush(); writer.close(); } } return sw.toString(); } }
yuzhongyousida/struts-2.3.1.2
src/xwork-core/src/main/java/com/opensymphony/xwork2/validator/metadata/StringLengthFieldValidatorDescription.java
Java
apache-2.0
4,719
/* * Copyright 2003 - 2015 The eFaps Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.efaps.eql.stmt.parts; /** * The Interface ISubQueryStmtPart. * * @author The eFaps Team */ public interface INestedQueryStmtPart extends IQueryPart { /** * Sets the select. * * @param _select Select to be added to the Statement * @throws Exception on error */ void setSelect(final String _select) throws Exception; }
eFaps/eFaps-EQL
src/main/java/org/efaps/eql/stmt/parts/INestedQueryStmtPart.java
Java
apache-2.0
987
/** * Defines {@link org.estatio.module.financial.dom.FinancialAccount}s, each of which is * {@link org.estatio.module.financial.dom.FinancialAccount#getOwner() owned} by a {@link org.estatio.module.party.dom.Party}. * * <p> * {@link org.estatio.module.financial.dom.FinancialAccount} is abstract, with * {@link org.estatio.module.financial.dom.FinancialAccountType} acts as a powertype. Currently only a single concrete * subtype, {@link org.estatio.module.financial.dom.BankAccount}, exists. * * <p> * {@link org.estatio.module.financial.dom.BankAccountType} characterises the type of the bank account, for example * <i>CHECKING</i>. * * <p> * A {@link org.estatio.module.party.dom.Party} is required to have a {@link org.estatio.module.financial.dom.BankAccount}. */ package org.estatio.module.financial.dom;
estatio/estatio
estatioapp/app/src/main/java/org/estatio/module/financial/dom/package-info.java
Java
apache-2.0
829
/* * Copyright 2015 NEC Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.o3project.odenos.core.component.network; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.CoreMatchers.nullValue; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.anyObject; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; import org.msgpack.type.ValueFactory; import org.o3project.odenos.core.component.network.flow.Flow; import org.o3project.odenos.core.component.network.flow.FlowChanged; import org.o3project.odenos.core.component.network.flow.FlowObject.FlowStatus; import org.o3project.odenos.core.component.network.flow.FlowSet; import org.o3project.odenos.core.component.network.flow.basic.BasicFlow; import org.o3project.odenos.core.component.network.flow.ofpflow.OFPFlow; import org.o3project.odenos.core.component.network.packet.InPacket; import org.o3project.odenos.core.component.network.packet.InPacketAdded; import org.o3project.odenos.core.component.network.packet.InPacketQueue; import org.o3project.odenos.core.component.network.packet.OutPacket; import org.o3project.odenos.core.component.network.packet.OutPacketAdded; import org.o3project.odenos.core.component.network.packet.OutPacketQueue; import org.o3project.odenos.core.component.network.packet.Packet; import org.o3project.odenos.core.component.network.packet.PacketQueue; import org.o3project.odenos.core.component.network.packet.PacketQueueSet; import org.o3project.odenos.core.component.network.packet.PacketStatus; import org.o3project.odenos.core.component.network.topology.Link; import org.o3project.odenos.core.component.network.topology.LinkChanged; import org.o3project.odenos.core.component.network.topology.Node; import org.o3project.odenos.core.component.network.topology.NodeChanged; import org.o3project.odenos.core.component.network.topology.Port; import org.o3project.odenos.core.component.network.topology.PortChanged; import org.o3project.odenos.core.component.network.topology.Topology; import org.o3project.odenos.core.component.network.topology.TopologyChanged; import org.o3project.odenos.remoteobject.ObjectSettings; import org.o3project.odenos.remoteobject.RequestParser; import org.o3project.odenos.remoteobject.message.Request; import org.o3project.odenos.remoteobject.message.Request.Method; import org.o3project.odenos.remoteobject.message.Response; import org.o3project.odenos.remoteobject.messagingclient.MessageDispatcher; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.reflect.Whitebox; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Test class for Network. */ @RunWith(PowerMockRunner.class) @PrepareForTest({ Network.class, RequestParser.class }) public class NetworkTest { private Network target; private MessageDispatcher dispatcher; /** * @throws java.lang.Exception */ @BeforeClass public static void setUpBeforeClass() throws Exception { } /** * @throws java.lang.Exception */ @AfterClass public static void tearDownAfterClass() throws Exception { } /** * @throws java.lang.Exception */ @Before public void setUp() throws Exception { dispatcher = Mockito.mock(MessageDispatcher.class); target = Mockito.spy(new Network("ojectId", dispatcher)); } /** * @throws java.lang.Exception */ @After public void tearDown() throws Exception { target = null; dispatcher = null; } private Network createPowerSpy() { Network network = PowerMockito.spy(new Network("ojectId", dispatcher)); target = network; return network; } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#getSettings()}. */ @Test public void testGetSettings() { ObjectSettings result = target.getSettings(); assertThat(result, is(notNullValue())); } /** * Test method for {@link org.o3project.odenos.core.component.network.Network#onRequest(org.o3project.odenos.remoteobject.message.Request)}. * @throws Exception */ @Test public void testOnRequest() throws Exception { /* * setting */ /* set listener for onRequest */ Whitebox.invokeMethod(target, "createParser"); Request request = new Request("ObjectId", Request.Method.GET, "settings/verbose_event/port", ValueFactory.createRawValue("body")); /* * test */ Response result = target.onRequest(request); /* * check */ assertThat(result.statusCode, is(Response.OK)); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#onRequest(org.o3project.odenos.remoteobject.message.Request)} * . */ @Test public void testOnRequestWithNullPath() { Request request = Mockito.spy(new Request("objectId", Request.Method.GET, "", null)); Response result = target.onRequest(request); assertThat(result.statusCode, is(Response.BAD_REQUEST)); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#onRequest(org.o3project.odenos.remoteobject.message.Request)} * . */ @Test public void testOnRequestWithBadBody() { Request request = Mockito.spy(new Request("objectId", Request.Method.GET, "/", new Object())); Response result = target.onRequest(request); assertThat(result.statusCode, is(Response.BAD_REQUEST)); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#getSuperType()}. */ @Test public void testGetSuperType() { String result = target.getSuperType(); assertThat(result, is("Network")); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#getDescription()}. */ @Test public void testGetDescription() { String result = target.getDescription(); assertThat(result, is("Network Component")); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#Network(java.lang.String, java.lang.String, org.o3project.odenos.remoteobject.messagingclient.MessageDispatcher)} * . */ @Test public void testNetwork() { /* * test */ target = new Network("ObjectId", dispatcher); /* * check */ assertThat(target.getSuperType(), is("Network")); assertThat(target.getDescription(), is("Network Component")); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#getSettingVerbosePort()} * . * * @throws Exception */ @Test public void testGetSettingVerbosePort() throws Exception { /* * setting */ target.putSettingVerbosePort("true"); /* * test */ Response result = target.getSettingVerbosePort(); /* * check */ assertThat(result.statusCode, is(Response.OK)); assertThat(result.getBodyValue(), is(notNullValue())); assertThat(result.getBody(String.class), is("true")); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#putSettingVerbosePort(java.lang.String)} * . * * @throws Exception */ @Test public void testPutSettingVerbosePort() throws Exception { /* * test */ Response result = target.putSettingVerbosePort("true"); /* * check */ assertThat(result.statusCode, is(Response.OK)); assertThat(result.getBodyValue(), is(notNullValue())); assertThat(result.getBody(String.class), is("true")); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#putSettingVerbosePort(java.lang.String)} * . * * @throws Exception */ @Test public void testPutSettingVerbosePortWithNull() throws Exception { /* * test */ Response result = target.putSettingVerbosePort(null); /* * check */ assertThat(result.statusCode, is(Response.OK)); assertThat(result.getBodyValue(), is(nullValue())); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#getSettingVerboseLink()} * . * * @throws Exception */ @Test public void testGetSettingVerboseLink() throws Exception { /* * setting */ target.putSettingVerboseLink("true"); /* * test */ Response result = target.getSettingVerboseLink(); /* * check */ assertThat(result.statusCode, is(Response.OK)); assertThat(result.getBodyValue(), is(notNullValue())); assertThat(result.getBody(String.class), is("true")); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#putSettingVerboseLink(java.lang.String)} * . * * @throws Exception */ @Test public void testPutSettingVerboseLink() throws Exception { /* * test */ Response result = target.putSettingVerboseLink("true"); /* * check */ assertThat(result.statusCode, is(Response.OK)); assertThat(result.getBodyValue(), is(notNullValue())); assertThat(result.getBody(String.class), is("true")); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#putSettingVerboseLink(java.lang.String)} * . * * @throws Exception */ @Test public void testPutSettingVerboseLinkWithNull() throws Exception { /* * test */ Response result = target.putSettingVerboseLink(null); /* * check */ assertThat(result.statusCode, is(Response.OK)); assertThat(result.getBodyValue(), is(nullValue())); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#getTopology()}. * * @throws Exception */ @Test public void testGetTopology() throws Exception { /* * test */ Response result = target.getTopology(); /* * check */ assertThat(result.statusCode, is(Response.OK)); assertThat(result.getBody(Topology.class), is(notNullValue())); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#putTopology(org.o3project.odenos.component.network.topology.TopologyObject.TopologyMessage)} * . * * @throws Exception */ @Test public void testPutTopologyWithDefaultTopology() throws Exception { Topology topology = new Topology(); /* * test */ Response result = target.putTopology(topology); /* * check */ assertThat(result.statusCode, is(Response.OK)); assertThat(result.getBody(Topology.class), is(notNullValue())); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#putTopology(org.o3project.odenos.component.network.topology.TopologyObject.TopologyMessage)} * . * * @throws Exception */ @Test public void testPutTopologyWithTopologyNodeLink() throws Exception { Map<String, Node> nodes = new HashMap<String, Node>(); Map<String, Link> links = new HashMap<String, Link>(); Topology topology = new Topology(nodes, links); /* * test */ Response result = target.putTopology(topology); /* * check */ Topology resultToporogy = result.getBody(Topology.class); assertThat(result.statusCode, is(Response.OK)); assertThat(resultToporogy, is(notNullValue())); assertThat(resultToporogy.validate(), is(true)); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#putTopology(org.o3project.odenos.component.network.topology.TopologyObject.TopologyMessage)} * . * * @throws Exception */ @Test public void testPutTopologyWithNullLink() throws Exception { Topology topology = Mockito.spy(new Topology("0", null, null)); /* * test */ Response result = target.putTopology(topology); /* * check */ assertThat(result.statusCode, is(Response.OK)); Topology resultTopology = result.getBody(Topology.class); assertThat(resultTopology.getVersion(), is("0")); assertThat(resultTopology.getNodeMap().size(), is(0)); assertThat(resultTopology.getLinkMap().size(), is(0)); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#postNode(org.o3project.odenos.component.network.topology.TopologyObject.NodeMessage)} * . * * @throws Exception */ @Test public void testPostNode() throws Exception { /* * setting */ createPowerSpy(); PowerMockito.doReturn(new Response(Response.OK, new Object())).when( target, "notifyNodeChanged", eq(null), anyObject(), eq(NodeChanged.Action.add)); /* * test */ Node node = new Node(); Response result = target.postNode(node); /* * check */ Node resultNode = result.getBody(Node.class); assertThat(result.statusCode, is(Response.OK)); assertThat(resultNode.getVersion(), is("1")); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#postNode(org.o3project.odenos.component.network.topology.TopologyObject.NodeMessage)} * . * * @throws Exception */ @Test public void testPostNodeAfterPost() throws Exception { /* * setting */ createPowerSpy(); PowerMockito.doReturn(new Response(Response.OK, new Object())).when( target, "notifyNodeChanged", eq(null), anyObject(), eq(NodeChanged.Action.add)); Node settingNode = new Node(); Response settingResult = target.postNode(settingNode); assertThat(settingResult.statusCode, is(Response.OK)); Node node = settingResult.getBody(Node.class); assertThat(node.getVersion(), is("1")); /* * test */ Response result = target.postNode(node); /* * check */ Node resultNode = result.getBody(Node.class); assertThat(result.statusCode, is(Response.OK)); assertThat(resultNode.getVersion(), is("1")); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#postNode(org.o3project.odenos.component.network.topology.TopologyObject.NodeMessage)} * . * * @throws Exception */ @Test public void testPostNodeWithNull() throws Exception { /* * test */ Response result = target.postNode(null); /* * check */ // FIXME check status code when Node is null. //assertThat(result.statusCode, is(Response.BAD_REQUEST)); assertThat(result.statusCode, is(Response.OK)); assertThat(result.getBody(Node.class), is(notNullValue())); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#getNodes(boolean, java.lang.String)} * . * * @throws Exception */ @Test public void testGetNodesWithQueryTrue() throws Exception { /* * setting */ Node node = new Node(); Response settingResponse = target.putNode("NodeId", node); assertThat(settingResponse.statusCode, is(Response.CREATED)); /* * test */ Response result = target.getNodes(true, ""); /* * check */ assertThat(result.statusCode, is(Response.OK)); Map<String, Node> resultNodes = result.getBodyAsMap(Node.class); assertThat(resultNodes.size(), is(1)); assertThat(resultNodes.containsKey("NodeId"), is(true)); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#getNodes(boolean, java.lang.String)} * . * * @throws Exception */ @Test public void testGetNodesWithQueryFalse() throws Exception { /* * setting */ Node node = new Node(); Response settingResponse = target.putNode("NodeId", node); assertThat(settingResponse.statusCode, is(Response.CREATED)); /* * test */ Response result = target.getNodes(false, null); /* * check */ assertThat(result.statusCode, is(Response.OK)); Map<String, Node> resultNodes = result.getBodyAsMap(Node.class); assertThat(resultNodes.size(), is(1)); assertThat(resultNodes.containsKey("NodeId"), is(true)); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#getNodes(boolean, java.lang.String)} * . * * @throws Exception */ @Test public void testGetNodesWithQueryFalse_NoNode() throws Exception { /* * test */ Response result = target.getNodes(false, null); /* * check */ assertThat(result.statusCode, is(Response.OK)); Map<String, Node> resultNodes = result.getBodyAsMap(Node.class); assertThat(resultNodes.size(), is(0)); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#getNode(java.lang.String)} * . * * @throws Exception */ @Test public void testGetNode() throws Exception { /* * setting */ Node node = new Node("NodeId"); Response settingResponse = target.postNode(node); assertThat(settingResponse.statusCode, is(Response.OK)); Node settingNode = settingResponse.getBody(Node.class); String nodeId = settingNode.getId(); /* * test */ Response result = target.getNode(nodeId); /* * check */ assertThat(result.statusCode, is(Response.OK)); assertThat(result.getBody(Node.class), is(settingNode)); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#getNode(java.lang.String)} * . */ @Test public void testGetNodeNotRegisterNodeId() { /* * test */ Response result = target.getNode("nodeId"); /* * check */ assertThat(result.statusCode, is(Response.NOT_FOUND)); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#putNode(java.lang.String, org.o3project.odenos.component.network.topology.TopologyObject.NodeMessage)} * . * * @throws Exception */ @Test public void testPutNodeCreate() throws Exception { /* * setting */ createPowerSpy(); PowerMockito.doReturn(null).when(target, "notifyNodeChanged", eq(null), anyObject(), eq(NodeChanged.Action.update)); /* * test */ Node node = new Node(); Response result = target.putNode("NodeId", node); /* * check */ Node resultNode = result.getBody(Node.class); assertThat(result.statusCode, is(Response.CREATED)); assertThat(resultNode.getId(), is("NodeId")); assertThat(resultNode.getVersion(), is("1")); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#putNode(java.lang.String, org.o3project.odenos.component.network.topology.TopologyObject.NodeMessage)} * . * * @throws Exception */ @Test public void testPutNodeUpdate() throws Exception { /* * setting */ createPowerSpy(); Map<String, Node> nodes = new HashMap<>(); Map<String, Link> links = new HashMap<>(); Node firstNode = new Node("1", "NodeId"); firstNode.putAttribute("Key", "Value"); nodes.put("NodeId", firstNode); Topology topology = new Topology(nodes, links); Whitebox.setInternalState(target, "topology", topology); PowerMockito.doReturn(null).when(target, "notifyNodeChanged", eq(null), anyObject(), eq(NodeChanged.Action.update)); /* * test */ Node targetNode = new Node("1", "NodeId"); targetNode.putAttribute("Key", "NewValue"); Response result = target.putNode("NodeId", targetNode); /* * check */ Node resultNode = result.getBody(Node.class); assertThat(result.statusCode, is(Response.OK)); assertThat(resultNode.getVersion(), is("2")); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#putNode(java.lang.String, org.o3project.odenos.component.network.topology.TopologyObject.NodeMessage)} * . * * @throws Exception */ @Test public void testPutNodeUpdate_SameNode() throws Exception { /* * setting */ createPowerSpy(); Map<String, Node> nodes = new HashMap<>(); Map<String, Link> links = new HashMap<>(); Node firstNode = new Node("1", "NodeId"); nodes.put("NodeId", firstNode); Topology topology = new Topology(nodes, links); Whitebox.setInternalState(target, "topology", topology); PowerMockito.doReturn(null).when(target, "notifyNodeChanged", eq(null), anyObject(), eq(NodeChanged.Action.update)); /* * test */ Node targetNode = new Node("1", "NodeId"); Response result = target.putNode("NodeId", targetNode); /* * check */ Node resultNode = result.getBody(Node.class); assertThat(result.statusCode, is(Response.OK)); assertThat(resultNode, is(targetNode)); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#putNode(java.lang.String, org.o3project.odenos.component.network.topology.TopologyObject.NodeMessage)} * . * * @throws Exception */ @Test public void testPutNodeWithNullId() throws Exception { /* * setting */ createPowerSpy(); PowerMockito.doReturn(null).when(target, "notifyNodeChanged", eq(null), anyObject(), eq(NodeChanged.Action.update)); /* * test */ Node node = new Node(); Response result = target.putNode(null, node); /* * check */ assertThat(result.statusCode, is(Response.BAD_REQUEST)); assertThat(result.getBody(Node.class), is(notNullValue())); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#putNode(java.lang.String, org.o3project.odenos.component.network.topology.TopologyObject.NodeMessage)} * . * * @throws Exception */ @Test public void testPutNodeWithNullNode() throws Exception { /* * setting */ target = PowerMockito.spy(new Network("ojectId", dispatcher)); PowerMockito.doReturn(null).when(target, "notifyNodeChanged", eq(null), anyObject(), eq(NodeChanged.Action.update)); /* * test */ Response result = target.putNode("NodeId", null); /* * check */ assertThat(result.statusCode, is(Response.BAD_REQUEST)); assertThat(result.getBody(Node.class), is(notNullValue())); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#deleteNode(java.lang.String, org.o3project.odenos.component.network.topology.TopologyObject.NodeMessage)} * . * * @throws Exception */ @Test public void testDeleteNode() throws Exception { /* * setting */ createPowerSpy(); PowerMockito.doReturn(null).when(target, "notifyNodeChanged", eq(null), anyObject(), eq(NodeChanged.Action.update)); Node settingNode = new Node(); Response settingResult = target.putNode("NodeId", settingNode); assertThat(settingResult.statusCode, is(Response.CREATED)); assertThat(settingResult.getBody(Node.class).getVersion(), is("1")); /* * test */ Node node = new Node("1", "NodeId"); Response result = target.deleteNode("NodeId", node); /* * check */ assertThat(result.statusCode, is(Response.OK)); Response checkResult = target.getNode("NodeId"); assertThat(checkResult.statusCode, is(Response.NOT_FOUND)); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#deleteNode(java.lang.String, org.o3project.odenos.component.network.topology.TopologyObject.NodeMessage)} * . * * @throws Exception */ @Test public void testDeleteNodeWithInvalidNode() throws Exception { /* * setting */ createPowerSpy(); PowerMockito.doReturn(null).when(target, "notifyNodeChanged", eq(null), anyObject(), eq(NodeChanged.Action.update)); Node settingNode = new Node(); Response settingResult = target.putNode("NodeId", settingNode); assertThat(settingResult.statusCode, is(Response.CREATED)); assertThat(settingResult.getBody(Node.class).getVersion(), is("1")); /* * test */ Node node = new Node("999", "NodeId"); Response result = target.deleteNode("NodeId", node); /* * check */ assertThat(result.statusCode, is(Response.CONFLICT)); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#deleteNode(java.lang.String, org.o3project.odenos.component.network.topology.TopologyObject.NodeMessage)} * . * * @throws Exception */ @Test public void testDeleteNodeNothing() throws Exception { Node node = new Node(); Response result = target.deleteNode("NodeId", node); /* * check */ assertThat(result.statusCode, is(Response.OK)); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#postPort(java.lang.String, org.o3project.odenos.component.network.topology.TopologyObject.PortMessage)} * . * * @throws Exception */ @Test public void testPostPort() throws Exception { /* * setting */ Node settingNode = new Node("NodeId"); Response settingResponse = target.postNode(settingNode); Node node = settingResponse.getBody(Node.class); String nodeId = node.getId(); /* * test */ Port port = new Port(); Response result = target.postPort(nodeId, port); /* * check */ Port resultPort = result.getBody(Port.class); // assertThat(result.statusCode, is(Response.CREATED)); assertThat(result.statusCode, is(Response.OK)); assertThat(resultPort.getNode(), is(nodeId)); assertThat(resultPort.getVersion(), is("1")); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#getPorts(boolean, java.lang.String, java.lang.String, org.o3project.odenos.component.network.topology.TopologyObject.PortMessage)} * . * * @throws Exception */ @Test public void testGetPorts() throws Exception { /* * setting */ Map<String, Port> ports = new HashMap<>(); ports.put("Port1", new Port("PortId1")); ports.put("Port2", new Port("PortId2")); ports.put("Port3", new Port("PortId3")); Map<String, String> attributes = new HashMap<>(); Node node = new Node("1", "NodeId", ports, attributes); Map<String, Node> nodes = new HashMap<>(); nodes.put("NodeId", node); Map<String, Link> links = new HashMap<>(); Topology topology = new Topology(nodes, links); Whitebox.setInternalState(target, "topology", topology); /* * test */ Response result = target.getPorts(false, null, "NodeId", null); /* * check */ assertThat(result.statusCode, is(Response.OK)); Map<String, Port> resultMap = result.getBodyAsMap(Port.class); assertThat(resultMap.size(), is(3)); assertThat(resultMap.containsKey("Port1"), is(true)); assertThat(resultMap.containsKey("Port2"), is(true)); assertThat(resultMap.containsKey("Port3"), is(true)); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#getPort(java.lang.String, java.lang.String)} * . * * @throws Exception */ @Test public void testGetPort() throws Exception { /* * setting */ Node node = new Node(); Response settingNodeResponse = target.putNode("NodeId", node); assertThat(settingNodeResponse.statusCode, is(Response.CREATED)); ; Port port = new Port(); Response settingPortResponse = target.putPort("NodeId", "PortId", port); assertThat(settingPortResponse.statusCode, is(Response.CREATED)); /* * test */ Response result = target.getPort("NodeId", "PortId"); /* * check */ assertThat(result.statusCode, is(Response.OK)); Port resultPort = result.getBody(Port.class); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#getPort(java.lang.String, java.lang.String)} * . */ @Test public void testGetPortWithNothingPort() { Response result = target.getPort("NodeId", "PortId"); /* * check */ assertThat(result.statusCode, is(Response.NOT_FOUND)); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#putPort(java.lang.String, java.lang.String, org.o3project.odenos.component.network.topology.TopologyObject.PortMessage)} * . * * @throws Exception */ @Test public void testPutPort() throws Exception { /* * setting */ Node node = new Node(); Response settingNodeResponse = target.putNode("NodeId", node); assertThat(settingNodeResponse.statusCode, is(Response.CREATED)); /* * test */ Port port = new Port(); Response result = target.putPort("NodeId", "PortId", port); /* * check */ assertThat(result.statusCode, is(Response.CREATED)); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#putPort(java.lang.String, java.lang.String, org.o3project.odenos.component.network.topology.TopologyObject.PortMessage)} * . * * @throws Exception */ @Test public void testPutPortAfterPut() throws Exception { /* * setting */ Node settingNode = new Node(); Response settingNodeResponse = target.putNode("NodeId", settingNode); assertThat(settingNodeResponse.statusCode, is(Response.CREATED)); Port settingPort = new Port(); Response settingPortResponse = target.putPort("NodeId", "PortId", settingPort); assertThat(settingPortResponse.statusCode, is(Response.CREATED)); /* * test */ Port port = new Port("1", "NodeId", "PortId"); Response result = target.putPort("NodeId", "PortId", port); /* * check */ assertThat(result.statusCode, is(Response.OK)); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#putPort(java.lang.String, java.lang.String, org.o3project.odenos.component.network.topology.TopologyObject.PortMessage)} * . * * @throws Exception */ @Test public void testPutPortAfterPortInvalid() throws Exception { /* * setting */ Node settingNode = new Node(); Response settingNodeResponse = target.putNode("NodeId", settingNode); assertThat(settingNodeResponse.statusCode, is(Response.CREATED)); Port settingPort = new Port(); Response settingPortResponse = target.putPort("NodeId", "PortId", settingPort); assertThat(settingPortResponse.statusCode, is(Response.CREATED)); /* * test */ Port port = new Port("999", "NodeId", "PortId"); Response result = target.putPort("NodeId", "PortId", port); /* * check */ assertThat(result.statusCode, is(Response.CONFLICT)); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#deletePort(java.lang.String, java.lang.String, org.o3project.odenos.component.network.topology.TopologyObject.PortMessage)} * . * * @throws Exception */ @Test public void testDeletePort() throws Exception { /* * setting */ Node settingNode = new Node(); Response settingNodeResponse = target.putNode("NodeId", settingNode); assertThat(settingNodeResponse.statusCode, is(Response.CREATED)); Port settingPort = new Port(); Response settingPortResponse = target.putPort("NodeId", "PortId", settingPort); assertThat(settingPortResponse.statusCode, is(Response.CREATED)); /* * test */ Port port = new Port("1", "PortId", "NodeId"); Response result = target.deletePort("NodeId", "PortId", port); /* * check */ assertThat(result.statusCode, is(Response.OK)); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#deletePort(java.lang.String, java.lang.String, org.o3project.odenos.component.network.topology.TopologyObject.PortMessage)} * . * * @throws Exception */ @Test public void testDeletePortWithInvalidPort() throws Exception { /* * setting */ Node settingNode = new Node(); Response settingNodeResponse = target.putNode("NodeId", settingNode); assertThat(settingNodeResponse.statusCode, is(Response.CREATED)); Port settingPort = new Port(); Response settingPortResponse = target.putPort("NodeId", "PortId", settingPort); assertThat(settingPortResponse.statusCode, is(Response.CREATED)); /* * test */ Port port = new Port("999", "PortId", "NodeId"); Response result = target.deletePort("NodeId", "PortId", port); /* * check */ assertThat(result.statusCode, is(Response.CONFLICT)); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#deletePort(java.lang.String, java.lang.String, org.o3project.odenos.component.network.topology.TopologyObject.PortMessage)} * . * * @throws Exception */ @Test public void testDeletePort_NothingNode() throws Exception { /* * test */ Port port = new Port(); Response result = target.deletePort("NodeId", "PortId", port); /* * check */ assertThat(result.statusCode, is(Response.NOT_FOUND)); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#deletePort(java.lang.String, java.lang.String, org.o3project.odenos.component.network.topology.TopologyObject.PortMessage)} * . * * @throws Exception */ @Test public void testDeletePort_NothingPort() throws Exception { /* * setting */ Node settingNode = new Node(); Response settingNodeResponse = target.putNode("NodeId", settingNode); assertThat(settingNodeResponse.statusCode, is(Response.CREATED)); /* * test */ Port port = new Port(); Response result = target.deletePort("NodeId", "PortId", port); /* * check */ // assertThat(result.statusCode,is(Response.NOT_FOUND)); assertThat(result.statusCode, is(Response.OK)); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#deletePort(java.lang.String, java.lang.String, org.o3project.odenos.component.network.topology.TopologyObject.PortMessage)} * . * * @throws Exception */ @Test public void testDeletePortWithPortNull() throws Exception { /* * setting */ Node settingNode = new Node(); Response settingNodeResponse = target.putNode("NodeId", settingNode); assertThat(settingNodeResponse.statusCode, is(Response.CREATED)); Port settingPort = new Port(); Response settingPortResponse = target.putPort("NodeId", "PortId", settingPort); assertThat(settingPortResponse.statusCode, is(Response.CREATED)); /* * test */ Response result = target.deletePort("NodeId", "PortId", null); /* * check */ // assertThat(result.statusCode,is(Response.NOT_FOUND)); assertThat(result.statusCode, is(Response.OK)); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#getNodePhysicalId(java.lang.String)} * . */ @Test public void testGetNodePhysicalIdWithNullId() { /* * test */ Response result = target.getNodePhysicalId(null); /* * check */ assertThat(result.statusCode, is(Response.NOT_FOUND)); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#putNodePhysicalId(java.lang.String, org.o3project.odenos.component.network.topology.TopologyObject.NodeMessage)} * . * * @throws Exception */ @Test public void testPutNodePhysicalId() throws Exception { /* * setting */ Map<String, Port> ports = new HashMap<String, Port>(); Map<String, String> attributes = new HashMap<String, String>(); attributes.put("physical_id", "PhysicalId"); Node firstNode = new Node("1", "NodeId", ports, attributes); target.putNode("NodeId", firstNode); Node node = new Node("1", "NodeId", ports, attributes); /* * test */ Response result = target.putNodePhysicalId("PhysicalId", node); /* * check */ verify(target, atLeastOnce()).putNode(eq("NodeId"), (Node) anyObject()); Node resultNode = result.getBody(Node.class); // same message assertThat(result.statusCode, is(Response.OK)); assertThat(resultNode.getVersion(), is("1")); // assertThat(resultNode.getId(), is("NodeId")); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#putNodePhysicalId(java.lang.String, org.o3project.odenos.component.network.topology.TopologyObject.NodeMessage)} * . * * @throws Exception */ @Test public void testPutNodePhysicalIdWithInvalidPhysicalId() throws Exception { /* * test */ Node node = new Node(); Response result = target.putNodePhysicalId("PhysicalId", node); /* * check */ verify(target, times(1)).putNode(eq((String) null), (Node) anyObject()); assertThat(result.statusCode, is(Response.BAD_REQUEST)); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#deleteNodePhysicalId(java.lang.String, org.o3project.odenos.component.network.topology.TopologyObject.NodeMessage)} * . * * @throws Exception */ @Test public void testDeleteNodePhysicalId() throws Exception { /* * setting */ Map<String, Node> nodes = new HashMap<>(); Map<String, String> attributes1 = new HashMap<>(); attributes1.put("physical_id", "PhysicalId1"); Node node1 = new Node("1", "NodeId1", new HashMap<String, Port>(), attributes1); nodes.put("NodeId1", node1); Map<String, String> attributes2 = new HashMap<>(); attributes2.put("physical_id", "PhysicalId2"); Node node2 = new Node("1", "NodeId2", new HashMap<String, Port>(), attributes2); nodes.put("NodeId2", node2); Map<String, String> attributes3 = new HashMap<>(); attributes3.put("physical_id", "PhysicalId3"); Node node3 = new Node("1", "NodeId3", new HashMap<String, Port>(), attributes3); nodes.put("NodeId3", node3); Map<String, Link> links = new HashMap<>(); Topology settingTopology = new Topology(nodes, links); Whitebox.setInternalState(target, "topology", settingTopology); /* * test */ Response result = target.deleteNodePhysicalId("PhysicalId2", node2); /* * check */ verify(target, atLeastOnce()).deleteNode(eq("NodeId2"), (Node) anyObject()); assertThat(result.statusCode, is(Response.OK)); // FIXME is body null? // Node resultNode = result.getBody(Node.class); // assertThat(resultNode.getId(), is("NodeId2")); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#getPortPhysicalId(java.lang.String)} * . * * @throws Exception */ @Test public void testGetPortPhysicalId() throws Exception { /* * setting */ Map<String, Node> nodes = new HashMap<>(); Map<String, String> attributes1 = new HashMap<>(); attributes1.put("physical_id", "PhysicalId1"); Port port1 = new Port("1", "PortId1", "NodeId1", "OutLink1", "InLink1", attributes1); Map<String, Port> ports1 = new HashMap<>(); ports1.put("PortId1", port1); Node node1 = new Node("1", "NodeId1", ports1, new HashMap<String, String>()); nodes.put("NodeId1", node1); Map<String, String> attributes2 = new HashMap<>(); attributes2.put("physical_id", "PhysicalId2"); Port port2 = new Port("1", "PortId2", "NodeId2", "OutLink2", "InLink2", attributes2); Map<String, Port> ports2 = new HashMap<>(); ports2.put("PortId2", port2); Node node2 = new Node("1", "NodeId2", ports2, new HashMap<String, String>()); nodes.put("NodeId2", node2); Map<String, String> attributes3 = new HashMap<>(); attributes3.put("physical_id", "PhysicalId3"); Port port3 = new Port("1", "PortId2", "NodeId2", "OutLink2", "InLink2", attributes2); Map<String, Port> ports3 = new HashMap<>(); ports3.put("PortId3", port3); Node node3 = new Node("1", "NodeId3", ports2, new HashMap<String, String>()); nodes.put("NodeId3", node3); Map<String, Link> links = new HashMap<>(); Topology settingTopology = new Topology(nodes, links); Whitebox.setInternalState(target, "topology", settingTopology); /* * test */ Response result = target.getPortPhysicalId("PhysicalId2"); /* * check */ assertThat(result.statusCode, is(Response.OK)); Port resultPort = result.getBody(Port.class); assertThat(resultPort.getId(), is("PortId2")); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#getPortPhysicalId(java.lang.String)} * . */ @Test public void testGetPortPhysicalIdWithNotingPort() { /* * test */ Response result = target.getPortPhysicalId("PhysicalId"); /* * check */ assertThat(result.statusCode, is(Response.NOT_FOUND)); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#putPortPhysicalId(java.lang.String, org.o3project.odenos.component.network.topology.TopologyObject.PortMessage)} * . * * @throws Exception */ @Test public void testPutPortPhysicalId() throws Exception { /* * setting */ Map<String, Node> nodes = new HashMap<>(); Map<String, String> attributes1 = new HashMap<>(); attributes1.put("physical_id", "PhysicalId1"); Map<String, Port> ports1 = new HashMap<>(); ports1.put("PortId1", new Port("1", "PortId1", "NodeId1", "OutLink1", "InLink1", attributes1)); Node node1 = new Node("1", "NodeId1", ports1, new HashMap<String, String>()); nodes.put("NodeId1", node1); Map<String, Link> links = new HashMap<>(); Topology settingTopology = new Topology(nodes, links); Whitebox.setInternalState(target, "topology", settingTopology); /* * test */ Map<String, String> attributes = new HashMap<>(); attributes.put("physical_id", "PhysicalId11"); Port port = new Port("1", "PortId1", "NodeId1", "OutLink1", "InLink1", attributes); Response result = target.putPortPhysicalId("PhysicalId1", port); /* * check */ assertThat(result.statusCode, is(Response.OK)); // FIXME is body null? // Port resultPort = result.getBody(Port.class); // assertThat(resultPort.getId(), is("PortId1")); // assertThat(resultPort.getAttribute("physical_id"), is("PhysicalId11")); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#putPortPhysicalId(java.lang.String, org.o3project.odenos.component.network.topology.TopologyObject.PortMessage)} * . * * @throws Exception */ @Test public void testPutPortWithInvalidPhysicalId() throws Exception { /* * setting */ Map<String, Node> nodes = new HashMap<>(); Map<String, String> attributes1 = new HashMap<>(); attributes1.put("physical_id", "PhysicalId1"); Map<String, Port> ports1 = new HashMap<>(); ports1.put("PortId1", new Port("1", "PortId1", "NodeId1", "OutLink1", "InLink1", attributes1)); Node node1 = new Node("1", "NodeId1", ports1, new HashMap<String, String>()); nodes.put("NodeId1", node1); Map<String, Link> links = new HashMap<>(); Topology settingTopology = new Topology(nodes, links); Whitebox.setInternalState(target, "topology", settingTopology); /* * test */ Map<String, String> attributes = new HashMap<>(); attributes.put("physical_id", "PhysicalId11"); Port port = new Port("1", "PortId2", "NodeId1", "OutLink1", "InLink1", attributes); Response result = target.putPortPhysicalId("PhysicalId11", port); /* * check */ assertThat(result.statusCode, is(Response.CREATED)); // FIXME is body null? // Port resultPort = result.getBody(Port.class); // assertThat(resultPort.getId(), is("PortId1")); // assertThat(resultPort.getAttribute("physical_id"), is("PhysicalId11")); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#deletePortPhysicalId(java.lang.String, org.o3project.odenos.component.network.topology.TopologyObject.PortMessage)} * . * * @throws Exception */ @Test public void testDeletePortPhysicalId() throws Exception { /* * setting */ Map<String, Node> nodes = new HashMap<>(); Map<String, String> attributes1 = new HashMap<>(); attributes1.put("physical_id", "PhysicalId1"); Map<String, Port> ports1 = new HashMap<>(); ports1.put("PortId1", new Port("1", "PortId1", "NodeId1", null, null, attributes1)); Node node1 = new Node("1", "NodeId1", ports1, new HashMap<String, String>()); nodes.put("NodeId1", node1); Map<String, Link> links = new HashMap<>(); Topology settingTopology = new Topology(nodes, links); Whitebox.setInternalState(target, "topology", settingTopology); /* * test */ Map<String, String> attributes = new HashMap<>(); attributes.put("physical_id", "PhysicalId1"); Port port = new Port("1", "PortId1", "NodeId1", "OutLink1", "InLink1", attributes); Response result = target.deletePortPhysicalId("PhysicalId1", port); /* * check */ assertThat(result.statusCode, is(Response.OK)); // FIXME is body null? // Port resultPort = result.getBody(Port.class); // assertThat(resultPort.getId(), is("PortId1")); // assertThat(resultPort.getAttribute("physical_id"), is("PhysicalId11")); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#postLink(org.o3project.odenos.component.network.topology.TopologyObject.LinkMessage)} * . * * @throws Exception */ @Test public void testPostLink() throws Exception { /* * setting */ createNodePortForLink(); /* * test */ Link link = new Link("LinkId", "SrcNodeId", "SrcPortId", "DstNodeId", "DstPortId"); Response result = target.postLink(link); /* * check */ // assertThat(result.statusCode, is(Response.CREATED)); assertThat(result.statusCode, is(Response.OK)); Link resultLink = result.getBody(Link.class); assertThat(resultLink.getId(), is(notNullValue())); assertThat(resultLink.getVersion(), is("1")); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#getLinks(boolean, java.lang.String)} * . */ @Test public void testGetLinks() { /* * setting */ Map<String, Link> links = new HashMap<>(); Map<String, String> attributes1 = new HashMap<>(); attributes1.put("attr", "attr1"); Link link1 = new Link("1", "LinkId1", "SrcNode1", "SrcPort1", "DstNode1", "DstPort1", attributes1); links.put("Link1", link1); Map<String, String> attributes2 = new HashMap<>(); attributes2.put("attr", "attr2"); Link link2 = new Link("1", "LinkId2", "SrcNode2", "SrcPort2", "DstNode2", "DstPort2", attributes2); links.put("Link2", link2); Map<String, String> attributes3 = new HashMap<>(); attributes3.put("attr", "attr3"); Link link3 = new Link("1", "LinkId3", "SrcNode3", "SrcPort3", "DstNode3", "DstPort3", attributes3); links.put("Link3", link3); Map<String, Node> nodes = new HashMap<>(); Topology topology = new Topology(nodes, links); Whitebox.setInternalState(target, "topology", topology); /* * test */ Response result = target.getLinks(true, "attributes=\"attr=attr2\""); /* * check */ assertThat(result.statusCode, is(Response.OK)); Map<String, Link> resultLinks = result.getBodyAsMap(Link.class); assertThat(resultLinks.size(), is(1)); assertThat(resultLinks.containsKey("LinkId2"), is(true)); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#getLinks(boolean, java.lang.String)} * . */ @Test public void testGetLinks_NoQuery() { /* * setting */ Map<String, Node> nodes = new HashMap<>(); Map<String, Link> links = new HashMap<>(); links.put("Link1", new Link("Link1")); links.put("Link2", new Link("Link2")); links.put("Link3", new Link("Link3")); Topology topology = new Topology(nodes, links); Whitebox.setInternalState(target, "topology", topology); /* * test */ Response result = target.getLinks(false, ""); /* * check */ assertThat(result.statusCode, is(Response.OK)); Map<String, Link> resultLinks = result.getBodyAsMap(Link.class); assertThat(resultLinks.size(), is(3)); assertThat(resultLinks.containsKey("Link1"), is(true)); assertThat(resultLinks.containsKey("Link2"), is(true)); assertThat(resultLinks.containsKey("Link3"), is(true)); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#getLink(java.lang.String)} * . */ @Test public void testGetLink_NothingLinkId() { /* * test */ Response result = target.getLink("LinkId"); /* * check */ assertThat(result.statusCode, is(Response.NOT_FOUND)); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#putLink(org.o3project.odenos.component.network.topology.TopologyObject.LinkMessage)} * . * * @throws Exception */ @Test public void testPutLink() throws Exception { /* * setting */ createNodePortForLink(); /* * test */ Link link = new Link("LinkId", "SrcNodeId", "SrcPortId", "DstNodeId", "DstPortId"); Response result = target.putLink(link.getId(), link); /* * check */ assertThat(result.statusCode, is(Response.CREATED)); Link resultLink = result.getBody(Link.class); assertThat(resultLink.getId(), is("LinkId")); assertThat(resultLink.getVersion(), is("1")); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#putLink(org.o3project.odenos.component.network.topology.TopologyObject.LinkMessage)} * . * * @throws Exception */ @Test public void testPutLinkAfterPut() throws Exception { /* * setting */ Map<String, Node> nodes = new HashMap<>(); Map<String, Port> srcPorts = new HashMap<>(); srcPorts.put("SrcPortId", new Port("SrcPortId")); Node settingSrcNode = new Node("1", "SrcNodeId", srcPorts, new HashMap<String, String>()); nodes.put("SrcNodeId", settingSrcNode); Map<String, Port> dstPorts = new HashMap<>(); dstPorts.put("DstPortId", new Port("DstPortId")); Node settingDstNode = new Node("1", "DstNodeId", dstPorts, new HashMap<String, String>()); nodes.put("DstNodeId", settingDstNode); Map<String, Link> links = new HashMap<>(); Link settingLink = new Link("LinkId", "SrcNodeId", "SrcPortId", "DstNodeId", "DstPortId"); settingLink.setVersion("1"); settingLink.putAttribute("Key", "Value"); links.put("LinkId", settingLink); Topology topology = new Topology(nodes, links); Whitebox.setInternalState(target, "topology", topology); /* * test */ Link link = new Link("LinkId", "SrcNodeId", "SrcPortId", "DstNodeId", "DstPortId"); link.setVersion("1"); link.putAttribute("Key", "NewValue"); Response result = target.putLink(link.getId(), link); /* * check */ assertThat(result.statusCode, is(Response.OK)); Link resultLink = result.getBody(Link.class); assertThat(resultLink.getId(), is("LinkId")); assertThat(resultLink.getVersion(), is("2")); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#putLink(org.o3project.odenos.component.network.topology.TopologyObject.LinkMessage)} * . * * @throws Exception */ @Test public void testPutLinkAfterPut_SameLink() throws Exception { /* * setting */ createNodePortForLink(); Link settingLink = new Link("LinkId", "SrcNodeId", "SrcPortId", "DstNodeId", "DstPortId"); Response settingResult = target.putLink(settingLink.getId(), settingLink); assertThat(settingResult.statusCode, is(Response.CREATED)); /* * test */ Link link = new Link("LinkId", "SrcNodeId", "SrcPortId", "DstNodeId", "DstPortId"); link.setVersion("1"); Response result = target.putLink(link.getId(), link); /* * check */ assertThat(result.statusCode, is(Response.OK)); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#deleteLink(java.lang.String, org.o3project.odenos.component.network.topology.TopologyObject.LinkMessage)} * . * * @throws Exception */ @Test public void testDeleteLink() throws Exception { /* * setting */ createNodePortForLink(); Link settingLink = new Link("LinkId", "SrcNodeId", "SrcPortId", "DstNodeId", "DstPortId"); Response settingResult = target.putLink(settingLink.getId(), settingLink); assertThat(settingResult.statusCode, is(Response.CREATED)); /* * test */ Link link = new Link("LinkId", "SrcNodeId", "SrcPortId", "DstNodeId", "DstPortId"); link.setVersion("1"); Response result = target.deleteLink("LinkId", link); /* * check */ assertThat(result.statusCode, is(Response.OK)); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#deleteLink(java.lang.String, org.o3project.odenos.component.network.topology.TopologyObject.LinkMessage)} * . * * @throws Exception */ @Test public void testDeleteLink_NothingLink() throws Exception { /* * test */ Link link = new Link(); Response result = target.deleteLink("LinkId", link); /* * check */ assertThat(result.statusCode, is(Response.NOT_FOUND)); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#postFlow(org.o3project.odenos.core.component.network.flow.FlowObject.FlowMessage)} * . * * @throws Exception */ @Test public void testPostFlow() throws Exception { /* * test */ Flow flow = new BasicFlow("FlowId", "Owner", true, "Priority"); flow.setStatus("none"); Response result = target.postFlow(flow); /* * check */ assertThat(result.statusCode, is(Response.OK)); Flow resultFlow = result.getBody(Flow.class); assertThat(resultFlow.getFlowId(), is(notNullValue())); assertThat(resultFlow.getVersion(), is("1")); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#postFlow(org.o3project.odenos.core.component.network.flow.FlowObject.FlowMessage)} * . * * @throws Exception */ @Test public void testPostFlow_DefaultConstructorFlow() throws Exception { /* * test */ Flow flow = new Flow(); Response result = target.postFlow(flow); /* * check */ assertThat(result.statusCode, is(Response.BAD_REQUEST)); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#getFlows(boolean, java.lang.String)} * . * * @throws Exception */ @Test public void testGetFlows() throws Exception { /* * setting */ Map<String, List<String>> priority = new HashMap<>(); Map<String, Flow> flows = new HashMap<>(); flows.put("FlowId1", new BasicFlow("FlowId1")); flows.put("FlowId2", new BasicFlow("FlowId2")); flows.put("FlowId3", new OFPFlow("FlowId3")); FlowSet flowSet = new FlowSet("1", priority, flows); Whitebox.setInternalState(target, "flowset", flowSet); /* * test */ Response result = target.getFlows(true, "type=BasicFlow"); /* * check */ assertThat(result.statusCode, is(Response.OK)); FlowSet resultFlowSet = result.getBody(FlowSet.class); Map<String, Flow> resultFlows = resultFlowSet.getFlows(); assertThat(resultFlows.size(), is(2)); assertThat(resultFlows.containsKey("FlowId1"), is(true)); assertThat(resultFlows.containsKey("FlowId2"), is(true)); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#getFlows(boolean, java.lang.String)} * . * * @throws Exception */ @Test public void testGetFlows_NoQuery() throws Exception { /* * setting */ Map<String, List<String>> priority = new HashMap<>(); Map<String, Flow> flows = new HashMap<>(); flows.put("Flow1", new Flow("FlowId1")); flows.put("Flow2", new Flow("FlowId2")); flows.put("Flow3", new Flow("FlowId3")); FlowSet flowSet = new FlowSet("1", priority, flows); Whitebox.setInternalState(target, "flowset", flowSet); /* * test */ Response result = target.getFlows(false, ""); /* * check */ assertThat(result.statusCode, is(Response.OK)); FlowSet resultFlowSet = result.getBody(FlowSet.class); Map<String, Flow> resultFlows = resultFlowSet.getFlows(); assertThat(resultFlows.size(), is(3)); assertThat(resultFlows.containsKey("Flow1"), is(true)); assertThat(resultFlows.containsKey("Flow2"), is(true)); assertThat(resultFlows.containsKey("Flow3"), is(true)); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#getFlow(java.lang.String)} * . */ @Test public void testGetFlow() { /* * test */ Response result = target.getFlow("FlowId"); /* * check */ assertThat(result.statusCode, is(Response.NOT_FOUND)); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#putFlow(java.lang.String, org.o3project.odenos.core.component.network.flow.FlowObject.FlowMessage)} * . * * @throws Exception */ @Test public void testPutFlow() throws Exception { /* * test */ Flow flow = new Flow(); Response result = target.putFlow("flowId", flow); /* * check */ assertThat(result.statusCode, is(Response.BAD_REQUEST)); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#deleteFlow(java.lang.String, org.o3project.odenos.core.component.network.flow.FlowObject.FlowMessage)} * . * * @throws Exception */ @Test public void testDeleteFlow() throws Exception { /* * test */ Flow flow = new Flow(); Response result = target.deleteFlow("FlowId", flow); /* * check */ assertThat(result.statusCode, is(Response.NOT_FOUND)); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#getPackets()}. * * @throws Exception */ @Test public void testGetPackets() throws Exception { /* * setting */ Packet settingInPacket = new InPacket(); Response settingInResponse = target.postInPacket(settingInPacket); assertThat(settingInResponse.statusCode, is(Response.OK)); Packet settingOutpacket = new OutPacket(); Response settingOutResponse = target.postOutPacket(settingOutpacket); assertThat(settingOutResponse.statusCode, is(Response.OK)); /* * test */ Response result = target.getPackets(); /* * check */ assertThat(result.statusCode, is(Response.OK)); PacketStatus resultPacket = result.getBody(PacketStatus.class); assertThat(resultPacket.getInStatus().getPacketCount(), is(1L)); assertThat(resultPacket.getOutStatus().getPacketCount(), is(1L)); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#getPackets()}. * * @throws Exception */ @Test public void testGetPackets_NoPacket() throws Exception { /* * test */ Response result = target.getPackets(); /* * check */ assertThat(result.statusCode, is(Response.OK)); PacketStatus resultPacket = result.getBody(PacketStatus.class); assertThat(resultPacket.getInStatus().getPacketCount(), is(0L)); assertThat(resultPacket.getOutStatus().getPacketCount(), is(0L)); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#postInPacket(org.o3project.odenos.core.component.network.packet.PacketObject.PacketMessage)} * . * * @throws Exception */ @Test public void testPostInPacket() throws Exception { /* * test */ Packet packet = new InPacket(); Response result = target.postInPacket(packet); /* * check */ assertThat(result.statusCode, is(Response.OK)); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#postInPacket(org.o3project.odenos.core.component.network.packet.PacketObject.PacketMessage)} * . * * @throws Exception */ @Test public void testPostInPacket_ArgumentPacket() throws Exception { /* * test */ Packet packet = new Packet() { @Override public String getType() { return null; } }; Response result = target.postInPacket(packet); /* * check */ assertThat(result.statusCode, is(Response.BAD_REQUEST)); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#postInPacket(org.o3project.odenos.core.component.network.packet.PacketObject.PacketMessage)} * . * * @throws Exception */ @Test public void testPostInPacket_ArgumentOutPacket() throws Exception { /* * test */ Packet packet = new OutPacket(); Response result = target.postInPacket(packet); /* * check */ // FIXME check status code. // assertThat(result.statusCode, is(Response.BAD_REQUEST)); assertThat(result.statusCode, is(Response.OK)); assertThat(result.getBody(Packet.class), is(notNullValue())); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#getInPacket(boolean, java.lang.String)} * . * * @throws Exception */ @Test public void testGetInPacketBooleanString_NoQuery() throws Exception { /* * setting */ Packet packet = new InPacket(); Response settingResponse = target.postInPacket(packet); assertThat(settingResponse.statusCode, is(Response.OK)); /* * test */ Response result = target.getInPacket(false, ""); /* * check */ assertThat(result.statusCode, is(Response.OK)); PacketStatus packetStatus = result.getBody(PacketStatus.class); assertThat(packetStatus.getInStatus().getPacketCount(), is(1L)); assertThat(packetStatus.getOutStatus().getPacketCount(), is(0L)); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#getInPacket(boolean, java.lang.String)} * . * * @throws Exception */ @Test public void testGetInPacketBooleanString_NoQuery_NoPacket() throws Exception { /* * test */ Response result = target.getInPacket(false, ""); /* * check */ assertThat(result.statusCode, is(Response.OK)); PacketStatus packetStatus = result.getBody(PacketStatus.class); assertThat(packetStatus.getInStatus().getPacketCount(), is(0L)); assertThat(packetStatus.getOutStatus().getPacketCount(), is(0L)); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#getInPacket(boolean, java.lang.String)} * . * * @throws Exception */ @Test public void testGetInPacketBooleanString_HasQuery() throws Exception { /* * setting */ Packet packet = new InPacket(); Response settingResponse = target.postInPacket(packet); assertThat(settingResponse.statusCode, is(Response.OK)); /* * test */ Response result = target.getInPacket(true, ""); /* * check */ assertThat(result.statusCode, is(Response.BAD_REQUEST)); // assertThat(result.getBody(Object.class), is(notNullValue())); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#deleteInPackets()}. */ @Test public void testDeleteInPackets() { InPacketQueue inPacketQueue = Mockito.spy(new InPacketQueue()); PacketQueueSet queueSet = Mockito.spy(new PacketQueueSet()); Whitebox.setInternalState(queueSet, "inQueue", inPacketQueue); Whitebox.setInternalState(target, "packetQueue", queueSet); /* * test */ Response result = target.deleteInPackets(); /* * check */ verify(inPacketQueue, times(1)).clearPackets(); assertThat(result.statusCode, is(Response.OK)); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#getHeadInPacket()}. * * @throws Exception */ @Test public void testGetHeadInPacket() throws Exception { /* * setting */ Packet packet = new InPacket(); Response settingResult = target.postInPacket(packet); assertThat(settingResult.statusCode, is(Response.OK)); /* * test */ Response result = target.getHeadInPacket(); /* * check */ assertThat(result.statusCode, is(Response.OK)); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#getHeadInPacket()}. */ @Test public void testGetHeadInPacket_NoContent() { /* * test */ Response result = target.getHeadInPacket(); /* * check */ assertThat(result.statusCode, is(Response.NO_CONTENT)); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#deleteHeadInPacket()} * . * * @throws Exception */ @Test public void testDeleteHeadInPacket() throws Exception { /* * setting */ Packet packet = new InPacket(); Response settingResult = target.postInPacket(packet); assertThat(settingResult.statusCode, is(Response.OK)); /* * test */ Response result = target.deleteHeadInPacket(); /* * check */ assertThat(result.statusCode, is(Response.OK)); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#deleteHeadInPacket()} * . */ @Test public void testDeleteHeadInPacket_NoContent() { /* * test */ Response result = target.deleteHeadInPacket(); /* * check */ assertThat(result.statusCode, is(Response.NO_CONTENT)); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#getInPacket(java.lang.String)} * . * * @throws Exception */ @Test public void testGetInPacketString() throws Exception { /* * setting */ Packet packet = new InPacket("InPacketId", "NodeId", "PortId", null, null); PacketQueueSet packetQueueSet = Mockito.spy(new PacketQueueSet()); InPacketQueue inPacketQueue = Mockito.mock(InPacketQueue.class); doReturn(inPacketQueue).when(packetQueueSet).getInQueue(); doReturn(packet).when(inPacketQueue).getPacket("InPacketId"); Whitebox.setInternalState(target, "packetQueue", packetQueueSet); /* * test */ Response result = target.getInPacket("InPacketId"); /* * check */ assertThat(result.statusCode, is(Response.OK)); Packet resultPacket = result.getBody(Packet.class); assertThat(resultPacket.getPacketId(), is("InPacketId")); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#getInPacket(java.lang.String)} * . */ @Test public void testGetInPacketString_NothingInPacketId() { /* * test */ Response result = target.getInPacket("InPacketId"); /* * check */ assertThat(result.statusCode, is(Response.NOT_FOUND)); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#deleteInPacket(java.lang.String)} * . * * @throws Exception */ @Test public void testDeleteInPacket() throws Exception { /* * setting */ Packet packet = new InPacket(); Response settingResult = target.postInPacket(packet); assertThat(settingResult.statusCode, is(Response.OK)); /* * test */ Response result = target.deleteInPacket("InPacketId"); /* * check */ assertThat(result.statusCode, is(Response.OK)); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#deleteInPacket(java.lang.String)} * . */ @Test public void testDeleteInPacket_NoContent() { /* * test */ Response result = target.deleteInPacket("InPacketId"); /* * check */ assertThat(result.statusCode, is(Response.OK)); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#postOutPacket(org.o3project.odenos.core.component.network.packet.PacketObject.PacketMessage)} * . * * @throws Exception */ @Test public void testPostOutPacket() throws Exception { /* * test */ Packet packet = new OutPacket(); /* * test */ Response result = target.postOutPacket(packet); /* * check */ assertThat(result.statusCode, is(Response.OK)); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#getOutPacket(boolean, java.lang.String)} * . * * @throws Exception */ @Test public void testGetOutPacketBooleanString_NoQuery() throws Exception { /* * setting */ Packet packet = new OutPacket(); Response settingResponse = target.postOutPacket(packet); assertThat(settingResponse.statusCode, is(Response.OK)); /* * test */ Response result = target.getOutPacket(false, ""); /* * check */ assertThat(result.statusCode, is(Response.OK)); PacketStatus resultPacketStatus = result.getBody(PacketStatus.class); assertThat(resultPacketStatus.getInStatus().getPacketCount(), is(0L)); assertThat(resultPacketStatus.getOutStatus().getPacketCount(), is(1L)); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#getOutPacket(boolean, java.lang.String)} * . * * @throws Exception */ @Test public void testGetOutPacketBooleanString_NoQuery_NoPacket() throws Exception { /* * test */ Response result = target.getOutPacket(false, ""); /* * check */ assertThat(result.statusCode, is(Response.OK)); PacketStatus resultPacketStatus = result.getBody(PacketStatus.class); assertThat(resultPacketStatus.getInStatus().getPacketCount(), is(0L)); assertThat(resultPacketStatus.getOutStatus().getPacketCount(), is(0L)); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#getOutPacket(boolean, java.lang.String)} * . * * @throws Exception */ @Test public void testGetOutPacketBooleanString_HasQuery() throws Exception { /* * setting */ Packet packet = new OutPacket(); Response settingResponse = target.postOutPacket(packet); assertThat(settingResponse.statusCode, is(Response.OK)); /* * test */ Response result = target.getOutPacket(true, ""); /* * check */ assertThat(result.statusCode, is(Response.BAD_REQUEST)); // assertThat(result.getBody(Object.class), is(notNullValue())); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#deleteOutPackets()} * . */ @Test public void testDeleteOutPackets() { /* * test */ Response result = target.deleteOutPackets(); /* * check */ assertThat(result.statusCode, is(Response.OK)); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#getHeadOutPacket()} * . * * @throws Exception */ @Test public void testGetHeadOutPacket() throws Exception { /* * setting */ Packet settingOutPacket = new OutPacket(); Response settingResponse = target.postOutPacket(settingOutPacket); assertThat(settingResponse.statusCode, is(Response.OK)); /* * test */ Response result = target.getHeadOutPacket(); /* * check */ assertThat(result.statusCode, is(Response.OK)); Packet resultPacket = result.getBody(Packet.class); assertThat(resultPacket.isBodyNull(), is(true)); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#deleteHeadOutPacket()} * . */ @Test public void testDeleteHeadOutPacket() { /* * test */ Response result = target.deleteHeadOutPacket(); /* * check */ assertThat(result.statusCode, is(Response.NO_CONTENT)); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#getOutPacket(java.lang.String)} * . * * @throws Exception */ @Test public void testGetOutPacketString() throws Exception { /* * setting */ Packet settingOutPacket = new OutPacket("OutPacketId", "NodeId", null, null, null, null); PacketQueueSet packetQueueSet = Mockito.spy(new PacketQueueSet()); OutPacketQueue outPacketQueue = Mockito.mock(OutPacketQueue.class); doReturn(outPacketQueue).when(packetQueueSet).getOutQueue(); doReturn(settingOutPacket).when(outPacketQueue) .getPacket("OutPacketId"); Whitebox.setInternalState(target, "packetQueue", packetQueueSet); /* * test */ Response result = target.getOutPacket("OutPacketId"); /* * check */ assertThat(result.statusCode, is(Response.OK)); Packet resultPacket = result.getBody(Packet.class); assertThat(resultPacket.isBodyNull(), is(true)); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#getOutPacket(java.lang.String)} * . * * @throws Exception */ @Test public void testGetOutPacketStringWithNothingPacket() throws Exception { /* * test */ Response result = target.getOutPacket("OutPacketId"); /* * check */ assertThat(result.statusCode, is(Response.NOT_FOUND)); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#deleteOutPacket(java.lang.String)} * . */ @Test public void testDeleteOutPacketWithNothingPacket() { /* * test */ Response result = target.deleteOutPacket("OutPacketId"); /* * check */ assertThat(result.statusCode, is(Response.OK)); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#postEvent(java.lang.String, java.lang.Object)} * . * * @throws Exception */ @Test public void testPostEvent() throws Exception { /* * test */ Response result = target.postEvent("EventType", new Object()); /* * check */ assertThat(result.statusCode, is(Response.ACCEPTED)); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#postEvent(java.lang.String, java.lang.Object)} * . * * @throws Exception */ @Test public void testPostEventWithNullEvent() throws Exception { /* * test */ Response result = target.postEvent(null, new Object()); /* * check */ assertThat(result.statusCode, is(Response.ACCEPTED)); } /** * Test method for * {@link org.o3project.odenos.core.component.network.Network#postEvent(java.lang.String, java.lang.Object)} * . * * @throws Exception */ @Test public void testPostEventWithNullObject() throws Exception { /* * test */ Response result = target.postEvent("EventType", null); /* * check */ assertThat(result.statusCode, is(Response.ACCEPTED)); } /** * Test method for {@link org.o3project.odenos.core.component.network.Network#validateLinkMessage(Link)}. * * @throws Exception */ @Test public void testValidateLinkMessage() throws Exception { /* * setting */ Map<String, Node> nodes = new HashMap<>(); Map<String, Port> ports1 = new HashMap<>(); ports1.put("SrcPort", new Port("SrcPort", "SrcNode")); Node srcNode = new Node("1", "SrcNode", ports1, new HashMap<String, String>()); nodes.put("SrcNode", srcNode); Map<String, Port> ports2 = new HashMap<>(); ports2.put("DstPort", new Port("DstPort", "DstNode")); Node dstNode = new Node("1", "DstNode", ports2, new HashMap<String, String>()); nodes.put("DstNode", dstNode); Map<String, Link> links = new HashMap<>(); Topology topology = new Topology(nodes, links); Whitebox.setInternalState(target, "topology", topology); Link link = new Link("LinkId", "SrcNode", "SrcPort", "DstNode", "DstPort"); /* * test */ String result = Whitebox.invokeMethod(target, "validateLinkMessage", link); /* * check */ assertThat(result, is(nullValue())); } /** * Test method for {@link org.o3project.odenos.core.component.network.Network#validateLinkMessage(Link)}. * * @throws Exception */ @Test public void testValidateLinkMessage_ExistsLink() throws Exception { /* * setting */ Map<String, Node> nodes = new HashMap<>(); Map<String, Port> ports1 = new HashMap<>(); ports1.put("SrcPort", new Port("SrcPort", "SrcNode")); Node srcNode = new Node("1", "SrcNode", ports1, new HashMap<String, String>()); nodes.put("SrcNode", srcNode); Map<String, Port> ports2 = new HashMap<>(); ports2.put("DstPort", new Port("DstPort", "DstNode")); Node dstNode = new Node("1", "DstNode", ports2, new HashMap<String, String>()); nodes.put("DstNode", dstNode); Map<String, Link> links = new HashMap<>(); Link settingLink = new Link("LinkId", "SrcNode", "SrcPort", "DstNode", "DstPort"); links.put("LinkId", settingLink); Topology topology = new Topology(nodes, links); Whitebox.setInternalState(target, "topology", topology); Link link = new Link("LinkId", "SrcNode", "SrcPort", "DstNode", "DstPort"); /* * test */ String result = Whitebox.invokeMethod(target, "validateLinkMessage", link); /* * check */ assertThat(result.contains("the link"), is(true)); } /** * Test method for {@link org.o3project.odenos.core.component.network.Network#validateLinkMessage(Link)}. * * @throws Exception */ @Test public void testValidateLinkMessage_InvalidNode() throws Exception { /* * setting */ Map<String, Node> nodes = new HashMap<>(); Map<String, Port> ports1 = new HashMap<>(); ports1.put("SrcPort", new Port("SrcPort", "SrcNode")); Node srcNode = new Node("1", "SrcNode", ports1, new HashMap<String, String>()); nodes.put("SrcNode", srcNode); Map<String, Port> ports2 = new HashMap<>(); ports2.put("DstPort", new Port("DstPort", "DstNode")); Node dstNode = new Node("1", "DstNode", ports2, new HashMap<String, String>()); nodes.put("DstNode", dstNode); Map<String, Link> links = new HashMap<>(); Topology topology = new Topology(nodes, links); Whitebox.setInternalState(target, "topology", topology); Link linkInvalidSrcNode = new Link("LinkId", "InvalidNode", "SrcPort", "DstNode", "DstPort"); Link linkInvalidDstNode = new Link("LinkId", "SrcNode", "SrcPort", "InvalidNode", "DstPort"); /* * test */ String resultInvalidSrcNode = Whitebox.invokeMethod(target, "validateLinkMessage", linkInvalidSrcNode); String resultInvalidDstNode = Whitebox.invokeMethod(target, "validateLinkMessage", linkInvalidDstNode); /* * check */ assertThat(resultInvalidSrcNode.contains("the src node"), is(true)); assertThat(resultInvalidDstNode.contains("the dst node"), is(true)); } /** * Test method for {@link org.o3project.odenos.core.component.network.Network#validateLinkMessage(Link)}. * * @throws Exception */ @Test public void testValidateLinkMessage_InvalidPort() throws Exception { /* * setting */ Map<String, Node> nodes = new HashMap<>(); Map<String, Port> ports1 = new HashMap<>(); ports1.put("SrcPort", new Port("SrcPort", "SrcNode")); Node srcNode = new Node("1", "SrcNode", ports1, new HashMap<String, String>()); nodes.put("SrcNode", srcNode); Map<String, Port> ports2 = new HashMap<>(); ports2.put("DstPort", new Port("DstPort", "DstNode")); Node dstNode = new Node("1", "DstNode", ports2, new HashMap<String, String>()); nodes.put("DstNode", dstNode); Map<String, Link> links = new HashMap<>(); Topology topology = new Topology(nodes, links); Whitebox.setInternalState(target, "topology", topology); Link linkInvalidSrcPort = new Link("LinkId", "SrcNode", "InvalidPort", "DstNode", "DstPort"); Link linkInvalidDstPort = new Link("LinkId", "SrcNode", "SrcPort", "SrcNode", "InvaluePort"); /* * test */ String resultInvalidSrcPort = Whitebox.invokeMethod(target, "validateLinkMessage", linkInvalidSrcPort); String resultInvalidDstPort = Whitebox.invokeMethod(target, "validateLinkMessage", linkInvalidDstPort); /* * check */ assertThat(resultInvalidSrcPort.contains("the src port"), is(true)); assertThat(resultInvalidDstPort.contains("the dst port"), is(true)); } /** * Test method for {@link org.o3project.odenos.core.component.network.Network#checkFlowSequence(Method, Boolean, FlowStatus, Boolean, FlowStatus)}. * * @throws Exception */ @Test public void testCheckFlowSequence_Post() throws Exception { /* * setting */ Method method = Method.POST; Boolean preEnabled = null; FlowStatus preStatus = null; Boolean postEnabled = true; FlowStatus postStatus = FlowStatus.NONE; /* * test */ Enum<?> result = Whitebox.invokeMethod(target, "checkFlowSequence", method, preEnabled, preStatus, postEnabled, postStatus); /* * check */ assertThat(result.name(), is("CREATE_WITH_EVENT")); } /** * Test method for {@link org.o3project.odenos.core.component.network.Network#checkFlowSequence(Method, Boolean, FlowStatus, Boolean, FlowStatus)}. * * @throws Exception */ @Test public void testCheckFlowSequence_Put() throws Exception { /* * setting */ Method method = Method.PUT; /* * test & check */ /* test 1 */ Boolean preEnabled1 = null; FlowStatus preStatus1 = null; Boolean postEnabled1 = true; FlowStatus postStatus1 = FlowStatus.NONE; Enum<?> result1 = Whitebox.invokeMethod(target, "checkFlowSequence", method, preEnabled1, preStatus1, postEnabled1, postStatus1); assertThat(result1.name(), is("CREATE_WITH_EVENT")); /* test 2 */ Boolean preEnabled2 = true; FlowStatus preStatus2 = FlowStatus.NONE; Boolean postEnabled2 = true; FlowStatus postStatus2 = FlowStatus.ESTABLISHING; Enum<?> result2 = Whitebox.invokeMethod(target, "checkFlowSequence", method, preEnabled2, preStatus2, postEnabled2, postStatus2); assertThat(result2.name(), is("UPDATE_WITH_EVENT")); /* test 3 */ Boolean preEnabled3 = true; FlowStatus preStatus3 = FlowStatus.ESTABLISHING; Boolean postEnabled3 = true; FlowStatus postStatus3 = FlowStatus.ESTABLISHED; Enum<?> result3 = Whitebox.invokeMethod(target, "checkFlowSequence", method, preEnabled3, preStatus3, postEnabled3, postStatus3); assertThat(result3.name(), is("UPDATE_WITH_EVENT")); /* test 4 */ Boolean preEnabled4 = true; FlowStatus preStatus4 = FlowStatus.ESTABLISHED; Boolean postEnabled4 = true; FlowStatus postStatus4 = FlowStatus.TEARDOWN; Enum<?> result4 = Whitebox.invokeMethod(target, "checkFlowSequence", method, preEnabled4, preStatus4, postEnabled4, postStatus4); assertThat(result4.name(), is("UPDATE_WITHOUT_EVENT")); /* test 5 */ Boolean preEnabled5 = true; FlowStatus preStatus5 = FlowStatus.TEARDOWN; Boolean postEnabled5 = true; FlowStatus postStatus5 = FlowStatus.NONE; Enum<?> result5 = Whitebox.invokeMethod(target, "checkFlowSequence", method, preEnabled5, preStatus5, postEnabled5, postStatus5); assertThat(result5.name(), is("DELETE_WITHOUT_EVENT")); /* test 6 */ Boolean preEnabled6 = false; FlowStatus preStatus6 = FlowStatus.ESTABLISHED; Boolean postEnabled6 = false; FlowStatus postStatus6 = FlowStatus.TEARDOWN; Enum<?> result6 = Whitebox.invokeMethod(target, "checkFlowSequence", method, preEnabled6, preStatus6, postEnabled6, postStatus6); assertThat(result6.name(), is("UPDATE_WITH_EVENT")); /* test 7 */ Boolean preEnabled7 = false; FlowStatus preStatus7 = FlowStatus.TEARDOWN; Boolean postEnabled7 = false; FlowStatus postStatus7 = FlowStatus.NONE; Enum<?> result7 = Whitebox.invokeMethod(target, "checkFlowSequence", method, preEnabled7, preStatus7, postEnabled7, postStatus7); assertThat(result7.name(), is("UPDATE_WITH_EVENT")); /* test 8 */ Boolean preEnabled8 = true; FlowStatus preStatus8 = FlowStatus.FAILED; Boolean postEnabled8 = true; FlowStatus postStatus8 = FlowStatus.TEARDOWN; Enum<?> result8 = Whitebox.invokeMethod(target, "checkFlowSequence", method, preEnabled8, preStatus8, postEnabled8, postStatus8); assertThat(result8.name(), is("UPDATE_WITH_EVENT")); } /** * Test method for {@link org.o3project.odenos.core.component.network.Network#checkFlowSequence(Method, Boolean, FlowStatus, Boolean, FlowStatus)}. * * @throws Exception */ @Test public void testCheckFlowSequence_Delete() throws Exception { /* * setting */ Method method = Method.DELETE; Boolean preEnabled1 = true; FlowStatus preStatus1 = FlowStatus.ESTABLISHED; Boolean postEnabled1 = true; FlowStatus postStatus1 = FlowStatus.ESTABLISHED; Boolean preEnabled2 = true; FlowStatus preStatus2 = FlowStatus.FAILED; Boolean postEnabled2 = true; FlowStatus postStatus2 = FlowStatus.FAILED; Boolean preEnabled3 = true; FlowStatus preStatus3 = FlowStatus.ESTABLISHED; Boolean postEnabled3 = true; FlowStatus postStatus3 = FlowStatus.FAILED; /* * test */ Enum<?> result1 = Whitebox.invokeMethod(target, "checkFlowSequence", method, preEnabled1, preStatus1, postEnabled1, postStatus1); Enum<?> result2 = Whitebox.invokeMethod(target, "checkFlowSequence", method, preEnabled2, preStatus2, postEnabled2, postStatus2); Enum<?> result3 = Whitebox.invokeMethod(target, "checkFlowSequence", method, preEnabled3, preStatus3, postEnabled3, postStatus3); /* * check */ assertThat(result1.name(), is("DELETE_EVENT_ONLY")); assertThat(result2.name(), is("DELETE_EVENT_ONLY")); assertThat(result3.name(), is("DELETE_EVENT_ONLY")); } /** * Test method for {@link org.o3project.odenos.core.component.network.Network#postPacket(PacketQueue, Packet)}. * * @throws Exception */ @Test public void testPostPacket_InQueue() throws Exception { /* * setting */ createPowerSpy(); PacketQueueSet packetQueueSet = Whitebox.getInternalState(target, "packetQueue"); InPacketQueue queue = Whitebox.getInternalState(packetQueueSet, "inQueue"); Packet packet = new InPacket("PacketId", "NodeId", "PortId", "data".getBytes(), new HashMap<String, String>()); PowerMockito.doReturn(new Response(Response.OK, "Body")).when(target, "notifyInPacketAdded", (Packet) anyObject()); /* * test */ Response result = Whitebox.invokeMethod(target, "postPacket", queue, packet); /* * check */ PowerMockito.verifyPrivate(target).invoke("notifyInPacketAdded", anyObject()); assertThat(result.statusCode, is(Response.OK)); } /** * Test method for {@link org.o3project.odenos.core.component.network.Network#postPacket(PacketQueue, Packet)}. * * @throws Exception */ @Test public void testPostPacket_OutQueue() throws Exception { /* * setting */ createPowerSpy(); PacketQueueSet packetQueueSet = Whitebox.getInternalState(target, "packetQueue"); OutPacketQueue queue = Whitebox.getInternalState(packetQueueSet, "outQueue"); Packet packet = new OutPacket("PacketId", "NodeId", new ArrayList<String>(), new ArrayList<String>(), "data".getBytes(), new HashMap<String, String>()); PowerMockito.doReturn(new Response(Response.OK, "Body")).when(target, "notifyOutPacketAdded", (Packet) anyObject()); /* * test */ Response result = Whitebox.invokeMethod(target, "postPacket", queue, packet); /* * check */ PowerMockito.verifyPrivate(target).invoke("notifyOutPacketAdded", anyObject()); assertThat(result.statusCode, is(Response.OK)); } /** * Test method for {@link org.o3project.odenos.core.component.network.Network#getPacket(PacketQueue, boolean, String)}. * * @throws Exception */ @Test public void testGetPacket_InPacket() throws Exception { /* * setting */ PacketQueue packetQueue = new InPacketQueue(); Map<String, String> attributes = new HashMap<>(); attributes.put("Key1", "Value1"); Packet packet = new InPacket("PacketId", "NodeId", "PortId", "data".getBytes(), attributes); packetQueue.enqueuePacket(packet); /* * test */ Response result = Whitebox.invokeMethod(target, "getPacket", packetQueue, true, "attributes=\"Key1=Value1\""); /* * check */ assertThat(result.statusCode, is(Response.OK)); @SuppressWarnings("unchecked") Map<String, Packet> resultPackets = result.getBody(Map.class); assertThat(resultPackets.containsKey("0000000000"), is(true)); } /** * Test method for {@link org.o3project.odenos.core.component.network.Network#getPacket(PacketQueue, boolean, String)}. * * @throws Exception */ @Test public void testGetPacket_NoQuery() throws Exception { /* * setting */ PacketQueue packetQueue = new InPacketQueue(); packetQueue.enqueuePacket(new InPacket()); /* * test */ Response result = Whitebox.invokeMethod(target, "getPacket", packetQueue, false, ""); /* * check */ assertThat(result.statusCode, is(Response.OK)); PacketStatus packetStatus = result.getBody(PacketStatus.class); assertThat(packetStatus.getInStatus().getPacketCount(), is(1L)); assertThat(packetStatus.getOutStatus().getPacketCount(), is(0L)); } /** * Test method for {@link org.o3project.odenos.core.component.network.Network#getPacket(PacketQueue, boolean, String)}. * * @throws Exception */ @Test public void testGetPacket_OutPacket() throws Exception { /* * setting */ PacketQueue packetQueue = new OutPacketQueue(); Map<String, String> attributes = new HashMap<>(); attributes.put("Key1", "Value1"); Packet packet = new OutPacket("PacketId", "NodeId", new ArrayList<String>(), new ArrayList<String>(), "data".getBytes(), attributes); packetQueue.enqueuePacket(packet); /* * test */ Response result = Whitebox.invokeMethod(target, "getPacket", packetQueue, true, "attributes=\"Key1=Value1\""); /* * check */ assertThat(result.statusCode, is(Response.OK)); @SuppressWarnings("unchecked") Map<String, Packet> resultPackets = result.getBody(Map.class); assertThat(resultPackets.containsKey("0000000000"), is(true)); } /** * Test method for {@link org.o3project.odenos.core.component.network.Network#getPacket(PacketQueue, boolean, String)}. * * @throws Exception */ @Test public void testGetPacket_OutPacket_NoQuery() throws Exception { /* * setting */ PacketQueue packetQueue = new OutPacketQueue(); packetQueue.enqueuePacket(new OutPacket()); /* * test */ Response result = Whitebox.invokeMethod(target, "getPacket", packetQueue, false, ""); /* * check */ assertThat(result.statusCode, is(Response.OK)); PacketStatus packetStatus = result.getBody(PacketStatus.class); assertThat(packetStatus.getInStatus().getPacketCount(), is(0L)); assertThat(packetStatus.getOutStatus().getPacketCount(), is(1L)); } /** * Test method for {@link org.o3project.odenos.core.component.network.Network#deletePackets(PacketQueue)}. * * @throws Exception */ @Test public void testDeletePackets_InPacket() throws Exception { /* * setting */ PacketQueue queue = new InPacketQueue(); queue.enqueuePacket(new InPacket()); /* * test */ Response result = Whitebox.invokeMethod(target, "deletePackets", queue); /* * check */ assertThat(result.statusCode, is(Response.OK)); PacketStatus status = queue.getPacketStatus(); assertThat(status.getInStatus().packetQueueCount, is(0L)); } /** * Test method for {@link org.o3project.odenos.core.component.network.Network#deletePackets(PacketQueue)}. * * @throws Exception */ @Test public void testDeletePackets_OutPacket() throws Exception { /* * setting */ PacketQueue queue = new OutPacketQueue(); queue.enqueuePacket(new OutPacket()); /* * test */ Response result = Whitebox.invokeMethod(target, "deletePackets", queue); /* * check */ assertThat(result.statusCode, is(Response.OK)); PacketStatus status = queue.getPacketStatus(); assertThat(status.getOutStatus().packetQueueCount, is(0L)); } /** * Test method for {@link org.o3project.odenos.core.component.network.Network#getHeadPacket(PacketQueue)}. * * @throws Exception */ @Test public void testGetHeadPacket_InPacket() throws Exception { /* * setting */ PacketQueue queue = new InPacketQueue(); queue.enqueuePacket(new InPacket()); /* * test */ Response result = Whitebox.invokeMethod(target, "getHeadPacket", queue); /* * check */ assertThat(result.statusCode, is(Response.OK)); } /** * Test method for {@link org.o3project.odenos.core.component.network.Network#getHeadPacket(PacketQueue)}. * * @throws Exception */ @Test public void testGetHeadPacket_InPacket_NoConnect() throws Exception { /* * setting */ PacketQueue queue = new InPacketQueue(); /* * test */ Response result = Whitebox.invokeMethod(target, "getHeadPacket", queue); /* * check */ assertThat(result.statusCode, is(Response.NO_CONTENT)); } /** * Test method for {@link org.o3project.odenos.core.component.network.Network#getHeadPacket(PacketQueue)}. * * @throws Exception */ @Test public void testGetHeadPacket_OutPacket() throws Exception { /* * setting */ PacketQueue queue = new OutPacketQueue(); queue.enqueuePacket(new OutPacket()); /* * test */ Response result = Whitebox.invokeMethod(target, "getHeadPacket", queue); /* * check */ assertThat(result.statusCode, is(Response.OK)); } /** * Test method for {@link org.o3project.odenos.core.component.network.Network#getHeadPacket(PacketQueue)}. * * @throws Exception */ @Test public void testGetHeadPacket_OutPacket_NoConnect() throws Exception { /* * setting */ PacketQueue queue = new OutPacketQueue(); /* * test */ Response result = Whitebox.invokeMethod(target, "getHeadPacket", queue); /* * check */ assertThat(result.statusCode, is(Response.NO_CONTENT)); } /** * Test method for {@link org.o3project.odenos.core.component.network.Network#deleteHeadPacket(PacketQueue)}. * * @throws Exception */ @Test public void testDeleteHeadPacket_InPacket() throws Exception { /* * setting */ PacketQueue queue = new InPacketQueue(); queue.enqueuePacket(new InPacket()); /* * test */ Response result = Whitebox.invokeMethod(target, "deleteHeadPacket", queue); /* * check */ assertThat(result.statusCode, is(Response.OK)); } /** * Test method for {@link org.o3project.odenos.core.component.network.Network#deleteHeadPacket(PacketQueue)}. * * @throws Exception */ @Test public void testDeleteHeadPacket_InPacket_EmptyPacket() throws Exception { /* * setting */ PacketQueue queue = new InPacketQueue(); /* * test */ Response result = Whitebox.invokeMethod(target, "deleteHeadPacket", queue); /* * check */ assertThat(result.statusCode, is(Response.NO_CONTENT)); } /** * Test method for {@link org.o3project.odenos.core.component.network.Network#deleteHeadPacket(PacketQueue)}. * * @throws Exception */ @Test public void testDeleteHeadPacket_OutPacket() throws Exception { /* * setting */ PacketQueue queue = new OutPacketQueue(); queue.enqueuePacket(new OutPacket()); /* * test */ Response result = Whitebox.invokeMethod(target, "deleteHeadPacket", queue); /* * check */ assertThat(result.statusCode, is(Response.OK)); } /** * Test method for {@link org.o3project.odenos.core.component.network.Network#deleteHeadPacket(PacketQueue)}. * * @throws Exception */ @Test public void testDeleteHeadPacket_OutPacket_EmptyPacket() throws Exception { /* * setting */ PacketQueue queue = new OutPacketQueue(); /* * test */ Response result = Whitebox.invokeMethod(target, "deleteHeadPacket", queue); /* * check */ assertThat(result.statusCode, is(Response.NO_CONTENT)); } /** * Test method for {@link org.o3project.odenos.core.component.network.Network#getPacket(PacketQueue, String)}. * * @throws Exception */ @Test public void testGetPacketPacketQueueString() throws Exception { /* * setting */ PacketQueue packetQueue = new InPacketQueue(); Packet packet = new InPacket("PacketId", "Nodeid", "PortId", "data".getBytes(), new HashMap<String, String>()); packetQueue.enqueuePacket(packet); /* * test */ Response result = Whitebox.invokeMethod(target, "getPacket", packetQueue, "0000000000"); /* * check */ assertThat(result.statusCode, is(Response.OK)); } /** * Test method for {@link org.o3project.odenos.core.component.network.Network#getPacket(PacketQueue, String)}. * * @throws Exception */ @Test public void testGetPacketPacketQueueString_NoPacket() throws Exception { /* * setting */ PacketQueue packetQueue = new InPacketQueue(); /* * test */ Response result = Whitebox.invokeMethod(target, "getPacket", packetQueue, "0000000000"); /* * check */ assertThat(result.statusCode, is(Response.NOT_FOUND)); } /** * Test method for {@link org.o3project.odenos.core.component.network.Network#deletePacket(PacketQueue, String)}. * * @throws Exception */ @Test public void testDeletePacket_InQueue() throws Exception { /* * setting */ PacketQueue packetQueue = new InPacketQueue(); Packet packet = new InPacket("PacketId", "Nodeid", "PortId", "data".getBytes(), new HashMap<String, String>()); packetQueue.enqueuePacket(packet); /* * test */ Response result = Whitebox.invokeMethod(target, "deletePacket", packetQueue, "0000000000"); /* * check */ assertThat(result.statusCode, is(Response.OK)); Packet resultPacket = result.getBody(InPacket.class); assertThat(resultPacket.getPacketId(), is("0000000000")); } /** * Test method for {@link org.o3project.odenos.core.component.network.Network#deletePacket(PacketQueue, String)}. * * @throws Exception */ @Test public void testDeletePacket_InQueueEmpty() throws Exception { /* * setting */ PacketQueue packetQueue = new InPacketQueue(); /* * test */ Response result = Whitebox.invokeMethod(target, "deletePacket", packetQueue, "0000000000"); /* * check */ assertThat(result.statusCode, is(Response.OK)); } /** * Test method for {@link org.o3project.odenos.core.component.network.Network#deletePacket(PacketQueue, String)}. * * @throws Exception */ @Test public void testDeletePacket_OutQueue() throws Exception { /* * setting */ PacketQueue packetQueue = new OutPacketQueue(); Packet packet = new OutPacket("PacketId", "Nodeid", new ArrayList<String>(), new ArrayList<String>(), "data".getBytes(), new HashMap<String, String>()); packetQueue.enqueuePacket(packet); /* * test */ Response result = Whitebox.invokeMethod(target, "deletePacket", packetQueue, "0000000000"); /* * check */ assertThat(result.statusCode, is(Response.OK)); Packet resultPacket = result.getBody(InPacket.class); assertThat(resultPacket.getPacketId(), is("0000000000")); } /** * Test method for {@link org.o3project.odenos.core.component.network.Network#deletePacket(PacketQueue, String)}. * * @throws Exception */ @Test public void testDeletePacket_OutQueueEmpty() throws Exception { /* * setting */ PacketQueue packetQueue = new OutPacketQueue(); /* * test */ Response result = Whitebox.invokeMethod(target, "deletePacket", packetQueue, "0000000000"); /* * check */ assertThat(result.statusCode, is(Response.OK)); } /** * Test method for {@link org.o3project.odenos.core.component.network.Network#notifyTopologyChanged(Topology, Topology, Action)}. * * @throws Exception */ @Test public void testNotifyTopologyChanged() throws Exception { /* * setting */ Topology prev = new Topology(); Topology curr = new Topology(); TopologyChanged.Action action = TopologyChanged.Action.add; /* * test */ Response result = Whitebox.invokeMethod(target, "notifyTopologyChanged", prev, curr, action); /* * check */ verify(target).postEvent(eq("TopologyChanged"), (TopologyChanged) anyObject()); assertThat(result.statusCode, is(Response.ACCEPTED)); } /** * Test method for {@link org.o3project.odenos.core.component.network.Network#notifyTopologyChangedToAdd(Topology)}. * * @throws Exception */ @Test public void testNotifyTopologyChangedToAdd() throws Exception { /* * setting */ createPowerSpy(); Topology curr = new Topology(); /* * test */ Response result = Whitebox.invokeMethod(target, "notifyTopologyChangedToAdd", curr); /* * check */ PowerMockito.verifyPrivate(target).invoke("notifyTopologyChanged", (Topology) null, curr, TopologyChanged.Action.add); assertThat(result.statusCode, is(Response.ACCEPTED)); } /** * Test method for {@link org.o3project.odenos.core.component.network.Network#notifyTopologyChangedToUpdate(Topology, Topology)}. * * @throws Exception */ @Test public void testNotifyTopologyChangedToUpdate() throws Exception { /* * setting */ createPowerSpy(); Topology prev = new Topology(); Topology curr = new Topology(); /* * test */ Response result = Whitebox.invokeMethod(target, "notifyTopologyChangedToUpdate", prev, curr); /* * check */ PowerMockito.verifyPrivate(target).invoke("notifyTopologyChanged", prev, curr, TopologyChanged.Action.update); assertThat(result.statusCode, is(Response.ACCEPTED)); } /** * Test method for {@link org.o3project.odenos.core.component.network.Network#notifyNodeChanged(Node, Node, Action)}. * * @throws Exception */ @Test public void testNotifyNodeChanged() throws Exception { /* * setting */ Node prev = new Node("NodeIdPrev"); Node curr = new Node("NodeIdCurr"); NodeChanged.Action action = NodeChanged.Action.add; /* * test */ Response result = Whitebox.invokeMethod(target, "notifyNodeChanged", prev, curr, action); /* * check */ verify(target).postEvent(eq("NodeChanged"), (NodeChanged) anyObject()); assertThat(result.statusCode, is(Response.ACCEPTED)); } /** * Test method for {@link org.o3project.odenos.core.component.network.Network#notifyPortChanged(Port, Port, Action)}. * * @throws Exception */ @Test public void testNotifyPortChanged() throws Exception { /* * setting */ Port prev = new Port("PortIdPrev"); Port curr = new Port("PortIdCurr"); PortChanged.Action action = PortChanged.Action.add; /* * test */ Response result = Whitebox.invokeMethod(target, "notifyPortChanged", prev, curr, action); /* * check */ verify(target).postEvent(eq("PortChanged"), (PortChanged) anyObject()); assertThat(result.statusCode, is(Response.ACCEPTED)); } /** * Test method for {@link org.o3project.odenos.core.component.network.Network#notifyLinkChanged(Link, Link, Action)}. * * @throws Exception */ @Test public void testNotifyLinkChanged() throws Exception { /* * setting */ Link prev = new Link("LinkIdPrev"); Link curr = new Link("LinkIdCurr"); LinkChanged.Action action = LinkChanged.Action.add; /* * test */ Response result = Whitebox.invokeMethod(target, "notifyLinkChanged", prev, curr, action); /* * check */ verify(target).postEvent(eq("LinkChanged"), (LinkChanged) anyObject()); assertThat(result.statusCode, is(Response.ACCEPTED)); } /** * Test method for {@link org.o3project.odenos.core.component.network.Network#notifyFlowChanged(Flow, Flow, Action)}. * * @throws Exception */ @Test public void testNotifyFlowChanged() throws Exception { /* * setting */ Flow prev = new Flow("LinkIdPrev"); Flow curr = new Flow("LinkIdCurr"); FlowChanged.Action action = FlowChanged.Action.add; /* * test */ Response result = Whitebox.invokeMethod(target, "notifyFlowChanged", prev, curr, action); /* * check */ verify(target).postEvent(eq("FlowChanged"), (FlowChanged) anyObject()); assertThat(result.statusCode, is(Response.ACCEPTED)); } /** * Test method for {@link org.o3project.odenos.core.component.network.Network#notifyInPacketAdded(Packet)}. * * @throws Exception */ @Test public void testNotifyInPacketAdded() throws Exception { /* * setting */ Packet inPacket = new InPacket(); /* * test */ Response result = Whitebox.invokeMethod(target, "notifyInPacketAdded", inPacket); /* * check */ verify(target).postEvent(eq("InPacketAdded"), (InPacketAdded) anyObject()); assertThat(result.statusCode, is(Response.ACCEPTED)); } /** * Test method for {@link org.o3project.odenos.core.component.network.Network#notifyOutPacketAdded(Packet)}. * * @throws Exception */ @Test public void testNotifyOutPacketAdded() throws Exception { /* * setting */ Packet outPacket = new OutPacket(); /* * test */ Response result = Whitebox.invokeMethod(target, "notifyOutPacketAdded", outPacket); /* * check */ verify(target).postEvent(eq("OutPacketAdded"), (OutPacketAdded) anyObject()); assertThat(result.statusCode, is(Response.ACCEPTED)); } /** * Test method for {@link org.o3project.odenos.core.component.network.Network#getNodeByPhysicalId(String)}. * * @throws Exception */ @Test public void testGetNodeByPhysicalId() throws Exception { /* * setting */ Map<String, String> attributes1 = new HashMap<>(); attributes1.put("physical_id", "PhysicalId1"); Node node1 = new Node("1", "NodeId1", new HashMap<String, Port>(), attributes1); Map<String, String> attributes2 = new HashMap<String, String>(); attributes2.put("physical_id", "PhysicalId2"); Node node2 = new Node("1", "NodeId2", new HashMap<String, Port>(), attributes2); Map<String, String> attributes3 = new HashMap<String, String>(); attributes3.put("physical_id", "PhysicalId3"); Node node3 = new Node("1", "NodeId3", new HashMap<String, Port>(), attributes3); Map<String, Node> nodes = new HashMap<>(); nodes.put("NodeId1", node1); nodes.put("NodeId2", node2); nodes.put("NodeId3", node3); Map<String, Link> links = new HashMap<>(); Topology topology = new Topology(nodes, links); Whitebox.setInternalState(target, "topology", topology); /* * test */ String result = Whitebox.invokeMethod(target, "getNodeByPhysicalId", "PhysicalId2"); /* * check */ assertThat(result, is("NodeId2")); } /** * Test method for {@link org.o3project.odenos.core.component.network.Network#getPortByPhysicalId(String)}. * * @throws Exception */ @Test public void testGetPortByPhysicalId() throws Exception { /* * setting */ Map<String, Node> nodes = new HashMap<>(); Map<String, String> attributes1 = new HashMap<>(); attributes1.put("physical_id", "PhysicalId1"); Port port1 = new Port("1", "PortId1", "NodeId1", "OutLink1", "Inlink1", attributes1); Map<String, Port> ports1 = new HashMap<>(); ports1.put("PortId1", port1); Node node1 = new Node("1", "NodeId1", ports1, new HashMap<String, String>()); nodes.put("NodeId1", node1); Map<String, String> attributes2 = new HashMap<String, String>(); attributes2.put("physical_id", "PhysicalId2"); Port port2 = new Port("1", "PortId2", "NodeId2", "OutLink2", "Inlink2", attributes2); Map<String, Port> ports2 = new HashMap<>(); ports1.put("PortId2", port2); Node node2 = new Node("1", "NodeId2", ports2, new HashMap<String, String>()); nodes.put("NodeId2", node2); Map<String, String> attributes3 = new HashMap<String, String>(); attributes3.put("physical_id", "PhysicalId3"); Port port3 = new Port("1", "PortId2", "NodeId2", "OutLink2", "Inlink2", attributes2); Map<String, Port> ports3 = new HashMap<>(); ports1.put("PortId3", port3); Node node3 = new Node("1", "NodeId3", ports3, new HashMap<String, String>()); nodes.put("NodeId3", node3); Map<String, Link> links = new HashMap<>(); Topology topology = new Topology(nodes, links); Whitebox.setInternalState(target, "topology", topology); /* * test */ Port result = Whitebox.invokeMethod(target, "getPortByPhysicalId", "PhysicalId2"); /* * check */ assertThat(result.getId(), is("PortId2")); } /** * Test method for {@link org.o3project.odenos.core.component.network.Network#createParser()}. * * @throws Exception */ @Test public void testCreateParser() throws Exception { /* * test */ RequestParser<?> result = Whitebox.invokeMethod(target, "createParser"); /* * check */ assertThat(result, is(notNullValue())); Object state = Whitebox.getInternalState(result, "headState"); assertThat(state, is(notNullValue())); } /** * Test method for {@link org.o3project.odenos.core.component.network.Network#createErrorResponse(int, Object)}. * * @throws Exception */ @Test public void testCreateErrorResponseIntObject() throws Exception { /* * test */ Response result = Whitebox.invokeMethod(target, "createErrorResponse", Response.INTERNAL_SERVER_ERROR, "Body"); /* * check */ assertThat(result.statusCode, is(Response.INTERNAL_SERVER_ERROR)); assertThat(result.getBody(String.class), is("Body")); } /** * Test method for {@link org.o3project.odenos.core.component.network.Network#createErrorResponse(int, Object, String)}. * * @throws Exception */ @Test public void testCreateErrorResponseIntObjectString() throws Exception { /* * test */ Response result = Whitebox.invokeMethod(target, "createErrorResponse", Response.INTERNAL_SERVER_ERROR, "Body", "message"); /* * check */ assertThat(result.statusCode, is(Response.INTERNAL_SERVER_ERROR)); assertThat(result.getBody(String.class), is("Body")); } /** * Test method for {@link org.o3project.odenos.core.component.network.Network#isNeededVerboseNodeEvent()}. * * @throws Exception */ @Test public void testIsNeededVerboseNodeEvent() throws Exception { /* * test */ boolean result = Whitebox.invokeMethod(target, "isNeededVerboseNodeEvent"); /* * check */ assertThat(result, is(true)); } /** * Test method for {@link org.o3project.odenos.core.component.network.Network#isNeededVerbosePortEvent()}. * * @throws Exception */ @Test public void testIsNeededVerbosePortEvent() throws Exception { /* * test */ boolean result = Whitebox.invokeMethod(target, "isNeededVerbosePortEvent"); /* * check */ assertThat(result, is(true)); } private void createNodePortForLink() throws Exception { Node srcNode = new Node(); target.putNode("SrcNodeId", srcNode); Port srcPort = new Port(); target.putPort("SrcNodeId", "SrcPortId", srcPort); Node dstNode = new Node(); target.putNode("DstNodeId", dstNode); Port dstPort = new Port(); target.putPort("DstNodeId", "DstPortId", dstPort); } }
y-higuchi/odenos
src/test/java/org/o3project/odenos/core/component/network/NetworkTest.java
Java
apache-2.0
116,642
/* * Copyright 2007 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.parsing; import com.google.common.base.CharMatcher; import com.google.common.base.Preconditions; import com.google.common.base.Splitter; import com.google.common.collect.ImmutableSet; import com.google.javascript.jscomp.parsing.Config.LanguageMode; import com.google.javascript.rhino.ErrorReporter; import com.google.javascript.rhino.IR; import com.google.javascript.rhino.JSDocInfo; import com.google.javascript.rhino.JSDocInfo.Visibility; import com.google.javascript.rhino.JSDocInfoBuilder; import com.google.javascript.rhino.JSTypeExpression; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.SimpleErrorReporter; import com.google.javascript.rhino.StaticSourceFile; import com.google.javascript.rhino.Token; import com.google.javascript.rhino.TokenStream; import com.google.javascript.rhino.TokenUtil; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; /** * A parser for JSDoc comments. * * @author nicksantos@google.com (Nick Santos) */ // TODO(nicksantos): Unify all the JSDocInfo stuff into one package, instead of // spreading it across multiple packages. public final class JsDocInfoParser { private final JsDocTokenStream stream; private final JSDocInfoBuilder jsdocBuilder; private final StaticSourceFile sourceFile; private final ErrorReporter errorReporter; // Use a template node for properties set on all nodes to minimize the // memory footprint associated with these (similar to IRFactory). private final Node templateNode; private void addParserWarning(String messageId, String messageArg) { addParserWarning(messageId, messageArg, stream.getLineno(), stream.getCharno()); } private void addParserWarning(String messageId, String messageArg, int lineno, int charno) { errorReporter.warning( SimpleErrorReporter.getMessage1(messageId, messageArg), getSourceName(), lineno, charno); } private void addParserWarning(String messageId) { addParserWarning(messageId, stream.getLineno(), stream.getCharno()); } private void addParserWarning(String messageId, int lineno, int charno) { errorReporter.warning( SimpleErrorReporter.getMessage0(messageId), getSourceName(), lineno, charno); } private void addTypeWarning(String messageId, String messageArg) { addTypeWarning(messageId, messageArg, stream.getLineno(), stream.getCharno()); } private void addTypeWarning(String messageId, String messageArg, int lineno, int charno) { errorReporter.warning( "Bad type annotation. " + SimpleErrorReporter.getMessage1(messageId, messageArg), getSourceName(), lineno, charno); } private void addTypeWarning(String messageId) { addTypeWarning(messageId, stream.getLineno(), stream.getCharno()); } private void addTypeWarning(String messageId, int lineno, int charno) { errorReporter.warning( "Bad type annotation. " + SimpleErrorReporter.getMessage0(messageId), getSourceName(), lineno, charno); } private void addMissingTypeWarning(int lineno, int charno) { errorReporter.warning("Missing type declaration.", getSourceName(), lineno, charno); } // The DocInfo with the fileoverview tag for the whole file. private JSDocInfo fileOverviewJSDocInfo = null; private State state; private final Map<String, Annotation> annotationNames; private final Set<String> suppressionNames; private final boolean preserveWhitespace; private static final Set<String> modifiesAnnotationKeywords = ImmutableSet.of("this", "arguments"); private static final Set<String> idGeneratorAnnotationKeywords = ImmutableSet.of("unique", "consistent", "stable", "mapped", "xid"); private JSDocInfoBuilder fileLevelJsDocBuilder; /** * Sets the JsDocBuilder for the file-level (root) node of this parse. The * parser uses the builder to append any preserve annotations it encounters * in JsDoc comments. * * @param fileLevelJsDocBuilder */ void setFileLevelJsDocBuilder( JSDocInfoBuilder fileLevelJsDocBuilder) { this.fileLevelJsDocBuilder = fileLevelJsDocBuilder; } /** * Sets the file overview JSDocInfo, in order to warn about multiple uses of * the @fileoverview tag in a file. */ void setFileOverviewJSDocInfo(JSDocInfo fileOverviewJSDocInfo) { this.fileOverviewJSDocInfo = fileOverviewJSDocInfo; } private enum State { SEARCHING_ANNOTATION, SEARCHING_NEWLINE, NEXT_IS_ANNOTATION } JsDocInfoParser(JsDocTokenStream stream, String comment, int commentPosition, StaticSourceFile sourceFile, Config config, ErrorReporter errorReporter) { this.stream = stream; this.sourceFile = sourceFile; boolean parseDocumentation = config.parseJsDocDocumentation.shouldParseDescriptions(); this.jsdocBuilder = new JSDocInfoBuilder(parseDocumentation); if (comment != null) { this.jsdocBuilder.recordOriginalCommentString(comment); this.jsdocBuilder.recordOriginalCommentPosition(commentPosition); } this.annotationNames = config.annotationNames; this.suppressionNames = config.suppressionNames; this.preserveWhitespace = config.parseJsDocDocumentation == Config.JsDocParsing.INCLUDE_DESCRIPTIONS_WITH_WHITESPACE; this.errorReporter = errorReporter; this.templateNode = this.createTemplateNode(); } private String getSourceName() { return sourceFile == null ? null : sourceFile.getName(); } /** * Parse a description as a {@code @type}. */ public JSDocInfo parseInlineTypeDoc() { skipEOLs(); JsDocToken token = next(); int lineno = stream.getLineno(); int startCharno = stream.getCharno(); Node typeAst = parseParamTypeExpression(token); recordTypeNode(lineno, startCharno, typeAst, token == JsDocToken.LEFT_CURLY); JSTypeExpression expr = createJSTypeExpression(typeAst); if (expr != null) { jsdocBuilder.recordType(expr); jsdocBuilder.recordInlineType(); return retrieveAndResetParsedJSDocInfo(); } return null; } private void recordTypeNode(int lineno, int startCharno, Node typeAst, boolean matchingLC) { if (typeAst != null) { int endLineno = stream.getLineno(); int endCharno = stream.getCharno(); jsdocBuilder.markTypeNode( typeAst, lineno, startCharno, endLineno, endCharno, matchingLC); } } /** * Parses a string containing a JsDoc type declaration, returning the * type if the parsing succeeded or {@code null} if it failed. */ public static Node parseTypeString(String typeString) { JsDocInfoParser parser = getParser(typeString); return parser.parseTopLevelTypeExpression(parser.next()); } /** * Parses a string containing a JsDoc declaration, returning the entire JSDocInfo * if the parsing succeeded or {@code null} if it failed. */ public static JSDocInfo parseJsdoc(String toParse) { JsDocInfoParser parser = getParser(toParse); parser.parse(); return parser.retrieveAndResetParsedJSDocInfo(); } private static JsDocInfoParser getParser(String toParse) { Config config = new Config( new HashSet<String>(), new HashSet<String>(), LanguageMode.ECMASCRIPT3); JsDocInfoParser parser = new JsDocInfoParser( new JsDocTokenStream(toParse), toParse, 0, null, config, NullErrorReporter.forOldRhino()); return parser; } /** * Parses a {@link JSDocInfo} object. This parsing method reads all tokens * returned by the {@link JsDocTokenStream#getJsDocToken()} method until the * {@link JsDocToken#EOC} is returned. * * @return {@code true} if JSDoc information was correctly parsed, * {@code false} otherwise */ boolean parse() { state = State.SEARCHING_ANNOTATION; skipEOLs(); JsDocToken token = next(); // Always record that we have a comment. if (jsdocBuilder.shouldParseDocumentation()) { ExtractionInfo blockInfo = extractBlockComment(token); token = blockInfo.token; if (!blockInfo.string.isEmpty()) { jsdocBuilder.recordBlockDescription(blockInfo.string); } } else { if (token != JsDocToken.ANNOTATION && token != JsDocToken.EOC) { // Mark that there was a description, but don't bother marking // what it was. jsdocBuilder.recordBlockDescription(""); } } return parseHelperLoop(token, new ArrayList<ExtendedTypeInfo>()); } private boolean parseHelperLoop(JsDocToken token, List<ExtendedTypeInfo> extendedTypes) { while (true) { switch (token) { case ANNOTATION: if (state == State.SEARCHING_ANNOTATION) { state = State.SEARCHING_NEWLINE; token = parseAnnotation(token, extendedTypes); } else { token = next(); } break; case EOC: boolean success = true; // TODO(johnlenz): It should be a parse error to have an @extends // or similiar annotations in a file overview block. checkExtendedTypes(extendedTypes); if (hasParsedFileOverviewDocInfo()) { fileOverviewJSDocInfo = retrieveAndResetParsedJSDocInfo(); Visibility visibility = fileOverviewJSDocInfo.getVisibility(); switch (visibility) { case PRIVATE: // fallthrough case PROTECTED: // PRIVATE and PROTECTED are not allowed in @fileoverview JsDoc. addParserWarning( "msg.bad.fileoverview.visibility.annotation", visibility.toString().toLowerCase()); success = false; break; default: // PACKAGE, PUBLIC, and (implicitly) INHERITED are allowed // in @fileoverview JsDoc. break; } } return success; case EOF: // discard any accumulated information jsdocBuilder.build(); addParserWarning("msg.unexpected.eof"); checkExtendedTypes(extendedTypes); return false; case EOL: if (state == State.SEARCHING_NEWLINE) { state = State.SEARCHING_ANNOTATION; } token = next(); break; default: if (token == JsDocToken.STAR && state == State.SEARCHING_ANNOTATION) { token = next(); } else { state = State.SEARCHING_NEWLINE; token = eatTokensUntilEOL(); } break; } } } private JsDocToken parseAnnotation(JsDocToken token, List<ExtendedTypeInfo> extendedTypes) { // JSTypes are represented as Rhino AST nodes, and then resolved later. JSTypeExpression type; int lineno = stream.getLineno(); int charno = stream.getCharno(); String annotationName = stream.getString(); Annotation annotation = annotationNames.get(annotationName); if (annotation == null || annotationName.isEmpty()) { addParserWarning("msg.bad.jsdoc.tag", annotationName); } else { // Mark the beginning of the annotation. jsdocBuilder.markAnnotation(annotationName, lineno, charno); switch (annotation) { case NG_INJECT: if (jsdocBuilder.isNgInjectRecorded()) { addParserWarning("msg.jsdoc.nginject.extra"); } else { jsdocBuilder.recordNgInject(true); } return eatUntilEOLIfNotAnnotation(); case JAGGER_INJECT: if (jsdocBuilder.isJaggerInjectRecorded()) { addParserWarning("msg.jsdoc.jaggerInject.extra"); } else { jsdocBuilder.recordJaggerInject(true); } return eatUntilEOLIfNotAnnotation(); case JAGGER_MODULE: if (jsdocBuilder.isJaggerModuleRecorded()) { addParserWarning("msg.jsdoc.jaggerModule.extra"); } else { jsdocBuilder.recordJaggerModule(true); } return eatUntilEOLIfNotAnnotation(); case JAGGER_PROVIDE: if (jsdocBuilder.isJaggerProvideRecorded()) { addParserWarning("msg.jsdoc.jaggerProvide.extra"); } else { jsdocBuilder.recordJaggerProvide(true); } return eatUntilEOLIfNotAnnotation(); case JAGGER_PROVIDE_PROMISE: if (jsdocBuilder.isJaggerProvidePromiseRecorded()) { addParserWarning("msg.jsdoc.jaggerProvidePromise.extra"); } else { jsdocBuilder.recordJaggerProvidePromise(true); } return eatUntilEOLIfNotAnnotation(); case ABSTRACT: if (!jsdocBuilder.recordAbstract()) { addTypeWarning("msg.jsdoc.incompat.type"); } return eatUntilEOLIfNotAnnotation(); case AUTHOR: if (jsdocBuilder.shouldParseDocumentation()) { ExtractionInfo authorInfo = extractSingleLineBlock(); String author = authorInfo.string; if (author.isEmpty()) { addParserWarning("msg.jsdoc.authormissing"); } else { jsdocBuilder.addAuthor(author); } token = authorInfo.token; } else { token = eatUntilEOLIfNotAnnotation(); } return token; case CONSISTENTIDGENERATOR: if (!jsdocBuilder.recordConsistentIdGenerator()) { addParserWarning("msg.jsdoc.consistidgen"); } return eatUntilEOLIfNotAnnotation(); case UNRESTRICTED: if (!jsdocBuilder.recordUnrestricted()) { addTypeWarning("msg.jsdoc.incompat.type"); } return eatUntilEOLIfNotAnnotation(); case STRUCT: if (!jsdocBuilder.recordStruct()) { addTypeWarning("msg.jsdoc.incompat.type"); } return eatUntilEOLIfNotAnnotation(); case DICT: if (!jsdocBuilder.recordDict()) { addTypeWarning("msg.jsdoc.incompat.type"); } return eatUntilEOLIfNotAnnotation(); case CONSTRUCTOR: if (!jsdocBuilder.recordConstructor()) { if (jsdocBuilder.isInterfaceRecorded()) { addTypeWarning("msg.jsdoc.interface.constructor"); } else { addTypeWarning("msg.jsdoc.incompat.type"); } } return eatUntilEOLIfNotAnnotation(); case RECORD: if (!jsdocBuilder.recordImplicitMatch()) { addTypeWarning("msg.jsdoc.record"); } return eatUntilEOLIfNotAnnotation(); case DEPRECATED: if (!jsdocBuilder.recordDeprecated()) { addParserWarning("msg.jsdoc.deprecated"); } // Find the reason/description, if any. ExtractionInfo reasonInfo = extractMultilineTextualBlock(token); String reason = reasonInfo.string; if (reason.length() > 0) { jsdocBuilder.recordDeprecationReason(reason); } token = reasonInfo.token; return token; case INTERFACE: if (!jsdocBuilder.recordInterface()) { if (jsdocBuilder.isConstructorRecorded()) { addTypeWarning("msg.jsdoc.interface.constructor"); } else { addTypeWarning("msg.jsdoc.incompat.type"); } } return eatUntilEOLIfNotAnnotation(); case DESC: if (jsdocBuilder.isDescriptionRecorded()) { addParserWarning("msg.jsdoc.desc.extra"); return eatUntilEOLIfNotAnnotation(); } else { ExtractionInfo descriptionInfo = extractMultilineTextualBlock(token); String description = descriptionInfo.string; jsdocBuilder.recordDescription(description); token = descriptionInfo.token; return token; } case FILE_OVERVIEW: String fileOverview = ""; if (jsdocBuilder.shouldParseDocumentation() && !lookAheadForAnnotation()) { ExtractionInfo fileOverviewInfo = extractMultilineTextualBlock( token, getWhitespaceOption(WhitespaceOption.TRIM), false); fileOverview = fileOverviewInfo.string; token = fileOverviewInfo.token; } else { token = eatUntilEOLIfNotAnnotation(); } if (!jsdocBuilder.recordFileOverview(fileOverview)) { addParserWarning("msg.jsdoc.fileoverview.extra"); } return token; case LICENSE: case PRESERVE: // Always use PRESERVE for @license and @preserve blocks. ExtractionInfo preserveInfo = extractMultilineTextualBlock( token, WhitespaceOption.PRESERVE, true); String preserve = preserveInfo.string; if (preserve.length() > 0) { if (fileLevelJsDocBuilder != null) { fileLevelJsDocBuilder.addLicense(preserve); } } token = preserveInfo.token; return token; case ENUM: token = next(); lineno = stream.getLineno(); charno = stream.getCharno(); type = null; if (token != JsDocToken.EOL && token != JsDocToken.EOC) { Node typeNode = parseAndRecordTypeNode(token); if (typeNode != null && typeNode.getToken() == Token.STRING) { String typeName = typeNode.getString(); if (!typeName.equals("number") && !typeName.equals("string") && !typeName.equals("boolean")) { typeNode = wrapNode(Token.BANG, typeNode); } } type = createJSTypeExpression(typeNode); } else { restoreLookAhead(token); } if (type == null) { type = createJSTypeExpression(newStringNode("number")); } if (!jsdocBuilder.recordEnumParameterType(type)) { addTypeWarning("msg.jsdoc.incompat.type", lineno, charno); } return eatUntilEOLIfNotAnnotation(); case EXPOSE: if (!jsdocBuilder.recordExpose()) { addParserWarning("msg.jsdoc.expose"); } return eatUntilEOLIfNotAnnotation(); case EXTERNS: if (!jsdocBuilder.recordExterns()) { addParserWarning("msg.jsdoc.externs"); } return eatUntilEOLIfNotAnnotation(); case EXTENDS: case IMPLEMENTS: skipEOLs(); token = next(); lineno = stream.getLineno(); charno = stream.getCharno(); boolean matchingRc = false; if (token == JsDocToken.LEFT_CURLY) { token = next(); matchingRc = true; } if (token == JsDocToken.STRING) { Node typeNode = parseAndRecordTypeNameNode( token, lineno, charno, matchingRc); lineno = stream.getLineno(); charno = stream.getCharno(); typeNode = wrapNode(Token.BANG, typeNode); type = createJSTypeExpression(typeNode); if (annotation == Annotation.EXTENDS) { // record the extended type, check later extendedTypes.add(new ExtendedTypeInfo( type, stream.getLineno(), stream.getCharno())); } else { Preconditions.checkState( annotation == Annotation.IMPLEMENTS); if (!jsdocBuilder.recordImplementedInterface(type)) { addTypeWarning("msg.jsdoc.implements.duplicate", lineno, charno); } } token = next(); if (matchingRc) { if (token != JsDocToken.RIGHT_CURLY) { addTypeWarning("msg.jsdoc.missing.rc"); } else { token = next(); } } else if (token != JsDocToken.EOL && token != JsDocToken.EOF && token != JsDocToken.EOC) { addTypeWarning("msg.end.annotation.expected"); } } else { addTypeWarning("msg.no.type.name", lineno, charno); } token = eatUntilEOLIfNotAnnotation(token); return token; case HIDDEN: if (!jsdocBuilder.recordHiddenness()) { addParserWarning("msg.jsdoc.hidden"); } return eatUntilEOLIfNotAnnotation(); case LENDS: skipEOLs(); matchingRc = false; if (match(JsDocToken.LEFT_CURLY)) { token = next(); matchingRc = true; } if (match(JsDocToken.STRING)) { token = next(); if (!jsdocBuilder.recordLends(stream.getString())) { addTypeWarning("msg.jsdoc.lends.incompatible"); } } else { addTypeWarning("msg.jsdoc.lends.missing"); } if (matchingRc && !match(JsDocToken.RIGHT_CURLY)) { addTypeWarning("msg.jsdoc.missing.rc"); } return eatUntilEOLIfNotAnnotation(); case MEANING: ExtractionInfo meaningInfo = extractMultilineTextualBlock(token); String meaning = meaningInfo.string; token = meaningInfo.token; if (!jsdocBuilder.recordMeaning(meaning)) { addParserWarning("msg.jsdoc.meaning.extra"); } return token; case NO_ALIAS: if (!jsdocBuilder.recordNoAlias()) { addParserWarning("msg.jsdoc.noalias"); } return eatUntilEOLIfNotAnnotation(); case NO_COMPILE: if (!jsdocBuilder.recordNoCompile()) { addParserWarning("msg.jsdoc.nocompile"); } return eatUntilEOLIfNotAnnotation(); case NO_COLLAPSE: if (!jsdocBuilder.recordNoCollapse()) { addParserWarning("msg.jsdoc.nocollapse"); } return eatUntilEOLIfNotAnnotation(); case NOT_IMPLEMENTED: return eatUntilEOLIfNotAnnotation(); case INHERIT_DOC: case OVERRIDE: if (!jsdocBuilder.recordOverride()) { addTypeWarning("msg.jsdoc.override"); } return eatUntilEOLIfNotAnnotation(); case POLYMER_BEHAVIOR: if (jsdocBuilder.isPolymerBehaviorRecorded()) { addParserWarning("msg.jsdoc.polymerBehavior.extra"); } else { jsdocBuilder.recordPolymerBehavior(); } return eatUntilEOLIfNotAnnotation(); case THROWS: { skipEOLs(); token = next(); lineno = stream.getLineno(); charno = stream.getCharno(); type = null; if (token == JsDocToken.LEFT_CURLY) { type = createJSTypeExpression( parseAndRecordTypeNode(token)); if (type == null) { // parsing error reported during recursive descent // recovering parsing return eatUntilEOLIfNotAnnotation(); } } // *Update* the token to that after the type annotation. token = current(); // Save the throw type. jsdocBuilder.recordThrowType(type); boolean isAnnotationNext = lookAheadForAnnotation(); // Find the throw's description (if applicable). if (jsdocBuilder.shouldParseDocumentation() && !isAnnotationNext) { ExtractionInfo descriptionInfo = extractMultilineTextualBlock(token); String description = descriptionInfo.string; if (description.length() > 0) { jsdocBuilder.recordThrowDescription(type, description); } token = descriptionInfo.token; } else { token = eatUntilEOLIfNotAnnotation(); } return token; } case PARAM: skipEOLs(); token = next(); lineno = stream.getLineno(); charno = stream.getCharno(); type = null; boolean hasParamType = false; if (token == JsDocToken.LEFT_CURLY) { type = createJSTypeExpression( parseAndRecordParamTypeNode(token)); if (type == null) { // parsing error reported during recursive descent // recovering parsing return eatUntilEOLIfNotAnnotation(); } skipEOLs(); token = next(); lineno = stream.getLineno(); charno = stream.getCharno(); hasParamType = true; } String name = null; boolean isBracketedParam = JsDocToken.LEFT_SQUARE == token; if (isBracketedParam) { token = next(); } if (JsDocToken.STRING != token) { addTypeWarning("msg.missing.variable.name", lineno, charno); } else { if (!hasParamType) { addMissingTypeWarning(stream.getLineno(), stream.getCharno()); } name = stream.getString(); if (isBracketedParam) { token = next(); // Throw out JsDocToolkit's "default" parameter // annotation. It makes no sense under our type // system. if (JsDocToken.EQUALS == token) { token = next(); if (JsDocToken.STRING == token) { token = next(); } } if (JsDocToken.RIGHT_SQUARE != token) { reportTypeSyntaxWarning("msg.jsdoc.missing.rb"); } else if (type != null) { // Make the type expression optional, if it isn't // already. type = JSTypeExpression.makeOptionalArg(type); } } // We do not handle the JsDocToolkit method // for handling properties of params, so if the param name has a DOT // in it, report a warning and throw it out. // See https://github.com/google/closure-compiler/issues/499 if (!TokenStream.isJSIdentifier(name)) { addParserWarning("msg.invalid.variable.name", name, lineno, charno); name = null; } else if (!jsdocBuilder.recordParameter(name, type)) { if (jsdocBuilder.hasParameter(name)) { addTypeWarning("msg.dup.variable.name", name, lineno, charno); } else { addTypeWarning("msg.jsdoc.incompat.type", name, lineno, charno); } } } if (name == null) { token = eatUntilEOLIfNotAnnotation(token); return token; } jsdocBuilder.markName(name, sourceFile, lineno, charno); // Find the parameter's description (if applicable). if (jsdocBuilder.shouldParseDocumentation() && token != JsDocToken.ANNOTATION) { ExtractionInfo paramDescriptionInfo = extractMultilineTextualBlock(token); String paramDescription = paramDescriptionInfo.string; if (paramDescription.length() > 0) { jsdocBuilder.recordParameterDescription(name, paramDescription); } token = paramDescriptionInfo.token; } else if (token != JsDocToken.EOC && token != JsDocToken.EOF) { token = eatUntilEOLIfNotAnnotation(); } return token; case NO_SIDE_EFFECTS: if (!jsdocBuilder.recordNoSideEffects()) { addParserWarning("msg.jsdoc.nosideeffects"); } return eatUntilEOLIfNotAnnotation(); case MODIFIES: token = parseModifiesTag(next()); return token; case IMPLICIT_CAST: if (!jsdocBuilder.recordImplicitCast()) { addTypeWarning("msg.jsdoc.implicitcast"); } return eatUntilEOLIfNotAnnotation(); case SEE: if (jsdocBuilder.shouldParseDocumentation()) { ExtractionInfo referenceInfo = extractSingleLineBlock(); String reference = referenceInfo.string; if (reference.isEmpty()) { addParserWarning("msg.jsdoc.seemissing"); } else { jsdocBuilder.addReference(reference); } token = referenceInfo.token; } else { token = eatUntilEOLIfNotAnnotation(); } return token; case STABLEIDGENERATOR: if (!jsdocBuilder.recordStableIdGenerator()) { addParserWarning("msg.jsdoc.stableidgen"); } return eatUntilEOLIfNotAnnotation(); case SUPPRESS: token = parseSuppressTag(next()); return token; case TEMPLATE: { int templateLineno = stream.getLineno(); int templateCharno = stream.getCharno(); // Always use TRIM for template TTL expressions. ExtractionInfo templateInfo = extractMultilineTextualBlock(token, WhitespaceOption.TRIM, false); String templateString = templateInfo.string; // TTL stands for type transformation language // TODO(lpino): This delimiter needs to be further discussed String ttlStartDelimiter = ":="; String ttlEndDelimiter = "=:"; String templateNames; String typeTransformationExpr = ""; boolean isTypeTransformation = false; boolean validTypeTransformation = true; // Detect if there is a type transformation if (!templateString.contains(ttlStartDelimiter)) { // If there is no type transformation take the first line if (templateString.contains("\n")) { templateNames = templateString.substring(0, templateString.indexOf('\n')); } else { templateNames = templateString; } } else { // Split the part with the template type names int ttlStartIndex = templateString.indexOf(ttlStartDelimiter); templateNames = templateString.substring(0, ttlStartIndex); // Check if the type transformation expression ends correctly if (!templateString.contains(ttlEndDelimiter)) { validTypeTransformation = false; addTypeWarning( "msg.jsdoc.typetransformation.missing.delimiter", templateLineno, templateCharno); } else { isTypeTransformation = true; // Split the part of the type transformation int ttlEndIndex = templateString.indexOf(ttlEndDelimiter); typeTransformationExpr = templateString.substring( ttlStartIndex + ttlStartDelimiter.length(), ttlEndIndex).trim(); } } // Obtain the template type names List<String> names = Splitter.on(',') .trimResults() .splitToList(templateNames); if (names.size() == 1 && names.get(0).isEmpty()) { addTypeWarning("msg.jsdoc.templatemissing", templateLineno, templateCharno); } else { for (String typeName : names) { if (!validTemplateTypeName(typeName)) { addTypeWarning( "msg.jsdoc.template.invalid.type.name", templateLineno, templateCharno); } else if (!isTypeTransformation) { if (!jsdocBuilder.recordTemplateTypeName(typeName)) { addTypeWarning( "msg.jsdoc.template.name.declared.twice", templateLineno, templateCharno); } } } } if (isTypeTransformation) { // A type transformation must be associated to a single type name if (names.size() > 1) { addTypeWarning( "msg.jsdoc.typetransformation.with.multiple.names", templateLineno, templateCharno); } if (typeTransformationExpr.isEmpty()) { validTypeTransformation = false; addTypeWarning( "msg.jsdoc.typetransformation.expression.missing", templateLineno, templateCharno); } // Build the AST for the type transformation if (validTypeTransformation) { TypeTransformationParser ttlParser = new TypeTransformationParser(typeTransformationExpr, sourceFile, errorReporter, templateLineno, templateCharno); // If the parsing was successful store the type transformation if (ttlParser.parseTypeTransformation() && !jsdocBuilder.recordTypeTransformation( names.get(0), ttlParser.getTypeTransformationAst())) { addTypeWarning( "msg.jsdoc.template.name.declared.twice", templateLineno, templateCharno); } } } token = templateInfo.token; return token; } case IDGENERATOR: token = parseIdGeneratorTag(next()); return token; case WIZACTION: if (!jsdocBuilder.recordWizaction()) { addParserWarning("msg.jsdoc.wizaction"); } return eatUntilEOLIfNotAnnotation(); case DISPOSES: { ExtractionInfo templateInfo = extractSingleLineBlock(); List<String> names = Splitter.on(',') .trimResults() .splitToList(templateInfo.string); if (names.isEmpty() || names.get(0).isEmpty()) { addTypeWarning("msg.jsdoc.disposeparameter.missing"); } else if (!jsdocBuilder.recordDisposesParameter(names)) { addTypeWarning("msg.jsdoc.disposeparameter.error"); } token = templateInfo.token; return token; } case VERSION: ExtractionInfo versionInfo = extractSingleLineBlock(); String version = versionInfo.string; if (version.isEmpty()) { addParserWarning("msg.jsdoc.versionmissing"); } else { if (!jsdocBuilder.recordVersion(version)) { addParserWarning("msg.jsdoc.extraversion"); } } token = versionInfo.token; return token; case CONSTANT: case FINAL: case DEFINE: case EXPORT: case RETURN: case PACKAGE: case PRIVATE: case PROTECTED: case PUBLIC: case THIS: case TYPE: case TYPEDEF: lineno = stream.getLineno(); charno = stream.getCharno(); Node typeNode = null; boolean hasType = lookAheadForType(); boolean isAlternateTypeAnnotation = annotation == Annotation.PACKAGE || annotation == Annotation.PRIVATE || annotation == Annotation.PROTECTED || annotation == Annotation.PUBLIC || annotation == Annotation.CONSTANT || annotation == Annotation.FINAL || annotation == Annotation.EXPORT; boolean canSkipTypeAnnotation = isAlternateTypeAnnotation || annotation == Annotation.RETURN; type = null; if (annotation == Annotation.RETURN && !hasType) { addMissingTypeWarning(stream.getLineno(), stream.getCharno()); } if (hasType || !canSkipTypeAnnotation) { skipEOLs(); token = next(); typeNode = parseAndRecordTypeNode(token); if (annotation == Annotation.THIS) { typeNode = wrapNode(Token.BANG, typeNode); } type = createJSTypeExpression(typeNode); } // The error was reported during recursive descent // recovering parsing boolean hasError = type == null && !canSkipTypeAnnotation; if (!hasError) { // Record types for @type. // If the @package, @private, @protected, or @public annotations // have a type attached, pretend that they actually wrote: // @type {type}\n@private // This will have some weird behavior in some cases // (for example, @private can now be used as a type-cast), // but should be mostly OK. if (((type != null && isAlternateTypeAnnotation) || annotation == Annotation.TYPE) && !jsdocBuilder.recordType(type)) { addTypeWarning("msg.jsdoc.incompat.type", lineno, charno); } boolean isAnnotationNext = lookAheadForAnnotation(); switch (annotation) { case CONSTANT: if (!jsdocBuilder.recordConstancy()) { addParserWarning("msg.jsdoc.const"); } break; case FINAL: if (!jsdocBuilder.recordFinality()) { addTypeWarning("msg.jsdoc.final"); } break; case DEFINE: if (!jsdocBuilder.recordDefineType(type)) { addParserWarning("msg.jsdoc.define", lineno, charno); } if (!isAnnotationNext) { return recordDescription(token); } break; case EXPORT: if (!jsdocBuilder.recordExport()) { addParserWarning("msg.jsdoc.export", lineno, charno); } else if (!jsdocBuilder.recordVisibility(Visibility.PUBLIC)) { addParserWarning("msg.jsdoc.extra.visibility", lineno, charno); } if (!isAnnotationNext) { return recordDescription(token); } break; case PRIVATE: if (!jsdocBuilder.recordVisibility(Visibility.PRIVATE)) { addParserWarning("msg.jsdoc.extra.visibility", lineno, charno); } if (!isAnnotationNext) { return recordDescription(token); } break; case PACKAGE: if (!jsdocBuilder.recordVisibility(Visibility.PACKAGE)) { addParserWarning("msg.jsdoc.extra.visibility", lineno, charno); } if (!isAnnotationNext) { return recordDescription(token); } break; case PROTECTED: if (!jsdocBuilder.recordVisibility(Visibility.PROTECTED)) { addParserWarning("msg.jsdoc.extra.visibility", lineno, charno); } if (!isAnnotationNext) { return recordDescription(token); } break; case PUBLIC: if (!jsdocBuilder.recordVisibility(Visibility.PUBLIC)) { addParserWarning("msg.jsdoc.extra.visibility", lineno, charno); } if (!isAnnotationNext) { return recordDescription(token); } break; case RETURN: if (type == null) { type = createJSTypeExpression(newNode(Token.QMARK)); } if (!jsdocBuilder.recordReturnType(type)) { addTypeWarning("msg.jsdoc.incompat.type", lineno, charno); break; } // TODO(johnlenz): The extractMultilineTextualBlock method // and friends look directly at the stream, regardless of // last token read, so we don't want to read the first // "STRING" out of the stream. // Find the return's description (if applicable). if (jsdocBuilder.shouldParseDocumentation() && !isAnnotationNext) { ExtractionInfo returnDescriptionInfo = extractMultilineTextualBlock(token); String returnDescription = returnDescriptionInfo.string; if (returnDescription.length() > 0) { jsdocBuilder.recordReturnDescription( returnDescription); } token = returnDescriptionInfo.token; } else { token = eatUntilEOLIfNotAnnotation(); } return token; case THIS: if (!jsdocBuilder.recordThisType(type)) { addTypeWarning("msg.jsdoc.incompat.type", lineno, charno); } break; case TYPEDEF: if (!jsdocBuilder.recordTypedef(type)) { addTypeWarning("msg.jsdoc.incompat.type", lineno, charno); } break; default: break; } } return eatUntilEOLIfNotAnnotation(); } } return next(); } /** * The types in @template annotations must start with a capital letter, and contain * only letters, digits, and underscores. */ private static boolean validTemplateTypeName(String name) { return !name.isEmpty() && CharMatcher.javaUpperCase().matches(name.charAt(0)) && CharMatcher.javaLetterOrDigit().or(CharMatcher.is('_')).matchesAllOf(name); } /** * Records a marker's description if there is one available and record it in * the current marker. */ private JsDocToken recordDescription(JsDocToken token) { // Find marker's description (if applicable). if (jsdocBuilder.shouldParseDocumentation()) { ExtractionInfo descriptionInfo = extractMultilineTextualBlock(token); token = descriptionInfo.token; } else { token = eatTokensUntilEOL(token); } return token; } private void checkExtendedTypes(List<ExtendedTypeInfo> extendedTypes) { for (ExtendedTypeInfo typeInfo : extendedTypes) { // If interface, record the multiple extended interfaces if (jsdocBuilder.isInterfaceRecorded()) { if (!jsdocBuilder.recordExtendedInterface(typeInfo.type)) { addParserWarning("msg.jsdoc.extends.duplicate", typeInfo.lineno, typeInfo.charno); } } else { if (!jsdocBuilder.recordBaseType(typeInfo.type)) { addTypeWarning("msg.jsdoc.incompat.type", typeInfo.lineno, typeInfo.charno); } } } } /** * Parse a {@code @suppress} tag of the form * {@code @suppress&#123;warning1|warning2&#125;}. * * @param token The current token. */ private JsDocToken parseSuppressTag(JsDocToken token) { if (token != JsDocToken.LEFT_CURLY) { addParserWarning("msg.jsdoc.suppress"); return token; } else { Set<String> suppressions = new HashSet<>(); while (true) { if (match(JsDocToken.STRING)) { String name = stream.getString(); if (!suppressionNames.contains(name)) { addParserWarning("msg.jsdoc.suppress.unknown", name); } suppressions.add(stream.getString()); token = next(); } else { addParserWarning("msg.jsdoc.suppress"); return token; } if (match(JsDocToken.PIPE, JsDocToken.COMMA)) { token = next(); } else { break; } } if (!match(JsDocToken.RIGHT_CURLY)) { addParserWarning("msg.jsdoc.suppress"); } else { token = next(); if (!jsdocBuilder.recordSuppressions(suppressions)) { addParserWarning("msg.jsdoc.suppress.duplicate"); } } return eatUntilEOLIfNotAnnotation(); } } /** * Parse a {@code @modifies} tag of the form * {@code @modifies&#123;this|arguments|param&#125;}. * * @param token The current token. */ private JsDocToken parseModifiesTag(JsDocToken token) { if (token == JsDocToken.LEFT_CURLY) { Set<String> modifies = new HashSet<>(); while (true) { if (match(JsDocToken.STRING)) { String name = stream.getString(); if (!modifiesAnnotationKeywords.contains(name) && !jsdocBuilder.hasParameter(name)) { addParserWarning("msg.jsdoc.modifies.unknown", name); } modifies.add(stream.getString()); token = next(); } else { addParserWarning("msg.jsdoc.modifies"); return token; } if (match(JsDocToken.PIPE)) { token = next(); } else { break; } } if (!match(JsDocToken.RIGHT_CURLY)) { addParserWarning("msg.jsdoc.modifies"); } else { token = next(); if (!jsdocBuilder.recordModifies(modifies)) { addParserWarning("msg.jsdoc.modifies.duplicate"); } } } return token; } /** * Parse a {@code @idgenerator} tag of the form * {@code @idgenerator} or * {@code @idgenerator&#123;consistent&#125;}. * * @param token The current token. */ private JsDocToken parseIdGeneratorTag(JsDocToken token) { String idgenKind = "unique"; if (token == JsDocToken.LEFT_CURLY) { if (match(JsDocToken.STRING)) { String name = stream.getString(); if (!idGeneratorAnnotationKeywords.contains(name) && !jsdocBuilder.hasParameter(name)) { addParserWarning("msg.jsdoc.idgen.unknown", name); } idgenKind = name; token = next(); } else { addParserWarning("msg.jsdoc.idgen.bad"); return token; } if (!match(JsDocToken.RIGHT_CURLY)) { addParserWarning("msg.jsdoc.idgen.bad"); } else { token = next(); } } switch (idgenKind) { case "unique": if (!jsdocBuilder.recordIdGenerator()) { addParserWarning("msg.jsdoc.idgen.duplicate"); } break; case "consistent": if (!jsdocBuilder.recordConsistentIdGenerator()) { addParserWarning("msg.jsdoc.idgen.duplicate"); } break; case "stable": if (!jsdocBuilder.recordStableIdGenerator()) { addParserWarning("msg.jsdoc.idgen.duplicate"); } break; case "xid": if (!jsdocBuilder.recordXidGenerator()) { addParserWarning("msg.jsdoc.idgen.duplicate"); } break; case "mapped": if (!jsdocBuilder.recordMappedIdGenerator()) { addParserWarning("msg.jsdoc.idgen.duplicate"); } break; } return token; } /** * Looks for a type expression at the current token and if found, * returns it. Note that this method consumes input. * * @param token The current token. * @return The type expression found or null if none. */ Node parseAndRecordTypeNode(JsDocToken token) { return parseAndRecordTypeNode(token, stream.getLineno(), stream.getCharno(), token == JsDocToken.LEFT_CURLY, false); } /** * Looks for a type expression at the current token and if found, * returns it. Note that this method consumes input. * * @param token The current token. * @param lineno The line of the type expression. * @param startCharno The starting character position of the type expression. * @param matchingLC Whether the type expression starts with a "{". * @return The type expression found or null if none. */ private Node parseAndRecordTypeNameNode(JsDocToken token, int lineno, int startCharno, boolean matchingLC) { return parseAndRecordTypeNode(token, lineno, startCharno, matchingLC, true); } /** * Looks for a type expression at the current token and if found, * returns it. Note that this method consumes input. * * Parameter type expressions are special for two reasons: * <ol> * <li>They must begin with '{', to distinguish type names from param names. * <li>They may end in '=', to denote optionality. * </ol> * * @param token The current token. * @return The type expression found or null if none. */ private Node parseAndRecordParamTypeNode(JsDocToken token) { Preconditions.checkArgument(token == JsDocToken.LEFT_CURLY); int lineno = stream.getLineno(); int startCharno = stream.getCharno(); Node typeNode = parseParamTypeExpressionAnnotation(token); recordTypeNode(lineno, startCharno, typeNode, true); return typeNode; } /** * Looks for a parameter type expression at the current token and if found, * returns it. Note that this method consumes input. * * @param token The current token. * @param lineno The line of the type expression. * @param startCharno The starting character position of the type expression. * @param matchingLC Whether the type expression starts with a "{". * @param onlyParseSimpleNames If true, only simple type names are parsed * (via a call to parseTypeNameAnnotation instead of * parseTypeExpressionAnnotation). * @return The type expression found or null if none. */ private Node parseAndRecordTypeNode(JsDocToken token, int lineno, int startCharno, boolean matchingLC, boolean onlyParseSimpleNames) { Node typeNode; if (onlyParseSimpleNames) { typeNode = parseTypeNameAnnotation(token); } else { typeNode = parseTypeExpressionAnnotation(token); } recordTypeNode(lineno, startCharno, typeNode, matchingLC); return typeNode; } /** * Converts a JSDoc token to its string representation. */ private String toString(JsDocToken token) { switch (token) { case ANNOTATION: return "@" + stream.getString(); case BANG: return "!"; case COMMA: return ","; case COLON: return ":"; case RIGHT_ANGLE: return ">"; case LEFT_SQUARE: return "["; case LEFT_CURLY: return "{"; case LEFT_PAREN: return "("; case LEFT_ANGLE: return "<"; case QMARK: return "?"; case PIPE: return "|"; case RIGHT_SQUARE: return "]"; case RIGHT_CURLY: return "}"; case RIGHT_PAREN: return ")"; case STAR: return "*"; case ELLIPSIS: return "..."; case EQUALS: return "="; case STRING: return stream.getString(); default: throw new IllegalStateException(token.toString()); } } /** * Constructs a new {@code JSTypeExpression}. * @param n A node. May be null. */ JSTypeExpression createJSTypeExpression(Node n) { return n == null ? null : new JSTypeExpression(n, getSourceName()); } /** * Tuple for returning both the string extracted and the * new token following a call to any of the extract*Block * methods. */ private static class ExtractionInfo { private final String string; private final JsDocToken token; public ExtractionInfo(String string, JsDocToken token) { this.string = string; this.token = token; } } /** * Tuple for recording extended types */ private static class ExtendedTypeInfo { final JSTypeExpression type; final int lineno; final int charno; public ExtendedTypeInfo(JSTypeExpression type, int lineno, int charno) { this.type = type; this.lineno = lineno; this.charno = charno; } } /** * Extracts the text found on the current line starting at token. Note that * token = token.info; should be called after this method is used to update * the token properly in the parser. * * @return The extraction information. */ private ExtractionInfo extractSingleLineBlock() { // Get the current starting point. stream.update(); int lineno = stream.getLineno(); int charno = stream.getCharno() + 1; String line = getRemainingJSDocLine().trim(); // Record the textual description. if (line.length() > 0) { jsdocBuilder.markText(line, lineno, charno, lineno, charno + line.length()); } return new ExtractionInfo(line, next()); } private ExtractionInfo extractMultilineTextualBlock(JsDocToken token) { return extractMultilineTextualBlock( token, getWhitespaceOption(WhitespaceOption.SINGLE_LINE), false); } private WhitespaceOption getWhitespaceOption(WhitespaceOption defaultValue) { return preserveWhitespace ? WhitespaceOption.PRESERVE : defaultValue; } private enum WhitespaceOption { /** * Preserves all whitespace and formatting. Needed for licenses and * purposely formatted text. */ PRESERVE, /** Preserves newlines but trims the output. */ TRIM, /** Removes newlines and turns the output into a single line string. */ SINGLE_LINE } /** * Extracts the text found on the current line and all subsequent * until either an annotation, end of comment or end of file is reached. * Note that if this method detects an end of line as the first token, it * will quit immediately (indicating that there is no text where it was * expected). Note that token = info.token; should be called after this * method is used to update the token properly in the parser. * * @param token The start token. * @param option How to handle whitespace. * @param includeAnnotations Whether the extracted text may include * annotations. If set to false, text extraction will stop on the first * encountered annotation token. * * @return The extraction information. */ private ExtractionInfo extractMultilineTextualBlock(JsDocToken token, WhitespaceOption option, boolean includeAnnotations) { if (token == JsDocToken.EOC || token == JsDocToken.EOL || token == JsDocToken.EOF) { return new ExtractionInfo("", token); } return extractMultilineComment(token, option, true, includeAnnotations); } /** * Extracts the top-level block comment from the JsDoc comment, if any. * This method differs from the extractMultilineTextualBlock in that it * terminates under different conditions (it doesn't have the same * prechecks), it does not first read in the remaining of the current * line and its conditions for ignoring the "*" (STAR) are different. * * @param token The starting token. * * @return The extraction information. */ private ExtractionInfo extractBlockComment(JsDocToken token) { return extractMultilineComment(token, getWhitespaceOption(WhitespaceOption.TRIM), false, false); } /** * Extracts text from the stream until the end of the comment, end of the * file, or an annotation token is encountered. If the text is being * extracted for a JSDoc marker, the first line in the stream will always be * included in the extract text. * * @param token The starting token. * @param option How to handle whitespace. * @param isMarker Whether the extracted text is for a JSDoc marker or a * block comment. * @param includeAnnotations Whether the extracted text may include * annotations. If set to false, text extraction will stop on the first * encountered annotation token. * * @return The extraction information. */ private ExtractionInfo extractMultilineComment( JsDocToken token, WhitespaceOption option, boolean isMarker, boolean includeAnnotations) { StringBuilder builder = new StringBuilder(); int startLineno = -1; int startCharno = -1; if (isMarker) { stream.update(); startLineno = stream.getLineno(); startCharno = stream.getCharno() + 1; String line = getRemainingJSDocLine(); if (option != WhitespaceOption.PRESERVE) { line = line.trim(); } builder.append(line); state = State.SEARCHING_ANNOTATION; token = next(); } boolean ignoreStar = false; // Track the start of the line to count whitespace that // the tokenizer skipped. Because this case is rare, it's easier // to do this here than in the tokenizer. int lineStartChar = -1; do { switch (token) { case STAR: if (ignoreStar) { // Mark the position after the star as the new start of the line. lineStartChar = stream.getCharno() + 1; ignoreStar = false; } else { // The star is part of the comment. padLine(builder, lineStartChar, option); lineStartChar = -1; builder.append('*'); } token = next(); while (token == JsDocToken.STAR) { if (lineStartChar != -1) { padLine(builder, lineStartChar, option); lineStartChar = -1; } builder.append('*'); token = next(); } continue; case EOL: if (option != WhitespaceOption.SINGLE_LINE) { builder.append('\n'); } ignoreStar = true; lineStartChar = 0; token = next(); continue; default: ignoreStar = false; state = State.SEARCHING_ANNOTATION; boolean isEOC = token == JsDocToken.EOC; if (!isEOC) { padLine(builder, lineStartChar, option); lineStartChar = -1; } if (token == JsDocToken.EOC || token == JsDocToken.EOF || // When we're capturing a license block, annotations // in the block are OK. (token == JsDocToken.ANNOTATION && !includeAnnotations)) { String multilineText = builder.toString(); if (option != WhitespaceOption.PRESERVE) { multilineText = multilineText.trim(); } if (isMarker && !multilineText.isEmpty()) { int endLineno = stream.getLineno(); int endCharno = stream.getCharno(); jsdocBuilder.markText(multilineText, startLineno, startCharno, endLineno, endCharno); } return new ExtractionInfo(multilineText, token); } builder.append(toString(token)); String line = getRemainingJSDocLine(); if (option != WhitespaceOption.PRESERVE) { line = trimEnd(line); } builder.append(line); token = next(); } } while (true); } private void padLine(StringBuilder builder, int lineStartChar, WhitespaceOption option) { if (lineStartChar != -1 && option == WhitespaceOption.PRESERVE) { int numSpaces = stream.getCharno() - lineStartChar; for (int i = 0; i < numSpaces; i++) { builder.append(' '); } } else if (builder.length() > 0) { if (builder.charAt(builder.length() - 1) != '\n' || option == WhitespaceOption.PRESERVE) { builder.append(' '); } } } /** * Trim characters from only the end of a string. * This method will remove all whitespace characters * (defined by TokenUtil.isWhitespace(char), in addition to the characters * provided, from the end of the provided string. * * @param s String to be trimmed * @return String with whitespace and characters in extraChars removed * from the end. */ private static String trimEnd(String s) { int trimCount = 0; while (trimCount < s.length()) { char ch = s.charAt(s.length() - trimCount - 1); if (TokenUtil.isWhitespace(ch)) { trimCount++; } else { break; } } if (trimCount == 0) { return s; } return s.substring(0, s.length() - trimCount); } // Based on ES4 grammar proposed on July 10, 2008. // http://wiki.ecmascript.org/doku.php?id=spec:spec // Deliberately written to line up with the actual grammar rules, // for maximum flexibility. // TODO(nicksantos): The current implementation tries to maintain backwards // compatibility with previous versions of the spec whenever we can. // We should try to gradually withdraw support for these. /** * TypeExpressionAnnotation := TypeExpression | * '{' TopLevelTypeExpression '}' */ private Node parseTypeExpressionAnnotation(JsDocToken token) { if (token == JsDocToken.LEFT_CURLY) { skipEOLs(); Node typeNode = parseTopLevelTypeExpression(next()); if (typeNode != null) { skipEOLs(); if (!match(JsDocToken.RIGHT_CURLY)) { reportTypeSyntaxWarning("msg.jsdoc.missing.rc"); } else { next(); } } return typeNode; } else { // TODO(tbreisacher): Add a SuggestedFix for this warning. reportTypeSyntaxWarning("msg.jsdoc.missing.braces"); return parseTypeExpression(token); } } /** * ParamTypeExpression := * OptionalParameterType | * TopLevelTypeExpression | * '...' TopLevelTypeExpression * * OptionalParameterType := * TopLevelTypeExpression '=' * */ private Node parseParamTypeExpression(JsDocToken token) { boolean restArg = false; if (token == JsDocToken.ELLIPSIS) { token = next(); if (token == JsDocToken.RIGHT_CURLY) { restoreLookAhead(token); // EMPTY represents the UNKNOWN type in the Type AST. return wrapNode(Token.ELLIPSIS, IR.empty()); } restArg = true; } Node typeNode = parseTopLevelTypeExpression(token); if (typeNode != null) { skipEOLs(); if (restArg) { typeNode = wrapNode(Token.ELLIPSIS, typeNode); } else if (match(JsDocToken.EQUALS)) { next(); skipEOLs(); typeNode = wrapNode(Token.EQUALS, typeNode); } } return typeNode; } /** * ParamTypeExpressionAnnotation := '{' ParamTypeExpression '}' */ private Node parseParamTypeExpressionAnnotation(JsDocToken token) { Preconditions.checkArgument(token == JsDocToken.LEFT_CURLY); skipEOLs(); Node typeNode = parseParamTypeExpression(next()); if (typeNode != null) { if (!match(JsDocToken.RIGHT_CURLY)) { reportTypeSyntaxWarning("msg.jsdoc.missing.rc"); } else { next(); } } return typeNode; } /** * TypeNameAnnotation := TypeName | '{' TypeName '}' */ private Node parseTypeNameAnnotation(JsDocToken token) { if (token == JsDocToken.LEFT_CURLY) { skipEOLs(); Node typeNode = parseTypeName(next()); if (typeNode != null) { skipEOLs(); if (!match(JsDocToken.RIGHT_CURLY)) { reportTypeSyntaxWarning("msg.jsdoc.missing.rc"); } else { next(); } } return typeNode; } else { return parseTypeName(token); } } /** * TopLevelTypeExpression := TypeExpression * | TypeUnionList * * We made this rule up, for the sake of backwards compatibility. */ private Node parseTopLevelTypeExpression(JsDocToken token) { Node typeExpr = parseTypeExpression(token); if (typeExpr != null) { // top-level unions are allowed if (match(JsDocToken.PIPE)) { next(); skipEOLs(); token = next(); return parseUnionTypeWithAlternate(token, typeExpr); } } return typeExpr; } /** * TypeExpressionList := TopLevelTypeExpression * | TopLevelTypeExpression ',' TypeExpressionList */ private Node parseTypeExpressionList(JsDocToken token) { Node typeExpr = parseTopLevelTypeExpression(token); if (typeExpr == null) { return null; } Node typeList = IR.block(); typeList.addChildToBack(typeExpr); while (match(JsDocToken.COMMA)) { next(); skipEOLs(); typeExpr = parseTopLevelTypeExpression(next()); if (typeExpr == null) { return null; } typeList.addChildToBack(typeExpr); } return typeList; } /** * TypeExpression := BasicTypeExpression * | '?' BasicTypeExpression * | '!' BasicTypeExpression * | BasicTypeExpression '?' * | BasicTypeExpression '!' * | '?' */ private Node parseTypeExpression(JsDocToken token) { if (token == JsDocToken.QMARK) { // A QMARK could mean that a type is nullable, or that it's unknown. // We use look-ahead 1 to determine whether it's unknown. Otherwise, // we assume it means nullable. There are 8 cases: // {?} - right curly // ? - EOF (possible when the parseTypeString method is given a bare type expression) // {?=} - equals // {function(?, number)} - comma // {function(number, ?)} - right paren // {function(): ?|number} - pipe // {Array.<?>} - greater than // /** ? */ - EOC (inline types) // I'm not a big fan of using look-ahead for this, but it makes // the type language a lot nicer. token = next(); if (token == JsDocToken.COMMA || token == JsDocToken.EQUALS || token == JsDocToken.RIGHT_SQUARE || token == JsDocToken.RIGHT_CURLY || token == JsDocToken.RIGHT_PAREN || token == JsDocToken.PIPE || token == JsDocToken.RIGHT_ANGLE || token == JsDocToken.EOC || token == JsDocToken.EOF) { restoreLookAhead(token); return newNode(Token.QMARK); } return wrapNode(Token.QMARK, parseBasicTypeExpression(token)); } else if (token == JsDocToken.BANG) { return wrapNode(Token.BANG, parseBasicTypeExpression(next())); } else { Node basicTypeExpr = parseBasicTypeExpression(token); if (basicTypeExpr != null) { if (match(JsDocToken.QMARK)) { next(); return wrapNode(Token.QMARK, basicTypeExpr); } else if (match(JsDocToken.BANG)) { next(); return wrapNode(Token.BANG, basicTypeExpr); } } return basicTypeExpr; } } /** * ContextTypeExpression := BasicTypeExpression | '?' * For expressions on the right hand side of a this: or new: */ private Node parseContextTypeExpression(JsDocToken token) { if (token == JsDocToken.QMARK) { return newNode(Token.QMARK); } else { return parseBasicTypeExpression(token); } } /** * BasicTypeExpression := '*' | 'null' | 'undefined' | TypeName * | FunctionType | UnionType | RecordType */ private Node parseBasicTypeExpression(JsDocToken token) { if (token == JsDocToken.STAR) { return newNode(Token.STAR); } else if (token == JsDocToken.LEFT_CURLY) { skipEOLs(); return parseRecordType(next()); } else if (token == JsDocToken.LEFT_PAREN) { skipEOLs(); return parseUnionType(next()); } else if (token == JsDocToken.STRING) { String string = stream.getString(); switch (string) { case "function": skipEOLs(); return parseFunctionType(next()); case "null": case "undefined": return newStringNode(string); default: return parseTypeName(token); } } restoreLookAhead(token); return reportGenericTypeSyntaxWarning(); } /** * TypeName := NameExpression | NameExpression TypeApplication * TypeApplication := '.<' TypeExpressionList '>' */ private Node parseTypeName(JsDocToken token) { if (token != JsDocToken.STRING) { return reportGenericTypeSyntaxWarning(); } String typeName = stream.getString(); int lineno = stream.getLineno(); int charno = stream.getCharno(); while (match(JsDocToken.EOL) && typeName.charAt(typeName.length() - 1) == '.') { skipEOLs(); if (match(JsDocToken.STRING)) { next(); typeName += stream.getString(); } } Node typeNameNode = newStringNode(typeName, lineno, charno); if (match(JsDocToken.LEFT_ANGLE)) { next(); skipEOLs(); Node memberType = parseTypeExpressionList(next()); if (memberType != null) { typeNameNode.addChildToFront(memberType); skipEOLs(); if (!match(JsDocToken.RIGHT_ANGLE)) { return reportTypeSyntaxWarning("msg.jsdoc.missing.gt"); } next(); } } return typeNameNode; } /** * FunctionType := 'function' FunctionSignatureType * FunctionSignatureType := * TypeParameters '(' 'this' ':' TypeName, ParametersType ')' ResultType * * <p>The Node that is produced has type Token.FUNCTION but does not look like a typical * function node. If there is a 'this:' or 'new:' type, that type is added as a child. * Then, if there are parameters, a PARAM_LIST node is added as a child. Finally, if * there is a return type, it is added as a child. This means that the parameters * could be the first or second child, and the return type could be * the first, second, or third child. */ private Node parseFunctionType(JsDocToken token) { // NOTE(nicksantos): We're not implementing generics at the moment, so // just throw out TypeParameters. if (token != JsDocToken.LEFT_PAREN) { restoreLookAhead(token); return reportTypeSyntaxWarning("msg.jsdoc.missing.lp"); } Node functionType = newNode(Token.FUNCTION); Node parameters = null; skipEOLs(); if (!match(JsDocToken.RIGHT_PAREN)) { token = next(); boolean hasParams = true; if (token == JsDocToken.STRING) { String tokenStr = stream.getString(); boolean isThis = "this".equals(tokenStr); boolean isNew = "new".equals(tokenStr); if (isThis || isNew) { if (match(JsDocToken.COLON)) { next(); skipEOLs(); Node contextType = wrapNode( isThis ? Token.THIS : Token.NEW, parseContextTypeExpression(next())); if (contextType == null) { return null; } functionType.addChildToFront(contextType); } else { return reportTypeSyntaxWarning("msg.jsdoc.missing.colon"); } if (match(JsDocToken.COMMA)) { next(); skipEOLs(); token = next(); } else { hasParams = false; } } } if (hasParams) { parameters = parseParametersType(token); if (parameters == null) { return null; } } } if (parameters != null) { functionType.addChildToBack(parameters); } skipEOLs(); if (!match(JsDocToken.RIGHT_PAREN)) { return reportTypeSyntaxWarning("msg.jsdoc.missing.rp"); } skipEOLs(); next(); Node resultType = parseResultType(); if (resultType == null) { return null; } else { functionType.addChildToBack(resultType); } return functionType; } /** * ParametersType := RestParameterType | NonRestParametersType * | NonRestParametersType ',' RestParameterType * RestParameterType := '...' Identifier * NonRestParametersType := ParameterType ',' NonRestParametersType * | ParameterType * | OptionalParametersType * OptionalParametersType := OptionalParameterType * | OptionalParameterType, OptionalParametersType * OptionalParameterType := ParameterType= * ParameterType := TypeExpression | Identifier ':' TypeExpression */ // NOTE(nicksantos): The official ES4 grammar forces optional and rest // arguments to come after the required arguments. Our parser does not // enforce this. Instead we allow them anywhere in the function at parse-time, // and then warn about them during type resolution. // // In theory, it might be mathematically nicer to do the order-checking here. // But in practice, the order-checking for structural functions is exactly // the same as the order-checking for @param annotations. And the latter // has to happen during type resolution. Rather than duplicate the // order-checking in two places, we just do all of it in type resolution. private Node parseParametersType(JsDocToken token) { Node paramsType = newNode(Token.PARAM_LIST); boolean isVarArgs = false; Node paramType = null; if (token != JsDocToken.RIGHT_PAREN) { do { if (paramType != null) { // skip past the comma next(); skipEOLs(); token = next(); } if (token == JsDocToken.ELLIPSIS) { // In the latest ES4 proposal, there are no type constraints allowed // on variable arguments. We support the old syntax for backwards // compatibility, but we should gradually tear it out. skipEOLs(); if (match(JsDocToken.RIGHT_PAREN)) { paramType = newNode(Token.ELLIPSIS); } else { skipEOLs(); paramType = wrapNode(Token.ELLIPSIS, parseTypeExpression(next())); skipEOLs(); } isVarArgs = true; } else { paramType = parseTypeExpression(token); if (match(JsDocToken.EQUALS)) { skipEOLs(); next(); paramType = wrapNode(Token.EQUALS, paramType); } } if (paramType == null) { return null; } paramsType.addChildToBack(paramType); if (isVarArgs) { break; } } while (match(JsDocToken.COMMA)); } if (isVarArgs && match(JsDocToken.COMMA)) { return reportTypeSyntaxWarning("msg.jsdoc.function.varargs"); } // The right paren will be checked by parseFunctionType return paramsType; } /** * ResultType := <empty> | ':' void | ':' TypeExpression */ private Node parseResultType() { skipEOLs(); if (!match(JsDocToken.COLON)) { return newNode(Token.EMPTY); } next(); skipEOLs(); if (match(JsDocToken.STRING) && "void".equals(stream.getString())) { next(); return newNode(Token.VOID); } else { return parseTypeExpression(next()); } } /** * UnionType := '(' TypeUnionList ')' * TypeUnionList := TypeExpression | TypeExpression '|' TypeUnionList * * We've removed the empty union type. */ private Node parseUnionType(JsDocToken token) { return parseUnionTypeWithAlternate(token, null); } /** * Create a new union type, with an alternate that has already been * parsed. The alternate may be null. */ private Node parseUnionTypeWithAlternate(JsDocToken token, Node alternate) { Node union = newNode(Token.PIPE); if (alternate != null) { union.addChildToBack(alternate); } Node expr = null; do { if (expr != null) { skipEOLs(); token = next(); Preconditions.checkState(token == JsDocToken.PIPE); skipEOLs(); token = next(); } expr = parseTypeExpression(token); if (expr == null) { return null; } union.addChildToBack(expr); } while (match(JsDocToken.PIPE)); if (alternate == null) { skipEOLs(); if (!match(JsDocToken.RIGHT_PAREN)) { return reportTypeSyntaxWarning("msg.jsdoc.missing.rp"); } next(); } if (union.getChildCount() == 1) { Node firstChild = union.getFirstChild(); union.removeChild(firstChild); return firstChild; } return union; } /** * RecordType := '{' FieldTypeList '}' */ private Node parseRecordType(JsDocToken token) { Node recordType = newNode(Token.LC); Node fieldTypeList = parseFieldTypeList(token); if (fieldTypeList == null) { return reportGenericTypeSyntaxWarning(); } skipEOLs(); if (!match(JsDocToken.RIGHT_CURLY)) { return reportTypeSyntaxWarning("msg.jsdoc.missing.rc"); } next(); recordType.addChildToBack(fieldTypeList); return recordType; } /** * FieldTypeList := FieldType | FieldType ',' FieldTypeList */ private Node parseFieldTypeList(JsDocToken token) { Node fieldTypeList = newNode(Token.LB); Set<String> names = new HashSet<>(); do { Node fieldType = parseFieldType(token); if (fieldType == null) { return null; } String name = fieldType.isStringKey() ? fieldType.getString() : fieldType.getFirstChild().getString(); if (names.add(name)) { fieldTypeList.addChildToBack(fieldType); } else { addTypeWarning("msg.jsdoc.type.record.duplicate", name); } skipEOLs(); if (!match(JsDocToken.COMMA)) { break; } // Move to the comma token. next(); // Move to the token past the comma skipEOLs(); if (match(JsDocToken.RIGHT_CURLY)) { // Allow trailing comma (ie, right curly following the comma) break; } token = next(); } while (true); return fieldTypeList; } /** * FieldType := FieldName | FieldName ':' TypeExpression */ private Node parseFieldType(JsDocToken token) { Node fieldName = parseFieldName(token); if (fieldName == null) { return null; } skipEOLs(); if (!match(JsDocToken.COLON)) { return fieldName; } // Move to the colon. next(); // Move to the token after the colon and parse // the type expression. skipEOLs(); Node typeExpression = parseTypeExpression(next()); if (typeExpression == null) { return null; } Node fieldType = newNode(Token.COLON); fieldType.addChildToBack(fieldName); fieldType.addChildToBack(typeExpression); return fieldType; } /** * FieldName := NameExpression | StringLiteral | NumberLiteral | * ReservedIdentifier */ private Node parseFieldName(JsDocToken token) { switch (token) { case STRING: String s = stream.getString(); Node n = Node.newString( Token.STRING_KEY, s, stream.getLineno(), stream.getCharno()) .clonePropsFrom(templateNode); n.setLength(s.length()); return n; default: return null; } } private Node wrapNode(Token type, Node n) { return n == null ? null : new Node(type, n, n.getLineno(), n.getCharno()).clonePropsFrom(templateNode); } private Node newNode(Token type) { return new Node(type, stream.getLineno(), stream.getCharno()).clonePropsFrom(templateNode); } private Node newStringNode(String s) { return newStringNode(s, stream.getLineno(), stream.getCharno()); } private Node newStringNode(String s, int lineno, int charno) { Node n = Node.newString(s, lineno, charno).clonePropsFrom(templateNode); n.setLength(s.length()); return n; } // This is similar to IRFactory.createTemplateNode to share common props // e.g., source-name, between all nodes. private Node createTemplateNode() { // The Node type choice is arbitrary. Node templateNode = IR.script(); templateNode.setStaticSourceFile( this.sourceFile); return templateNode; } private Node reportTypeSyntaxWarning(String warning) { addTypeWarning(warning, stream.getLineno(), stream.getCharno()); return null; } private Node reportGenericTypeSyntaxWarning() { return reportTypeSyntaxWarning("msg.jsdoc.type.syntax"); } private JsDocToken eatUntilEOLIfNotAnnotation() { return eatUntilEOLIfNotAnnotation(next()); } private JsDocToken eatUntilEOLIfNotAnnotation(JsDocToken token) { if (token == JsDocToken.ANNOTATION) { state = State.SEARCHING_ANNOTATION; return token; } return eatTokensUntilEOL(token); } /** * Eats tokens until {@link JsDocToken#EOL} included, and switches back the * state to {@link State#SEARCHING_ANNOTATION}. */ private JsDocToken eatTokensUntilEOL() { return eatTokensUntilEOL(next()); } /** * Eats tokens until {@link JsDocToken#EOL} included, and switches back the * state to {@link State#SEARCHING_ANNOTATION}. */ private JsDocToken eatTokensUntilEOL(JsDocToken token) { do { if (token == JsDocToken.EOL || token == JsDocToken.EOC || token == JsDocToken.EOF) { state = State.SEARCHING_ANNOTATION; return token; } token = next(); } while (true); } /** * Specific value indicating that the {@link #unreadToken} contains no token. */ private static final JsDocToken NO_UNREAD_TOKEN = null; /** * One token buffer. */ private JsDocToken unreadToken = NO_UNREAD_TOKEN; /** Restores the lookahead token to the token stream */ private void restoreLookAhead(JsDocToken token) { unreadToken = token; } /** * Tests whether the next symbol of the token stream matches the specific * token. */ private boolean match(JsDocToken token) { unreadToken = next(); return unreadToken == token; } /** * Tests that the next symbol of the token stream matches one of the specified * tokens. */ private boolean match(JsDocToken token1, JsDocToken token2) { unreadToken = next(); return unreadToken == token1 || unreadToken == token2; } /** * Gets the next token of the token stream or the buffered token if a matching * was previously made. */ private JsDocToken next() { if (unreadToken == NO_UNREAD_TOKEN) { return stream.getJsDocToken(); } else { return current(); } } /** * Gets the current token, invalidating it in the process. */ private JsDocToken current() { JsDocToken t = unreadToken; unreadToken = NO_UNREAD_TOKEN; return t; } /** * Skips all EOLs and all empty lines in the JSDoc. Call this method if you * want the JSDoc entry to span multiple lines. */ private void skipEOLs() { while (match(JsDocToken.EOL)) { next(); if (match(JsDocToken.STAR)) { next(); } } } /** * Returns the remainder of the line. */ private String getRemainingJSDocLine() { String result = stream.getRemainingJSDocLine(); unreadToken = NO_UNREAD_TOKEN; return result; } /** * Determines whether the parser has been populated with docinfo with a * fileoverview tag. */ private boolean hasParsedFileOverviewDocInfo() { return jsdocBuilder.isPopulatedWithFileOverview(); } JSDocInfo retrieveAndResetParsedJSDocInfo() { return jsdocBuilder.build(); } /** * Gets the fileoverview JSDocInfo, if any. */ JSDocInfo getFileOverviewJSDocInfo() { return fileOverviewJSDocInfo; } /** * Look ahead for a type annotation by advancing the character stream. * Does not modify the token stream. * This is kind of a hack, and is only necessary because we use the token * stream to parse types, but need the underlying character stream to get * JsDoc descriptions. * @return Whether we found a type annotation. */ private boolean lookAheadForType() { return lookAheadFor('{'); } private boolean lookAheadForAnnotation() { return lookAheadFor('@'); } /** * Look ahead by advancing the character stream. * Does not modify the token stream. * @return Whether we found the char. */ private boolean lookAheadFor(char expect) { boolean matched = false; int c; while (true) { c = stream.getChar(); if (c == ' ') { continue; } else if (c == expect) { matched = true; break; } else { break; } } stream.ungetChar(c); return matched; } }
LorenzoDV/closure-compiler
src/com/google/javascript/jscomp/parsing/JsDocInfoParser.java
Java
apache-2.0
85,162
// 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 com.cloud.api.query.dao; import java.util.List; import java.util.Map; import com.cloud.api.ApiDBUtils; import com.cloud.dc.VsphereStoragePolicyVO; import com.cloud.dc.dao.VsphereStoragePolicyDao; import com.cloud.server.ResourceTag; import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.response.DiskOfferingResponse; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import com.cloud.api.query.vo.DiskOfferingJoinVO; import com.cloud.offering.DiskOffering; import com.cloud.offering.ServiceOffering; import com.cloud.utils.db.Attribute; import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; import javax.inject.Inject; @Component public class DiskOfferingJoinDaoImpl extends GenericDaoBase<DiskOfferingJoinVO, Long> implements DiskOfferingJoinDao { public static final Logger s_logger = Logger.getLogger(DiskOfferingJoinDaoImpl.class); @Inject VsphereStoragePolicyDao _vsphereStoragePolicyDao; private final SearchBuilder<DiskOfferingJoinVO> dofIdSearch; private final Attribute _typeAttr; protected DiskOfferingJoinDaoImpl() { dofIdSearch = createSearchBuilder(); dofIdSearch.and("id", dofIdSearch.entity().getId(), SearchCriteria.Op.EQ); dofIdSearch.done(); _typeAttr = _allAttributes.get("type"); _count = "select count(distinct id) from disk_offering_view WHERE "; } @Override public List<DiskOfferingJoinVO> findByDomainId(long domainId) { SearchBuilder<DiskOfferingJoinVO> sb = createSearchBuilder(); sb.and("domainId", sb.entity().getDomainId(), SearchCriteria.Op.FIND_IN_SET); sb.done(); SearchCriteria<DiskOfferingJoinVO> sc = sb.create(); sc.setParameters("domainId", String.valueOf(domainId)); return listBy(sc); } @Override public List<DiskOfferingJoinVO> findByZoneId(long zoneId) { SearchBuilder<DiskOfferingJoinVO> sb = createSearchBuilder(); sb.and("zoneId", sb.entity().getZoneId(), SearchCriteria.Op.FIND_IN_SET); sb.done(); SearchCriteria<DiskOfferingJoinVO> sc = sb.create(); sc.setParameters("zoneId", String.valueOf(zoneId)); return listBy(sc); } @Override public DiskOfferingResponse newDiskOfferingResponse(DiskOfferingJoinVO offering) { DiskOfferingResponse diskOfferingResponse = new DiskOfferingResponse(); diskOfferingResponse.setId(offering.getUuid()); diskOfferingResponse.setName(offering.getName()); diskOfferingResponse.setDisplayText(offering.getDisplayText()); diskOfferingResponse.setProvisioningType(offering.getProvisioningType().toString()); diskOfferingResponse.setCreated(offering.getCreated()); diskOfferingResponse.setDiskSize(offering.getDiskSize() / (1024 * 1024 * 1024)); diskOfferingResponse.setMinIops(offering.getMinIops()); diskOfferingResponse.setMaxIops(offering.getMaxIops()); diskOfferingResponse.setDisplayOffering(offering.isDisplayOffering()); diskOfferingResponse.setDomainId(offering.getDomainUuid()); diskOfferingResponse.setDomain(offering.getDomainPath()); diskOfferingResponse.setZoneId(offering.getZoneUuid()); diskOfferingResponse.setZone(offering.getZoneName()); diskOfferingResponse.setTags(offering.getTags()); diskOfferingResponse.setCustomized(offering.isCustomized()); diskOfferingResponse.setCustomizedIops(offering.isCustomizedIops()); diskOfferingResponse.setHypervisorSnapshotReserve(offering.getHypervisorSnapshotReserve()); diskOfferingResponse.setStorageType(offering.isUseLocalStorage() ? ServiceOffering.StorageType.local.toString() : ServiceOffering.StorageType.shared.toString()); diskOfferingResponse.setBytesReadRate(offering.getBytesReadRate()); diskOfferingResponse.setBytesReadRateMax(offering.getBytesReadRateMax()); diskOfferingResponse.setBytesReadRateMaxLength(offering.getBytesReadRateMaxLength()); diskOfferingResponse.setBytesWriteRate(offering.getBytesWriteRate()); diskOfferingResponse.setBytesWriteRateMax(offering.getBytesWriteRateMax()); diskOfferingResponse.setBytesWriteRateMaxLength(offering.getBytesWriteRateMaxLength()); diskOfferingResponse.setIopsReadRate(offering.getIopsReadRate()); diskOfferingResponse.setIopsReadRateMax(offering.getIopsReadRateMax()); diskOfferingResponse.setIopsReadRateMaxLength(offering.getIopsReadRateMaxLength()); diskOfferingResponse.setIopsWriteRate(offering.getIopsWriteRate()); diskOfferingResponse.setIopsWriteRateMax(offering.getIopsWriteRateMax()); diskOfferingResponse.setIopsWriteRateMaxLength(offering.getIopsWriteRateMaxLength()); diskOfferingResponse.setCacheMode(offering.getCacheMode()); diskOfferingResponse.setObjectName("diskoffering"); Map<String, String> offeringDetails = ApiDBUtils.getResourceDetails(offering.getId(), ResourceTag.ResourceObjectType.DiskOffering); if (offeringDetails != null && !offeringDetails.isEmpty()) { String vsphereStoragePolicyId = offeringDetails.get(ApiConstants.STORAGE_POLICY); if (vsphereStoragePolicyId != null) { VsphereStoragePolicyVO vsphereStoragePolicyVO = _vsphereStoragePolicyDao.findById(Long.parseLong(vsphereStoragePolicyId)); if (vsphereStoragePolicyVO != null) diskOfferingResponse.setVsphereStoragePolicy(vsphereStoragePolicyVO.getName()); } } return diskOfferingResponse; } @Override public DiskOfferingJoinVO newDiskOfferingView(DiskOffering offering) { SearchCriteria<DiskOfferingJoinVO> sc = dofIdSearch.create(); sc.setParameters("id", offering.getId()); List<DiskOfferingJoinVO> offerings = searchIncludingRemoved(sc, null, null, false); assert offerings != null && offerings.size() == 1 : "No disk offering found for offering id " + offering.getId(); return offerings.get(0); } }
GabrielBrascher/cloudstack
server/src/main/java/com/cloud/api/query/dao/DiskOfferingJoinDaoImpl.java
Java
apache-2.0
6,981
package com.dglogik.mobile; public interface Executable extends Runnable { }
IOT-DSA/dslink-java-android
mobile/src/main/java/com/dglogik/mobile/Executable.java
Java
apache-2.0
78
/* * 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 net.jini.io; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.util.Collection; import net.jini.loader.RiverClassLoader; /** * An extension of <code>ObjectOutputStream</code> that implements the * dynamic class loading semantics of Java(TM) Remote Method Invocation * (Java RMI) argument and result * marshalling (using {@link RiverClassLoader}). A * <code>MarshalOutputStream</code> writes data that is intended to be * written by a corresponding {@link MarshalInputStream}. * * <p><code>MarshalOutputStream</code> implements the output side of * the dynamic class loading semantics by overriding {@link * ObjectOutputStream#annotateClass annotateClass} and {@link * ObjectOutputStream#annotateProxyClass annotateProxyClass} to * annotate class descriptors in the stream with codebase strings * obtained using {@link RiverClassLoader#getClassAnnotation * RiverClassLoader.getClassAnnotation}. * * <p><code>MarshalOutputStream</code> writes class annotations to its * own stream; a subclass may override the {@link #writeAnnotation * writeAnnotation} method to write the class annotations to a * different location. * * <p><code>MarshalOutputStream</code> does not modify the stream * protocol version of its instances' superclass state (see {@link * ObjectOutputStream#useProtocolVersion * ObjectOutputStream.useProtocolVersion}). * * * @since 2.0 **/ public class MarshalOutputStream extends ObjectOutputStream implements ObjectStreamContext { /** context for ObjectStreamContext implementation */ private final Collection context; /** * Creates a new <code>MarshalOutputStream</code> that writes * marshalled data to the specified underlying * <code>OutputStream</code>. * * <p>This constructor passes <code>out</code> to the superclass * constructor that has an <code>OutputStream</code> parameter. * * <p><code>context</code> will be used as the return value of the * created stream's {@link #getObjectStreamContext * getObjectStreamContext} method. * * @param out the output stream to write marshalled data to * * @param context the collection of context information objects to * be returned by this stream's {@link #getObjectStreamContext * getObjectStreamContext} method * * @throws IOException if the superclass's constructor throws an * <code>IOException</code> * * @throws SecurityException if the superclass's constructor * throws a <code>SecurityException</code> * * @throws NullPointerException if <code>out</code> or * <code>context</code> is <code>null</code> **/ public MarshalOutputStream(OutputStream out, Collection context) throws IOException { super(out); if (context == null) { throw new NullPointerException(); } this.context = context; } /** * Returns the collection of context information objects that * was passed to this stream's constructor. **/ public Collection getObjectStreamContext() { return context; } /** * Annotates the stream descriptor for the class <code>cl</code>. * * <p><code>MarshalOutputStream</code> implements this method as * follows: * * <p>This method invokes {@link RiverClassLoader#getClassAnnotation * RiverClassLoader.getClassAnnotation} with <code>cl</code> to get * the appropriate class annotation string value (possibly * <code>null</code>), and then it invokes this stream's {@link * #writeAnnotation writeAnnotation} method with that string to * record the annotation. * * @param cl the class to annotate * * @throws IOException if <code>writeAnnotation</code> throws an * <code>IOException</code> * * @throws NullPointerException if <code>cl</code> is * <code>null</code> **/ protected void annotateClass(Class cl) throws IOException { writeAnnotation(RiverClassLoader.getClassAnnotation(cl)); } /** * Annotates the stream descriptor for the proxy class * <code>cl</code>. * * <p><code>MarshalOutputStream</code> implements this method as * follows: * * <p>This method invokes {@link RiverClassLoader#getClassAnnotation * RiverClassLoader.getClassAnnotation} with <code>cl</code> to get * the appropriate class annotation string value (possibly * <code>null</code>), and then it invokes this stream's {@link * #writeAnnotation writeAnnotation} method with that string to * record the annotation. * * @param cl the proxy class to annotate * * @throws IOException if <code>writeAnnotation</code> throws an * <code>IOException</code> * * @throws NullPointerException if <code>cl</code> is * <code>null</code> **/ protected void annotateProxyClass(Class cl) throws IOException { writeAnnotation(RiverClassLoader.getClassAnnotation(cl)); } /** * Writes a class annotation string value (possibly * <code>null</code>) to be read by a corresponding * <code>MarshalInputStream</code> implementation. * * <p><code>MarshalOutputStream</code> implements this method to * just write the annotation value to this stream using {@link * ObjectOutputStream#writeObject writeObject}. * * <p>A subclass can override this method to write the annotation * to a different location. * * @param annotation the class annotation string value (possibly * <code>null</code>) to write * * @throws IOException if I/O exception occurs writing the * annotation **/ protected void writeAnnotation(String annotation) throws IOException { writeObject(annotation); } }
cdegroot/river
src/net/jini/io/MarshalOutputStream.java
Java
apache-2.0
6,631
package test; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) @SuiteClasses({ TestCompositeDiscount.class, ProductDiscountTest.class, EventDiscountTest.class, CustomerDiscountTest.class, HKCurrencyTest.class, USCurrencyTest.class, POSBatchModeTest.class, POSConsoleModeTest.class, TMNoTaxTest.class, TMVATTest.class, PaymentTest.class, CurrencyFactoryTest.class }) public class CSIT5100_TestMain { }
KeithYue/POS
src/test/CSIT5100_TestMain.java
Java
apache-2.0
499
package de.immobilienscout24.rest.facades.offer.realestates._1; import de.immobilienscout24.rest.schema.common._1.CommercializationType; import de.immobilienscout24.rest.schema.common._1.CourtageInfo; import de.immobilienscout24.rest.schema.common._1.LeaseIntervalType; import de.immobilienscout24.rest.schema.common._1.Price; import de.immobilienscout24.rest.schema.common._1.SiteConstructibleType; import de.immobilienscout24.rest.schema.common._1.SiteDevelopmentType; import de.immobilienscout24.rest.schema.offer.realestates._1.TradeSite; public class TradeSiteFacade implements SiteFacade { final private TradeSite realestate; public TradeSiteFacade(TradeSite realestate) { this.realestate = realestate; } public TradeSite get() { return realestate; } public void setLeaseInterval(LeaseIntervalType value) { realestate.setLeaseInterval(value); } public CommercializationType getCommercializationType() { return realestate.getCommercializationType(); } public void setCommercializationType(CommercializationType value) { realestate.setCommercializationType(value); } public Integer getTenancy() { return realestate.getTenancy(); } public void setTenancy(Integer value) { realestate.setTenancy(value); } public Price getPrice() { return realestate.getPrice(); } public void setPrice(Price value) { realestate.setPrice(value); } public double getPlotArea() { return realestate.getPlotArea(); } public void setPlotArea(double value) { realestate.setPlotArea(value); } public Double getMinDivisible() { return realestate.getMinDivisible(); } public void setMinDivisible(Double value) { realestate.setMinDivisible(value); } public CourtageInfo getCourtage() { return realestate.getCourtage(); } public void setCourtage(CourtageInfo value) { realestate.setCourtage(value); } public String getFreeFrom() { return realestate.getFreeFrom(); } public void setFreeFrom(String value) { realestate.setFreeFrom(value); } public Boolean isShortTermConstructible() { return realestate.isShortTermConstructible(); } public void setShortTermConstructible(Boolean value) { realestate.setShortTermConstructible(value); } public Boolean isBuildingPermission() { return realestate.isBuildingPermission(); } public void setBuildingPermission(Boolean value) { realestate.setBuildingPermission(value); } public Boolean isDemolition() { return realestate.isDemolition(); } public void setDemolition(Boolean value) { realestate.setDemolition(value); } public SiteDevelopmentType getSiteDevelopmentType() { return realestate.getSiteDevelopmentType(); } public void setSiteDevelopmentType(SiteDevelopmentType value) { realestate.setSiteDevelopmentType(value); } public SiteConstructibleType getSiteConstructibleType() { return realestate.getSiteConstructibleType(); } public void setSiteConstructibleType(SiteConstructibleType value) { realestate.setSiteConstructibleType(value); } public Double getGrz() { return realestate.getGrz(); } public void setGrz(Double value) { realestate.setGrz(value); } public Double getGfz() { return realestate.getGfz(); } public void setGfz(Double value) { realestate.setGfz(value); } public LeaseIntervalType getLeaseInterval() { return realestate.getLeaseInterval(); } }
ImmobilienScout24/restapi-java-sdk
src/main/java/de/immobilienscout24/rest/facades/offer/realestates/_1/TradeSiteFacade.java
Java
apache-2.0
3,345
/* * 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.jasper.runtime; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.jsp.JspFactory; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.PageContext; import io.undertow.test.TomcatBaseTest; import org.junit.Assert; import org.junit.Test; import org.apache.jasper.Constants; import org.apache.tomcat.util.buf.ByteChunk; public class TestPageContextImpl extends TomcatBaseTest { @Test public void testDoForward() throws Exception { getTomcatInstanceTestWebapp(false, true); ByteChunk res = new ByteChunk(); int rc = getUrl("http://localhost:" + getPort() + "/test/bug5nnnn/bug53545.jsp", res, null); Assert.assertEquals(HttpServletResponse.SC_OK, rc); String body = res.toString(); Assert.assertTrue(body.contains("OK")); Assert.assertFalse(body.contains("FAIL")); } @Test public void testIncludeThrowsIOException() throws Exception { getTomcatInstanceTestWebapp(false, true); ByteChunk res = new ByteChunk(); int rc = getUrl("http://localhost:" + getPort() + "/test/jsp/pageContext1.jsp", res, null); Assert.assertEquals(HttpServletResponse.SC_OK, rc); String body = res.toString(); Assert.assertTrue(body.contains("OK")); Assert.assertFalse(body.contains("FAILED")); res = new ByteChunk(); rc = getUrl("http://localhost:" + getPort() + "/test/jsp/pageContext1.jsp?flush=true", res, null); Assert.assertEquals(HttpServletResponse.SC_OK, rc); body = res.toString(); Assert.assertTrue(body.contains("Flush")); Assert.assertTrue(body.contains("OK")); Assert.assertFalse(body.contains("FAILED")); } public static class Bug56010 extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { PageContext pageContext = JspFactory.getDefaultFactory().getPageContext( this, req, resp, null, false, JspWriter.DEFAULT_BUFFER, true); JspWriter out = pageContext.getOut(); if (Constants.DEFAULT_BUFFER_SIZE == out.getBufferSize()) { resp.getWriter().println("OK"); } else { resp.getWriter().println("FAIL"); } } } }
undertow-io/jastow
src/test/java/org/apache/jasper/runtime/TestPageContextImpl.java
Java
apache-2.0
3,450
/* * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.liquigraph.trinity; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Iterator; import java.util.Optional; import java.util.Properties; import java.util.ServiceLoader; import java.util.Spliterators; import java.util.stream.Stream; import java.util.stream.StreamSupport; import static java.util.Spliterator.ORDERED; public final class CypherClientLookup { private static final Logger LOGGER = LoggerFactory.getLogger(CypherClientLookup.class); private final Iterator<CypherClientCreator> clients; public CypherClientLookup() { clients = ServiceLoader.load(CypherClientCreator.class).iterator(); } public Optional<CypherClient<OngoingTransaction>> getInstance(CypherTransport transport, Properties configuration) { LOGGER.debug("Starting Cypher client discovery for transport {}", transport); Optional<CypherClient<OngoingTransaction>> result = lookUp(transport, configuration); return logAbsence(transport, result); } private Optional<CypherClient<OngoingTransaction>> lookUp(CypherTransport transport, Properties configuration) { return createStream(clients, ORDERED) .filter(serviceCreator -> serviceCreator.supports(transport)) .findFirst() .map(creator -> { LOGGER.info("Found implementation of type {} for transport {}", creator.getClass(), transport); return creator.create(configuration); }); } private Optional<CypherClient<OngoingTransaction>> logAbsence(CypherTransport transport, Optional<CypherClient<OngoingTransaction>> result) { if (!result.isPresent()) { LOGGER.error("No implementations could be found for {}", transport); return result; } return result; } private static <T> Stream<T> createStream(Iterator<T> iterator, int characteristics) { return StreamSupport.stream( Spliterators.spliteratorUnknownSize(iterator, characteristics), false ); } }
mgazanayi/trinity
trinity-neo4j-v3/src/main/java/org/liquigraph/trinity/CypherClientLookup.java
Java
apache-2.0
2,750
/* * Copyright (c) 2014 Wael Chatila / Icegreen Technologies. All Rights Reserved. * This software is released under the Apache license 2.0 * This file has been used and modified. * Original file can be found on http://foedus.sourceforge.net */ package com.icegreen.greenmail.smtp.commands; import com.icegreen.greenmail.smtp.SmtpConnection; import com.icegreen.greenmail.smtp.SmtpManager; import com.icegreen.greenmail.smtp.SmtpState; /** * EHLO/HELO command. * <p/> * TODO: What does HELO do if it's already been called before? * <p/> * <a https://tools.ietf.org/html/rfc2821#section-4.1.1.1">RFC2821</a> * <a href="https://tools.ietf.org/html/rfc4954">RFC4954</a> * <a href="https://tools.ietf.org/html/rfc2554">RFC2554</a> */ public class HeloCommand extends SmtpCommand { @Override public void execute(SmtpConnection conn, SmtpState state, SmtpManager manager, String commandLine) { extractHeloName(conn, commandLine); state.clearMessage(); conn.send("250-" + conn.getServerGreetingsName()); conn.send("250 AUTH "+AuthCommand.SUPPORTED_AUTH_MECHANISM); } private void extractHeloName(SmtpConnection conn, String commandLine) { String heloName; if (commandLine.length() > 5) heloName = commandLine.substring(5); else heloName = null; conn.setHeloName(heloName); } }
greenmail-mail-test/greenmail
greenmail-core/src/main/java/com/icegreen/greenmail/smtp/commands/HeloCommand.java
Java
apache-2.0
1,461
/* * Copyright (c) 2013-2015, Arjuna Technologies Limited, Newcastle-upon-Tyne, England. All rights reserved. */ package com.arjuna.databroker.data.core.jee; import java.util.Map; import com.arjuna.databroker.data.DataFlow; import com.arjuna.databroker.data.DataFlowNodeFactoryInventory; import com.arjuna.databroker.data.DataFlowNodeInventory; public abstract class AbstractJEEDataFlow implements DataFlow { public AbstractJEEDataFlow(String name, Map<String, String> properties) { _name = name; _properties = properties; _dataFlowNodeInventory = new JEEDataFlowNodeInventory(); _dataFlowNodeFactoryInventory = new JEEDataFlowNodeFactoryInventory(); } @Override public String getName() { return _name; } public void setName(String name) { _name = name; } @Override public Map<String, String> getProperties() { return _properties; } public void setProperties(Map<String, String> properties) { _properties = properties; } @Override public DataFlowNodeInventory getDataFlowNodeInventory() { return _dataFlowNodeInventory; } @Override public DataFlowNodeFactoryInventory getDataFlowNodeFactoryInventory() { return _dataFlowNodeFactoryInventory; } private String _name; private Map<String, String> _properties; private DataFlowNodeInventory _dataFlowNodeInventory; private DataFlowNodeFactoryInventory _dataFlowNodeFactoryInventory; }
RISBIC/DataBroker
data-core-jee/src/main/java/com/arjuna/databroker/data/core/jee/AbstractJEEDataFlow.java
Java
apache-2.0
1,626
/* * Copyright (C) 2018 Google 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.google.iot.m2m.base; /** * Checked exception indicating that this {@link Technology} does not support groups. * * @see Technology#createNewGroup() */ public class GroupsNotSupportedException extends TechnologyException { public GroupsNotSupportedException() {} @SuppressWarnings("unused") public GroupsNotSupportedException(String reason) { super(reason); } @SuppressWarnings("unused") public GroupsNotSupportedException(String reason, Throwable t) { super(reason, t); } @SuppressWarnings("unused") public GroupsNotSupportedException(Throwable t) { super(t); } }
google/splot-java
splot-base/src/main/java/com/google/iot/m2m/base/GroupsNotSupportedException.java
Java
apache-2.0
1,242
package com.github.chrisprice.phonegapbuild.api.managers; import com.github.chrisprice.phonegapbuild.api.PatchedMultiPartWriter; import com.github.chrisprice.phonegapbuild.api.data.me.MeResponse; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.json.JSONConfiguration; import com.sun.jersey.client.apache.ApacheHttpClient; import com.sun.jersey.client.apache.config.DefaultApacheHttpClientConfig; public class MeManagerImpl implements MeManager { private static class TokenResponse { private String token; public String getToken() { return token; } } private static final String TOKEN_PARAM = "auth_token"; @Override public WebResource createRootWebResource(String username, String password) { return createRootWebResource(username, password, null); } @Override public WebResource createRootWebResource(String username, String password, String proxyUri) { // create a DefaultApacheHttpClientConfig (instead of just a ClientConfig) DefaultApacheHttpClientConfig config = new DefaultApacheHttpClientConfig(); // configure it to use a proxy if (proxyUri != null) { config.getProperties().put(DefaultApacheHttpClientConfig.PROPERTY_PROXY_URI, proxyUri); } // configure it to parse JSON to POJOs config.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); // configure to follow re-directs (used for downloading packages) config.getProperties().put(DefaultApacheHttpClientConfig.PROPERTY_FOLLOW_REDIRECTS, Boolean.TRUE); // set http auth credentials config.getState().setCredentials(null, null, -1, username, password); // configure it to explicity use the patched MultiPartWriter config.getClasses().add(PatchedMultiPartWriter.class); // create an ApacheHttpClient (instead of just a Client) ApacheHttpClient c = ApacheHttpClient.create(config); // create a resource WebResource webResource = c.resource("https://build.phonegap.com"); // fetch a token TokenResponse tokenResponse = requestToken(webResource); // associate the token with all future requests return webResource.queryParam(TOKEN_PARAM, tokenResponse.getToken()); } private TokenResponse requestToken(WebResource resource) { return resource.path(TOKEN_PATH).post(TokenResponse.class); } /* (non-Javadoc) * @see com.github.chrisprice.phonegapbuild.api.managers.MeManager#requestMe(com.sun.jersey.api.client.WebResource) */ @Override public MeResponse requestMe(WebResource resource) { return resource.path(API_V1_PATH).get(MeResponse.class); } }
margaritis/phonegap-build
api/src/main/java/com/github/chrisprice/phonegapbuild/api/managers/MeManagerImpl.java
Java
apache-2.0
2,613
/* * Copyright 2020 Google 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 * * 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. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/bigquery/storage/v1beta2/storage.proto package com.google.cloud.bigquery.storage.v1beta2; /** * * * <pre> * Structured custom BigQuery Storage error message. The error can be attached * as error details in the returned rpc Status. In particular, the use of error * codes allows more structured error handling, and reduces the need to evaluate * unstructured error text strings. * </pre> * * Protobuf type {@code google.cloud.bigquery.storage.v1beta2.StorageError} */ public final class StorageError extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.bigquery.storage.v1beta2.StorageError) StorageErrorOrBuilder { private static final long serialVersionUID = 0L; // Use StorageError.newBuilder() to construct. private StorageError(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private StorageError() { code_ = 0; entity_ = ""; errorMessage_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new StorageError(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private StorageError( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 8: { int rawValue = input.readEnum(); code_ = rawValue; break; } case 18: { java.lang.String s = input.readStringRequireUtf8(); entity_ = s; break; } case 26: { java.lang.String s = input.readStringRequireUtf8(); errorMessage_ = s; break; } default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.bigquery.storage.v1beta2.StorageProto .internal_static_google_cloud_bigquery_storage_v1beta2_StorageError_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.bigquery.storage.v1beta2.StorageProto .internal_static_google_cloud_bigquery_storage_v1beta2_StorageError_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.bigquery.storage.v1beta2.StorageError.class, com.google.cloud.bigquery.storage.v1beta2.StorageError.Builder.class); } /** * * * <pre> * Error code for `StorageError`. * </pre> * * Protobuf enum {@code google.cloud.bigquery.storage.v1beta2.StorageError.StorageErrorCode} */ public enum StorageErrorCode implements com.google.protobuf.ProtocolMessageEnum { /** * * * <pre> * Default error. * </pre> * * <code>STORAGE_ERROR_CODE_UNSPECIFIED = 0;</code> */ STORAGE_ERROR_CODE_UNSPECIFIED(0), /** * * * <pre> * Table is not found in the system. * </pre> * * <code>TABLE_NOT_FOUND = 1;</code> */ TABLE_NOT_FOUND(1), /** * * * <pre> * Stream is already committed. * </pre> * * <code>STREAM_ALREADY_COMMITTED = 2;</code> */ STREAM_ALREADY_COMMITTED(2), /** * * * <pre> * Stream is not found. * </pre> * * <code>STREAM_NOT_FOUND = 3;</code> */ STREAM_NOT_FOUND(3), /** * * * <pre> * Invalid Stream type. * For example, you try to commit a stream that is not pending. * </pre> * * <code>INVALID_STREAM_TYPE = 4;</code> */ INVALID_STREAM_TYPE(4), /** * * * <pre> * Invalid Stream state. * For example, you try to commit a stream that is not finalized or is * garbaged. * </pre> * * <code>INVALID_STREAM_STATE = 5;</code> */ INVALID_STREAM_STATE(5), /** * * * <pre> * Stream is finalized. * </pre> * * <code>STREAM_FINALIZED = 6;</code> */ STREAM_FINALIZED(6), UNRECOGNIZED(-1), ; /** * * * <pre> * Default error. * </pre> * * <code>STORAGE_ERROR_CODE_UNSPECIFIED = 0;</code> */ public static final int STORAGE_ERROR_CODE_UNSPECIFIED_VALUE = 0; /** * * * <pre> * Table is not found in the system. * </pre> * * <code>TABLE_NOT_FOUND = 1;</code> */ public static final int TABLE_NOT_FOUND_VALUE = 1; /** * * * <pre> * Stream is already committed. * </pre> * * <code>STREAM_ALREADY_COMMITTED = 2;</code> */ public static final int STREAM_ALREADY_COMMITTED_VALUE = 2; /** * * * <pre> * Stream is not found. * </pre> * * <code>STREAM_NOT_FOUND = 3;</code> */ public static final int STREAM_NOT_FOUND_VALUE = 3; /** * * * <pre> * Invalid Stream type. * For example, you try to commit a stream that is not pending. * </pre> * * <code>INVALID_STREAM_TYPE = 4;</code> */ public static final int INVALID_STREAM_TYPE_VALUE = 4; /** * * * <pre> * Invalid Stream state. * For example, you try to commit a stream that is not finalized or is * garbaged. * </pre> * * <code>INVALID_STREAM_STATE = 5;</code> */ public static final int INVALID_STREAM_STATE_VALUE = 5; /** * * * <pre> * Stream is finalized. * </pre> * * <code>STREAM_FINALIZED = 6;</code> */ public static final int STREAM_FINALIZED_VALUE = 6; public final int getNumber() { if (this == UNRECOGNIZED) { throw new java.lang.IllegalArgumentException( "Can't get the number of an unknown enum value."); } return value; } /** * @param value The numeric wire value of the corresponding enum entry. * @return The enum associated with the given numeric wire value. * @deprecated Use {@link #forNumber(int)} instead. */ @java.lang.Deprecated public static StorageErrorCode valueOf(int value) { return forNumber(value); } /** * @param value The numeric wire value of the corresponding enum entry. * @return The enum associated with the given numeric wire value. */ public static StorageErrorCode forNumber(int value) { switch (value) { case 0: return STORAGE_ERROR_CODE_UNSPECIFIED; case 1: return TABLE_NOT_FOUND; case 2: return STREAM_ALREADY_COMMITTED; case 3: return STREAM_NOT_FOUND; case 4: return INVALID_STREAM_TYPE; case 5: return INVALID_STREAM_STATE; case 6: return STREAM_FINALIZED; default: return null; } } public static com.google.protobuf.Internal.EnumLiteMap<StorageErrorCode> internalGetValueMap() { return internalValueMap; } private static final com.google.protobuf.Internal.EnumLiteMap<StorageErrorCode> internalValueMap = new com.google.protobuf.Internal.EnumLiteMap<StorageErrorCode>() { public StorageErrorCode findValueByNumber(int number) { return StorageErrorCode.forNumber(number); } }; public final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor() { if (this == UNRECOGNIZED) { throw new java.lang.IllegalStateException( "Can't get the descriptor of an unrecognized enum value."); } return getDescriptor().getValues().get(ordinal()); } public final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType() { return getDescriptor(); } public static final com.google.protobuf.Descriptors.EnumDescriptor getDescriptor() { return com.google.cloud.bigquery.storage.v1beta2.StorageError.getDescriptor() .getEnumTypes() .get(0); } private static final StorageErrorCode[] VALUES = values(); public static StorageErrorCode valueOf( com.google.protobuf.Descriptors.EnumValueDescriptor desc) { if (desc.getType() != getDescriptor()) { throw new java.lang.IllegalArgumentException("EnumValueDescriptor is not for this type."); } if (desc.getIndex() == -1) { return UNRECOGNIZED; } return VALUES[desc.getIndex()]; } private final int value; private StorageErrorCode(int value) { this.value = value; } // @@protoc_insertion_point(enum_scope:google.cloud.bigquery.storage.v1beta2.StorageError.StorageErrorCode) } public static final int CODE_FIELD_NUMBER = 1; private int code_; /** * * * <pre> * BigQuery Storage specific error code. * </pre> * * <code>.google.cloud.bigquery.storage.v1beta2.StorageError.StorageErrorCode code = 1;</code> * * @return The enum numeric value on the wire for code. */ @java.lang.Override public int getCodeValue() { return code_; } /** * * * <pre> * BigQuery Storage specific error code. * </pre> * * <code>.google.cloud.bigquery.storage.v1beta2.StorageError.StorageErrorCode code = 1;</code> * * @return The code. */ @java.lang.Override public com.google.cloud.bigquery.storage.v1beta2.StorageError.StorageErrorCode getCode() { @SuppressWarnings("deprecation") com.google.cloud.bigquery.storage.v1beta2.StorageError.StorageErrorCode result = com.google.cloud.bigquery.storage.v1beta2.StorageError.StorageErrorCode.valueOf(code_); return result == null ? com.google.cloud.bigquery.storage.v1beta2.StorageError.StorageErrorCode.UNRECOGNIZED : result; } public static final int ENTITY_FIELD_NUMBER = 2; private volatile java.lang.Object entity_; /** * * * <pre> * Name of the failed entity. * </pre> * * <code>string entity = 2;</code> * * @return The entity. */ @java.lang.Override public java.lang.String getEntity() { java.lang.Object ref = entity_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); entity_ = s; return s; } } /** * * * <pre> * Name of the failed entity. * </pre> * * <code>string entity = 2;</code> * * @return The bytes for entity. */ @java.lang.Override public com.google.protobuf.ByteString getEntityBytes() { java.lang.Object ref = entity_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); entity_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int ERROR_MESSAGE_FIELD_NUMBER = 3; private volatile java.lang.Object errorMessage_; /** * * * <pre> * Message that describes the error. * </pre> * * <code>string error_message = 3;</code> * * @return The errorMessage. */ @java.lang.Override public java.lang.String getErrorMessage() { java.lang.Object ref = errorMessage_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); errorMessage_ = s; return s; } } /** * * * <pre> * Message that describes the error. * </pre> * * <code>string error_message = 3;</code> * * @return The bytes for errorMessage. */ @java.lang.Override public com.google.protobuf.ByteString getErrorMessageBytes() { java.lang.Object ref = errorMessage_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); errorMessage_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (code_ != com.google.cloud.bigquery.storage.v1beta2.StorageError.StorageErrorCode .STORAGE_ERROR_CODE_UNSPECIFIED .getNumber()) { output.writeEnum(1, code_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(entity_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, entity_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(errorMessage_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 3, errorMessage_); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (code_ != com.google.cloud.bigquery.storage.v1beta2.StorageError.StorageErrorCode .STORAGE_ERROR_CODE_UNSPECIFIED .getNumber()) { size += com.google.protobuf.CodedOutputStream.computeEnumSize(1, code_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(entity_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, entity_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(errorMessage_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, errorMessage_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.bigquery.storage.v1beta2.StorageError)) { return super.equals(obj); } com.google.cloud.bigquery.storage.v1beta2.StorageError other = (com.google.cloud.bigquery.storage.v1beta2.StorageError) obj; if (code_ != other.code_) return false; if (!getEntity().equals(other.getEntity())) return false; if (!getErrorMessage().equals(other.getErrorMessage())) return false; if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + CODE_FIELD_NUMBER; hash = (53 * hash) + code_; hash = (37 * hash) + ENTITY_FIELD_NUMBER; hash = (53 * hash) + getEntity().hashCode(); hash = (37 * hash) + ERROR_MESSAGE_FIELD_NUMBER; hash = (53 * hash) + getErrorMessage().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.bigquery.storage.v1beta2.StorageError parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.bigquery.storage.v1beta2.StorageError parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.bigquery.storage.v1beta2.StorageError parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.bigquery.storage.v1beta2.StorageError parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.bigquery.storage.v1beta2.StorageError parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.bigquery.storage.v1beta2.StorageError parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.bigquery.storage.v1beta2.StorageError parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.bigquery.storage.v1beta2.StorageError parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.bigquery.storage.v1beta2.StorageError parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.bigquery.storage.v1beta2.StorageError parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.bigquery.storage.v1beta2.StorageError parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.bigquery.storage.v1beta2.StorageError parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.bigquery.storage.v1beta2.StorageError prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Structured custom BigQuery Storage error message. The error can be attached * as error details in the returned rpc Status. In particular, the use of error * codes allows more structured error handling, and reduces the need to evaluate * unstructured error text strings. * </pre> * * Protobuf type {@code google.cloud.bigquery.storage.v1beta2.StorageError} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.bigquery.storage.v1beta2.StorageError) com.google.cloud.bigquery.storage.v1beta2.StorageErrorOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.bigquery.storage.v1beta2.StorageProto .internal_static_google_cloud_bigquery_storage_v1beta2_StorageError_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.bigquery.storage.v1beta2.StorageProto .internal_static_google_cloud_bigquery_storage_v1beta2_StorageError_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.bigquery.storage.v1beta2.StorageError.class, com.google.cloud.bigquery.storage.v1beta2.StorageError.Builder.class); } // Construct using com.google.cloud.bigquery.storage.v1beta2.StorageError.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {} } @java.lang.Override public Builder clear() { super.clear(); code_ = 0; entity_ = ""; errorMessage_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.bigquery.storage.v1beta2.StorageProto .internal_static_google_cloud_bigquery_storage_v1beta2_StorageError_descriptor; } @java.lang.Override public com.google.cloud.bigquery.storage.v1beta2.StorageError getDefaultInstanceForType() { return com.google.cloud.bigquery.storage.v1beta2.StorageError.getDefaultInstance(); } @java.lang.Override public com.google.cloud.bigquery.storage.v1beta2.StorageError build() { com.google.cloud.bigquery.storage.v1beta2.StorageError result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.bigquery.storage.v1beta2.StorageError buildPartial() { com.google.cloud.bigquery.storage.v1beta2.StorageError result = new com.google.cloud.bigquery.storage.v1beta2.StorageError(this); result.code_ = code_; result.entity_ = entity_; result.errorMessage_ = errorMessage_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.bigquery.storage.v1beta2.StorageError) { return mergeFrom((com.google.cloud.bigquery.storage.v1beta2.StorageError) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.bigquery.storage.v1beta2.StorageError other) { if (other == com.google.cloud.bigquery.storage.v1beta2.StorageError.getDefaultInstance()) return this; if (other.code_ != 0) { setCodeValue(other.getCodeValue()); } if (!other.getEntity().isEmpty()) { entity_ = other.entity_; onChanged(); } if (!other.getErrorMessage().isEmpty()) { errorMessage_ = other.errorMessage_; onChanged(); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.cloud.bigquery.storage.v1beta2.StorageError parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.google.cloud.bigquery.storage.v1beta2.StorageError) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int code_ = 0; /** * * * <pre> * BigQuery Storage specific error code. * </pre> * * <code>.google.cloud.bigquery.storage.v1beta2.StorageError.StorageErrorCode code = 1;</code> * * @return The enum numeric value on the wire for code. */ @java.lang.Override public int getCodeValue() { return code_; } /** * * * <pre> * BigQuery Storage specific error code. * </pre> * * <code>.google.cloud.bigquery.storage.v1beta2.StorageError.StorageErrorCode code = 1;</code> * * @param value The enum numeric value on the wire for code to set. * @return This builder for chaining. */ public Builder setCodeValue(int value) { code_ = value; onChanged(); return this; } /** * * * <pre> * BigQuery Storage specific error code. * </pre> * * <code>.google.cloud.bigquery.storage.v1beta2.StorageError.StorageErrorCode code = 1;</code> * * @return The code. */ @java.lang.Override public com.google.cloud.bigquery.storage.v1beta2.StorageError.StorageErrorCode getCode() { @SuppressWarnings("deprecation") com.google.cloud.bigquery.storage.v1beta2.StorageError.StorageErrorCode result = com.google.cloud.bigquery.storage.v1beta2.StorageError.StorageErrorCode.valueOf(code_); return result == null ? com.google.cloud.bigquery.storage.v1beta2.StorageError.StorageErrorCode.UNRECOGNIZED : result; } /** * * * <pre> * BigQuery Storage specific error code. * </pre> * * <code>.google.cloud.bigquery.storage.v1beta2.StorageError.StorageErrorCode code = 1;</code> * * @param value The code to set. * @return This builder for chaining. */ public Builder setCode( com.google.cloud.bigquery.storage.v1beta2.StorageError.StorageErrorCode value) { if (value == null) { throw new NullPointerException(); } code_ = value.getNumber(); onChanged(); return this; } /** * * * <pre> * BigQuery Storage specific error code. * </pre> * * <code>.google.cloud.bigquery.storage.v1beta2.StorageError.StorageErrorCode code = 1;</code> * * @return This builder for chaining. */ public Builder clearCode() { code_ = 0; onChanged(); return this; } private java.lang.Object entity_ = ""; /** * * * <pre> * Name of the failed entity. * </pre> * * <code>string entity = 2;</code> * * @return The entity. */ public java.lang.String getEntity() { java.lang.Object ref = entity_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); entity_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Name of the failed entity. * </pre> * * <code>string entity = 2;</code> * * @return The bytes for entity. */ public com.google.protobuf.ByteString getEntityBytes() { java.lang.Object ref = entity_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); entity_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Name of the failed entity. * </pre> * * <code>string entity = 2;</code> * * @param value The entity to set. * @return This builder for chaining. */ public Builder setEntity(java.lang.String value) { if (value == null) { throw new NullPointerException(); } entity_ = value; onChanged(); return this; } /** * * * <pre> * Name of the failed entity. * </pre> * * <code>string entity = 2;</code> * * @return This builder for chaining. */ public Builder clearEntity() { entity_ = getDefaultInstance().getEntity(); onChanged(); return this; } /** * * * <pre> * Name of the failed entity. * </pre> * * <code>string entity = 2;</code> * * @param value The bytes for entity to set. * @return This builder for chaining. */ public Builder setEntityBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); entity_ = value; onChanged(); return this; } private java.lang.Object errorMessage_ = ""; /** * * * <pre> * Message that describes the error. * </pre> * * <code>string error_message = 3;</code> * * @return The errorMessage. */ public java.lang.String getErrorMessage() { java.lang.Object ref = errorMessage_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); errorMessage_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Message that describes the error. * </pre> * * <code>string error_message = 3;</code> * * @return The bytes for errorMessage. */ public com.google.protobuf.ByteString getErrorMessageBytes() { java.lang.Object ref = errorMessage_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); errorMessage_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Message that describes the error. * </pre> * * <code>string error_message = 3;</code> * * @param value The errorMessage to set. * @return This builder for chaining. */ public Builder setErrorMessage(java.lang.String value) { if (value == null) { throw new NullPointerException(); } errorMessage_ = value; onChanged(); return this; } /** * * * <pre> * Message that describes the error. * </pre> * * <code>string error_message = 3;</code> * * @return This builder for chaining. */ public Builder clearErrorMessage() { errorMessage_ = getDefaultInstance().getErrorMessage(); onChanged(); return this; } /** * * * <pre> * Message that describes the error. * </pre> * * <code>string error_message = 3;</code> * * @param value The bytes for errorMessage to set. * @return This builder for chaining. */ public Builder setErrorMessageBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); errorMessage_ = value; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.bigquery.storage.v1beta2.StorageError) } // @@protoc_insertion_point(class_scope:google.cloud.bigquery.storage.v1beta2.StorageError) private static final com.google.cloud.bigquery.storage.v1beta2.StorageError DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.bigquery.storage.v1beta2.StorageError(); } public static com.google.cloud.bigquery.storage.v1beta2.StorageError getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<StorageError> PARSER = new com.google.protobuf.AbstractParser<StorageError>() { @java.lang.Override public StorageError parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new StorageError(input, extensionRegistry); } }; public static com.google.protobuf.Parser<StorageError> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<StorageError> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.bigquery.storage.v1beta2.StorageError getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/java-bigquerystorage
proto-google-cloud-bigquerystorage-v1beta2/src/main/java/com/google/cloud/bigquery/storage/v1beta2/StorageError.java
Java
apache-2.0
36,462
package io.quarkus.arc.test.observers.injection; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import io.quarkus.arc.Arc; import io.quarkus.arc.test.ArcTestContainer; import java.util.UUID; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import javax.enterprise.context.Dependent; import javax.enterprise.event.Observes; import javax.enterprise.inject.Instance; import javax.inject.Singleton; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; public class SimpleObserverInjectionTest { @RegisterExtension public ArcTestContainer container = new ArcTestContainer(Fool.class, StringObserver.class); @Test public void testObserverInjection() { AtomicReference<String> msg = new AtomicReference<String>(); Fool.DESTROYED.set(false); Arc.container().beanManager().fireEvent(msg); String id1 = msg.get(); assertNotNull(id1); assertTrue(Fool.DESTROYED.get()); Fool.DESTROYED.set(false); Arc.container().beanManager().fireEvent(msg); assertNotEquals(id1, msg.get()); assertTrue(Fool.DESTROYED.get()); } @Singleton static class StringObserver { @SuppressWarnings({ "rawtypes", "unchecked" }) void observeString(@Observes AtomicReference value, Fool fool, Instance<Fool> fools) { value.set(fool.id); fools.forEach(f -> { // Fool is @Dependent! assertNotEquals(fool.id, f.id); }); } } @Dependent static class Fool { static final AtomicBoolean DESTROYED = new AtomicBoolean(); private String id; @PostConstruct void init() { id = UUID.randomUUID().toString(); } @PreDestroy void destroy() { DESTROYED.set(true); } } }
quarkusio/quarkus
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/observers/injection/SimpleObserverInjectionTest.java
Java
apache-2.0
2,135
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.workspaces.model; import javax.annotation.Generated; /** * */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public enum DedicatedTenancySupportResultEnum { ENABLED("ENABLED"), DISABLED("DISABLED"); private String value; private DedicatedTenancySupportResultEnum(String value) { this.value = value; } @Override public String toString() { return this.value; } /** * Use this in place of valueOf. * * @param value * real value * @return DedicatedTenancySupportResultEnum corresponding to the value * * @throws IllegalArgumentException * If the specified value does not map to one of the known values in this enum. */ public static DedicatedTenancySupportResultEnum fromValue(String value) { if (value == null || "".equals(value)) { throw new IllegalArgumentException("Value cannot be null or empty!"); } for (DedicatedTenancySupportResultEnum enumEntry : DedicatedTenancySupportResultEnum.values()) { if (enumEntry.toString().equals(value)) { return enumEntry; } } throw new IllegalArgumentException("Cannot create enum from " + value + " value!"); } }
aws/aws-sdk-java
aws-java-sdk-workspaces/src/main/java/com/amazonaws/services/workspaces/model/DedicatedTenancySupportResultEnum.java
Java
apache-2.0
1,896
package com.logginghub.logging.modules; import com.logginghub.integrationtests.logging.HubTestFixture; import com.logginghub.integrationtests.logging.HubTestFixture.HubFixture; import com.logginghub.logging.LogEvent; import com.logginghub.logging.LogEventBuilder; import com.logginghub.logging.exceptions.ConnectorException; import com.logginghub.logging.exceptions.LoggingMessageSenderException; import com.logginghub.logging.hub.configuration.FilterConfiguration; import com.logginghub.logging.messages.LogEventMessage; import com.logginghub.logging.messaging.SocketClient; import com.logginghub.logging.servers.SocketHub; import com.logginghub.utils.Bucket; import com.logginghub.utils.ThreadUtils; import com.logginghub.utils.logging.Logger; import org.junit.Ignore; import org.junit.Test; import java.io.IOException; import java.util.EnumSet; import java.util.concurrent.Callable; import static org.hamcrest.MatcherAssert.*; import static org.hamcrest.Matchers.*; // TODO : fix the race conditions in the socket connector that mean we leak threads //@RunWith(CustomRunner.class) public class TestLoggingBridgeModule extends BaseHub { @Test public void test_default_configuration_import() throws IOException, ConnectorException, LoggingMessageSenderException { final HubFixture hubAFixture = fixture.createSocketHub(EnumSet.noneOf(HubTestFixture.Features.class)); HubFixture hubBFixture = fixture.createSocketHub(EnumSet.of(HubTestFixture.Features.Bridge)); hubBFixture.getLoggingBridgeConfiguration().setPort(hubAFixture.getSocketHubConfiguration().getPort()); final SocketHub hubA = hubAFixture.start(); final SocketHub hubB = hubBFixture.start(); ThreadUtils.repeatUntilTrue(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return hubA.getConnectionsList().size() == 1; } }); SocketClient clientA = fixture.createClient("clientA", hubA); SocketClient clientB = fixture.createClientAutoSubscribe("clientB", hubB); clientA.send(new LogEventMessage(LogEventBuilder.create(0, Logger.info, "Test message"))); Bucket<LogEvent> events = fixture.createEventBucketFor(clientB); events.waitForMessages(1); assertThat(events.get(0).getMessage(), is("Test message")); } @Test public void test_import() throws IOException, ConnectorException, LoggingMessageSenderException { final HubFixture hubAFixture = fixture.createSocketHub(EnumSet.noneOf(HubTestFixture.Features.class)); HubFixture hubBFixture = fixture.createSocketHub(EnumSet.of(HubTestFixture.Features.Bridge)); hubBFixture.getLoggingBridgeConfiguration().setImportEvents(true); hubBFixture.getLoggingBridgeConfiguration().setExportEvents(false); hubBFixture.getLoggingBridgeConfiguration().setPort(hubAFixture.getSocketHubConfiguration().getPort()); final SocketHub hubA = hubAFixture.start(); final SocketHub hubB = hubBFixture.start(); ThreadUtils.repeatUntilTrue(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return hubA.getConnectionsList().size() == 1; } }); SocketClient clientA = fixture.createClientAutoSubscribe("clientA", hubA); SocketClient clientB = fixture.createClientAutoSubscribe("clientB", hubB); clientA.send(new LogEventMessage(LogEventBuilder.create(0, Logger.info, "Test message from client A to hub A"))); clientB.send(new LogEventMessage(LogEventBuilder.create(0, Logger.info, "Test message from client B to hub B"))); Bucket<LogEvent> eventsA = fixture.createEventBucketFor(clientA); Bucket<LogEvent> eventsB = fixture.createEventBucketFor(clientB); eventsB.waitForMessages(1); assertThat(eventsB.get(0).getMessage(), is("Test message from client A to hub A")); assertThat(eventsA.size(), is(0)); } @Test public void test_export() throws IOException, ConnectorException, LoggingMessageSenderException { final HubFixture hubAFixture = fixture.createSocketHub(EnumSet.noneOf(HubTestFixture.Features.class)); HubFixture hubBFixture = fixture.createSocketHub(EnumSet.of(HubTestFixture.Features.Bridge)); hubBFixture.getLoggingBridgeConfiguration().setImportEvents(false); hubBFixture.getLoggingBridgeConfiguration().setExportEvents(true); hubBFixture.getLoggingBridgeConfiguration().setPort(hubAFixture.getSocketHubConfiguration().getPort()); final SocketHub hubA = hubAFixture.start(); final SocketHub hubB = hubBFixture.start(); ThreadUtils.repeatUntilTrue(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return hubA.getConnectionsList().size() == 1; } }); SocketClient clientA = fixture.createClientAutoSubscribe("clientA", hubA); SocketClient clientB = fixture.createClientAutoSubscribe("clientB", hubB); clientA.send(new LogEventMessage(LogEventBuilder.create(0, Logger.info, "Test message from client A to hub A"))); clientB.send(new LogEventMessage(LogEventBuilder.create(0, Logger.info, "Test message from client B to hub B"))); Bucket<LogEvent> eventsA = fixture.createEventBucketFor(clientA); Bucket<LogEvent> eventsB = fixture.createEventBucketFor(clientB); eventsA.waitForMessages(1); assertThat(eventsA.get(0).getMessage(), is("Test message from client B to hub B")); assertThat(eventsB.size(), is(0)); } @Ignore // jshaw - I'm pretty certain this test has race conditions @Test public void test_import_and_export_one_way() throws IOException, ConnectorException, LoggingMessageSenderException { final HubFixture hubAFixture = fixture.createSocketHub(EnumSet.noneOf(HubTestFixture.Features.class)); HubFixture hubBFixture = fixture.createSocketHub(EnumSet.of(HubTestFixture.Features.Bridge)); hubBFixture.getLoggingBridgeConfiguration().setImportEvents(true); hubBFixture.getLoggingBridgeConfiguration().setExportEvents(true); hubBFixture.getLoggingBridgeConfiguration().setPort(hubAFixture.getSocketHubConfiguration().getPort()); final SocketHub hubA = hubAFixture.start(); hubA.setName("HubA"); final SocketHub hubB = hubBFixture.start(); hubB.setName("HubB"); // Wait for hubB to connect to hubA ThreadUtils.repeatUntilTrue(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return hubA.getConnectionsList().size() == 1; } }); assertThat(hubA.getConnectionsList().size(), is(1)); assertThat(hubB.getConnectionsList().size(), is(0)); SocketClient clientA = fixture.createClientAutoSubscribe("clientA", hubA); SocketClient clientB = fixture.createClientAutoSubscribe("clientB", hubB); assertThat(hubA.getConnectionsList().size(), is(2)); assertThat(hubB.getConnectionsList().size(), is(1)); Bucket<LogEvent> eventsA = fixture.createEventBucketFor(clientA); Bucket<LogEvent> eventsB = fixture.createEventBucketFor(clientB); clientA.send(new LogEventMessage(LogEventBuilder.create(0, Logger.info, "Test message from client A to hub A"))); clientB.send(new LogEventMessage(LogEventBuilder.create(0, Logger.info, "Test message from client B to hub B"))); eventsA.waitForMessages(1); assertThat(eventsA.get(0).getMessage(), is("Test message from client B to hub B")); eventsB.waitForMessages(1); assertThat(eventsB.get(0).getMessage(), is("Test message from client A to hub A")); assertThat(eventsA.size(), is(1)); assertThat(eventsB.size(), is(1)); } @Test public void test_import_filter() throws IOException, ConnectorException, LoggingMessageSenderException { final HubFixture hubAFixture = fixture.createSocketHub(EnumSet.noneOf(HubTestFixture.Features.class)); HubFixture hubBFixture = fixture.createSocketHub(EnumSet.of(HubTestFixture.Features.Bridge)); hubBFixture.getLoggingBridgeConfiguration().setImportEvents(true); hubBFixture.getLoggingBridgeConfiguration().setExportEvents(false); hubBFixture.getLoggingBridgeConfiguration().getFilters().add(FilterConfiguration.contains("orange")); hubBFixture.getLoggingBridgeConfiguration().setPort(hubAFixture.getSocketHubConfiguration().getPort()); final SocketHub hubA = hubAFixture.start(); final SocketHub hubB = hubBFixture.start(); ThreadUtils.repeatUntilTrue(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return hubA.getConnectionsList().size() == 1; } }); SocketClient clientA = fixture.createClientAutoSubscribe("clientA", hubA); SocketClient clientB = fixture.createClientAutoSubscribe("clientB", hubB); clientA.send(new LogEventMessage(LogEventBuilder.create(0, Logger.info, "Test message orange from client B to hub B"))); clientA.send(new LogEventMessage(LogEventBuilder.create(0, Logger.info, "Test message apple from client A to hub A"))); Bucket<LogEvent> eventsA = fixture.createEventBucketFor(clientA); Bucket<LogEvent> eventsB = fixture.createEventBucketFor(clientB); eventsB.waitForMessages(1); assertThat(eventsB.get(0).getMessage(), is("Test message apple from client A to hub A")); assertThat(eventsA.size(), is(0)); } }
logginghub/core
logginghub-integrationtests/src/test/java/com/logginghub/logging/modules/TestLoggingBridgeModule.java
Java
apache-2.0
9,974
/* * 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.kafka.streams.state.internals; import org.apache.kafka.streams.KeyValue; import org.apache.kafka.streams.errors.InvalidStateStoreException; import org.apache.kafka.streams.kstream.Windowed; import org.apache.kafka.streams.kstream.internals.SessionWindow; import org.apache.kafka.streams.state.KeyValueIterator; import org.apache.kafka.streams.state.QueryableStoreTypes; import org.apache.kafka.test.ReadOnlySessionStoreStub; import org.apache.kafka.test.StateStoreProviderStub; import org.apache.kafka.test.StreamsTestUtils; import org.junit.Before; import org.junit.Test; import java.util.Arrays; import java.util.Collections; import java.util.List; import static org.apache.kafka.test.StreamsTestUtils.toList; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsEqual.equalTo; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.fail; public class CompositeReadOnlySessionStoreTest { private final String storeName = "session-store"; private final StateStoreProviderStub stubProviderOne = new StateStoreProviderStub(false); private final StateStoreProviderStub stubProviderTwo = new StateStoreProviderStub(false); private final ReadOnlySessionStoreStub<String, Long> underlyingSessionStore = new ReadOnlySessionStoreStub<>(); private final ReadOnlySessionStoreStub<String, Long> otherUnderlyingStore = new ReadOnlySessionStoreStub<>(); private CompositeReadOnlySessionStore<String, Long> sessionStore; @Before public void before() { stubProviderOne.addStore(storeName, underlyingSessionStore); stubProviderOne.addStore("other-session-store", otherUnderlyingStore); sessionStore = new CompositeReadOnlySessionStore<>( new WrappingStoreProvider(Arrays.<StateStoreProvider>asList(stubProviderOne, stubProviderTwo)), QueryableStoreTypes.<String, Long>sessionStore(), storeName); } @Test public void shouldFetchResulstFromUnderlyingSessionStore() throws Exception { underlyingSessionStore.put(new Windowed<>("a", new SessionWindow(0, 0)), 1L); underlyingSessionStore.put(new Windowed<>("a", new SessionWindow(10, 10)), 2L); final List<KeyValue<Windowed<String>, Long>> results = toList(sessionStore.fetch("a")); assertEquals(Arrays.asList(KeyValue.pair(new Windowed<>("a", new SessionWindow(0, 0)), 1L), KeyValue.pair(new Windowed<>("a", new SessionWindow(10, 10)), 2L)), results); } @Test public void shouldReturnEmptyIteratorIfNoData() throws Exception { final KeyValueIterator<Windowed<String>, Long> result = sessionStore.fetch("b"); assertFalse(result.hasNext()); } @Test public void shouldFindValueForKeyWhenMultiStores() throws Exception { final ReadOnlySessionStoreStub<String, Long> secondUnderlying = new ReadOnlySessionStoreStub<>(); stubProviderTwo.addStore(storeName, secondUnderlying); final Windowed<String> keyOne = new Windowed<>("key-one", new SessionWindow(0, 0)); final Windowed<String> keyTwo = new Windowed<>("key-two", new SessionWindow(0, 0)); underlyingSessionStore.put(keyOne, 0L); secondUnderlying.put(keyTwo, 10L); final List<KeyValue<Windowed<String>, Long>> keyOneResults = toList(sessionStore.fetch("key-one")); final List<KeyValue<Windowed<String>, Long>> keyTwoResults = toList(sessionStore.fetch("key-two")); assertEquals(Collections.singletonList(KeyValue.pair(keyOne, 0L)), keyOneResults); assertEquals(Collections.singletonList(KeyValue.pair(keyTwo, 10L)), keyTwoResults); } @Test public void shouldNotGetValueFromOtherStores() throws Exception { final Windowed<String> expectedKey = new Windowed<>("foo", new SessionWindow(0, 0)); otherUnderlyingStore.put(new Windowed<>("foo", new SessionWindow(10, 10)), 10L); underlyingSessionStore.put(expectedKey, 1L); final KeyValueIterator<Windowed<String>, Long> result = sessionStore.fetch("foo"); assertEquals(KeyValue.pair(expectedKey, 1L), result.next()); assertFalse(result.hasNext()); } @Test(expected = InvalidStateStoreException.class) public void shouldThrowInvalidStateStoreExceptionOnRebalance() throws Exception { final CompositeReadOnlySessionStore<String, String> store = new CompositeReadOnlySessionStore<>(new StateStoreProviderStub(true), QueryableStoreTypes.<String, String>sessionStore(), "whateva"); store.fetch("a"); } @Test public void shouldThrowInvalidStateStoreExceptionIfSessionFetchThrows() { underlyingSessionStore.setOpen(false); try { sessionStore.fetch("key"); fail("Should have thrown InvalidStateStoreException with session store"); } catch (InvalidStateStoreException e) { } } @Test(expected = NullPointerException.class) public void shouldThrowNullPointerExceptionIfFetchingNullKey() { sessionStore.fetch(null); } @Test public void shouldFetchKeyRangeAcrossStores() { final ReadOnlySessionStoreStub<String, Long> secondUnderlying = new ReadOnlySessionStoreStub<>(); stubProviderTwo.addStore(storeName, secondUnderlying); underlyingSessionStore.put(new Windowed<>("a", new SessionWindow(0, 0)), 0L); secondUnderlying.put(new Windowed<>("b", new SessionWindow(0, 0)), 10L); final List<KeyValue<Windowed<String>, Long>> results = StreamsTestUtils.toList(sessionStore.fetch("a", "b")); assertThat(results.size(), equalTo(2)); } @Test(expected = NullPointerException.class) public void shouldThrowNPEIfKeyIsNull() { underlyingSessionStore.fetch(null); } @Test(expected = NullPointerException.class) public void shouldThrowNPEIfFromKeyIsNull() { underlyingSessionStore.fetch(null, "a"); } @Test(expected = NullPointerException.class) public void shouldThrowNPEIfToKeyIsNull() { underlyingSessionStore.fetch("a", null); } }
zzwlstarby/mykafka
streams/src/test/java/org/apache/kafka/streams/state/internals/CompositeReadOnlySessionStoreTest.java
Java
apache-2.0
7,129
package no.javazone.ems; import net.hamnaberg.json.Item; import net.hamnaberg.json.Link; import net.hamnaberg.json.Property; import net.hamnaberg.json.Value; import org.apache.commons.codec.binary.Hex; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.URI; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; public class ItemMappers { private static final Logger LOG = LoggerFactory.getLogger(ItemMappers.class); public static String generateIdString(Item item) { Optional<URI> uriOptional = item.getHref(); if (!uriOptional.isPresent()) { throw new IllegalStateException("manglet href"); } URI href = uriOptional.get(); return new String(Hex.encodeHex(getMda().digest(href.toString().getBytes()))); } private static MessageDigest getMda() { try { return MessageDigest.getInstance("SHA-256"); } catch (NoSuchAlgorithmException e) { LOG.error("Kunne ikke lage SHA-256", e); throw new IllegalStateException(); } } public static List<String> mapPropertyToList(Item item, String propertyName) { return item .propertyByName(propertyName) .map(Property::getArray) .map(list -> list.stream() .filter(Value::isString) .map(Value::asString) .collect(Collectors.toList())) .orElse(new ArrayList<>()); } public static Optional<URI> mapLink(Item item, String rel) { return item.linkByRel(rel) .map(link -> Optional.of(link.getHref())) .orElse(Optional.empty()); } public static String mapLinkPrompt(Item item, String rel) { return item.linkByRel(rel) .flatMap(Link::getPrompt) .orElse(null); } public static String mapPropertyToString(Item item, String propertyName) { return item.propertyByName(propertyName) .flatMap(Property::getValue) .map(Value::asString) .orElse(null); } public static Optional<URI> mapItemLink(Item item, String relName) { return item.linkByRel(relName) .map(Link::getHref); } }
javaBin/javazone-web-api
src/main/java/no/javazone/ems/ItemMappers.java
Java
apache-2.0
2,446
/* * Copyright 2003-2018 Bas Leijdekkers * * 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.siyeh.ig.fixes; import com.intellij.openapi.project.Project; import com.intellij.psi.*; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.searches.SuperMethodsSearch; import com.intellij.psi.tree.IElementType; import com.intellij.psi.util.ClassUtil; import com.intellij.psi.util.PsiFormatUtil; import com.intellij.psi.util.PsiUtil; import com.siyeh.ig.psiutils.ClassUtils; import com.siyeh.ig.psiutils.TypeUtils; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.IOException; import java.lang.reflect.Modifier; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.*; public class SerialVersionUIDBuilder extends JavaRecursiveElementVisitor { @NonNls private static final String ACCESS_METHOD_NAME_PREFIX = "access$"; private final PsiClass clazz; private int index = -1; private final Set<MemberSignature> nonPrivateConstructors; private final Set<MemberSignature> nonPrivateMethods; private final Set<MemberSignature> nonPrivateFields; private final List<MemberSignature> staticInitializers; private boolean assertStatement = false; private final Map<PsiElement, String> memberMap = new HashMap<>(); private static final Comparator<PsiClass> INTERFACE_COMPARATOR = (object1, object2) -> { if (object1 == null && object2 == null) { return 0; } if (object1 == null) { return 1; } if (object2 == null) { return -1; } final String name1 = object1.getQualifiedName(); final String name2 = object2.getQualifiedName(); if (name1 == null && name2 == null) { return 0; } if (name1 == null) { return 1; } if (name2 == null) { return -1; } return name1.compareTo(name2); }; private SerialVersionUIDBuilder(@NotNull PsiClass clazz) { this.clazz = clazz; nonPrivateMethods = new HashSet<>(); final PsiMethod[] methods = clazz.getMethods(); for (final PsiMethod method : methods) { if (!method.isConstructor() && !method.hasModifierProperty(PsiModifier.PRIVATE)) { final MemberSignature methodSignature = new MemberSignature(method); nonPrivateMethods.add(methodSignature); SuperMethodsSearch.search(method, null, true, false).forEach(method1 -> { final MemberSignature superSignature = new MemberSignature(methodSignature.getName(), methodSignature.getModifiers(), ClassUtil.getAsmMethodSignature(method1.getMethod()).replace('/', '.')); nonPrivateMethods.add(superSignature); return true; }); } } nonPrivateFields = new HashSet<>(); final PsiField[] fields = clazz.getFields(); for (final PsiField field : fields) { if (!field.hasModifierProperty(PsiModifier.PRIVATE) || !(field.hasModifierProperty(PsiModifier.STATIC) || field.hasModifierProperty(PsiModifier.TRANSIENT))) { final MemberSignature fieldSignature = new MemberSignature(field); nonPrivateFields.add(fieldSignature); } } staticInitializers = new ArrayList<>(1); final PsiClassInitializer[] initializers = clazz.getInitializers(); if (initializers.length > 0) { for (final PsiClassInitializer initializer : initializers) { final PsiModifierList modifierList = initializer.getModifierList(); if (modifierList != null && modifierList.hasModifierProperty(PsiModifier.STATIC)) { final MemberSignature initializerSignature = MemberSignature.getStaticInitializerMemberSignature(); staticInitializers.add(initializerSignature); break; } } } if (staticInitializers.isEmpty()) { final PsiField[] psiFields = clazz.getFields(); for (final PsiField field : psiFields) { if (hasStaticInitializer(field)) { final MemberSignature initializerSignature = MemberSignature.getStaticInitializerMemberSignature(); staticInitializers.add(initializerSignature); break; } } } final PsiMethod[] constructors = clazz.getConstructors(); nonPrivateConstructors = new HashSet<>(constructors.length); if (constructors.length == 0 && !clazz.isInterface()) { // generated empty constructor if no constructor is defined in the source final MemberSignature constructorSignature; if (clazz.hasModifierProperty(PsiModifier.PUBLIC)) { constructorSignature = MemberSignature.getPublicConstructor(); } else { constructorSignature = MemberSignature.getPackagePrivateConstructor(); } nonPrivateConstructors.add(constructorSignature); } for (final PsiMethod constructor : constructors) { if (!constructor.hasModifierProperty(PsiModifier.PRIVATE)) { final MemberSignature constructorSignature = new MemberSignature(constructor); nonPrivateConstructors.add(constructorSignature); } } } /** * @see java.io.ObjectStreamClass#computeDefaultSUID(Class) */ public static long computeDefaultSUID(@NotNull PsiClass psiClass) { final Project project = psiClass.getProject(); final GlobalSearchScope scope = GlobalSearchScope.allScope(project); final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project); final PsiClass serializable = psiFacade.findClass(CommonClassNames.JAVA_IO_SERIALIZABLE, scope); if (serializable == null) { // no jdk defined for project. return -1L; } final boolean isSerializable = psiClass.isInheritor(serializable, true); if (!isSerializable) { return 0L; } final SerialVersionUIDBuilder serialVersionUIDBuilder = new SerialVersionUIDBuilder(psiClass); try { final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); final DataOutputStream dataOutputStream = new DataOutputStream(byteArrayOutputStream); final String className = PsiFormatUtil.getExternalName(psiClass); if (className != null) { dataOutputStream.writeUTF(className); } final PsiModifierList classModifierList = psiClass.getModifierList(); int classModifiers = classModifierList != null ? MemberSignature.calculateModifierBitmap(classModifierList) : 0; final MemberSignature[] methodSignatures = serialVersionUIDBuilder.getNonPrivateMethodSignatures(); if (psiClass.isInterface()) { classModifiers |= Modifier.INTERFACE; if (methodSignatures.length == 0) { // interfaces were not marked abstract when they did't have methods in java 1.0 // For serialization compatibility the abstract modifier is ignored. classModifiers &= ~Modifier.ABSTRACT; } } dataOutputStream.writeInt(classModifiers); final PsiClass[] interfaces = psiClass.getInterfaces(); Arrays.sort(interfaces, INTERFACE_COMPARATOR); for (PsiClass aInterfaces : interfaces) { final String name = aInterfaces.getQualifiedName(); if (name != null) { dataOutputStream.writeUTF(name); } } final MemberSignature[] fields = serialVersionUIDBuilder.getNonPrivateFields(); writeSignatures(fields, dataOutputStream); final MemberSignature[] staticInitializers = serialVersionUIDBuilder.getStaticInitializers(); writeSignatures(staticInitializers, dataOutputStream); final MemberSignature[] constructors = serialVersionUIDBuilder.getNonPrivateConstructors(); writeSignatures(constructors, dataOutputStream); writeSignatures(methodSignatures, dataOutputStream); dataOutputStream.flush(); @NonNls final String algorithm = "SHA"; final MessageDigest digest = MessageDigest.getInstance(algorithm); final byte[] digestBytes = digest.digest(byteArrayOutputStream.toByteArray()); long serialVersionUID = 0L; for (int i = Math.min(digestBytes.length, 8) - 1; i >= 0; i--) { serialVersionUID = serialVersionUID << 8 | digestBytes[i] & 0xFF; } return serialVersionUID; } catch (IOException exception) { throw new InternalError(exception.getMessage(), exception); } catch (NoSuchAlgorithmException exception) { throw new SecurityException(exception.getMessage(), exception); } } private static void writeSignatures(MemberSignature[] signatures, DataOutputStream dataOutputStream) throws IOException { Arrays.sort(signatures); for (final MemberSignature field : signatures) { dataOutputStream.writeUTF(field.getName()); dataOutputStream.writeInt(field.getModifiers()); dataOutputStream.writeUTF(field.getSignature()); } } private String getAccessMethodIndex(PsiElement element) { String cache = memberMap.get(element); if (cache == null) { cache = String.valueOf(index); index++; memberMap.put(element, cache); } return cache; } public MemberSignature @NotNull [] getNonPrivateConstructors() { init(); return nonPrivateConstructors.toArray(new MemberSignature[0]); } public MemberSignature @NotNull [] getNonPrivateFields() { init(); return nonPrivateFields.toArray(new MemberSignature[0]); } public MemberSignature @NotNull [] getNonPrivateMethodSignatures() { init(); return nonPrivateMethods.toArray(new MemberSignature[0]); } public MemberSignature @NotNull [] getStaticInitializers() { init(); return staticInitializers.toArray(new MemberSignature[0]); } private static boolean hasStaticInitializer(PsiField field) { if (field.hasModifierProperty(PsiModifier.STATIC)) { final PsiExpression initializer = field.getInitializer(); if (initializer == null) { return false; } final PsiType fieldType = field.getType(); final PsiType stringType = TypeUtils.getStringType(field); if (field.hasModifierProperty(PsiModifier.FINAL) && (fieldType instanceof PsiPrimitiveType || fieldType.equals(stringType))) { return !PsiUtil.isConstantExpression(initializer); } else { return true; } } return false; } private void init() { if (index < 0) { index = 0; clazz.acceptChildren(this); } } @Override public void visitAssertStatement(PsiAssertStatement statement) { super.visitAssertStatement(statement); if (assertStatement) { return; } final MemberSignature memberSignature = MemberSignature.getAssertionsDisabledFieldMemberSignature(); nonPrivateFields.add(memberSignature); if (staticInitializers.isEmpty()) { final MemberSignature initializerSignature = MemberSignature.getStaticInitializerMemberSignature(); staticInitializers.add(initializerSignature); } assertStatement = true; } @Override public void visitMethodCallExpression( @NotNull PsiMethodCallExpression methodCallExpression) { // for navigating the psi tree in the order javac navigates its AST final PsiExpressionList argumentList = methodCallExpression.getArgumentList(); final PsiExpression[] expressions = argumentList.getExpressions(); for (final PsiExpression expression : expressions) { expression.accept(this); } final PsiReferenceExpression methodExpression = methodCallExpression.getMethodExpression(); methodExpression.accept(this); } @Override public void visitReferenceElement(PsiJavaCodeReferenceElement reference) { super.visitReferenceElement(reference); final PsiElement parentClass = ClassUtils.getContainingClass(reference); if (reference.getParent() instanceof PsiTypeElement) { return; } final PsiElement element = reference.resolve(); if (!(element instanceof PsiClass)) { return; } final PsiClass elementParentClass = ClassUtils.getContainingClass(element); if (elementParentClass == null || !elementParentClass.equals(clazz) || element.equals(parentClass)) { return; } final PsiClass innerClass = (PsiClass)element; if (!innerClass.hasModifierProperty(PsiModifier.PRIVATE)) { return; } final PsiMethod[] constructors = innerClass.getConstructors(); if (constructors.length == 0) { getAccessMethodIndex(innerClass); } } @Override public void visitReferenceExpression(@NotNull PsiReferenceExpression expression) { super.visitReferenceExpression(expression); final PsiElement element = expression.resolve(); final PsiElement elementParentClass = ClassUtils.getContainingClass(element); final PsiElement expressionParentClass = ClassUtils.getContainingClass(expression); if (expressionParentClass == null || expressionParentClass .equals(elementParentClass)) { return; } PsiElement parentOfParentClass = ClassUtils.getContainingClass(expressionParentClass); while (parentOfParentClass != null && !parentOfParentClass.equals(clazz)) { if (!(expressionParentClass instanceof PsiAnonymousClass)) { getAccessMethodIndex(expressionParentClass); } getAccessMethodIndex(parentOfParentClass); parentOfParentClass = ClassUtils.getContainingClass(parentOfParentClass); } if (element instanceof PsiField) { final PsiField field = (PsiField)element; if (field.hasModifierProperty(PsiModifier.PRIVATE)) { boolean isStatic = false; final PsiType type = field.getType(); if (field.hasModifierProperty(PsiModifier.STATIC)) { if (field.hasModifierProperty(PsiModifier.FINAL) && type instanceof PsiPrimitiveType) { final PsiExpression initializer = field.getInitializer(); if (PsiUtil.isConstantExpression(initializer)) { return; } } isStatic = true; } final String returnTypeSignature = ClassUtil.getClassObjectPresentation(type); final String className = clazz.getQualifiedName(); @NonNls final StringBuilder signatureBuffer = new StringBuilder("("); if (!isStatic) { signatureBuffer.append('L').append(className).append(';'); } final String accessMethodIndex = getAccessMethodIndex(field); if (!clazz.equals(field.getContainingClass())) { return; } @NonNls String name = null; final PsiElement parent = expression.getParent(); if (parent instanceof PsiAssignmentExpression) { final PsiAssignmentExpression assignment = (PsiAssignmentExpression)parent; if (assignment.getLExpression().equals(expression)) { name = ACCESS_METHOD_NAME_PREFIX + accessMethodIndex + "02"; signatureBuffer.append(returnTypeSignature); } } else if (parent instanceof PsiPostfixExpression) { final PsiPostfixExpression postfixExpression = (PsiPostfixExpression)parent; final IElementType tokenType = postfixExpression.getOperationTokenType(); if (tokenType.equals(JavaTokenType.PLUSPLUS)) { name = ACCESS_METHOD_NAME_PREFIX + accessMethodIndex + "08"; } else if (tokenType.equals(JavaTokenType.MINUSMINUS)) { name = ACCESS_METHOD_NAME_PREFIX + accessMethodIndex + "10"; } } else if (parent instanceof PsiPrefixExpression) { final PsiPrefixExpression prefixExpression = (PsiPrefixExpression)parent; final IElementType tokenType = prefixExpression.getOperationTokenType(); if (tokenType.equals(JavaTokenType.PLUSPLUS)) { name = ACCESS_METHOD_NAME_PREFIX + accessMethodIndex + "04"; } else if (tokenType.equals(JavaTokenType.MINUSMINUS)) { name = ACCESS_METHOD_NAME_PREFIX + accessMethodIndex + "06"; } } if (name == null) { name = ACCESS_METHOD_NAME_PREFIX + accessMethodIndex + "00"; } signatureBuffer.append(')').append(returnTypeSignature); final String signature = signatureBuffer.toString(); final MemberSignature methodSignature = new MemberSignature(name, Modifier.STATIC, signature); nonPrivateMethods.add(methodSignature); } } else if (element instanceof PsiMethod) { final PsiMethod method = (PsiMethod)element; if (method.hasModifierProperty(PsiModifier.PRIVATE) && clazz.equals(method.getContainingClass())) { final String signature; if (method.hasModifierProperty(PsiModifier.STATIC)) { signature = ClassUtil.getAsmMethodSignature(method).replace('/', '.'); } else { final String returnTypeSignature = ClassUtil.getClassObjectPresentation(method.getReturnType()); @NonNls final StringBuilder signatureBuffer = new StringBuilder(); signatureBuffer.append("(L"); signatureBuffer.append(clazz.getQualifiedName()).append(';'); final PsiParameter[] parameters = method.getParameterList().getParameters(); for (final PsiParameter parameter : parameters) { final PsiType type = parameter.getType(); final String typeSignature = ClassUtil.getClassObjectPresentation(type); signatureBuffer.append(typeSignature); } signatureBuffer.append(')'); signatureBuffer.append(returnTypeSignature); signature = signatureBuffer.toString(); } final String accessMethodIndex = getAccessMethodIndex(method); final MemberSignature methodSignature = new MemberSignature(ACCESS_METHOD_NAME_PREFIX + accessMethodIndex + "00", Modifier.STATIC, signature); nonPrivateMethods.add(methodSignature); } } } }
leafclick/intellij-community
plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/fixes/SerialVersionUIDBuilder.java
Java
apache-2.0
18,856
package com.example.post_inverse_add; import arez.annotations.ArezComponent; import com.example.post_inverse_add.other.BaseProtectedAccessPostInverseAddModel; @ArezComponent public abstract class ProtectedAccessFromBasePostInverseAddModel extends BaseProtectedAccessPostInverseAddModel { }
realityforge/arez
processor/src/test/fixtures/input/com/example/post_inverse_add/ProtectedAccessFromBasePostInverseAddModel.java
Java
apache-2.0
294
package com.github.dubulee.fixedscrolllayout; import android.content.Context; import android.hardware.SensorManager; import android.view.ViewConfiguration; import android.view.animation.AnimationUtils; import android.view.animation.Interpolator; /** * FixedScrollScroller.java * Created by mugku on 2015/12/28. * Copyright (c) mugku. All rights reserved. */ public class FixedScrollScroller { private final Interpolator mInterpolator; private int mMode; private int mStartX; private int mStartY; private int mFinalX; private int mFinalY; private int mMinX; private int mMaxX; private int mMinY; private int mMaxY; private int mCurrX; private int mCurrY; private long mStartTime; private int mDuration; private float mDurationReciprocal; private float mDeltaX; private float mDeltaY; private boolean mFinished; private boolean mFlywheel; private float mVelocity; private float mCurrVelocity; private int mDistance; private float mFlingFriction = ViewConfiguration.getScrollFriction(); private static final int SCROLL_MODE = 0; private static final int FLING_MODE = 1; private static float DECELERATION_RATE = (float) (Math.log(0.78) / Math.log(0.9)); private static final float INFLEXION = 0.35f; // Tension lines cross at (INFLEXION, 1) private static final float START_TENSION = 0.5f; private static final float END_TENSION = 1.0f; private static final float P1 = START_TENSION * INFLEXION; private static final float P2 = 1.0f - END_TENSION * (1.0f - INFLEXION); private static final int NB_SAMPLES = 100; private static final float[] SPLINE_POSITION = new float[NB_SAMPLES + 1]; private float mDeceleration; private final float mPpi; // A context-specific coefficient adjusted to physical values. private float mPhysicalCoeff; static { float x_min = 0.0f; float y_min = 0.0f; for (int i = 0; i < NB_SAMPLES; i++) { final float alpha = (float) i / NB_SAMPLES; float x_max = 1.0f; float x, tx, coef; while (true) { x = x_min + (x_max - x_min) / 2.0f; coef = 3.0f * x * (1.0f - x); tx = coef * ((1.0f - x) * P1 + x * P2) + x * x * x; if (Math.abs(tx - alpha) < 1E-5) break; if (tx > alpha) x_max = x; else x_min = x; } SPLINE_POSITION[i] = coef * ((1.0f - x) * START_TENSION + x) + x * x * x; float y_max = 1.0f; float y, dy; while (true) { y = y_min + (y_max - y_min) / 2.0f; coef = 3.0f * y * (1.0f - y); dy = coef * ((1.0f - y) * START_TENSION + y) + y * y * y; if (Math.abs(dy - alpha) < 1E-5) break; if (dy > alpha) y_max = y; else y_min = y; } } SPLINE_POSITION[NB_SAMPLES] = 1.0f; } public FixedScrollScroller(Context context, Interpolator interpolator, boolean flywheel) { mFinished = true; if (interpolator == null) { mInterpolator = new ViscousFluidInterpolator(); } else { mInterpolator = interpolator; } mPpi = context.getResources().getDisplayMetrics().density * 160.0f; mDeceleration = computeDeceleration(ViewConfiguration.getScrollFriction()); mFlywheel = flywheel; mPhysicalCoeff = computeDeceleration(0.84f); // look and feel tuning } public final void setFriction(float friction) { mDeceleration = computeDeceleration(friction); mFlingFriction = friction; } private float computeDeceleration(float friction) { return SensorManager.GRAVITY_EARTH // g (m/s^2) * 39.37f // inch/meter * mPpi // pixels per inch * friction; } public final int getDuration() { return mDuration; } public final int getCurrY() { return mCurrY; } public float getCurrVelocity() { return mMode == FLING_MODE ? mCurrVelocity : mVelocity - mDeceleration * timePassed() / 2000.0f; } public final int getFinalY() { return mFinalY; } public boolean computeScrollOffset() { if (mFinished) { return false; } int timePassed = (int)(AnimationUtils.currentAnimationTimeMillis() - mStartTime); if (timePassed < mDuration) { switch (mMode) { case SCROLL_MODE: final float x = mInterpolator.getInterpolation(timePassed * mDurationReciprocal); mCurrX = mStartX + Math.round(x * mDeltaX); mCurrY = mStartY + Math.round(x * mDeltaY); break; case FLING_MODE: final float t = (float) timePassed / mDuration; final int index = (int) (NB_SAMPLES * t); float distanceCoef = 1.f; float velocityCoef = 0.f; if (index < NB_SAMPLES) { final float t_inf = (float) index / NB_SAMPLES; final float t_sup = (float) (index + 1) / NB_SAMPLES; final float d_inf = SPLINE_POSITION[index]; final float d_sup = SPLINE_POSITION[index + 1]; velocityCoef = (d_sup - d_inf) / (t_sup - t_inf); distanceCoef = d_inf + (t - t_inf) * velocityCoef; } mCurrVelocity = velocityCoef * mDistance / mDuration * 1000.0f; mCurrX = mStartX + Math.round(distanceCoef * (mFinalX - mStartX)); // Pin to mMinX <= mCurrX <= mMaxX mCurrX = Math.min(mCurrX, mMaxX); mCurrX = Math.max(mCurrX, mMinX); mCurrY = mStartY + Math.round(distanceCoef * (mFinalY - mStartY)); // Pin to mMinY <= mCurrY <= mMaxY mCurrY = Math.min(mCurrY, mMaxY); mCurrY = Math.max(mCurrY, mMinY); if (mCurrX == mFinalX && mCurrY == mFinalY) { mFinished = true; } break; } } else { mCurrX = mFinalX; mCurrY = mFinalY; mFinished = true; } return true; } public void fling(int startX, int startY, int velocityX, int velocityY, int minX, int maxX, int minY, int maxY) { // Continue a scroll or fling in progress if (mFlywheel && !mFinished) { float oldVel = getCurrVelocity(); float dx = (float) (mFinalX - mStartX); float dy = (float) (mFinalY - mStartY); float hyp = (float) Math.hypot(dx, dy); float ndx = dx / hyp; float ndy = dy / hyp; float oldVelocityX = ndx * oldVel; float oldVelocityY = ndy * oldVel; if (Math.signum(velocityX) == Math.signum(oldVelocityX) && Math.signum(velocityY) == Math.signum(oldVelocityY)) { velocityX += oldVelocityX; velocityY += oldVelocityY; } } mMode = FLING_MODE; mFinished = false; float velocity = (float) Math.hypot(velocityX, velocityY); mVelocity = velocity; mDuration = getSplineFlingDuration(velocity); mStartTime = AnimationUtils.currentAnimationTimeMillis(); mStartX = startX; mStartY = startY; float coeffX = velocity == 0 ? 1.0f : velocityX / velocity; float coeffY = velocity == 0 ? 1.0f : velocityY / velocity; double totalDistance = getSplineFlingDistance(velocity); mDistance = (int) (totalDistance * Math.signum(velocity)); mMinX = minX; mMaxX = maxX; mMinY = minY; mMaxY = maxY; mFinalX = startX + (int) Math.round(totalDistance * coeffX); // Pin to mMinX <= mFinalX <= mMaxX mFinalX = Math.min(mFinalX, mMaxX); mFinalX = Math.max(mFinalX, mMinX); mFinalY = startY + (int) Math.round(totalDistance * coeffY); // Pin to mMinY <= mFinalY <= mMaxY mFinalY = Math.min(mFinalY, mMaxY); mFinalY = Math.max(mFinalY, mMinY); } private double getSplineDeceleration(float velocity) { return Math.log(INFLEXION * Math.abs(velocity) / (mFlingFriction * mPhysicalCoeff)); } private int getSplineFlingDuration(float velocity) { final double l = getSplineDeceleration(velocity); final double decelMinusOne = DECELERATION_RATE - 1.0; return (int) (1000.0 * Math.exp(l / decelMinusOne)); } private double getSplineFlingDistance(float velocity) { final double l = getSplineDeceleration(velocity); final double decelMinusOne = DECELERATION_RATE - 1.0; return mFlingFriction * mPhysicalCoeff * Math.exp(DECELERATION_RATE / decelMinusOne * l); } public void abortAnimation() { mCurrX = mFinalX; mCurrY = mFinalY; mFinished = true; } public int timePassed() { return (int)(AnimationUtils.currentAnimationTimeMillis() - mStartTime); } public void setFinalY(int newY) { mFinalY = newY; mDeltaY = mFinalY - mStartY; mFinished = false; } static class ViscousFluidInterpolator implements Interpolator { /** Controls the viscous fluid effect (how much of it). */ private static final float VISCOUS_FLUID_SCALE = 8.0f; private static final float VISCOUS_FLUID_NORMALIZE; private static final float VISCOUS_FLUID_OFFSET; static { // must be set to 1.0 (used in viscousFluid()) VISCOUS_FLUID_NORMALIZE = 1.0f / viscousFluid(1.0f); // account for very small floating-point error VISCOUS_FLUID_OFFSET = 1.0f - VISCOUS_FLUID_NORMALIZE * viscousFluid(1.0f); } private static float viscousFluid(float x) { x *= VISCOUS_FLUID_SCALE; if (x < 1.0f) { x -= (1.0f - (float)Math.exp(-x)); } else { float start = 0.36787944117f; // 1/e == exp(-1) x = 1.0f - (float)Math.exp(1.0f - x); x = start + x * (1.0f - start); } return x; } @Override public float getInterpolation(float input) { final float interpolated = VISCOUS_FLUID_NORMALIZE * viscousFluid(input); if (interpolated > 0) { return interpolated + VISCOUS_FLUID_OFFSET; } return interpolated; } } }
mugku/FixedScrollLayout
fixedscrolllayout/src/main/java/com/github/dubulee/fixedscrolllayout/FixedScrollScroller.java
Java
apache-2.0
10,932
package com.deliver8r.maven.servicewrapper; public enum DevNode { DEV, NODE }
deliver8r/servicewrapper-maven-plugin
src/main/java/com/deliver8r/maven/servicewrapper/DevNode.java
Java
apache-2.0
80
package ru.extas.web.contacts.salepoint; import com.vaadin.data.util.filter.Compare; import com.vaadin.shared.ui.combobox.FilteringMode; import ru.extas.model.contacts.Company; import ru.extas.model.contacts.SalePoint; import ru.extas.model.contacts.SalePoint_; import ru.extas.web.commons.container.ExtaDbContainer; /** * Выбор контакта - юр. лица * с возможностью добавления нового * <p> * Date: 12.09.13 * Time: 12:15 * * @author Valery Orlov * @version $Id: $Id * @since 0.3 */ public class SalePointSimpleSelect extends com.vaadin.ui.ComboBox { private static final long serialVersionUID = -8005905898383483037L; protected final ExtaDbContainer<SalePoint> container; /** * <p>Constructor for CompanySelect.</p> * * @param caption a {@link java.lang.String} object. */ public SalePointSimpleSelect(final String caption) { this(caption, "Выберите существующий контакт или введите новый"); } /** * <p>Constructor for CompanySelect.</p> * * @param caption a {@link java.lang.String} object. * @param description a {@link java.lang.String} object. */ public SalePointSimpleSelect(final String caption, final String description) { super(caption); // Преконфигурация setDescription(description); setInputPrompt("контакт..."); setWidth(25, Unit.EM); setImmediate(true); setScrollToSelectedItem(true); // Инициализация контейнера container = new ExtaDbContainer<>(SalePoint.class); container.sort(new Object[]{SalePoint_.name.getName()}, new boolean[]{true}); // Устанавливаем контент выбора setFilteringMode(FilteringMode.CONTAINS); setContainerDataSource(container); setItemCaptionMode(ItemCaptionMode.PROPERTY); setItemCaptionPropertyId("name"); container.setSingleSelectConverter(this); // Функционал добавления нового контакта setNullSelectionAllowed(false); setNewItemsAllowed(false); } /** * <p>setContainerFilter.</p> * * @param company a {@link ru.extas.model.contacts.Company} object. * @param region a {@link java.lang.String} object. */ public void setContainerFilter(final Company company, final String region) { container.removeAllContainerFilters(); if (company != null) container.addContainerFilter(new Compare.Equal("company", company)); if (region != null) container.addContainerFilter(new Compare.Equal("posAddress.regionWithType", region)); refreshContainer(); } /** * <p>refreshContainer.</p> */ public void refreshContainer() { container.refresh(); } }
ExtaSoft/extacrm
src/main/java/ru/extas/web/contacts/salepoint/SalePointSimpleSelect.java
Java
apache-2.0
2,951
/* * Copyright (C) 2014 Siegenthaler Solutions. * * 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 me.siegenthaler.spotify.webapi.android.request; import me.siegenthaler.spotify.webapi.android.model.Track; /** * (non-doc) */ public final class SearchTrackRequest extends SearchRequest<SearchTrackRequest, Track> { private final static AbstractRequest.PageType PARAMETER_TYPE = new AbstractRequest.PageType(Track.class); /** * (non-doc) */ public SearchTrackRequest() { super(PARAMETER_TYPE, "track"); } }
SiegenthalerSolutions/spotify-web-api-android
library/src/main/java/me/siegenthaler/spotify/webapi/android/request/SearchTrackRequest.java
Java
apache-2.0
1,065
/* * 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 javax.el; import java.beans.FeatureDescriptor; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Objects; public class ListELResolver extends ELResolver { private final boolean readOnly; private static final Class<?> UNMODIFIABLE = Collections.unmodifiableList(new ArrayList<>()).getClass(); public ListELResolver() { this.readOnly = false; } public ListELResolver(boolean readOnly) { this.readOnly = readOnly; } @Override public Class<?> getType(ELContext context, Object base, Object property) { Objects.requireNonNull(context); if (base instanceof List<?>) { context.setPropertyResolved(base, property); List<?> list = (List<?>) base; int idx = coerce(property); if (idx < 0 || idx >= list.size()) { throw new PropertyNotFoundException( new ArrayIndexOutOfBoundsException(idx).getMessage()); } return Object.class; } return null; } @Override public Object getValue(ELContext context, Object base, Object property) { Objects.requireNonNull(context); if (base instanceof List<?>) { context.setPropertyResolved(base, property); List<?> list = (List<?>) base; int idx = coerce(property); if (idx < 0 || idx >= list.size()) { return null; } return list.get(idx); } return null; } @Override public void setValue(ELContext context, Object base, Object property, Object value) { Objects.requireNonNull(context); if (base instanceof List<?>) { context.setPropertyResolved(base, property); @SuppressWarnings("unchecked") // Must be OK to cast to Object List<Object> list = (List<Object>) base; if (this.readOnly) { throw new PropertyNotWritableException(Util.message(context, "resolverNotWriteable", base.getClass().getName())); } int idx = coerce(property); try { list.set(idx, value); } catch (UnsupportedOperationException e) { throw new PropertyNotWritableException(e); } catch (IndexOutOfBoundsException e) { throw new PropertyNotFoundException(e); } } } @Override public boolean isReadOnly(ELContext context, Object base, Object property) { Objects.requireNonNull(context); if (base instanceof List<?>) { context.setPropertyResolved(base, property); List<?> list = (List<?>) base; try { int idx = coerce(property); if (idx < 0 || idx >= list.size()) { throw new PropertyNotFoundException( new ArrayIndexOutOfBoundsException(idx) .getMessage()); } } catch (IllegalArgumentException e) { // ignore } return this.readOnly || UNMODIFIABLE.equals(list.getClass()); } return this.readOnly; } @Override public Iterator<FeatureDescriptor> getFeatureDescriptors(ELContext context, Object base) { return null; } @Override public Class<?> getCommonPropertyType(ELContext context, Object base) { if (base instanceof List<?>) { // implies base != null return Integer.class; } return null; } private static final int coerce(Object property) { if (property instanceof Number) { return ((Number) property).intValue(); } if (property instanceof Character) { return ((Character) property).charValue(); } if (property instanceof Boolean) { return (((Boolean) property).booleanValue() ? 1 : 0); } if (property instanceof String) { return Integer.parseInt((String) property); } throw new IllegalArgumentException(property != null ? property.toString() : "null"); } }
IAMTJW/Tomcat-8.5.20
tomcat-8.5.20/java/javax/el/ListELResolver.java
Java
apache-2.0
5,277
package com.vladmihalcea.book.hpjp.hibernate.cache.readwrite; import com.vladmihalcea.book.hpjp.util.AbstractTest; import org.hibernate.annotations.CacheConcurrencyStrategy; import org.junit.Before; import org.junit.Test; import javax.persistence.*; import java.util.ArrayList; import java.util.List; import java.util.Properties; import static org.junit.Assert.assertEquals; /** * @author Vlad Mihalcea */ public class SequenceReadWriteCacheConcurrencyStrategyTest extends AbstractTest { @Override protected Class<?>[] entities() { return new Class<?>[] { Post.class, PostComment.class }; } @Override protected Properties properties() { Properties properties = super.properties(); properties.put("hibernate.cache.use_second_level_cache", Boolean.TRUE.toString()); properties.put("hibernate.cache.region.factory_class", "ehcache"); return properties; } @Before public void init() { super.init(); doInJPA(entityManager -> { Post post = new Post(); post.setTitle("High-Performance Java Persistence"); PostComment comment1 = new PostComment(); comment1.setReview("JDBC part review"); post.addComment(comment1); PostComment comment2 = new PostComment(); comment2.setReview("Hibernate part review"); post.addComment(comment2); entityManager.persist(post); }); printCacheRegionStatistics(Post.class.getName()); printCollectionCacheRegionStatistics(Post.class, "comments"); LOGGER.info("Post entity inserted"); } @Test public void testPostEntityLoad() { LOGGER.info("Load Post entity and comments collection"); doInJPA(entityManager -> { Post post = entityManager.find(Post.class, 1L); assertEquals(2, post.getComments().size()); printEntityCacheRegionStatistics(Post.class); printCollectionCacheRegionStatistics(Post.class, "comments"); }); } @Entity(name = "Post") @Table(name = "post") @org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE) public static class Post { @Id @GeneratedValue(strategy = GenerationType.SEQUENCE) private Long id; private String title; @Version private int version; @OneToMany(cascade = CascadeType.ALL, mappedBy = "post", orphanRemoval = true) @org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE) private List<PostComment> comments = new ArrayList<>(); public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public List<PostComment> getComments() { return comments; } public void addComment(PostComment comment) { comments.add(comment); comment.setPost(this); } } @Entity(name = "PostComment") @Table(name = "post_comment") @org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE) public static class PostComment { @Id @GeneratedValue(strategy = GenerationType.SEQUENCE) private Long id; @ManyToOne(fetch = FetchType.LAZY) private Post post; private String review; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Post getPost() { return post; } public void setPost(Post post) { this.post = post; } public String getReview() { return review; } public void setReview(String review) { this.review = review; } } }
vladmihalcea/high-performance-java-persistence
core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/cache/readwrite/SequenceReadWriteCacheConcurrencyStrategyTest.java
Java
apache-2.0
4,060
/* * 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 com.alibaba.dubbo.common.extensionloader.ext5.impl; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.extensionloader.ext5.NoAdaptiveMethodExt; public class Ext5Impl1 implements NoAdaptiveMethodExt { public String echo(URL url, String s) { return "Ext5Impl1-echo"; } }
dadarom/dubbo
dubbo-common/src/test/java/com/alibaba/dubbo/common/extensionloader/ext5/impl/Ext5Impl1.java
Java
apache-2.0
1,115
/* * Copyright (C) 2010 PIRAmIDE-SP3 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. * * This software consists of contributions made by many individuals, * listed below: * * Author: Aitor Almeida <aitor.almeida@deusto.es> * Pablo Orduña <pablo.orduna@deusto.es> * Eduardo Castillejo <eduardo.castillejo@deusto.es> * */ package piramide.multimodal.downloader.client; import java.io.BufferedInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import android.content.Context; import android.content.Intent; import android.net.Uri; public class ApplicationDownloader { private static final String APK_FILENAME = "application.apk"; private final Context context; private final String url; ApplicationDownloader(Context context, String url){ this.context = context; this.url = url; } void download() throws DownloaderException{ final HttpClient client = new DefaultHttpClient(); try { final FileOutputStream fos = this.context.openFileOutput(APK_FILENAME, Context.MODE_WORLD_READABLE); final HttpResponse response = client.execute(new HttpGet(this.url)); if(response.getStatusLine().getStatusCode() < 200 || response.getStatusLine().getStatusCode() >= 400){ throw new DownloaderException("Invalid status code downloading application: " + response.getStatusLine().getReasonPhrase()); } downloadFile(response, fos); fos.close(); } catch (ClientProtocolException e) { throw new DownloaderException(e); } catch (IOException e) { throw new DownloaderException(e); } } void install(){ final Intent intent = new Intent(); intent.setAction(android.content.Intent.ACTION_VIEW); intent.setDataAndType(Uri.parse("file://" + this.context.getFilesDir().getAbsolutePath() + "/" + APK_FILENAME), "application/vnd.android.package-archive"); this.context.startActivity(intent); } private void downloadFile(HttpResponse response, OutputStream os) throws IOException { final InputStream is = response.getEntity().getContent(); long size = response.getEntity().getContentLength(); BufferedInputStream bis = new BufferedInputStream(is); final byte [] buffer = new byte[1024 * 1024]; // 1 MB long position = 0; while(position < size){ final int read = bis.read(buffer, 0, buffer.length); if(read <= 0) break; os.write(buffer, 0, read); os.flush(); position += read; } is.close(); } }
aitoralmeida/imhotep
PiramideApplicationDownloader/src/piramide/multimodal/downloader/client/ApplicationDownloader.java
Java
apache-2.0
3,264
/** * Copyright (c) 2007-2014 Kaazing Corporation. All rights reserved. * * 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.kaazing.gateway.server.context.resolve; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import org.kaazing.gateway.server.config.sep2014.ServiceAcceptOptionsType; import org.kaazing.gateway.service.AcceptOptionsContext; import org.kaazing.gateway.util.Utils; import org.kaazing.gateway.util.ssl.SslCipherSuites; import static org.kaazing.gateway.service.TransportOptionNames.*; public class DefaultAcceptOptionsContext implements AcceptOptionsContext { private static int DEFAULT_WEBSOCKET_MAXIMUM_MESSAGE_SIZE = 128 * 1024; //128KB private static int DEFAULT_HTTP_KEEPALIVE_TIMEOUT = 30; //seconds private static final long UNLIMITED_MAX_OUTPUT_RATE = 0xFFFFFFFFL; private static long DEFAULT_TCP_MAXIMUM_OUTBOUND_RATE = UNLIMITED_MAX_OUTPUT_RATE; //unlimited /** * The name of the extended handshake protocol to be sent on the wire. */ public static final String EXTENDED_HANDSHAKE_PROTOCOL_NAME = "x-kaazing-handshake"; private static final String PING_PONG = "x-kaazing-ping-pong"; private static final String IDLE_TIMEOUT = "x-kaazing-idle-timeout"; private static final long DEFAULT_WS_INACTIVITY_TIMEOUT_MILLIS = 0L; private static List<String> DEFAULT_WEBSOCKET_PROTOCOLS; private static List<String> DEFAULT_WEBSOCKET_EXTENSIONS; static { // Note: including null in these arrays permits us to process no protocols/extensions // without throwing an exception. DEFAULT_WEBSOCKET_PROTOCOLS = Arrays.asList(EXTENDED_HANDSHAKE_PROTOCOL_NAME, null); DEFAULT_WEBSOCKET_EXTENSIONS = Arrays.asList(PING_PONG, null); } private final boolean sslEncryptionEnabled; private final String[] sslCiphers; private final String[] sslProtocols; private final boolean sslWantClientAuth; private final boolean sslNeedClientAuth; private final URI tcpTransportURI; private final URI sslTransportURI; private final URI httpTransportURI; private final int wsMaxMessageSize; private final long wsInactivityTimeout; private final int httpKeepaliveTimeout; private final Map<String, String> binds; private final List<String> wsProtocols; private final List<String> wsExtensions; private final long tcpMaximumOutboundRate; private final String udpInterface; private final URI pipeTransportURI; public DefaultAcceptOptionsContext() { this(ServiceAcceptOptionsType.Factory.newInstance(), ServiceAcceptOptionsType.Factory.newInstance()); } public DefaultAcceptOptionsContext(ServiceAcceptOptionsType acceptOptions, ServiceAcceptOptionsType defaultOptions) { this.binds = new HashMap<String, String>(); Boolean sslEncryptionEnabled = null; if (acceptOptions != null) { ServiceAcceptOptionsType.SslEncryption.Enum encrypted = acceptOptions.getSslEncryption(); if (encrypted != null) { sslEncryptionEnabled = encrypted != ServiceAcceptOptionsType.SslEncryption.DISABLED; } } boolean wantClientAuth = false; boolean needClientAuth = false; if (acceptOptions != null) { ServiceAcceptOptionsType.SslVerifyClient.Enum verifyClient = acceptOptions.getSslVerifyClient(); if (verifyClient != null) { if (verifyClient == ServiceAcceptOptionsType.SslVerifyClient.REQUIRED) { wantClientAuth = false; needClientAuth = true; } else if (verifyClient == ServiceAcceptOptionsType.SslVerifyClient.OPTIONAL) { wantClientAuth = true; needClientAuth = false; } else { wantClientAuth = false; needClientAuth = false; } } } String udpInterface = null; if (acceptOptions != null) { udpInterface = acceptOptions.getUdpInterface(); } String sslCiphers = null; if (acceptOptions != null) { sslCiphers = acceptOptions.getSslCiphers(); } String sslProtocols = null; if (acceptOptions != null) { sslProtocols = acceptOptions.getSslProtocols(); } String pipeTransport = null; if (acceptOptions != null) { pipeTransport = acceptOptions.getPipeTransport(); } String tcpTransport = null; if (acceptOptions != null) { tcpTransport = acceptOptions.getTcpTransport(); } String sslTransport = null; if (acceptOptions != null) { sslTransport = acceptOptions.getSslTransport(); } String httpTransport = null; if (acceptOptions != null) { httpTransport = acceptOptions.getHttpTransport(); } Long httpKeepaliveTimeout = null; if (acceptOptions != null) { String value = acceptOptions.getHttpKeepaliveTimeout(); if (value != null) { long val = Utils.parseTimeInterval(value, TimeUnit.SECONDS); if (val > 0) { httpKeepaliveTimeout = val; } } } Integer wsMaxMessageSize = null; if (acceptOptions != null) { String wsMax = acceptOptions.getWsMaximumMessageSize(); if (wsMax != null) { wsMaxMessageSize = Utils.parseDataSize(wsMax); } } Long wsInactivityTimeout = null; if (acceptOptions != null) { String value = acceptOptions.getWsInactivityTimeout(); if (value != null) { long val = Utils.parseTimeInterval(value, TimeUnit.MILLISECONDS); if (val > 0) { wsInactivityTimeout = val; } } } Long tcpMaxOutboundRate = null; if (acceptOptions != null) { String tcpMax = acceptOptions.getTcpMaximumOutboundRate(); if (tcpMax != null) { tcpMaxOutboundRate = Utils.parseDataRate(tcpMax); } } if (defaultOptions != null) { // add all the binds addBind("ws", defaultOptions.getWsBind()); addBind("wss", defaultOptions.getWssBind()); addBind("http", defaultOptions.getHttpBind()); addBind("https", defaultOptions.getHttpsBind()); addBind("ssl", defaultOptions.getSslBind()); addBind("tcp", defaultOptions.getTcpBind()); if (sslEncryptionEnabled == null) { ServiceAcceptOptionsType.SslEncryption.Enum encrypted = defaultOptions.getSslEncryption(); sslEncryptionEnabled = encrypted != ServiceAcceptOptionsType.SslEncryption.DISABLED; } if (!wantClientAuth && !needClientAuth) { ServiceAcceptOptionsType.SslVerifyClient.Enum verifyClient = defaultOptions.getSslVerifyClient(); if (verifyClient != null) { if (verifyClient == ServiceAcceptOptionsType.SslVerifyClient.REQUIRED) { wantClientAuth = false; needClientAuth = true; } else if (verifyClient == ServiceAcceptOptionsType.SslVerifyClient.OPTIONAL) { wantClientAuth = true; needClientAuth = false; } else { wantClientAuth = false; needClientAuth = false; } } } if (sslCiphers == null) { sslCiphers = defaultOptions.getSslCiphers(); } if (sslProtocols == null) { sslProtocols = defaultOptions.getSslProtocols(); } if (pipeTransport == null) { pipeTransport = defaultOptions.getPipeTransport(); } if (tcpTransport == null) { tcpTransport = defaultOptions.getTcpTransport(); } if (sslTransport == null) { sslTransport = defaultOptions.getSslTransport(); } if (httpTransport == null) { httpTransport = defaultOptions.getHttpTransport(); } if (httpKeepaliveTimeout == null) { try { httpKeepaliveTimeout = Utils.parseTimeInterval(defaultOptions.getHttpKeepaliveTimeout(), TimeUnit.SECONDS); } catch (NumberFormatException e) { throw new IllegalArgumentException("Cannot parse http.keepalive.timeout as a time interval: \"" + defaultOptions.getHttpKeepaliveTimeout() + "\"."); } } if (wsMaxMessageSize == null) { String wsMax = defaultOptions.getWsMaximumMessageSize(); if (wsMax != null) { wsMaxMessageSize = Utils.parseDataSize(wsMax); } } if (wsInactivityTimeout == null) { try { wsInactivityTimeout = Utils.parseTimeInterval(defaultOptions.getWsInactivityTimeout(), TimeUnit.MILLISECONDS); } catch (NumberFormatException e) { throw new IllegalArgumentException("Cannot parse ws.inactivity.timeout as a time interval: \"" + defaultOptions.getWsInactivityTimeout() + "\"."); } } if (tcpMaxOutboundRate == null) { String tcpMax = defaultOptions.getTcpMaximumOutboundRate(); if (tcpMax != null) { tcpMaxOutboundRate = Utils.parseDataRate(tcpMax); } } } this.sslEncryptionEnabled = (sslEncryptionEnabled == null) ? true : sslEncryptionEnabled; this.sslCiphers = (sslCiphers != null) ? SslCipherSuites.resolveCSV(sslCiphers) : null; this.sslProtocols = (sslProtocols != null) ? resolveProtocols(sslProtocols) : null; this.sslWantClientAuth = wantClientAuth; this.sslNeedClientAuth = needClientAuth; if (pipeTransport != null) { this.pipeTransportURI = URI.create(pipeTransport); if (!this.pipeTransportURI.isAbsolute()) { throw new IllegalArgumentException(String .format("pipe.transport must contain an absolute URI, not \"%s\"", pipeTransport)); } } else { this.pipeTransportURI = null; } if (tcpTransport != null) { this.tcpTransportURI = URI.create(tcpTransport); if (!this.tcpTransportURI.isAbsolute()) { throw new IllegalArgumentException(String .format("tcp.transport must contain an absolute URI, not \"%s\"", tcpTransport)); } } else { this.tcpTransportURI = null; } if (sslTransport != null) { this.sslTransportURI = URI.create(sslTransport); if (!this.sslTransportURI.isAbsolute()) { throw new IllegalArgumentException(String .format("ssl.transport must contain an absolute URI, not \"%s\"", sslTransport)); } } else { this.sslTransportURI = null; } if (httpTransport != null) { this.httpTransportURI = URI.create(httpTransport); if (!this.httpTransportURI.isAbsolute()) { throw new IllegalArgumentException(String .format("http.transport must contain an absolute URI, not \"%s\"", httpTransport)); } } else { this.httpTransportURI = null; } // We are documenting that a configured outbound rate of 0 means unlimited and, and we will treat as unlimited rates // at or above 0xFFFFFFFF. Handle these cases here at the edge so the rest of our code doesn't need to worry. this.tcpMaximumOutboundRate = (tcpMaxOutboundRate == null) ? DEFAULT_TCP_MAXIMUM_OUTBOUND_RATE : (tcpMaxOutboundRate == 0 || tcpMaxOutboundRate > UNLIMITED_MAX_OUTPUT_RATE) ? UNLIMITED_MAX_OUTPUT_RATE : tcpMaxOutboundRate; this.wsMaxMessageSize = (wsMaxMessageSize == null) ? DEFAULT_WEBSOCKET_MAXIMUM_MESSAGE_SIZE : wsMaxMessageSize; this.wsInactivityTimeout = (wsInactivityTimeout == null) ? DEFAULT_WS_INACTIVITY_TIMEOUT_MILLIS : wsInactivityTimeout; this.httpKeepaliveTimeout = (httpKeepaliveTimeout == null) ? DEFAULT_HTTP_KEEPALIVE_TIMEOUT : httpKeepaliveTimeout.intValue(); // Hard code supported protocols and extensions. this.wsProtocols = DEFAULT_WEBSOCKET_PROTOCOLS; //KG-9977 add x-kaazing-idle-timeout extension if configured if (this.wsInactivityTimeout > 0) { ArrayList<String> extensions = new ArrayList<String>(DEFAULT_WEBSOCKET_EXTENSIONS); extensions.add(IDLE_TIMEOUT); this.wsExtensions = extensions; } else { this.wsExtensions = DEFAULT_WEBSOCKET_EXTENSIONS; } // if there were default options, overlay the service accept options to have the final options for this service if (acceptOptions != null) { addBind("ws", acceptOptions.getWsBind()); addBind("wss", acceptOptions.getWssBind()); addBind("http", acceptOptions.getHttpBind()); addBind("https", acceptOptions.getHttpsBind()); addBind("ssl", acceptOptions.getSslBind()); addBind("tcp", acceptOptions.getTcpBind()); } this.udpInterface = udpInterface; } @Override public Map<String, String> getBinds() { return binds; } @Override public boolean isSslEncryptionEnabled() { return sslEncryptionEnabled; } @Override public Integer getSessionIdleTimeout(String scheme) { Integer ret = null; if (scheme.equals("http") || scheme.equals("https")) { ret = httpKeepaliveTimeout; } return ret; } @Override public Integer getHttpKeepaliveTimeout() { return httpKeepaliveTimeout; } @Override public int getWsMaxMessageSize() { return wsMaxMessageSize; } @Override public long getWsInactivityTimeout() { return wsInactivityTimeout; } @Override public long getTcpMaximumOutboundRate() { return tcpMaximumOutboundRate; } @Override public List<String> getWsProtocols() { return wsProtocols; } @Override public List<String> getWsExtensions() { return wsExtensions; } @Override public URI getInternalURI(URI externalURI) { String authority = externalURI.getAuthority(); String internalAuthority = binds.get(externalURI.getScheme()); if (internalAuthority != null) { if (!internalAuthority.equals(authority)) { try { return new URI(externalURI.getScheme(), internalAuthority, externalURI.getPath(), externalURI.getQuery(), externalURI.getFragment()); } catch (URISyntaxException e) { // ignore } } return externalURI; } // there's no binding for this URI, return null return null; } @Override public void addBind(String scheme, String hostPort) { if (hostPort != null) { if (!hostPort.contains(":")) { try { int port = Integer.parseInt(hostPort); this.binds.put(scheme, "0.0.0.0:" + port); } catch (NumberFormatException ex) { throw new RuntimeException("Failed to add bind for scheme " + scheme + " to port " + hostPort, ex); } } else { this.binds.put(scheme, hostPort); } } } @Override public String[] getSslCiphers() { return sslCiphers; } @Override public String[] getSslProtocols() { return sslProtocols; } @Override public boolean getSslWantClientAuth() { return sslWantClientAuth; } @Override public boolean getSslNeedClientAuth() { return sslNeedClientAuth; } @Override public URI getTcpTransport() { return tcpTransportURI; } @Override public URI getSslTransport() { return sslTransportURI; } @Override public URI getHttpTransport() { return httpTransportURI; } @Override public URI getPipeTransport() { return pipeTransportURI; } @Override public String getUdpInterface() { return udpInterface; } public Map<String, Object> asOptionsMap() { Map<String, Object> result = new LinkedHashMap<String, Object>(); result.put(SUPPORTED_PROTOCOLS, getWsProtocols().toArray(new String[getWsProtocols().size()])); result.put("ws.extensions", getWsExtensions()); result.put("ws[ws/rfc6455].ws[ws/rfc6455].extensions", getWsExtensions()); result.put("ws[ws/draft-7x].ws[ws/draft-7x].extensions", getWsExtensions()); result.put("ws.maxMessageSize", getWsMaxMessageSize()); result.put("ws[ws/rfc6455].ws[ws/rfc6455].maxMessageSize", getWsMaxMessageSize()); result.put("ws[ws/draft-7x].ws[ws/draft-7x].maxMessageSize", getWsMaxMessageSize()); result.put("ws.inactivityTimeout", getWsInactivityTimeout()); result.put("ws[ws/rfc6455].ws[ws/rfc6455].inactivityTimeout", getWsInactivityTimeout()); result.put("ws[ws/draft-7x].ws[ws/draft-7x].inactivityTimeout", getWsInactivityTimeout()); result.put("http[http/1.1].keepAliveTimeout", getHttpKeepaliveTimeout()); result.put(PIPE_TRANSPORT, getPipeTransport()); result.put(SSL_CIPHERS, getSslCiphers()); result.put(SSL_PROTOCOLS, getSslProtocols()); result.put(SSL_ENCRYPTION_ENABLED, isSslEncryptionEnabled()); result.put(SSL_WANT_CLIENT_AUTH, getSslWantClientAuth()); result.put(SSL_NEED_CLIENT_AUTH, getSslNeedClientAuth()); result.put(TCP_TRANSPORT, getTcpTransport()); result.put(SSL_TRANSPORT, getSslTransport()); result.put("http[http/1.1].transport", getHttpTransport()); result.put(TCP_MAXIMUM_OUTBOUND_RATE, getTcpMaximumOutboundRate()); result.put("udp.interface", getUdpInterface()); for (Map.Entry<String, String> entry : getBinds().entrySet()) { /* For lookups out of this COPY of the options, we need to * translate the scheme names into hierarchical transport names, * i.e.: * * ssl -> ssl.tcp.bind * http -> http.tcp.bind * https -> http.ssl.tcp.bind * ws -> ws.tcp.bind * wss -> ws.ssl.tcp.bind */ String internalBindOptionName = resolveInternalBindOptionName(entry.getKey()); if (internalBindOptionName != null) { result.put(internalBindOptionName, entry.getValue()); } else { throw new RuntimeException("Cannot apply unknown bind option '" + entry.getKey() + "'."); } } return result; } private String resolveInternalBindOptionName(String externalBindOptionName) { if (externalBindOptionName.equals("tcp")) { return "tcp.bind"; } else if (externalBindOptionName.equals("ssl")) { return "ssl.tcp.bind"; } else if (externalBindOptionName.equals("http")) { return "http.tcp.bind"; } else if (externalBindOptionName.equals("https")) { return "http.ssl.tcp.bind"; } else if (externalBindOptionName.equals("ws")) { return "ws.http.tcp.bind"; } else if (externalBindOptionName.equals("wss")) { return "ws.http.ssl.tcp.bind"; } else if (externalBindOptionName.equals("wsn")) { return "wsn.http.tcp.bind"; } else if (externalBindOptionName.equals("wsn+ssl")) { return "wsn.http.ssl.tcp.bind"; } else if (externalBindOptionName.equals("wsx")) { return "wsn.http.wsn.http.tcp.bind"; } else if (externalBindOptionName.equals("wsx+ssl")) { return "wsn.http.wsn.http.ssl.tcp.bind"; } else if (externalBindOptionName.equals("httpxe")) { return "http.http.tcp.bind"; } else if (externalBindOptionName.equals("httpxe+ssl")) { return "http.http.ssl.tcp.bind"; } return null; } // We return a String array here, rather than a list, because the // javax.net.ssl.SSLEngine.setEnabledProtocols() method wants a // String array. public static String[] resolveProtocols(String csv) { if (csv != null && !csv.equals("")) { return csv.split(","); } else { return null; } } }
jitsni/gateway.distribution
gateway.server/src/main/java/org/kaazing/gateway/server/context/resolve/DefaultAcceptOptionsContext.java
Java
apache-2.0
22,399
/** * Copyright (C) 2006-2013 phloc systems * http://www.phloc.com * office[at]phloc[dot]com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.phloc.commons.locale.country; import java.util.HashSet; import java.util.Locale; import java.util.Set; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.annotation.concurrent.ThreadSafe; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.phloc.commons.CGlobal; import com.phloc.commons.annotations.PresentForCodeCoverage; import com.phloc.commons.annotations.ReturnsMutableCopy; import com.phloc.commons.collections.ContainerHelper; import com.phloc.commons.locale.LocaleCache; import com.phloc.commons.state.EChange; import com.phloc.commons.string.StringHelper; /** * This is a global cache for country objects to avoid too many object flowing * around.<br> * This cache is application independent. * * @author Philip Helger */ @ThreadSafe public final class CountryCache { private static final Logger s_aLogger = LoggerFactory.getLogger (CountryCache.class); private static final ReadWriteLock s_aRWLock = new ReentrantReadWriteLock (); /** Contains all known countries (as ISO 3166 2-letter codes). */ private static final Set <String> s_aCountries = new HashSet <String> (); static { _initialFillCache (); } @PresentForCodeCoverage @SuppressWarnings ("unused") private static final CountryCache s_aInstance = new CountryCache (); private CountryCache () {} private static void _initialFillCache () { for (final Locale aLocale : LocaleCache.getAllLocales ()) { final String sCountry = aLocale.getCountry (); if (StringHelper.hasText (sCountry)) addCountry (sCountry); } } @Nonnull private static String _getUnifiedCountry (@Nonnull final String sCountry) { // We can US locale, because the ISO 3166 codes don't contain non-ASCII // chars return sCountry.toUpperCase (Locale.US); } @Nonnull static EChange addCountry (@Nonnull final String sCountry) { if (sCountry == null) throw new NullPointerException ("country"); if (!sCountry.equals (_getUnifiedCountry (sCountry))) throw new IllegalArgumentException ("illegal casing of '" + sCountry + "'"); s_aRWLock.writeLock ().lock (); try { return EChange.valueOf (s_aCountries.add (sCountry)); } finally { s_aRWLock.writeLock ().unlock (); } } @Nullable public static Locale getCountry (@Nullable final Locale aCountry) { return aCountry == null ? null : getCountry (aCountry.getCountry ()); } @Nullable public static Locale getCountry (@Nullable final String sCountry) { if (StringHelper.hasNoText (sCountry)) return null; // Was something like "_AT" (e.g. the result of getCountry (...).toString // ()) passed in? -> indirect recursion if (sCountry.indexOf (CGlobal.LOCALE_SEPARATOR) >= 0) return getCountry (LocaleCache.getLocale (sCountry)); final String sRealCountry = _getUnifiedCountry (sCountry); if (!containsCountry (sRealCountry)) s_aLogger.warn ("Trying to retrieve unsupported country " + sRealCountry); return LocaleCache.getLocale ("", sRealCountry, ""); } /** * @return a set with all contained countries. Never <code>null</code>. */ @Nonnull @ReturnsMutableCopy public static Set <String> getAllCountries () { s_aRWLock.readLock ().lock (); try { return ContainerHelper.newSet (s_aCountries); } finally { s_aRWLock.readLock ().unlock (); } } /** * @return a set with all contained country locales. Never <code>null</code>. */ @Nonnull @ReturnsMutableCopy public static Set <Locale> getAllCountryLocales () { final Set <Locale> ret = new HashSet <Locale> (); for (final String sCountry : getAllCountries ()) ret.add (LocaleCache.getLocale ("", sCountry, "")); return ret; } /** * Check if the passed country is known. * * @param aCountry * The country to check. May be <code>null</code>. * @return <code>true</code> if the passed country is contained, * <code>false</code> otherwise. */ public static boolean containsCountry (@Nullable final Locale aCountry) { return aCountry != null && containsCountry (aCountry.getCountry ()); } /** * Check if the passed country is known. * * @param sCountry * The country to check. May be <code>null</code>. * @return <code>true</code> if the passed country is contained, * <code>false</code> otherwise. */ public static boolean containsCountry (@Nullable final String sCountry) { if (sCountry == null) return false; final String sUnifiedCountry = _getUnifiedCountry (sCountry); s_aRWLock.readLock ().lock (); try { return s_aCountries.contains (sUnifiedCountry); } finally { s_aRWLock.readLock ().unlock (); } } /** * Reset the cache to the initial state. */ public static void resetCache () { s_aRWLock.writeLock ().lock (); try { s_aCountries.clear (); _initialFillCache (); if (s_aLogger.isDebugEnabled ()) s_aLogger.debug ("Cache was reset: " + CountryCache.class.getName ()); } finally { s_aRWLock.writeLock ().unlock (); } } }
lsimons/phloc-schematron-standalone
phloc-commons/src/main/java/com/phloc/commons/locale/country/CountryCache.java
Java
apache-2.0
6,033
/* The contents of this file are subject to the license and copyright terms * detailed in the license directory at the root of the source tree (also * available online at http://fedora-commons.org/license/). */ package org.fcrepo.server.storage.translation; import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.Reader; import java.io.StringReader; import java.io.UnsupportedEncodingException; import java.net.URISyntaxException; import java.text.ParseException; import java.util.Comparator; import java.util.Date; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import javax.xml.stream.XMLStreamException; import javax.activation.MimeType; import org.apache.commons.io.IOUtils; import org.apache.abdera.Abdera; import org.apache.abdera.ext.thread.ThreadHelper; import org.apache.abdera.i18n.iri.IRI; import org.apache.abdera.model.Category; import org.apache.abdera.model.Content; import org.apache.abdera.model.Document; import org.apache.abdera.model.Entry; import org.apache.abdera.model.Feed; import org.apache.abdera.model.Person; import org.apache.abdera.parser.Parser; import org.apache.abdera.util.MimeTypeHelper; import org.apache.abdera.xpath.XPath; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.fcrepo.common.Constants; import org.fcrepo.common.MalformedPIDException; import org.fcrepo.common.PID; import org.fcrepo.common.xml.format.XMLFormat; import org.fcrepo.server.errors.ObjectIntegrityException; import org.fcrepo.server.errors.StreamIOException; import org.fcrepo.server.errors.ValidationException; import org.fcrepo.server.storage.types.Datastream; import org.fcrepo.server.storage.types.DatastreamManagedContent; import org.fcrepo.server.storage.types.DatastreamReferencedContent; import org.fcrepo.server.storage.types.DatastreamXMLMetadata; import org.fcrepo.server.storage.types.DigitalObject; import org.fcrepo.server.validation.ValidationUtility; import org.fcrepo.utilities.DateUtility; import org.fcrepo.utilities.FileUtils; import org.fcrepo.utilities.NormalizedURI; /** * Deserializer for Fedora Objects in Atom format. * * @author Edwin Shin * @since 3.0 * @version $Id$ */ public class AtomDODeserializer implements DODeserializer, Constants { public static final XMLFormat DEFAULT_FORMAT = ATOM1_1; private static final Logger logger = LoggerFactory.getLogger(AtomDODeserializer.class); /** The object to deserialize to. */ private DigitalObject m_obj; private String m_encoding; /** The current translation context. */ private int m_transContext; /** The format this deserializer reads. */ private final XMLFormat m_format; private final Abdera abdera = Abdera.getInstance(); private Feed m_feed; private XPath m_xpath; private ZipInputStream m_zin; /** * Temporary directory for the unpacked contents of an Atom Zip archive. */ private File m_tempDir; public AtomDODeserializer() { this(DEFAULT_FORMAT); } public AtomDODeserializer(XMLFormat format) { if (format.equals(ATOM1_1) || format.equals(ATOM_ZIP1_1)) { m_format = format; } else { throw new IllegalArgumentException("Not an Atom format: " + format.uri); } } /** * {@inheritDoc} */ public void deserialize(InputStream in, DigitalObject obj, String encoding, int transContext) throws ObjectIntegrityException, StreamIOException, UnsupportedEncodingException { if (m_format.equals(ATOM_ZIP1_1)) { try { m_tempDir = FileUtils.createTempDir("atomzip", null); m_zin = new ZipInputStream(new BufferedInputStream(in)); ZipEntry entry; while ((entry = m_zin.getNextEntry()) != null) { FileUtils.copy(m_zin, new FileOutputStream(new File(m_tempDir, entry.getName()))); } in = new FileInputStream(new File(m_tempDir, "atommanifest.xml")); } catch (FileNotFoundException e) { throw new StreamIOException(e.getMessage(), e); } catch (IOException e) { throw new StreamIOException(e.getMessage(), e); } } Parser parser = abdera.getParser(); Document<Feed> feedDoc = parser.parse(in); m_feed = feedDoc.getRoot(); m_xpath = abdera.getXPath(); m_obj = obj; m_encoding = encoding; m_transContext = transContext; addObjectProperties(); addDatastreams(); DOTranslationUtility.normalizeDatastreams(m_obj, m_transContext, m_encoding); FileUtils.delete(m_tempDir); } /** * {@inheritDoc} */ public DODeserializer getInstance() { return new AtomDODeserializer(m_format); } /** * Set the Fedora Object properties from the Feed metadata. * * @throws ObjectIntegrityException */ private void addObjectProperties() throws ObjectIntegrityException { PID pid; try { pid = new PID(m_feed.getId().toString()); } catch (MalformedPIDException e) { throw new ObjectIntegrityException(e.getMessage(), e); } String label = m_feed.getTitle(); String state = m_xpath.valueOf("/a:feed/a:category[@scheme='" + MODEL.STATE.uri + "']/@term", m_feed); String createDate = m_xpath.valueOf("/a:feed/a:category[@scheme='" + MODEL.CREATED_DATE.uri + "']/@term", m_feed); m_obj.setPid(pid.toString()); try { m_obj.setState(DOTranslationUtility.readStateAttribute(state)); } catch (ParseException e) { throw new ObjectIntegrityException("Could not read object state", e); } m_obj.setLabel(label); m_obj.setOwnerId(getOwnerId()); m_obj.setCreateDate(DateUtility.convertStringToDate(createDate)); m_obj.setLastModDate(m_feed.getUpdated()); setExtProps(); } private void addDatastreams() throws UnsupportedEncodingException, StreamIOException, ObjectIntegrityException { m_feed.sortEntries(new UpdatedIdComparator(true)); List<Entry> entries = m_feed.getEntries(); for (Entry entry : entries) { if (ThreadHelper.getInReplyTo(entry) != null) { addDatastreamVersion(entry); } } } private void addDatastreamVersion(Entry entry) throws UnsupportedEncodingException, StreamIOException, ObjectIntegrityException { IRI ref = ThreadHelper.getInReplyTo(entry).getRef(); Entry parent = m_feed.getEntry(ref.toString()); Datastream ds; String controlGroup = getDSControlGroup(parent); if (controlGroup.equals("X")) { ds = addInlineDatastreamVersion(entry); } else if (controlGroup.equals("M")) { ds = addManagedDatastreamVersion(entry); } else { ds = addExternalReferencedDatastreamVersion(entry); } m_obj.addDatastreamVersion(ds, true); } private Datastream addInlineDatastreamVersion(Entry entry) throws ObjectIntegrityException, StreamIOException { DatastreamXMLMetadata ds = new DatastreamXMLMetadata(); setDSCommonProperties(ds, entry); String dsId = ds.DatastreamID; String dsvId = ds.DSVersionID; ds.DSLocation = m_obj.getPid() + "+" + dsId + "+" + dsvId; if (ds.DSVersionID.equals("AUDIT.0")) { addAuditDatastream(entry); } else { try { if (m_format.equals(ATOM_ZIP1_1)) { ByteArrayOutputStream bout = new ByteArrayOutputStream(); FileUtils.copy(new FileInputStream(getContentSrcAsFile(entry.getContentSrc())), bout); ds.xmlContent = bout.toByteArray(); } else { ds.xmlContent = entry.getContent().getBytes(m_encoding); //IOUtils.toByteArray(entry.getContentStream()); } } catch (UnsupportedEncodingException e) { throw new StreamIOException(e.getMessage(), e); } catch (FileNotFoundException e) { throw new ObjectIntegrityException(e.getMessage(), e); } } if (ds.xmlContent != null) { ds.DSSize = ds.xmlContent.length; } MimeType mimeType = entry.getContentMimeType(); if (mimeType == null) { ds.DSMIME = "text/xml"; } else { ds.DSMIME = mimeType.toString(); } return ds; } private Datastream addExternalReferencedDatastreamVersion(Entry entry) throws ObjectIntegrityException { Datastream ds = new DatastreamReferencedContent(); setDSCommonProperties(ds, entry); ds.DSLocation = entry.getContentSrc().toString(); // Normalize the dsLocation for the deserialization context ds.DSLocation = (DOTranslationUtility.normalizeDSLocationURLs(m_obj.getPid(), ds, m_transContext)).DSLocation; ds.DSLocationType = Datastream.DS_LOCATION_TYPE_URL; ds.DSMIME = entry.getContentMimeType().toString(); return ds; } private Datastream addManagedDatastreamVersion(Entry entry) throws StreamIOException, ObjectIntegrityException { Datastream ds = new DatastreamManagedContent(); setDSCommonProperties(ds, entry); ds.DSLocationType = Datastream.DS_LOCATION_TYPE_INTERNAL; ds.DSMIME = getDSMimeType(entry); // Managed Content can take any of the following forms: // 1) inline text (plaintext, html, xml) // 2) inline Base64 // 3) referenced content IRI contentLocation = entry.getContentSrc(); if (contentLocation != null) { // URL FORMAT VALIDATION for dsLocation: // For Managed Content the URL is only checked when we are parsing a // a NEW ingest file because the URL is replaced with an internal identifier // once the repository has sucked in the content for storage. // AtomZIP files can have a simple filename (nb, not file: )for the content location, so don't validate that if (m_obj.isNew() && !m_format.equals(ATOM_ZIP1_1)) { ValidationUtility .validateURL(contentLocation.toString(),ds.DSControlGrp); } if (m_format.equals(ATOM_ZIP1_1)) { if (!contentLocation.isAbsolute() && !contentLocation.isPathAbsolute()) { File f = getContentSrcAsFile(contentLocation); contentLocation = new IRI(DatastreamManagedContent.TEMP_SCHEME + f.getAbsolutePath()); } } ds.DSLocation = contentLocation.toString(); ds.DSLocation = (DOTranslationUtility.normalizeDSLocationURLs(m_obj .getPid(), ds, m_transContext)).DSLocation; return ds; } try { File temp = File.createTempFile("binary-datastream", null); OutputStream out = new FileOutputStream(temp); if (MimeTypeHelper.isText(ds.DSMIME) || MimeTypeHelper.isXml(ds.DSMIME)) { IOUtils.copy(new StringReader(entry.getContent()), out, m_encoding); } else { IOUtils.copy(entry.getContentStream(), out); } ds.DSLocation = DatastreamManagedContent.TEMP_SCHEME + temp.getAbsolutePath(); } catch (IOException e) { throw new StreamIOException(e.getMessage(), e); } return ds; } private void addAuditDatastream(Entry entry) throws ObjectIntegrityException, StreamIOException { try { Reader auditTrail; if (m_format.equals(ATOM_ZIP1_1)) { File f = getContentSrcAsFile(entry.getContentSrc()); auditTrail = new InputStreamReader(new FileInputStream(f), m_encoding); } else { auditTrail = new StringReader(entry.getContent()); } m_obj.getAuditRecords().addAll(DOTranslationUtility .getAuditRecords(auditTrail)); auditTrail.close(); } catch (XMLStreamException e) { throw new ObjectIntegrityException(e.getMessage(), e); } catch (IOException e) { throw new StreamIOException(e.getMessage(), e); } } private String getOwnerId() { Person owner = m_feed.getAuthor(); if (owner == null) { return ""; } else { return owner.getName(); } } /** * Parses the id to determine a datastreamId. * * @param id * @return */ private String getDatastreamId(Entry entry) { String entryId = entry.getId().toString(); // matches info:fedora/pid/dsid/timestamp Pattern pattern = Pattern.compile("^" + Constants.FEDORA.uri + ".+?/([^/]+)/?.*"); Matcher matcher = pattern.matcher(entryId); if (matcher.find()) { return matcher.group(1); } else { return m_obj.newDatastreamID(); } } private String getDatastreamVersionId(Entry entry) { String dsId = getDatastreamId(entry); String dsvId = entry.getTitle(); // e.g. Match DS1.0 but not DS1 if (dsvId.matches("^" + dsId + ".*\\.[\\w]")) { return dsvId; } else { if (!m_obj.datastreams(dsId).iterator().hasNext()) { return dsId + ".0"; } else { return m_obj.newDatastreamID(dsId); } } } private String getDSControlGroup(Entry entry) throws ObjectIntegrityException { List<Category> controlGroups = entry.getCategories(MODEL.CONTROL_GROUP.uri); // Try to infer the control group if not provided if (controlGroups.isEmpty() || controlGroups.size() > 1) { if (entry.getContentType() != null) { if (entry.getContentType().equals(Content.Type.XML)) { return "X"; } else { // only XML can be inline return "M"; } } if (entry.getContentSrc() != null) { return "M"; } // TODO other cases // link alts, link enclosures else { throw new ObjectIntegrityException("No control group provided by " + m_obj.getPid()); } } else { return controlGroups.get(0).getTerm(); } } private String getDSState(Entry entry) { List<Category> state = entry.getCategories(MODEL.STATE.uri); if (state.isEmpty() || state.size() > 1) { return "A"; } else { return state.get(0).getTerm(); } } /** * Note: AUDIT datastreams always return false, otherwise defaults to true. * * @param entry * @return */ private boolean getDSVersionable(Entry entry) { if (getDatastreamId(entry).equals("AUDIT")) { return false; } List<Category> versionable = entry.getCategories(MODEL.VERSIONABLE.uri); if (versionable.isEmpty() || versionable.size() > 1) { return true; } else { return Boolean.valueOf(versionable.get(0).getTerm()); } } private String[] getDSAltIds(Entry entry) { List<Category> altIds = entry.getCategories(MODEL.ALT_IDS.uri); if (altIds.isEmpty()) { return new String[0]; } else { return altIds.get(0).getTerm().split(" "); // TODO we could handle size > 1 } } private String getDSFormatURI(Entry entry) { List<Category> formatURI = entry.getCategories(MODEL.FORMAT_URI.uri); if (formatURI.isEmpty() || formatURI.size() > 1) { return null; } else { return formatURI.get(0).getTerm(); } } private String getDSLabel(Entry entry) { List<Category> label = entry.getCategories(MODEL.LABEL.uri); if (label.isEmpty()) { return ""; } return label.get(0).getTerm(); } private String getDSMimeType(Entry entry) { String dsMimeType = "application/unknown"; MimeType mimeType = entry.getContentMimeType(); if (mimeType == null) { Content.Type type = entry.getContentType(); if (type != null) { if (type == Content.Type.HTML) { dsMimeType = "text/html"; } else if (type == Content.Type.TEXT) { dsMimeType = "text/plain"; } else if (type == Content.Type.XHTML) { dsMimeType = "application/xhtml+xml"; } else if (type == Content.Type.XML) { dsMimeType = "text/xml"; } } } else { dsMimeType = mimeType.toString(); } return dsMimeType; } private String getDSChecksumType(Entry entry) { List<Category> digestType = entry.getCategories(MODEL.DIGEST_TYPE.uri); if (digestType.isEmpty()) { return Datastream.CHECKSUMTYPE_DISABLED; } else { return digestType.get(0).getTerm(); } } private String getDSChecksum(Entry entry) { List<Category> digest = entry.getCategories(MODEL.DIGEST.uri); if (digest.isEmpty()) { return Datastream.CHECKSUM_NONE; } else { return digest.get(0).getTerm(); } } private void setDSCommonProperties(Datastream dsVersion, Entry entry) throws ObjectIntegrityException { IRI ref = ThreadHelper.getInReplyTo(entry).getRef(); Entry parent = m_feed.getEntry(ref.toString()); dsVersion.DatastreamID = getDatastreamId(parent); dsVersion.DSControlGrp = getDSControlGroup(parent); dsVersion.DSState = getDSState(parent); dsVersion.DSVersionable = getDSVersionable(parent); setDatastreamVersionProperties(dsVersion, entry); } private void setDatastreamVersionProperties(Datastream ds, Entry entry) throws ValidationException { ds.DatastreamAltIDs = getDSAltIds(entry); ds.DSCreateDT = entry.getUpdated(); ds.DSFormatURI = getDSFormatURI(entry); ds.DSLabel = getDSLabel(entry); ds.DSVersionID = getDatastreamVersionId(entry); ds.DSChecksumType = getDSChecksumType(entry); String checksum = getDSChecksum(entry); if (m_obj.isNew()) { if (logger.isDebugEnabled()) { logger.debug("New Object: checking supplied checksum"); } if (checksum != null && !checksum.equals("") && !checksum.equals(Datastream.CHECKSUM_NONE)) { String tmpChecksum = ds.getChecksum(); if (logger.isDebugEnabled()) { logger.debug("checksum = " + tmpChecksum); } if (!checksum.equals(tmpChecksum)) { throw new ValidationException("Checksum Mismatch: " + tmpChecksum); } } ds.DSChecksumType = ds.getChecksumType(); } else { ds.DSChecksum = checksum; } } private void setExtProps() { List<Category> epCategories = m_feed.getCategories(MODEL.EXT_PROPERTY.uri); for (Category epCategory : epCategories) { m_obj.setExtProperty(epCategory.getTerm(), epCategory.getLabel()); } } /** * Returns the an Entry's contentSrc as a File relative to {@link #m_tempDir}. * * @param contentSrc * @return the contentSrc as a File relative to m_tempDir. * @throws ObjectIntegrityException */ protected File getContentSrcAsFile(IRI contentSrc) throws ObjectIntegrityException { if (contentSrc.isAbsolute() || contentSrc.isPathAbsolute()) { throw new ObjectIntegrityException("contentSrc must not be absolute"); } try { // Normalize the IRI to resolve percent-encoding and // backtracking (e.g. "../") NormalizedURI nUri = new NormalizedURI(m_tempDir.toURI().toString() + contentSrc.toString()); nUri.normalize(); File f = new File(nUri.toURI()); if (f.getParentFile().equals(m_tempDir)) { return f; } else { throw new ObjectIntegrityException(contentSrc.toString() + " is not a valid path."); } } catch (URISyntaxException e) { throw new ObjectIntegrityException(e.getMessage(), e); } } private static class UpdatedIdComparator implements Comparator<Entry> { private boolean ascending = true; UpdatedIdComparator(boolean ascending) { this.ascending = ascending; } public int compare(Entry o1, Entry o2) { Date d1 = o1.getUpdated(); Date d2 = o2.getUpdated(); String id1 = o1.getId().toString(); String id2 = o2.getId().toString(); int r = d1.compareTo(d2); if (d1.equals(d2)) { r = id1.compareTo(id2); } return (ascending) ? r : -r; } } }
fcrepo4-archive/fcrepo
fcrepo-server/src/main/java/org/fcrepo/server/storage/translation/AtomDODeserializer.java
Java
apache-2.0
22,724
/* * 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.calcite.sql.validate; import org.apache.calcite.rel.type.StructKind; import org.apache.calcite.sql.SqlNode; import org.apache.calcite.sql.SqlWithItem; import java.util.List; /** Scope providing the objects that are available after evaluating an item * in a WITH clause. * * <p>For example, in</p> * * <blockquote>{@code WITH t1 AS (q1) t2 AS (q2) q3}</blockquote> * * <p>{@code t1} provides a scope that is used to validate {@code q2} * (and therefore {@code q2} may reference {@code t1}), * and {@code t2} provides a scope that is used to validate {@code q3} * (and therefore q3 may reference {@code t1} and {@code t2}).</p> */ class WithScope extends ListScope { private final SqlWithItem withItem; /** Creates a WithScope. */ WithScope(SqlValidatorScope parent, SqlWithItem withItem) { super(parent); this.withItem = withItem; } public SqlNode getNode() { return withItem; } @Override public SqlValidatorNamespace getTableNamespace(List<String> names) { if (names.size() == 1 && names.get(0).equals(withItem.name.getSimple())) { return validator.getNamespace(withItem); } return super.getTableNamespace(names); } @Override public void resolve(List<String> names, boolean deep, Resolved resolved) { if (names.size() == 1 && names.equals(withItem.name.names)) { final SqlValidatorNamespace ns = validator.getNamespace(withItem); final Step path = resolved.emptyPath() .add(ns.getRowType(), 0, StructKind.FULLY_QUALIFIED); resolved.found(ns, false, null, path); return; } super.resolve(names, deep, resolved); } } // End WithScope.java
sreev/incubator-calcite
core/src/main/java/org/apache/calcite/sql/validate/WithScope.java
Java
apache-2.0
2,482
package com.yxkang.android.image.core; import java.util.Locale; /** * ImageProtocol */ @SuppressWarnings("ALL") public enum ImageProtocol { HTTP("http"), HTTPS("https"), FILE("file"), CONTENT("content"); private String protocol; private String uriPrefix; ImageProtocol(String protocol) { this.protocol = protocol; this.uriPrefix = protocol + "://"; } public boolean belongsTo(String uri) { return uri.toLowerCase(Locale.CHINA).startsWith(uriPrefix); } /** * Appends scheme to incoming path * * @param path the path * @return the path with the uri prefix */ public String wrap(String path) { return uriPrefix + path; } /** * Removed scheme part ("scheme://") from incoming URI * * @param uri the incoming URI * @return the path without the uri prefix */ public String crop(String uri) { if (!belongsTo(uri)) { throw new IllegalArgumentException( String.format("URI [%1$s] doesn't have expected protocol [%2$s]", uri, protocol)); } return uri.substring(uriPrefix.length()); } }
fine1021/library
support/src/main/java/com/yxkang/android/image/core/ImageProtocol.java
Java
apache-2.0
1,177
/** * Copyright [2009-2010] [dennis zhuang(killme2008@gmail.com)] Licensed under the Apache License, * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You * may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by * applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See * the License for the specific language governing permissions and limitations under the License */ package net.rubyeye.xmemcached.exception; /** * Base exception type for memcached client * * @author boyan * */ public class MemcachedException extends Exception { public MemcachedException() { super(); } public MemcachedException(String s) { super(s); } public MemcachedException(String message, Throwable cause) { super(message, cause); } public MemcachedException(Throwable cause) { super(cause); } private static final long serialVersionUID = -136568012546568164L; }
killme2008/xmemcached
src/main/java/net/rubyeye/xmemcached/exception/MemcachedException.java
Java
apache-2.0
1,121
/** * Copyright 2017 - 2018 Syncleus, 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.syncleus.aethermud.command.commands; import com.syncleus.aethermud.common.AetherMudEntry; import com.syncleus.aethermud.core.GameManager; import com.syncleus.aethermud.merchant.Merchant; import com.syncleus.aethermud.merchant.MerchantCommandHandler; import com.syncleus.aethermud.merchant.bank.commands.BankCommand; import com.syncleus.aethermud.merchant.lockers.LockerCommand; import com.syncleus.aethermud.merchant.playerclass_selector.PlayerClassCommand; import com.syncleus.aethermud.player.PlayerClass; import com.syncleus.aethermud.server.communication.Color; import com.google.common.base.Joiner; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.MessageEvent; import java.util.Arrays; import java.util.List; import java.util.Optional; import java.util.Set; public class TalkCommand extends Command { final static List<String> validTriggers = Arrays.asList("talk"); final static String description = "Talk to a merchant."; final static String correctUsage = "talk <merchant name>"; public TalkCommand(GameManager gameManager) { super(gameManager, validTriggers, description, correctUsage); } @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { TalkCommand talkCommand = this; execCommand(ctx, e, () -> { if (aetherMudSession.getGrabMerchant().isPresent()) { aetherMudSession.setGrabMerchant(Optional.empty()); return; } originalMessageParts.remove(0); String desiredMerchantTalk = Joiner.on(" ").join(originalMessageParts); Set<Merchant> merchants = currentRoom.getMerchants(); for (Merchant merchant : merchants) { if (merchant.getValidTriggers().contains(desiredMerchantTalk)) { write(merchant.getWelcomeMessage() + "\r\n"); if (merchant.getMerchantType() == Merchant.MerchantType.BASIC) { write(merchant.getMenu() + "\r\n"); gameManager.getChannelUtils().write(playerId, "\r\n" + MerchantCommandHandler.buildPrompt()); } else if (merchant.getMerchantType() == Merchant.MerchantType.BANK) { write(BankCommand.getPrompt()); } else if (merchant.getMerchantType() == Merchant.MerchantType.LOCKER) { write(LockerCommand.getPrompt()); } else if (merchant.getMerchantType() == Merchant.MerchantType.PLAYERCLASS_SELECTOR) { if (player.getLevel() < 2) { write("Before you can pick a character class, you must be at least level 2."); return; } if (!player.getPlayerClass().equals(PlayerClass.BASIC)) { write("You've already selected a character class. " + "\r\nIf you'd like to re-select you must present the old wise man with a " + "" + Color.YELLOW + "golden" + Color.MAGENTA + " fortune cookie" + Color.RESET); return; } write(PlayerClassCommand.getPrompt()); } aetherMudSession.setGrabMerchant(Optional.of( new AetherMudEntry<>(merchant, talkCommand))); } } }); } }
Syncleus/AetherMUD
src/main/java/com/syncleus/aethermud/command/commands/TalkCommand.java
Java
apache-2.0
4,158
package com.google.api.ads.dfp.jaxws.v201306; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; /** * * {@code ProductTemplate} is used to generate products. All generated products will * inherit all attributes from their {@code ProductTemplate}, except for segmentation, * which will be included in the {@link Product#targeting}. The generated products in turn will be * used to create {@link ProposalLineItem proposal line items} so that almost all attributes * in the product template are properties of the proposal line item. * * * <p>Java class for ProductTemplate complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="ProductTemplate"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="id" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/> * &lt;element name="name" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="creationDateTime" type="{https://www.google.com/apis/ads/publisher/v201306}DateTime" minOccurs="0"/> * &lt;element name="lastModifiedDateTime" type="{https://www.google.com/apis/ads/publisher/v201306}DateTime" minOccurs="0"/> * &lt;element name="description" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="nameMacro" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="status" type="{https://www.google.com/apis/ads/publisher/v201306}ProductTemplateStatus" minOccurs="0"/> * &lt;element name="productType" type="{https://www.google.com/apis/ads/publisher/v201306}ProductType" minOccurs="0"/> * &lt;element name="creatorId" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/> * &lt;element name="rateType" type="{https://www.google.com/apis/ads/publisher/v201306}RateType" minOccurs="0"/> * &lt;element name="roadblockingType" type="{https://www.google.com/apis/ads/publisher/v201306}RoadblockingType" minOccurs="0"/> * &lt;element name="creativePlaceholders" type="{https://www.google.com/apis/ads/publisher/v201306}CreativePlaceholder" maxOccurs="unbounded" minOccurs="0"/> * &lt;element name="lineItemType" type="{https://www.google.com/apis/ads/publisher/v201306}LineItemType" minOccurs="0"/> * &lt;element name="priority" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/> * &lt;element name="frequencyCaps" type="{https://www.google.com/apis/ads/publisher/v201306}FrequencyCap" maxOccurs="unbounded" minOccurs="0"/> * &lt;element name="allowFrequencyCapsCustomization" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/> * &lt;element name="productSegmentation" type="{https://www.google.com/apis/ads/publisher/v201306}ProductSegmentation" minOccurs="0"/> * &lt;element name="targeting" type="{https://www.google.com/apis/ads/publisher/v201306}ProductTemplateTargeting" minOccurs="0"/> * &lt;element name="customFieldValues" type="{https://www.google.com/apis/ads/publisher/v201306}BaseCustomFieldValue" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "ProductTemplate", propOrder = { "id", "name", "creationDateTime", "lastModifiedDateTime", "description", "nameMacro", "status", "productType", "creatorId", "rateType", "roadblockingType", "creativePlaceholders", "lineItemType", "priority", "frequencyCaps", "allowFrequencyCapsCustomization", "productSegmentation", "targeting", "customFieldValues" }) public class ProductTemplate { protected Long id; protected String name; protected DateTime creationDateTime; protected DateTime lastModifiedDateTime; protected String description; protected String nameMacro; protected ProductTemplateStatus status; protected ProductType productType; protected Long creatorId; protected RateType rateType; protected RoadblockingType roadblockingType; protected List<CreativePlaceholder> creativePlaceholders; protected LineItemType lineItemType; protected Integer priority; protected List<FrequencyCap> frequencyCaps; protected Boolean allowFrequencyCapsCustomization; protected ProductSegmentation productSegmentation; protected ProductTemplateTargeting targeting; protected List<BaseCustomFieldValue> customFieldValues; /** * Gets the value of the id property. * * @return * possible object is * {@link Long } * */ public Long getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link Long } * */ public void setId(Long value) { this.id = value; } /** * Gets the value of the name property. * * @return * possible object is * {@link String } * */ public String getName() { return name; } /** * Sets the value of the name property. * * @param value * allowed object is * {@link String } * */ public void setName(String value) { this.name = value; } /** * Gets the value of the creationDateTime property. * * @return * possible object is * {@link DateTime } * */ public DateTime getCreationDateTime() { return creationDateTime; } /** * Sets the value of the creationDateTime property. * * @param value * allowed object is * {@link DateTime } * */ public void setCreationDateTime(DateTime value) { this.creationDateTime = value; } /** * Gets the value of the lastModifiedDateTime property. * * @return * possible object is * {@link DateTime } * */ public DateTime getLastModifiedDateTime() { return lastModifiedDateTime; } /** * Sets the value of the lastModifiedDateTime property. * * @param value * allowed object is * {@link DateTime } * */ public void setLastModifiedDateTime(DateTime value) { this.lastModifiedDateTime = value; } /** * Gets the value of the description property. * * @return * possible object is * {@link String } * */ public String getDescription() { return description; } /** * Sets the value of the description property. * * @param value * allowed object is * {@link String } * */ public void setDescription(String value) { this.description = value; } /** * Gets the value of the nameMacro property. * * @return * possible object is * {@link String } * */ public String getNameMacro() { return nameMacro; } /** * Sets the value of the nameMacro property. * * @param value * allowed object is * {@link String } * */ public void setNameMacro(String value) { this.nameMacro = value; } /** * Gets the value of the status property. * * @return * possible object is * {@link ProductTemplateStatus } * */ public ProductTemplateStatus getStatus() { return status; } /** * Sets the value of the status property. * * @param value * allowed object is * {@link ProductTemplateStatus } * */ public void setStatus(ProductTemplateStatus value) { this.status = value; } /** * Gets the value of the productType property. * * @return * possible object is * {@link ProductType } * */ public ProductType getProductType() { return productType; } /** * Sets the value of the productType property. * * @param value * allowed object is * {@link ProductType } * */ public void setProductType(ProductType value) { this.productType = value; } /** * Gets the value of the creatorId property. * * @return * possible object is * {@link Long } * */ public Long getCreatorId() { return creatorId; } /** * Sets the value of the creatorId property. * * @param value * allowed object is * {@link Long } * */ public void setCreatorId(Long value) { this.creatorId = value; } /** * Gets the value of the rateType property. * * @return * possible object is * {@link RateType } * */ public RateType getRateType() { return rateType; } /** * Sets the value of the rateType property. * * @param value * allowed object is * {@link RateType } * */ public void setRateType(RateType value) { this.rateType = value; } /** * Gets the value of the roadblockingType property. * * @return * possible object is * {@link RoadblockingType } * */ public RoadblockingType getRoadblockingType() { return roadblockingType; } /** * Sets the value of the roadblockingType property. * * @param value * allowed object is * {@link RoadblockingType } * */ public void setRoadblockingType(RoadblockingType value) { this.roadblockingType = value; } /** * Gets the value of the creativePlaceholders property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the creativePlaceholders property. * * <p> * For example, to add a new item, do as follows: * <pre> * getCreativePlaceholders().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link CreativePlaceholder } * * */ public List<CreativePlaceholder> getCreativePlaceholders() { if (creativePlaceholders == null) { creativePlaceholders = new ArrayList<CreativePlaceholder>(); } return this.creativePlaceholders; } /** * Gets the value of the lineItemType property. * * @return * possible object is * {@link LineItemType } * */ public LineItemType getLineItemType() { return lineItemType; } /** * Sets the value of the lineItemType property. * * @param value * allowed object is * {@link LineItemType } * */ public void setLineItemType(LineItemType value) { this.lineItemType = value; } /** * Gets the value of the priority property. * * @return * possible object is * {@link Integer } * */ public Integer getPriority() { return priority; } /** * Sets the value of the priority property. * * @param value * allowed object is * {@link Integer } * */ public void setPriority(Integer value) { this.priority = value; } /** * Gets the value of the frequencyCaps property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the frequencyCaps property. * * <p> * For example, to add a new item, do as follows: * <pre> * getFrequencyCaps().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link FrequencyCap } * * */ public List<FrequencyCap> getFrequencyCaps() { if (frequencyCaps == null) { frequencyCaps = new ArrayList<FrequencyCap>(); } return this.frequencyCaps; } /** * Gets the value of the allowFrequencyCapsCustomization property. * * @return * possible object is * {@link Boolean } * */ public Boolean isAllowFrequencyCapsCustomization() { return allowFrequencyCapsCustomization; } /** * Sets the value of the allowFrequencyCapsCustomization property. * * @param value * allowed object is * {@link Boolean } * */ public void setAllowFrequencyCapsCustomization(Boolean value) { this.allowFrequencyCapsCustomization = value; } /** * Gets the value of the productSegmentation property. * * @return * possible object is * {@link ProductSegmentation } * */ public ProductSegmentation getProductSegmentation() { return productSegmentation; } /** * Sets the value of the productSegmentation property. * * @param value * allowed object is * {@link ProductSegmentation } * */ public void setProductSegmentation(ProductSegmentation value) { this.productSegmentation = value; } /** * Gets the value of the targeting property. * * @return * possible object is * {@link ProductTemplateTargeting } * */ public ProductTemplateTargeting getTargeting() { return targeting; } /** * Sets the value of the targeting property. * * @param value * allowed object is * {@link ProductTemplateTargeting } * */ public void setTargeting(ProductTemplateTargeting value) { this.targeting = value; } /** * Gets the value of the customFieldValues property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the customFieldValues property. * * <p> * For example, to add a new item, do as follows: * <pre> * getCustomFieldValues().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link BaseCustomFieldValue } * * */ public List<BaseCustomFieldValue> getCustomFieldValues() { if (customFieldValues == null) { customFieldValues = new ArrayList<BaseCustomFieldValue>(); } return this.customFieldValues; } }
nafae/developer
modules/dfp_appengine/src/main/java/com/google/api/ads/dfp/jaxws/v201306/ProductTemplate.java
Java
apache-2.0
15,693
/** * StringAttribute.java * * This file was auto-generated from WSDL * by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter. */ package com.google.api.ads.adwords.axis.v201406.o; /** * {@link Attribute} type that contains a string value. */ public class StringAttribute extends com.google.api.ads.adwords.axis.v201406.o.Attribute implements java.io.Serializable { /* String value contained by this {@link Attribute}. */ private java.lang.String value; public StringAttribute() { } public StringAttribute( java.lang.String attributeType, java.lang.String value) { super( attributeType); this.value = value; } /** * Gets the value value for this StringAttribute. * * @return value * String value contained by this {@link Attribute}. */ public java.lang.String getValue() { return value; } /** * Sets the value value for this StringAttribute. * * @param value * String value contained by this {@link Attribute}. */ public void setValue(java.lang.String value) { this.value = value; } private java.lang.Object __equalsCalc = null; public synchronized boolean equals(java.lang.Object obj) { if (!(obj instanceof StringAttribute)) return false; StringAttribute other = (StringAttribute) obj; if (obj == null) return false; if (this == obj) return true; if (__equalsCalc != null) { return (__equalsCalc == obj); } __equalsCalc = obj; boolean _equals; _equals = super.equals(obj) && ((this.value==null && other.getValue()==null) || (this.value!=null && this.value.equals(other.getValue()))); __equalsCalc = null; return _equals; } private boolean __hashCodeCalc = false; public synchronized int hashCode() { if (__hashCodeCalc) { return 0; } __hashCodeCalc = true; int _hashCode = super.hashCode(); if (getValue() != null) { _hashCode += getValue().hashCode(); } __hashCodeCalc = false; return _hashCode; } // Type metadata private static org.apache.axis.description.TypeDesc typeDesc = new org.apache.axis.description.TypeDesc(StringAttribute.class, true); static { typeDesc.setXmlType(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/o/v201406", "StringAttribute")); org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("value"); elemField.setXmlName(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/o/v201406", "value")); elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string")); elemField.setMinOccurs(0); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); } /** * Return type metadata object */ public static org.apache.axis.description.TypeDesc getTypeDesc() { return typeDesc; } /** * Get Custom Serializer */ public static org.apache.axis.encoding.Serializer getSerializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanSerializer( _javaType, _xmlType, typeDesc); } /** * Get Custom Deserializer */ public static org.apache.axis.encoding.Deserializer getDeserializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanDeserializer( _javaType, _xmlType, typeDesc); } }
nafae/developer
modules/adwords_axis/src/main/java/com/google/api/ads/adwords/axis/v201406/o/StringAttribute.java
Java
apache-2.0
3,963
/* * Copyright 2016 Intuit * * 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.intuit.data.autumn.client.impl; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.config.ClientConfig; import com.sun.jersey.api.client.config.DefaultClientConfig; import junit.framework.TestCase; import org.junit.Before; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import com.intuit.data.autumn.client.HttpCallConfig; import org.mockito.runners.MockitoJUnitRunner; import java.util.HashMap; import java.util.Map; import static com.github.tomakehurst.wiremock.client.WireMock.*; import static com.sun.jersey.api.json.JSONConfiguration.FEATURE_POJO_MAPPING; import static java.lang.Boolean.TRUE; import static javax.ws.rs.HttpMethod.*; import static javax.ws.rs.core.MediaType.APPLICATION_JSON; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.mortbay.jetty.HttpHeaders.ACCEPT; import static org.mortbay.jetty.HttpHeaders.CONTENT_TYPE; import static org.mortbay.jetty.HttpStatus.*; @RunWith(MockitoJUnitRunner.class) public class HttpCallImplTest extends TestCase { private int port = 9876; @Rule public WireMockRule wireMockRule = new WireMockRule(port); private HttpCallImpl<ClientResponse> httpCallsImpl; private Client client; private Map<String, String> map; private String accept; private String type; private String url = "http://localhost:" + port + "/test"; @Before public void before() { httpCallsImpl = new HttpCallImpl<>(); ClientConfig clientConfig = new DefaultClientConfig(); clientConfig.getFeatures().put(FEATURE_POJO_MAPPING, TRUE); this.client = Client.create(clientConfig); map = new HashMap<>(); map.put("foo", "bar"); map.put("dead", "beef"); accept = APPLICATION_JSON; type = APPLICATION_JSON; } @Test public void testMakeRequest() throws Exception { try { httpCallsImpl.makeRequest(OPTIONS, url, null, ClientResponse.class, map, map, accept, type, ORDINAL_200_OK); fail(); } catch (UnsupportedOperationException ignored) { } try { httpCallsImpl.makeRequest(HEAD, url, null, ClientResponse.class, map, map, accept, type, ORDINAL_200_OK); fail(); } catch (UnsupportedOperationException ignored) { } stubFor(get(urlEqualTo("/test")) .withHeader(ACCEPT, equalTo(accept)) .withHeader(CONTENT_TYPE, equalTo(type)) .withHeader("foo", equalTo(map.get("foo"))) .withHeader("dead", equalTo(map.get("dead"))) .willReturn(aResponse().withStatus(ORDINAL_200_OK))); ClientResponse response = httpCallsImpl.makeRequest(GET, url, null, ClientResponse.class, map, null, accept, type, ORDINAL_200_OK); assertThat(response.getStatus(), is(ORDINAL_200_OK)); try { httpCallsImpl.makeRequest(GET, url, null, ClientResponse.class, map, null, accept, type, ORDINAL_201_Created); fail(); } catch (RuntimeException ignored) { } response = httpCallsImpl.makeRequest(GET, url, null, null, null, null, accept, type, ORDINAL_404_Not_Found); assertThat(response.getStatus(), is(ORDINAL_404_Not_Found)); } @Test public void testMakeRequestGet() throws Exception { stubFor(get(urlEqualTo("/test")) .withHeader(ACCEPT, equalTo(accept)) .withHeader(CONTENT_TYPE, equalTo(type)) .withHeader("foo", equalTo(map.get("foo"))) .withHeader("dead", equalTo(map.get("dead"))) .willReturn(aResponse().withStatus(ORDINAL_200_OK))); ClientResponse response = httpCallsImpl.makeRequest(GET, url, null, ClientResponse.class, map, null, accept, type, ORDINAL_200_OK); assertThat(response.getStatus(), is(ORDINAL_200_OK)); try { httpCallsImpl.makeRequest(GET, url, null, null, map, null, accept, type, ORDINAL_201_Created); fail(); } catch (RuntimeException ignored) { } response = httpCallsImpl.makeRequest(GET, url, null, ClientResponse.class, null, null, accept, type, ORDINAL_404_Not_Found); assertThat(response.getStatus(), is(ORDINAL_404_Not_Found)); } @Test public void testMakeRequestPost() throws Exception { stubFor(post(urlEqualTo("/test")) .withHeader(ACCEPT, equalTo(accept)) .withHeader(CONTENT_TYPE, equalTo(type)) .withHeader("foo", equalTo(map.get("foo"))) .withHeader("dead", equalTo(map.get("dead"))) .willReturn(aResponse().withStatus(ORDINAL_200_OK))); ClientResponse response = httpCallsImpl.makeRequest(POST, url, null, ClientResponse.class, map, null, accept, type, ORDINAL_200_OK); assertThat(response.getStatus(), is(ORDINAL_200_OK)); } @Test public void testMakeRequestPut() throws Exception { stubFor(put(urlEqualTo("/test")) .withHeader(ACCEPT, equalTo(accept)) .withHeader(CONTENT_TYPE, equalTo(type)) .withHeader("foo", equalTo(map.get("foo"))) .withHeader("dead", equalTo(map.get("dead"))) .willReturn(aResponse().withStatus(ORDINAL_200_OK))); ClientResponse response = httpCallsImpl.makeRequest(PUT, url, null, ClientResponse.class, map, null, accept, type, ORDINAL_200_OK); assertThat(response.getStatus(), is(ORDINAL_200_OK)); } @Test public void testMakeRequestDelete() throws Exception { stubFor(delete(urlEqualTo("/test")) .withHeader(ACCEPT, equalTo(accept)) .withHeader(CONTENT_TYPE, equalTo(type)) .withHeader("foo", equalTo(map.get("foo"))) .withHeader("dead", equalTo(map.get("dead"))) .willReturn(aResponse().withStatus(ORDINAL_200_OK))); ClientResponse response = httpCallsImpl.makeRequest(DELETE, url, null, ClientResponse.class, map, null, accept, type, ORDINAL_200_OK); assertThat(response.getStatus(), is(ORDINAL_200_OK)); } @Test public void testAddHeaders() throws Exception { WebResource webResource = client.resource(url); WebResource.Builder webResourceFromMethod = httpCallsImpl.addHeaders(webResource, map, accept, type); stubFor(get(urlEqualTo("/test")) .withHeader(ACCEPT, equalTo(accept)) .withHeader(CONTENT_TYPE, equalTo(type)) .withHeader("foo", equalTo(map.get("foo"))) .withHeader("dead", equalTo(map.get("dead"))) .willReturn(aResponse().withStatus(ORDINAL_200_OK))); ClientResponse x = webResourceFromMethod.get(ClientResponse.class); assertThat(x.getStatus(), is(ORDINAL_200_OK)); } @Test public void testAddQueryParams() throws Exception { WebResource webResource = client.resource(url); WebResource response = httpCallsImpl.addQueryParams(webResource, map); webResource = webResource.queryParam("foo", map.get("foo")); webResource = webResource.queryParam("dead", map.get("dead")); assertThat(webResource, is(response)); } @Test public void testDoGet() throws Exception { stubFor(get(urlEqualTo("/test")) .withHeader(ACCEPT, equalTo(accept)) .withHeader("foo", equalTo(map.get("foo"))) .withHeader("dead", equalTo(map.get("dead"))) .willReturn(aResponse().withStatus(ORDINAL_200_OK))); ClientResponse response = httpCallsImpl.doGet(url, ClientResponse.class, map, null, accept, ORDINAL_200_OK); assertThat(response.getStatus(), is(ORDINAL_200_OK)); // try { // response = httpCallsImpl.doGet(url, null, map, null, accept, ORDINAL_200_OK); // fail(); // } catch (RuntimeException ignored) { // } response = httpCallsImpl.doGet(url, ClientResponse.class, null, null, accept, ORDINAL_404_Not_Found); assertThat(response.getStatus(), is(ORDINAL_404_Not_Found)); } @Test public void testDoGetWithHttpConfig() throws Exception { stubFor(get(urlEqualTo("/test")) .withHeader(ACCEPT, equalTo(accept)) .withHeader("foo", equalTo(map.get("foo"))) .withHeader("dead", equalTo(map.get("dead"))) .willReturn(aResponse().withStatus(ORDINAL_200_OK))); HttpCallConfig httpCallConfig = HttpCallConfig.Builder.aHttpCallConfig() .withUrl(url) .withToMap(ClientResponse.class) .withHeaders(map) .withAccept(accept) .withExpectedStatus(ORDINAL_200_OK).build(); ClientResponse response = httpCallsImpl.doGet(httpCallConfig); assertThat(response.getStatus(), is(ORDINAL_200_OK)); } @Test public void testDoPost() throws Exception { stubFor(post(urlEqualTo("/test")) .withHeader(ACCEPT, equalTo(accept)) .withHeader(CONTENT_TYPE, equalTo(type)) .withHeader("foo", equalTo(map.get("foo"))) .withHeader("dead", equalTo(map.get("dead"))) .willReturn(aResponse().withStatus(ORDINAL_200_OK))); ClientResponse response = httpCallsImpl.doPost(url, null, ClientResponse.class, map, null, accept, type, ORDINAL_200_OK); assertThat(response.getStatus(), is(ORDINAL_200_OK)); } @Test public void testDoPostWithEntity() throws Exception { stubFor(post(urlEqualTo("/test")) .withRequestBody(matching("entity")) .withHeader(ACCEPT, equalTo(accept)) .withHeader(CONTENT_TYPE, equalTo(type)) .withHeader("foo", equalTo(map.get("foo"))) .withHeader("dead", equalTo(map.get("dead"))) .willReturn(aResponse().withStatus(ORDINAL_200_OK))); ClientResponse response = httpCallsImpl.doPost(url, "entity", ClientResponse.class, map, null, accept, type, ORDINAL_200_OK); assertThat(response.getStatus(), is(ORDINAL_200_OK)); } @Ignore("???") @Test public void testDoPostWithHttpConfig() throws Exception { stubFor(put(urlEqualTo("/test")) .withRequestBody(matching(null)) .withHeader(ACCEPT, equalTo(accept)) .withHeader(CONTENT_TYPE, equalTo(type)) .withHeader("foo", equalTo(map.get("foo"))) .withHeader("dead", equalTo(map.get("dead"))) .willReturn(aResponse().withStatus(ORDINAL_200_OK))); HttpCallConfig httpCallConfig = HttpCallConfig.Builder.aHttpCallConfig() .withUrl(url) .withToMap(ClientResponse.class) .withHeaders(map) .withQueryParams(null) .withAccept(accept) .withType(type) .withExpectedStatus(ORDINAL_200_OK).build(); ClientResponse response = httpCallsImpl.doPost(httpCallConfig); assertThat(response.getStatus(), is(ORDINAL_200_OK)); } @Ignore("???") @Test public void testDoPostWithEntityWithHttpConfig() throws Exception { stubFor(put(urlEqualTo("/test")) .withRequestBody(matching("entity")) .withHeader(ACCEPT, equalTo(accept)) .withHeader(CONTENT_TYPE, equalTo(type)) .withHeader("foo", equalTo(map.get("foo"))) .withHeader("dead", equalTo(map.get("dead"))) .willReturn(aResponse().withStatus(ORDINAL_200_OK))); HttpCallConfig httpCallConfig = HttpCallConfig.Builder.aHttpCallConfig() .withUrl(url) .withData("entity") .withToMap(ClientResponse.class) .withHeaders(map) .withQueryParams(null) .withAccept(accept) .withType(type) .withExpectedStatus(ORDINAL_200_OK).build(); ClientResponse response = httpCallsImpl.doPost(httpCallConfig); assertThat(response.getStatus(), is(ORDINAL_200_OK)); } @Test public void testDoPut() throws Exception { stubFor(put(urlEqualTo("/test")) .withHeader(ACCEPT, equalTo(accept)) .withHeader(CONTENT_TYPE, equalTo(type)) .withHeader("foo", equalTo(map.get("foo"))) .withHeader("dead", equalTo(map.get("dead"))) .willReturn(aResponse().withStatus(ORDINAL_200_OK))); ClientResponse response = httpCallsImpl.doPut(url, null, ClientResponse.class, map, null, accept, type, ORDINAL_200_OK); assertThat(response.getStatus(), is(ORDINAL_200_OK)); } @Test public void testDoPutWithEntity() throws Exception { stubFor(put(urlEqualTo("/test")) .withRequestBody(matching("entity")) .withHeader(ACCEPT, equalTo(accept)) .withHeader(CONTENT_TYPE, equalTo(type)) .withHeader("foo", equalTo(map.get("foo"))) .withHeader("dead", equalTo(map.get("dead"))) .willReturn(aResponse().withStatus(ORDINAL_200_OK))); ClientResponse response = httpCallsImpl.doPut(url, "entity", ClientResponse.class, map, null, accept, type, ORDINAL_200_OK); assertThat(response.getStatus(), is(ORDINAL_200_OK)); } @Test public void testDoPutWithHttpConfig() throws Exception { stubFor(put(urlEqualTo("/test")) .withHeader(ACCEPT, equalTo(accept)) .withHeader(CONTENT_TYPE, equalTo(type)) .withHeader("foo", equalTo(map.get("foo"))) .withHeader("dead", equalTo(map.get("dead"))) .willReturn(aResponse().withStatus(ORDINAL_200_OK))); HttpCallConfig httpCallConfig = HttpCallConfig.Builder.aHttpCallConfig() .withUrl(url) .withToMap(ClientResponse.class) .withHeaders(map) .withAccept(accept) .withType(type) .withExpectedStatus(ORDINAL_200_OK).build(); ClientResponse response = httpCallsImpl.doPut(httpCallConfig); assertThat(response.getStatus(), is(ORDINAL_200_OK)); } @Test public void testDoPutWithEntityWithHttpConfig() throws Exception { stubFor(put(urlEqualTo("/test")) .withRequestBody(matching("entity")) .withHeader(ACCEPT, equalTo(accept)) .withHeader(CONTENT_TYPE, equalTo(type)) .withHeader("foo", equalTo(map.get("foo"))) .withHeader("dead", equalTo(map.get("dead"))) .willReturn(aResponse().withStatus(ORDINAL_200_OK))); String entity = "entity"; HttpCallConfig httpCallConfig = HttpCallConfig.Builder.aHttpCallConfig() .withUrl(url) .withData(entity) .withToMap(ClientResponse.class) .withHeaders(map) .withAccept(accept) .withType(type) .withExpectedStatus(ORDINAL_200_OK).build(); ClientResponse response = httpCallsImpl.doPut(httpCallConfig); assertThat(response.getStatus(), is(ORDINAL_200_OK)); } @Test public void testDoDelete() throws Exception { stubFor(delete(urlEqualTo("/test")) .withHeader(ACCEPT, equalTo(accept)) .withHeader("foo", equalTo(map.get("foo"))) .withHeader("dead", equalTo(map.get("dead"))) .willReturn(aResponse().withStatus(ORDINAL_200_OK))); ClientResponse response = httpCallsImpl.doDelete(url, ClientResponse.class, map, null, accept, ORDINAL_200_OK); assertThat(response.getStatus(), is(ORDINAL_200_OK)); } @Test public void testDoDeleteWithHttpConfig() throws Exception { stubFor(delete(urlEqualTo("/test")) .withHeader(ACCEPT, equalTo(accept)) .withHeader("foo", equalTo(map.get("foo"))) .withHeader("dead", equalTo(map.get("dead"))) .willReturn(aResponse().withStatus(ORDINAL_200_OK))); HttpCallConfig httpCallConfig = HttpCallConfig.Builder.aHttpCallConfig() .withUrl(url) .withToMap(ClientResponse.class) .withHeaders(map) .withAccept(accept) .withExpectedStatus(ORDINAL_200_OK).build(); ClientResponse response = httpCallsImpl.doDelete(httpCallConfig); assertThat(response.getStatus(), is(ORDINAL_200_OK)); } }
jwtodd/Autumn
modules/client/src/test/java/com/intuit/data/autumn/client/impl/HttpCallImplTest.java
Java
apache-2.0
17,788
/* Priha - A JSR-170 implementation library. Copyright (C) 2007-2009 Janne Jalkanen (Janne.Jalkanen@iki.fi) 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.priha.providers; import java.util.Collection; import java.util.List; import java.util.Properties; import javax.jcr.*; import org.priha.core.ItemType; import org.priha.core.RepositoryImpl; import org.priha.core.WorkspaceImpl; import org.priha.nodetype.QNodeDefinition; import org.priha.path.Path; import org.priha.util.ConfigurationException; import org.priha.util.QName; /** * A few ground rules: * <ul> * <li>A RepositoryProvider shall not cache the Session object</li> * <li>A RepositoryProvider shall be thread-safe</li> * <li>There shall always be a default workspace called "default"</li> * </ul> * <p> * Priha RepositoryManager ensures that methods which modify the repository * (addNode(), close(), copy(), move(), open(), putPropertyValue(), remove(), * start(), stop(), storeFinished(), storeStarted()) are single-threaded. * However, the rest of the methods which are supposed to read from the * repository, are protected by a read lock, and therefore they can be * accessed at the same time from multiple threads. If you do any modifications * anywhere, make sure these are thread-safe. * <p> * The RepositoryProvider lifecycle is as follows. * <ol> * <li>When Priha first starts up and parses its configuration, it locates each * RepositoryProvider from the configuration, and calls its <code>start()</code> * method to notify that it exists.</li> * <li>Once the user then grabs a Session object, the RepositoryProvider is * notified via the <code>open()</code> method.</li> * <li>The user now uses all of the other methods from the repo.</li> * <li>Once the user chooses to logout, then the <code>close()</code> method * is called.</li> * <li>Then, finally, when Priha closes down, the <code>stop()</code> method * will be called. Priha installs its own shutdown hook for this case.</li> * </ol> */ public interface RepositoryProvider { // // REPOSITORY MANAGEMENT // /** * Opens a repository. Called whenever a session login() is performed. * * @param rep The Repository which owns this Provider. * @param credentials The Credentials object passed to the Session.open() call. May be null, * if there were no credentials. * @param workspaceName The workspace which will be accessed. * @throws NoSuchWorkspaceException if no such workspace exists. */ public void open( RepositoryImpl rep, Credentials credentials, String workspaceName ) throws RepositoryException, NoSuchWorkspaceException; /** * Starts access to a repository. This is called only once per * RepositoryProvider lifecycle. * * @param repository The Repository which owns this provider. * @param properties A set of filtered properties for this provider. * @throws ConfigurationException If the repository cannot be started due to a faulty configuration. * * @see org.priha.core.ProviderManager#filterProperties(RepositoryImpl, String) */ public void start( RepositoryImpl repository, Properties properties ) throws ConfigurationException; /** * Stops a given repository. This may be called without a preceding call * to close(). All allocated resources can now be deallocated. * <p> * This method will only be called when the Repository shuts down. * * @param rep The Repository object. */ public void stop( RepositoryImpl rep ); /** * The repository will no longer be used by a session, so any session-specific * things can now be deallocated. * * @param ws The Workspace attached to the Session. */ public void close( WorkspaceImpl ws ); /** * Lists all workspaces which are available in this Repository. This method is * called after start() but before open(). * * @return The workspace names. * @throws RepositoryException */ public Collection<String> listWorkspaces() throws RepositoryException; // // GETTING NODES AND VALUES // /** * Returns a list of properties for a Node. * * @param ws The Workspace in which the properties should be located. * @param path The path of the Node. * @return A List of the names of the properties under this Node. * @throws PathNotFoundException If the path given does not exist. * @throws RepositoryException If something goes wrong. */ public abstract List<QName> listProperties( WorkspaceImpl ws, Path path ) throws PathNotFoundException, RepositoryException; /** * Returns the value of a property. * * @param ws The workspace in which the property value should be located. * @param path The path to the Property * @return Either a ValueImpl or ValueImpl[], depending on whether this is a multi-valued thing * @throws RepositoryException If something goes wrong. * @throws PathNotFoundException If there is nothing at the end of this Path, i.e. the object could not be found. */ public abstract ValueContainer getPropertyValue( WorkspaceImpl ws, Path path ) throws PathNotFoundException, RepositoryException; /** * Returns true, if the Item exists and is of given type. * * @param ws The workspace in which the existence of the Node is checked. * @param path The path to the Node. * @param type Type to check for * @return True, if the item exists. False otherwise (like when it's actually of a different type) * @throws RepositoryException */ public boolean itemExists( WorkspaceImpl ws, Path path, ItemType type ) throws RepositoryException; /** * Lists all the Nodes from the repository which belong to this parent. * * @param ws The Workspace. * @param parentpath The path to the Node whose children should be listed. * @return A List of Path objects with the <i>full</i> paths to the children. * @throws RepositoryException If the children cannot be found. */ public List<Path> listNodes(WorkspaceImpl ws, Path parentpath) throws RepositoryException; /** * If an item by this UUID exists, returns a Path. * * @param ws * @param uuid * @return * @throws ItemNotFoundException If the repository does not contain an UUID by this name. */ public Path findByUUID( WorkspaceImpl ws, String uuid ) throws ItemNotFoundException, RepositoryException; /** * Finds all the Property paths which are of type REFERENCE and whose content * is equal to the UUID given. * * @param ws * @param uuid * @return A list of paths to properties which reference the node by the given UUID. * @throws RepositoryException */ public List<Path> findReferences(WorkspaceImpl ws, String uuid) throws RepositoryException; // // METHODS WHICH CHANGE THE REPOSITORY CONTENT // /** * Adds a new Node to the repository to the given Path. The properties of the * Node will be stored separately using successive putPropertyValue() calls. * This includes also system things like the jcr:primaryType, so this method * really exists just to ensure that the Node can be added to the repository. * * @param ws The workspace. * @param path Path to the node in this workspace. * @paran definition The definition of the Node which will be added. The provider * may use this to optimize for particular types. * @throws RepositoryException If the Node cannot be added. */ public void addNode( StoreTransaction tx, Path path, QNodeDefinition definition ) throws RepositoryException; /** * Sets or adds a new Property to the repository. Note that * a Property may be multi-valued. It is up to the provider to * decide how it serializes the data. * * @param ws The workspace * @param property The Property content to store. * @throws RepositoryException If the property cannot be stored. */ public void putPropertyValue( StoreTransaction tx, Path path, ValueContainer property ) throws RepositoryException; /** * Removes a node or a property from the repository. If the removed * entity is a Node, all of its children and properties MUST also be removed * from the repository. * <p> * In addition, it MUST NOT be an error if remove() is called on a path * which is already removed. In such a case, remove() shall fail silently. * * @param ws * @param path */ public void remove( StoreTransaction tx, Path path ) throws RepositoryException; /** * This method is called whenever Priha starts a transaction which will save the * contents of the repository. You could, for example, use this to start a transaction. * * @param ws The workspace * @return An arbitrary StoreTransaction object. May be null. */ public StoreTransaction storeStarted(WorkspaceImpl ws) throws RepositoryException; /** * This method is called when the repository-changing operation is complete. For example, * you could close the transaction at this stage. * @param tx The same StoreTransaction object which was returned from storeStarted(). */ public void storeFinished(StoreTransaction tx) throws RepositoryException; /** * If the store has been cancelled and changes need to be rolled back. A RepositoryProvider * should use this opportunity to make sure it is in a consistent state. * * @param tx The transaction from storeStarted(). */ public void storeCancelled(StoreTransaction tx) throws RepositoryException; public void reorderNodes(StoreTransaction tx, Path path, List<Path> childOrder) throws RepositoryException; }
jalkanen/Priha
src/java/org/priha/providers/RepositoryProvider.java
Java
apache-2.0
10,858
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.roots.ui.configuration.actions; import com.intellij.openapi.actionSystem.ActionPlaces; import com.intellij.openapi.actionSystem.ActionToolbar; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.Presentation; import com.intellij.openapi.actionSystem.ex.CustomComponentAction; import com.intellij.openapi.actionSystem.impl.ActionButtonWithText; import com.intellij.util.ui.EmptyIcon; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.util.function.Supplier; public abstract class IconWithTextAction extends AnAction implements CustomComponentAction { protected IconWithTextAction() { this(Presentation.NULL_STRING, Presentation.NULL_STRING, null); } protected IconWithTextAction(String text) { this(text, null, null); } protected IconWithTextAction(@NotNull Supplier<String> dynamicText) { this(dynamicText, Presentation.NULL_STRING, null); } protected IconWithTextAction(String text, String description, Icon icon) { this(() -> text, () -> description, icon); } protected IconWithTextAction(@NotNull Supplier<String> dynamicText, @NotNull Supplier<String> dynamicDescription, @Nullable Icon icon) { super(dynamicText, dynamicDescription, icon); if (icon == null) { getTemplatePresentation().setIcon(EmptyIcon.ICON_0); getTemplatePresentation().setDisabledIcon(EmptyIcon.ICON_0); } } @NotNull @Override public JComponent createCustomComponent(@NotNull Presentation presentation, @NotNull String place) { return createCustomComponentImpl(this, presentation, place); } @NotNull public static JComponent createCustomComponentImpl(@NotNull AnAction action, @NotNull Presentation presentation, @NotNull String place) { return new ActionButtonWithText(action, presentation, place, ActionToolbar.DEFAULT_MINIMUM_BUTTON_SIZE); } /** @deprecated use {@link IconWithTextAction#createCustomComponentImpl(AnAction, Presentation, String)} */ @Deprecated public static JComponent createCustomComponentImpl(AnAction action, Presentation presentation) { return new ActionButtonWithText(action, presentation, ActionPlaces.UNKNOWN, ActionToolbar.DEFAULT_MINIMUM_BUTTON_SIZE); } }
leafclick/intellij-community
platform/platform-impl/src/com/intellij/openapi/roots/ui/configuration/actions/IconWithTextAction.java
Java
apache-2.0
2,446
package com.coolweather.app; import java.util.ArrayList; import java.util.List; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; public class CoolWeatherDB { public static final String DB_NAME="cool_weather"; public static final int VERSION=1; private static CoolWeatherDB coolWeatherDB; private SQLiteDatabase db; private CoolWeatherDB(Context context) { CoolWeatherOpenHelper dbHelper=new CoolWeatherOpenHelper(context,DB_NAME,null,VERSION); db=dbHelper.getWritableDatabase(); } //»ñÈ¡CoolWeatherDBµÄʵÀý public synchronized static CoolWeatherDB getInstance(Context context) { if(coolWeatherDB==null) { coolWeatherDB=new CoolWeatherDB(context); } return coolWeatherDB; } //½«provinceµÄÊý¾ÝÌí¼Óµ½¡°Province¡±±íÖÐ public void saveProvince(Province province) { if(province!=null) { ContentValues values=new ContentValues(); values.put("province_name", province.getProvinceName()); values.put("province_code", province.getProvinceCode()); db.insert("Province", null, values); } } //´ÓÊý¾Ý¿âÖжÁÈ¡È«¹úËùÓÐÊ¡·ÝµÄÐÅÏ¢ public List<Province> loadProvinces() { List<Province> list=new ArrayList<Province>(); Cursor cursor=db.query("Province", null, null, null, null, null, null); if(cursor.moveToFirst()) { do { Province province=new Province(); province.setId(cursor.getInt(cursor.getColumnIndex("id"))); province.setProvinceName(cursor.getString(cursor.getColumnIndex("province_name"))); province.setProvinceCode(cursor.getString(cursor.getColumnIndex("province_code"))); list.add(province); }while(cursor.moveToNext()); } return list; } //½«city´æÈëÊý¾Ý¿âÖÐ public void saveCities(City city) { if(city!=null) { ContentValues values=new ContentValues(); values.put("city_name", city.getCityName()); values.put("city_code", city.getCityCode()); values.put("province_id", city.getProvinceId()); db.insert("City", null, values); } } //¶ÁÈ¡Êý¾Ý¿âÖиø¶¨Ê¡µÄËùÓÐcityµÄÐÅÏ¢ public List<City> loadCities(int provinceId) { List<City> list=new ArrayList<City>(); Cursor cursor=db.query("City", null, "province_id=?", new String[]{String.valueOf(provinceId)}, null, null, null); if(cursor.moveToFirst()) { do { City city=new City(); city.setId(cursor.getInt(cursor.getColumnIndex("id"))); city.setCityName(cursor.getString(cursor.getColumnIndex("city_name"))); city.setCityCode(cursor.getString(cursor.getColumnIndex("city_code"))); city.setProvinceId(provinceId); list.add(city); }while(cursor.moveToNext()); } return list; } //½«CountyʵÀý´æÈëÊý¾Ý¿â public void saveCounties(County county) { if(county!=null) { ContentValues values=new ContentValues(); values.put("county_name", county.getCountyName()); values.put("county_code", county.getCountyCode()); values.put("city_id", county.getCityId()); db.insert("County", null, values); } } //½«Ä³³ÇÊеÄËùÓÐCountyÈ¡³ö public List<County> loadCounties(int cityId) { List<County> list=new ArrayList<County>(); Cursor cursor=db.query("County", null, "city_id=?", new String[]{String.valueOf(cityId)}, null, null, null); if(cursor.moveToFirst()) { do { County county=new County(); county.setId(cursor.getInt(cursor.getColumnIndex("id"))); county.setCountyName(cursor.getString(cursor.getColumnIndex("county_name"))); county.setCountyCode(cursor.getString(cursor.getColumnIndex("county_code"))); county.setCityId(cityId); list.add(county); }while(cursor.moveToNext()); } return list; } }
cokonian/CoolWeather
src/com/coolweather/app/CoolWeatherDB.java
Java
apache-2.0
4,016
package com.jjinterna.pbxevents.tcx.callrouter.internal; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; @Path("route.vxml") public interface CallRouterResource { @GET @Produces("application/voicexml+xml") String route(@QueryParam("ani") String ani, @QueryParam("dnis") String dnis); }
gmanev/PBXEvents
pbxevents-3cx-callrouter/src/main/java/com/jjinterna/pbxevents/tcx/callrouter/internal/CallRouterResource.java
Java
apache-2.0
354
/** * */ package com.notbed.database; import java.sql.Connection; /** * @author Alexandru Bledea * @since Sep 21, 2013 */ public interface IConnectionProvider { /** * */ Connection getConnection(); /** * @param con */ void close(Connection con); }
napp-abledea/notbed-db
com.notbed.database/src/com/notbed/database/IConnectionProvider.java
Java
apache-2.0
269
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.psalgs.list.singly; /** * * @author djoshi * * http://www.geeksforgeeks.org/swap-kth-node-from-beginning-with-kth-node-from-end-in-a-linked-list/ * * Swap Kth node from beginning with Kth node from end in a Linked List */ public class SwapKthNode { static class Node { int data; Node next; Node(int d) { data = d; next = null; } } Node head; static int len; private int getCount() { int count = 1; Node curr = head; while (curr != null) { count++; curr = curr.next; } return count; } private void printList() { Node temp = head; while (temp != null) { System.out.print(temp.data + " "); temp = temp.next; } System.out.println(); } private void swapKth(int k) { int swap = len - k - 1; int count = 1; Node curr = head; Node prev1 = null; Node prev2 = null; Node prev = null; Node swap1 = null; Node swap2 = null; while(curr != null) { if(count == k) { prev1 = prev; swap1 = curr; } if(count == swap) { prev2 = prev; swap2 = curr; } count++; prev = curr; curr = curr.next; } // swap the nodes; Node next1 = swap1.next; Node next2 = swap2.next; prev1.next = swap2; swap2.next = next1; prev2.next = swap1; swap1.next = next2; } public static void main(String args[]) { SwapKthNode llist = new SwapKthNode(); llist.head = new Node(1); llist.head.next = new Node(2); llist.head.next.next = new Node(3); llist.head.next.next.next = new Node(4); llist.head.next.next.next.next = new Node(5); llist.head.next.next.next.next.next = new Node(6); llist.head.next.next.next.next.next.next = new Node(7); llist.head.next.next.next.next.next.next.next = new Node(8); llist.printList(); len = llist.getCount(); llist.swapKth(2); // for (int i = 1; i <= len; i++) { // llist.swapKth(i); // } llist.printList(); } }
dhaval0129/PSAlgs
src/main/java/com/psalgs/list/singly/SwapKthNode.java
Java
apache-2.0
2,614
package com.google.api.ads.adwords.jaxws.v201402.cm; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for TimeUnit. * * <p>The following schema fragment specifies the expected content contained within this class. * <p> * <pre> * &lt;simpleType name="TimeUnit"> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;enumeration value="MINUTE"/> * &lt;enumeration value="HOUR"/> * &lt;enumeration value="DAY"/> * &lt;enumeration value="WEEK"/> * &lt;enumeration value="MONTH"/> * &lt;enumeration value="LIFETIME"/> * &lt;/restriction> * &lt;/simpleType> * </pre> * */ @XmlType(name = "TimeUnit") @XmlEnum public enum TimeUnit { MINUTE, HOUR, DAY, WEEK, MONTH, LIFETIME; public String value() { return name(); } public static TimeUnit fromValue(String v) { return valueOf(v); } }
nafae/developer
modules/adwords_appengine/src/main/java/com/google/api/ads/adwords/jaxws/v201402/cm/TimeUnit.java
Java
apache-2.0
963